installer.php 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642
  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.3.2', '<')) {
  93. $this->warning('Require PHP version 5.3.2 or greater.');
  94. $pass = false;
  95. }
  96. $reqs = array('gd', 'curl', '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', 'background', 'file');
  124. foreach ($fileSubdirs as $fileSubdir) {
  125. $fileFullPath = INSTALLDIR."/$fileSubdir/";
  126. if (!is_writable($fileFullPath)) {
  127. $this->warning(sprintf('Cannot write to %s directory: <code>%s</code>', $fileSubdir, $fileFullPath),
  128. sprintf('On your server, try this command: <code>chmod a+w %s</code>', $fileFullPath));
  129. $pass = false;
  130. }
  131. }
  132. return $pass;
  133. }
  134. /**
  135. * Checks if a php extension is both installed and loaded
  136. *
  137. * @param string $name of extension to check
  138. *
  139. * @return boolean whether extension is installed and loaded
  140. */
  141. function checkExtension($name)
  142. {
  143. if (extension_loaded($name)) {
  144. return true;
  145. } elseif (function_exists('dl') && ini_get('enable_dl') && !ini_get('safe_mode')) {
  146. // dl will throw a fatal error if it's disabled or we're in safe mode.
  147. // More fun, it may not even exist under some SAPIs in 5.3.0 or later...
  148. $soname = $name . '.' . PHP_SHLIB_SUFFIX;
  149. if (PHP_SHLIB_SUFFIX == 'dll') {
  150. $soname = "php_" . $soname;
  151. }
  152. return @dl($soname);
  153. } else {
  154. return false;
  155. }
  156. }
  157. /**
  158. * Basic validation on the database paramters
  159. * Side effects: error output if not valid
  160. *
  161. * @return boolean success
  162. */
  163. function validateDb()
  164. {
  165. $fail = false;
  166. if (empty($this->host)) {
  167. $this->updateStatus("No hostname specified.", true);
  168. $fail = true;
  169. }
  170. if (empty($this->database)) {
  171. $this->updateStatus("No database specified.", true);
  172. $fail = true;
  173. }
  174. if (empty($this->username)) {
  175. $this->updateStatus("No username specified.", true);
  176. $fail = true;
  177. }
  178. if (empty($this->sitename)) {
  179. $this->updateStatus("No sitename specified.", true);
  180. $fail = true;
  181. }
  182. return !$fail;
  183. }
  184. /**
  185. * Basic validation on the administrator user paramters
  186. * Side effects: error output if not valid
  187. *
  188. * @return boolean success
  189. */
  190. function validateAdmin()
  191. {
  192. $fail = false;
  193. if (empty($this->adminNick)) {
  194. $this->updateStatus("No initial user nickname specified.", true);
  195. $fail = true;
  196. }
  197. if ($this->adminNick && !preg_match('/^[0-9a-z]{1,64}$/', $this->adminNick)) {
  198. $this->updateStatus('The user nickname "' . htmlspecialchars($this->adminNick) .
  199. '" is invalid; should be plain letters and numbers no longer than 64 characters.', true);
  200. $fail = true;
  201. }
  202. // @fixme hardcoded list; should use Nickname::isValid()
  203. // if/when it's safe to have loaded the infrastructure here
  204. $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');
  205. if (in_array($this->adminNick, $blacklist)) {
  206. $this->updateStatus('The user nickname "' . htmlspecialchars($this->adminNick) .
  207. '" is reserved.', true);
  208. $fail = true;
  209. }
  210. if (empty($this->adminPass)) {
  211. $this->updateStatus("No initial user password specified.", true);
  212. $fail = true;
  213. }
  214. return !$fail;
  215. }
  216. /**
  217. * Make sure a site profile was selected
  218. *
  219. * @return type boolean success
  220. */
  221. function validateSiteProfile()
  222. {
  223. if (empty($this->siteProfile)) {
  224. $this->updateStatus("No site profile selected.", true);
  225. return false;
  226. }
  227. return true;
  228. }
  229. /**
  230. * Set up the database with the appropriate function for the selected type...
  231. * Saves database info into $this->db.
  232. *
  233. * @fixme escape things in the connection string in case we have a funny pass etc
  234. * @return mixed array of database connection params on success, false on failure
  235. */
  236. function setupDatabase()
  237. {
  238. if ($this->db) {
  239. throw new Exception("Bad order of operations: DB already set up.");
  240. }
  241. $this->updateStatus("Starting installation...");
  242. if (empty($this->password)) {
  243. $auth = '';
  244. } else {
  245. $auth = ":$this->password";
  246. }
  247. $scheme = self::$dbModules[$this->dbtype]['scheme'];
  248. $dsn = "{$scheme}://{$this->username}{$auth}@{$this->host}/{$this->database}";
  249. $this->updateStatus("Checking database...");
  250. $conn = $this->connectDatabase($dsn);
  251. // ensure database encoding is UTF8
  252. if ($this->dbtype == 'mysql') {
  253. // @fixme utf8m4 support for mysql 5.5?
  254. // Force the comms charset to utf8 for sanity
  255. // This doesn't currently work. :P
  256. //$conn->executes('set names utf8');
  257. } else if ($this->dbtype == 'pgsql') {
  258. $record = $conn->getRow('SHOW server_encoding');
  259. if ($record->server_encoding != 'UTF8') {
  260. $this->updateStatus("GNU social requires UTF8 character encoding. Your database is ". htmlentities($record->server_encoding));
  261. return false;
  262. }
  263. }
  264. if (!$conn instanceof DB_common) {
  265. // Is not the right instance
  266. throw new Exception('Cannot connect to database: ' . $conn->getMessage());
  267. }
  268. $res = $this->updateStatus("Creating database tables...");
  269. if (!$this->createCoreTables($conn)) {
  270. $this->updateStatus("Error creating tables.", true);
  271. return false;
  272. }
  273. foreach (array('sms_carrier' => 'SMS carrier',
  274. 'notice_source' => 'notice source',
  275. 'foreign_services' => 'foreign service')
  276. as $scr => $name) {
  277. $this->updateStatus(sprintf("Adding %s data to database...", $name));
  278. $res = $this->runDbScript($scr.'.sql', $conn);
  279. if ($res === false) {
  280. $this->updateStatus(sprintf("Can't run %s script.", $name), true);
  281. return false;
  282. }
  283. }
  284. $db = array('type' => $this->dbtype, 'database' => $dsn);
  285. return $db;
  286. }
  287. /**
  288. * Open a connection to the database.
  289. *
  290. * @param <type> $dsn
  291. * @return <type>
  292. */
  293. function connectDatabase($dsn)
  294. {
  295. global $_DB;
  296. return $_DB->connect($dsn);
  297. }
  298. /**
  299. * Create core tables on the given database connection.
  300. *
  301. * @param DB_common $conn
  302. */
  303. function createCoreTables(DB_common $conn)
  304. {
  305. $schema = Schema::get($conn);
  306. $tableDefs = $this->getCoreSchema();
  307. foreach ($tableDefs as $name => $def) {
  308. if (defined('DEBUG_INSTALLER')) {
  309. echo " $name ";
  310. }
  311. $schema->ensureTable($name, $def);
  312. }
  313. return true;
  314. }
  315. /**
  316. * Fetch the core table schema definitions.
  317. *
  318. * @return array of table names => table def arrays
  319. */
  320. function getCoreSchema()
  321. {
  322. $schema = array();
  323. include INSTALLDIR . '/db/core.php';
  324. return $schema;
  325. }
  326. /**
  327. * Return a parseable PHP literal for the given value.
  328. * This will include quotes for strings, etc.
  329. *
  330. * @param mixed $val
  331. * @return string
  332. */
  333. function phpVal($val)
  334. {
  335. return var_export($val, true);
  336. }
  337. /**
  338. * Return an array of parseable PHP literal for the given values.
  339. * These will include quotes for strings, etc.
  340. *
  341. * @param mixed $val
  342. * @return array
  343. */
  344. function phpVals($map)
  345. {
  346. return array_map(array($this, 'phpVal'), $map);
  347. }
  348. /**
  349. * Write a stock configuration file.
  350. *
  351. * @return boolean success
  352. *
  353. * @fixme escape variables in output in case we have funny chars, apostrophes etc
  354. */
  355. function writeConf()
  356. {
  357. $vals = $this->phpVals(array(
  358. 'sitename' => $this->sitename,
  359. 'server' => $this->server,
  360. 'path' => $this->path,
  361. 'ssl' => in_array($this->ssl, array('never', 'sometimes', 'always'))
  362. ? $this->ssl
  363. : 'never',
  364. 'db_database' => $this->db['database'],
  365. 'db_type' => $this->db['type']
  366. ));
  367. // assemble configuration file in a string
  368. $cfg = "<?php\n".
  369. "if (!defined('GNUSOCIAL')) { exit(1); }\n\n".
  370. // site name
  371. "\$config['site']['name'] = {$vals['sitename']};\n\n".
  372. // site location
  373. "\$config['site']['server'] = {$vals['server']};\n".
  374. "\$config['site']['path'] = {$vals['path']}; \n\n".
  375. "\$config['site']['ssl'] = {$vals['ssl']}; \n\n".
  376. // checks if fancy URLs are enabled
  377. ($this->fancy ? "\$config['site']['fancy'] = true;\n\n":'').
  378. // database
  379. "\$config['db']['database'] = {$vals['db_database']};\n\n".
  380. ($this->db['type'] == 'pgsql' ? "\$config['db']['quote_identifiers'] = true;\n\n":'').
  381. "\$config['db']['type'] = {$vals['db_type']};\n\n";
  382. // Normalize line endings for Windows servers
  383. $cfg = str_replace("\n", PHP_EOL, $cfg);
  384. // write configuration file out to install directory
  385. $res = file_put_contents(INSTALLDIR.'/config.php', $cfg);
  386. return $res;
  387. }
  388. /**
  389. * Write the site profile. We do this after creating the initial user
  390. * in case the site profile is set to single user. This gets around the
  391. * 'chicken-and-egg' problem of the system requiring a valid user for
  392. * single user mode, before the intial user is actually created. Yeah,
  393. * we should probably do this in smarter way.
  394. *
  395. * @return int res number of bytes written
  396. */
  397. function writeSiteProfile()
  398. {
  399. $vals = $this->phpVals(array(
  400. 'site_profile' => $this->siteProfile,
  401. 'nickname' => $this->adminNick
  402. ));
  403. $cfg =
  404. // site profile
  405. "\$config['site']['profile'] = {$vals['site_profile']};\n";
  406. if ($this->siteProfile == "singleuser") {
  407. $cfg .= "\$config['singleuser']['nickname'] = {$vals['nickname']};\n\n";
  408. } else {
  409. $cfg .= "\n";
  410. }
  411. // Normalize line endings for Windows servers
  412. $cfg = str_replace("\n", PHP_EOL, $cfg);
  413. // write configuration file out to install directory
  414. $res = file_put_contents(INSTALLDIR.'/config.php', $cfg, FILE_APPEND);
  415. return $res;
  416. }
  417. /**
  418. * Install schema into the database
  419. *
  420. * @param string $filename location of database schema file
  421. * @param DB_common $conn connection to database
  422. *
  423. * @return boolean - indicating success or failure
  424. */
  425. function runDbScript($filename, DB_common $conn)
  426. {
  427. $sql = trim(file_get_contents(INSTALLDIR . '/db/' . $filename));
  428. $stmts = explode(';', $sql);
  429. foreach ($stmts as $stmt) {
  430. $stmt = trim($stmt);
  431. if (!mb_strlen($stmt)) {
  432. continue;
  433. }
  434. try {
  435. $res = $conn->simpleQuery($stmt);
  436. } catch (Exception $e) {
  437. $error = $e->getMessage();
  438. $this->updateStatus("ERROR ($error) for SQL '$stmt'");
  439. return false;
  440. }
  441. }
  442. return true;
  443. }
  444. /**
  445. * Create the initial admin user account.
  446. * Side effect: may load portions of GNU social framework.
  447. * Side effect: outputs program info
  448. */
  449. function registerInitialUser()
  450. {
  451. require_once INSTALLDIR . '/lib/common.php';
  452. $data = array('nickname' => $this->adminNick,
  453. 'password' => $this->adminPass,
  454. 'fullname' => $this->adminNick);
  455. if ($this->adminEmail) {
  456. $data['email'] = $this->adminEmail;
  457. }
  458. $user = User::register($data);
  459. if (empty($user)) {
  460. return false;
  461. }
  462. // give initial user carte blanche
  463. $user->grantRole('owner');
  464. $user->grantRole('moderator');
  465. $user->grantRole('administrator');
  466. return true;
  467. }
  468. /**
  469. * The beef of the installer!
  470. * Create database, config file, and admin user.
  471. *
  472. * Prerequisites: validation of input data.
  473. *
  474. * @return boolean success
  475. */
  476. function doInstall()
  477. {
  478. global $config;
  479. $this->updateStatus("Initializing...");
  480. ini_set('display_errors', 1);
  481. error_reporting(E_ALL & ~E_STRICT & ~E_NOTICE);
  482. if (!defined('GNUSOCIAL')) {
  483. define('GNUSOCIAL', true);
  484. }
  485. if (!defined('STATUSNET')) {
  486. define('STATUSNET', true);
  487. }
  488. require_once INSTALLDIR . '/lib/framework.php';
  489. StatusNet::initDefaults($this->server, $this->path);
  490. if ($this->siteProfile == "singleuser") {
  491. // Until we use ['site']['profile']==='singleuser' everywhere
  492. $config['singleuser']['enabled'] = true;
  493. }
  494. try {
  495. $this->db = $this->setupDatabase();
  496. if (!$this->db) {
  497. // database connection failed, do not move on to create config file.
  498. return false;
  499. }
  500. } catch (Exception $e) {
  501. // Lower-level DB error!
  502. $this->updateStatus("Database error: " . $e->getMessage(), true);
  503. return false;
  504. }
  505. // Make sure we can write to the file twice
  506. $oldUmask = umask(000);
  507. if (!$this->skipConfig) {
  508. $this->updateStatus("Writing config file...");
  509. $res = $this->writeConf();
  510. if (!$res) {
  511. $this->updateStatus("Can't write config file.", true);
  512. return false;
  513. }
  514. }
  515. if (!empty($this->adminNick)) {
  516. // Okay, cross fingers and try to register an initial user
  517. if ($this->registerInitialUser()) {
  518. $this->updateStatus(
  519. "An initial user with the administrator role has been created."
  520. );
  521. } else {
  522. $this->updateStatus(
  523. "Could not create initial user account.",
  524. true
  525. );
  526. return false;
  527. }
  528. }
  529. if (!$this->skipConfig) {
  530. $this->updateStatus("Setting site profile...");
  531. $res = $this->writeSiteProfile();
  532. if (!$res) {
  533. $this->updateStatus("Can't write to config file.", true);
  534. return false;
  535. }
  536. }
  537. // Restore original umask
  538. umask($oldUmask);
  539. // Set permissions back to something decent
  540. chmod(INSTALLDIR.'/config.php', 0644);
  541. $scheme = $this->ssl === 'always' ? 'https' : 'http';
  542. $link = "{$scheme}://{$this->server}/{$this->path}";
  543. $this->updateStatus("GNU social has been installed at $link");
  544. $this->updateStatus(
  545. '<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 mailing list and <a href="http://gnu.io/resources/">good documentation</a>.'
  546. );
  547. return true;
  548. }
  549. /**
  550. * Output a pre-install-time warning message
  551. * @param string $message HTML ok, but should be plaintext-able
  552. * @param string $submessage HTML ok, but should be plaintext-able
  553. */
  554. abstract function warning($message, $submessage='');
  555. /**
  556. * Output an install-time progress message
  557. * @param string $message HTML ok, but should be plaintext-able
  558. * @param boolean $error true if this should be marked as an error condition
  559. */
  560. abstract function updateStatus($status, $error=false);
  561. }