database.mysqli.lib.php 54 KB

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