database.mysqli.lib.php 54 KB

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