ElggInstaller.php 43 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648
  1. <?php
  2. /**
  3. * Elgg Installer.
  4. * Controller for installing Elgg. Supports both web-based on CLI installation.
  5. *
  6. * This controller steps the user through the install process. The method for
  7. * each step handles both the GET and POST requests. There is no XSS/CSRF protection
  8. * on the POST processing since the installer is only run once by the administrator.
  9. *
  10. * The installation process can be resumed by hitting the first page. The installer
  11. * will try to figure out where to pick up again.
  12. *
  13. * All the logic for the installation process is in this class, but it depends on
  14. * the core libraries. To do this, we selectively load a subset of the core libraries
  15. * for the first few steps and then load the entire engine once the database and
  16. * site settings are configured. In addition, this controller does its own session
  17. * handling until the database is setup.
  18. *
  19. * There is an aborted attempt in the code at creating the data directory for
  20. * users as a subdirectory of Elgg's root. The idea was to protect this directory
  21. * through a .htaccess file. The problem is that a malicious user can upload a
  22. * .htaccess of his own that overrides the protection for his user directory. The
  23. * best solution is server level configuration that turns off AllowOverride for the
  24. * data directory. See ticket #3453 for discussion on this.
  25. *
  26. * @package Elgg.Core
  27. * @subpackage Installer
  28. */
  29. class ElggInstaller {
  30. protected $steps = array(
  31. 'welcome',
  32. 'requirements',
  33. 'database',
  34. 'settings',
  35. 'admin',
  36. 'complete',
  37. );
  38. protected $status = array(
  39. 'config' => FALSE,
  40. 'database' => FALSE,
  41. 'settings' => FALSE,
  42. 'admin' => FALSE,
  43. );
  44. protected $isAction = FALSE;
  45. protected $autoLogin = TRUE;
  46. /**
  47. * Global Elgg configuration
  48. *
  49. * @var \stdClass
  50. */
  51. private $CONFIG;
  52. /**
  53. * Constructor bootstraps the Elgg engine
  54. */
  55. public function __construct() {
  56. global $CONFIG;
  57. if (!isset($CONFIG)) {
  58. $CONFIG = new stdClass;
  59. }
  60. $this->CONFIG = $CONFIG;
  61. $this->isAction = isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] === 'POST';
  62. $this->bootstrapConfig();
  63. $this->bootstrapEngine();
  64. _elgg_services()->setValue('session', \ElggSession::getMock());
  65. elgg_set_viewtype('installation');
  66. set_error_handler('_elgg_php_error_handler');
  67. set_exception_handler('_elgg_php_exception_handler');
  68. _elgg_services()->translator->registerTranslations("{$this->getElggRoot()}/install/languages/", TRUE);
  69. }
  70. /**
  71. * @return string The absolute path to Elgg's root directory
  72. */
  73. private function getElggRoot() {
  74. return dirname(dirname(__DIR__));
  75. }
  76. /**
  77. * Dispatches a request to one of the step controllers
  78. *
  79. * @param string $step The installation step to run
  80. *
  81. * @return void
  82. * @throws InstallationException
  83. */
  84. public function run($step) {
  85. global $CONFIG;
  86. // language needs to be set before the first call to elgg_echo()
  87. $CONFIG->language = 'en';
  88. // check if this is a URL rewrite test coming in
  89. $this->processRewriteTest();
  90. if (!in_array($step, $this->getSteps())) {
  91. $msg = _elgg_services()->translator->translate('InstallationException:UnknownStep', array($step));
  92. throw new InstallationException($msg);
  93. }
  94. $this->setInstallStatus();
  95. $this->checkInstallCompletion($step);
  96. // check if this is an install being resumed
  97. $this->resumeInstall($step);
  98. $this->finishBootstraping($step);
  99. $params = $this->getPostVariables();
  100. $this->$step($params);
  101. }
  102. /**
  103. * Set the auto login flag
  104. *
  105. * @param bool $flag Auto login
  106. *
  107. * @return void
  108. */
  109. public function setAutoLogin($flag) {
  110. $this->autoLogin = (bool) $flag;
  111. }
  112. /**
  113. * A batch install of Elgg
  114. *
  115. * All required parameters must be passed in as an associative array. See
  116. * $requiredParams for a list of them. This creates the necessary files,
  117. * loads the database, configures the site settings, and creates the admin
  118. * account. If it fails, an exception is thrown. It does not check any of
  119. * the requirements as the multiple step web installer does.
  120. *
  121. * If the settings.php file exists, it will use that rather than the parameters
  122. * passed to this function.
  123. *
  124. * @param array $params Array of key value pairs
  125. * @param bool $createHtaccess Should .htaccess be created
  126. *
  127. * @return void
  128. * @throws InstallationException
  129. */
  130. public function batchInstall(array $params, $createHtaccess = FALSE) {
  131. restore_error_handler();
  132. restore_exception_handler();
  133. $defaults = array(
  134. 'dbhost' => 'localhost',
  135. 'dbprefix' => 'elgg_',
  136. 'language' => 'en',
  137. 'siteaccess' => ACCESS_PUBLIC,
  138. );
  139. $params = array_merge($defaults, $params);
  140. $requiredParams = array(
  141. 'dbuser',
  142. 'dbpassword',
  143. 'dbname',
  144. 'sitename',
  145. 'wwwroot',
  146. 'dataroot',
  147. 'displayname',
  148. 'email',
  149. 'username',
  150. 'password',
  151. );
  152. foreach ($requiredParams as $key) {
  153. if (empty($params[$key])) {
  154. $msg = _elgg_services()->translator->translate('install:error:requiredfield', array($key));
  155. throw new InstallationException($msg);
  156. }
  157. }
  158. // password is passed in once
  159. $params['password1'] = $params['password2'] = $params['password'];
  160. if ($createHtaccess) {
  161. $rewriteTester = new ElggRewriteTester();
  162. if (!$rewriteTester->createHtaccess($params['wwwroot'], $this->CONFIG->path)) {
  163. throw new InstallationException(_elgg_services()->translator->translate('install:error:htaccess'));
  164. }
  165. }
  166. $this->setInstallStatus();
  167. if (!$this->status['config']) {
  168. if (!$this->createSettingsFile($params)) {
  169. throw new InstallationException(_elgg_services()->translator->translate('install:error:settings'));
  170. }
  171. }
  172. if (!$this->connectToDatabase()) {
  173. throw new InstallationException(_elgg_services()->translator->translate('install:error:databasesettings'));
  174. }
  175. if (!$this->status['database']) {
  176. if (!$this->installDatabase()) {
  177. throw new InstallationException(_elgg_services()->translator->translate('install:error:cannotloadtables'));
  178. }
  179. }
  180. // load remaining core libraries
  181. $this->finishBootstraping('settings');
  182. if (!$this->saveSiteSettings($params)) {
  183. throw new InstallationException(_elgg_services()->translator->translate('install:error:savesitesettings'));
  184. }
  185. if (!$this->createAdminAccount($params)) {
  186. throw new InstallationException(_elgg_services()->translator->translate('install:admin:cannot_create'));
  187. }
  188. }
  189. /**
  190. * Renders the data passed by a controller
  191. *
  192. * @param string $step The current step
  193. * @param array $vars Array of vars to pass to the view
  194. *
  195. * @return void
  196. */
  197. protected function render($step, $vars = array()) {
  198. $vars['next_step'] = $this->getNextStep($step);
  199. $title = _elgg_services()->translator->translate("install:$step");
  200. $body = elgg_view("install/pages/$step", $vars);
  201. echo elgg_view_page(
  202. $title,
  203. $body,
  204. 'default',
  205. array(
  206. 'step' => $step,
  207. 'steps' => $this->getSteps(),
  208. )
  209. );
  210. exit;
  211. }
  212. /**
  213. * Step controllers
  214. */
  215. /**
  216. * Welcome controller
  217. *
  218. * @param array $vars Not used
  219. *
  220. * @return void
  221. */
  222. protected function welcome($vars) {
  223. $this->render('welcome');
  224. }
  225. /**
  226. * Requirements controller
  227. *
  228. * Checks version of php, libraries, permissions, and rewrite rules
  229. *
  230. * @param array $vars Vars
  231. *
  232. * @return void
  233. */
  234. protected function requirements($vars) {
  235. $report = array();
  236. // check PHP parameters and libraries
  237. $this->checkPHP($report);
  238. // check URL rewriting
  239. $this->checkRewriteRules($report);
  240. // check for existence of settings file
  241. if ($this->checkSettingsFile($report) != TRUE) {
  242. // no file, so check permissions on engine directory
  243. $this->checkEngineDir($report);
  244. }
  245. // check the database later
  246. $report['database'] = array(array(
  247. 'severity' => 'info',
  248. 'message' => _elgg_services()->translator->translate('install:check:database')
  249. ));
  250. // any failures?
  251. $numFailures = $this->countNumConditions($report, 'failure');
  252. // any warnings
  253. $numWarnings = $this->countNumConditions($report, 'warning');
  254. $params = array(
  255. 'report' => $report,
  256. 'num_failures' => $numFailures,
  257. 'num_warnings' => $numWarnings,
  258. );
  259. $this->render('requirements', $params);
  260. }
  261. /**
  262. * Database set up controller
  263. *
  264. * Creates the settings.php file and creates the database tables
  265. *
  266. * @param array $submissionVars Submitted form variables
  267. *
  268. * @return void
  269. */
  270. protected function database($submissionVars) {
  271. $formVars = array(
  272. 'dbuser' => array(
  273. 'type' => 'text',
  274. 'value' => '',
  275. 'required' => TRUE,
  276. ),
  277. 'dbpassword' => array(
  278. 'type' => 'password',
  279. 'value' => '',
  280. 'required' => FALSE,
  281. ),
  282. 'dbname' => array(
  283. 'type' => 'text',
  284. 'value' => '',
  285. 'required' => TRUE,
  286. ),
  287. 'dbhost' => array(
  288. 'type' => 'text',
  289. 'value' => 'localhost',
  290. 'required' => TRUE,
  291. ),
  292. 'dbprefix' => array(
  293. 'type' => 'text',
  294. 'value' => 'elgg_',
  295. 'required' => TRUE,
  296. ),
  297. );
  298. if ($this->checkSettingsFile()) {
  299. // user manually created settings file so we fake out action test
  300. $this->isAction = TRUE;
  301. }
  302. if ($this->isAction) {
  303. do {
  304. // only create settings file if it doesn't exist
  305. if (!$this->checkSettingsFile()) {
  306. if (!$this->validateDatabaseVars($submissionVars, $formVars)) {
  307. // error so we break out of action and serve same page
  308. break;
  309. }
  310. if (!$this->createSettingsFile($submissionVars)) {
  311. break;
  312. }
  313. }
  314. // check db version and connect
  315. if (!$this->connectToDatabase()) {
  316. break;
  317. }
  318. if (!$this->installDatabase()) {
  319. break;
  320. }
  321. system_message(_elgg_services()->translator->translate('install:success:database'));
  322. $this->continueToNextStep('database');
  323. } while (FALSE); // PHP doesn't support breaking out of if statements
  324. }
  325. $formVars = $this->makeFormSticky($formVars, $submissionVars);
  326. $params = array('variables' => $formVars,);
  327. if ($this->checkSettingsFile()) {
  328. // settings file exists and we're here so failed to create database
  329. $params['failure'] = TRUE;
  330. }
  331. $this->render('database', $params);
  332. }
  333. /**
  334. * Site settings controller
  335. *
  336. * Sets the site name, URL, data directory, etc.
  337. *
  338. * @param array $submissionVars Submitted vars
  339. *
  340. * @return void
  341. */
  342. protected function settings($submissionVars) {
  343. $formVars = array(
  344. 'sitename' => array(
  345. 'type' => 'text',
  346. 'value' => 'My New Community',
  347. 'required' => TRUE,
  348. ),
  349. 'siteemail' => array(
  350. 'type' => 'email',
  351. 'value' => '',
  352. 'required' => FALSE,
  353. ),
  354. 'wwwroot' => array(
  355. 'type' => 'url',
  356. 'value' => _elgg_services()->config->getSiteUrl(),
  357. 'required' => TRUE,
  358. ),
  359. 'dataroot' => array(
  360. 'type' => 'text',
  361. 'value' => '',
  362. 'required' => TRUE,
  363. ),
  364. 'siteaccess' => array(
  365. 'type' => 'access',
  366. 'value' => ACCESS_PUBLIC,
  367. 'required' => TRUE,
  368. ),
  369. );
  370. // if Apache, we give user option of having Elgg create data directory
  371. //if (ElggRewriteTester::guessWebServer() == 'apache') {
  372. // $formVars['dataroot']['type'] = 'combo';
  373. // $this->CONFIG->translations['en']['install:settings:help:dataroot'] =
  374. // $this->CONFIG->translations['en']['install:settings:help:dataroot:apache'];
  375. //}
  376. if ($this->isAction) {
  377. do {
  378. //if (!$this->createDataDirectory($submissionVars, $formVars)) {
  379. // break;
  380. //}
  381. if (!$this->validateSettingsVars($submissionVars, $formVars)) {
  382. break;
  383. }
  384. if (!$this->saveSiteSettings($submissionVars)) {
  385. break;
  386. }
  387. system_message(_elgg_services()->translator->translate('install:success:settings'));
  388. $this->continueToNextStep('settings');
  389. } while (FALSE); // PHP doesn't support breaking out of if statements
  390. }
  391. $formVars = $this->makeFormSticky($formVars, $submissionVars);
  392. $this->render('settings', array('variables' => $formVars));
  393. }
  394. /**
  395. * Admin account controller
  396. *
  397. * Creates an admin user account
  398. *
  399. * @param array $submissionVars Submitted vars
  400. *
  401. * @return void
  402. */
  403. protected function admin($submissionVars) {
  404. $formVars = array(
  405. 'displayname' => array(
  406. 'type' => 'text',
  407. 'value' => '',
  408. 'required' => TRUE,
  409. ),
  410. 'email' => array(
  411. 'type' => 'email',
  412. 'value' => '',
  413. 'required' => TRUE,
  414. ),
  415. 'username' => array(
  416. 'type' => 'text',
  417. 'value' => '',
  418. 'required' => TRUE,
  419. ),
  420. 'password1' => array(
  421. 'type' => 'password',
  422. 'value' => '',
  423. 'required' => TRUE,
  424. 'pattern' => '.{6,}',
  425. ),
  426. 'password2' => array(
  427. 'type' => 'password',
  428. 'value' => '',
  429. 'required' => TRUE,
  430. ),
  431. );
  432. if ($this->isAction) {
  433. do {
  434. if (!$this->validateAdminVars($submissionVars, $formVars)) {
  435. break;
  436. }
  437. if (!$this->createAdminAccount($submissionVars, $this->autoLogin)) {
  438. break;
  439. }
  440. system_message(_elgg_services()->translator->translate('install:success:admin'));
  441. $this->continueToNextStep('admin');
  442. } while (FALSE); // PHP doesn't support breaking out of if statements
  443. }
  444. // bit of a hack to get the password help to show right number of characters
  445. $lang = _elgg_services()->translator->getCurrentLanguage();
  446. $this->CONFIG->translations[$lang]['install:admin:help:password1'] =
  447. sprintf($this->CONFIG->translations[$lang]['install:admin:help:password1'],
  448. $this->CONFIG->min_password_length);
  449. $formVars = $this->makeFormSticky($formVars, $submissionVars);
  450. $this->render('admin', array('variables' => $formVars));
  451. }
  452. /**
  453. * Controller for last step
  454. *
  455. * @return void
  456. */
  457. protected function complete() {
  458. $params = array();
  459. if ($this->autoLogin) {
  460. $params['destination'] = 'admin';
  461. } else {
  462. $params['destination'] = 'index.php';
  463. }
  464. $this->render('complete', $params);
  465. }
  466. /**
  467. * Step management
  468. */
  469. /**
  470. * Get an array of steps
  471. *
  472. * @return array
  473. */
  474. protected function getSteps() {
  475. return $this->steps;
  476. }
  477. /**
  478. * Forwards the browser to the next step
  479. *
  480. * @param string $currentStep Current installation step
  481. *
  482. * @return void
  483. */
  484. protected function continueToNextStep($currentStep) {
  485. $this->isAction = FALSE;
  486. forward($this->getNextStepUrl($currentStep));
  487. }
  488. /**
  489. * Get the next step as a string
  490. *
  491. * @param string $currentStep Current installation step
  492. *
  493. * @return string
  494. */
  495. protected function getNextStep($currentStep) {
  496. $index = 1 + array_search($currentStep, $this->steps);
  497. if (isset($this->steps[$index])) {
  498. return $this->steps[$index];
  499. } else {
  500. return null;
  501. }
  502. }
  503. /**
  504. * Get the URL of the next step
  505. *
  506. * @param string $currentStep Current installation step
  507. *
  508. * @return string
  509. */
  510. protected function getNextStepUrl($currentStep) {
  511. $nextStep = $this->getNextStep($currentStep);
  512. return _elgg_services()->config->getSiteUrl() . "install.php?step=$nextStep";
  513. }
  514. /**
  515. * Check the different install steps for completion
  516. *
  517. * @return void
  518. * @throws InstallationException
  519. */
  520. protected function setInstallStatus() {
  521. if (!is_readable("{$this->CONFIG->path}engine/settings.php")) {
  522. return;
  523. }
  524. $this->loadSettingsFile();
  525. $this->status['config'] = TRUE;
  526. // must be able to connect to database to jump install steps
  527. $dbSettingsPass = $this->checkDatabaseSettings(
  528. $this->CONFIG->dbuser,
  529. $this->CONFIG->dbpass,
  530. $this->CONFIG->dbname,
  531. $this->CONFIG->dbhost
  532. );
  533. if ($dbSettingsPass == FALSE) {
  534. return;
  535. }
  536. if (!include_once("{$this->CONFIG->path}engine/lib/database.php")) {
  537. throw new InstallationException(_elgg_services()->translator->translate('InstallationException:MissingLibrary', array('database.php')));
  538. }
  539. // check that the config table has been created
  540. $query = "show tables";
  541. $result = _elgg_services()->db->getData($query);
  542. if ($result) {
  543. foreach ($result as $table) {
  544. $table = (array) $table;
  545. if (in_array("{$this->CONFIG->dbprefix}config", $table)) {
  546. $this->status['database'] = TRUE;
  547. }
  548. }
  549. if ($this->status['database'] == FALSE) {
  550. return;
  551. }
  552. } else {
  553. // no tables
  554. return;
  555. }
  556. // check that the config table has entries
  557. $query = "SELECT COUNT(*) AS total FROM {$this->CONFIG->dbprefix}config";
  558. $result = _elgg_services()->db->getData($query);
  559. if ($result && $result[0]->total > 0) {
  560. $this->status['settings'] = TRUE;
  561. } else {
  562. return;
  563. }
  564. // check that the users entity table has an entry
  565. $query = "SELECT COUNT(*) AS total FROM {$this->CONFIG->dbprefix}users_entity";
  566. $result = _elgg_services()->db->getData($query);
  567. if ($result && $result[0]->total > 0) {
  568. $this->status['admin'] = TRUE;
  569. } else {
  570. return;
  571. }
  572. }
  573. /**
  574. * Security check to ensure the installer cannot be run after installation
  575. * has finished. If this is detected, the viewer is sent to the front page.
  576. *
  577. * @param string $step Installation step to check against
  578. *
  579. * @return void
  580. */
  581. protected function checkInstallCompletion($step) {
  582. if ($step != 'complete') {
  583. if (!in_array(FALSE, $this->status)) {
  584. // install complete but someone is trying to view an install page
  585. forward();
  586. }
  587. }
  588. }
  589. /**
  590. * Check if this is a case of a install being resumed and figure
  591. * out where to continue from. Returns the best guess on the step.
  592. *
  593. * @param string $step Installation step to resume from
  594. *
  595. * @return string
  596. */
  597. protected function resumeInstall($step) {
  598. // only do a resume from the first step
  599. if ($step !== 'welcome') {
  600. return;
  601. }
  602. if ($this->status['database'] == FALSE) {
  603. return;
  604. }
  605. if ($this->status['settings'] == FALSE) {
  606. forward("install.php?step=settings");
  607. }
  608. if ($this->status['admin'] == FALSE) {
  609. forward("install.php?step=admin");
  610. }
  611. // everything appears to be set up
  612. forward("install.php?step=complete");
  613. }
  614. /**
  615. * Bootstraping
  616. */
  617. /**
  618. * Load the essential libraries of the engine
  619. *
  620. * @return void
  621. */
  622. protected function bootstrapEngine() {
  623. require_once $this->CONFIG->path . 'engine/load.php';
  624. }
  625. /**
  626. * Load remaining engine libraries and complete bootstraping (see start.php)
  627. *
  628. * @param string $step Which step to boot strap for. Required because
  629. * boot strapping is different until the DB is populated.
  630. *
  631. * @return void
  632. * @throws InstallationException
  633. */
  634. protected function finishBootstraping($step) {
  635. $dbIndex = array_search('database', $this->getSteps());
  636. $settingsIndex = array_search('settings', $this->getSteps());
  637. $adminIndex = array_search('admin', $this->getSteps());
  638. $completeIndex = array_search('complete', $this->getSteps());
  639. $stepIndex = array_search($step, $this->getSteps());
  640. // To log in the user, we need to use the Elgg core session handling.
  641. // Otherwise, use default php session handling
  642. $useElggSession = ($stepIndex == $adminIndex && $this->isAction) ||
  643. $stepIndex == $completeIndex;
  644. if (!$useElggSession) {
  645. session_name('Elgg_install');
  646. session_start();
  647. _elgg_services()->events->unregisterHandler('boot', 'system', 'session_init');
  648. }
  649. if ($stepIndex > $dbIndex) {
  650. // once the database has been created, load rest of engine
  651. $lib_dir = $this->CONFIG->path . 'engine/lib/';
  652. $this->loadSettingsFile();
  653. $lib_files = array(
  654. // these want to be loaded first apparently?
  655. 'autoloader.php',
  656. 'database.php',
  657. 'actions.php',
  658. 'admin.php',
  659. 'annotations.php',
  660. 'cron.php',
  661. 'entities.php',
  662. 'extender.php',
  663. 'filestore.php',
  664. 'group.php',
  665. 'mb_wrapper.php',
  666. 'memcache.php',
  667. 'metadata.php',
  668. 'metastrings.php',
  669. 'navigation.php',
  670. 'notification.php',
  671. 'objects.php',
  672. 'pagehandler.php',
  673. 'pam.php',
  674. 'plugins.php',
  675. 'private_settings.php',
  676. 'relationships.php',
  677. 'river.php',
  678. 'sites.php',
  679. 'statistics.php',
  680. 'tags.php',
  681. 'user_settings.php',
  682. 'users.php',
  683. 'upgrade.php',
  684. 'widgets.php',
  685. 'deprecated-1.7.php',
  686. 'deprecated-1.8.php',
  687. 'deprecated-1.9.php',
  688. );
  689. foreach ($lib_files as $file) {
  690. $path = $lib_dir . $file;
  691. if (!include_once($path)) {
  692. throw new InstallationException('InstallationException:MissingLibrary', array($file));
  693. }
  694. }
  695. _elgg_services()->db->setupConnections();
  696. _elgg_services()->translator->registerTranslations("{$this->getElggRoot()}/languages/");
  697. $this->CONFIG->language = 'en';
  698. if ($stepIndex > $settingsIndex) {
  699. $this->CONFIG->site_guid = (int) _elgg_services()->datalist->get('default_site');
  700. $this->CONFIG->site_id = $this->CONFIG->site_guid;
  701. $this->CONFIG->site = get_entity($this->CONFIG->site_guid);
  702. $this->CONFIG->dataroot = _elgg_services()->datalist->get('dataroot');
  703. _elgg_session_boot();
  704. }
  705. _elgg_services()->events->trigger('init', 'system');
  706. }
  707. }
  708. /**
  709. * Set up configuration variables
  710. *
  711. * @return void
  712. */
  713. protected function bootstrapConfig() {
  714. $this->CONFIG->installer_running = true;
  715. $this->CONFIG->wwwroot = $this->getBaseUrl();
  716. $this->CONFIG->url = $this->CONFIG->wwwroot;
  717. $this->CONFIG->path = "{$this->getElggRoot()}/";
  718. $this->CONFIG->viewpath = $this->CONFIG->path . 'views/';
  719. $this->CONFIG->pluginspath = $this->CONFIG->path . 'mod/';
  720. $this->CONFIG->context = array();
  721. $this->CONFIG->entity_types = array('group', 'object', 'site', 'user');
  722. // required by elgg_view_page()
  723. $this->CONFIG->sitename = '';
  724. $this->CONFIG->sitedescription = '';
  725. // required by Elgg\Config::get
  726. $this->CONFIG->site_guid = 1;
  727. }
  728. /**
  729. * @return bool Whether the install process is encrypted.
  730. */
  731. private function isHttps() {
  732. return (!empty($_SERVER["HTTPS"]) && $_SERVER["HTTPS"] == "on") ||
  733. $_SERVER['SERVER_PORT'] == 443;
  734. }
  735. /**
  736. * Get the best guess at the base URL
  737. *
  738. * @note Cannot use current_page_url() because it depends on $this->CONFIG->wwwroot
  739. * @todo Should this be a core function?
  740. *
  741. * @return string
  742. */
  743. protected function getBaseUrl() {
  744. $protocol = $this->isHttps() ? 'https' : 'http';
  745. if (isset($_SERVER["SERVER_PORT"])) {
  746. $port = ':' . $_SERVER["SERVER_PORT"];
  747. } else {
  748. $port = '';
  749. }
  750. if ($port == ':80' || $port == ':443') {
  751. $port = '';
  752. }
  753. $uri = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : '';
  754. $cutoff = strpos($uri, 'install.php');
  755. $uri = substr($uri, 0, $cutoff);
  756. $serverName = isset($_SERVER['SERVER_NAME']) ? $_SERVER['SERVER_NAME'] : '';
  757. return "$protocol://{$serverName}$port{$uri}";
  758. }
  759. /**
  760. * Load settings.php
  761. *
  762. * @return void
  763. * @throws InstallationException
  764. */
  765. protected function loadSettingsFile() {
  766. if (!include_once("{$this->CONFIG->path}engine/settings.php")) {
  767. throw new InstallationException(_elgg_services()->translator->translate('InstallationException:CannotLoadSettings'));
  768. }
  769. }
  770. /**
  771. * Action handling methods
  772. */
  773. /**
  774. * Return an associative array of post variables
  775. * (could be selective based on expected variables)
  776. *
  777. * Does not filter as person installing the site should not be attempting
  778. * XSS attacks. If filtering is added, it should not be done for passwords.
  779. *
  780. * @return array
  781. */
  782. protected function getPostVariables() {
  783. $vars = array();
  784. foreach ($_POST as $k => $v) {
  785. $vars[$k] = $v;
  786. }
  787. return $vars;
  788. }
  789. /**
  790. * If form is reshown, remember previously submitted variables
  791. *
  792. * @param array $formVars Vars int he form
  793. * @param array $submissionVars Submitted vars
  794. *
  795. * @return array
  796. */
  797. protected function makeFormSticky($formVars, $submissionVars) {
  798. foreach ($submissionVars as $field => $value) {
  799. $formVars[$field]['value'] = $value;
  800. }
  801. return $formVars;
  802. }
  803. /**
  804. * Requirement checks support methods
  805. */
  806. /**
  807. * Check that the engine dir is writable
  808. *
  809. * @param array &$report The requirements report object
  810. *
  811. * @return bool
  812. */
  813. protected function checkEngineDir(&$report) {
  814. $writable = is_writable("{$this->CONFIG->path}engine");
  815. if (!$writable) {
  816. $report['settings'] = array(
  817. array(
  818. 'severity' => 'failure',
  819. 'message' => _elgg_services()->translator->translate('install:check:enginedir'),
  820. )
  821. );
  822. return FALSE;
  823. }
  824. return TRUE;
  825. }
  826. /**
  827. * Check that the settings file exists
  828. *
  829. * @param array &$report The requirements report array
  830. *
  831. * @return bool
  832. */
  833. protected function checkSettingsFile(&$report = array()) {
  834. if (!file_exists("{$this->CONFIG->path}engine/settings.php")) {
  835. return FALSE;
  836. }
  837. if (!is_readable("{$this->CONFIG->path}engine/settings.php")) {
  838. $report['settings'] = array(
  839. array(
  840. 'severity' => 'failure',
  841. 'message' => _elgg_services()->translator->translate('install:check:readsettings'),
  842. )
  843. );
  844. }
  845. return TRUE;
  846. }
  847. /**
  848. * Check version of PHP, extensions, and variables
  849. *
  850. * @param array &$report The requirements report array
  851. *
  852. * @return void
  853. */
  854. protected function checkPHP(&$report) {
  855. $phpReport = array();
  856. $min_php_version = '5.4.0';
  857. if (version_compare(PHP_VERSION, $min_php_version, '<')) {
  858. $phpReport[] = array(
  859. 'severity' => 'failure',
  860. 'message' => _elgg_services()->translator->translate('install:check:php:version', array($min_php_version, PHP_VERSION))
  861. );
  862. }
  863. $this->checkPhpExtensions($phpReport);
  864. $this->checkPhpDirectives($phpReport);
  865. if (count($phpReport) == 0) {
  866. $phpReport[] = array(
  867. 'severity' => 'pass',
  868. 'message' => _elgg_services()->translator->translate('install:check:php:success')
  869. );
  870. }
  871. $report['php'] = $phpReport;
  872. }
  873. /**
  874. * Check the server's PHP extensions
  875. *
  876. * @param array &$phpReport The PHP requirements report array
  877. *
  878. * @return void
  879. */
  880. protected function checkPhpExtensions(&$phpReport) {
  881. $extensions = get_loaded_extensions();
  882. $requiredExtensions = array(
  883. 'mysql',
  884. 'json',
  885. 'xml',
  886. 'gd',
  887. );
  888. foreach ($requiredExtensions as $extension) {
  889. if (!in_array($extension, $extensions)) {
  890. $phpReport[] = array(
  891. 'severity' => 'failure',
  892. 'message' => _elgg_services()->translator->translate('install:check:php:extension', array($extension))
  893. );
  894. }
  895. }
  896. $recommendedExtensions = array(
  897. 'mbstring',
  898. );
  899. foreach ($recommendedExtensions as $extension) {
  900. if (!in_array($extension, $extensions)) {
  901. $phpReport[] = array(
  902. 'severity' => 'warning',
  903. 'message' => _elgg_services()->translator->translate('install:check:php:extension:recommend', array($extension))
  904. );
  905. }
  906. }
  907. }
  908. /**
  909. * Check PHP parameters
  910. *
  911. * @param array &$phpReport The PHP requirements report array
  912. *
  913. * @return void
  914. */
  915. protected function checkPhpDirectives(&$phpReport) {
  916. if (ini_get('open_basedir')) {
  917. $phpReport[] = array(
  918. 'severity' => 'warning',
  919. 'message' => _elgg_services()->translator->translate("install:check:php:open_basedir")
  920. );
  921. }
  922. if (ini_get('safe_mode')) {
  923. $phpReport[] = array(
  924. 'severity' => 'warning',
  925. 'message' => _elgg_services()->translator->translate("install:check:php:safe_mode")
  926. );
  927. }
  928. if (ini_get('arg_separator.output') !== '&') {
  929. $separator = htmlspecialchars(ini_get('arg_separator.output'));
  930. $msg = _elgg_services()->translator->translate("install:check:php:arg_separator", array($separator));
  931. $phpReport[] = array(
  932. 'severity' => 'failure',
  933. 'message' => $msg,
  934. );
  935. }
  936. if (ini_get('register_globals')) {
  937. $phpReport[] = array(
  938. 'severity' => 'failure',
  939. 'message' => _elgg_services()->translator->translate("install:check:php:register_globals")
  940. );
  941. }
  942. if (ini_get('session.auto_start')) {
  943. $phpReport[] = array(
  944. 'severity' => 'failure',
  945. 'message' => _elgg_services()->translator->translate("install:check:php:session.auto_start")
  946. );
  947. }
  948. }
  949. /**
  950. * Confirm that the rewrite rules are firing
  951. *
  952. * @param array &$report The requirements report array
  953. *
  954. * @return void
  955. */
  956. protected function checkRewriteRules(&$report) {
  957. $tester = new ElggRewriteTester();
  958. $url = _elgg_services()->config->getSiteUrl() . "rewrite.php";
  959. $report['rewrite'] = array($tester->run($url, $this->CONFIG->path));
  960. }
  961. /**
  962. * Check if the request is coming from the URL rewrite test on the
  963. * requirements page.
  964. *
  965. * @return void
  966. */
  967. protected function processRewriteTest() {
  968. if (strpos($_SERVER['REQUEST_URI'], 'rewrite.php') !== FALSE) {
  969. echo 'success';
  970. exit;
  971. }
  972. }
  973. /**
  974. * Count the number of failures in the requirements report
  975. *
  976. * @param array $report The requirements report array
  977. * @param string $condition 'failure' or 'warning'
  978. *
  979. * @return int
  980. */
  981. protected function countNumConditions($report, $condition) {
  982. $count = 0;
  983. foreach ($report as $category => $checks) {
  984. foreach ($checks as $check) {
  985. if ($check['severity'] === $condition) {
  986. $count++;
  987. }
  988. }
  989. }
  990. return $count;
  991. }
  992. /**
  993. * Database support methods
  994. */
  995. /**
  996. * Validate the variables for the database step
  997. *
  998. * @param array $submissionVars Submitted vars
  999. * @param array $formVars Vars in the form
  1000. *
  1001. * @return bool
  1002. */
  1003. protected function validateDatabaseVars($submissionVars, $formVars) {
  1004. foreach ($formVars as $field => $info) {
  1005. if ($info['required'] == TRUE && !$submissionVars[$field]) {
  1006. $name = _elgg_services()->translator->translate("install:database:label:$field");
  1007. register_error(_elgg_services()->translator->translate('install:error:requiredfield', array($name)));
  1008. return FALSE;
  1009. }
  1010. }
  1011. // according to postgres documentation: SQL identifiers and key words must
  1012. // begin with a letter (a-z, but also letters with diacritical marks and
  1013. // non-Latin letters) or an underscore (_). Subsequent characters in an
  1014. // identifier or key word can be letters, underscores, digits (0-9), or dollar signs ($).
  1015. // Refs #4994
  1016. if (!preg_match("/^[a-zA-Z_][\w]*$/", $submissionVars['dbprefix'])) {
  1017. register_error(_elgg_services()->translator->translate('install:error:database_prefix'));
  1018. return FALSE;
  1019. }
  1020. return $this->checkDatabaseSettings(
  1021. $submissionVars['dbuser'],
  1022. $submissionVars['dbpassword'],
  1023. $submissionVars['dbname'],
  1024. $submissionVars['dbhost']
  1025. );
  1026. }
  1027. /**
  1028. * Confirm the settings for the database
  1029. *
  1030. * @param string $user Username
  1031. * @param string $password Password
  1032. * @param string $dbname Database name
  1033. * @param string $host Host
  1034. *
  1035. * @return bool
  1036. */
  1037. protected function checkDatabaseSettings($user, $password, $dbname, $host) {
  1038. $config = new \Elgg\Database\Config((object)[
  1039. 'dbhost' => $host,
  1040. 'dbuser' => $user,
  1041. 'dbpass' => $password,
  1042. 'dbname' => $dbname,
  1043. ]);
  1044. $logger = new \Elgg\Logger(new \Elgg\PluginHooksService());
  1045. $db = new \Elgg\Database($config, $logger);
  1046. try {
  1047. $db->getDataRow("SELECT 1");
  1048. } catch (DatabaseException $e) {
  1049. if (0 === strpos($e->getMessage(), "Elgg couldn't connect")) {
  1050. register_error(_elgg_services()->translator->translate('install:error:databasesettings'));
  1051. } else {
  1052. register_error(_elgg_services()->translator->translate('install:error:nodatabase', array($dbname)));
  1053. }
  1054. return FALSE;
  1055. }
  1056. // check MySQL version - must be 5.0 or >
  1057. $version = $db->getServerVersion(\Elgg\Database\Config::READ_WRITE);
  1058. $required_version = 5.0;
  1059. $points = explode('.', $version);
  1060. if ($points[0] < $required_version) {
  1061. register_error(_elgg_services()->translator->translate('install:error:oldmysql', array($version)));
  1062. return FALSE;
  1063. }
  1064. return TRUE;
  1065. }
  1066. /**
  1067. * Writes the settings file to the engine directory
  1068. *
  1069. * @param array $params Array of inputted params from the user
  1070. *
  1071. * @return bool
  1072. */
  1073. protected function createSettingsFile($params) {
  1074. $templateFile = "{$this->CONFIG->path}engine/settings.example.php";
  1075. $template = file_get_contents($templateFile);
  1076. if (!$template) {
  1077. register_error(_elgg_services()->translator->translate('install:error:readsettingsphp'));
  1078. return FALSE;
  1079. }
  1080. foreach ($params as $k => $v) {
  1081. $template = str_replace("{{" . $k . "}}", $v, $template);
  1082. }
  1083. $settingsFilename = "{$this->CONFIG->path}engine/settings.php";
  1084. $result = file_put_contents($settingsFilename, $template);
  1085. if (!$result) {
  1086. register_error(_elgg_services()->translator->translate('install:error:writesettingphp'));
  1087. return FALSE;
  1088. }
  1089. return TRUE;
  1090. }
  1091. /**
  1092. * Bootstrap database connection before entire engine is available
  1093. *
  1094. * @return bool
  1095. */
  1096. protected function connectToDatabase() {
  1097. if (!include_once("{$this->CONFIG->path}engine/settings.php")) {
  1098. register_error('Elgg could not load the settings file. It does not exist or there is a file permissions issue.');
  1099. return FALSE;
  1100. }
  1101. if (!include_once("{$this->CONFIG->path}engine/lib/database.php")) {
  1102. register_error('Could not load database.php');
  1103. return FALSE;
  1104. }
  1105. try {
  1106. _elgg_services()->db->setupConnections();
  1107. } catch (DatabaseException $e) {
  1108. register_error($e->getMessage());
  1109. return FALSE;
  1110. }
  1111. return TRUE;
  1112. }
  1113. /**
  1114. * Create the database tables
  1115. *
  1116. * @return bool
  1117. */
  1118. protected function installDatabase() {
  1119. try {
  1120. _elgg_services()->db->runSqlScript("{$this->CONFIG->path}engine/schema/mysql.sql");
  1121. } catch (Exception $e) {
  1122. $msg = $e->getMessage();
  1123. if (strpos($msg, 'already exists')) {
  1124. $msg = _elgg_services()->translator->translate('install:error:tables_exist');
  1125. }
  1126. register_error($msg);
  1127. return FALSE;
  1128. }
  1129. return TRUE;
  1130. }
  1131. /**
  1132. * Site settings support methods
  1133. */
  1134. /**
  1135. * Create the data directory if requested
  1136. *
  1137. * @param array &$submissionVars Submitted vars
  1138. * @param array $formVars Variables in the form
  1139. *
  1140. * @return bool
  1141. */
  1142. protected function createDataDirectory(&$submissionVars, $formVars) {
  1143. // did the user have option of Elgg creating the data directory
  1144. if ($formVars['dataroot']['type'] != 'combo') {
  1145. return TRUE;
  1146. }
  1147. // did the user select the option
  1148. if ($submissionVars['dataroot'] != 'dataroot-checkbox') {
  1149. return TRUE;
  1150. }
  1151. $dir = sanitise_filepath($submissionVars['path']) . 'data';
  1152. if (file_exists($dir) || mkdir($dir, 0700)) {
  1153. $submissionVars['dataroot'] = $dir;
  1154. if (!file_exists("$dir/.htaccess")) {
  1155. $htaccess = "Order Deny,Allow\nDeny from All\n";
  1156. if (!file_put_contents("$dir/.htaccess", $htaccess)) {
  1157. return FALSE;
  1158. }
  1159. }
  1160. return TRUE;
  1161. }
  1162. return FALSE;
  1163. }
  1164. /**
  1165. * Validate the site settings form variables
  1166. *
  1167. * @param array $submissionVars Submitted vars
  1168. * @param array $formVars Vars in the form
  1169. *
  1170. * @return bool
  1171. */
  1172. protected function validateSettingsVars($submissionVars, $formVars) {
  1173. foreach ($formVars as $field => $info) {
  1174. $submissionVars[$field] = trim($submissionVars[$field]);
  1175. if ($info['required'] == TRUE && $submissionVars[$field] === '') {
  1176. $name = _elgg_services()->translator->translate("install:settings:label:$field");
  1177. register_error(_elgg_services()->translator->translate('install:error:requiredfield', array($name)));
  1178. return FALSE;
  1179. }
  1180. }
  1181. // check that data root is absolute path
  1182. if (stripos(PHP_OS, 'win') === 0) {
  1183. if (strpos($submissionVars['dataroot'], ':') !== 1) {
  1184. $msg = _elgg_services()->translator->translate('install:error:relative_path', array($submissionVars['dataroot']));
  1185. register_error($msg);
  1186. return FALSE;
  1187. }
  1188. } else {
  1189. if (strpos($submissionVars['dataroot'], '/') !== 0) {
  1190. $msg = _elgg_services()->translator->translate('install:error:relative_path', array($submissionVars['dataroot']));
  1191. register_error($msg);
  1192. return FALSE;
  1193. }
  1194. }
  1195. // check that data root exists
  1196. if (!file_exists($submissionVars['dataroot'])) {
  1197. $msg = _elgg_services()->translator->translate('install:error:datadirectoryexists', array($submissionVars['dataroot']));
  1198. register_error($msg);
  1199. return FALSE;
  1200. }
  1201. // check that data root is writable
  1202. if (!is_writable($submissionVars['dataroot'])) {
  1203. $msg = _elgg_services()->translator->translate('install:error:writedatadirectory', array($submissionVars['dataroot']));
  1204. register_error($msg);
  1205. return FALSE;
  1206. }
  1207. if (!isset($this->CONFIG->data_dir_override) || !$this->CONFIG->data_dir_override) {
  1208. // check that data root is not subdirectory of Elgg root
  1209. if (stripos($submissionVars['dataroot'], $submissionVars['path']) === 0) {
  1210. $msg = _elgg_services()->translator->translate('install:error:locationdatadirectory', array($submissionVars['dataroot']));
  1211. register_error($msg);
  1212. return FALSE;
  1213. }
  1214. }
  1215. // check that email address is email address
  1216. if ($submissionVars['siteemail'] && !is_email_address($submissionVars['siteemail'])) {
  1217. $msg = _elgg_services()->translator->translate('install:error:emailaddress', array($submissionVars['siteemail']));
  1218. register_error($msg);
  1219. return FALSE;
  1220. }
  1221. // @todo check that url is a url
  1222. // @note filter_var cannot be used because it doesn't work on international urls
  1223. return TRUE;
  1224. }
  1225. /**
  1226. * Initialize the site including site entity, plugins, and configuration
  1227. *
  1228. * @param array $submissionVars Submitted vars
  1229. *
  1230. * @return bool
  1231. */
  1232. protected function saveSiteSettings($submissionVars) {
  1233. // ensure that file path, data path, and www root end in /
  1234. $submissionVars['dataroot'] = sanitise_filepath($submissionVars['dataroot']);
  1235. $submissionVars['wwwroot'] = sanitise_filepath($submissionVars['wwwroot']);
  1236. $site = new ElggSite();
  1237. $site->name = strip_tags($submissionVars['sitename']);
  1238. $site->url = $submissionVars['wwwroot'];
  1239. $site->access_id = ACCESS_PUBLIC;
  1240. $site->email = $submissionVars['siteemail'];
  1241. $guid = $site->save();
  1242. if (!$guid) {
  1243. register_error(_elgg_services()->translator->translate('install:error:createsite'));
  1244. return FALSE;
  1245. }
  1246. // bootstrap site info
  1247. $this->CONFIG->site_guid = $guid;
  1248. $this->CONFIG->site_id = $guid;
  1249. $this->CONFIG->site = $site;
  1250. _elgg_services()->datalist->set('installed', time());
  1251. _elgg_services()->datalist->set('dataroot', $submissionVars['dataroot']);
  1252. _elgg_services()->datalist->set('default_site', $site->getGUID());
  1253. _elgg_services()->datalist->set('version', elgg_get_version());
  1254. _elgg_services()->datalist->set('simplecache_enabled', 1);
  1255. _elgg_services()->datalist->set('system_cache_enabled', 1);
  1256. _elgg_services()->datalist->set('simplecache_lastupdate', time());
  1257. // @todo plugins might use this, but core doesn't. remove in 2.0
  1258. _elgg_services()->datalist->set('path', $this->CONFIG->path);
  1259. // new installations have run all the upgrades
  1260. $upgrades = elgg_get_upgrade_files("{$this->CONFIG->path}engine/lib/upgrades/");
  1261. _elgg_services()->datalist->set('processed_upgrades', serialize($upgrades));
  1262. _elgg_services()->configTable->set('view', 'default', $site->getGUID());
  1263. _elgg_services()->configTable->set('language', 'en', $site->getGUID());
  1264. _elgg_services()->configTable->set('default_access', $submissionVars['siteaccess'], $site->getGUID());
  1265. _elgg_services()->configTable->set('allow_registration', TRUE, $site->getGUID());
  1266. _elgg_services()->configTable->set('walled_garden', FALSE, $site->getGUID());
  1267. _elgg_services()->configTable->set('allow_user_default_access', '', $site->getGUID());
  1268. _elgg_services()->configTable->set('default_limit', 10, $site->getGUID());
  1269. $this->setSubtypeClasses();
  1270. $this->enablePlugins();
  1271. return TRUE;
  1272. }
  1273. /**
  1274. * Register classes for core objects
  1275. *
  1276. * @return void
  1277. */
  1278. protected function setSubtypeClasses() {
  1279. add_subtype("object", "plugin", "ElggPlugin");
  1280. add_subtype("object", "file", "ElggFile");
  1281. add_subtype("object", "widget", "ElggWidget");
  1282. add_subtype("object", "comment", "ElggComment");
  1283. add_subtype("object", "elgg_upgrade", 'ElggUpgrade');
  1284. }
  1285. /**
  1286. * Enable a set of default plugins
  1287. *
  1288. * @return void
  1289. */
  1290. protected function enablePlugins() {
  1291. _elgg_generate_plugin_entities();
  1292. $plugins = elgg_get_plugins('any');
  1293. foreach ($plugins as $plugin) {
  1294. if ($plugin->getManifest()) {
  1295. if ($plugin->getManifest()->getActivateOnInstall()) {
  1296. $plugin->activate();
  1297. }
  1298. if (in_array('theme', $plugin->getManifest()->getCategories())) {
  1299. $plugin->setPriority('last');
  1300. }
  1301. }
  1302. }
  1303. }
  1304. /**
  1305. * Admin account support methods
  1306. */
  1307. /**
  1308. * Validate account form variables
  1309. *
  1310. * @param array $submissionVars Submitted vars
  1311. * @param array $formVars Form vars
  1312. *
  1313. * @return bool
  1314. */
  1315. protected function validateAdminVars($submissionVars, $formVars) {
  1316. foreach ($formVars as $field => $info) {
  1317. if ($info['required'] == TRUE && !$submissionVars[$field]) {
  1318. $name = _elgg_services()->translator->translate("install:admin:label:$field");
  1319. register_error(_elgg_services()->translator->translate('install:error:requiredfield', array($name)));
  1320. return FALSE;
  1321. }
  1322. }
  1323. if ($submissionVars['password1'] !== $submissionVars['password2']) {
  1324. register_error(_elgg_services()->translator->translate('install:admin:password:mismatch'));
  1325. return FALSE;
  1326. }
  1327. if (trim($submissionVars['password1']) == "") {
  1328. register_error(_elgg_services()->translator->translate('install:admin:password:empty'));
  1329. return FALSE;
  1330. }
  1331. $minLength = _elgg_services()->configTable->get('min_password_length');
  1332. if (strlen($submissionVars['password1']) < $minLength) {
  1333. register_error(_elgg_services()->translator->translate('install:admin:password:tooshort'));
  1334. return FALSE;
  1335. }
  1336. // check that email address is email address
  1337. if ($submissionVars['email'] && !is_email_address($submissionVars['email'])) {
  1338. $msg = _elgg_services()->translator->translate('install:error:emailaddress', array($submissionVars['email']));
  1339. register_error($msg);
  1340. return FALSE;
  1341. }
  1342. return TRUE;
  1343. }
  1344. /**
  1345. * Create a user account for the admin
  1346. *
  1347. * @param array $submissionVars Submitted vars
  1348. * @param bool $login Login in the admin user?
  1349. *
  1350. * @return bool
  1351. */
  1352. protected function createAdminAccount($submissionVars, $login = FALSE) {
  1353. try {
  1354. $guid = register_user(
  1355. $submissionVars['username'],
  1356. $submissionVars['password1'],
  1357. $submissionVars['displayname'],
  1358. $submissionVars['email']
  1359. );
  1360. } catch (Exception $e) {
  1361. register_error($e->getMessage());
  1362. return false;
  1363. }
  1364. if (!$guid) {
  1365. register_error(_elgg_services()->translator->translate('install:admin:cannot_create'));
  1366. return false;
  1367. }
  1368. $user = get_entity($guid);
  1369. if (!$user instanceof ElggUser) {
  1370. register_error(_elgg_services()->translator->translate('install:error:loadadmin'));
  1371. return false;
  1372. }
  1373. elgg_set_ignore_access(TRUE);
  1374. if ($user->makeAdmin() == FALSE) {
  1375. register_error(_elgg_services()->translator->translate('install:error:adminaccess'));
  1376. } else {
  1377. _elgg_services()->datalist->set('admin_registered', 1);
  1378. }
  1379. elgg_set_ignore_access(false);
  1380. // add validation data to satisfy user validation plugins
  1381. create_metadata($guid, 'validated', TRUE, '', 0, ACCESS_PUBLIC);
  1382. create_metadata($guid, 'validated_method', 'admin_user', '', 0, ACCESS_PUBLIC);
  1383. if ($login) {
  1384. $handler = new Elgg\Http\DatabaseSessionHandler(_elgg_services()->db);
  1385. // session.cache_limiter is unfortunately set to "" by the NativeSessionStorage constructor,
  1386. // so we must capture and inject it directly.
  1387. $options = [
  1388. 'cache_limiter' => session_cache_limiter(),
  1389. ];
  1390. $storage = new Symfony\Component\HttpFoundation\Session\Storage\NativeSessionStorage($options, $handler);
  1391. $session = new ElggSession(new Symfony\Component\HttpFoundation\Session\Session($storage));
  1392. $session->setName('Elgg');
  1393. _elgg_services()->setValue('session', $session);
  1394. if (login($user) == FALSE) {
  1395. register_error(_elgg_services()->translator->translate('install:error:adminlogin'));
  1396. }
  1397. }
  1398. return TRUE;
  1399. }
  1400. }