database.lib.php 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725
  1. <?php
  2. /* For licensing terms, see /license.txt */
  3. use Doctrine\Common\Annotations\AnnotationRegistry;
  4. use Doctrine\DBAL\Connection;
  5. use Doctrine\DBAL\Driver\Statement;
  6. use Doctrine\DBAL\Types\Type;
  7. use Doctrine\ORM\EntityManager;
  8. /**
  9. * Class Database
  10. */
  11. class Database
  12. {
  13. /**
  14. * @var EntityManager
  15. */
  16. private static $em;
  17. private static $connection;
  18. public static $utcDateTimeClass;
  19. /**
  20. * @param EntityManager $em
  21. */
  22. public function setManager($em)
  23. {
  24. self::$em = $em;
  25. }
  26. /**
  27. * @param Connection $connection
  28. */
  29. public function setConnection(Connection $connection)
  30. {
  31. self::$connection = $connection;
  32. }
  33. /**
  34. * @return Connection
  35. */
  36. public function getConnection()
  37. {
  38. return self::$connection;
  39. }
  40. /**
  41. * @return EntityManager
  42. */
  43. public static function getManager()
  44. {
  45. return self::$em;
  46. }
  47. /**
  48. * Returns the name of the main database.
  49. *
  50. * @return string
  51. */
  52. public static function get_main_database()
  53. {
  54. return self::getManager()->getConnection()->getDatabase();
  55. }
  56. /**
  57. * Get main table
  58. *
  59. * @param string $table
  60. *
  61. * @return string
  62. */
  63. public static function get_main_table($table)
  64. {
  65. return $table;
  66. }
  67. /**
  68. * Get course table
  69. *
  70. * @param string $table
  71. *
  72. * @return string
  73. */
  74. public static function get_course_table($table)
  75. {
  76. return DB_COURSE_PREFIX.$table;
  77. }
  78. /**
  79. * Counts the number of rows in a table
  80. * @param string $table The table of which the rows should be counted
  81. *
  82. * @return int The number of rows in the given table.
  83. * @deprecated
  84. */
  85. public static function count_rows($table)
  86. {
  87. $obj = self::fetch_object(self::query("SELECT COUNT(*) AS n FROM $table"));
  88. return $obj->n;
  89. }
  90. /**
  91. * Returns the number of affected rows in the last database operation.
  92. * @param Statement $result
  93. *
  94. * @return int
  95. */
  96. public static function affected_rows(Statement $result)
  97. {
  98. return $result->rowCount();
  99. }
  100. /**
  101. * @return string
  102. */
  103. public static function getUTCDateTimeTypeClass()
  104. {
  105. return isset(self::$utcDateTimeClass) ? self::$utcDateTimeClass : 'Application\DoctrineExtensions\DBAL\Types\UTCDateTimeType';
  106. }
  107. /**
  108. * Connect to the database sets the entity manager.
  109. *
  110. * @param array $params
  111. * @param string $sysPath
  112. * @param string $entityRootPath
  113. * @param bool $returnConnection
  114. * @param bool $returnManager
  115. *
  116. * @throws \Doctrine\ORM\ORMException
  117. *
  118. * @return
  119. */
  120. public function connect(
  121. $params = array(),
  122. $sysPath = '',
  123. $entityRootPath = '',
  124. $returnConnection = false,
  125. $returnManager = false
  126. ) {
  127. $config = self::getDoctrineConfig($entityRootPath);
  128. $config->setAutoGenerateProxyClasses(true);
  129. $config->setEntityNamespaces(
  130. array(
  131. 'ChamiloUserBundle' => 'Chamilo\UserBundle\Entity',
  132. 'ChamiloCoreBundle' => 'Chamilo\CoreBundle\Entity',
  133. 'ChamiloCourseBundle' => 'Chamilo\CourseBundle\Entity',
  134. 'ChamiloSkillBundle' => 'Chamilo\SkillBundle\Entity',
  135. 'ChamiloTicketBundle' => 'Chamilo\TicketBundle\Entity',
  136. 'ChamiloFaqBundle' => 'Chamilo\FaqBundle\Entity'
  137. )
  138. );
  139. $params['charset'] = 'utf8';
  140. $entityManager = EntityManager::create($params, $config);
  141. $sysPath = !empty($sysPath) ? $sysPath : api_get_path(SYS_PATH);
  142. // Registering Constraints
  143. AnnotationRegistry::registerAutoloadNamespace(
  144. 'Symfony\Component\Validator\Constraint',
  145. $sysPath."vendor/symfony/symfony/src"
  146. );
  147. AnnotationRegistry::registerFile(
  148. $sysPath."vendor/symfony/symfony/src/Symfony/Bridge/Doctrine/Validator/Constraints/UniqueEntity.php"
  149. );
  150. // Registering gedmo extensions
  151. AnnotationRegistry::registerAutoloadNamespace(
  152. 'Gedmo\Mapping\Annotation',
  153. $sysPath."vendor/gedmo/doctrine-extensions/lib"
  154. );
  155. Type::overrideType(
  156. Type::DATETIME,
  157. self::getUTCDateTimeTypeClass()
  158. );
  159. $listener = new \Gedmo\Timestampable\TimestampableListener();
  160. $entityManager->getEventManager()->addEventSubscriber($listener);
  161. $listener = new \Gedmo\Tree\TreeListener();
  162. $entityManager->getEventManager()->addEventSubscriber($listener);
  163. $listener = new \Gedmo\Sortable\SortableListener();
  164. $entityManager->getEventManager()->addEventSubscriber($listener);
  165. $connection = $entityManager->getConnection();
  166. $connection->executeQuery('SET sql_mode = "";');
  167. if ($returnConnection) {
  168. return $connection;
  169. }
  170. if ($returnManager) {
  171. return $entityManager;
  172. }
  173. $this->setConnection($connection);
  174. $this->setManager($entityManager);
  175. }
  176. /**
  177. * Escape MySQL wildchars _ and % in LIKE search
  178. * @param string $text The string to escape
  179. *
  180. * @return string The escaped string
  181. */
  182. public static function escape_sql_wildcards($text)
  183. {
  184. $text = api_preg_replace("/_/", "\_", $text);
  185. $text = api_preg_replace("/%/", "\%", $text);
  186. return $text;
  187. }
  188. /**
  189. * Escapes a string to insert into the database as text
  190. *
  191. * @param string $string
  192. *
  193. * @return string
  194. */
  195. public static function escape_string($string)
  196. {
  197. $string = self::getManager()->getConnection()->quote($string);
  198. return trim($string, "'");
  199. }
  200. /**
  201. * Gets the array from a SQL result (as returned by Database::query)
  202. *
  203. * @param Statement $result
  204. * @param string $option Optional: "ASSOC","NUM" or "BOTH"
  205. *
  206. * @return array|mixed
  207. */
  208. public static function fetch_array(Statement $result, $option = 'BOTH')
  209. {
  210. if ($result === false) {
  211. return array();
  212. }
  213. return $result->fetch(self::customOptionToDoctrineOption($option));
  214. }
  215. /**
  216. * Gets an associative array from a SQL result (as returned by Database::query).
  217. *
  218. * @param Statement $result
  219. *
  220. * @return array
  221. */
  222. public static function fetch_assoc(Statement $result)
  223. {
  224. return $result->fetch(PDO::FETCH_ASSOC);
  225. }
  226. /**
  227. * Gets the next row of the result of the SQL query
  228. * (as returned by Database::query) in an object form
  229. *
  230. * @param Statement $result
  231. *
  232. * @return mixed
  233. */
  234. public static function fetch_object(Statement $result)
  235. {
  236. return $result->fetch(PDO::FETCH_OBJ);
  237. }
  238. /**
  239. * Gets the array from a SQL result (as returned by Database::query)
  240. * help achieving database independence
  241. *
  242. * @param Statement $result
  243. *
  244. * @return mixed
  245. */
  246. public static function fetch_row(Statement $result)
  247. {
  248. if ($result === false) {
  249. return array();
  250. }
  251. return $result->fetch(PDO::FETCH_NUM);
  252. }
  253. /**
  254. * Frees all the memory associated with the provided result identifier.
  255. * @return boolean|null Returns TRUE on success or FALSE on failure.
  256. * Notes: Use this method if you are concerned about how much memory is being used for queries that return large result sets.
  257. * Anyway, all associated result memory is automatically freed at the end of the script's execution.
  258. */
  259. public static function free_result(Statement $result)
  260. {
  261. $result->closeCursor();
  262. }
  263. /**
  264. * Gets the ID of the last item inserted into the database
  265. *
  266. * @return string
  267. */
  268. public static function insert_id()
  269. {
  270. return self::getManager()->getConnection()->lastInsertId();
  271. }
  272. /**
  273. * @param Statement $result
  274. *
  275. * @return int
  276. */
  277. public static function num_rows(Statement $result)
  278. {
  279. if ($result === false) {
  280. return 0;
  281. }
  282. return $result->rowCount();
  283. }
  284. /**
  285. * Acts as the relative *_result() function of most DB drivers and fetches a
  286. * specific line and a field
  287. *
  288. * @param Statement $resource
  289. * @param int $row
  290. * @param string $field
  291. *
  292. * @return mixed
  293. */
  294. public static function result(Statement $resource, $row, $field = '')
  295. {
  296. if ($resource->rowCount() > 0) {
  297. $result = $resource->fetchAll(PDO::FETCH_BOTH);
  298. return $result[$row][$field];
  299. }
  300. }
  301. /**
  302. * @param string $query
  303. *
  304. * @return Statement
  305. *
  306. * @throws \Doctrine\DBAL\DBALException
  307. */
  308. public static function query($query)
  309. {
  310. $connection = self::getManager()->getConnection();
  311. if (api_get_setting('server_type') == 'test') {
  312. $result = $connection->executeQuery($query);
  313. } else {
  314. try {
  315. $result = $connection->executeQuery($query);
  316. } catch (Exception $e) {
  317. error_log($e->getMessage());
  318. api_not_allowed(false, get_lang('GeneralError'));
  319. }
  320. }
  321. return $result;
  322. }
  323. /**
  324. * @param string $option
  325. *
  326. * @return int
  327. */
  328. public static function customOptionToDoctrineOption($option)
  329. {
  330. switch ($option) {
  331. case 'ASSOC':
  332. return PDO::FETCH_ASSOC;
  333. break;
  334. case 'NUM':
  335. return PDO::FETCH_NUM;
  336. break;
  337. case 'BOTH':
  338. default:
  339. return PDO::FETCH_BOTH;
  340. break;
  341. }
  342. }
  343. /**
  344. * Stores a query result into an array.
  345. *
  346. * @author Olivier Brouckaert
  347. * @param Statement $result - the return value of the query
  348. * @param string $option BOTH, ASSOC, or NUM
  349. *
  350. * @return array - the value returned by the query
  351. */
  352. public static function store_result(Statement $result, $option = 'BOTH')
  353. {
  354. return $result->fetchAll(self::customOptionToDoctrineOption($option));
  355. }
  356. /**
  357. * Database insert
  358. * @param string $table_name
  359. * @param array $attributes
  360. * @param bool $show_query
  361. *
  362. * @return false|string
  363. */
  364. public static function insert($table_name, $attributes, $show_query = false)
  365. {
  366. if (empty($attributes) || empty($table_name)) {
  367. return false;
  368. }
  369. $params = array_keys($attributes);
  370. if (!empty($params)) {
  371. $sql = 'INSERT INTO '.$table_name.' ('.implode(',', $params).')
  372. VALUES (:'.implode(', :', $params).')';
  373. $statement = self::getManager()->getConnection()->prepare($sql);
  374. $result = $statement->execute($attributes);
  375. if ($show_query) {
  376. var_dump($sql);
  377. error_log($sql);
  378. }
  379. if ($result) {
  380. return self::getManager()->getConnection()->lastInsertId();
  381. }
  382. }
  383. return false;
  384. }
  385. /**
  386. * @param string $tableName use Database::get_main_table
  387. * @param array $attributes Values to updates
  388. * Example: $params['name'] = 'Julio'; $params['lastname'] = 'Montoya';
  389. * @param array $whereConditions where conditions i.e array('id = ?' =>'4')
  390. * @param bool $showQuery
  391. *
  392. * @return bool|int
  393. */
  394. public static function update(
  395. $tableName,
  396. $attributes,
  397. $whereConditions = array(),
  398. $showQuery = false
  399. ) {
  400. if (!empty($tableName) && !empty($attributes)) {
  401. $updateSql = '';
  402. $count = 1;
  403. foreach ($attributes as $key => $value) {
  404. if ($showQuery) {
  405. echo $key.': '.$value.PHP_EOL;
  406. }
  407. $updateSql .= "$key = :$key ";
  408. if ($count < count($attributes)) {
  409. $updateSql .= ', ';
  410. }
  411. $count++;
  412. }
  413. if (!empty($updateSql)) {
  414. //Parsing and cleaning the where conditions
  415. $whereReturn = self::parse_where_conditions($whereConditions);
  416. $sql = "UPDATE $tableName SET $updateSql $whereReturn ";
  417. $statement = self::getManager()->getConnection()->prepare($sql);
  418. $result = $statement->execute($attributes);
  419. if ($showQuery) {
  420. var_dump($sql);
  421. var_dump($attributes);
  422. var_dump($whereConditions);
  423. }
  424. if ($result) {
  425. return $statement->rowCount();
  426. }
  427. }
  428. }
  429. return false;
  430. }
  431. /**
  432. * Experimental useful database finder
  433. * @todo lot of stuff to do here
  434. * @todo known issues, it doesn't work when using LIKE conditions
  435. * @example array('where'=> array('course_code LIKE "?%"'))
  436. * @example array('where'=> array('type = ? AND category = ?' => array('setting', 'Plugins'))
  437. * @example array('where'=> array('name = "Julio" AND lastname = "montoya"'))
  438. * @param array $columns
  439. * @param string $table_name
  440. * @param array $conditions
  441. * @param string $type_result
  442. * @param string $option
  443. * @return array
  444. */
  445. public static function select($columns, $table_name, $conditions = array(), $type_result = 'all', $option = 'ASSOC')
  446. {
  447. $conditions = self::parse_conditions($conditions);
  448. //@todo we could do a describe here to check the columns ...
  449. if (is_array($columns)) {
  450. $clean_columns = implode(',', $columns);
  451. } else {
  452. if ($columns == '*') {
  453. $clean_columns = '*';
  454. } else {
  455. $clean_columns = (string) $columns;
  456. }
  457. }
  458. $sql = "SELECT $clean_columns FROM $table_name $conditions";
  459. $result = self::query($sql);
  460. $array = array();
  461. if ($type_result === 'all') {
  462. while ($row = self::fetch_array($result, $option)) {
  463. if (isset($row['id'])) {
  464. $array[$row['id']] = $row;
  465. } else {
  466. $array[] = $row;
  467. }
  468. }
  469. } else {
  470. $array = self::fetch_array($result, $option);
  471. }
  472. return $array;
  473. }
  474. /**
  475. * Parses WHERE/ORDER conditions i.e array('where'=>array('id = ?' =>'4'), 'order'=>'id DESC'))
  476. * @todo known issues, it doesn't work when using
  477. * LIKE conditions example: array('where'=>array('course_code LIKE "?%"'))
  478. * @param array $conditions
  479. */
  480. public static function parse_conditions($conditions)
  481. {
  482. if (empty($conditions)) {
  483. return '';
  484. }
  485. $return_value = $where_return = '';
  486. foreach ($conditions as $type_condition => $condition_data) {
  487. if ($condition_data == false) {
  488. continue;
  489. }
  490. $type_condition = strtolower($type_condition);
  491. switch ($type_condition) {
  492. case 'where':
  493. foreach ($condition_data as $condition => $value_array) {
  494. if (is_array($value_array)) {
  495. $clean_values = array();
  496. foreach ($value_array as $item) {
  497. $item = self::escape_string($item);
  498. $clean_values[] = $item;
  499. }
  500. } else {
  501. $value_array = self::escape_string($value_array);
  502. $clean_values = $value_array;
  503. }
  504. if (!empty($condition) && $clean_values != '') {
  505. $condition = str_replace('%', "'@percentage@'", $condition); //replace "%"
  506. $condition = str_replace("'?'", "%s", $condition);
  507. $condition = str_replace("?", "%s", $condition);
  508. $condition = str_replace("@%s@", "@-@", $condition);
  509. $condition = str_replace("%s", "'%s'", $condition);
  510. $condition = str_replace("@-@", "@%s@", $condition);
  511. // Treat conditions as string
  512. $condition = vsprintf($condition, $clean_values);
  513. $condition = str_replace('@percentage@', '%', $condition); //replace "%"
  514. $where_return .= $condition;
  515. }
  516. }
  517. if (!empty($where_return)) {
  518. $return_value = " WHERE $where_return";
  519. }
  520. break;
  521. case 'order':
  522. $order_array = $condition_data;
  523. if (!empty($order_array)) {
  524. // 'order' => 'id desc, name desc'
  525. $order_array = self::escape_string($order_array, null, false);
  526. $new_order_array = explode(',', $order_array);
  527. $temp_value = array();
  528. foreach ($new_order_array as $element) {
  529. $element = explode(' ', $element);
  530. $element = array_filter($element);
  531. $element = array_values($element);
  532. if (!empty($element[1])) {
  533. $element[1] = strtolower($element[1]);
  534. $order = 'DESC';
  535. if (in_array($element[1], array('desc', 'asc'))) {
  536. $order = $element[1];
  537. }
  538. $temp_value[] = $element[0].' '.$order.' ';
  539. } else {
  540. //by default DESC
  541. $temp_value[] = $element[0].' DESC ';
  542. }
  543. }
  544. if (!empty($temp_value)) {
  545. $return_value .= ' ORDER BY '.implode(', ', $temp_value);
  546. }
  547. }
  548. break;
  549. case 'limit':
  550. $limit_array = explode(',', $condition_data);
  551. if (!empty($limit_array)) {
  552. if (count($limit_array) > 1) {
  553. $return_value .= ' LIMIT '.intval($limit_array[0]).' , '.intval($limit_array[1]);
  554. } else {
  555. $return_value .= ' LIMIT '.intval($limit_array[0]);
  556. }
  557. }
  558. break;
  559. }
  560. }
  561. return $return_value;
  562. }
  563. /**
  564. * @param array $conditions
  565. *
  566. * @return string
  567. */
  568. public static function parse_where_conditions($conditions)
  569. {
  570. return self::parse_conditions(array('where' => $conditions));
  571. }
  572. /**
  573. * @param string $table_name
  574. * @param array $where_conditions
  575. * @param bool $show_query
  576. *
  577. * @return int
  578. */
  579. public static function delete($table_name, $where_conditions, $show_query = false)
  580. {
  581. $where_return = self::parse_where_conditions($where_conditions);
  582. $sql = "DELETE FROM $table_name $where_return ";
  583. if ($show_query) { echo $sql; echo '<br />'; }
  584. $result = self::query($sql);
  585. $affected_rows = self::affected_rows($result);
  586. //@todo should return affected_rows for
  587. return $affected_rows;
  588. }
  589. /**
  590. * Get Doctrine configuration
  591. * @param string $path
  592. *
  593. * @return \Doctrine\ORM\Configuration
  594. */
  595. public static function getDoctrineConfig($path)
  596. {
  597. $isDevMode = false;
  598. $isSimpleMode = false; // related to annotations @Entity
  599. $cache = null;
  600. $path = !empty($path) ? $path : api_get_path(SYS_PATH);
  601. $paths = array(
  602. //$path.'src/Chamilo/ClassificationBundle/Entity',
  603. //$path.'src/Chamilo/MediaBundle/Entity',
  604. //$path.'src/Chamilo/PageBundle/Entity',
  605. $path.'src/Chamilo/CoreBundle/Entity',
  606. $path.'src/Chamilo/UserBundle/Entity',
  607. $path.'src/Chamilo/CourseBundle/Entity',
  608. $path.'src/Chamilo/TicketBundle/Entity',
  609. $path.'src/Chamilo/SkillBundle/Entity',
  610. //$path.'vendor/sonata-project/user-bundle/Entity',
  611. //$path.'vendor/sonata-project/user-bundle/Model',
  612. //$path.'vendor/friendsofsymfony/user-bundle/FOS/UserBundle/Entity',
  613. );
  614. $proxyDir = $path.'app/cache/';
  615. $config = \Doctrine\ORM\Tools\Setup::createAnnotationMetadataConfiguration(
  616. $paths,
  617. $isDevMode,
  618. $proxyDir,
  619. $cache,
  620. $isSimpleMode
  621. );
  622. return $config;
  623. }
  624. /**
  625. * @param string $table
  626. *
  627. * @return bool
  628. */
  629. public static function tableExists($table)
  630. {
  631. return self::getManager()->getConnection()->getSchemaManager()->tablesExist($table);
  632. }
  633. /**
  634. * @param string $table
  635. * @return \Doctrine\DBAL\Schema\Column[]
  636. */
  637. public static function listTableColumns($table)
  638. {
  639. return self::getManager()->getConnection()->getSchemaManager()->listTableColumns($table);
  640. }
  641. }