database.lib.php 61 KB

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