database.lib.php 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688
  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 :
  106. 'Application\DoctrineExtensions\DBAL\Types\UTCDateTimeType';
  107. }
  108. /**
  109. * Connect to the database sets the entity manager.
  110. *
  111. * @param array $params
  112. * @param string $sysPath
  113. * @param string $entityRootPath
  114. *
  115. * @throws \Doctrine\ORM\ORMException
  116. */
  117. public function connect($params = array(), $sysPath = '', $entityRootPath = '')
  118. {
  119. $config = self::getDoctrineConfig($entityRootPath);
  120. $config->setAutoGenerateProxyClasses(true);
  121. $config->setEntityNamespaces(
  122. array(
  123. 'ChamiloUserBundle' => 'Chamilo\UserBundle\Entity',
  124. 'ChamiloCoreBundle' => 'Chamilo\CoreBundle\Entity',
  125. 'ChamiloCourseBundle' => 'Chamilo\CourseBundle\Entity'
  126. )
  127. );
  128. $params['charset'] = 'utf8';
  129. $entityManager = EntityManager::create($params, $config);
  130. $sysPath = !empty($sysPath) ? $sysPath : api_get_path(SYS_PATH);
  131. // Registering Constraints
  132. AnnotationRegistry::registerAutoloadNamespace(
  133. 'Symfony\Component\Validator\Constraint',
  134. $sysPath."vendor/symfony/validator"
  135. );
  136. AnnotationRegistry::registerFile(
  137. $sysPath."vendor/symfony/doctrine-bridge/Symfony/Bridge/Doctrine/Validator/Constraints/UniqueEntity.php"
  138. );
  139. // Registering gedmo extensions
  140. AnnotationRegistry::registerAutoloadNamespace(
  141. 'Gedmo\Mapping\Annotation',
  142. $sysPath."vendor/gedmo/doctrine-extensions/lib"
  143. );
  144. Type::overrideType(
  145. Type::DATETIME,
  146. self::getUTCDateTimeTypeClass()
  147. );
  148. $listener = new \Gedmo\Timestampable\TimestampableListener();
  149. $entityManager->getEventManager()->addEventSubscriber($listener);
  150. $listener = new \Gedmo\Tree\TreeListener();
  151. $entityManager->getEventManager()->addEventSubscriber($listener);
  152. $listener = new \Gedmo\Sortable\SortableListener();
  153. $entityManager->getEventManager()->addEventSubscriber($listener);
  154. $connection = $entityManager->getConnection();
  155. $connection->executeQuery('set sql_mode=""');
  156. $this->setConnection($connection);
  157. $this->setManager($entityManager);
  158. }
  159. /**
  160. * Escape MySQL wildchars _ and % in LIKE search
  161. * @param string $text The string to escape
  162. *
  163. * @return string The escaped string
  164. */
  165. public static function escape_sql_wildcards($text)
  166. {
  167. $text = api_preg_replace("/_/", "\_", $text);
  168. $text = api_preg_replace("/%/", "\%", $text);
  169. return $text;
  170. }
  171. /**
  172. * Escapes a string to insert into the database as text
  173. *
  174. * @param string $string
  175. *
  176. * @return string
  177. */
  178. public static function escape_string($string)
  179. {
  180. $string = self::getManager()->getConnection()->quote($string);
  181. // The quote method from PDO also adds quotes around the string, which
  182. // is not how the legacy mysql_real_escape_string() was used in
  183. // Chamilo, so we need to remove the quotes around. Using trim will
  184. // remove more than one quote if they are sequenced, generating
  185. // broken queries and SQL injection risks
  186. return substr($string, 1, -1);
  187. }
  188. /**
  189. * Gets the array from a SQL result (as returned by Database::query)
  190. *
  191. * @param Statement $result
  192. * @param string $option Optional: "ASSOC","NUM" or "BOTH"
  193. *
  194. * @return array|mixed
  195. */
  196. public static function fetch_array(Statement $result, $option = 'BOTH')
  197. {
  198. if ($result === false) {
  199. return array();
  200. }
  201. return $result->fetch(self::customOptionToDoctrineOption($option));
  202. }
  203. /**
  204. * Gets an associative array from a SQL result (as returned by Database::query).
  205. *
  206. * @param Statement $result
  207. *
  208. * @return array
  209. */
  210. public static function fetch_assoc(Statement $result)
  211. {
  212. return $result->fetch(PDO::FETCH_ASSOC);
  213. }
  214. /**
  215. * Gets the next row of the result of the SQL query
  216. * (as returned by Database::query) in an object form
  217. *
  218. * @param Statement $result
  219. *
  220. * @return mixed
  221. */
  222. public static function fetch_object(Statement $result)
  223. {
  224. return $result->fetch(PDO::FETCH_OBJ);
  225. }
  226. /**
  227. * Gets the array from a SQL result (as returned by Database::query)
  228. * help achieving database independence
  229. *
  230. * @param Statement $result
  231. *
  232. * @return mixed
  233. */
  234. public static function fetch_row(Statement $result)
  235. {
  236. return $result->fetch(PDO::FETCH_NUM);
  237. }
  238. /**
  239. * Frees all the memory associated with the provided result identifier.
  240. * @return boolean|null Returns TRUE on success or FALSE on failure.
  241. * Notes: Use this method if you are concerned about how much memory is being used for queries that return large result sets.
  242. * Anyway, all associated result memory is automatically freed at the end of the script's execution.
  243. */
  244. public static function free_result(Statement $result)
  245. {
  246. $result->closeCursor();
  247. }
  248. /**
  249. * Gets the ID of the last item inserted into the database
  250. *
  251. * @return string
  252. */
  253. public static function insert_id()
  254. {
  255. return self::getManager()->getConnection()->lastInsertId();
  256. }
  257. /**
  258. * @param Statement $result
  259. *
  260. * @return int
  261. */
  262. public static function num_rows(Statement $result)
  263. {
  264. return $result->rowCount();
  265. }
  266. /**
  267. * Acts as the relative *_result() function of most DB drivers and fetches a
  268. * specific line and a field
  269. *
  270. * @param Statement $resource
  271. * @param int $row
  272. * @param string $field
  273. *
  274. * @return mixed
  275. */
  276. public static function result(Statement $resource, $row, $field = '')
  277. {
  278. if ($resource->rowCount() > 0) {
  279. $result = $resource->fetchAll(PDO::FETCH_BOTH);
  280. return $result[$row][$field];
  281. }
  282. }
  283. /**
  284. * @param string $query
  285. *
  286. * @return Statement
  287. *
  288. * @throws \Doctrine\DBAL\DBALException
  289. */
  290. public static function query($query)
  291. {
  292. $connection = self::getManager()->getConnection();
  293. if (api_get_setting('server_type') == 'test') {
  294. $result = $connection->executeQuery($query);
  295. } else {
  296. try {
  297. $result = $connection->executeQuery($query);
  298. } catch (Exception $e) {
  299. error_log($e->getMessage());
  300. api_not_allowed(false, get_lang('GeneralError'));
  301. exit;
  302. }
  303. }
  304. return $result;
  305. }
  306. /**
  307. * @param string $option
  308. *
  309. * @return int
  310. */
  311. public static function customOptionToDoctrineOption($option)
  312. {
  313. switch ($option) {
  314. case 'ASSOC':
  315. return PDO::FETCH_ASSOC;
  316. break;
  317. case 'NUM':
  318. return PDO::FETCH_NUM;
  319. break;
  320. case 'BOTH':
  321. default:
  322. return PDO::FETCH_BOTH;
  323. break;
  324. }
  325. }
  326. /**
  327. * Stores a query result into an array.
  328. *
  329. * @author Olivier Brouckaert
  330. * @param Statement $result - the return value of the query
  331. * @param string $option BOTH, ASSOC, or NUM
  332. *
  333. * @return array - the value returned by the query
  334. */
  335. public static function store_result(Statement $result, $option = 'BOTH')
  336. {
  337. return $result->fetchAll(self::customOptionToDoctrineOption($option));
  338. }
  339. /**
  340. * Database insert
  341. * @param string $table_name
  342. * @param array $attributes
  343. * @param bool $show_query
  344. *
  345. * @return false|string
  346. */
  347. public static function insert($table_name, $attributes, $show_query = false)
  348. {
  349. if (empty($attributes) || empty($table_name)) {
  350. return false;
  351. }
  352. $params = array_keys($attributes);
  353. if (!empty($params)) {
  354. $sql = 'INSERT INTO '.$table_name.' ('.implode(',', $params).')
  355. VALUES (:'.implode(', :' ,$params).')';
  356. $statement = self::getManager()->getConnection()->prepare($sql);
  357. $result = $statement->execute($attributes);
  358. if ($show_query) {
  359. var_dump($sql);
  360. error_log($sql);
  361. }
  362. if ($result) {
  363. return self::getManager()->getConnection()->lastInsertId();
  364. }
  365. }
  366. return false;
  367. }
  368. /**
  369. * @param string $table_name use Database::get_main_table
  370. * @param array $attributes Values to updates
  371. * Example: $params['name'] = 'Julio'; $params['lastname'] = 'Montoya';
  372. * @param array $where_conditions where conditions i.e array('id = ?' =>'4')
  373. * @param bool $show_query
  374. *
  375. * @return bool|int
  376. */
  377. public static function update(
  378. $table_name,
  379. $attributes,
  380. $where_conditions = array(),
  381. $show_query = false
  382. ) {
  383. if (!empty($table_name) && !empty($attributes)) {
  384. $update_sql = '';
  385. //Cleaning attributes
  386. $count = 1;
  387. foreach ($attributes as $key => $value) {
  388. $update_sql .= "$key = :$key ";
  389. if ($count < count($attributes)) {
  390. $update_sql.=', ';
  391. }
  392. $count++;
  393. }
  394. if (!empty($update_sql)) {
  395. //Parsing and cleaning the where conditions
  396. $where_return = self::parse_where_conditions($where_conditions);
  397. $sql = "UPDATE $table_name SET $update_sql $where_return ";
  398. $statement = self::getManager()->getConnection()->prepare($sql);
  399. $result = $statement->execute($attributes);
  400. if ($show_query) {
  401. var_dump($sql);
  402. }
  403. if ($result) {
  404. return $statement->rowCount();
  405. }
  406. }
  407. }
  408. return false;
  409. }
  410. /**
  411. * Experimental useful database finder
  412. * @todo lot of stuff to do here
  413. * @todo known issues, it doesn't work when using LIKE conditions
  414. * @example array('where'=> array('course_code LIKE "?%"'))
  415. * @example array('where'=> array('type = ? AND category = ?' => array('setting', 'Plugins'))
  416. * @example array('where'=> array('name = "Julio" AND lastname = "montoya"'))
  417. */
  418. public static function select($columns, $table_name, $conditions = array(), $type_result = 'all', $option = 'ASSOC')
  419. {
  420. $conditions = self::parse_conditions($conditions);
  421. //@todo we could do a describe here to check the columns ...
  422. if (is_array($columns)) {
  423. $clean_columns = implode(',', $columns);
  424. } else {
  425. if ($columns == '*') {
  426. $clean_columns = '*';
  427. } else {
  428. $clean_columns = (string)$columns;
  429. }
  430. }
  431. $sql = "SELECT $clean_columns FROM $table_name $conditions";
  432. $result = self::query($sql);
  433. $array = array();
  434. if ($type_result == 'all') {
  435. while ($row = self::fetch_array($result, $option)) {
  436. if (isset($row['id'])) {
  437. $array[$row['id']] = $row;
  438. } else {
  439. $array[] = $row;
  440. }
  441. }
  442. } else {
  443. $array = self::fetch_array($result, $option);
  444. }
  445. return $array;
  446. }
  447. /**
  448. * Parses WHERE/ORDER conditions i.e array('where'=>array('id = ?' =>'4'), 'order'=>'id DESC'))
  449. * @todo known issues, it doesn't work when using
  450. * LIKE conditions example: array('where'=>array('course_code LIKE "?%"'))
  451. * @param array $conditions
  452. */
  453. public static function parse_conditions($conditions)
  454. {
  455. if (empty($conditions)) {
  456. return '';
  457. }
  458. $return_value = $where_return = '';
  459. foreach ($conditions as $type_condition => $condition_data) {
  460. if ($condition_data == false) {
  461. continue;
  462. }
  463. $type_condition = strtolower($type_condition);
  464. switch ($type_condition) {
  465. case 'where':
  466. foreach ($condition_data as $condition => $value_array) {
  467. if (is_array($value_array)) {
  468. $clean_values = array();
  469. foreach($value_array as $item) {
  470. $item = Database::escape_string($item);
  471. $clean_values[]= $item;
  472. }
  473. } else {
  474. $value_array = Database::escape_string($value_array);
  475. $clean_values = $value_array;
  476. }
  477. if (!empty($condition) && $clean_values != '') {
  478. $condition = str_replace('%',"'@percentage@'", $condition); //replace "%"
  479. $condition = str_replace("'?'","%s", $condition);
  480. $condition = str_replace("?","%s", $condition);
  481. $condition = str_replace("@%s@","@-@", $condition);
  482. $condition = str_replace("%s","'%s'", $condition);
  483. $condition = str_replace("@-@","@%s@", $condition);
  484. // Treat conditions as string
  485. $condition = vsprintf($condition, $clean_values);
  486. $condition = str_replace('@percentage@','%', $condition); //replace "%"
  487. $where_return .= $condition;
  488. }
  489. }
  490. if (!empty($where_return)) {
  491. $return_value = " WHERE $where_return" ;
  492. }
  493. break;
  494. case 'order':
  495. $order_array = $condition_data;
  496. if (!empty($order_array)) {
  497. // 'order' => 'id desc, name desc'
  498. $order_array = self::escape_string($order_array, null, false);
  499. $new_order_array = explode(',', $order_array);
  500. $temp_value = array();
  501. foreach($new_order_array as $element) {
  502. $element = explode(' ', $element);
  503. $element = array_filter($element);
  504. $element = array_values($element);
  505. if (!empty($element[1])) {
  506. $element[1] = strtolower($element[1]);
  507. $order = 'DESC';
  508. if (in_array($element[1], array('desc', 'asc'))) {
  509. $order = $element[1];
  510. }
  511. $temp_value[]= $element[0].' '.$order.' ';
  512. } else {
  513. //by default DESC
  514. $temp_value[]= $element[0].' DESC ';
  515. }
  516. }
  517. if (!empty($temp_value)) {
  518. $return_value .= ' ORDER BY '.implode(', ', $temp_value);
  519. } else {
  520. //$return_value .= '';
  521. }
  522. }
  523. break;
  524. case 'limit':
  525. $limit_array = explode(',', $condition_data);
  526. if (!empty($limit_array)) {
  527. if (count($limit_array) > 1) {
  528. $return_value .= ' LIMIT '.intval($limit_array[0]).' , '.intval($limit_array[1]);
  529. } else {
  530. $return_value .= ' LIMIT '.intval($limit_array[0]);
  531. }
  532. }
  533. break;
  534. }
  535. }
  536. return $return_value;
  537. }
  538. /**
  539. * @param array $conditions
  540. *
  541. * @return string
  542. */
  543. public static function parse_where_conditions($conditions)
  544. {
  545. return self::parse_conditions(array('where' => $conditions));
  546. }
  547. /**
  548. * @param string $table_name
  549. * @param array $where_conditions
  550. * @param bool $show_query
  551. *
  552. * @return int
  553. */
  554. public static function delete($table_name, $where_conditions, $show_query = false)
  555. {
  556. $where_return = self::parse_where_conditions($where_conditions);
  557. $sql = "DELETE FROM $table_name $where_return ";
  558. if ($show_query) { echo $sql; echo '<br />'; }
  559. $result = self::query($sql);
  560. $affected_rows = self::affected_rows($result);
  561. //@todo should return affected_rows for
  562. return $affected_rows;
  563. }
  564. /**
  565. * Get Doctrine configuration
  566. * @param string $path
  567. *
  568. * @return \Doctrine\ORM\Configuration
  569. */
  570. public static function getDoctrineConfig($path)
  571. {
  572. $isDevMode = false;
  573. $isSimpleMode = false; // related to annotations @Entity
  574. $cache = null;
  575. $path = !empty($path) ? $path : api_get_path(SYS_PATH);
  576. $paths = array(
  577. $path.'src/Chamilo/CoreBundle/Entity',
  578. $path.'src/Chamilo/UserBundle/Entity',
  579. $path.'src/Chamilo/CourseBundle/Entity'
  580. );
  581. $proxyDir = $path.'app/cache/';
  582. return \Doctrine\ORM\Tools\Setup::createAnnotationMetadataConfiguration(
  583. $paths,
  584. $isDevMode,
  585. $proxyDir,
  586. $cache,
  587. $isSimpleMode
  588. );
  589. }
  590. /**
  591. * @param string $table
  592. *
  593. * @return bool
  594. */
  595. public static function tableExists($table)
  596. {
  597. return self::getManager()->getConnection()->getSchemaManager()->tablesExist($table);
  598. }
  599. /**
  600. * @param string $table
  601. * @return \Doctrine\DBAL\Schema\Column[]
  602. */
  603. public static function listTableColumns($table)
  604. {
  605. return self::getManager()->getConnection()->getSchemaManager()->listTableColumns($table);
  606. }
  607. }