installer.php 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652
  1. <?php
  2. /**
  3. * StatusNet - the distributed open-source microblogging tool
  4. * Copyright (C) 2009-2010, StatusNet, Inc.
  5. *
  6. * This program is free software: you can redistribute it and/or modify
  7. * it under the terms of the GNU Affero General Public License as published by
  8. * the Free Software Foundation, either version 3 of the License, or
  9. * (at your option) any later version.
  10. *
  11. * This program is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. * GNU Affero General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU Affero General Public License
  17. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  18. *
  19. * @category Installation
  20. * @package Installation
  21. *
  22. * @author Adrian Lang <mail@adrianlang.de>
  23. * @author Brenda Wallace <shiny@cpan.org>
  24. * @author Brett Taylor <brett@webfroot.co.nz>
  25. * @author Brion Vibber <brion@pobox.com>
  26. * @author CiaranG <ciaran@ciarang.com>
  27. * @author Craig Andrews <candrews@integralblue.com>
  28. * @author Eric Helgeson <helfire@Erics-MBP.local>
  29. * @author Evan Prodromou <evan@status.net>
  30. * @author Mikael Nordfeldth <mmn@hethane.se>
  31. * @author Robin Millette <millette@controlyourself.ca>
  32. * @author Sarven Capadisli <csarven@status.net>
  33. * @author Tom Adams <tom@holizz.com>
  34. * @author Zach Copley <zach@status.net>
  35. * @copyright 2009-2010 StatusNet, Inc http://status.net
  36. * @copyright 2009-2014 Free Software Foundation, Inc http://www.fsf.org
  37. * @license GNU Affero General Public License http://www.gnu.org/licenses/
  38. * @version 1.0.x
  39. * @link http://status.net
  40. */
  41. abstract class Installer
  42. {
  43. /** Web site info */
  44. public $sitename, $server, $path, $fancy, $siteProfile, $ssl;
  45. /** DB info */
  46. public $host, $database, $dbtype, $username, $password, $db;
  47. /** Administrator info */
  48. public $adminNick, $adminPass, $adminEmail;
  49. /** Should we skip writing the configuration file? */
  50. public $skipConfig = false;
  51. public static $dbModules = array(
  52. 'mysql' => array(
  53. 'name' => 'MariaDB (or MySQL 5.5+)',
  54. 'check_module' => 'mysqli',
  55. 'scheme' => 'mysqli', // DSN prefix for PEAR::DB
  56. ),
  57. /* 'pgsql' => array(
  58. 'name' => 'PostgreSQL',
  59. 'check_module' => 'pgsql',
  60. 'scheme' => 'pgsql', // DSN prefix for PEAR::DB
  61. ),*/
  62. );
  63. /**
  64. * Attempt to include a PHP file and report if it worked, while
  65. * suppressing the annoying warning messages on failure.
  66. */
  67. private function haveIncludeFile($filename) {
  68. $old = error_reporting(error_reporting() & ~E_WARNING);
  69. $ok = include_once($filename);
  70. error_reporting($old);
  71. return $ok;
  72. }
  73. /**
  74. * Check if all is ready for installation
  75. *
  76. * @return void
  77. */
  78. function checkPrereqs()
  79. {
  80. $pass = true;
  81. $config = INSTALLDIR.'/config.php';
  82. if (file_exists($config)) {
  83. if (!is_writable($config) || filesize($config) > 0) {
  84. if (filesize($config) == 0) {
  85. $this->warning('Config file "config.php" already exists and is empty, but is not writable.');
  86. } else {
  87. $this->warning('Config file "config.php" already exists.');
  88. }
  89. $pass = false;
  90. }
  91. }
  92. if (version_compare(PHP_VERSION, '5.5.0', '<')) {
  93. $this->warning('Require PHP version 5.5.0 or greater.');
  94. $pass = false;
  95. }
  96. $reqs = array('gd', 'curl', 'intl', 'json',
  97. 'xmlwriter', 'mbstring', 'xml', 'dom', 'simplexml');
  98. foreach ($reqs as $req) {
  99. if (!$this->checkExtension($req)) {
  100. $this->warning(sprintf('Cannot load required extension: <code>%s</code>', $req));
  101. $pass = false;
  102. }
  103. }
  104. // Make sure we have at least one database module available
  105. $missingExtensions = array();
  106. foreach (self::$dbModules as $type => $info) {
  107. if (!$this->checkExtension($info['check_module'])) {
  108. $missingExtensions[] = $info['check_module'];
  109. }
  110. }
  111. if (count($missingExtensions) == count(self::$dbModules)) {
  112. $req = implode(', ', $missingExtensions);
  113. $this->warning(sprintf('Cannot find a database extension. You need at least one of %s.', $req));
  114. $pass = false;
  115. }
  116. // @fixme this check seems to be insufficient with Windows ACLs
  117. if (!is_writable(INSTALLDIR)) {
  118. $this->warning(sprintf('Cannot write config file to: <code>%s</code></p>', INSTALLDIR),
  119. sprintf('On your server, try this command: <code>chmod a+w %s</code>', INSTALLDIR));
  120. $pass = false;
  121. }
  122. // Check the subdirs used for file uploads
  123. $fileSubdirs = array('avatar', 'file');
  124. foreach ($fileSubdirs as $fileSubdir) {
  125. $fileFullPath = INSTALLDIR."/$fileSubdir";
  126. if (!file_exists($fileFullPath)) {
  127. $pass = $pass && mkdir($fileFullPath);
  128. } elseif (!is_dir($fileFullPath)) {
  129. $this->warning(sprintf('GNU social expected a directory but found something else on this path: %s', $fileFullPath),
  130. 'Either make sure it goes to a directory or remove it and a directory will be created.');
  131. $pass = false;
  132. } elseif (!is_writable($fileFullPath)) {
  133. $this->warning(sprintf('Cannot write to %s directory: <code>%s</code>', $fileSubdir, $fileFullPath),
  134. sprintf('On your server, try this command: <code>chmod a+w %s</code>', $fileFullPath));
  135. $pass = false;
  136. }
  137. }
  138. return $pass;
  139. }
  140. /**
  141. * Checks if a php extension is both installed and loaded
  142. *
  143. * @param string $name of extension to check
  144. *
  145. * @return boolean whether extension is installed and loaded
  146. */
  147. function checkExtension($name)
  148. {
  149. if (extension_loaded($name)) {
  150. return true;
  151. } elseif (function_exists('dl') && ini_get('enable_dl') && !ini_get('safe_mode')) {
  152. // dl will throw a fatal error if it's disabled or we're in safe mode.
  153. // More fun, it may not even exist under some SAPIs in 5.3.0 or later...
  154. $soname = $name . '.' . PHP_SHLIB_SUFFIX;
  155. if (PHP_SHLIB_SUFFIX == 'dll') {
  156. $soname = "php_" . $soname;
  157. }
  158. return @dl($soname);
  159. } else {
  160. return false;
  161. }
  162. }
  163. /**
  164. * Basic validation on the database paramters
  165. * Side effects: error output if not valid
  166. *
  167. * @return boolean success
  168. */
  169. function validateDb()
  170. {
  171. $fail = false;
  172. if (empty($this->host)) {
  173. $this->updateStatus("No hostname specified.", true);
  174. $fail = true;
  175. }
  176. if (empty($this->database)) {
  177. $this->updateStatus("No database specified.", true);
  178. $fail = true;
  179. }
  180. if (empty($this->username)) {
  181. $this->updateStatus("No username specified.", true);
  182. $fail = true;
  183. }
  184. if (empty($this->sitename)) {
  185. $this->updateStatus("No sitename specified.", true);
  186. $fail = true;
  187. }
  188. return !$fail;
  189. }
  190. /**
  191. * Basic validation on the administrator user paramters
  192. * Side effects: error output if not valid
  193. *
  194. * @return boolean success
  195. */
  196. function validateAdmin()
  197. {
  198. $fail = false;
  199. if (empty($this->adminNick)) {
  200. $this->updateStatus("No initial user nickname specified.", true);
  201. $fail = true;
  202. }
  203. if ($this->adminNick && !preg_match('/^[0-9a-z]{1,64}$/', $this->adminNick)) {
  204. $this->updateStatus('The user nickname "' . htmlspecialchars($this->adminNick) .
  205. '" is invalid; should be plain letters and numbers no longer than 64 characters.', true);
  206. $fail = true;
  207. }
  208. // @fixme hardcoded list; should use Nickname::isValid()
  209. // if/when it's safe to have loaded the infrastructure here
  210. $blacklist = array('main', 'panel', 'twitter', 'settings', 'rsd.xml', 'favorited', 'featured', 'favoritedrss', 'featuredrss', 'rss', 'getfile', 'api', 'groups', 'group', 'peopletag', 'tag', 'user', 'message', 'conversation', 'notice', 'attachment', 'search', 'index.php', 'doc', 'opensearch', 'robots.txt', 'xd_receiver.html', 'facebook', 'activity');
  211. if (in_array($this->adminNick, $blacklist)) {
  212. $this->updateStatus('The user nickname "' . htmlspecialchars($this->adminNick) .
  213. '" is reserved.', true);
  214. $fail = true;
  215. }
  216. if (empty($this->adminPass)) {
  217. $this->updateStatus("No initial user password specified.", true);
  218. $fail = true;
  219. }
  220. return !$fail;
  221. }
  222. /**
  223. * Make sure a site profile was selected
  224. *
  225. * @return type boolean success
  226. */
  227. function validateSiteProfile()
  228. {
  229. if (empty($this->siteProfile)) {
  230. $this->updateStatus("No site profile selected.", true);
  231. return false;
  232. }
  233. return true;
  234. }
  235. /**
  236. * Set up the database with the appropriate function for the selected type...
  237. * Saves database info into $this->db.
  238. *
  239. * @fixme escape things in the connection string in case we have a funny pass etc
  240. * @return mixed array of database connection params on success, false on failure
  241. */
  242. function setupDatabase()
  243. {
  244. if ($this->db) {
  245. throw new Exception("Bad order of operations: DB already set up.");
  246. }
  247. $this->updateStatus("Starting installation...");
  248. if (empty($this->password)) {
  249. $auth = '';
  250. } else {
  251. $auth = ":$this->password";
  252. }
  253. $scheme = self::$dbModules[$this->dbtype]['scheme'];
  254. $dsn = "{$scheme}://{$this->username}{$auth}@{$this->host}/{$this->database}";
  255. $this->updateStatus("Checking database...");
  256. $conn = $this->connectDatabase($dsn);
  257. // ensure database encoding is UTF8
  258. if ($this->dbtype == 'mysql') {
  259. // @fixme utf8m4 support for mysql 5.5?
  260. // Force the comms charset to utf8 for sanity
  261. // This doesn't currently work. :P
  262. //$conn->executes('set names utf8');
  263. } else if ($this->dbtype == 'pgsql') {
  264. $record = $conn->getRow('SHOW server_encoding');
  265. if ($record->server_encoding != 'UTF8') {
  266. $this->updateStatus("GNU social requires UTF8 character encoding. Your database is ". htmlentities($record->server_encoding));
  267. return false;
  268. }
  269. }
  270. if (!$conn instanceof DB_common) {
  271. // Is not the right instance
  272. throw new Exception('Cannot connect to database: ' . $conn->getMessage());
  273. }
  274. $res = $this->updateStatus("Creating database tables...");
  275. if (!$this->createCoreTables($conn)) {
  276. $this->updateStatus("Error creating tables.", true);
  277. return false;
  278. }
  279. foreach (array('sms_carrier' => 'SMS carrier',
  280. 'notice_source' => 'notice source',
  281. 'foreign_services' => 'foreign service')
  282. as $scr => $name) {
  283. $this->updateStatus(sprintf("Adding %s data to database...", $name));
  284. $res = $this->runDbScript($scr.'.sql', $conn);
  285. if ($res === false) {
  286. $this->updateStatus(sprintf("Can't run %s script.", $name), true);
  287. return false;
  288. }
  289. }
  290. $db = array('type' => $this->dbtype, 'database' => $dsn);
  291. return $db;
  292. }
  293. /**
  294. * Open a connection to the database.
  295. *
  296. * @param <type> $dsn
  297. * @return <type>
  298. */
  299. function connectDatabase($dsn)
  300. {
  301. global $_DB;
  302. return $_DB->connect($dsn);
  303. }
  304. /**
  305. * Create core tables on the given database connection.
  306. *
  307. * @param DB_common $conn
  308. */
  309. function createCoreTables(DB_common $conn)
  310. {
  311. $schema = Schema::get($conn);
  312. $tableDefs = $this->getCoreSchema();
  313. foreach ($tableDefs as $name => $def) {
  314. if (defined('DEBUG_INSTALLER')) {
  315. echo " $name ";
  316. }
  317. $schema->ensureTable($name, $def);
  318. }
  319. return true;
  320. }
  321. /**
  322. * Fetch the core table schema definitions.
  323. *
  324. * @return array of table names => table def arrays
  325. */
  326. function getCoreSchema()
  327. {
  328. $schema = array();
  329. include INSTALLDIR . '/db/core.php';
  330. return $schema;
  331. }
  332. /**
  333. * Return a parseable PHP literal for the given value.
  334. * This will include quotes for strings, etc.
  335. *
  336. * @param mixed $val
  337. * @return string
  338. */
  339. function phpVal($val)
  340. {
  341. return var_export($val, true);
  342. }
  343. /**
  344. * Return an array of parseable PHP literal for the given values.
  345. * These will include quotes for strings, etc.
  346. *
  347. * @param mixed $val
  348. * @return array
  349. */
  350. function phpVals($map)
  351. {
  352. return array_map(array($this, 'phpVal'), $map);
  353. }
  354. /**
  355. * Write a stock configuration file.
  356. *
  357. * @return boolean success
  358. *
  359. * @fixme escape variables in output in case we have funny chars, apostrophes etc
  360. */
  361. function writeConf()
  362. {
  363. $vals = $this->phpVals(array(
  364. 'sitename' => $this->sitename,
  365. 'server' => $this->server,
  366. 'path' => $this->path,
  367. 'ssl' => in_array($this->ssl, array('never', 'always'))
  368. ? $this->ssl
  369. : 'never',
  370. 'db_database' => $this->db['database'],
  371. 'db_type' => $this->db['type']
  372. ));
  373. // assemble configuration file in a string
  374. $cfg = "<?php\n".
  375. "if (!defined('GNUSOCIAL')) { exit(1); }\n\n".
  376. // site name
  377. "\$config['site']['name'] = {$vals['sitename']};\n\n".
  378. // site location
  379. "\$config['site']['server'] = {$vals['server']};\n".
  380. "\$config['site']['path'] = {$vals['path']}; \n\n".
  381. "\$config['site']['ssl'] = {$vals['ssl']}; \n\n".
  382. // checks if fancy URLs are enabled
  383. ($this->fancy ? "\$config['site']['fancy'] = true;\n\n":'').
  384. // database
  385. "\$config['db']['database'] = {$vals['db_database']};\n\n".
  386. ($this->db['type'] == 'pgsql' ? "\$config['db']['quote_identifiers'] = true;\n\n":'').
  387. "\$config['db']['type'] = {$vals['db_type']};\n\n".
  388. "// Uncomment below for better performance. Just remember you must run\n".
  389. "// php scripts/checkschema.php whenever your enabled plugins change!\n".
  390. "//\$config['db']['schemacheck'] = 'script';\n\n";
  391. // Normalize line endings for Windows servers
  392. $cfg = str_replace("\n", PHP_EOL, $cfg);
  393. // write configuration file out to install directory
  394. $res = file_put_contents(INSTALLDIR.'/config.php', $cfg);
  395. return $res;
  396. }
  397. /**
  398. * Write the site profile. We do this after creating the initial user
  399. * in case the site profile is set to single user. This gets around the
  400. * 'chicken-and-egg' problem of the system requiring a valid user for
  401. * single user mode, before the intial user is actually created. Yeah,
  402. * we should probably do this in smarter way.
  403. *
  404. * @return int res number of bytes written
  405. */
  406. function writeSiteProfile()
  407. {
  408. $vals = $this->phpVals(array(
  409. 'site_profile' => $this->siteProfile,
  410. 'nickname' => $this->adminNick
  411. ));
  412. $cfg =
  413. // site profile
  414. "\$config['site']['profile'] = {$vals['site_profile']};\n";
  415. if ($this->siteProfile == "singleuser") {
  416. $cfg .= "\$config['singleuser']['nickname'] = {$vals['nickname']};\n\n";
  417. } else {
  418. $cfg .= "\n";
  419. }
  420. // Normalize line endings for Windows servers
  421. $cfg = str_replace("\n", PHP_EOL, $cfg);
  422. // write configuration file out to install directory
  423. $res = file_put_contents(INSTALLDIR.'/config.php', $cfg, FILE_APPEND);
  424. return $res;
  425. }
  426. /**
  427. * Install schema into the database
  428. *
  429. * @param string $filename location of database schema file
  430. * @param DB_common $conn connection to database
  431. *
  432. * @return boolean - indicating success or failure
  433. */
  434. function runDbScript($filename, DB_common $conn)
  435. {
  436. $sql = trim(file_get_contents(INSTALLDIR . '/db/' . $filename));
  437. $stmts = explode(';', $sql);
  438. foreach ($stmts as $stmt) {
  439. $stmt = trim($stmt);
  440. if (!mb_strlen($stmt)) {
  441. continue;
  442. }
  443. try {
  444. $res = $conn->simpleQuery($stmt);
  445. } catch (Exception $e) {
  446. $error = $e->getMessage();
  447. $this->updateStatus("ERROR ($error) for SQL '$stmt'");
  448. return false;
  449. }
  450. }
  451. return true;
  452. }
  453. /**
  454. * Create the initial admin user account.
  455. * Side effect: may load portions of GNU social framework.
  456. * Side effect: outputs program info
  457. */
  458. function registerInitialUser()
  459. {
  460. require_once INSTALLDIR . '/lib/common.php';
  461. $data = array('nickname' => $this->adminNick,
  462. 'password' => $this->adminPass,
  463. 'fullname' => $this->adminNick);
  464. if ($this->adminEmail) {
  465. $data['email'] = $this->adminEmail;
  466. }
  467. try {
  468. $user = User::register($data, true); // true to skip email sending verification
  469. } catch (Exception $e) {
  470. return false;
  471. }
  472. // give initial user carte blanche
  473. $user->grantRole('owner');
  474. $user->grantRole('moderator');
  475. $user->grantRole('administrator');
  476. return true;
  477. }
  478. /**
  479. * The beef of the installer!
  480. * Create database, config file, and admin user.
  481. *
  482. * Prerequisites: validation of input data.
  483. *
  484. * @return boolean success
  485. */
  486. function doInstall()
  487. {
  488. global $config;
  489. $this->updateStatus("Initializing...");
  490. ini_set('display_errors', 1);
  491. error_reporting(E_ALL & ~E_STRICT & ~E_NOTICE);
  492. if (!defined('GNUSOCIAL')) {
  493. define('GNUSOCIAL', true);
  494. }
  495. if (!defined('STATUSNET')) {
  496. define('STATUSNET', true);
  497. }
  498. require_once INSTALLDIR . '/lib/framework.php';
  499. GNUsocial::initDefaults($this->server, $this->path);
  500. if ($this->siteProfile == "singleuser") {
  501. // Until we use ['site']['profile']==='singleuser' everywhere
  502. $config['singleuser']['enabled'] = true;
  503. }
  504. try {
  505. $this->db = $this->setupDatabase();
  506. if (!$this->db) {
  507. // database connection failed, do not move on to create config file.
  508. return false;
  509. }
  510. } catch (Exception $e) {
  511. // Lower-level DB error!
  512. $this->updateStatus("Database error: " . $e->getMessage(), true);
  513. return false;
  514. }
  515. // Make sure we can write to the file twice
  516. $oldUmask = umask(000);
  517. if (!$this->skipConfig) {
  518. $this->updateStatus("Writing config file...");
  519. $res = $this->writeConf();
  520. if (!$res) {
  521. $this->updateStatus("Can't write config file.", true);
  522. return false;
  523. }
  524. }
  525. if (!empty($this->adminNick)) {
  526. // Okay, cross fingers and try to register an initial user
  527. if ($this->registerInitialUser()) {
  528. $this->updateStatus(
  529. "An initial user with the administrator role has been created."
  530. );
  531. } else {
  532. $this->updateStatus(
  533. "Could not create initial user account.",
  534. true
  535. );
  536. return false;
  537. }
  538. }
  539. if (!$this->skipConfig) {
  540. $this->updateStatus("Setting site profile...");
  541. $res = $this->writeSiteProfile();
  542. if (!$res) {
  543. $this->updateStatus("Can't write to config file.", true);
  544. return false;
  545. }
  546. }
  547. // Restore original umask
  548. umask($oldUmask);
  549. // Set permissions back to something decent
  550. chmod(INSTALLDIR.'/config.php', 0644);
  551. $scheme = $this->ssl === 'always' ? 'https' : 'http';
  552. $link = "{$scheme}://{$this->server}/{$this->path}";
  553. $this->updateStatus("GNU social has been installed at $link");
  554. $this->updateStatus(
  555. '<strong>DONE!</strong> You can visit your <a href="'.htmlspecialchars($link).'">new GNU social site</a> (log in as "'.htmlspecialchars($this->adminNick).'"). If this is your first GNU social install, make your experience the best possible by visiting our resource site to join the <a href="https://gnu.io/social/resources/">mailing list or IRC</a>. <a href="'.htmlspecialchars($link).'/doc/faq">FAQ is found here</a>.'
  556. );
  557. return true;
  558. }
  559. /**
  560. * Output a pre-install-time warning message
  561. * @param string $message HTML ok, but should be plaintext-able
  562. * @param string $submessage HTML ok, but should be plaintext-able
  563. */
  564. abstract function warning($message, $submessage='');
  565. /**
  566. * Output an install-time progress message
  567. * @param string $message HTML ok, but should be plaintext-able
  568. * @param boolean $error true if this should be marked as an error condition
  569. */
  570. abstract function updateStatus($status, $error=false);
  571. }