install_upgrade.lib.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381
  1. <?php
  2. /*
  3. ==============================================================================
  4. Dokeos - elearning and course management software
  5. Copyright (c) 2004-2005 Dokeos S.A.
  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, 44 rue des palais, 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 $dokeos_version;
  147. global $dbHostForm;
  148. global $dbUsernameForm;
  149. global $dbPassForm;
  150. global $enableTrackingForm;
  151. global $singleDbForm;
  152. global $dbPrefixForm;
  153. global $dbNameForm;
  154. global $dbStatsForm;
  155. global $dbScormForm;
  156. global $dbUserForm;
  157. global $urlForm;
  158. global $pathForm;
  159. global $urlAppendPath;
  160. global $languageForm;
  161. global $encryptPassForm;
  162. $file_path = dirname(__FILE__).'/'.DOKEOS_CONFIG_FILENAME;
  163. $content = file_get_contents($file_path);
  164. $config['{DATE_GENERATED}'] = date('r');
  165. $config['{DATABASE_HOST}'] = $dbHostForm;
  166. $config['{DATABASE_USER}'] = $dbUsernameForm;
  167. $config['{DATABASE_PASSWORD}'] = $dbPassForm;
  168. $config['{TRACKING_ENABLED}'] = trueFalse($enableTrackingForm);
  169. $config['{SINGLE_DATABASE}'] = trueFalse($singleDbForm);
  170. $config['{COURSE_TABLE_PREFIX}'] = ($singleDbForm ? 'crs_' : '');
  171. $config['{DATABASE_GLUE}'] = ($singleDbForm ? '_' : '`.`');
  172. $config['{DATABASE_PREFIX}'] = $dbPrefixForm;
  173. $config['{DATABASE_MAIN}'] = $dbNameForm;
  174. $config['{DATABASE_STATS}'] = ($singleDbForm ? $dbNameForm : $dbStatsForm);
  175. $config['{DATABASE_SCORM}'] = ($singleDbForm ? $dbNameForm : $dbScormForm);
  176. $config['{DATABASE_PERSONAL}'] =($singleDbForm ? $dbNameForm : $dbUserForm);
  177. $config['{ROOT_WEB}'] = $urlForm;
  178. $config['{ROOT_SYS}'] = str_replace('\\', '/', realpath($pathForm).'/');
  179. $config['{URL_APPEND_PATH}'] = $urlAppendPath;
  180. $config['{GARBAGE_DIR}'] = str_replace("\\", "/", realpath("../garbage/")."/");
  181. $config['{PLATFORM_LANGUAGE}'] = $languageForm;
  182. $config['{SECURITY_KEY}'] = md5(uniqid(rand().time()));
  183. $config['{ENCRYPT_PASSWORD}'] = trueFalse($encryptPassForm);
  184. foreach ($config as $key => $value)
  185. {
  186. $content = str_replace($key, $value, $content);
  187. }
  188. $fp = @ fopen($path, 'w');
  189. if (!$fp)
  190. {
  191. echo '<b><font color="red">Your script doesn\'t have write access to the config directory</font></b><br />
  192. <em>('.str_replace('\\', '/', realpath($path)).')</em><br /><br />
  193. You probably do not have write access on Dokeos root directory,
  194. i.e. you should <em>CHMOD 777</em> or <em>755</em> or <em>775</em>.<br /><br />
  195. Your problems can be related on two possible causes:<br />
  196. <ul>
  197. <li>Permission problems.<br />Try initially with <em>chmod -R 777</em> and increase restrictions gradually.</li>
  198. <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>
  199. </ul>
  200. <a href="http://www.dokeos.com/forum/" target="_blank">Read about this problem in Support Forum</a><br /><br />
  201. Please go back to step 5.
  202. <p><input type="submit" name="step5" value="&lt; Back" /></p>
  203. </td></tr></table></form></body></html>';
  204. exit ();
  205. }
  206. fwrite($fp, $content);
  207. fclose($fp);
  208. }
  209. /**
  210. * Creates the structure of the main database and fills it
  211. * with data. Placeholder symbols in the main database file
  212. * have to be replaced by the settings entered by the user during installation.
  213. *
  214. * @param array $installation_settings list of settings entered by the user
  215. */
  216. function load_main_database($installation_settings)
  217. {
  218. $dokeos_main_sql_file_string = file_get_contents(DOKEOS_MAIN_DATABASE_FILE);
  219. //replace symbolic parameters with user-specified values
  220. foreach ($installation_settings as $key => $value)
  221. {
  222. $dokeos_main_sql_file_string = str_replace($key, mysql_real_escape_string($value), $dokeos_main_sql_file_string);
  223. }
  224. //split in array of sql strings
  225. $sql_instructions = array();
  226. $success = split_sql_file($sql_instructions, $dokeos_main_sql_file_string);
  227. //execute the sql instructions
  228. $count = count($sql_instructions);
  229. for ($i = 0; $i < $count; $i++)
  230. {
  231. $this_sql_query = $sql_instructions[$i]['query'];
  232. mysql_query($this_sql_query);
  233. }
  234. }
  235. /**
  236. * Function copied and adapted from phpMyAdmin 2.6.0 PMA_splitSqlFile (also GNU GPL)
  237. *
  238. * Removes comment lines and splits up large sql files into individual queries
  239. *
  240. * Last revision: September 23, 2001 - gandon
  241. *
  242. * @param array the splitted sql commands
  243. * @param string the sql commands
  244. * @param integer the MySQL release number (because certains php3 versions
  245. * can't get the value of a constant from within a function)
  246. *
  247. * @return boolean always true
  248. *
  249. * @access public
  250. */
  251. function split_sql_file(&$ret, $sql)
  252. {
  253. // do not trim, see bug #1030644
  254. //$sql = trim($sql);
  255. $sql = rtrim($sql, "\n\r");
  256. $sql_len = strlen($sql);
  257. $char = '';
  258. $string_start = '';
  259. $in_string = FALSE;
  260. $nothing = TRUE;
  261. $time0 = time();
  262. for ($i = 0; $i < $sql_len; ++$i) {
  263. $char = $sql[$i];
  264. // We are in a string, check for not escaped end of strings except for
  265. // backquotes that can't be escaped
  266. if ($in_string) {
  267. for (;;) {
  268. $i = strpos($sql, $string_start, $i);
  269. // No end of string found -> add the current substring to the
  270. // returned array
  271. if (!$i) {
  272. $ret[] = $sql;
  273. return TRUE;
  274. }
  275. // Backquotes or no backslashes before quotes: it's indeed the
  276. // end of the string -> exit the loop
  277. else if ($string_start == '`' || $sql[$i-1] != '\\') {
  278. $string_start = '';
  279. $in_string = FALSE;
  280. break;
  281. }
  282. // one or more Backslashes before the presumed end of string...
  283. else {
  284. // ... first checks for escaped backslashes
  285. $j = 2;
  286. $escaped_backslash = FALSE;
  287. while ($i-$j > 0 && $sql[$i-$j] == '\\') {
  288. $escaped_backslash = !$escaped_backslash;
  289. $j++;
  290. }
  291. // ... if escaped backslashes: it's really the end of the
  292. // string -> exit the loop
  293. if ($escaped_backslash) {
  294. $string_start = '';
  295. $in_string = FALSE;
  296. break;
  297. }
  298. // ... else loop
  299. else {
  300. $i++;
  301. }
  302. } // end if...elseif...else
  303. } // end for
  304. } // end if (in string)
  305. // lets skip comments (/*, -- and #)
  306. else if (($char == '-' && $sql_len > $i + 2 && $sql[$i + 1] == '-' && $sql[$i + 2] <= ' ') || $char == '#' || ($char == '/' && $sql_len > $i + 1 && $sql[$i + 1] == '*')) {
  307. $i = strpos($sql, $char == '/' ? '*/' : "\n", $i);
  308. // didn't we hit end of string?
  309. if ($i === FALSE) {
  310. break;
  311. }
  312. if ($char == '/') $i++;
  313. }
  314. // We are not in a string, first check for delimiter...
  315. else if ($char == ';') {
  316. // if delimiter found, add the parsed part to the returned array
  317. $ret[] = array('query' => substr($sql, 0, $i), 'empty' => $nothing);
  318. $nothing = TRUE;
  319. $sql = ltrim(substr($sql, min($i + 1, $sql_len)));
  320. $sql_len = strlen($sql);
  321. if ($sql_len) {
  322. $i = -1;
  323. } else {
  324. // The submited statement(s) end(s) here
  325. return TRUE;
  326. }
  327. } // end else if (is delimiter)
  328. // ... then check for start of a string,...
  329. else if (($char == '"') || ($char == '\'') || ($char == '`')) {
  330. $in_string = TRUE;
  331. $nothing = FALSE;
  332. $string_start = $char;
  333. } // end else if (is start of string)
  334. elseif ($nothing) {
  335. $nothing = FALSE;
  336. }
  337. // loic1: send a fake header each 30 sec. to bypass browser timeout
  338. $time1 = time();
  339. if ($time1 >= $time0 + 30) {
  340. $time0 = $time1;
  341. header('X-pmaPing: Pong');
  342. } // end if
  343. } // end for
  344. // add any rest to the returned array
  345. if (!empty($sql) && preg_match('@[^[:space:]]+@', $sql)) {
  346. $ret[] = array('query' => $sql, 'empty' => $nothing);
  347. }
  348. return TRUE;
  349. } // end of the 'PMA_splitSqlFile()' function
  350. ?>