database.mysqli.lib.php 54 KB

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