database.lib.php 60 KB

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