install_upgrade.lib.php 19 KB

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