database.lib.php 52 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307
  1. <?php // $Id: database.lib.php 22265 2009-07-20 23:26:43Z juliomontoya $
  2. /* For licensing terms, see /license.txt */
  3. /**
  4. * This is the main database library for Chamilo.
  5. * Include/require it in your code to use its functionality.
  6. * Because this library contains all the basic database calls, it could be
  7. * replaced by another library for say, PostgreSQL, to actually use Chamilo
  8. * with another database (this is not ready yet because a lot of code still
  9. * uses the MySQL database functions extensively).
  10. *
  11. * @package chamilo.library
  12. * @todo the table constants have all to start with TABLE_
  13. * This is because of the analogy with the tool constants TOOL_
  14. */
  15. /* CONSTANTS */
  16. // Main database tables
  17. define('TABLE_MAIN_COURSE', 'course');
  18. define('TABLE_MAIN_USER', 'user');
  19. define('TABLE_MAIN_CLASS', 'class');
  20. define('TABLE_MAIN_ADMIN', 'admin');
  21. define('TABLE_MAIN_COURSE_CLASS', 'course_rel_class');
  22. define('TABLE_MAIN_COURSE_USER', 'course_rel_user');
  23. define('TABLE_MAIN_CLASS_USER', 'class_user');
  24. define('TABLE_MAIN_CATEGORY', 'course_category');
  25. define('TABLE_MAIN_COURSE_MODULE', 'course_module');
  26. define('TABLE_MAIN_SYSTEM_ANNOUNCEMENTS', 'sys_announcement');
  27. define('TABLE_MAIN_LANGUAGE', 'language');
  28. define('TABLE_MAIN_SETTINGS_OPTIONS', 'settings_options');
  29. define('TABLE_MAIN_SETTINGS_CURRENT', 'settings_current');
  30. define('TABLE_MAIN_SESSION', 'session');
  31. define('TABLE_MAIN_SESSION_CATEGORY', 'session_category');
  32. define('TABLE_MAIN_SESSION_COURSE', 'session_rel_course');
  33. define('TABLE_MAIN_SESSION_USER', 'session_rel_user');
  34. define('TABLE_MAIN_SESSION_CLASS', 'session_rel_class');
  35. define('TABLE_MAIN_SESSION_COURSE_USER', 'session_rel_course_rel_user');
  36. define('TABLE_MAIN_SHARED_SURVEY', 'shared_survey');
  37. define('TABLE_MAIN_SHARED_SURVEY_QUESTION', 'shared_survey_question');
  38. define('TABLE_MAIN_SHARED_SURVEY_QUESTION_OPTION', 'shared_survey_question_option');
  39. define('TABLE_MAIN_TEMPLATES', 'templates');
  40. define('TABLE_MAIN_SYSTEM_TEMPLATE', 'system_template');
  41. define('TABLE_MAIN_OPENID_ASSOCIATION', 'openid_association');
  42. // Gradebook
  43. define('TABLE_MAIN_GRADEBOOK_CATEGORY', 'gradebook_category');
  44. define('TABLE_MAIN_GRADEBOOK_EVALUATION', 'gradebook_evaluation');
  45. define('TABLE_MAIN_GRADEBOOK_LINKEVAL_LOG', 'gradebook_linkeval_log');
  46. define('TABLE_MAIN_GRADEBOOK_RESULT', 'gradebook_result');
  47. define('TABLE_MAIN_GRADEBOOK_RESULT_LOG', 'gradebook_result_log');
  48. define('TABLE_MAIN_GRADEBOOK_LINK', 'gradebook_link');
  49. define('TABLE_MAIN_GRADEBOOK_SCORE_DISPLAY','gradebook_score_display');
  50. define('TABLE_MAIN_GRADEBOOK_CERTIFICATE', 'gradebook_certificate');
  51. //Profiling
  52. define('TABLE_MAIN_USER_FIELD', 'user_field');
  53. define('TABLE_MAIN_USER_FIELD_OPTIONS', 'user_field_options');
  54. define('TABLE_MAIN_USER_FIELD_VALUES', 'user_field_values');
  55. //User tags
  56. define('TABLE_MAIN_TAG', 'tag');
  57. define('TABLE_MAIN_USER_REL_TAG', 'user_rel_tag');
  58. //User groups
  59. define('TABLE_MAIN_GROUP', 'groups');
  60. define('TABLE_MAIN_USER_REL_GROUP', 'group_rel_user');
  61. define('TABLE_MAIN_GROUP_REL_TAG', 'group_rel_tag');
  62. // Search engine
  63. define('TABLE_MAIN_SPECIFIC_FIELD', 'specific_field');
  64. define('TABLE_MAIN_SPECIFIC_FIELD_VALUES', 'specific_field_values');
  65. define('TABLE_MAIN_SEARCH_ENGINE_REF', 'search_engine_ref');
  66. // Access URLs
  67. define('TABLE_MAIN_ACCESS_URL', 'access_url');
  68. define('TABLE_MAIN_ACCESS_URL_REL_USER', 'access_url_rel_user');
  69. define('TABLE_MAIN_ACCESS_URL_REL_COURSE', 'access_url_rel_course');
  70. define('TABLE_MAIN_ACCESS_URL_REL_SESSION', 'access_url_rel_session');
  71. // Global calendar
  72. define('TABLE_MAIN_SYSTEM_CALENDAR', 'sys_calendar');
  73. // Reservation System
  74. define('TABLE_MAIN_RESERVATION_ITEM', 'reservation_item');
  75. define('TABLE_MAIN_RESERVATION_RESERVATION', 'reservation_main');
  76. define('TABLE_MAIN_RESERVATION_SUBSCRIBTION', 'reservation_subscription');
  77. define('TABLE_MAIN_RESERVATION_CATEGORY', 'reservation_category');
  78. define('TABLE_MAIN_RESERVATION_ITEM_RIGHTS', 'reservation_item_rights');
  79. // Social networking
  80. define('TABLE_MAIN_USER_REL_USER', 'user_rel_user');
  81. define('TABLE_MAIN_USER_FRIEND_RELATION_TYPE', 'user_friend_relation_type');
  82. // Web services
  83. define('TABLE_MAIN_USER_API_KEY', 'user_api_key');
  84. define('TABLE_MAIN_COURSE_FIELD', 'course_field');
  85. define('TABLE_MAIN_COURSE_FIELD_VALUES', 'course_field_values');
  86. define('TABLE_MAIN_SESSION_FIELD', 'session_field');
  87. define('TABLE_MAIN_SESSION_FIELD_VALUES', 'session_field_values');
  88. // Message
  89. define('TABLE_MAIN_MESSAGE', 'message');
  90. // Term and conditions
  91. define('TABLE_MAIN_LEGAL', 'legal');
  92. // Dashboard blocks plugin
  93. define('TABLE_MAIN_BLOCK', 'block');
  94. // Statistic database tables
  95. define('TABLE_STATISTIC_TRACK_E_LASTACCESS', 'track_e_lastaccess');
  96. define('TABLE_STATISTIC_TRACK_E_ACCESS', 'track_e_access');
  97. define('TABLE_STATISTIC_TRACK_E_LOGIN', 'track_e_login');
  98. define('TABLE_STATISTIC_TRACK_E_DOWNLOADS', 'track_e_downloads');
  99. define('TABLE_STATISTIC_TRACK_E_LINKS', 'track_e_links');
  100. define('TABLE_STATISTIC_TRACK_E_ONLINE', 'track_e_online');
  101. define('TABLE_STATISTIC_TRACK_E_HOTPOTATOES', 'track_e_hotpotatoes');
  102. define('TABLE_STATISTIC_TRACK_E_COURSE_ACCESS', 'track_e_course_access');
  103. define('TABLE_STATISTIC_TRACK_E_EXERCICES', 'track_e_exercices');
  104. define('TABLE_STATISTIC_TRACK_E_ATTEMPT', 'track_e_attempt');
  105. define('TABLE_STATISTIC_TRACK_E_ATTEMPT_RECORDING', 'track_e_attempt_recording');
  106. define('TABLE_STATISTIC_TRACK_E_DEFAULT', 'track_e_default');
  107. define('TABLE_STATISTIC_TRACK_E_UPLOADS', 'track_e_uploads');
  108. define('TABLE_STATISTIC_TRACK_E_HOTSPOT', 'track_e_hotspot');
  109. define('TABLE_STATISTIC_TRACK_E_ITEM_PROPERTY', 'track_e_item_property');
  110. // SCORM database tables
  111. define('TABLE_SCORM_MAIN', 'scorm_main');
  112. define('TABLE_SCORM_SCO_DATA', 'scorm_sco_data');
  113. // Course tables
  114. define('TABLE_AGENDA', 'calendar_event');
  115. define('TABLE_AGENDA_REPEAT', 'calendar_event_repeat');
  116. define('TABLE_AGENDA_REPEAT_NOT', 'calendar_event_repeat_not');
  117. define('TABLE_AGENDA_ATTACHMENT', 'calendar_event_attachment');
  118. define('TABLE_ANNOUNCEMENT', 'announcement');
  119. define('TABLE_ANNOUNCEMENT_ATTACHMENT', 'announcement_attachment');
  120. define('TABLE_CHAT_CONNECTED', 'chat_connected'); // @todo: probably no longer in use !!!
  121. define('TABLE_COURSE_DESCRIPTION', 'course_description');
  122. define('TABLE_DOCUMENT', 'document');
  123. define('TABLE_ITEM_PROPERTY', 'item_property');
  124. define('TABLE_LINK', 'link');
  125. define('TABLE_LINK_CATEGORY', 'link_category');
  126. define('TABLE_TOOL_LIST', 'tool');
  127. define('TABLE_TOOL_INTRO', 'tool_intro');
  128. define('TABLE_SCORMDOC', 'scormdocument');
  129. define('TABLE_STUDENT_PUBLICATION', 'student_publication');
  130. define('TABLE_STUDENT_PUBLICATION_ASSIGNMENT', 'student_publication_assignment');
  131. define('CHAT_CONNECTED_TABLE', 'chat_connected');
  132. // Course forum tables
  133. define('TABLE_FORUM_CATEGORY', 'forum_category');
  134. define('TABLE_FORUM', 'forum_forum');
  135. define('TABLE_FORUM_THREAD', 'forum_thread');
  136. define('TABLE_FORUM_POST', 'forum_post');
  137. define('TABLE_FORUM_ATTACHMENT', 'forum_attachment');
  138. define('TABLE_FORUM_MAIL_QUEUE', 'forum_mailcue');
  139. define('TABLE_FORUM_THREAD_QUALIFY', 'forum_thread_qualify');
  140. define('TABLE_FORUM_THREAD_QUALIFY_LOG', 'forum_thread_qualify_log');
  141. define('TABLE_FORUM_NOTIFICATION', 'forum_notification');
  142. // Course group tables
  143. define('TABLE_GROUP', 'group_info');
  144. define('TABLE_GROUP_USER', 'group_rel_user');
  145. define('TABLE_GROUP_TUTOR', 'group_rel_tutor');
  146. define('TABLE_GROUP_CATEGORY', 'group_category');
  147. // Course dropbox tables
  148. define('TABLE_DROPBOX_CATEGORY','dropbox_category');
  149. define('TABLE_DROPBOX_FEEDBACK','dropbox_feedback');
  150. define('TABLE_DROPBOX_POST', 'dropbox_post');
  151. define('TABLE_DROPBOX_FILE', 'dropbox_file');
  152. define('TABLE_DROPBOX_PERSON', 'dropbox_person');
  153. // Course quiz (or test, or exercice) tables
  154. define('TABLE_QUIZ_QUESTION', 'quiz_question');
  155. define('TABLE_QUIZ_TEST', 'quiz');
  156. define('TABLE_QUIZ_ANSWER', 'quiz_answer');
  157. define('TABLE_QUIZ_TEST_QUESTION', 'quiz_rel_question');
  158. // Linked resource table
  159. define('TABLE_LINKED_RESOURCES', 'resource');
  160. // New SCORM tables
  161. define('TABLE_LP_MAIN', 'lp');
  162. define('TABLE_LP_ITEM', 'lp_item');
  163. define('TABLE_LP_VIEW', 'lp_view');
  164. define('TABLE_LP_ITEM_VIEW', 'lp_item_view');
  165. define('TABLE_LP_IV_INTERACTION', 'lp_iv_interaction'); // IV = Item View
  166. define('TABLE_LP_IV_OBJECTIVE', 'lp_iv_objective'); // IV = Item View
  167. // Smartblogs (Kevin Van Den Haute::kevin@develop-it.be)
  168. // Permission tables
  169. define('TABLE_PERMISSION_USER', 'permission_user');
  170. define('TABLE_PERMISSION_TASK', 'permission_task');
  171. define('TABLE_PERMISSION_GROUP', 'permission_group');
  172. // Role tables
  173. define('TABLE_ROLE', 'role');
  174. define('TABLE_ROLE_PERMISSION', 'role_permissions');
  175. define('TABLE_ROLE_USER', 'role_user');
  176. define('TABLE_ROLE_GROUP', 'role_group');
  177. // Blog tables
  178. define('TABLE_BLOGS', 'blog');
  179. define('TABLE_BLOGS_POSTS', 'blog_post');
  180. define('TABLE_BLOGS_COMMENTS', 'blog_comment');
  181. define('TABLE_BLOGS_REL_USER', 'blog_rel_user');
  182. define('TABLE_BLOGS_TASKS', 'blog_task');
  183. define('TABLE_BLOGS_TASKS_REL_USER', 'blog_task_rel_user');
  184. define('TABLE_BLOGS_RATING', 'blog_rating');
  185. define('TABLE_BLOGS_ATTACHMENT', 'blog_attachment');
  186. define('TABLE_BLOGS_TASKS_PERMISSIONS', 'permission_task');
  187. //end of Smartblogs
  188. // User information tables
  189. define('TABLE_USER_INFO', 'userinfo_def');
  190. define('TABLE_USER_INFO_CONTENT', 'userinfo_content');
  191. // Course settings table
  192. define('TABLE_COURSE_SETTING', 'course_setting');
  193. // Course online tables
  194. define('TABLE_ONLINE_LINK', 'online_link');
  195. define('TABLE_ONLINE_CONNECTED','online_connected');
  196. // User database
  197. define('TABLE_PERSONAL_AGENDA', 'personal_agenda');
  198. define('TABLE_PERSONAL_AGENDA_REPEAT', 'personal_agenda_repeat');
  199. define('TABLE_PERSONAL_AGENDA_REPEAT_NOT', 'personal_agenda_repeat_not');
  200. define('TABLE_USER_COURSE_CATEGORY', 'user_course_category');
  201. // Survey
  202. // @TODO: Are these MAIN tables or course tables?
  203. // @TODO: Probably these constants are obsolete.
  204. define('TABLE_MAIN_SURVEY', 'survey');
  205. define('TABLE_MAIN_SURVEYQUESTION', 'questions');
  206. // Survey
  207. define('TABLE_SURVEY', 'survey');
  208. define('TABLE_SURVEY_QUESTION', 'survey_question');
  209. define('TABLE_SURVEY_QUESTION_OPTION', 'survey_question_option');
  210. define('TABLE_SURVEY_INVITATION', 'survey_invitation');
  211. define('TABLE_SURVEY_ANSWER', 'survey_answer');
  212. define('TABLE_SURVEY_QUESTION_GROUP', 'survey_group');
  213. define('TABLE_SURVEY_REPORT', 'survey_report');
  214. // Wiki tables
  215. define('TABLE_WIKI', 'wiki');
  216. define('TABLE_WIKI_CONF', 'wiki_conf');
  217. define('TABLE_WIKI_DISCUSS', 'wiki_discuss');
  218. define('TABLE_WIKI_MAILCUE', 'wiki_mailcue');
  219. // Glossary
  220. define('TABLE_GLOSSARY', 'glossary');
  221. // Notebook
  222. define('TABLE_NOTEBOOK', 'notebook');
  223. // Message
  224. define('TABLE_MESSAGE', 'message');
  225. define('TABLE_MESSAGE_ATTACHMENT', 'message_attachment');
  226. // Metadata
  227. define('TABLE_METADATA', 'metadata');
  228. // Attendance Sheet
  229. define('TABLE_ATTENDANCE', 'attendance');
  230. define('TABLE_ATTENDANCE_CALENDAR', 'attendance_calendar');
  231. define('TABLE_ATTENDANCE_SHEET', 'attendance_sheet');
  232. define('TABLE_ATTENDANCE_RESULT', 'attendance_result');
  233. // Thematic
  234. define('TABLE_THEMATIC','thematic');
  235. define('TABLE_THEMATIC_PLAN', 'thematic_plan');
  236. define('TABLE_THEMATIC_ADVANCE','thematic_advance');
  237. /* DATABASE CLASS
  238. The class and its methods
  239. */
  240. class Database {
  241. /*
  242. Accessor methods
  243. Usually, you won't need these directly but instead
  244. rely on of the get_xxx_table methods.
  245. */
  246. /**
  247. * Returns the name of the main database.
  248. */
  249. public static function get_main_database() {
  250. global $_configuration;
  251. return $_configuration['main_database'];
  252. }
  253. /**
  254. * Returns the name of the statistics database.
  255. */
  256. public static function get_statistic_database() {
  257. global $_configuration;
  258. return $_configuration['statistics_database'];
  259. }
  260. /**
  261. * Returns the name of the SCORM database.
  262. * @deprecated
  263. */
  264. public static function get_scorm_database() {
  265. global $_configuration;
  266. return $_configuration['scorm_database'];
  267. }
  268. /**
  269. * Returns the name of the database where all the personal stuff of the user is stored
  270. */
  271. public static function get_user_personal_database() {
  272. global $_configuration;
  273. return $_configuration['user_personal_database'];
  274. }
  275. /**
  276. * Returns the name of the main database.
  277. */
  278. public static function get_current_course_database() {
  279. $course_info = api_get_course_info();
  280. return $course_info['dbName'];
  281. }
  282. /**
  283. * Returns the glued name of the current course database.
  284. */
  285. public static function get_current_course_glued_database() {
  286. $course_info = api_get_course_info();
  287. return $course_info['dbNameGlu'];
  288. }
  289. /**
  290. * The glue is the string needed between database and table.
  291. * The trick is: in multiple databases, this is a period (with backticks).
  292. * In single database, this can be e.g. an underscore so we just fake
  293. * there are multiple databases and the code can be written independent
  294. * of the single / multiple database setting.
  295. */
  296. public static function get_database_glue() {
  297. global $_configuration;
  298. return $_configuration['db_glue'];
  299. }
  300. /**
  301. * Returns the database prefix.
  302. * All created COURSE databases are prefixed with this string.
  303. *
  304. * TIP: This can be convenient e.g. if you have multiple system installations
  305. * on the same physical server.
  306. */
  307. public static function get_database_name_prefix() {
  308. global $_configuration;
  309. return $_configuration['db_prefix'];
  310. }
  311. /**
  312. * Returns the course table prefix for single database.
  313. * Not certain exactly when this is used.
  314. * Do research.
  315. * It's used in local.inc.php.
  316. */
  317. public static function get_course_table_prefix() {
  318. global $_configuration;
  319. return $_configuration['table_prefix'];
  320. }
  321. /*
  322. Table name methods
  323. Use these methods to get table names for queries,
  324. instead of constructing them yourself.
  325. Backticks automatically surround the result,
  326. e.g. `COURSE_NAME`.`link`
  327. so the queries can look cleaner.
  328. Example:
  329. $table = Database::get_course_table(TABLE_DOCUMENT);
  330. $sql_query = "SELECT * FROM $table WHERE $condition";
  331. $sql_result = Database::query($sql_query);
  332. $result = Database::fetch_array($sql_result);
  333. */
  334. /**
  335. * A more generic method than the other get_main_xxx_table methods,
  336. * This one returns the correct complete name of any table of the main database of which you pass
  337. * the short name as a parameter.
  338. * Please, define table names as constants in this library and use them
  339. * instead of directly using magic words in your tool code.
  340. *
  341. * @param string $short_table_name, the name of the table
  342. */
  343. public static function get_main_table($short_table_name) {
  344. return self::format_table_name(self::get_main_database(), $short_table_name);
  345. }
  346. /**
  347. * A more generic method than the older get_course_xxx_table methods,
  348. * This one can return the correct complete name of any course table of which you pass
  349. * the short name as a parameter.
  350. * Please, define table names as constants in this library and use them
  351. * instead of directly using magic words in your tool code.
  352. *
  353. * @param string $short_table_name, the name of the table
  354. * @param string $database_name, optional, name of the course database
  355. * - if you don't specify this, you work on the current course.
  356. */
  357. public static function get_course_table($short_table_name, $database_name = '') {
  358. return self::format_glued_course_table_name(self::fix_database_parameter($database_name), $short_table_name);
  359. }
  360. /**
  361. * Gets a complete course table name from a course code
  362. *
  363. * @param string $course_code
  364. * @param string $table the name of the table
  365. */
  366. public static function get_course_table_from_code($course_code, $table) {
  367. $course_table = self::get_main_table(TABLE_MAIN_COURSE);
  368. $course_cat_table = self::get_main_table(TABLE_MAIN_CATEGORY);
  369. $result = self::fetch_array(self::query(
  370. "SELECT $course_table.db_name, $course_cat_table.code
  371. FROM $course_table
  372. LEFT JOIN $course_cat_table
  373. ON $course_table.category_code = $course_cat_table.code
  374. WHERE $course_table.code = '$course_code'
  375. LIMIT 1"));
  376. return sprintf("%s.%s", $result[0], $table);
  377. }
  378. /**
  379. * This generic method returns the correct and complete name of any statistic table
  380. * of which you pass the short name as a parameter.
  381. * Please, define table names as constants in this library and use them
  382. * instead of directly using magic words in your tool code.
  383. *
  384. * @param string $short_table_name, the name of the table
  385. */
  386. public static function get_statistic_table($short_table_name) {
  387. return self::format_table_name(self::get_statistic_database(), $short_table_name);
  388. }
  389. /**
  390. * This generic method returns the correct and complete name of any scorm
  391. * table of which you pass the short name as a parameter. Please, define
  392. * table names as constants in this library and use them instead of directly
  393. * using magic words in your tool code.
  394. *
  395. * @param string $short_table_name, the name of the table
  396. */
  397. public static function get_scorm_table($short_table_name) {
  398. return self::format_table_name(self::get_scorm_database(), $short_table_name);
  399. }
  400. /**
  401. * This generic method returns the correct and complete name of any scorm
  402. * table of which you pass the short name as a parameter. Please, define
  403. * table names as constants in this library and use them instead of directly
  404. * using magic words in your tool code.
  405. *
  406. * @param string $short_table_name, the name of the table
  407. */
  408. public static function get_user_personal_table($short_table_name) {
  409. return self::format_table_name(self::get_user_personal_database(), $short_table_name);
  410. }
  411. public static function get_course_chat_connected_table($database_name = '') {
  412. return self::format_glued_course_table_name(self::fix_database_parameter($database_name), CHAT_CONNECTED_TABLE);
  413. }
  414. /*
  415. Query methods
  416. These methods execute a query and return the result(s).
  417. */
  418. /**
  419. * @return a list (array) of all courses.
  420. * @todo shouldn't this be in the course.lib.php script?
  421. */
  422. public static function get_course_list() {
  423. $table = self::get_main_table(TABLE_MAIN_COURSE);
  424. return self::store_result(self::query("SELECT * FROM $table"));
  425. }
  426. /**
  427. * Returns an array with all database fields for the specified course.
  428. *
  429. * @param the real (system) code of the course (ID from inside the main course table)
  430. * @todo shouldn't this be in the course.lib.php script?
  431. */
  432. public static function get_course_info($course_code) {
  433. $course_code = self::escape_string($course_code);
  434. $table = self::get_main_table(TABLE_MAIN_COURSE);
  435. $result = self::generate_abstract_course_field_names(
  436. self::fetch_array(self::query("SELECT * FROM $table WHERE `code` = '$course_code'")));
  437. return $result === false ? array('db_name' => '') : $result;
  438. }
  439. /**
  440. * @param $user_id (integer): the id of the user
  441. * @return $user_info (array): user_id, lastname, firstname, username, email, ...
  442. * @author Patrick Cool <patrick.cool@UGent.be>, expanded to get info for any user
  443. * @author Roan Embrechts, first version + converted to Database API
  444. * @version 30 September 2004
  445. * @desc find all the information about a specified user. Without parameter this is the current user.
  446. * @todo shouldn't this be in the user.lib.php script?
  447. */
  448. public static function get_user_info_from_id($user_id = '') {
  449. if (empty($user_id)) {
  450. return $GLOBALS['_user'];
  451. }
  452. $table = self::get_main_table(TABLE_MAIN_USER);
  453. $user_id = self::escape_string($user_id);
  454. return self::generate_abstract_user_field_names(
  455. self::fetch_array(self::query("SELECT * FROM $table WHERE user_id = '$user_id'")));
  456. }
  457. /**
  458. * Returns course code from a given gradebook category's id
  459. * @param int Category ID
  460. * @return string Course code
  461. * @todo move this function in a gradebook-related library
  462. */
  463. public static function get_course_by_category($category_id) {
  464. $info = self::fetch_array(self::query('SELECT course_code FROM '.self::get_main_table(TABLE_MAIN_GRADEBOOK_CATEGORY).' WHERE id='.$category_id), 'ASSOC');
  465. return $info ? $info['course_code'] : false;
  466. }
  467. /**
  468. * This method creates an abstraction layer between database field names
  469. * and field names expected in code.
  470. *
  471. * This approach helps when changing database names.
  472. * It's also useful now to get rid of the 'franglais'.
  473. *
  474. * @todo add more array entries to abstract course info from field names
  475. * @author Roan Embrechts
  476. *
  477. * @todo What's the use of this method. I think this is better removed.
  478. * There should be consistency in the variable names and the use throughout the scripts
  479. * for the database name we should consistently use or db_name or database (db_name probably being the better one)
  480. */
  481. public static function generate_abstract_course_field_names($result_array) {
  482. $visual_code = isset($result_array['visual_code']) ? $result_array['visual_code'] : null;
  483. $code = isset($result_array['code']) ? $result_array['code'] : null;
  484. $title = isset($result_array['title']) ? $result_array['title'] : null;
  485. $db_name = isset($result_array['db_name']) ? $result_array['db_name'] : null;
  486. $category_code = isset($result_array['category_code']) ? $result_array['category_code'] : null;
  487. $result_array['official_code'] = $visual_code;
  488. $result_array['visual_code'] = $visual_code;
  489. $result_array['real_code'] = $code;
  490. $result_array['system_code'] = $code;
  491. $result_array['title'] = $title;
  492. $result_array['database'] = $db_name;
  493. $result_array['faculty'] = $category_code;
  494. //$result_array['directory'] = $result_array['directory'];
  495. /*
  496. still to do: (info taken from local.inc.php)
  497. $_course['id' ] = $cData['cours_id' ]; //auto-assigned integer
  498. $_course['name' ] = $cData['title' ];
  499. $_course['official_code'] = $cData['visual_code' ]; // use in echo
  500. $_course['sysCode' ] = $cData['code' ]; // use as key in db
  501. $_course['path' ] = $cData['directory' ]; // use as key in path
  502. $_course['dbName' ] = $cData['db_name' ]; // use as key in db list
  503. $_course['dbNameGlu' ] = $_configuration['table_prefix'] . $cData['dbName'] . $_configuration['db_glue']; // use in all queries
  504. $_course['titular' ] = $cData['tutor_name' ];
  505. $_course['language' ] = $cData['course_language' ];
  506. $_course['extLink' ]['url' ] = $cData['department_url' ];
  507. $_course['extLink' ]['name'] = $cData['department_name'];
  508. $_course['categoryCode'] = $cData['faCode' ];
  509. $_course['categoryName'] = $cData['faName' ];
  510. $_course['visibility' ] = (bool) ($cData['visibility'] == 2 || $cData['visibility'] == 3);
  511. $_course['registrationAllowed'] = (bool) ($cData['visibility'] == 1 || $cData['visibility'] == 2);
  512. */
  513. return $result_array;
  514. }
  515. /**
  516. * This method creates an abstraction layer between database field names
  517. * and field names expected in code.
  518. *
  519. * This helps when changing database names.
  520. * It's also useful now to get rid of the 'franglais'.
  521. *
  522. * @todo add more array entries to abstract user info from field names
  523. * @author Roan Embrechts
  524. * @author Patrick Cool
  525. *
  526. * @todo what's the use of this function. I think this is better removed.
  527. * There should be consistency in the variable names and the use throughout the scripts
  528. */
  529. public static function generate_abstract_user_field_names($result_array) {
  530. $result_array['firstName'] = $result_array['firstname'];
  531. $result_array['lastName'] = $result_array['lastname'];
  532. $result_array['mail'] = $result_array['email'];
  533. #$result_array['picture_uri'] = $result_array['picture_uri'];
  534. #$result_array ['user_id'] = $result_array['user_id'];
  535. return $result_array;
  536. }
  537. /**
  538. * Counts the number of rows in a table
  539. * @param string $table The table of which the rows should be counted
  540. * @return int The number of rows in the given table.
  541. */
  542. public static function count_rows($table) {
  543. $obj = self::fetch_object(self::query("SELECT COUNT(*) AS n FROM $table"));
  544. return $obj->n;
  545. }
  546. /*
  547. An intermediate API-layer between the system and the dabase server.
  548. */
  549. /**
  550. * Returns the number of affected rows in the last database operation.
  551. * @param resource $connection (optional) The database server connection, for detailed description see the method query().
  552. * @return int Returns the number of affected rows on success, and -1 if the last query failed.
  553. */
  554. public static function affected_rows($connection = null) {
  555. return self::use_default_connection($connection) ? mysql_affected_rows() : mysql_affected_rows($connection);
  556. }
  557. /**
  558. * Closes non-persistent database connection.
  559. * @param resource $connection (optional) The database server connection, for detailed description see the method query().
  560. * @return bool Returns TRUE on success or FALSE on failure.
  561. */
  562. public static function close($connection = null) {
  563. return self::use_default_connection($connection) ? mysql_close() : mysql_close($connection);
  564. }
  565. /**
  566. * Opens a connection to a database server.
  567. * @param array $parameters (optional) An array that contains the necessary parameters for accessing the server.
  568. * @return resource/boolean Returns a database connection on success or FALSE on failure.
  569. * Note: Currently the array could contain MySQL-specific parameters:
  570. * $parameters['server'], $parameters['username'], $parameters['password'],
  571. * $parameters['new_link'], $parameters['client_flags'], $parameters['persistent'].
  572. * For details see documentation about the functions mysql_connect() and mysql_pconnect().
  573. * @link http://php.net/manual/en/function.mysql-connect.php
  574. * @link http://php.net/manual/en/function.mysql-pconnect.php
  575. */
  576. public static function connect($parameters = array()) {
  577. // A MySQL-specific implementation.
  578. if (!isset($parameters['server'])) {
  579. $parameters['server'] = @ini_get('mysql.default_host');
  580. if (empty($parameters['server'])) {
  581. $parameters['server'] = 'localhost:3306';
  582. }
  583. }
  584. if (!isset($parameters['username'])) {
  585. $parameters['username'] = @ini_get('mysql.default_user');
  586. }
  587. if (!isset($parameters['password'])) {
  588. $parameters['password'] = @ini_get('mysql.default_password');
  589. }
  590. if (!isset($parameters['new_link'])) {
  591. $parameters['new_link'] = false;
  592. }
  593. if (!isset($parameters['client_flags'])) {
  594. $parameters['client_flags'] = 0;
  595. }
  596. return $parameters['persistent']
  597. ? mysql_pconnect($parameters['server'], $parameters['username'], $parameters['password'], $parameters['client_flags'])
  598. : mysql_connect($parameters['server'], $parameters['username'], $parameters['password'], $parameters['new_link'], $parameters['client_flags']);
  599. }
  600. /**
  601. * Returns the error number from the last operation done on the database server.
  602. * @param resource $connection (optional) The database server connection, for detailed description see the method query().
  603. * @return int Returns the error number from the last database (operation, or 0 (zero) if no error occurred.
  604. */
  605. public static function errno($connection = null) {
  606. return self::use_default_connection($connection) ? mysql_errno() : mysql_errno($connection);
  607. }
  608. /**
  609. * Returns the error text from the last operation done on the database server.
  610. * @param resource $connection (optional) The database server connection, for detailed description see the method query().
  611. * @return string Returns the error text from the last database operation, or '' (empty string) if no error occurred.
  612. */
  613. public static function error($connection = null) {
  614. return self::use_default_connection($connection) ? mysql_error() : mysql_error($connection);
  615. }
  616. /**
  617. * Escapes a string to insert into the database as text
  618. * @param string The string to escape
  619. * @param resource $connection (optional) The database server connection, for detailed description see the method query().
  620. * @return string The escaped string
  621. * @author Yannick Warnier <yannick.warnier@dokeos.com>
  622. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  623. */
  624. public static function escape_string($string, $connection = null) {
  625. return get_magic_quotes_gpc()
  626. ? (self::use_default_connection($connection)
  627. ? mysql_real_escape_string(stripslashes($string))
  628. : mysql_real_escape_string(stripslashes($string), $connection))
  629. : (self::use_default_connection($connection)
  630. ? mysql_real_escape_string($string)
  631. : mysql_real_escape_string($string, $connection));
  632. }
  633. /**
  634. * Gets the array from a SQL result (as returned by Database::query) - help achieving database independence
  635. * @param resource The result from a call to sql_query (e.g. Database::query)
  636. * @param string Optional: "ASSOC","NUM" or "BOTH", as the constant used in mysql_fetch_array.
  637. * @return array Array of results as returned by php
  638. * @author Yannick Warnier <yannick.warnier@dokeos.com>
  639. */
  640. public static function fetch_array($result, $option = 'BOTH') {
  641. return $option == 'ASSOC' ? mysql_fetch_array($result, MYSQL_ASSOC) : ($option == 'NUM' ? mysql_fetch_array($result, MYSQL_NUM) : mysql_fetch_array($result));
  642. }
  643. /**
  644. * Gets an associative array from a SQL result (as returned by Database::query).
  645. * This method is equivalent to calling Database::fetch_array() with 'ASSOC' value for the optional second parameter.
  646. * @param resource $result The result from a call to sql_query (e.g. Database::query).
  647. * @return array Returns an associative array that corresponds to the fetched row and moves the internal data pointer ahead.
  648. */
  649. public static function fetch_assoc($result) {
  650. return mysql_fetch_assoc($result);
  651. }
  652. /**
  653. * Gets the next row of the result of the SQL query (as returned by Database::query) in an object form
  654. * @param resource The result from a call to sql_query (e.g. Database::query)
  655. * @param string Optional class name to instanciate
  656. * @param array Optional array of parameters
  657. * @return object Object of class StdClass or the required class, containing the query result row
  658. * @author Yannick Warnier <yannick.warnier@dokeos.com>
  659. */
  660. public static function fetch_object($result, $class = null, $params = null) {
  661. return !empty($class) ? (is_array($params) ? mysql_fetch_object($result, $class, $params) : mysql_fetch_object($result, $class)) : mysql_fetch_object($result);
  662. }
  663. /**
  664. * Gets the array from a SQL result (as returned by Database::query) - help achieving database independence
  665. * @param resource The result from a call to sql_query (see Database::query()).
  666. * @return array Array of results as returned by php (mysql_fetch_row)
  667. */
  668. public static function fetch_row($result) {
  669. return mysql_fetch_row($result);
  670. }
  671. /**
  672. * Frees all the memory associated with the provided result identifier.
  673. * @return bool Returns TRUE on success or FALSE on failure.
  674. * Notes: Use this method if you are concerned about how much memory is being used for queries that return large result sets.
  675. * Anyway, all associated result memory is automatically freed at the end of the script's execution.
  676. */
  677. public static function free_result($result) {
  678. return mysql_free_result($result);
  679. }
  680. /**
  681. * Returns the database client library version.
  682. * @return strung Returns a string that represents the client library version.
  683. */
  684. public function get_client_info() {
  685. return mysql_get_client_info();
  686. }
  687. /**
  688. * Returns a list of databases created on the server. The list may contain all of the
  689. * available database names or filtered database names by using a pattern.
  690. * @param string $pattern (optional) A pattern for filtering database names as if it was needed for the SQL's LIKE clause, for example 'chamilo_%'.
  691. * @param resource $connection (optional) The database server connection, for detailed description see the method query().
  692. * @return array Returns in an array the retrieved list of database names.
  693. */
  694. public static function get_databases($pattern = '', $connection = null) {
  695. $result = array();
  696. $query_result = Database::query(!empty($pattern) ? "SHOW DATABASES LIKE '".self::escape_string($pattern, $connection)."'" : "SHOW DATABASES", $connection);
  697. while ($row = Database::fetch_row($query_result)) {
  698. $result[] = $row[0];
  699. }
  700. return $result;
  701. }
  702. /**
  703. * 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.
  704. * By using a special option, this method is able to return an indexed list of fields' properties, where field names are keys.
  705. * @param string $table This is the examined table.
  706. * @param string $pattern (optional) A pattern for filtering field names as if it was needed for the SQL's LIKE clause, for example 'column_%'.
  707. * @param string $database (optional) The name of the targeted database. If it is omited, the current database is assumed, see Database::select_db().
  708. * @param bool $including_properties (optional) When this option is true, the returned result has the followong format:
  709. * array(field_name_1 => array(0 => property_1, 1 => property_2, ...), fieald_name_2 => array(0 => property_1, ...), ...)
  710. * @param resource $connection (optional) The database server connection, for detailed description see the method query().
  711. * @return array Returns in an array the retrieved list of field names.
  712. */
  713. public static function get_fields($table, $pattern = '', $database = '', $including_properties = false, $connection = null) {
  714. $result = array();
  715. $query = "SHOW COLUMNS FROM `".self::escape_string($table, $connection)."`";
  716. if (!empty($database)) {
  717. $query .= " FROM `".self::escape_string($database, $connection)."`";
  718. }
  719. if (!empty($pattern)) {
  720. $query .= " LIKE '".self::escape_string($pattern, $connection)."'";
  721. }
  722. $query_result = Database::query($query, $connection);
  723. if ($including_properties) {
  724. // Making an indexed list of the fields and their properties.
  725. while ($row = Database::fetch_row($query_result)) {
  726. $result[$row[0]] = $row;
  727. }
  728. } else {
  729. // Making a plain, flat list.
  730. while ($row = Database::fetch_row($query_result)) {
  731. $result[] = $row[0];
  732. }
  733. }
  734. return $result;
  735. }
  736. /**
  737. * Returns information about the type of the current connection and the server host name.
  738. * @param resource $connection (optional) The database server connection, for detailed description see the method query().
  739. * @return string/boolean Returns string data on success or FALSE on failure.
  740. */
  741. public function get_host_info($connection = null) {
  742. return self::use_default_connection($connection) ? mysql_get_host_info() : mysql_get_host_info($connection);
  743. }
  744. /**
  745. * Retrieves database client/server protocol version.
  746. * @param resource $connection (optional) The database server connection, for detailed description see the method query().
  747. * @return int/boolean Returns the protocol version on success or FALSE on failure.
  748. */
  749. public function get_proto_info($connection = null) {
  750. return self::use_default_connection($connection) ? mysql_get_proto_info() : mysql_get_proto_info($connection);
  751. }
  752. /**
  753. * Retrieves the database server version.
  754. * @param resource $connection (optional) The database server connection, for detailed description see the method query().
  755. * @return string/boolean Returns the MySQL server version on success or FALSE on failure.
  756. */
  757. public function get_server_info($connection = null) {
  758. return self::use_default_connection($connection) ? mysql_get_server_info() : mysql_get_server_info($connection);
  759. }
  760. /**
  761. * Returns a list of tables within a database. The list may contain all of the
  762. * available table names or filtered table names by using a pattern.
  763. * @param string $database (optional) The name of the examined database. If it is omited, the current database is assumed, see Database::select_db().
  764. * @param string $pattern (optional) A pattern for filtering table names as if it was needed for the SQL's LIKE clause, for example 'access_%'.
  765. * @param resource $connection (optional) The database server connection, for detailed description see the method query().
  766. * @return array Returns in an array the retrieved list of table names.
  767. */
  768. public static function get_tables($database = '', $pattern = '', $connection = null) {
  769. $result = array();
  770. $query = "SHOW TABLES";
  771. if (!empty($database)) {
  772. $query .= " FROM `".self::escape_string($database, $connection)."`";
  773. }
  774. if (!empty($pattern)) {
  775. $query .= " LIKE '".self::escape_string($pattern, $connection)."'";
  776. }
  777. $query_result = Database::query($query, $connection);
  778. while ($row = Database::fetch_row($query_result)) {
  779. $result[] = $row[0];
  780. }
  781. return $result;
  782. }
  783. /**
  784. * Gets the ID of the last item inserted into the database
  785. * @param resource $connection (optional) The database server connection, for detailed description see the method query().
  786. * @return int The last ID as returned by the DB function
  787. * @comment This should be updated to use ADODB at some point
  788. */
  789. public static function insert_id($connection = null) {
  790. return self::use_default_connection($connection) ? mysql_insert_id() : mysql_insert_id($connection);
  791. }
  792. /**
  793. * Gets the number of rows from the last query result - help achieving database independence
  794. * @param resource The result
  795. * @return integer The number of rows contained in this result
  796. * @author Yannick Warnier <yannick.warnier@dokeos.com>
  797. **/
  798. public static function num_rows($result) {
  799. return is_resource($result) ? mysql_num_rows($result) : false;
  800. }
  801. /**
  802. * Acts as the relative *_result() function of most DB drivers and fetches a
  803. * specific line and a field
  804. * @param resource The database resource to get data from
  805. * @param integer The row number
  806. * @param string Optional field name or number
  807. * @result mixed One cell of the result, or FALSE on error
  808. */
  809. public static function result($resource, $row, $field = '') {
  810. return self::num_rows($resource) > 0 ? (!empty($field) ? mysql_result($resource, $row, $field) : mysql_result($resource, $row)) : null;
  811. }
  812. /**
  813. * This method returns a resource
  814. * Documentation has been added by Arthur Portugal
  815. * Some adaptations have been implemented by Ivan Tcholakov, 2009, 2010
  816. * @author Olivier Brouckaert
  817. * @param string $query The SQL query
  818. * @param resource $connection (optional) The database server (MySQL) connection.
  819. * If it is not specified, the connection opened by mysql_connect() is assumed.
  820. * If no connection is found, the server will try to create one as if mysql_connect() was called with no arguments.
  821. * If no connection is found or established, an E_WARNING level error is generated.
  822. * @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)
  823. * @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)
  824. * @return resource The returned result from the query
  825. * Note: The parameter $connection could be skipped. Here are examples of this method usage:
  826. * Database::query($query);
  827. * $result = Database::query($query);
  828. * Database::query($query, $connection);
  829. * $result = Database::query($query, $connection);
  830. * The following ways for calling this method are obsolete:
  831. * Database::query($query, __FILE__, __LINE__);
  832. * $result = Database::query($query, __FILE__, __LINE__);
  833. * Database::query($query, $connection, __FILE__, __LINE__);
  834. * $result = Database::query($query, $connection, __FILE__, __LINE__);
  835. */
  836. public static function query($query, $connection = null, $file = null, $line = null) {
  837. $use_default_connection = self::use_default_connection($connection);
  838. if ($use_default_connection) {
  839. // Let us do parameter shifting, thus the method would be similar
  840. // (in regard to parameter order) to the original function mysql_query().
  841. $line = $file;
  842. $file = $connection;
  843. $connection = null;
  844. }
  845. if (!($result = $use_default_connection ? @mysql_query($query) : @mysql_query($query, $connection))) {
  846. $backtrace = debug_backtrace(); // Retrieving information about the caller statement.
  847. if (isset($backtrace[0])) {
  848. $caller = & $backtrace[0];
  849. } else {
  850. $caller = array();
  851. }
  852. if (isset($backtrace[1])) {
  853. $owner = & $backtrace[1];
  854. } else {
  855. $owner = array();
  856. }
  857. if (empty($file)) {
  858. $file = $caller['file'];
  859. }
  860. if (empty($line)) {
  861. $line = $caller['line'];
  862. }
  863. $type = $owner['type'];
  864. $function = $owner['function'];
  865. $class = $owner['class'];
  866. $server_type = api_get_setting('server_type');
  867. if (!empty($line) && !empty($server_type) && $server_type != 'production') {
  868. $info = '<pre>' .
  869. '<strong>DATABASE ERROR #'.self::errno($connection).':</strong><br /> ' .
  870. self::remove_XSS(self::error($connection)) . '<br />' .
  871. '<strong>QUERY :</strong><br /> ' .
  872. self::remove_XSS($query) . '<br />' .
  873. '<strong>FILE :</strong><br /> ' .
  874. (empty($file) ? ' unknown ' : $file) . '<br />' .
  875. '<strong>LINE :</strong><br /> ' .
  876. (empty($line) ? ' unknown ' : $line) . '<br />';
  877. if (empty($type)) {
  878. if (!empty($function)) {
  879. $info .= '<strong>FUNCTION :</strong><br /> ' . $function;
  880. }
  881. } else {
  882. if (!empty($class) && !empty($function)) {
  883. $info .= '<strong>CLASS :</strong><br /> ' . $class . '<br />';
  884. $info .= '<strong>METHOD :</strong><br /> ' . $function;
  885. }
  886. }
  887. $info .= '</pre>';
  888. echo $info;
  889. }
  890. }
  891. return $result;
  892. }
  893. /**
  894. * Selects a database.
  895. * @param string $database_name The name of the database that is to be selected.
  896. * @param resource $connection (optional) The database server connection, for detailed description see the method query().
  897. * @return bool Returns TRUE on success or FALSE on failure.
  898. */
  899. public static function select_db($database_name, $connection = null) {
  900. return self::use_default_connection($connection) ? mysql_select_db($database_name) : mysql_select_db($database_name, $connection);
  901. }
  902. /**
  903. * Stores a query result into an array.
  904. *
  905. * @author Olivier Brouckaert
  906. * @param resource $result - the return value of the query
  907. * @param option BOTH, ASSOC, or NUM
  908. * @return array - the value returned by the query
  909. */
  910. public static function store_result($result, $option = 'BOTH') {
  911. $array = array();
  912. if ($result !== false) { // For isolation from database engine's behaviour.
  913. while ($row = self::fetch_array($result, $option)) {
  914. $array[] = $row;
  915. }
  916. }
  917. return $array;
  918. }
  919. /*
  920. Encodings and collations supported by MySQL database server
  921. */
  922. /**
  923. * Checks whether a given encoding is supported by the database server.
  924. * @param string $encoding The encoding (a system conventional id, for example 'UTF-8') to be checked.
  925. * @return bool Returns a boolean value as a check-result.
  926. * @author Ivan Tcholakov
  927. */
  928. public static function is_encoding_supported($encoding) {
  929. static $supported = array();
  930. if (!isset($supported[$encoding])) {
  931. $supported[$encoding] = false;
  932. if (strlen($db_encoding = self::to_db_encoding($encoding)) > 0) {
  933. if (self::num_rows(self::query("SHOW CHARACTER SET WHERE Charset = '".self::escape_string($db_encoding)."';")) > 0) {
  934. $supported[$encoding] = true;
  935. }
  936. }
  937. }
  938. return $supported[$encoding];
  939. }
  940. /**
  941. * Constructs a SQL clause about default character set and default collation for newly created databases and tables.
  942. * Example: Database::make_charset_clause('UTF-8', 'bulgarian') returns
  943. * DEFAULT CHARACTER SET `utf8` DEFAULT COLLATE `utf8_general_ci`
  944. * @param string $encoding (optional) The default database/table encoding (a system conventional id) to be used.
  945. * @param string $language (optional) Language (a system conventional id) used for choosing language sensitive collation (if it is possible).
  946. * @return string Returns the constructed SQL clause or empty string if $encoding is not correct or is not supported.
  947. * @author Ivan Tcholakov
  948. */
  949. public static function make_charset_clause($encoding = null, $language = null) {
  950. if (empty($encoding)) {
  951. $encoding = api_get_system_encoding();
  952. }
  953. if (empty($language)) {
  954. $language = api_get_interface_language();
  955. }
  956. $charset_clause = '';
  957. if (self::is_encoding_supported($encoding)) {
  958. $db_encoding = Database::to_db_encoding($encoding);
  959. $charset_clause .= " DEFAULT CHARACTER SET `".$db_encoding."`";
  960. $db_collation = Database::to_db_collation($encoding, $language);
  961. if (!empty($db_collation)) {
  962. $charset_clause .= " DEFAULT COLLATE `".$db_collation."`";
  963. }
  964. }
  965. return $charset_clause;
  966. }
  967. /**
  968. * Converts an encoding identificator to MySQL-specific encoding identifictor,
  969. * i.e. 'UTF-8' --> 'utf8'.
  970. * @param string $encoding The conventional encoding identificator.
  971. * @return string Returns the corresponding MySQL-specific encoding identificator if any, otherwise returns NULL.
  972. * @author Ivan Tcholakov
  973. */
  974. public static function to_db_encoding($encoding) {
  975. static $result = array();
  976. if (!isset($result[$encoding])) {
  977. $result[$encoding] = null;
  978. $encoding_map = & self::get_db_encoding_map();
  979. foreach ($encoding_map as $key => $value) {
  980. if (api_equal_encodings($encoding, $key)) {
  981. $result[$encoding] = $value;
  982. break;
  983. }
  984. }
  985. }
  986. return $result[$encoding];
  987. }
  988. /**
  989. * Converts a MySQL-specific encoding identifictor to conventional encoding identificator,
  990. * i.e. 'utf8' --> 'UTF-8'.
  991. * @param string $encoding The MySQL-specific encoding identificator.
  992. * @return string Returns the corresponding conventional encoding identificator if any, otherwise returns NULL.
  993. * @author Ivan Tcholakov
  994. */
  995. public static function from_db_encoding($db_encoding) {
  996. static $result = array();
  997. if (!isset($result[$db_encoding])) {
  998. $result[$db_encoding] = null;
  999. $encoding_map = & self::get_db_encoding_map();
  1000. foreach ($encoding_map as $key => $value) {
  1001. if (strtolower($db_encoding) == $value) {
  1002. $result[$db_encoding] = $key;
  1003. break;
  1004. }
  1005. }
  1006. }
  1007. return $result[$db_encoding];
  1008. }
  1009. /**
  1010. * Chooses the default MySQL-specific collation from given encoding and language.
  1011. * @param string $encoding A conventional encoding id, i.e. 'UTF-8'
  1012. * @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.
  1013. * @return string Returns a suitable default collation, for example 'utf8_general_ci', or NULL if collation was not found.
  1014. * @author Ivan Tcholakov
  1015. */
  1016. public static function to_db_collation($encoding, $language = null) {
  1017. static $result = array();
  1018. if (!isset($result[$encoding][$language])) {
  1019. $result[$encoding][$language] = null;
  1020. if (self::is_encoding_supported($encoding)) {
  1021. $db_encoding = self::to_db_encoding($encoding);
  1022. if (!empty($language)) {
  1023. $lang = api_purify_language_id($language);
  1024. $res = self::check_db_collation($db_encoding, $lang);
  1025. if (empty($res)) {
  1026. $db_collation_map = & self::get_db_collation_map();
  1027. if (isset($db_collation_map[$lang])) {
  1028. $res = self::check_db_collation($db_encoding, $db_collation_map[$lang]);
  1029. }
  1030. }
  1031. if (empty($res)) {
  1032. $res = self::check_db_collation($db_encoding, null);
  1033. }
  1034. $result[$encoding][$language] = $res;
  1035. } else {
  1036. $result[$encoding][$language] = self::check_db_collation($db_encoding, null);
  1037. }
  1038. }
  1039. }
  1040. return $result[$encoding][$language];
  1041. }
  1042. /*
  1043. Private methods
  1044. You should not access these from outside the class
  1045. No effort is made to keep the names / results the same.
  1046. */
  1047. /**
  1048. * Glues a course database.
  1049. * glue format from local.inc.php.
  1050. */
  1051. private static function glue_course_database_name($database_name) {
  1052. return self::get_course_table_prefix().$database_name.self::get_database_glue();
  1053. }
  1054. /**
  1055. * @param string $database_name, can be empty to use current course db
  1056. *
  1057. * @return the glued parameter if it is not empty,
  1058. * or the current course database (glued) if the parameter is empty.
  1059. */
  1060. private static function fix_database_parameter($database_name) {
  1061. if (empty($database_name)) {
  1062. $course_info = api_get_course_info();
  1063. return $course_info['dbNameGlu'];
  1064. }
  1065. return self::glue_course_database_name($database_name);
  1066. }
  1067. /**
  1068. * Structures a course database and table name to ready them
  1069. * for querying. The course database parameter is considered glued:
  1070. * e.g. COURSE001`.`
  1071. */
  1072. private static function format_glued_course_table_name($database_name_with_glue, $table) {
  1073. return '`'.$database_name_with_glue.$table.'`';
  1074. }
  1075. /**
  1076. * Structures a database and table name to ready them
  1077. * for querying. The database parameter is considered not glued,
  1078. * just plain e.g. COURSE001
  1079. */
  1080. private static function format_table_name($database, $table) {
  1081. return '`'.$database.'`.`'.$table.'`';
  1082. }
  1083. /**
  1084. * This private method is to be used by the other methods in this class for
  1085. * checking whether the input parameter $connection actually has been provided.
  1086. * If the input parameter connection is not a resource or if it is not FALSE (in case of error)
  1087. * then the default opened connection should be used by the called method.
  1088. * @param resource/boolean $connection The checked parameter $connection.
  1089. * @return boolean TRUE means that calling method should use the default connection.
  1090. * FALSE means that (valid) parameter $connection has been provided and it should be used.
  1091. */
  1092. private static function use_default_connection($connection) {
  1093. return !is_resource($connection) && $connection !== false;
  1094. }
  1095. /**
  1096. * This private method tackles the XSS injections. It is similar to Security::remove_XSS() and works always,
  1097. * including the time of initialization when the class Security has not been loaded yet.
  1098. * @param string The input variable to be filtered from XSS, in this class it is expected to be a string.
  1099. * @return string Returns the filtered string as a result.
  1100. */
  1101. private static function remove_XSS(& $var) {
  1102. return class_exists('Security') && class_exists('HTMLPurifier') ? Security::remove_XSS($var) : api_htmlentities($var, ENT_QUOTES);
  1103. }
  1104. /**
  1105. * This private method encapsulates a table with relations between
  1106. * conventional and MuSQL-specific encoding identificators.
  1107. * @author Ivan Tcholakov
  1108. */
  1109. private static function & get_db_encoding_map() {
  1110. static $encoding_map = array(
  1111. 'ARMSCII-8' => 'armscii8',
  1112. 'BIG5' => 'big5',
  1113. 'BINARY' => 'binary',
  1114. 'CP866' => 'cp866',
  1115. 'EUC-JP' => 'ujis',
  1116. 'EUC-KR' => 'euckr',
  1117. 'GB2312' => 'gb2312',
  1118. 'GBK' => 'gbk',
  1119. 'ISO-8859-1' => 'latin1',
  1120. 'ISO-8859-2' => 'latin2',
  1121. 'ISO-8859-7' => 'greek',
  1122. 'ISO-8859-8' => 'hebrew',
  1123. 'ISO-8859-9' => 'latin5',
  1124. 'ISO-8859-13' => 'latin7',
  1125. 'ISO-8859-15' => 'latin1',
  1126. 'KOI8-R' => 'koi8r',
  1127. 'KOI8-U' => 'koi8u',
  1128. 'SHIFT-JIS' => 'sjis',
  1129. 'TIS-620' => 'tis620',
  1130. 'US-ASCII' => 'ascii',
  1131. 'UTF-8' => 'utf8',
  1132. 'WINDOWS-1250' => 'cp1250',
  1133. 'WINDOWS-1251' => 'cp1251',
  1134. 'WINDOWS-1252' => 'latin1',
  1135. 'WINDOWS-1256' => 'cp1256',
  1136. 'WINDOWS-1257' => 'cp1257'
  1137. );
  1138. return $encoding_map;
  1139. }
  1140. /**
  1141. * A helper language id translation table for choosing some collations.
  1142. * @author Ivan Tcholakov
  1143. */
  1144. private static function & get_db_collation_map() {
  1145. static $db_collation_map = array(
  1146. 'german' => 'german2',
  1147. 'simpl_chinese' => 'chinese',
  1148. 'trad_chinese' => 'chinese',
  1149. 'turkce' => 'turkish'
  1150. );
  1151. return $db_collation_map;
  1152. }
  1153. /**
  1154. * Constructs a MySQL-specific collation and checks whether it is supported by the database server.
  1155. * @param string $db_encoding A MySQL-specific encoding id, i.e. 'utf8'
  1156. * @param string $language A MySQL-compatible language id, i.e. 'bulgarian'
  1157. * @return string Returns a suitable default collation, for example 'utf8_general_ci', or NULL if collation was not found.
  1158. * @author Ivan Tcholakov
  1159. */
  1160. private static function check_db_collation($db_encoding, $language) {
  1161. if (empty($db_encoding)) {
  1162. return null;
  1163. }
  1164. if (empty($language)) {
  1165. $result = self::fetch_array(self::query("SHOW COLLATION WHERE Charset = '".self::escape_string($db_encoding)."' AND `Default` = 'Yes';"), 'NUM');
  1166. return $result ? $result[0] : null;
  1167. }
  1168. $collation = $db_encoding.'_'.$language.'_ci';
  1169. $query_result = self::query("SHOW COLLATION WHERE Charset = '".self::escape_string($db_encoding)."';");
  1170. while ($result = self::fetch_array($query_result, 'NUM')) {
  1171. if ($result[0] == $collation) {
  1172. return $collation;
  1173. }
  1174. }
  1175. return null;
  1176. }
  1177. /*
  1178. DEPRECATED METHODS
  1179. */
  1180. /**
  1181. * @deprecated Use api_get_language_isocode($language) instead.
  1182. */
  1183. public static function get_language_isocode($language) {
  1184. return api_get_language_isocode($language);
  1185. }
  1186. /**
  1187. * @deprecated Use Database::insert_id() instead.
  1188. */
  1189. public static function get_last_insert_id() {
  1190. return mysql_insert_id();
  1191. }
  1192. }
  1193. //end class Database