database.lib.php 61 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485
  1. <?php
  2. /* For licensing terms, see /license.txt */
  3. /**
  4. * This is the main database library for Chamilo.
  5. * Include/require it in your code to use its functionality.
  6. * Because this library contains all the basic database calls, it could be
  7. * replaced by another library for say, PostgreSQL, to actually use Chamilo
  8. * with another database (this is not ready yet because a lot of code still
  9. * uses the MySQL database functions extensively).
  10. *
  11. * If trying to replicate the database layer, don't forget to look for "sql"
  12. * named functions in main_api.lib.php
  13. *
  14. * @package chamilo.library
  15. */
  16. /**
  17. * Database class definition
  18. * @package chamilo.database
  19. */
  20. class Database
  21. {
  22. /* Variable use only in the installation process to log errors. See the Database::query function */
  23. static $log_queries = false;
  24. /*
  25. Accessor methods
  26. Usually, you won't need these directly but instead
  27. rely on of the get_xxx_table methods.
  28. */
  29. /**
  30. * Returns the name of the main database.
  31. */
  32. public static function get_main_database()
  33. {
  34. global $_configuration;
  35. return isset($_configuration['main_database']) ? $_configuration['main_database'] : null;
  36. }
  37. /**
  38. * Returns the name of the statistics database.
  39. * @todo use main_database
  40. */
  41. public static function get_statistic_database()
  42. {
  43. global $_configuration;
  44. return isset($_configuration['main_database']) ? $_configuration['main_database'] : null;
  45. }
  46. /**
  47. * Returns the name of the current course database.
  48. * @return mixed Glued database name of false if undefined
  49. */
  50. public static function get_current_course_database()
  51. {
  52. $course_info = api_get_course_info();
  53. if (empty($course_info['dbName'])) {
  54. return false;
  55. }
  56. return $course_info['dbName'];
  57. }
  58. /**
  59. * Returns the glued name of the current course database.
  60. * @return mixed Glued database name of false if undefined
  61. */
  62. public static function get_current_course_glued_database()
  63. {
  64. $course_info = api_get_course_info();
  65. if (empty($course_info['dbNameGlu'])) {
  66. return false;
  67. }
  68. return $course_info['dbNameGlu'];
  69. }
  70. /**
  71. * The glue is the string needed between database and table.
  72. * The trick is: in multiple databases, this is a period (with backticks).
  73. * In single database, this can be e.g. an underscore so we just fake
  74. * there are multiple databases and the code can be written independent
  75. * of the single / multiple database setting.
  76. */
  77. public static function get_database_glue()
  78. {
  79. global $_configuration;
  80. return $_configuration['db_glue'];
  81. }
  82. /**
  83. * Returns the database prefix.
  84. * All created COURSE databases are prefixed with this string.
  85. *
  86. * TIP: This can be convenient if you have multiple system installations
  87. * on the same physical server.
  88. */
  89. public static function get_database_name_prefix()
  90. {
  91. global $_configuration;
  92. return $_configuration['db_prefix'];
  93. }
  94. /**
  95. * Returns the course table prefix for single database.
  96. * Not certain exactly when this is used.
  97. * Do research.
  98. * It's used in local.inc.php.
  99. */
  100. public static function get_course_table_prefix()
  101. {
  102. global $_configuration;
  103. return $_configuration['table_prefix'];
  104. }
  105. /*
  106. Table name methods
  107. Use these methods to get table names for queries,
  108. instead of constructing them yourself.
  109. Backticks automatically surround the result,
  110. e.g. COURSE_NAME.link
  111. so the queries can look cleaner.
  112. Example:
  113. $table = Database::get_course_table(TABLE_DOCUMENT);
  114. $sql_query = "SELECT * FROM $table WHERE $condition";
  115. $sql_result = Database::query($sql_query);
  116. $result = Database::fetch_array($sql_result);
  117. */
  118. /**
  119. * A more generic method than the other get_main_xxx_table methods,
  120. * This one returns the correct complete name of any table of the main
  121. * database of which you pass the short name as a parameter.
  122. * Please, define table names as constants in this library and use them
  123. * instead of directly using magic words in your tool code.
  124. *
  125. * @param string $short_table_name, the name of the table
  126. */
  127. public static function get_main_table($short_table_name)
  128. {
  129. return self::format_table_name(
  130. self::get_main_database(),
  131. $short_table_name
  132. );
  133. }
  134. /**
  135. * A more generic method than the older get_course_xxx_table methods,
  136. * This one can return the correct complete name of any course table of
  137. * which you pass the short name as a parameter.
  138. * Please, define table names as constants in this library and use them
  139. * instead of directly using magic words in your tool code.
  140. *
  141. * @param string $short_table_name, the name of the table
  142. * @param string $database_name, optional, name of the course database
  143. * - if you don't specify this, you work on the current course.
  144. */
  145. public static function get_course_table($short_table_name, $extra = null)
  146. {
  147. //forces fatal errors so we can debug more easily
  148. if (!empty($extra)) {
  149. //@todo remove this
  150. echo "<h3>Dev Message: get_course_table() doesn't have a 2nd parameter</h3>";
  151. //exit;
  152. }
  153. return self::format_table_name(self::get_main_database(), DB_COURSE_PREFIX.$short_table_name);
  154. //return self::format_glued_course_table_name(self::fix_database_parameter($database_name), $short_table_name);
  155. }
  156. /**
  157. * This generic method returns the correct and complete name of any
  158. * statistic table of which you pass the short name as a parameter.
  159. * Please, define table names as constants in this library and use them
  160. * instead of directly using magic words in your tool code.
  161. *
  162. * @param string $short_table_name, the name of the table
  163. */
  164. public static function get_statistic_table($short_table_name)
  165. {
  166. return self::get_main_table($short_table_name);
  167. }
  168. /**
  169. * This generic method returns the correct and complete name of any user
  170. * table of which you pass the short name as a parameter. Please, define
  171. * table names as constants in this library and use them instead of directly
  172. * using magic words in your tool code.
  173. *
  174. * @param string $short_table_name, the name of the table
  175. */
  176. public static function get_user_personal_table($short_table_name)
  177. {
  178. return self::get_main_table($short_table_name);
  179. }
  180. public static function get_course_chat_connected_table($database_name = '')
  181. {
  182. return self::format_glued_course_table_name(self::fix_database_parameter($database_name), TABLE_CHAT_CONNECTED);
  183. }
  184. /*
  185. Query methods
  186. These methods execute a query and return the result(s).
  187. */
  188. /**
  189. * @return a list (array) of all courses.
  190. * @todo shouldn't this be in the course.lib.php script?
  191. */
  192. public static function get_course_list()
  193. {
  194. $table = self::get_main_table(TABLE_MAIN_COURSE);
  195. return self::store_result(self::query("SELECT *, id as real_id FROM $table"));
  196. }
  197. /**
  198. * Returns an array with all database fields for the specified course.
  199. *
  200. * @param string The real (system) course code (main course table ID)
  201. * @todo shouldn't this be in the course.lib.php script?
  202. */
  203. public static function get_course_info($course_code)
  204. {
  205. $course_code = self::escape_string($course_code);
  206. $table = self::get_main_table(TABLE_MAIN_COURSE);
  207. $result = self::generate_abstract_course_field_names(
  208. self::fetch_array(self::query("SELECT *, id as real_id FROM $table WHERE code = '$course_code'"))
  209. );
  210. return $result === false ? array('db_name' => '') : $result;
  211. }
  212. /**
  213. * Returns course code from a given gradebook category's id
  214. * @param int Category ID
  215. * @return string Course code
  216. * @todo move this function in a gradebook-related library
  217. */
  218. public static function get_course_by_category($category_id)
  219. {
  220. $category_id = intval($category_id);
  221. $info = self::fetch_array(
  222. self::query(
  223. 'SELECT course_code FROM '.self::get_main_table(TABLE_MAIN_GRADEBOOK_CATEGORY).' WHERE id='.$category_id
  224. ),
  225. 'ASSOC'
  226. );
  227. return $info ? $info['course_code'] : false;
  228. }
  229. /**
  230. * This method creates an abstraction layer between database field names
  231. * and field names expected in code.
  232. *
  233. * This approach helps when changing database names.
  234. * It's also useful now to get rid of the 'franglais'.
  235. *
  236. * @todo add more array entries to abstract course info from field names
  237. * @author Roan Embrechts
  238. *
  239. * @todo What's the use of this method. I think this is better removed.
  240. * There should be consistency in the variable names and the
  241. * use throughout the scripts
  242. * for the database name we should consistently use or db_name
  243. * or database (db_name probably being the better one)
  244. */
  245. public static function generate_abstract_course_field_names($result_array)
  246. {
  247. $visual_code = isset($result_array['visual_code']) ? $result_array['visual_code'] : null;
  248. $code = isset($result_array['code']) ? $result_array['code'] : null;
  249. $title = isset($result_array['title']) ? $result_array['title'] : null;
  250. $db_name = isset($result_array['db_name']) ? $result_array['db_name'] : null;
  251. $category_code = isset($result_array['category_code']) ? $result_array['category_code'] : null;
  252. $result_array['official_code'] = $visual_code;
  253. $result_array['visual_code'] = $visual_code;
  254. $result_array['real_code'] = $code;
  255. $result_array['system_code'] = $code;
  256. $result_array['title'] = $title;
  257. $result_array['database'] = $db_name;
  258. $result_array['faculty'] = $category_code;
  259. //$result_array['directory'] = $result_array['directory'];
  260. /*
  261. still to do: (info taken from local.inc.php)
  262. $_course['id' ] = $cData['cours_id' ]; //auto-assigned integer
  263. $_course['name' ] = $cData['title' ];
  264. $_course['official_code'] = $cData['visual_code' ]; // use in echo
  265. $_course['sysCode' ] = $cData['code' ]; // use as key in db
  266. $_course['path' ] = $cData['directory' ]; // use as key in path
  267. $_course['dbName' ] = $cData['db_name' ]; // use as key in db list
  268. $_course['dbNameGlu' ] = $_configuration['table_prefix'] . $cData['dbName'] . $_configuration['db_glue']; // use in all queries
  269. $_course['titular' ] = $cData['tutor_name' ];
  270. $_course['language' ] = $cData['course_language' ];
  271. $_course['extLink' ]['url' ] = $cData['department_url' ];
  272. $_course['extLink' ]['name'] = $cData['department_name'];
  273. $_course['categoryCode'] = $cData['faCode' ];
  274. $_course['categoryName'] = $cData['faName' ];
  275. $_course['visibility' ] = (bool) ($cData['visibility'] == 2 || $cData['visibility'] == 3);
  276. $_course['registrationAllowed'] = (bool) ($cData['visibility'] == 1 || $cData['visibility'] == 2);
  277. */
  278. return $result_array;
  279. }
  280. /**
  281. * This method creates an abstraction layer between database field names
  282. * and field names expected in code.
  283. *
  284. * This helps when changing database names.
  285. * It's also useful now to get rid of the 'franglais'.
  286. *
  287. * @todo add more array entries to abstract user info from field names
  288. * @author Roan Embrechts
  289. * @author Patrick Cool
  290. *
  291. * @todo what's the use of this function. I think this is better removed.
  292. * There should be consistency in the variable names and the use throughout the scripts
  293. */
  294. public static function generate_abstract_user_field_names($result_array)
  295. {
  296. $result_array['firstName'] = $result_array['firstname'];
  297. $result_array['lastName'] = $result_array['lastname'];
  298. $result_array['mail'] = $result_array['email'];
  299. #$result_array['picture_uri'] = $result_array['picture_uri'];
  300. #$result_array ['user_id'] = $result_array['user_id'];
  301. return $result_array;
  302. }
  303. /**
  304. * Counts the number of rows in a table
  305. * @param string $table The table of which the rows should be counted
  306. * @return int The number of rows in the given table.
  307. */
  308. public static function count_rows($table)
  309. {
  310. $obj = self::fetch_object(self::query("SELECT COUNT(*) AS n FROM $table")); //
  311. return $obj->n;
  312. }
  313. /*
  314. An intermediate API-layer between the system and the dabase server.
  315. */
  316. /**
  317. * Returns the number of affected rows in the last database operation.
  318. * @param resource $connection (optional) The database server connection, for detailed description see the method query().
  319. * @return int Returns the number of affected rows on success, and -1 if the last query failed.
  320. */
  321. public static function affected_rows($connection = null)
  322. {
  323. return self::use_default_connection($connection) ? mysql_affected_rows() : mysql_affected_rows($connection);
  324. }
  325. /**
  326. * Closes non-persistent database connection.
  327. * @param resource $connection (optional) The database server connection, for detailed description see the method query().
  328. * @return bool Returns TRUE on success or FALSE on failure.
  329. */
  330. public static function close($connection = null)
  331. {
  332. return self::use_default_connection($connection) ? mysql_close() : mysql_close($connection);
  333. }
  334. /**
  335. * Opens a connection to a database server.
  336. * @param array $parameters (optional) An array that contains the necessary parameters for accessing the server.
  337. * @return resource/boolean Returns a database connection on success or FALSE on failure.
  338. * Note: Currently the array could contain MySQL-specific parameters:
  339. * $parameters['server'], $parameters['username'], $parameters['password'],
  340. * $parameters['new_link'], $parameters['client_flags'], $parameters['persistent'].
  341. * For details see documentation about the functions mysql_connect() and mysql_pconnect().
  342. * @link http://php.net/manual/en/function.mysql-connect.php
  343. * @link http://php.net/manual/en/function.mysql-pconnect.php
  344. */
  345. public static function connect($parameters = array())
  346. {
  347. // A MySQL-specific implementation.
  348. if (!isset($parameters['server'])) {
  349. $parameters['server'] = @ini_get('mysql.default_host');
  350. if (empty($parameters['server'])) {
  351. $parameters['server'] = 'localhost:3306';
  352. }
  353. }
  354. if (!isset($parameters['username'])) {
  355. $parameters['username'] = @ini_get('mysql.default_user');
  356. }
  357. if (!isset($parameters['password'])) {
  358. $parameters['password'] = @ini_get('mysql.default_password');
  359. }
  360. if (!isset($parameters['new_link'])) {
  361. $parameters['new_link'] = false;
  362. }
  363. if (!isset($parameters['client_flags'])) {
  364. $parameters['client_flags'] = 0;
  365. }
  366. $persistent = isset($parameters['persistent']) ? $parameters['persistent'] : null;
  367. $server = isset($parameters['server']) ? $parameters['server'] : null;
  368. $username = isset($parameters['username']) ? $parameters['username'] : null;
  369. $password = isset($parameters['password']) ? $parameters['password'] : null;
  370. $client_flag = isset($parameters['client_flags']) ? $parameters['client_flags'] : null;
  371. $new_link = isset($parameters['new_link']) ? $parameters['new_link'] : null;
  372. $client_flags = isset($parameters['client_flags']) ? $parameters['client_flags'] : null;
  373. return $persistent
  374. ? mysql_pconnect($server, $username, $password, $client_flags)
  375. : mysql_connect($server, $username, $password, $new_link, $client_flags);
  376. }
  377. /**
  378. * Returns error number from the last operation done on the database server.
  379. * @param resource $connection (optional) The database server connection,
  380. * for detailed description see the method query().
  381. * @return int Returns the error number from the last database (operation, or 0 (zero) if no error occurred.
  382. */
  383. public static function errno($connection = null)
  384. {
  385. return self::use_default_connection($connection) ? mysql_errno() : mysql_errno($connection);
  386. }
  387. /**
  388. * Returns error text from the last operation done on the database server.
  389. * @param resource $connection (optional) The database server connection, for detailed description see the method query().
  390. * @return string Returns the error text from the last database operation, or '' (empty string) if no error occurred.
  391. */
  392. public static function error($connection = null)
  393. {
  394. return self::use_default_connection($connection) ? mysql_error() : mysql_error($connection);
  395. }
  396. /**
  397. * Escapes a string to insert into the database as text
  398. * @param string The string to escape
  399. * @param resource $connection (optional) The database server connection, for detailed description see the method query().
  400. * @return string The escaped string
  401. * @author Yannick Warnier <yannick.warnier@dokeos.com>
  402. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  403. */
  404. public static function escape_string($string, $connection = null)
  405. {
  406. return get_magic_quotes_gpc()
  407. ? (self::use_default_connection($connection)
  408. ? mysql_real_escape_string(stripslashes($string))
  409. : mysql_real_escape_string(stripslashes($string), $connection))
  410. : (self::use_default_connection($connection)
  411. ? mysql_real_escape_string($string)
  412. : mysql_real_escape_string($string, $connection));
  413. }
  414. /**
  415. * Gets the array from a SQL result (as returned by Database::query) - help achieving database independence
  416. * @param resource The result from a call to sql_query (e.g. Database::query)
  417. * @param string Optional: "ASSOC","NUM" or "BOTH", as the constant used in mysql_fetch_array.
  418. * @return array Array of results as returned by php
  419. * @author Yannick Warnier <yannick.warnier@beeznest.com>
  420. */
  421. public static function fetch_array($result, $option = 'BOTH')
  422. {
  423. if ($result === false) {
  424. return array();
  425. }
  426. return $option == 'ASSOC' ? mysql_fetch_array($result, MYSQL_ASSOC) : ($option == 'NUM' ? mysql_fetch_array(
  427. $result,
  428. MYSQL_NUM
  429. ) : mysql_fetch_array($result));
  430. }
  431. /**
  432. * Gets an associative array from a SQL result (as returned by Database::query).
  433. * This method is equivalent to calling Database::fetch_array() with 'ASSOC' value for the optional second parameter.
  434. * @param resource $result The result from a call to sql_query (e.g. Database::query).
  435. * @return array Returns an associative array that corresponds to the fetched row and moves the internal data pointer ahead.
  436. */
  437. public static function fetch_assoc($result)
  438. {
  439. return mysql_fetch_assoc($result);
  440. }
  441. /**
  442. * Gets the next row of the result of the SQL query (as returned by Database::query) in an object form
  443. * @param resource The result from a call to sql_query (e.g. Database::query)
  444. * @param string Optional class name to instanciate
  445. * @param array Optional array of parameters
  446. * @return object Object of class StdClass or the required class, containing the query result row
  447. * @author Yannick Warnier <yannick.warnier@dokeos.com>
  448. */
  449. public static function fetch_object($result, $class = null, $params = null)
  450. {
  451. return !empty($class) ? (is_array($params) ? mysql_fetch_object($result, $class, $params) : mysql_fetch_object(
  452. $result,
  453. $class
  454. )) : mysql_fetch_object($result);
  455. }
  456. /**
  457. * Gets the array from a SQL result (as returned by Database::query) - help achieving database independence
  458. * @param resource The result from a call to sql_query (see Database::query()).
  459. * @return array Array of results as returned by php (mysql_fetch_row)
  460. */
  461. public static function fetch_row($result)
  462. {
  463. return mysql_fetch_row($result);
  464. }
  465. /**
  466. * Frees all the memory associated with the provided result identifier.
  467. * @return bool Returns TRUE on success or FALSE on failure.
  468. * Notes: Use this method if you are concerned about how much memory is being used for queries that return large result sets.
  469. * Anyway, all associated result memory is automatically freed at the end of the script's execution.
  470. */
  471. public static function free_result($result)
  472. {
  473. return mysql_free_result($result);
  474. }
  475. /**
  476. * Returns the database client library version.
  477. * @return strung Returns a string that represents the client library version.
  478. */
  479. public static function get_client_info()
  480. {
  481. return mysql_get_client_info();
  482. }
  483. /**
  484. * Returns a list of databases created on the server. The list may contain all of the
  485. * available database names or filtered database names by using a pattern.
  486. * @param string $pattern (optional) A pattern for filtering database names as if it was needed for the SQL's LIKE clause, for example 'chamilo_%'.
  487. * @param resource $connection (optional) The database server connection, for detailed description see the method query().
  488. * @return array Returns in an array the retrieved list of database names.
  489. */
  490. public static function get_databases($pattern = '', $connection = null)
  491. {
  492. $result = array();
  493. $query_result = Database::query(
  494. !empty($pattern) ? "SHOW DATABASES LIKE '".self::escape_string(
  495. $pattern,
  496. $connection
  497. )."'" : "SHOW DATABASES",
  498. $connection
  499. );
  500. while ($row = Database::fetch_row($query_result)) {
  501. $result[] = $row[0];
  502. }
  503. return $result;
  504. }
  505. /**
  506. * Returns a list of the fields that a given table contains. The list may contain all of the available field names or filtered field names by using a pattern.
  507. * By using a special option, this method is able to return an indexed list of fields' properties, where field names are keys.
  508. * @param string $table This is the examined table.
  509. * @param string $pattern (optional) A pattern for filtering field names as if it was needed for the SQL's LIKE clause, for example 'column_%'.
  510. * @param string $database (optional) The name of the targeted database. If it is omited, the current database is assumed, see Database::select_db().
  511. * @param bool $including_properties (optional) When this option is true, the returned result has the followong format:
  512. * array(field_name_1 => array(0 => property_1, 1 => property_2, ...), fieald_name_2 => array(0 => property_1, ...), ...)
  513. * @param resource $connection (optional) The database server connection, for detailed description see the method query().
  514. * @return array Returns in an array the retrieved list of field names.
  515. */
  516. public static function get_fields(
  517. $table,
  518. $pattern = '',
  519. $database = '',
  520. $including_properties = false,
  521. $connection = null
  522. ) {
  523. $result = array();
  524. $query = "SHOW COLUMNS FROM `".self::escape_string($table, $connection)."`";
  525. if (!empty($database)) {
  526. $query .= " FROM `".self::escape_string($database, $connection)."`";
  527. }
  528. if (!empty($pattern)) {
  529. $query .= " LIKE '".self::escape_string($pattern, $connection)."'";
  530. }
  531. $query_result = Database::query($query, $connection);
  532. if ($including_properties) {
  533. // Making an indexed list of the fields and their properties.
  534. while ($row = Database::fetch_row($query_result)) {
  535. $result[$row[0]] = $row;
  536. }
  537. } else {
  538. // Making a plain, flat list.
  539. while ($row = Database::fetch_row($query_result)) {
  540. $result[] = $row[0];
  541. }
  542. }
  543. return $result;
  544. }
  545. /**
  546. * Returns information about the type of the current connection and the server host name.
  547. * @param resource $connection (optional) The database server connection, for detailed description see the method query().
  548. * @return string/boolean Returns string data on success or FALSE on failure.
  549. */
  550. public static function get_host_info($connection = null)
  551. {
  552. return self::use_default_connection($connection) ? mysql_get_host_info() : mysql_get_host_info($connection);
  553. }
  554. /**
  555. * Retrieves database client/server protocol version.
  556. * @param resource $connection (optional) The database server connection, for detailed description see the method query().
  557. * @return int/boolean Returns the protocol version on success or FALSE on failure.
  558. */
  559. public static function get_proto_info($connection = null)
  560. {
  561. return self::use_default_connection($connection) ? mysql_get_proto_info() : mysql_get_proto_info($connection);
  562. }
  563. /**
  564. * Retrieves the database server version.
  565. * @param resource $connection (optional) The database server connection, for detailed description see the method query().
  566. * @return string/boolean Returns the MySQL server version on success or FALSE on failure.
  567. */
  568. public static function get_server_info($connection = null)
  569. {
  570. return self::use_default_connection($connection) ? mysql_get_server_info() : mysql_get_server_info($connection);
  571. }
  572. /**
  573. * Returns a list of tables within a database. The list may contain all of the
  574. * available table names or filtered table names by using a pattern.
  575. * @param string $database (optional) The name of the examined database. If it is omited, the current database is assumed, see Database::select_db().
  576. * @param string $pattern (optional) A pattern for filtering table names as if it was needed for the SQL's LIKE clause, for example 'access_%'.
  577. * @param resource $connection (optional) The database server connection, for detailed description see the method query().
  578. * @return array Returns in an array the retrieved list of table names.
  579. */
  580. public static function get_tables($database = '', $pattern = '', $connection = null)
  581. {
  582. $result = array();
  583. $query = "SHOW TABLES";
  584. if (!empty($database)) {
  585. $query .= " FROM `".self::escape_string($database, $connection)."`";
  586. }
  587. if (!empty($pattern)) {
  588. $query .= " LIKE '".self::escape_string($pattern, $connection)."'";
  589. }
  590. $query_result = Database::query($query, $connection);
  591. while ($row = Database::fetch_row($query_result)) {
  592. $result[] = $row[0];
  593. }
  594. return $result;
  595. }
  596. /**
  597. * Gets the ID of the last item inserted into the database
  598. * This should be updated to use ADODB at some point
  599. * @param resource $connection (optional) The database server connection, for detailed description see the method query().
  600. * @return int The last ID as returned by the DB function
  601. */
  602. public static function insert_id($connection = null)
  603. {
  604. return self::use_default_connection($connection) ? mysql_insert_id() : mysql_insert_id($connection);
  605. }
  606. /**
  607. * Gets the number of rows from the last query result - help achieving database independence
  608. * @param resource The result
  609. * @return integer The number of rows contained in this result
  610. * @author Yannick Warnier <yannick.warnier@dokeos.com>
  611. **/
  612. public static function num_rows($result)
  613. {
  614. return is_resource($result) ? mysql_num_rows($result) : false;
  615. }
  616. /**
  617. * Acts as the relative *_result() function of most DB drivers and fetches a
  618. * specific line and a field
  619. * @param resource The database resource to get data from
  620. * @param integer The row number
  621. * @param string Optional field name or number
  622. * @return mixed One cell of the result, or FALSE on error
  623. */
  624. public static function result($resource, $row, $field = '')
  625. {
  626. return self::num_rows($resource) > 0 ? (!empty($field) ? mysql_result($resource, $row, $field) : mysql_result(
  627. $resource,
  628. $row
  629. )) : null;
  630. }
  631. /**
  632. * This method returns a resource
  633. * Documentation has been added by Arthur Portugal
  634. * Some adaptations have been implemented by Ivan Tcholakov, 2009, 2010
  635. * @author Olivier Brouckaert
  636. * @param string $query The SQL query
  637. * @param resource $connection (optional) The database server (MySQL) connection.
  638. * If it is not specified, the connection opened by mysql_connect() is assumed.
  639. * If no connection is found, the server will try to create one as if mysql_connect() was called with no arguments.
  640. * If no connection is found or established, an E_WARNING level error is generated.
  641. * @param string $file (optional) On error it shows the file in which the error has been trigerred (use the "magic" constant __FILE__ as input parameter)
  642. * @param string $line (optional) On error it shows the line in which the error has been trigerred (use the "magic" constant __LINE__ as input parameter)
  643. * @return resource The returned result from the query
  644. * Note: The parameter $connection could be skipped. Here are examples of this method usage:
  645. * Database::query($query);
  646. * $result = Database::query($query);
  647. * Database::query($query, $connection);
  648. * $result = Database::query($query, $connection);
  649. * The following ways for calling this method are obsolete:
  650. * Database::query($query, __FILE__, __LINE__);
  651. * $result = Database::query($query, __FILE__, __LINE__);
  652. * Database::query($query, $connection, __FILE__, __LINE__);
  653. * $result = Database::query($query, $connection, __FILE__, __LINE__);
  654. */
  655. public static function query($query, $connection = null, $file = null, $line = null)
  656. {
  657. $use_default_connection = self::use_default_connection($connection);
  658. if ($use_default_connection) {
  659. // Let us do parameter shifting, thus the method would be similar
  660. // (in regard to parameter order) to the original function mysql_query().
  661. $line = $file;
  662. $file = $connection;
  663. $connection = null;
  664. }
  665. //@todo remove this before the stable release
  666. //Check if the table contains a c_ (means a course id)
  667. if (api_get_setting('server_type') === 'test' && strpos($query, 'c_')) {
  668. //Check if the table contains inner joins
  669. if (
  670. strpos($query, 'assoc_handle') === false &&
  671. strpos($query, 'olpc_peru_filter') === false &&
  672. strpos($query, 'allow_public_certificates') === false &&
  673. strpos($query, 'DROP TABLE IF EXISTS') === false &&
  674. strpos($query, 'thematic_advance') === false &&
  675. strpos($query, 'thematic_plan') === false &&
  676. strpos($query, 'track_c_countries') === false &&
  677. strpos($query, 'track_c_os') === false &&
  678. strpos($query, 'track_c_providers') === false &&
  679. strpos($query, 'track_c_referers') === false &&
  680. strpos($query, 'track_c_browsers') === false &&
  681. strpos($query, 'settings_current') === false &&
  682. strpos($query, 'branch_sync') === false &&
  683. strpos($query, 'branch_sync_log') === false &&
  684. strpos($query, 'branch_sync_log') === false &&
  685. strpos($query, 'branch_transaction') === false &&
  686. strpos($query, 'branch_transaction_status') === false &&
  687. strpos($query, 'dokeos_classic_2D') === false &&
  688. strpos($query, 'cosmic_campus') === false &&
  689. strpos($query, 'static_') === false &&
  690. strpos($query, 'public_admin') === false &&
  691. strpos($query, 'chamilo_electric_blue') === false &&
  692. strpos($query, 'wcag_anysurfer_public_pages') === false &&
  693. strpos($query, 'specific_field') === false &&
  694. strpos($query, 'down_doc_path') === false &&
  695. strpos($query, 'INNER JOIN') === false &&
  696. strpos($query, 'inner join') === false &&
  697. strpos($query, 'left join') === false &&
  698. strpos($query, 'LEFT JOIN') === false &&
  699. strpos($query, 'insert') === false &&
  700. strpos($query, 'INSERT') === false &&
  701. strpos($query, 'ALTER') === false &&
  702. strpos($query, 'alter') === false &&
  703. strpos($query, 'c_id') === false &&
  704. strpos($query, 'create table') === false &&
  705. strpos($query, 'CREATE TABLE') === false &&
  706. strpos($query, 'AUTO_INCREMENT') === false
  707. ) {
  708. //@todo remove this
  709. echo '<pre>';
  710. $message = '<h4>Dev message: please add the c_id field in this query or report this error in support.chamilo.org </h4>';
  711. $message .= $query;
  712. echo $message;
  713. echo '</pre>';
  714. //error_log($message);
  715. }
  716. }
  717. if (!($result = $use_default_connection ? @mysql_query($query) : @mysql_query($query, $connection))) {
  718. $backtrace = debug_backtrace(); // Retrieving information about the caller statement.
  719. if (isset($backtrace[0])) {
  720. $caller = & $backtrace[0];
  721. } else {
  722. $caller = array();
  723. }
  724. if (isset($backtrace[1])) {
  725. $owner = & $backtrace[1];
  726. } else {
  727. $owner = array();
  728. }
  729. if (empty($file)) {
  730. $file = $caller['file'];
  731. }
  732. if (empty($line) && $line !== false) {
  733. $line = $caller['line'];
  734. }
  735. $type = isset($owner['type']) ? $owner['type'] : null;
  736. $function = $owner['function'];
  737. $class = isset($owner['class']) ? $owner['class'] : null;
  738. $server_type = api_get_setting('server_type');
  739. if (!empty($line) && !empty($server_type) && $server_type != 'production') {
  740. $info = '<pre>'.
  741. '<strong>DATABASE ERROR #'.self::errno($connection).':</strong><br /> '.
  742. self::remove_XSS(self::error($connection)).'<br />'.
  743. '<strong>QUERY :</strong><br /> '.
  744. self::remove_XSS($query).'<br />'.
  745. '<strong>FILE :</strong><br /> '.
  746. (empty($file) ? ' unknown ' : $file).'<br />'.
  747. '<strong>LINE :</strong><br /> '.
  748. (empty($line) ? ' unknown ' : $line).'<br />';
  749. if (empty($type)) {
  750. if (!empty($function)) {
  751. $info .= '<strong>FUNCTION :</strong><br /> '.$function;
  752. }
  753. } else {
  754. if (!empty($class) && !empty($function)) {
  755. $info .= '<strong>CLASS :</strong><br /> '.$class.'<br />';
  756. $info .= '<strong>METHOD :</strong><br /> '.$function;
  757. }
  758. }
  759. $info .= '</pre>';
  760. echo $info;
  761. }
  762. if (isset(self::$log_queries) && self::$log_queries) {
  763. error_log("---------------- SQL error ---------------- ");
  764. error_log($query);
  765. error_log('error #'.self::errno($connection));
  766. error_log('error: '.self::error($connection));
  767. $info = 'FILE: '.(empty($file) ? ' unknown ' : $file);
  768. $info .= ' +'.(empty($line) ? ' unknown ' : $line);
  769. error_log($info);
  770. if (empty($type)) {
  771. if (!empty($function)) {
  772. $info = 'FUNCTION: '.$function;
  773. error_log($info);
  774. }
  775. } else {
  776. if (!empty($class) && !empty($function)) {
  777. $info = 'CLASS: '.$class.' METHOD: '.$function;
  778. error_log($info);
  779. }
  780. }
  781. error_log("---------------- end ----------------");
  782. }
  783. }
  784. return $result;
  785. }
  786. /**
  787. * Selects a database.
  788. * @param string $database_name The name of the database that is to be selected.
  789. * @param resource $connection (optional) The database server connection, for detailed description see the method query().
  790. * @return bool Returns TRUE on success or FALSE on failure.
  791. */
  792. public static function select_db($database_name, $connection = null)
  793. {
  794. return self::use_default_connection($connection) ? mysql_select_db($database_name) : mysql_select_db(
  795. $database_name,
  796. $connection
  797. );
  798. }
  799. /**
  800. * Stores a query result into an array.
  801. *
  802. * @author Olivier Brouckaert
  803. * @param resource $result - the return value of the query
  804. * @param option BOTH, ASSOC, or NUM
  805. * @return array - the value returned by the query
  806. */
  807. public static function store_result($result, $option = 'BOTH')
  808. {
  809. $array = array();
  810. if ($result !== false) { // For isolation from database engine's behaviour.
  811. while ($row = self::fetch_array($result, $option)) {
  812. $array[] = $row;
  813. }
  814. }
  815. return $array;
  816. }
  817. /*
  818. Encodings and collations supported by MySQL database server
  819. */
  820. /**
  821. * Checks whether a given encoding is supported by the database server.
  822. * @param string $encoding The encoding (a system conventional id, for example 'UTF-8') to be checked.
  823. * @return bool Returns a boolean value as a check-result.
  824. * @author Ivan Tcholakov
  825. */
  826. public static function is_encoding_supported($encoding)
  827. {
  828. static $supported = array();
  829. if (!isset($supported[$encoding])) {
  830. $supported[$encoding] = false;
  831. if (strlen($db_encoding = self::to_db_encoding($encoding)) > 0) {
  832. if (self::num_rows(
  833. self::query("SHOW CHARACTER SET WHERE Charset = '".self::escape_string($db_encoding)."';")
  834. ) > 0
  835. ) {
  836. $supported[$encoding] = true;
  837. }
  838. }
  839. }
  840. return $supported[$encoding];
  841. }
  842. /**
  843. * Constructs a SQL clause about default character set and default collation for newly created databases and tables.
  844. * Example: Database::make_charset_clause('UTF-8', 'bulgarian') returns
  845. * DEFAULT CHARACTER SET `utf8` DEFAULT COLLATE `utf8_general_ci`
  846. * @param string $encoding (optional) The default database/table encoding (a system conventional id) to be used.
  847. * @param string $language (optional) Language (a system conventional id) used for choosing language sensitive collation (if it is possible).
  848. * @return string Returns the constructed SQL clause or empty string if $encoding is not correct or is not supported.
  849. * @author Ivan Tcholakov
  850. */
  851. public static function make_charset_clause($encoding = null, $language = null)
  852. {
  853. if (empty($encoding)) {
  854. $encoding = api_get_system_encoding();
  855. }
  856. if (empty($language)) {
  857. $language = api_get_interface_language();
  858. }
  859. $charset_clause = '';
  860. if (self::is_encoding_supported($encoding)) {
  861. $db_encoding = Database::to_db_encoding($encoding);
  862. $charset_clause .= " DEFAULT CHARACTER SET `".$db_encoding."`";
  863. $db_collation = Database::to_db_collation($encoding, $language);
  864. if (!empty($db_collation)) {
  865. $charset_clause .= " DEFAULT COLLATE `".$db_collation."`";
  866. }
  867. }
  868. return $charset_clause;
  869. }
  870. /**
  871. * Converts an encoding identificator to MySQL-specific encoding identifictor,
  872. * i.e. 'UTF-8' --> 'utf8'.
  873. * @param string $encoding The conventional encoding identificator.
  874. * @return string Returns the corresponding MySQL-specific encoding identificator if any, otherwise returns NULL.
  875. * @author Ivan Tcholakov
  876. */
  877. public static function to_db_encoding($encoding)
  878. {
  879. static $result = array();
  880. if (!isset($result[$encoding])) {
  881. $result[$encoding] = null;
  882. $encoding_map = & self::get_db_encoding_map();
  883. foreach ($encoding_map as $key => $value) {
  884. if (api_equal_encodings($encoding, $key)) {
  885. $result[$encoding] = $value;
  886. break;
  887. }
  888. }
  889. }
  890. return $result[$encoding];
  891. }
  892. /**
  893. * Converts a MySQL-specific encoding identifictor to conventional encoding identificator,
  894. * i.e. 'utf8' --> 'UTF-8'.
  895. * @param string $encoding The MySQL-specific encoding identificator.
  896. * @return string Returns the corresponding conventional encoding identificator if any, otherwise returns NULL.
  897. * @author Ivan Tcholakov
  898. */
  899. public static function from_db_encoding($db_encoding)
  900. {
  901. static $result = array();
  902. if (!isset($result[$db_encoding])) {
  903. $result[$db_encoding] = null;
  904. $encoding_map = & self::get_db_encoding_map();
  905. foreach ($encoding_map as $key => $value) {
  906. if (strtolower($db_encoding) == $value) {
  907. $result[$db_encoding] = $key;
  908. break;
  909. }
  910. }
  911. }
  912. return $result[$db_encoding];
  913. }
  914. /**
  915. * Chooses the default MySQL-specific collation from given encoding and language.
  916. * @param string $encoding A conventional encoding id, i.e. 'UTF-8'
  917. * @param string $language (optional) A conventional for the system language id, i.e. 'bulgarian'. If it is empty, the chosen collation is the default server value corresponding to the given encoding.
  918. * @return string Returns a suitable default collation, for example 'utf8_general_ci', or NULL if collation was not found.
  919. * @author Ivan Tcholakov
  920. */
  921. public static function to_db_collation($encoding, $language = null)
  922. {
  923. static $result = array();
  924. if (!isset($result[$encoding][$language])) {
  925. $result[$encoding][$language] = null;
  926. if (self::is_encoding_supported($encoding)) {
  927. $db_encoding = self::to_db_encoding($encoding);
  928. if (!empty($language)) {
  929. $lang = api_purify_language_id($language);
  930. $res = self::check_db_collation($db_encoding, $lang);
  931. if (empty($res)) {
  932. $db_collation_map = & self::get_db_collation_map();
  933. if (isset($db_collation_map[$lang])) {
  934. $res = self::check_db_collation($db_encoding, $db_collation_map[$lang]);
  935. }
  936. }
  937. if (empty($res)) {
  938. $res = self::check_db_collation($db_encoding, null);
  939. }
  940. $result[$encoding][$language] = $res;
  941. } else {
  942. $result[$encoding][$language] = self::check_db_collation($db_encoding, null);
  943. }
  944. }
  945. }
  946. return $result[$encoding][$language];
  947. }
  948. /*
  949. Private methods
  950. You should not access these from outside the class
  951. No effort is made to keep the names / results the same.
  952. */
  953. /**
  954. * Glues a course database.
  955. * glue format from local.inc.php.
  956. */
  957. private static function glue_course_database_name($database_name)
  958. {
  959. return self::get_course_table_prefix().$database_name.self::get_database_glue();
  960. }
  961. /**
  962. * @param string $database_name, can be empty to use current course db
  963. *
  964. * @return the glued parameter if it is not empty,
  965. * or the current course database (glued) if the parameter is empty.
  966. */
  967. private static function fix_database_parameter($database_name)
  968. {
  969. if (empty($database_name)) {
  970. $course_info = api_get_course_info();
  971. return $course_info['dbNameGlu'];
  972. }
  973. return self::glue_course_database_name($database_name);
  974. }
  975. /**
  976. * Structures a course database and table name to ready them
  977. * for querying. The course database parameter is considered glued:
  978. * e.g. COURSE001`.`
  979. */
  980. private static function format_glued_course_table_name($database_name_with_glue, $table)
  981. {
  982. return '`'.$database_name_with_glue.$table.'`';
  983. }
  984. /**
  985. * Structures a database and table name to ready them
  986. * for querying. The database parameter is considered not glued,
  987. * just plain e.g. COURSE001
  988. */
  989. private static function format_table_name($database, $table)
  990. {
  991. //global $_configuration;
  992. //$glue = isset($_configuration['db_glue']) ? $_configuration['db_glue'] : null;
  993. //$_configuration['db_glue'] should not be an option
  994. $glue = '`.`';
  995. $table_name = '`'.$database.$glue.$table.'`';
  996. return $table_name;
  997. }
  998. /**
  999. * This private method is to be used by the other methods in this class for
  1000. * checking whether the input parameter $connection actually has been provided.
  1001. * If the input parameter connection is not a resource or if it is not FALSE (in case of error)
  1002. * then the default opened connection should be used by the called method.
  1003. * @param resource/boolean $connection The checked parameter $connection.
  1004. * @return boolean TRUE means that calling method should use the default connection.
  1005. * FALSE means that (valid) parameter $connection has been provided and it should be used.
  1006. */
  1007. private static function use_default_connection($connection)
  1008. {
  1009. return !is_resource($connection) && $connection !== false;
  1010. }
  1011. /**
  1012. * This private method tackles the XSS injections. It is similar to Security::remove_XSS() and works always,
  1013. * including the time of initialization when the class Security has not been loaded yet.
  1014. * @param string The input variable to be filtered from XSS, in this class it is expected to be a string.
  1015. * @return string Returns the filtered string as a result.
  1016. */
  1017. private static function remove_XSS(& $var)
  1018. {
  1019. return class_exists('Security') ? Security::remove_XSS($var) : @htmlspecialchars(
  1020. $var,
  1021. ENT_QUOTES,
  1022. api_get_system_encoding()
  1023. );
  1024. }
  1025. /**
  1026. * This private method encapsulates a table with relations between
  1027. * conventional and MuSQL-specific encoding identificators.
  1028. * @author Ivan Tcholakov
  1029. */
  1030. private static function & get_db_encoding_map()
  1031. {
  1032. static $encoding_map = array(
  1033. 'ARMSCII-8' => 'armscii8',
  1034. 'BIG5' => 'big5',
  1035. 'BINARY' => 'binary',
  1036. 'CP866' => 'cp866',
  1037. 'EUC-JP' => 'ujis',
  1038. 'EUC-KR' => 'euckr',
  1039. 'GB2312' => 'gb2312',
  1040. 'GBK' => 'gbk',
  1041. 'ISO-8859-1' => 'latin1',
  1042. 'ISO-8859-2' => 'latin2',
  1043. 'ISO-8859-7' => 'greek',
  1044. 'ISO-8859-8' => 'hebrew',
  1045. 'ISO-8859-9' => 'latin5',
  1046. 'ISO-8859-13' => 'latin7',
  1047. 'ISO-8859-15' => 'latin1',
  1048. 'KOI8-R' => 'koi8r',
  1049. 'KOI8-U' => 'koi8u',
  1050. 'SHIFT-JIS' => 'sjis',
  1051. 'TIS-620' => 'tis620',
  1052. 'US-ASCII' => 'ascii',
  1053. 'UTF-8' => 'utf8',
  1054. 'WINDOWS-1250' => 'cp1250',
  1055. 'WINDOWS-1251' => 'cp1251',
  1056. 'WINDOWS-1252' => 'latin1',
  1057. 'WINDOWS-1256' => 'cp1256',
  1058. 'WINDOWS-1257' => 'cp1257'
  1059. );
  1060. return $encoding_map;
  1061. }
  1062. /**
  1063. * A helper language id translation table for choosing some collations.
  1064. * @author Ivan Tcholakov
  1065. */
  1066. private static function & get_db_collation_map()
  1067. {
  1068. static $db_collation_map = array(
  1069. 'german' => 'german2',
  1070. 'simpl_chinese' => 'chinese',
  1071. 'trad_chinese' => 'chinese',
  1072. 'turkce' => 'turkish'
  1073. );
  1074. return $db_collation_map;
  1075. }
  1076. /**
  1077. * Constructs a MySQL-specific collation and checks whether it is supported by the database server.
  1078. * @param string $db_encoding A MySQL-specific encoding id, i.e. 'utf8'
  1079. * @param string $language A MySQL-compatible language id, i.e. 'bulgarian'
  1080. * @return string Returns a suitable default collation, for example 'utf8_general_ci', or NULL if collation was not found.
  1081. * @author Ivan Tcholakov
  1082. */
  1083. private static function check_db_collation($db_encoding, $language)
  1084. {
  1085. if (empty($db_encoding)) {
  1086. return null;
  1087. }
  1088. if (empty($language)) {
  1089. $result = self::fetch_array(
  1090. self::query(
  1091. "SHOW COLLATION WHERE Charset = '".self::escape_string($db_encoding)."' AND `Default` = 'Yes';"
  1092. ),
  1093. 'NUM'
  1094. );
  1095. return $result ? $result[0] : null;
  1096. }
  1097. $collation = $db_encoding.'_'.$language.'_ci';
  1098. $query_result = self::query("SHOW COLLATION WHERE Charset = '".self::escape_string($db_encoding)."';");
  1099. while ($result = self::fetch_array($query_result, 'NUM')) {
  1100. if ($result[0] == $collation) {
  1101. return $collation;
  1102. }
  1103. }
  1104. return null;
  1105. }
  1106. /*
  1107. New useful DB functions
  1108. */
  1109. /**
  1110. * Experimental useful database insert
  1111. * @todo lot of stuff to do here
  1112. */
  1113. public static function insert($table_name, $attributes, $show_query = false)
  1114. {
  1115. if (empty($attributes) || empty($table_name)) {
  1116. return false;
  1117. }
  1118. $filtred_attributes = array();
  1119. foreach ($attributes as $key => $value) {
  1120. $filtred_attributes[$key] = "'".self::escape_string($value)."'";
  1121. }
  1122. $params = array_keys(
  1123. $filtred_attributes
  1124. ); //@todo check if the field exists in the table we should use a describe of that table
  1125. $values = array_values($filtred_attributes);
  1126. if (!empty($params) && !empty($values)) {
  1127. $sql = 'INSERT INTO '.$table_name.' ('.implode(', ', $params).') VALUES ('.implode(', ', $values).')';
  1128. $result = self::query($sql);
  1129. //error_log($sql);
  1130. if ($show_query) {
  1131. //var_dump($sql);
  1132. error_log($sql);
  1133. }
  1134. if (!$result) {
  1135. error_log("Error in query: $sql");
  1136. }
  1137. return self::get_last_insert_id();
  1138. }
  1139. return false;
  1140. }
  1141. /**
  1142. * Experimental useful database finder
  1143. * @todo lot of stuff to do here
  1144. * @todo known issues, it doesn't work when using LIKE conditions
  1145. * @example array('where'=> array('course_code LIKE "?%"'))
  1146. * @example array('where'=> array('type = ? AND category = ?' => array('setting', 'Plugins'))
  1147. * @example array('where'=> array('name = "Julio" AND lastname = "montoya"))
  1148. */
  1149. public static function select($columns, $table_name, $conditions = array(), $type_result = 'all', $option = 'ASSOC')
  1150. {
  1151. $conditions = self::parse_conditions($conditions);
  1152. //@todo we could do a describe here to check the columns ...
  1153. $clean_columns = '';
  1154. if (is_array($columns)) {
  1155. $clean_columns = implode(',', $columns);
  1156. } else {
  1157. if ($columns == '*') {
  1158. $clean_columns = '*';
  1159. } else {
  1160. $clean_columns = (string)$columns;
  1161. }
  1162. }
  1163. $sql = "SELECT $clean_columns FROM $table_name $conditions";
  1164. //var_dump($sql);
  1165. $result = self::query($sql);
  1166. $array = array();
  1167. if ($type_result == 'all') {
  1168. while ($row = self::fetch_array($result, $option)) {
  1169. if (isset($row['id'])) {
  1170. $array[$row['id']] = $row;
  1171. } else {
  1172. $array[] = $row;
  1173. }
  1174. }
  1175. } else {
  1176. $array = self::fetch_array($result, $option);
  1177. }
  1178. return $array;
  1179. }
  1180. /**
  1181. * Parses WHERE/ORDER conditions i.e array('where'=>array('id = ?' =>'4'), 'order'=>'id DESC'))
  1182. * @todo known issues, it doesn't work when using LIKE conditions example: array('where'=>array('course_code LIKE "?%"'))
  1183. * @param array
  1184. * @todo lot of stuff to do here
  1185. */
  1186. static function parse_conditions($conditions)
  1187. {
  1188. if (empty($conditions)) {
  1189. return '';
  1190. }
  1191. $return_value = $where_return = '';
  1192. foreach ($conditions as $type_condition => $condition_data) {
  1193. if ($condition_data == false) {
  1194. continue;
  1195. }
  1196. $type_condition = strtolower($type_condition);
  1197. switch ($type_condition) {
  1198. case 'where':
  1199. foreach ($condition_data as $condition => $value_array) {
  1200. if (is_array($value_array)) {
  1201. $clean_values = array();
  1202. foreach ($value_array as $item) {
  1203. $item = Database::escape_string($item);
  1204. $clean_values[] = $item;
  1205. }
  1206. } else {
  1207. $value_array = Database::escape_string($value_array);
  1208. $clean_values = $value_array;
  1209. }
  1210. if (!empty($condition) && $clean_values != '') {
  1211. $condition = str_replace('%', "'@percentage@'", $condition); //replace "%"
  1212. $condition = str_replace("'?'", "%s", $condition);
  1213. $condition = str_replace("?", "%s", $condition);
  1214. $condition = str_replace("@%s@", "@-@", $condition);
  1215. $condition = str_replace("%s", "'%s'", $condition);
  1216. $condition = str_replace("@-@", "@%s@", $condition);
  1217. //Treat conditons as string
  1218. $condition = vsprintf($condition, $clean_values);
  1219. $condition = str_replace('@percentage@', '%', $condition); //replace "%"
  1220. $where_return .= $condition;
  1221. }
  1222. }
  1223. if (!empty($where_return)) {
  1224. $return_value = " WHERE $where_return";
  1225. }
  1226. break;
  1227. case 'order':
  1228. $order_array = $condition_data;
  1229. if (!empty($order_array)) {
  1230. // 'order' => 'id desc, name desc'
  1231. $order_array = self::escape_string($order_array);
  1232. $new_order_array = explode(',', $order_array);
  1233. $temp_value = array();
  1234. foreach ($new_order_array as $element) {
  1235. $element = explode(' ', $element);
  1236. $element = array_filter($element);
  1237. $element = array_values($element);
  1238. if (!empty($element[1])) {
  1239. $element[1] = strtolower($element[1]);
  1240. $order = 'DESC';
  1241. if (in_array($element[1], array('desc', 'asc'))) {
  1242. $order = $element[1];
  1243. }
  1244. $temp_value[] = $element[0].' '.$order.' ';
  1245. } else {
  1246. //by default DESC
  1247. $temp_value[] = $element[0].' DESC ';
  1248. }
  1249. }
  1250. if (!empty($temp_value)) {
  1251. $return_value .= ' ORDER BY '.implode(', ', $temp_value);
  1252. } else {
  1253. //$return_value .= '';
  1254. }
  1255. }
  1256. break;
  1257. case 'limit':
  1258. $limit_array = explode(',', $condition_data);
  1259. if (!empty($limit_array)) {
  1260. if (count($limit_array) > 1) {
  1261. $return_value .= ' LIMIT '.intval($limit_array[0]).' , '.intval($limit_array[1]);
  1262. } else {
  1263. $return_value .= ' LIMIT '.intval($limit_array[0]);
  1264. }
  1265. }
  1266. break;
  1267. }
  1268. }
  1269. return $return_value;
  1270. }
  1271. public static function parse_where_conditions($coditions)
  1272. {
  1273. return self::parse_conditions(array('where' => $coditions));
  1274. }
  1275. /**
  1276. * Experimental useful database update
  1277. * @todo lot of stuff to do here
  1278. */
  1279. public static function delete($table_name, $where_conditions, $show_query = false)
  1280. {
  1281. $result = false;
  1282. $where_return = self::parse_where_conditions($where_conditions);
  1283. $sql = "DELETE FROM $table_name $where_return ";
  1284. if ($show_query) {
  1285. echo $sql;
  1286. echo '<br />';
  1287. }
  1288. $result = self::query($sql);
  1289. $affected_rows = self::affected_rows();
  1290. //@todo should return affected_rows for
  1291. return $affected_rows;
  1292. }
  1293. /**
  1294. * Experimental useful database update
  1295. * @param string table name use Database::get_main_table
  1296. * @param array array with values to updates, keys are the fields in the database: Example: $params['name'] = 'Julio'; $params['lastname'] = 'Montoya';
  1297. * @param array where conditions i.e array('id = ?' =>'4')
  1298. * @todo lot of stuff to do here
  1299. */
  1300. public static function update($table_name, $attributes, $where_conditions = array(), $show_query = false)
  1301. {
  1302. if (!empty($table_name) && !empty($attributes)) {
  1303. $update_sql = '';
  1304. //Cleaning attributes
  1305. $count = 1;
  1306. foreach ($attributes as $key => $value) {
  1307. if (!is_array($value)) {
  1308. $value = self::escape_string($value);
  1309. }
  1310. $update_sql .= "$key = '$value' ";
  1311. if ($count < count($attributes)) {
  1312. $update_sql .= ', ';
  1313. }
  1314. $count++;
  1315. }
  1316. if (!empty($update_sql)) {
  1317. //Parsing and cleaning the where conditions
  1318. $where_return = self::parse_where_conditions($where_conditions);
  1319. $sql = "UPDATE $table_name SET $update_sql $where_return ";
  1320. if ($show_query) {
  1321. var_dump($sql);
  1322. }
  1323. $result = self::query($sql);
  1324. $affected_rows = self::affected_rows();
  1325. return $affected_rows;
  1326. }
  1327. }
  1328. return false;
  1329. }
  1330. /*
  1331. DEPRECATED METHODS
  1332. */
  1333. /**
  1334. * @deprecated Use api_get_language_isocode($language) instead.
  1335. */
  1336. public static function get_language_isocode($language)
  1337. {
  1338. return api_get_language_isocode($language);
  1339. }
  1340. /**
  1341. * @deprecated Use Database::insert_id() instead.
  1342. */
  1343. public static function get_last_insert_id()
  1344. {
  1345. return mysql_insert_id();
  1346. }
  1347. }