PageRenderTime 63ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 0ms

/community/www/install/install.php

https://github.com/svn2github/efront-lms
PHP | 1434 lines | 1291 code | 8 blank | 135 comment | 152 complexity | 19fa2f1d90f4cdd8d9afd4f61ad2da24 MD5 | raw file
Possible License(s): BSD-3-Clause, MPL-2.0-no-copyleft-exception, LGPL-3.0

Large files files are truncated, but you can click here to view the full file

  1. <?php
  2. /**
  3. * $LastChangedRevision$
  4. * Installation file
  5. *
  6. * This file is used to perform the installation
  7. * @package eFront
  8. */
  9. session_cache_limiter('none'); //Initialize session
  10. session_start();
  11. Installation :: setErrorReporting();
  12. //error_reporting(E_ALL);
  13. /*The inclusion directory*/
  14. $path = "../../libraries/";
  15. //Read current version from sample_config file
  16. preg_match("/define\('G_VERSION_NUM', '(.*)'\);/", file_get_contents("sample_config.php"), $matches);
  17. define("G_VERSION_NUM", $matches[1]);
  18. //Read current build from globals.php file
  19. //preg_match('/\$LastChangedRevision$matches);
  20. preg_match('/\$build = (\d+);/', file_get_contents($path."globals.php"), $matches);
  21. define("G_BUILD", $matches[1]);
  22. $versionTypes = array('educational' => 'Educational',
  23. 'enterprise' => 'Enterprise',
  24. 'standard' => 'Community++',
  25. 'community' => 'Community');
  26. define("G_VERSIONTYPE", 'community');
  27. /*Disable output buffering during installation for better error handling*/
  28. define("NO_OUTPUT_BUFFERING", true);
  29. //Set some ini properties we need
  30. ini_set("display_errors", true);
  31. ini_set('include_path', $path.'../PEAR/');
  32. //ini_set("memory_limit", "-1");
  33. ini_get("max_execution_time") < 120 ? ini_set("max_execution_time", "120") : null;
  34. //It is imperative that the smarty directory is writable in order to continue
  35. if (!is_writable($path.'smarty/themes_cache')) {
  36. echo Installation :: printErrorMessage("Directory <b>".realpath($path.'smarty/themes_cache')."</b> must be writable by the server in order to continue");
  37. exit;
  38. }
  39. //Check whether we are on http or https
  40. isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on' ? $protocol = 'https' : $protocol = 'http';
  41. //Set the servername
  42. define("G_SERVERNAME", dirname(dirname($protocol.'://'.$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF'])).'/');
  43. //Check if smarty and language file exist, and halt program execution if it is not present
  44. if (is_file($path."smarty/smarty_config.php") && is_file($path."language/lang-english.php.inc")) {
  45. /**The default theme path*/
  46. define("G_THEMESPATH", str_replace("\\", "/", dirname(dirname(dirname(__FILE__)))."/www/themes/"));
  47. /** The default theme path*/
  48. define("G_DEFAULTTHEMEPATH", G_THEMESPATH."default/");
  49. /** The default theme url*/
  50. define("G_DEFAULTTHEMEURL", "themes/default/");
  51. $currentTheme = "efront2013";
  52. /**The current theme path*/
  53. define("G_CURRENTTHEMEPATH", G_THEMESPATH.$currentTheme."/");
  54. /**The current theme url*/
  55. define("G_CURRENTTHEMEURL", "themes/".$currentTheme."/");
  56. /**The current theme css url*/
  57. define("G_CURRENTTHEMECSS", G_CURRENTTHEMEURL."css/css_global.css");
  58. /**The current theme cache path*/
  59. define("G_CURRENTTHEMECACHE", dirname(dirname(dirname(__FILE__)))."/libraries/smarty/themes_cache/".$currentTheme."/");
  60. /**The smarty libraries*/
  61. require_once $path."smarty/libs/Smarty.class.php";
  62. require_once $path."smarty/smarty_config.php";
  63. /**The default language file*/
  64. require_once $path."language/lang-english.php.inc";
  65. } else {
  66. echo Installation :: printErrorMessage("Some files are missing, installation cannot continue");
  67. exit;
  68. }
  69. //If we asked for unattended installation, there must be a 2nd parameter with the configuration details or performing an upgrade
  70. if (isset($_GET['unattended']) && !isset($_GET['upgrade']) && (!isset($_GET['config']) || !is_file(basename($_GET['config'])))) {
  71. unset($_GET['unattended']);
  72. }
  73. $smarty -> assign("T_VERSION_TYPE", $versionTypes[G_VERSIONTYPE]);
  74. if (is_file($path."configuration.php")) {
  75. $smarty -> assign("T_INSTALLATION_OPTIONS", array(array('text' => 'Emergency restore', 'image' => "16x16/undo.png", 'href' => 'install/'.basename($_SERVER['PHP_SELF'])."?restore=1")));
  76. $smarty -> assign("T_CONFIGURATION_EXISTS", true);
  77. }
  78. if ((isset($_GET['step']) && $_GET['step'] == 1) || isset($_GET['unattended'])) {
  79. if (is_file('../php.ini') && !is_file('php.ini') && copy('../php.ini', 'php.ini') && !isset($_GET['unattended'])) {
  80. header("location:".$_SERVER['PHP_SELF']."?step=1".(isset($_GET['upgrade']) ? '&upgrade=1' : ''));
  81. }
  82. $exclude_normal = true;
  83. require_once $path."includes/check_status.php";
  84. Installation :: fix($settings_mandatory, 'local');
  85. if ($_GET['mode'] != 'none' && sizeof($settings_mandatory) > 0) {
  86. if (!$_GET['mode']) {
  87. Installation :: fix($settings_mandatory, 'local');
  88. header("location:".$_SERVER['PHP_SELF']."?step=1&mode=htaccess".(isset($_GET['upgrade']) ? '&upgrade=1' : ''));
  89. } else {
  90. Installation :: fix($settings_mandatory, 'htaccess');
  91. header("location:".$_SERVER['PHP_SELF']."?step=1&mode=none".(isset($_GET['upgrade']) ? '&upgrade=1' : ''));
  92. }
  93. } else if ($_GET['mode'] == 'none' && sizeof($settings_mandatory) > 0) {
  94. $message = 'The system tried to automatically fix the errors shown below by applying custom php.ini and .htaccess files, but was unable to. Please fix the following errors manually.';
  95. } else if ($_GET['mode'] == 'none') {
  96. $message = 'The system automatically changed some php parameters to meet installation prerequisites by applying a local php.ini and/or a .htaccess file';
  97. $message_type = 'success';
  98. }
  99. if (!$install) {
  100. $smarty -> assign("T_MISSING_SETTINGS", true);
  101. }
  102. }
  103. if ((isset($_GET['step']) && $_GET['step'] == 2) || isset($_GET['unattended'])) {
  104. //unset session, if any
  105. // unset($_SESSION);
  106. // session_destroy();
  107. /** HTML_QuickForm Class*/
  108. require_once 'HTML/QuickForm.php';
  109. /** HTML_QuickForm Smarty renderer class*/
  110. require_once 'HTML/QuickForm/Renderer/ArraySmarty.php';
  111. /**ADODB database abstraction class*/
  112. require_once($path.'adodb/adodb.inc.php');
  113. /**ADODB exceptions class*/
  114. require_once($path.'adodb/adodb-exceptions.inc.php');
  115. /**Various tools*/
  116. require_once($path.'tools.php');
  117. if ($_GET['upgrade']) {
  118. $currentVersion = Installation :: checkCurrentVersion();
  119. $smarty -> assign("T_CURRENT_VERSION", $currentVersion);
  120. }
  121. //Initialize ADODB
  122. $ADODB_CACHE_DIR = $path."adodb/cache";
  123. $ADODB_FETCH_MODE = ADODB_FETCH_ASSOC;
  124. $form = new HTML_QuickForm("info_form", "post", $_SERVER['PHP_SELF']."?step=2".($_GET['upgrade'] ? '&upgrade=1': ''), "", "class = 'indexForm'", true);
  125. $form -> registerRule('checkParameter', 'callback', 'eF_checkParameter'); //Register this rule for checking user input with our function, eF_checkParameter
  126. $form -> addElement('select', 'db_type', null, array('mysql' => 'MySQL', 'mssql' => 'MSSQL'));
  127. //$form -> addRule('db_type', 'The field "database type" is mandatory', 'required', null, 'client'); //The database type can only be string and is mandatory
  128. $form -> addRule('db_type', 'Invalid database type', 'checkParameter', 'string'); //The database type can only be string and is mandatory
  129. $form -> setDefaults(array('db_type' => 'mysql'));
  130. $form -> freeze(array('db_type')); //Freeze this element, since it can't change for now
  131. $form -> addElement('text', 'db_host', null, 'class = "inputText"');
  132. $form -> addRule('db_host', 'The field "Database host" is mandatory', 'required', null, 'client'); //The database type can only be string and is mandatory
  133. //$form -> addRule('db_host', 'Invalid database host', 'checkParameter', 'alnum_general'); //The database host can only be string and is mandatory
  134. $form -> addElement('text', 'db_user', null, 'class = "inputText"');
  135. $form -> addRule('db_user', 'The field "Database user" is mandatory', 'required', null, 'client'); //The database type can only be string and is mandatory
  136. $form -> addRule('db_user', 'Invalid database user', 'checkParameter', 'alnum'); //The database user can only be string
  137. $form -> addElement('password', 'db_password', null, 'class = "inputText"');
  138. $form -> addElement('text', 'db_name', null, 'class = "inputText"');
  139. $form -> addRule('db_name', 'The field "Database name" is mandatory', 'required', null, 'client'); //The database type can only be string and is mandatory
  140. $form -> addRule('db_name', 'Invalid database name', 'checkParameter', 'alnum'); //The database name can only be string
  141. $form -> addElement('text', 'db_prefix', null, 'class = "inputText"');
  142. $form -> addRule('db_prefix', 'Invalid database prefix', 'checkParameter', 'alnum'); //The database name can only be string
  143. if ($_GET['upgrade']) {
  144. $form -> addElement('text', 'old_db_name', null, 'class = "inputText"');
  145. $form -> addRule('old_db_name', 'The field "Upgrade from database" is mandatory', 'required', null, 'client'); //The database type can only be string and is mandatory
  146. $form -> addRule('old_db_name', 'Invalid database name', 'checkParameter', 'alnum_general'); //The database name can only be string
  147. //$form -> addElement('checkbox', 'upgrade_search', null, null, 'style = "vertical-align:middle"');
  148. $form -> addElement('checkbox', 'backup', null, null, 'style = "vertical-align:middle"');
  149. } else {
  150. $form -> addElement('text', 'admin_name', null, 'class = "inputText"');
  151. $form -> addRule('admin_name', 'The field "Administrator user name" is mandatory', 'required', null, 'client');
  152. $form -> addRule('admin_name', 'Invalid administrator user name', 'checkParameter', 'login');
  153. $form -> addElement('password', 'admin_password', null, 'class = "inputText"');
  154. $form -> addRule('admin_password', 'The field "Administrator password" is mandatory', 'required', null, 'client');
  155. $form -> addElement('text', 'admin_email', null, 'class = "inputText"');
  156. $form -> addRule('admin_email', 'The field "Administrator email" is mandatory', 'required', null, 'client');
  157. $form -> addRule('admin_email', 'Invalid administrator email', 'checkParameter', 'email');
  158. $form -> addElement('checkbox', 'default_data', null, null, 'style = "vertical-align:middle"');
  159. }
  160. $form -> addElement('submit', 'submit_form', $_GET['upgrade'] ? 'Upgrade' : 'Install', 'class = "flatButton"');
  161. $form -> addElement('submit', 'delete_form', 'Delete existing tables and retry', 'class = "flatButton"');
  162. $form -> setDefaults(array('db_host' => 'localhost', //$_SERVER['HTTP_HOST']
  163. 'db_user' => 'root',
  164. 'db_password' => '',
  165. 'db_name' => 'efront',
  166. 'db_prefix' => '',
  167. 'admin_name' => 'admin',
  168. 'backup' => true,
  169. //'upgrade_search' => true,
  170. 'default_data' => true));
  171. if ($_GET['upgrade']) {
  172. $form -> setDefaults($currentVersion);
  173. $form -> setDefaults(array('old_db_name' => $currentVersion['db_name']));
  174. }
  175. $form->disable_csrf = true;
  176. if (($form -> isSubmitted() && $form -> validate()) || isset($_GET['unattended'])) {
  177. try {
  178. if (function_exists('apc_clear_cache')) {
  179. apc_clear_cache('user');
  180. }
  181. $db = ADONewConnection($form -> exportValue('db_type')); //Set Connection parameter to "mysql"
  182. if (isset($_GET['unattended'])) {
  183. if (isset($_GET['upgrade'])) {
  184. $values = $currentVersion;
  185. $values['old_db_name'] = $values['db_name'];
  186. } else {
  187. $contents = file(basename($_GET['config']));
  188. $values = array();
  189. foreach ($contents as $value) {
  190. $value = explode("=", $value);
  191. $values[trim($value[0])] = trim($value[1]);
  192. }
  193. }
  194. } else {
  195. $values = $form -> exportValues();
  196. }
  197. //first, try to connect to the host
  198. $db -> NConnect($values['db_host'], $values['db_user'], $values['db_password']);
  199. if ($values['db_type'] == 'mysql') {
  200. $db -> Execute("SET NAMES 'UTF8'");
  201. }
  202. $file_contents = trim(file_get_contents("sql_".$values['db_type'].".txt")); //Get the sql queries text
  203. $file_contents = explode(';',$file_contents); //Form the sql queries, by splitting each CREATE statement
  204. if (!end($file_contents)) {
  205. array_pop($file_contents); //Remove last element, if it is an empty array (which is usually the case)
  206. }
  207. //Create the new database and database tables, either if it is a clean install, or if it is an upgrade in a different database
  208. if (!$_GET['upgrade'] || $values['old_db_name'] != $values['db_name']) {
  209. //Check whether the db exists. If not, create it
  210. try {
  211. $db -> NConnect($values['db_host'], $values['db_user'], $values['db_password'], $values['db_name']);
  212. } catch (Exception $e) {
  213. $db -> Execute("create database ".$values['db_name']." DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci"); //Create the new database
  214. $db -> NConnect($values['db_host'], $values['db_user'], $values['db_password'], $values['db_name']);
  215. }
  216. if ($values['db_type'] == 'mysql') {
  217. $db -> Execute("SET NAMES 'UTF8'");
  218. }
  219. foreach ($file_contents as $query) {
  220. //Apply the selected prefix to table names
  221. $query = preg_replace('/CREATE TABLE (\w+) (.*)/', 'CREATE TABLE '.$values['db_prefix'].'$1 $2', $query);
  222. preg_match('/CREATE TABLE (\w+) .*/', $query, $matches);
  223. try {
  224. if (isset($values['delete_form']) && $matches[1]) {
  225. //$db -> Execute("drop table if exists ".$matches[1]);
  226. Installation :: dropTableIfExists($matches[1], $values['db_type']);
  227. }
  228. $db -> Execute($query);
  229. } catch (Exception $e) {
  230. $failed_tables[] = $e -> msg; //Each failed query will not halt the execution, but will be recorded to this table
  231. }
  232. }
  233. if (isset($failed_tables)) { //If there were any errors, assign them to smarty to be displayed
  234. $smarty -> assign('T_FAILED_TABLES', 1);
  235. throw new Exception(implode(', ', $failed_tables));
  236. }
  237. }
  238. if ($_GET['upgrade']) {
  239. $db -> NConnect($values['db_host'], $values['db_user'], $values['db_password'], $values['db_name']);
  240. $db -> Execute("SET NAMES 'UTF8'");
  241. try {
  242. $db -> Execute("truncate cache");
  243. } catch (Exception $e) {} //If the table could not be emptied, it doesn't exist, which is ok
  244. $dbVersion = $db -> getCol("select value from configuration where name = 'database_version'");
  245. if (!empty($dbVersion)) {
  246. $dbVersion = $dbVersion[0];
  247. } else {
  248. $dbVersion = '3.5';
  249. }
  250. //Include old configuration file in order to perform the automatic backup, use database functions, etc
  251. require_once($path."configuration.php");
  252. if ($values['backup'] || isset($_GET['unattended'])) {
  253. $backupFile = EfrontSystem :: backup($values['db_name'].'_'.time().'.zip'); //Auto backup database
  254. }
  255. if (version_compare($dbVersion, '3.6.11') == -1) {
  256. Installation :: createTable('themes', $file_contents);
  257. //Get all the database tables, except for the temporary installation tables
  258. $result = $db -> Execute("show table status"); //Get the database tables
  259. while (!$result->EOF) {
  260. if (strpos($result -> fields['Name'], 'install_') !== 0) {
  261. $tables[] = $result -> fields['Name'];
  262. }
  263. $result -> MoveNext();
  264. }
  265. //We are upgrading onto the same database.
  266. if ($values['old_db_name'] == $values['db_name']) {
  267. $db -> NConnect($values['db_host'], $values['db_user'], $values['db_password'], $values['db_name']);
  268. $db -> Execute("SET NAMES 'UTF8'");
  269. //ini_set("memory_limit", "-1");
  270. //Delete old temporary installation tables
  271. foreach ($tables as $table) {
  272. try {
  273. $result = $db -> Execute("drop table install_$table"); //Delete temporary installation tables, if such exist
  274. } catch (Exception $e) {
  275. } //If the table could not be deleted, it doesn't exist
  276. }
  277. //Create temporary tables with the 'install_' prefix
  278. foreach ($file_contents as $query) {
  279. //Apply the selected prefix to table names
  280. $matches = array();
  281. preg_match('/CREATE TABLE (\w+) .*/', $query, $matches);
  282. $queryCreate = preg_replace('/CREATE TABLE (\w+) (.*)/', 'CREATE TABLE if not exists '.$values['db_prefix'].'$1 $2', $query);
  283. $queryCreateTemp = preg_replace('/(.*CREATE TABLE )(\w+)( .*)/', '$1 '.$values['db_prefix'].'install_$2 $3', $query); //Use temporary installation tables
  284. try {
  285. $db -> Execute($queryCreateTemp);
  286. $db -> Execute($queryCreate);
  287. $newTables[] = $matches[1];
  288. } catch (Exception $e) {
  289. $failed_tables[] = $e -> msg; //Each failed query will not halt the execution, but will be recorded to this table
  290. }
  291. }
  292. if (isset($failed_tables)) { //If there were any errors, assign them to smarty to be displayed
  293. $smarty -> assign('T_FAILED_TABLES', 1);
  294. throw new Exception(implode(', ', $failed_tables));
  295. }
  296. $existingTables = array_diff($tables, $newTables); //These are tables pre-existing in the database, which should remain intact
  297. $userProfile = eF_getTableData("user_profile", "*"); //Get any additional user profile fields
  298. } else {
  299. //The inclusion of configuration.php triggered the creation of a new configuration file. Truncate it in the new database
  300. $result = $db -> Execute("truncate configuration");
  301. //Special handling of modules table
  302. $db -> NConnect($values['db_host'], $values['db_user'], $values['db_password'], $values['old_db_name']);
  303. $db -> Execute("SET NAMES 'UTF8'");
  304. $existingTables = $db -> GetCol("show tables");
  305. $moduleTables = array_diff($existingTables, $tables);
  306. $moduleTableQueries = array();
  307. foreach ($moduleTables as $table) {
  308. $result = $db -> execute("show create table ".$table);
  309. $moduleTableQueries[$table] = $result -> getAll();
  310. $tables[] = $table;
  311. }
  312. $userProfile = eF_getTableData("user_profile", "*"); //Get any additional user profile fields
  313. $db -> NConnect($values['db_host'], $values['db_user'], $values['db_password'], $values['db_name']);
  314. $db -> Execute("SET NAMES 'UTF8'");
  315. //Delete old temporary installation tables
  316. foreach ($tables as $key => $table) {
  317. try {
  318. $result = $db -> Execute("drop table install_$table"); //Delete temporary installation tables, if such exist
  319. } catch (Exception $e) {
  320. } //If the table could not be deleted, it doesn't exist
  321. if (preg_match("/^.*_view$/", $table)) {
  322. unset($tables[$key]);
  323. }
  324. }
  325. //Create missing tables in the target database
  326. foreach ($moduleTableQueries as $query) {
  327. if (isset($query[0]['Create Table'])) {
  328. $db -> Execute($query[0]['Create Table']);
  329. }
  330. }
  331. //For every table that already exists in the target database, we must empty otherwise we may end up with duplicate values
  332. $commonTables = array_intersect($existingTables, $tables);
  333. foreach ($commonTables as $table) {
  334. try {
  335. $db -> Execute("truncate table $table");
  336. } catch (Exception $e) {/*Do nothing, if for example it's views we are trying to truncate*/
  337. }
  338. }
  339. }
  340. for ($i = 0; $i < sizeof($userProfile); $i++) {
  341. $userProfile[$i]['mandatory'] ? $mandatory = "NOT NULL" : $mandatory = "NULL";
  342. $userProfile[$i]['default_value'] ? $default = $userProfile[$i]['default_value'] : $default = false;
  343. try {
  344. if ($values['old_db_name'] == $values['db_name']) {
  345. $db -> Execute("ALTER TABLE install_users ADD ".$userProfile[$i]['name']." varchar(255) ".$mandatory." DEFAULT '".$default."'");
  346. } else {
  347. $db -> Execute("ALTER TABLE users ADD ".$userProfile[$i]['name']." varchar(255) ".$mandatory." DEFAULT '".$default."'");
  348. }
  349. } catch (Exception $e) {
  350. $failed_updates[] = $e -> msg;
  351. }
  352. }
  353. unset($tables['userpage']); //deprecated table
  354. $upgradedTables = array();
  355. foreach ($tables as $table) {
  356. if ($values['old_db_name'] == $values['db_name']) {
  357. if (!in_array($table, $existingTables)) {
  358. //Installation :: updateDBTable($table, "install_".$table);
  359. if (Installation :: quickUpgrade($table)) {
  360. $upgradedTables[] = $table;
  361. }
  362. }
  363. } else {
  364. $oldDB = array('db_host' => $values['db_host'], 'db_user' => $values['db_user'], 'db_password' => $values['db_password'], 'db_name' => $values['old_db_name']);
  365. $newDB = array('db_host' => $values['db_host'], 'db_user' => $values['db_user'], 'db_password' => $values['db_password'], 'db_name' => $values['db_name']);
  366. Installation :: updateDBTable($table, $table, $oldDB, $newDB);
  367. }
  368. }
  369. //In any case, Restore connection to the normal database
  370. $GLOBALS['db'] -> NConnect($values['db_host'], $values['db_user'], $values['db_password'], $values['db_name']);
  371. $GLOBALS['db'] -> Execute("SET NAMES 'UTF8'");
  372. //The upgrade completed successfully, so delete old tables and rename temporary install_ tables to its original names
  373. if ($values['old_db_name'] == $values['db_name']) {
  374. foreach ($upgradedTables as $table) {
  375. if (!in_array($table, $existingTables)) {
  376. $db -> Execute("drop table $table");
  377. $db -> Execute("RENAME TABLE install_$table TO $table");
  378. }
  379. }
  380. foreach ($tables as $table) {
  381. if (!in_array($table, $existingTables)) {
  382. try {
  383. $db -> Execute("drop table install_$table");
  384. } catch (Exception $e) {
  385. }
  386. }
  387. }
  388. }
  389. if ($values['upgrade_search']) {
  390. //EfrontSearch::reBuiltIndex();
  391. }
  392. if (version_compare($dbVersion, '3.6.7') == -1) {
  393. $courses = eF_getTableData("courses","*");
  394. foreach ($courses as $key => $value) {
  395. $options = unserialize($value['options']);
  396. if (!isset($options['certificate_export_method'])) {
  397. $options['certificate_export_method'] = 'rtf';
  398. eF_updateTableData('courses',array('options' => serialize($options)),'id='.$value['id']);
  399. }
  400. }
  401. EfrontTimes :: upgradeFromUsersOnline();
  402. }
  403. if (version_compare($dbVersion, '3.6.10') == -1) {
  404. $result = eF_getTableData("users_to_projects", "*");
  405. foreach ($result as $value) {
  406. if (isset($value['filename']) && $value['filename'] != '') {
  407. try {
  408. $file = new EfrontFile($value['filename']);
  409. if ($file['directory'] == G_UPLOADPATH.$value['users_LOGIN'].'/projects') {
  410. $projectDirectory = G_UPLOADPATH.$value['users_LOGIN'].'/projects/'.$value['projects_ID'].'/';
  411. if (!is_dir($projectDirectory)) {
  412. EfrontDirectory :: createDirectory($projectDirectory);
  413. }
  414. $file -> rename($projectDirectory.$file['physical_name']);
  415. }
  416. } catch (Exception $e) {
  417. }
  418. }
  419. }
  420. //change flv path with offset because of the tinymce 3.4.2
  421. $result = eF_getTableData("content", "*", "data like '%flvToPlay%'");
  422. foreach ($result as $value) {
  423. if (mb_strpos($value['data'], "flvToPlay=../../../../../") !== false) {
  424. $value['data'] = str_replace("flvToPlay=../../../../../", "flvToPlay=##EFRONTEDITOROFFSET##", $value['data']);
  425. eF_updateTableData("content", array('data' => $value['data']), "id=".$value['id']);
  426. }
  427. }
  428. }
  429. $options = EfrontConfiguration :: getValues();
  430. //This means that the version upgrading from is 3.5
  431. if ($dbVersion == '3.5') {
  432. //Try to restore custom blocks
  433. try {
  434. if ($options['custom_blocks']) {
  435. $basedir = G_EXTERNALPATH;
  436. if (!is_dir($basedir) && !mkdir($basedir, 0755)) {
  437. throw new EfrontFileException(_COULDNOTCREATEDIRECTORY.': '.$fullPath, EfrontFileException :: CANNOT_CREATE_DIR);
  438. }
  439. $blocks = unserialize($options['custom_blocks']);
  440. foreach ($blocks as $value) {
  441. $value['name'] = rand().time(); //Use a random name
  442. $block = array('name' => $value['name'],
  443. 'title' => $value['title']);
  444. file_put_contents($basedir.$value['name'].'.tpl', $value['content']);
  445. isset($customBlocks) && sizeof($customBlocks) > 0 ? $customBlocks[] = $block : $customBlocks = array($block);
  446. }
  447. $currentSetTheme = new themes($GLOBALS['configuration']['theme']);
  448. $currentSetTheme -> layout['custom_blocks'] = $customBlocks;
  449. $currentSetTheme -> persist();
  450. }
  451. } catch (Exception $e) {
  452. }
  453. //Try to restore custom logo
  454. try {
  455. $logoFile = new EfrontFile($options['logo']);
  456. if (strpos($logoFile['path'], G_LOGOPATH) === false) {
  457. copy ($logoFile['path'], G_LOGOPATH.$logoFile['name']);
  458. }
  459. } catch (Exception $e) {
  460. }
  461. //Try to restore custom favicon
  462. try {
  463. if (strpos($faviconFile['path'], G_LOGOPATH) === false) {
  464. $faviconFile = new EfrontFile($options['logo']);
  465. }
  466. copy ($faviconFile['path'], G_LOGOPATH.$faviconFile['name']);
  467. } catch (Exception $e) {
  468. }
  469. //Try to restore paypalbusiness addres
  470. try {
  471. $result = eF_getTableData("paypal_configuration", "paypalbusiness");
  472. if (!empty($result)) {
  473. EfrontConfiguration :: setValue('paypalbusiness', $result[0]['paypalbusiness']);
  474. }
  475. } catch (Exception $e) {
  476. }
  477. //Reset certain version options
  478. try {
  479. if ($options['version_type'] == 'standard') {
  480. EfrontConfiguration :: setValue('version_type', 'community');
  481. }
  482. } catch (Exception $e) {
  483. }
  484. //Add default notifications to 3.5
  485. EfrontNotification::addDefaultNotifications();
  486. }
  487. }
  488. //Now upgrade to 3.6.12
  489. include ("upgrade.php");
  490. Installation :: createConfigurationFile($values, true);
  491. //the following lines remove some old editor files that prevent editor from loading in version 3.6
  492. $removedDir = array();
  493. //$removedDir[] = G_ROOTPATH.'www/editor/tiny_mce/themes/advanced/langs';
  494. $removedDir[] = G_ROOTPATH.'www/editor/tiny_mce/plugins/zoom';
  495. $removedDir[] = G_ROOTPATH.'www/editor/tiny_mce/plugins/flash';
  496. $removedDir[] = G_ROOTPATH.'www/editor/tiny_mce/plugins/devkit';
  497. $removedDir[] = G_ROOTPATH.'www/editor/tiny_mce/plugins/mathtype';
  498. $removedDir[] = G_ROOTPATH.'www/editor/tiny_mce/plugins/lessons_info';
  499. foreach ($removedDir as $key => $value) {
  500. if (is_dir($value)) {
  501. try {
  502. $directory = new EfrontDirectory($value);
  503. $directory -> delete();
  504. } catch (EfrontFileException $e) {} //Don't stop on filesystem errors
  505. }
  506. }
  507. $fileSystemTree = new FileSystemTree(G_ROOTPATH.'www/editor/tiny_mce/plugins', true);
  508. foreach (new EfrontDirectoryOnlyFilterIterator($fileSystemTree -> tree) as $key => $value) {
  509. //alternatively we can delete only lang files without _dlg
  510. /* if (is_dir($key.'/langs')) {
  511. try {
  512. $directory = new EfrontDirectory($key.'/langs');
  513. $directory -> delete();
  514. } catch (EfrontFileException $e) {} //Don't stop on filesystem errors
  515. }
  516. */
  517. if (is_dir($key.'/jscripts')) {
  518. try {
  519. if ($value['name'] != 'preview' && $value['name'] != 'Jsvk') {
  520. $directory = new EfrontDirectory($key.'/jscripts');
  521. $directory -> delete();
  522. }
  523. } catch (EfrontFileException $e) {} //Don't stop on filesystem errors
  524. }
  525. }
  526. try {
  527. $cacheTree = new FileSystemTree(G_THEMECACHE, true);
  528. foreach (new EfrontDirectoryOnlyFilterIterator($cacheTree -> tree) as $value) {
  529. $value -> delete();
  530. }
  531. } catch (Exception $e) {}
  532. EfrontConfiguration :: setValue('database_version', G_VERSION_NUM);
  533. if (!defined("PREPROCESSED") && $GLOBALS['configuration']['version_type'] != G_VERSIONTYPE) {
  534. EfrontConfiguration :: setValue('version_type', G_VERSIONTYPE);
  535. EfrontConfiguration :: setValue('version_users', '');
  536. EfrontConfiguration :: setValue('version_activated', '');
  537. EfrontConfiguration :: setValue('version_upgrades', '');
  538. EfrontConfiguration :: setValue('version_key', '');
  539. }
  540. EfrontConfiguration :: setValue('editor_type', 'tinymce_new');
  541. EfrontConfiguration :: setValue('phplivedocx_server', 'https://api.livedocx.com/1.2/mailmerge.asmx?WSDL'); //code for updating phplivedocx_server
  542. $defaultConfig = EfrontConfiguration :: getValues();
  543. $phplivedocxConfig = '<?php
  544. define("PATH_ZF","'.G_ROOTPATH.'Zend/library/'.'");
  545. define("USERNAME","'.$defaultConfig['phplivedocx_username'].'");
  546. define("PASSWORD","'.$defaultConfig['phplivedocx_password'].'");
  547. define("PHPLIVEDOCXAPI","'.$defaultConfig['phplivedocx_server'].'");
  548. ?>';
  549. try {
  550. if (!file_exists($path."phplivedocx_config.php") || is_writable($path."phplivedocx_config.php")) {
  551. file_put_contents($path."phplivedocx_config.php", $phplivedocxConfig);
  552. }
  553. } catch (Exception $e) {}
  554. //Upgrade for 3.6.8's default/site/theme logo: If a logo is set, then set this as the 'site logo' and set 'use_logo' to 1 (which means 'use site logo')
  555. if ($GLOBALS['configuration']['logo'] && !$GLOBALS['configuration']['site_logo']) {
  556. EfrontConfiguration :: setValue('use_logo', 1);
  557. EfrontConfiguration :: setValue('site_logo', $GLOBALS['configuration']['logo']);
  558. }
  559. $defaultConfig['editor_type'] == 'tinymce_new' ? $editorDir = 'tiny_mce_new' : $editorDir = 'tiny_mce';
  560. try {
  561. $cacheEditor = new FileSystemTree(G_ROOTPATH.'www/editor/'.$editorDir, true);
  562. foreach (new EfrontFileOnlyFilterIterator($cacheEditor -> tree) as $key => $value) {
  563. if ($value['extension'] == 'gz') {
  564. $value -> delete();
  565. }
  566. }
  567. } catch (Exception $e) {}
  568. Installation :: addModules(true);
  569. EfrontStats :: createViews();
  570. if (!isset($_GET['unattended'])) {
  571. header("location:".$_SERVER['PHP_SELF']."?finish=1&upgrade=1");
  572. exit;
  573. }
  574. } else {
  575. //Create the file libraries/configuration.php
  576. Installation :: createConfigurationFile($values);
  577. /**Include the file configuration.php*/
  578. require_once($path."configuration.php");
  579. if (stripos(php_uname(), 'windows') !== false) {
  580. EfrontConfiguration :: setValue('file_encoding', 'UTF7-IMAP');
  581. }
  582. EfrontConfiguration :: setValue('time_zone', date_default_timezone_get());
  583. /*Languages declarations. Must be put before creating default users and lessons*/
  584. include_once "insert_languages.php";
  585. addLanguagesDB();
  586. //modern is the default theme
  587. try {
  588. $file = new EfrontFile(G_THEMESPATH."efront2013/theme.xml");
  589. themes :: create(themes :: parseFile($file));
  590. $currentTheme = new themes('efront2013');
  591. EfrontConfiguration :: setValue('theme', $currentTheme -> {$currentTheme -> entity}['id']);
  592. } catch (Exception $e) {}
  593. //Create the default system users and lessons
  594. if (isset($values['default_data']) && $values['default_data']) {
  595. /*
  596. //The new db itself
  597. foreach (explode(";\r\n", file_get_contents(G_LIBRARIESPATH.'enterprise.sql')) as $command) {
  598. if (trim($command)) {
  599. $db -> execute(trim($command));
  600. }
  601. }
  602. $db -> Execute($sql);
  603. $fields = array('password' => EfrontUser::createPassword($values['admin_password']),
  604. 'email' => $values['admin_email'],
  605. 'timestamp' => time());
  606. eF_updateTableData("users", $fields);
  607. $fields = array('login' => $values['admin_name']);
  608. eF_updateTableData("users", $fields, "login='admin'");
  609. $fields = array('created' => time());
  610. eF_updateTableData("courses", $fields);
  611. eF_updateTableData("lessons", $fields);
  612. $fields = array('from_timestamp' => time());
  613. eF_updateTableData("users_to_courses", $fields);
  614. eF_updateTableData("users_to_lessons", $fields);
  615. */
  616. $result = Installation :: createDefaultUsers($values);
  617. foreach ($result as $value) {
  618. if ($value -> user['user_type'] != 'administrator') {
  619. $lessonUsers[$value -> user['login']] = $value -> user['user_type'];
  620. }
  621. }
  622. Installation :: createDefaultLessons($values, $lessonUsers);
  623. } else {
  624. $result = Installation :: createDefaultUsers($values, true);
  625. }
  626. EfrontConfiguration :: setValue('editor_type', 'tinymce_new');
  627. EfrontNotification::addDefaultNotifications();
  628. EfrontConfiguration :: setValue('phplivedocx_server', 'https://api.livedocx.com/1.2/mailmerge.asmx?WSDL'); //code for updating phplivedocx_server
  629. $defaultConfig = EfrontConfiguration :: getValues();
  630. $phplivedocxConfig = '<?php
  631. define("PATH_ZF","'.G_ROOTPATH.'Zend/library/'.'");
  632. define("USERNAME","'.$defaultConfig['phplivedocx_username'].'");
  633. define("PASSWORD","'.$defaultConfig['phplivedocx_password'].'");
  634. define("PHPLIVEDOCXAPI","'.$defaultConfig['phplivedocx_server'].'");
  635. ?>';
  636. file_put_contents($path."phplivedocx_config.php", $phplivedocxConfig);
  637. Installation :: addModules();
  638. if (is_file('post_install.php')) {
  639. include('post_install.php');
  640. runPostInstallationFunctions();
  641. }
  642. EfrontStats::createViews();
  643. if (!isset($_GET['unattended'])) {
  644. header("location:".$_SERVER['PHP_SELF']."?finish=1");
  645. exit;
  646. }
  647. }
  648. } catch (Exception $e) {
  649. Installation::handleInstallationExceptions($e);
  650. }
  651. }
  652. $renderer = new HTML_QuickForm_Renderer_ArraySmarty($smarty);
  653. $renderer->setRequiredTemplate(
  654. '{$html}{if $required}
  655. &nbsp;<span class = "formRequired">*</span>
  656. {/if}'
  657. );
  658. $form -> setJsWarnings('The following errors occured:', 'Please correct the above errors');
  659. $form -> setRequiredNote('* Denotes mandatory fields');
  660. $form -> accept($renderer);
  661. $smarty -> assign('T_DATABASE_FORM', $renderer -> toArray());
  662. }
  663. if (isset($_GET['finish']) || isset($_GET['unattended'])) {
  664. //delete theme cache
  665. try {
  666. $path = "../../libraries/";
  667. require_once($path."configuration.php");
  668. $cacheTree = new FileSystemTree(G_THEMECACHE, true);
  669. foreach (new EfrontDirectoryOnlyFilterIterator($cacheTree -> tree) as $value) {
  670. //$value -> delete();
  671. }
  672. } catch (Exception $e) {
  673. Installation::handleInstallationExceptions($e);
  674. }
  675. if (isset($_GET['unattended'])) {
  676. if ($_GET['ajax']) {
  677. echo json_encode(array('status' => 1, 'message' => 'Successfully completed Unattended upgrade'));
  678. EfrontSystem :: unlockSystem();
  679. } else {
  680. header("location:".G_SERVERNAME."index.php?delete_install=1");
  681. }
  682. } else {
  683. session_destroy();
  684. unset($_SESSION);
  685. }
  686. //$message = "Upgrade is completed, but the contents of the templates folder, ".G_THEMECACHE." could not be deleted. Please delete them manually";
  687. }
  688. if (isset($_GET['restore'])) {
  689. try {
  690. $path = "../../libraries/";
  691. try {
  692. if (is_file($path."configuration.php")) {
  693. require_once($path."configuration.php");
  694. } else {
  695. echo Installation :: printErrorMessage("You must have a valid configuration file for the emergency restore to work");
  696. exit;
  697. }
  698. } catch (Exception $e) {
  699. $smarty -> assign("T_EXCEPTION_TRACE", $e -> getTraceAsString());
  700. $message = $e -> getMessage().' ('.$e -> getCode().') &nbsp;<a href = "javascript:void(0)" onclick = "eF_js_showDivPopup(\''._ERRORDETAILS.'\', 2, \'error_details\')">'._MOREINFO.'</a>';
  701. $message_type = 'failure';
  702. }
  703. foreach($it = new DirectoryIterator(G_BACKUPPATH) as $key => $value) {
  704. if (!$value -> isDir() && pathinfo($value -> getFileName(), PATHINFO_EXTENSION) == 'zip') {
  705. $files[] = basename($value);
  706. }
  707. }
  708. $smarty -> assign("T_BACKUP_FILES", $files);
  709. if (isset($_GET['file']) && in_array($_GET['file'], $files)) {
  710. //ini_set("memory_limit", "-1");
  711. EfrontSystem :: restore(G_BACKUPPATH.$_GET['file']); //Auto backup database
  712. $message = "The restoring procedure completed successfully";
  713. $message_type = "success";
  714. }
  715. } catch (Exception $e) {
  716. Installation::handleInstallationExceptions($e);
  717. }
  718. }
  719. $loadScripts = array('EfrontScripts',
  720. 'scriptaculous/prototype',
  721. 'scriptaculous/scriptaculous',
  722. 'scriptaculous/effects',
  723. 'efront_ajax');
  724. $smarty -> assign("T_HEADER_LOAD_SCRIPTS", implode(",", array_unique($loadScripts))); //array_unique, so it doesn't send duplicate entries
  725. $smarty -> assign("T_MESSAGE", $message);
  726. $smarty -> assign("T_MESSAGE_TYPE", $message_type);
  727. $smarty -> load_filter('output', 'eF_template_applyImageMap');
  728. $smarty -> load_filter('output', 'eF_template_applyThemeToImages');
  729. $smarty -> display ("install/install.tpl");
  730. /**
  731. *
  732. * @author user
  733. *
  734. */
  735. class InstallationException extends Exception
  736. {
  737. const DATABASE_NOT_EMPTY = 1;
  738. }
  739. /**
  740. *
  741. * @author user
  742. *
  743. */
  744. class Installation
  745. {
  746. /**
  747. *
  748. * @param $values
  749. * @return unknown_type
  750. */
  751. public static function createConfigurationFile($values, $upgrade = false) {
  752. $patterns = array("/(define\(['\"]G_DBTYPE['\"], ['\"]).*(['\"]\);)/",
  753. "/(define\(['\"]G_DBHOST['\"], ['\"]).*(['\"]\);)/",
  754. "/(define\(['\"]G_DBUSER['\"], ['\"]).*(['\"]\);)/",
  755. "/(define\(['\"]G_DBPASSWD['\"], ['\"]).*(['\"]\);)/",
  756. "/(define\(['\"]G_DBNAME['\"], ['\"]).*(['\"]\);)/",
  757. "/(define\(['\"]G_DBPREFIX['\"], ['\"]).*(['\"]\);)/",
  758. "/(define\(['\"]G_VERSION_NUM['\"], ['\"]).*(['\"]\);)/");
  759. dirname(dirname($_SERVER['PHP_SELF'])) != '.' ? $servername = dirname(dirname($_SERVER['PHP_SELF'])) : $servername = '';
  760. $servername = str_replace("\\", "/", $servername);
  761. $replacements = array('${1}'.$values['db_type'].'${2}',
  762. '${1}'.$values['db_host'].'${2}',
  763. '${1}'.$values['db_user'].'${2}',
  764. '${1}'.$values['db_password'].'${2}',
  765. '${1}'.$values['db_name'].'${2}',
  766. '${1}'.$values['db_prefix'].'${2}',
  767. '${1}'.G_VERSION_NUM.'${2}');
  768. if ($upgrade) {
  769. $file_contents = file_get_contents($GLOBALS['path'].'configuration.php'); //Load sample configuration file
  770. $new_file_contents = preg_replace("/(define\(['\"]G_SERVERNAME['\"], ['\"]).*(['\"]\);)/", "define('G_OFFSET', '".rtrim($servername, "/").'/'."');", $file_contents, -1, $count);
  771. } else {
  772. $file_contents = file_get_contents('sample_config.php'); //Load sample configuration file
  773. $new_file_contents = preg_replace("/define\('G_OFFSET', ''\)/", "define('G_OFFSET', '".rtrim($servername, "/").'/'."')", $file_contents, -1, $count);
  774. }
  775. $new_file_contents = preg_replace($patterns, $replacements, $new_file_contents, -1, $count); //Replace sample settings with current settings
  776. if (!file_put_contents($GLOBALS['path'].'configuration.php', $new_file_contents)) {
  777. throw new Exception("The configuration file could not be created");
  778. }
  779. }
  780. /**
  781. *
  782. * @param $values
  783. * @param $users
  784. * @return unknown_type
  785. */
  786. public static function createDefaultLessons($values, $users) {
  787. //Content is now taken from a file called sample_data.sql. To produce an up-to-date version of this file,
  788. //call the following command from the command line:
  789. //mysqldump -u periklis -p <db_name> lessons courses users_to_lessons users_to_courses search_keywords search_invertedindex tests_to_questions tests rules questions lesson_conditions glossary f_forums lessons_to_courses directions content --no-create-info --compact --single-transaction > ~/sample_data.sql
  790. //Replacing <db_name> with the database that will provide the data
  791. foreach (explode("\n", file_get_contents('sample_data.sql')) as $command) {
  792. if (trim($command)) {
  793. $GLOBALS['db'] -> execute(trim($command));
  794. }
  795. }
  796. $file = new EfrontFile(EfrontDirectory :: normalize(getcwd()).'/lessons.zip');
  797. $newFile = $file->copy(G_LESSONSPATH, true);
  798. $newFile->uncompress();
  799. $newFile->delete();
  800. /*
  801. //Check if any lessons were created in a previous attempt
  802. $result = eF_getTableData("lessons", "*");
  803. foreach ($result as $value) {
  804. $lesson = new EfrontLesson($value);
  805. $lesson -> delete();
  806. }
  807. //Check if any courses were created in a previous attempt
  808. $result = eF_getTableData("courses", "id");
  809. foreach ($result as $value) {
  810. $course = new EfrontLesson($value);
  811. $course -> delete();
  812. }
  813. //Check if any categories were created in a previous attempt
  814. $result = eF_getTableDataFlat("directions", "id");
  815. if (sizeof($result) > 0) {
  816. foreach ($result['id'] as $id) {
  817. EfrontDirection::deleteDirection($id);
  818. }
  819. }
  820. //Create default categories
  821. $ancientCivId = eF_insertTableData("directions", array('name' => 'Ancient Civilizations', 'active' => 1));
  822. $ProgrammingId = eF_insertTableData("directions", array('name' => 'Programming', 'active' => 1));
  823. try {
  824. //Create "Greedy Algorithms" lesson
  825. $fields = array('directions_ID' => $ProgrammingId, 'active' => 1, 'course_only' => 0);
  826. $file = new EfrontFile(EfrontDirectory :: normalize(getcwd()).'/Greedy_algorithms.zip');
  827. $lesson = EfrontLesson :: createLesson(array_merge(array('name' => 'Greedy algorithms'), $fields));
  828. $file = $file -> copy($lesson -> getDirectory());
  829. $lesson -> import($file);
  830. $lesson -> addUsers(array_keys($users), array_values($users));
  831. } catch (Exception $e) {}//do nothing, just move on to the next lesson
  832. try {
  833. //Create "Maya civilization" lesson
  834. $fields = array('directions_ID' => $ancientCivId, 'active' => 1, 'course_only' => 0);
  835. $file = new EfrontFile(EfrontDirectory :: normalize(getcwd()).'/Maya_civilization.zip');
  836. $lesson = EfrontLesson :: createLesson(array_merge(array('name' => 'Maya civilization'), $fields));
  837. $file = $file -> copy($lesson -> getDirectory());
  838. $lesson -> import($file);
  839. $lesson -> addUsers(array_keys($users), array_values($users));
  840. } catch (Exception $e) {}//do nothing, just move on to the next lesson
  841. try {
  842. //Create "How to be a programmer" course
  843. $fields = array('directions_ID' => $ProgrammingId, 'active' => 1);
  844. $file = new EfrontFile(EfrontDirectory :: normalize(getcwd()).'/How_to_be_a_programmer.zip');
  845. $course = EfrontCourse :: createCourse(array_merge(array('name' => 'How to be a programmer'), $fields));
  846. $file = $file -> copy($lesson -> getDirectory()); //$lesson is put here on purpose, since $course does not have a directory
  847. $course -> import($file);
  848. $course -> addUsers(array('student'), 'student');
  849. $course -> addUsers(array('professor'), 'professor');
  850. } catch (Exception $e) {}//do nothing, just move on to the next lesson
  851. */
  852. }
  853. /**
  854. *
  855. * @param $values
  856. * @return unknown_type
  857. */
  858. public static function createDefaultUsers($values, $adminOnly = false) {
  859. $language = 'english';
  860. $adminData = array('login' => $values['admin_name'],
  861. 'password' => $values['admin_password'],
  862. 'email' => $values['admin_email'],
  863. 'name' => 'System',
  864. 'surname' => 'Administrator',
  865. 'languages_NAME' => $language,
  866. 'active' => '1',
  867. 'user_type'=> 'administrator',
  868. 'additional_accounts' => $adminOnly ? '' : serialize(array('student', 'professor')));
  869. $admin = EfrontUser :: createUser($adminData);
  870. EfrontConfiguration :: setValue('system_email', $values['admin_email']);
  871. if (!$adminOnly) {
  872. $professorData = array('login' => 'professor',
  873. 'password' => $values['admin_password'],
  874. 'email' => $values['admin_email'],
  875. 'name' => 'Default',
  876. 'surname' => 'Professor',
  877. 'languages_NAME' => $language,
  878. 'active' => '1',
  879. 'user_type'=> 'professor',
  880. 'additional_accounts' => serialize(array($values['admin_name'], 'student')));
  881. $professor = EfrontUser :: createUser($professorData);
  882. $studentData = array('login' => 'student',
  883. 'password' => $values['admin_password'],
  884. 'email' => $values['admin_email'],
  885. 'name' => 'Default',
  886. 'surname' => 'Student',
  887. 'languages_NAME' => $language,
  888. 'active' => '1',
  889. 'user_type'=> 'student',
  890. 'additional_accounts' => serialize(array($values['admin_name'], 'professor')));
  891. $student = EfrontUser :: createUser($studentData);
  892. return array($admin, $professor, $student);
  893. } else {
  894. return array($admin);
  895. }
  896. }
  897. /**
  898. * Install modules
  899. *
  900. * @since 3.6.0
  901. * @access public
  902. * @static
  903. */
  904. public static function addModules($upgrade = false) {
  905. $modulesToInstall = array(
  906. "administrator_tools",
  907. "bbb",
  908. "billboard",
  909. "blogs",
  910. "bootstrap",
  911. "chat",
  912. "crossword",
  913. "export_unit",
  914. "faq",
  915. "flashcards",
  916. "gift_aiken",
  917. "gradebook",
  918. "idle_users",
  919. "info_kiosk",
  920. "journal",
  921. "links",
  922. "outlook_invitation",
  923. "quick_mails",
  924. "quote",
  925. "rss",
  926. "security",
  927. "workbook",
  928. "youtube",
  929. );
  930. $modulesList = eF_getTableData("modules", "*");
  931. foreach ($modulesList as $module) {
  932. $existingModules[] = $module['className'];
  933. }
  934. $filesystem = new FileSystemTree(G_MODULESPATH, true);
  935. foreach (new EfrontNodeFilterIterator($filesystem -> tree) as $moduleDirectory => $value) {
  936. try {
  937. if (in_array(str_replace("module_", "", basename($moduleDirectory)), $modulesToInstall) && is_file($moduleDirectory.'/module.xml')) {
  938. $xml = simplexml_load_file($moduleDirectory.'/module.xml');
  939. $className = (string)$xml -> className;
  940. $className = str_replace(" ", "", $className);
  941. $database_file = (string)$xml -> database;
  942. if (is_file($moduleDirectory.'/'.$className. ".class.php")) {
  943. require_once $moduleDirectory."/".$className.".class.php";
  944. if (class_exists($className)) {
  945. $module = new $className("administrator.php?ctg=module&op=".$className, $className);
  946. // Check whether the roles defined are acceptable
  947. $roles = $module -> getPermittedRoles();
  948. $roles_failure = 0;
  949. if (sizeof($roles) == 0) {
  950. throw new Exception(_NOMODULEPERMITTEDROLESDEFINED);
  951. } else {
  952. foreach ($roles as $role) {
  953. if ($role != 'administrator' && $role != 'student' && $role != 'professor') {
  954. throw new Exception(_NOMODULEPERMITTEDROLESDEFINED);
  955. }
  956. }
  957. }
  958. $fields = array('className' => $className,
  959. 'db_file' => $database_file,
  960. 'name' => $className,
  961. 'active' => 0,
  962. 'title' => ((string)$xml -> title)?(string)$xml -> title:" ",
  963. 'author' => (string)$xml -> author,
  964. 'version' => (string)$xml -> version,
  965. 'description' => (string)$xml -> description,
  966. 'position' => basename($moduleDirectory),
  967. 'permissions' => implode(",", $module -> getPermittedRoles()));
  968. // Install module database
  969. if ($upgrade && in_array($className, $existingModules)) {
  970. if ($module -> onUpgrade()) {
  971. eF_updateTableData("modules", $fields, "className ='".$_GET['upgrade']."'");
  972. } else {
  973. throw new Exception(_MODULEDBERRORONUPGRADECHECKUPGRADEFUNCTION);
  974. }
  975. } else {
  976. if ($module -> onInstall()) {
  977. if ($className == 'module_security') {
  978. $fields['active'] = 1; //Since 3.6.10, security module starts as activated (instead of rss)
  979. }
  980. eF_insertTableData("modules", $fields);
  981. } else {
  982. throw new Exception(_MODULEDBERRORONINSTALL);
  983. }
  984. }
  985. } else {
  986. throw new Exception('"'.$className .'" '. _MODULECLASSNOTEXISTSIN . ' ' .$moduleDirectory.'/'.$className.'.class.php');
  987. }
  988. } else {
  989. throw new Exception(_NOMODULECLASSFOUND . ' "'. $className .'" : '.$moduleDirectory);
  990. }
  991. }
  992. } catch (Exception $e) {/*Don't install any failed modules*/}
  993. }
  994. }
  995. /**
  996. *
  997. * @return unknown_type
  998. */
  999. public static function checkCurrentVersion() {
  1000. if (is_file($GLOBALS['path'].'configuration.php')) {
  1001. $file_contents = file_get_contents($GLOBALS['path'].'configuration.php'); //Load existing configuration file
  1002. preg_match('/define\(["\']G_DBTYPE["\'], ["\'](.*)["\']\);/', $file_contents, $type);
  1003. preg_match('/define\(["\']G_DBHOST["\'], ["\'](.*)["\']\);/', $file_contents, $host);
  1004. preg_match('/define\(["\']G_DBUSER["\'], ["\'](.*)["\']\);/', $file_contents, $user);
  1005. preg_match('/define\(["\']G_DBPASSWD["\'], ["\'](.*)["\']\);/', $file_contents, $password);
  1006. preg_match('/define\(["\']G_DBNAME["\'], ["\'](.*)["\']\);/', $file_contents, $name);
  1007. //preg_match('/define\(["\']G_VERSION_NUM["\'], ["\'](.*)["\']\);/', $file_contents, $name);
  1008. $currentVersion = array('db_type' => $type[1],
  1009. 'db_host' => $host[1],
  1010. 'db_user' => $user[1],
  1011. 'db_password' => $password[1],
  1012. 'db_name' => $name[1]);
  1013. } else {
  1014. }
  1015. return $currentVersion;
  1016. }
  1017. /**
  1018. * Automatically fix PHP settings errors
  1019. *
  1020. * This function is used to automatically apply a suitable php.ini or .htaccess file to correct the most
  1021. * usual PHP settings errors: session.save_path, magic_quotes_gpc, register_globals.
  1022. *
  1023. * @param array $settings The settings that need to be fixed
  1024. * @param string $mode Can be 'local', which means that the fix will be in a local php.ini file, or 'htaccess', which means that the fix will be performed with a .htaccess file
  1025. * @since 3.6.0
  1026. * @access public
  1027. * @static
  1028. */
  1029. public static function fix($settings, $mode = 'local') {
  1030. $sessionSavePathDir = '';
  1031. if ($settings['session.save_path'] && function_exists('sys_get_temp_dir') && is_writable(sys_get_temp_dir())) { //If the session.save_path does not exist, set it to system's default temp dir
  1032. $sessionSavePathDir = trim(sys_get_temp_dir(), '\\');
  1033. } else if (!function_exists('sys_get_temp_dir') || (function_exists('sys_get_temp_dir') && !is_writable(sys_get_temp_dir()))) {
  1034. $rootDir = dirname(dirname(dirname(__FILE__)));
  1035. if (is_dir(dirname($rootDir).'/tmp') && is_writable(dirname($rootDir).'/tmp')) {

Large files files are truncated, but you can click here to view the full file