database.lib.php 61 KB

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