database.lib.php 60 KB

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