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