database.lib.php 61 KB

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