install_upgrade.lib.php 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542
  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. $seek = array('\\','//');
  167. $destroy = array('/','/');
  168. $rootSys = str_replace($seek,$destroy,realpath($pathForm).'/');
  169. $file_path = dirname(__FILE__).'/'.DOKEOS_CONFIG_FILENAME;
  170. $content = file_get_contents($file_path);
  171. $config['{DATE_GENERATED}'] = date('r');
  172. $config['{DATABASE_HOST}'] = $dbHostForm;
  173. $config['{DATABASE_USER}'] = $dbUsernameForm;
  174. $config['{DATABASE_PASSWORD}'] = $dbPassForm;
  175. $config['TRACKING_ENABLED'] = trueFalse($enableTrackingForm);
  176. $config['SINGLE_DATABASE'] = trueFalse($singleDbForm);
  177. $config['{COURSE_TABLE_PREFIX}'] = ($singleDbForm ? 'crs_' : '');
  178. $config['{DATABASE_GLUE}'] = ($singleDbForm ? '_' : '`.`');
  179. $config['{DATABASE_PREFIX}'] = $dbPrefixForm;
  180. $config['{DATABASE_MAIN}'] = $dbNameForm;
  181. $config['{DATABASE_STATS}'] = (($singleDbForm && empty($dbStatsForm)) ? $dbNameForm : $dbStatsForm);
  182. $config['{DATABASE_SCORM}'] = (($singleDbForm && empty($dbScormForm)) ? $dbNameForm : $dbScormForm);
  183. $config['{DATABASE_PERSONAL}'] =(($singleDbForm && empty($dbUserForm)) ? $dbNameForm : $dbUserForm);
  184. $config['{ROOT_WEB}'] = $urlForm;
  185. $config['{ROOT_SYS}'] = str_replace('\\', '/', $rootSys);
  186. $config['{URL_APPEND_PATH}'] = $urlAppendPath;
  187. $config['{PLATFORM_LANGUAGE}'] = $languageForm;
  188. $config['{SECURITY_KEY}'] = md5(uniqid(rand().time()));
  189. $config['{ENCRYPT_PASSWORD}'] = $encryptPassForm;
  190. $config['SESSION_LIFETIME'] = $session_lifetime;
  191. $config['{NEW_VERSION}'] = $new_version;
  192. $config['NEW_VERSION_STABLE'] = trueFalse($new_version_stable);
  193. foreach ($config as $key => $value)
  194. {
  195. $content = str_replace($key, $value, $content);
  196. }
  197. $fp = @ fopen($path, 'w');
  198. if (!$fp)
  199. {
  200. echo '<b><font color="red">Your script doesn\'t have write access to the config directory</font></b><br />
  201. <em>('.str_replace('\\', '/', realpath($path)).')</em><br /><br />
  202. You probably do not have write access on Dokeos root directory,
  203. i.e. you should <em>CHMOD 777</em> or <em>755</em> or <em>775</em>.<br /><br />
  204. Your problems can be related on two possible causes:<br />
  205. <ul>
  206. <li>Permission problems.<br />Try initially with <em>chmod -R 777</em> and increase restrictions gradually.</li>
  207. <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>
  208. </ul>
  209. <a href="http://www.dokeos.com/forum/" target="_blank">Read about this problem in Support Forum</a><br /><br />
  210. Please go back to step 5.
  211. <p><input type="submit" name="step5" value="&lt; Back" /></p>
  212. </td></tr></table></form></body></html>';
  213. exit ();
  214. }
  215. fwrite($fp, $content);
  216. fclose($fp);
  217. }
  218. /**
  219. * Creates the structure of the main database and fills it
  220. * with data. Placeholder symbols in the main database file
  221. * have to be replaced by the settings entered by the user during installation.
  222. *
  223. * @param array $installation_settings list of settings entered by the user
  224. */
  225. function load_main_database($installation_settings)
  226. {
  227. $dokeos_main_sql_file_string = file_get_contents(DOKEOS_MAIN_DATABASE_FILE);
  228. //replace symbolic parameters with user-specified values
  229. foreach ($installation_settings as $key => $value)
  230. {
  231. $dokeos_main_sql_file_string = str_replace($key, mysql_real_escape_string($value), $dokeos_main_sql_file_string);
  232. }
  233. //split in array of sql strings
  234. $sql_instructions = array();
  235. $success = split_sql_file($sql_instructions, $dokeos_main_sql_file_string);
  236. //execute the sql instructions
  237. $count = count($sql_instructions);
  238. for ($i = 0; $i < $count; $i++)
  239. {
  240. $this_sql_query = $sql_instructions[$i]['query'];
  241. mysql_query($this_sql_query);
  242. }
  243. }
  244. /**
  245. * Creates the structure of the stats database
  246. * @param string Name of the file containing the SQL script inside the install directory
  247. */
  248. function load_database_script($db_script)
  249. {
  250. $dokeos_sql_file_string = file_get_contents($db_script);
  251. //split in array of sql strings
  252. $sql_instructions = array();
  253. $success = split_sql_file($sql_instructions, $dokeos_sql_file_string);
  254. //execute the sql instructions
  255. $count = count($sql_instructions);
  256. for ($i = 0; $i < $count; $i++)
  257. {
  258. $this_sql_query = $sql_instructions[$i]['query'];
  259. mysql_query($this_sql_query);
  260. }
  261. }
  262. /**
  263. * Function copied and adapted from phpMyAdmin 2.6.0 PMA_splitSqlFile (also GNU GPL)
  264. *
  265. * Removes comment lines and splits up large sql files into individual queries
  266. *
  267. * Last revision: September 23, 2001 - gandon
  268. *
  269. * @param array the splitted sql commands
  270. * @param string the sql commands
  271. * @param integer the MySQL release number (because certains php3 versions
  272. * can't get the value of a constant from within a function)
  273. *
  274. * @return boolean always true
  275. *
  276. * @access public
  277. */
  278. function split_sql_file(&$ret, $sql)
  279. {
  280. // do not trim, see bug #1030644
  281. //$sql = trim($sql);
  282. $sql = rtrim($sql, "\n\r");
  283. $sql_len = strlen($sql);
  284. $char = '';
  285. $string_start = '';
  286. $in_string = FALSE;
  287. $nothing = TRUE;
  288. $time0 = time();
  289. for ($i = 0; $i < $sql_len; ++$i) {
  290. $char = $sql[$i];
  291. // We are in a string, check for not escaped end of strings except for
  292. // backquotes that can't be escaped
  293. if ($in_string) {
  294. for (;;) {
  295. $i = strpos($sql, $string_start, $i);
  296. // No end of string found -> add the current substring to the
  297. // returned array
  298. if (!$i) {
  299. $ret[] = $sql;
  300. return TRUE;
  301. }
  302. // Backquotes or no backslashes before quotes: it's indeed the
  303. // end of the string -> exit the loop
  304. else if ($string_start == '`' || $sql[$i-1] != '\\') {
  305. $string_start = '';
  306. $in_string = FALSE;
  307. break;
  308. }
  309. // one or more Backslashes before the presumed end of string...
  310. else {
  311. // ... first checks for escaped backslashes
  312. $j = 2;
  313. $escaped_backslash = FALSE;
  314. while ($i-$j > 0 && $sql[$i-$j] == '\\') {
  315. $escaped_backslash = !$escaped_backslash;
  316. $j++;
  317. }
  318. // ... if escaped backslashes: it's really the end of the
  319. // string -> exit the loop
  320. if ($escaped_backslash) {
  321. $string_start = '';
  322. $in_string = FALSE;
  323. break;
  324. }
  325. // ... else loop
  326. else {
  327. $i++;
  328. }
  329. } // end if...elseif...else
  330. } // end for
  331. } // end if (in string)
  332. // lets skip comments (/*, -- and #)
  333. else if (($char == '-' && $sql_len > $i + 2 && $sql[$i + 1] == '-' && $sql[$i + 2] <= ' ') || $char == '#' || ($char == '/' && $sql_len > $i + 1 && $sql[$i + 1] == '*')) {
  334. $i = strpos($sql, $char == '/' ? '*/' : "\n", $i);
  335. // didn't we hit end of string?
  336. if ($i === FALSE) {
  337. break;
  338. }
  339. if ($char == '/') $i++;
  340. }
  341. // We are not in a string, first check for delimiter...
  342. else if ($char == ';') {
  343. // if delimiter found, add the parsed part to the returned array
  344. $ret[] = array('query' => substr($sql, 0, $i), 'empty' => $nothing);
  345. $nothing = TRUE;
  346. $sql = ltrim(substr($sql, min($i + 1, $sql_len)));
  347. $sql_len = strlen($sql);
  348. if ($sql_len) {
  349. $i = -1;
  350. } else {
  351. // The submited statement(s) end(s) here
  352. return TRUE;
  353. }
  354. } // end else if (is delimiter)
  355. // ... then check for start of a string,...
  356. else if (($char == '"') || ($char == '\'') || ($char == '`')) {
  357. $in_string = TRUE;
  358. $nothing = FALSE;
  359. $string_start = $char;
  360. } // end else if (is start of string)
  361. elseif ($nothing) {
  362. $nothing = FALSE;
  363. }
  364. // loic1: send a fake header each 30 sec. to bypass browser timeout
  365. $time1 = time();
  366. if ($time1 >= $time0 + 30) {
  367. $time0 = $time1;
  368. header('X-pmaPing: Pong');
  369. } // end if
  370. } // end for
  371. // add any rest to the returned array
  372. if (!empty($sql) && preg_match('@[^[:space:]]+@', $sql)) {
  373. $ret[] = array('query' => $sql, 'empty' => $nothing);
  374. }
  375. return TRUE;
  376. } // end of the 'PMA_splitSqlFile()' function
  377. /**
  378. * Get an SQL file's contents
  379. *
  380. * This function bases its parsing on the pre-set format of the specific SQL files in
  381. * the install/upgrade procedure:
  382. * Lines starting with "--" are comments (but need to be taken into account as they also hold sections names)
  383. * Other lines are considered to be one-line-per-query lines (this is checked quickly by this function)
  384. * @param string File to parse (in the current directory)
  385. * @param string Section to return
  386. * @param boolean Print (true) or hide (false) error texts when they occur
  387. */
  388. function get_sql_file_contents($file,$section,$print_errors=true)
  389. {
  390. //check given parameters
  391. if(empty($file))
  392. {
  393. $error = "Missing name of file to parse in get_sql_file_contents()";
  394. if($print_errors) echo $error;
  395. return false;
  396. }
  397. if(!in_array($section,array('main','user','stats','scorm','course')))
  398. {
  399. $error = "Section '$section' is not authorized in get_sql_file_contents()";
  400. if($print_errors) echo $error;
  401. return false;
  402. }
  403. $filepath = getcwd().'/'.$file;
  404. if(!is_file($filepath) or !is_readable($filepath))
  405. {
  406. $error = "File $filepath not found or not readable in get_sql_file_contents()";
  407. if($print_errors) echo $error;
  408. return false;
  409. }
  410. //read the file in an array
  411. $file_contents = file($filepath);
  412. if(!is_array($file_contents) or count($file_contents)<1)
  413. {
  414. $error = "File $filepath looks empty in get_sql_file_contents()";
  415. if($print_errors) echo $error;
  416. return false;
  417. }
  418. //prepare the resulting array
  419. $section_contents = array();
  420. $record = false;
  421. foreach($file_contents as $index => $line)
  422. {
  423. if(substr($line,0,2) == '--')
  424. {
  425. //This is a comment. Check if section name, otherwise ignore
  426. $result = array();
  427. if(preg_match('/^-- xx([A-Z]*)xx/',$line,$result))
  428. { //we got a section name here
  429. if($result[1] == strtoupper($section))
  430. { //we have the section we are looking for, start recording
  431. $record = true;
  432. }
  433. else
  434. { //we have another section's header. If we were recording, stop now and exit loop
  435. if($record == true)
  436. {
  437. break;
  438. }
  439. $record = false;
  440. }
  441. }
  442. }else{
  443. if($record == true)
  444. {
  445. if(!empty($line)){
  446. $section_contents[] = $line;
  447. }
  448. }
  449. }
  450. }
  451. //now we have our section's SQL statements group ready, return
  452. return $section_contents;
  453. }
  454. function directory_to_array($directory)
  455. {
  456. $array_items = array();
  457. if ($handle = opendir($directory))
  458. {
  459. while (false !== ($file = readdir($handle)))
  460. {
  461. if ($file != "." && $file != "..")
  462. {
  463. if (is_dir($directory. "/" . $file))
  464. {
  465. $array_items = array_merge($array_items, directory_to_array($directory. "/" . $file));
  466. $file = $directory . "/" . $file;
  467. $array_items[] = preg_replace("/\/\//si", "/", $file);
  468. }
  469. }
  470. }
  471. closedir($handle);
  472. }
  473. return $array_items;
  474. }
  475. /**
  476. * Adds a new document to the database - specific to version 1.8.0
  477. *
  478. * @param array $_course
  479. * @param string $path
  480. * @param string $filetype
  481. * @param int $filesize
  482. * @param string $title
  483. * @return id if inserted document
  484. */
  485. function add_document_180($_course,$path,$filetype,$filesize,$title,$comment=NULL)
  486. {
  487. $table_document = Database::get_course_table(TABLE_DOCUMENT,$_course['dbName']);
  488. $sql="INSERT INTO $table_document
  489. (`path`,`filetype`,`size`,`title`, `comment`)
  490. VALUES ('$path','$filetype','$filesize','".
  491. Database::escape_string($title)."', '$comment')";
  492. if(api_sql_query($sql,__FILE__,__LINE__))
  493. {
  494. //display_message("Added to database (id ".mysql_insert_id().")!");
  495. return mysql_insert_id();
  496. }
  497. else
  498. {
  499. //display_error("The uploaded file could not be added to the database (".mysql_error().")!");
  500. return false;
  501. }
  502. }
  503. ?>