database.lib.php 22 KB

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