database.lib.php 20 KB

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