install_upgrade.lib.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519
  1. <?php
  2. /*
  3. ==============================================================================
  4. Dokeos - elearning and course management software
  5. Copyright (c) 2004-2008 Dokeos S.P.R.L
  6. Copyright (c) Roan Embrechts, Vrije Universiteit Brussel
  7. Copyright (c) Bart Mollet, Hogeschool Gent
  8. For a full list of contributors, see "credits.txt".
  9. The full license can be read in "license.txt".
  10. This program is free software; you can redistribute it and/or
  11. modify it under the terms of the GNU General Public License
  12. as published by the Free Software Foundation; either version 2
  13. of the License, or (at your option) any later version.
  14. See the GNU General Public License for more details.
  15. Contact address: Dokeos, rue du Corbeau, 108, B-1030 Brussels, Belgium
  16. Mail: info@dokeos.com
  17. ==============================================================================
  18. */
  19. /**
  20. ==============================================================================
  21. * This file contains functions used by the install and upgrade scripts.
  22. * The current functions are used to
  23. * - fill existing tables with data;
  24. * - write a .htaccess file in the courses folder for extra security;
  25. * - write the Dokeos config file containing important settings like database names
  26. * and paswords and other options.
  27. *
  28. * Ideas for future additions:
  29. * - a function get_old_version_settings to retrieve the config file settings
  30. * of older versions before upgrading.
  31. ==============================================================================
  32. */
  33. /*
  34. ==============================================================================
  35. CONSTANTS
  36. ==============================================================================
  37. */
  38. define("DOKEOS_MAIN_DATABASE_FILE", "dokeos_main.sql");
  39. define("LANGUAGE_DATA_FILENAME", "language_data.csv");
  40. define("COUNTRY_DATA_FILENAME", "country_data.csv");
  41. define("SETTING_OPTION_DATA_FILENAME", "setting_option_data.csv");
  42. define("SETTING_CURRENT_DATA_FILENAME", "setting_current_data.csv");
  43. define("COURSES_HTACCESS_FILENAME", "htaccess.dist");
  44. define("DOKEOS_CONFIG_FILENAME", "configuration.dist.php");
  45. /*
  46. ==============================================================================
  47. DATABASE FUNCTIONS
  48. ==============================================================================
  49. */
  50. /**
  51. * We assume this function is called from install scripts that reside inside
  52. * the install folder.
  53. */
  54. function set_file_folder_permissions()
  55. {
  56. @chmod('.',0755); //set permissions on install dir
  57. @chmod('..',0755); //set permissions on parent dir of install dir
  58. @chmod('language_data.csv',0755);
  59. @chmod('setting_current_data.csv',0755);
  60. @chmod('setting_option_data.csv',0755);
  61. @chmod('country_data.csv.csv',0755);
  62. }
  63. /**
  64. * Fills the language table with all available languages.
  65. */
  66. function fill_language_table($language_table)
  67. {
  68. $file_path = dirname(__FILE__).'/'.LANGUAGE_DATA_FILENAME;
  69. $add_language_sql = "LOAD DATA INFILE '".mysql_real_escape_string($file_path)."' INTO TABLE $language_table FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '\'';";
  70. @ mysql_query($add_language_sql);
  71. }
  72. /**
  73. * Fills the current settings table with the Dokeos default settings.
  74. * After using the LOAD DATA INFILE instruction, the database stores some
  75. * variables literally as '$variable'. The instructions after that replace
  76. * that literal by the actual value of the variable.
  77. */
  78. function fill_current_settings_table($current_settings_table, $installation_settings)
  79. {
  80. $institutionForm = $installation_settings['institution_form'];
  81. $institutionUrlForm = $installation_settings['institution_url_form'];
  82. $campusForm = $installation_settings['campus_form'];
  83. $emailForm = $installation_settings['email_form'];
  84. $adminLastName = $installation_settings['admin_last_name'];
  85. $adminFirstName = $installation_settings['admin_first_name'];
  86. $languageForm = $installation_settings['language_form'];
  87. $allowSelfReg = $installation_settings['allow_self_registration'];
  88. $allowSelfRegProf = $installation_settings['allow_teacher_self_registration'];
  89. $adminPhoneForm = $installation_settings['admin_phone_form'];
  90. $file_path = dirname(__FILE__).'/'.SETTING_CURRENT_DATA_FILENAME;
  91. $add_setting_current_sql = "LOAD DATA INFILE '".mysql_real_escape_string($file_path)."' INTO TABLE $current_settings_table FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '\'';";
  92. @ mysql_query($add_setting_current_sql);
  93. //replace literal '$variable' by the contents of variable $variable
  94. mysql_query("UPDATE $current_settings_table SET selected_value='$institutionForm' WHERE selected_value='\$institutionForm'");
  95. mysql_query("UPDATE $current_settings_table SET selected_value='$institutionUrlForm' WHERE selected_value='\$institutionUrlForm'");
  96. mysql_query("UPDATE $current_settings_table SET selected_value='$campusForm' WHERE selected_value='\$campusForm'");
  97. mysql_query("UPDATE $current_settings_table SET selected_value='$emailForm' WHERE selected_value='\$emailForm'");
  98. mysql_query("UPDATE $current_settings_table SET selected_value='$adminLastName' WHERE selected_value='\$adminLastName'");
  99. mysql_query("UPDATE $current_settings_table SET selected_value='$adminFirstName' WHERE selected_value='\$adminFirstName'");
  100. mysql_query("UPDATE $current_settings_table SET selected_value='$languageForm' WHERE selected_value='\$languageForm'");
  101. mysql_query("UPDATE $current_settings_table SET selected_value='".trueFalse($allowSelfReg)."' WHERE selected_value='\$allowSelfReg'");
  102. mysql_query("UPDATE $current_settings_table SET selected_value='".trueFalse($allowSelfRegProf)."' WHERE selected_value='\$allowSelfRegProf'");
  103. mysql_query("UPDATE $current_settings_table SET selected_value='$adminPhoneForm' WHERE selected_value='\$adminPhoneForm'");
  104. }
  105. /**
  106. * Fills the table with the possible options for all settings.
  107. */
  108. function fill_settings_options_table($settings_options_table)
  109. {
  110. $file_path = dirname(__FILE__).'/'.SETTING_OPTION_DATA_FILENAME;
  111. $add_setting_option_sql = "LOAD DATA INFILE '".mysql_real_escape_string($file_path)."' INTO TABLE $settings_options_table FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '\'';";
  112. @ mysql_query($add_setting_option_sql);
  113. }
  114. /**
  115. * Fills the countries table with a list of countries.
  116. */
  117. function fill_track_countries_table($track_countries_table)
  118. {
  119. $file_path = dirname(__FILE__).'/'.COUNTRY_DATA_FILENAME;
  120. $add_country_sql = "LOAD DATA INFILE '".mysql_real_escape_string($file_path)."' INTO TABLE $track_countries_table FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '\'';";
  121. @ mysql_query($add_country_sql);
  122. }
  123. /**
  124. * Add's a .htaccess file to the courses directory
  125. * @param string $url_append The path from your webroot to your dokeos root
  126. */
  127. function write_courses_htaccess_file($url_append)
  128. {
  129. $file_path = dirname(__FILE__).'/'.COURSES_HTACCESS_FILENAME;
  130. $content = file_get_contents($file_path);
  131. $content = str_replace('{DOKEOS_URL_APPEND_PATH}', $url_append, $content);
  132. $fp = @ fopen('../../courses/.htaccess', 'w');
  133. if ($fp)
  134. {
  135. fwrite($fp, $content);
  136. return fclose($fp);
  137. }
  138. return false;
  139. }
  140. /**
  141. * Write the main Dokeos config file
  142. * @param string $path Path to the config file
  143. */
  144. function write_dokeos_config_file($path)
  145. {
  146. global $dbHostForm;
  147. global $dbUsernameForm;
  148. global $dbPassForm;
  149. global $enableTrackingForm;
  150. global $singleDbForm;
  151. global $dbPrefixForm;
  152. global $dbNameForm;
  153. global $dbStatsForm;
  154. global $dbScormForm;
  155. global $dbUserForm;
  156. global $urlForm;
  157. global $pathForm;
  158. global $urlAppendPath;
  159. global $languageForm;
  160. global $encryptPassForm;
  161. global $installType;
  162. global $updatePath;
  163. global $session_lifetime;
  164. global $new_version;
  165. global $new_version_stable;
  166. $rootSys = realpath($pathForm).'/';
  167. $garbageDir = realpath('../garbage/').'/';
  168. //change paths if updating
  169. //if($installType=='update'){
  170. // $rootSys = $updatePath;
  171. // $garbageDir = realpath($updatePath.'claroline/garbage/').'/';
  172. // $urlAppendPath = '';
  173. //}
  174. $file_path = dirname(__FILE__).'/'.DOKEOS_CONFIG_FILENAME;
  175. $content = file_get_contents($file_path);
  176. $config['{DATE_GENERATED}'] = date('r');
  177. $config['{DATABASE_HOST}'] = $dbHostForm;
  178. $config['{DATABASE_USER}'] = $dbUsernameForm;
  179. $config['{DATABASE_PASSWORD}'] = $dbPassForm;
  180. $config['{TRACKING_ENABLED}'] = trueFalse($enableTrackingForm);
  181. $config['{SINGLE_DATABASE}'] = trueFalse($singleDbForm);
  182. $config['{COURSE_TABLE_PREFIX}'] = ($singleDbForm ? 'crs_' : '');
  183. $config['{DATABASE_GLUE}'] = ($singleDbForm ? '_' : '`.`');
  184. $config['{DATABASE_PREFIX}'] = $dbPrefixForm;
  185. $config['{DATABASE_MAIN}'] = $dbNameForm;
  186. $config['{DATABASE_STATS}'] = (($singleDbForm && empty($dbStatsForm)) ? $dbNameForm : $dbStatsForm);
  187. $config['{DATABASE_SCORM}'] = (($singleDbForm && empty($dbScormForm)) ? $dbNameForm : $dbScormForm);
  188. $config['{DATABASE_PERSONAL}'] =(($singleDbForm && empty($dbUserForm)) ? $dbNameForm : $dbUserForm);
  189. $config['{ROOT_WEB}'] = $urlForm;
  190. $config['{ROOT_SYS}'] = str_replace('\\', '/', $rootSys);
  191. $config['{URL_APPEND_PATH}'] = $urlAppendPath;
  192. $config['{GARBAGE_DIR}'] = str_replace("\\", '/', $garbageDir);
  193. $config['{PLATFORM_LANGUAGE}'] = $languageForm;
  194. $config['{SECURITY_KEY}'] = md5(uniqid(rand().time()));
  195. $config['{ENCRYPT_PASSWORD}'] = trueFalse($encryptPassForm);
  196. $config['{SESSION_LIFETIME}'] = $session_lifetime;
  197. $config['{NEW_VERSION}'] = $new_version;
  198. $config['{NEW_VERSION_STABLE}'] = trueFalse($new_version_stable);
  199. foreach ($config as $key => $value)
  200. {
  201. $content = str_replace($key, $value, $content);
  202. }
  203. $fp = @ fopen($path, 'w');
  204. if (!$fp)
  205. {
  206. echo '<b><font color="red">Your script doesn\'t have write access to the config directory</font></b><br />
  207. <em>('.str_replace('\\', '/', realpath($path)).')</em><br /><br />
  208. You probably do not have write access on Dokeos root directory,
  209. i.e. you should <em>CHMOD 777</em> or <em>755</em> or <em>775</em>.<br /><br />
  210. Your problems can be related on two possible causes:<br />
  211. <ul>
  212. <li>Permission problems.<br />Try initially with <em>chmod -R 777</em> and increase restrictions gradually.</li>
  213. <li>PHP is running in <a href="http://www.php.net/manual/en/features.safe-mode.php" target="_blank">Safe-Mode</a>. If possible, try to switch it off.</li>
  214. </ul>
  215. <a href="http://www.dokeos.com/forum/" target="_blank">Read about this problem in Support Forum</a><br /><br />
  216. Please go back to step 5.
  217. <p><input type="submit" name="step5" value="&lt; Back" /></p>
  218. </td></tr></table></form></body></html>';
  219. exit ();
  220. }
  221. fwrite($fp, $content);
  222. fclose($fp);
  223. }
  224. /**
  225. * Creates the structure of the main database and fills it
  226. * with data. Placeholder symbols in the main database file
  227. * have to be replaced by the settings entered by the user during installation.
  228. *
  229. * @param array $installation_settings list of settings entered by the user
  230. */
  231. function load_main_database($installation_settings)
  232. {
  233. $dokeos_main_sql_file_string = file_get_contents(DOKEOS_MAIN_DATABASE_FILE);
  234. //replace symbolic parameters with user-specified values
  235. foreach ($installation_settings as $key => $value)
  236. {
  237. $dokeos_main_sql_file_string = str_replace($key, mysql_real_escape_string($value), $dokeos_main_sql_file_string);
  238. }
  239. //split in array of sql strings
  240. $sql_instructions = array();
  241. $success = split_sql_file($sql_instructions, $dokeos_main_sql_file_string);
  242. //execute the sql instructions
  243. $count = count($sql_instructions);
  244. for ($i = 0; $i < $count; $i++)
  245. {
  246. $this_sql_query = $sql_instructions[$i]['query'];
  247. mysql_query($this_sql_query);
  248. }
  249. }
  250. /**
  251. * Creates the structure of the stats database
  252. * @param string Name of the file containing the SQL script inside the install directory
  253. */
  254. function load_database_script($db_script)
  255. {
  256. $dokeos_sql_file_string = file_get_contents($db_script);
  257. //split in array of sql strings
  258. $sql_instructions = array();
  259. $success = split_sql_file($sql_instructions, $dokeos_sql_file_string);
  260. //execute the sql instructions
  261. $count = count($sql_instructions);
  262. for ($i = 0; $i < $count; $i++)
  263. {
  264. $this_sql_query = $sql_instructions[$i]['query'];
  265. mysql_query($this_sql_query);
  266. }
  267. }
  268. /**
  269. * Function copied and adapted from phpMyAdmin 2.6.0 PMA_splitSqlFile (also GNU GPL)
  270. *
  271. * Removes comment lines and splits up large sql files into individual queries
  272. *
  273. * Last revision: September 23, 2001 - gandon
  274. *
  275. * @param array the splitted sql commands
  276. * @param string the sql commands
  277. * @param integer the MySQL release number (because certains php3 versions
  278. * can't get the value of a constant from within a function)
  279. *
  280. * @return boolean always true
  281. *
  282. * @access public
  283. */
  284. function split_sql_file(&$ret, $sql)
  285. {
  286. // do not trim, see bug #1030644
  287. //$sql = trim($sql);
  288. $sql = rtrim($sql, "\n\r");
  289. $sql_len = strlen($sql);
  290. $char = '';
  291. $string_start = '';
  292. $in_string = FALSE;
  293. $nothing = TRUE;
  294. $time0 = time();
  295. for ($i = 0; $i < $sql_len; ++$i) {
  296. $char = $sql[$i];
  297. // We are in a string, check for not escaped end of strings except for
  298. // backquotes that can't be escaped
  299. if ($in_string) {
  300. for (;;) {
  301. $i = strpos($sql, $string_start, $i);
  302. // No end of string found -> add the current substring to the
  303. // returned array
  304. if (!$i) {
  305. $ret[] = $sql;
  306. return TRUE;
  307. }
  308. // Backquotes or no backslashes before quotes: it's indeed the
  309. // end of the string -> exit the loop
  310. else if ($string_start == '`' || $sql[$i-1] != '\\') {
  311. $string_start = '';
  312. $in_string = FALSE;
  313. break;
  314. }
  315. // one or more Backslashes before the presumed end of string...
  316. else {
  317. // ... first checks for escaped backslashes
  318. $j = 2;
  319. $escaped_backslash = FALSE;
  320. while ($i-$j > 0 && $sql[$i-$j] == '\\') {
  321. $escaped_backslash = !$escaped_backslash;
  322. $j++;
  323. }
  324. // ... if escaped backslashes: it's really the end of the
  325. // string -> exit the loop
  326. if ($escaped_backslash) {
  327. $string_start = '';
  328. $in_string = FALSE;
  329. break;
  330. }
  331. // ... else loop
  332. else {
  333. $i++;
  334. }
  335. } // end if...elseif...else
  336. } // end for
  337. } // end if (in string)
  338. // lets skip comments (/*, -- and #)
  339. else if (($char == '-' && $sql_len > $i + 2 && $sql[$i + 1] == '-' && $sql[$i + 2] <= ' ') || $char == '#' || ($char == '/' && $sql_len > $i + 1 && $sql[$i + 1] == '*')) {
  340. $i = strpos($sql, $char == '/' ? '*/' : "\n", $i);
  341. // didn't we hit end of string?
  342. if ($i === FALSE) {
  343. break;
  344. }
  345. if ($char == '/') $i++;
  346. }
  347. // We are not in a string, first check for delimiter...
  348. else if ($char == ';') {
  349. // if delimiter found, add the parsed part to the returned array
  350. $ret[] = array('query' => substr($sql, 0, $i), 'empty' => $nothing);
  351. $nothing = TRUE;
  352. $sql = ltrim(substr($sql, min($i + 1, $sql_len)));
  353. $sql_len = strlen($sql);
  354. if ($sql_len) {
  355. $i = -1;
  356. } else {
  357. // The submited statement(s) end(s) here
  358. return TRUE;
  359. }
  360. } // end else if (is delimiter)
  361. // ... then check for start of a string,...
  362. else if (($char == '"') || ($char == '\'') || ($char == '`')) {
  363. $in_string = TRUE;
  364. $nothing = FALSE;
  365. $string_start = $char;
  366. } // end else if (is start of string)
  367. elseif ($nothing) {
  368. $nothing = FALSE;
  369. }
  370. // loic1: send a fake header each 30 sec. to bypass browser timeout
  371. $time1 = time();
  372. if ($time1 >= $time0 + 30) {
  373. $time0 = $time1;
  374. header('X-pmaPing: Pong');
  375. } // end if
  376. } // end for
  377. // add any rest to the returned array
  378. if (!empty($sql) && preg_match('@[^[:space:]]+@', $sql)) {
  379. $ret[] = array('query' => $sql, 'empty' => $nothing);
  380. }
  381. return TRUE;
  382. } // end of the 'PMA_splitSqlFile()' function
  383. /**
  384. * Get an SQL file's contents
  385. *
  386. * This function bases its parsing on the pre-set format of the specific SQL files in
  387. * the install/upgrade procedure:
  388. * Lines starting with "--" are comments (but need to be taken into account as they also hold sections names)
  389. * Other lines are considered to be one-line-per-query lines (this is checked quickly by this function)
  390. * @param string File to parse (in the current directory)
  391. * @param string Section to return
  392. * @param boolean Print (true) or hide (false) error texts when they occur
  393. */
  394. function get_sql_file_contents($file,$section,$print_errors=true)
  395. {
  396. //check given parameters
  397. if(empty($file))
  398. {
  399. $error = "Missing name of file to parse in get_sql_file_contents()";
  400. if($print_errors) echo $error;
  401. return false;
  402. }
  403. if(!in_array($section,array('main','user','stats','scorm','course')))
  404. {
  405. $error = "Section '$section' is not authorized in get_sql_file_contents()";
  406. if($print_errors) echo $error;
  407. return false;
  408. }
  409. $filepath = getcwd().'/'.$file;
  410. if(!is_file($filepath) or !is_readable($filepath))
  411. {
  412. $error = "File $filepath not found or not readable in get_sql_file_contents()";
  413. if($print_errors) echo $error;
  414. return false;
  415. }
  416. //read the file in an array
  417. $file_contents = file($filepath);
  418. if(!is_array($file_contents) or count($file_contents)<1)
  419. {
  420. $error = "File $filepath looks empty in get_sql_file_contents()";
  421. if($print_errors) echo $error;
  422. return false;
  423. }
  424. //prepare the resulting array
  425. $section_contents = array();
  426. $record = false;
  427. foreach($file_contents as $index => $line)
  428. {
  429. if(substr($line,0,2) == '--')
  430. {
  431. //This is a comment. Check if section name, otherwise ignore
  432. $result = array();
  433. if(preg_match('/^-- xx([A-Z]*)xx/',$line,$result))
  434. { //we got a section name here
  435. if($result[1] == strtoupper($section))
  436. { //we have the section we are looking for, start recording
  437. $record = true;
  438. }
  439. else
  440. { //we have another section's header. If we were recording, stop now and exit loop
  441. if($record == true)
  442. {
  443. break;
  444. }
  445. $record = false;
  446. }
  447. }
  448. }else{
  449. if($record == true)
  450. {
  451. if(!empty($line)){
  452. $section_contents[] = $line;
  453. }
  454. }
  455. }
  456. }
  457. //now we have our section's SQL statements group ready, return
  458. return $section_contents;
  459. }
  460. function directory_to_array($directory)
  461. {
  462. $array_items = array();
  463. if ($handle = opendir($directory))
  464. {
  465. while (false !== ($file = readdir($handle)))
  466. {
  467. if ($file != "." && $file != "..")
  468. {
  469. if (is_dir($directory. "/" . $file))
  470. {
  471. $array_items = array_merge($array_items, directory_to_array($directory. "/" . $file));
  472. $file = $directory . "/" . $file;
  473. $array_items[] = preg_replace("/\/\//si", "/", $file);
  474. }
  475. }
  476. }
  477. closedir($handle);
  478. }
  479. return $array_items;
  480. }
  481. ?>