4 * StatusNet - the distributed open-source microblogging tool
5 * Copyright (C) 2009-2010, StatusNet, Inc.
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU Affero General Public License as published by
9 * the Free Software Foundation, either version 3 of the License, or
10 * (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU Affero General Public License for more details.
17 * You should have received a copy of the GNU Affero General Public License
18 * along with this program. If not, see <http://www.gnu.org/licenses/>.
20 * @category Installation
21 * @package Installation
23 * @author Adrian Lang <mail@adrianlang.de>
24 * @author Brenda Wallace <shiny@cpan.org>
25 * @author Brett Taylor <brett@webfroot.co.nz>
26 * @author Brion Vibber <brion@pobox.com>
27 * @author CiaranG <ciaran@ciarang.com>
28 * @author Craig Andrews <candrews@integralblue.com>
29 * @author Eric Helgeson <helfire@Erics-MBP.local>
30 * @author Evan Prodromou <evan@status.net>
31 * @author Mikael Nordfeldth <mmn@hethane.se>
32 * @author Robin Millette <millette@controlyourself.ca>
33 * @author Sarven Capadisli <csarven@status.net>
34 * @author Tom Adams <tom@holizz.com>
35 * @author Zach Copley <zach@status.net>
36 * @copyright 2009-2010 StatusNet, Inc http://status.net
37 * @copyright 2009-2014 Free Software Foundation, Inc http://www.fsf.org
38 * @license GNU Affero General Public License http://www.gnu.org/licenses/
40 * @link http://status.net
43 abstract class Installer
46 public $sitename, $server, $path, $fancy, $siteProfile, $ssl;
48 public $host, $database, $dbtype, $username, $password, $db;
49 /** Administrator info */
50 public $adminNick, $adminPass, $adminEmail;
51 /** Should we skip writing the configuration file? */
52 public $skipConfig = false;
54 public static $dbModules = array(
56 'name' => 'MariaDB (or MySQL 5.5+)',
57 'check_module' => 'mysqli',
58 'scheme' => 'mysqli', // DSN prefix for PEAR::DB
61 'name' => 'PostgreSQL',
62 'check_module' => 'pgsql',
63 'scheme' => 'pgsql', // DSN prefix for PEAR::DB
68 * Attempt to include a PHP file and report if it worked, while
69 * suppressing the annoying warning messages on failure.
71 private function haveIncludeFile($filename) {
72 $old = error_reporting(error_reporting() & ~E_WARNING);
73 $ok = include_once($filename);
74 error_reporting($old);
79 * Check if all is ready for installation
83 function checkPrereqs()
87 $config = INSTALLDIR.'/config.php';
88 if (file_exists($config)) {
89 if (!is_writable($config) || filesize($config) > 0) {
90 if (filesize($config) == 0) {
91 $this->warning('Config file "config.php" already exists and is empty, but is not writable.');
93 $this->warning('Config file "config.php" already exists.');
99 if (version_compare(PHP_VERSION, '5.3.2', '<')) {
100 $this->warning('Require PHP version 5.3.2 or greater.');
104 $reqs = array('gd', 'curl', 'intl', 'json',
105 'xmlwriter', 'mbstring', 'xml', 'dom', 'simplexml');
107 foreach ($reqs as $req) {
108 if (!$this->checkExtension($req)) {
109 $this->warning(sprintf('Cannot load required extension: <code>%s</code>', $req));
114 // Make sure we have at least one database module available
115 $missingExtensions = array();
116 foreach (self::$dbModules as $type => $info) {
117 if (!$this->checkExtension($info['check_module'])) {
118 $missingExtensions[] = $info['check_module'];
122 if (count($missingExtensions) == count(self::$dbModules)) {
123 $req = implode(', ', $missingExtensions);
124 $this->warning(sprintf('Cannot find a database extension. You need at least one of %s.', $req));
128 // @fixme this check seems to be insufficient with Windows ACLs
129 if (!is_writable(INSTALLDIR)) {
130 $this->warning(sprintf('Cannot write config file to: <code>%s</code></p>', INSTALLDIR),
131 sprintf('On your server, try this command: <code>chmod a+w %s</code>', INSTALLDIR));
135 // Check the subdirs used for file uploads
136 $fileSubdirs = array('avatar', 'background', 'file');
137 foreach ($fileSubdirs as $fileSubdir) {
138 $fileFullPath = INSTALLDIR."/$fileSubdir/";
139 if (!is_writable($fileFullPath)) {
140 $this->warning(sprintf('Cannot write to %s directory: <code>%s</code>', $fileSubdir, $fileFullPath),
141 sprintf('On your server, try this command: <code>chmod a+w %s</code>', $fileFullPath));
150 * Checks if a php extension is both installed and loaded
152 * @param string $name of extension to check
154 * @return boolean whether extension is installed and loaded
156 function checkExtension($name)
158 if (extension_loaded($name)) {
160 } elseif (function_exists('dl') && ini_get('enable_dl') && !ini_get('safe_mode')) {
161 // dl will throw a fatal error if it's disabled or we're in safe mode.
162 // More fun, it may not even exist under some SAPIs in 5.3.0 or later...
163 $soname = $name . '.' . PHP_SHLIB_SUFFIX;
164 if (PHP_SHLIB_SUFFIX == 'dll') {
165 $soname = "php_" . $soname;
174 * Basic validation on the database paramters
175 * Side effects: error output if not valid
177 * @return boolean success
179 function validateDb()
183 if (empty($this->host)) {
184 $this->updateStatus("No hostname specified.", true);
188 if (empty($this->database)) {
189 $this->updateStatus("No database specified.", true);
193 if (empty($this->username)) {
194 $this->updateStatus("No username specified.", true);
198 if (empty($this->sitename)) {
199 $this->updateStatus("No sitename specified.", true);
207 * Basic validation on the administrator user paramters
208 * Side effects: error output if not valid
210 * @return boolean success
212 function validateAdmin()
216 if (empty($this->adminNick)) {
217 $this->updateStatus("No initial user nickname specified.", true);
220 if ($this->adminNick && !preg_match('/^[0-9a-z]{1,64}$/', $this->adminNick)) {
221 $this->updateStatus('The user nickname "' . htmlspecialchars($this->adminNick) .
222 '" is invalid; should be plain letters and numbers no longer than 64 characters.', true);
225 // @fixme hardcoded list; should use Nickname::isValid()
226 // if/when it's safe to have loaded the infrastructure here
227 $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');
228 if (in_array($this->adminNick, $blacklist)) {
229 $this->updateStatus('The user nickname "' . htmlspecialchars($this->adminNick) .
230 '" is reserved.', true);
234 if (empty($this->adminPass)) {
235 $this->updateStatus("No initial user password specified.", true);
243 * Make sure a site profile was selected
245 * @return type boolean success
247 function validateSiteProfile()
249 if (empty($this->siteProfile)) {
250 $this->updateStatus("No site profile selected.", true);
258 * Set up the database with the appropriate function for the selected type...
259 * Saves database info into $this->db.
261 * @fixme escape things in the connection string in case we have a funny pass etc
262 * @return mixed array of database connection params on success, false on failure
264 function setupDatabase()
267 throw new Exception("Bad order of operations: DB already set up.");
269 $this->updateStatus("Starting installation...");
271 if (empty($this->password)) {
274 $auth = ":$this->password";
276 $scheme = self::$dbModules[$this->dbtype]['scheme'];
277 $dsn = "{$scheme}://{$this->username}{$auth}@{$this->host}/{$this->database}";
279 $this->updateStatus("Checking database...");
280 $conn = $this->connectDatabase($dsn);
282 // ensure database encoding is UTF8
283 if ($this->dbtype == 'mysql') {
284 // @fixme utf8m4 support for mysql 5.5?
285 // Force the comms charset to utf8 for sanity
286 // This doesn't currently work. :P
287 //$conn->executes('set names utf8');
288 } else if ($this->dbtype == 'pgsql') {
289 $record = $conn->getRow('SHOW server_encoding');
290 if ($record->server_encoding != 'UTF8') {
291 $this->updateStatus("GNU social requires UTF8 character encoding. Your database is ". htmlentities($record->server_encoding));
296 if (!$conn instanceof DB_common) {
297 // Is not the right instance
298 throw new Exception('Cannot connect to database: ' . $conn->getMessage());
301 $res = $this->updateStatus("Creating database tables...");
302 if (!$this->createCoreTables($conn)) {
303 $this->updateStatus("Error creating tables.", true);
307 foreach (array('sms_carrier' => 'SMS carrier',
308 'notice_source' => 'notice source',
309 'foreign_services' => 'foreign service')
311 $this->updateStatus(sprintf("Adding %s data to database...", $name));
312 $res = $this->runDbScript($scr.'.sql', $conn);
313 if ($res === false) {
314 $this->updateStatus(sprintf("Can't run %s script.", $name), true);
319 $db = array('type' => $this->dbtype, 'database' => $dsn);
324 * Open a connection to the database.
329 function connectDatabase($dsn)
332 return $_DB->connect($dsn);
336 * Create core tables on the given database connection.
338 * @param DB_common $conn
340 function createCoreTables(DB_common $conn)
342 $schema = Schema::get($conn);
343 $tableDefs = $this->getCoreSchema();
344 foreach ($tableDefs as $name => $def) {
345 if (defined('DEBUG_INSTALLER')) {
348 $schema->ensureTable($name, $def);
354 * Fetch the core table schema definitions.
356 * @return array of table names => table def arrays
358 function getCoreSchema()
361 include INSTALLDIR . '/db/core.php';
366 * Return a parseable PHP literal for the given value.
367 * This will include quotes for strings, etc.
372 function phpVal($val)
374 return var_export($val, true);
378 * Return an array of parseable PHP literal for the given values.
379 * These will include quotes for strings, etc.
384 function phpVals($map)
386 return array_map(array($this, 'phpVal'), $map);
390 * Write a stock configuration file.
392 * @return boolean success
394 * @fixme escape variables in output in case we have funny chars, apostrophes etc
398 $vals = $this->phpVals(array(
399 'sitename' => $this->sitename,
400 'server' => $this->server,
401 'path' => $this->path,
402 'ssl' => in_array($this->ssl, array('never', 'sometimes', 'always'))
405 'db_database' => $this->db['database'],
406 'db_type' => $this->db['type']
409 // assemble configuration file in a string
411 "if (!defined('GNUSOCIAL')) { exit(1); }\n\n".
414 "\$config['site']['name'] = {$vals['sitename']};\n\n".
417 "\$config['site']['server'] = {$vals['server']};\n".
418 "\$config['site']['path'] = {$vals['path']}; \n\n".
419 "\$config['site']['ssl'] = {$vals['ssl']}; \n\n".
421 // checks if fancy URLs are enabled
422 ($this->fancy ? "\$config['site']['fancy'] = true;\n\n":'').
425 "\$config['db']['database'] = {$vals['db_database']};\n\n".
426 ($this->db['type'] == 'pgsql' ? "\$config['db']['quote_identifiers'] = true;\n\n":'').
427 "\$config['db']['type'] = {$vals['db_type']};\n\n".
429 "// Uncomment below for better performance. Just remember you must run\n".
430 "// php scripts/checkschema.php whenever your enabled plugins change!\n".
431 "//\$config['db']['schemacheck'] = 'script';\n\n";
433 // Normalize line endings for Windows servers
434 $cfg = str_replace("\n", PHP_EOL, $cfg);
436 // write configuration file out to install directory
437 $res = file_put_contents(INSTALLDIR.'/config.php', $cfg);
443 * Write the site profile. We do this after creating the initial user
444 * in case the site profile is set to single user. This gets around the
445 * 'chicken-and-egg' problem of the system requiring a valid user for
446 * single user mode, before the intial user is actually created. Yeah,
447 * we should probably do this in smarter way.
449 * @return int res number of bytes written
451 function writeSiteProfile()
453 $vals = $this->phpVals(array(
454 'site_profile' => $this->siteProfile,
455 'nickname' => $this->adminNick
460 "\$config['site']['profile'] = {$vals['site_profile']};\n";
462 if ($this->siteProfile == "singleuser") {
463 $cfg .= "\$config['singleuser']['nickname'] = {$vals['nickname']};\n\n";
468 // Normalize line endings for Windows servers
469 $cfg = str_replace("\n", PHP_EOL, $cfg);
471 // write configuration file out to install directory
472 $res = file_put_contents(INSTALLDIR.'/config.php', $cfg, FILE_APPEND);
478 * Install schema into the database
480 * @param string $filename location of database schema file
481 * @param DB_common $conn connection to database
483 * @return boolean - indicating success or failure
485 function runDbScript($filename, DB_common $conn)
487 $sql = trim(file_get_contents(INSTALLDIR . '/db/' . $filename));
488 $stmts = explode(';', $sql);
489 foreach ($stmts as $stmt) {
491 if (!mb_strlen($stmt)) {
495 $res = $conn->simpleQuery($stmt);
496 } catch (Exception $e) {
497 $error = $e->getMessage();
498 $this->updateStatus("ERROR ($error) for SQL '$stmt'");
506 * Create the initial admin user account.
507 * Side effect: may load portions of GNU social framework.
508 * Side effect: outputs program info
510 function registerInitialUser()
512 require_once INSTALLDIR . '/lib/common.php';
514 $data = array('nickname' => $this->adminNick,
515 'password' => $this->adminPass,
516 'fullname' => $this->adminNick);
517 if ($this->adminEmail) {
518 $data['email'] = $this->adminEmail;
521 $user = User::register($data);
522 } catch (Exception $e) {
526 // give initial user carte blanche
528 $user->grantRole('owner');
529 $user->grantRole('moderator');
530 $user->grantRole('administrator');
536 * The beef of the installer!
537 * Create database, config file, and admin user.
539 * Prerequisites: validation of input data.
541 * @return boolean success
547 $this->updateStatus("Initializing...");
548 ini_set('display_errors', 1);
549 error_reporting(E_ALL & ~E_STRICT & ~E_NOTICE);
550 if (!defined('GNUSOCIAL')) {
551 define('GNUSOCIAL', true);
553 if (!defined('STATUSNET')) {
554 define('STATUSNET', true);
557 require_once INSTALLDIR . '/lib/framework.php';
558 GNUsocial::initDefaults($this->server, $this->path);
560 if ($this->siteProfile == "singleuser") {
561 // Until we use ['site']['profile']==='singleuser' everywhere
562 $config['singleuser']['enabled'] = true;
566 $this->db = $this->setupDatabase();
568 // database connection failed, do not move on to create config file.
571 } catch (Exception $e) {
572 // Lower-level DB error!
573 $this->updateStatus("Database error: " . $e->getMessage(), true);
577 // Make sure we can write to the file twice
578 $oldUmask = umask(000);
580 if (!$this->skipConfig) {
581 $this->updateStatus("Writing config file...");
582 $res = $this->writeConf();
585 $this->updateStatus("Can't write config file.", true);
590 if (!empty($this->adminNick)) {
591 // Okay, cross fingers and try to register an initial user
592 if ($this->registerInitialUser()) {
594 "An initial user with the administrator role has been created."
598 "Could not create initial user account.",
605 if (!$this->skipConfig) {
606 $this->updateStatus("Setting site profile...");
607 $res = $this->writeSiteProfile();
610 $this->updateStatus("Can't write to config file.", true);
615 // Restore original umask
617 // Set permissions back to something decent
618 chmod(INSTALLDIR.'/config.php', 0644);
620 $scheme = $this->ssl === 'always' ? 'https' : 'http';
621 $link = "{$scheme}://{$this->server}/{$this->path}";
623 $this->updateStatus("GNU social has been installed at $link");
625 '<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>.'
632 * Output a pre-install-time warning message
633 * @param string $message HTML ok, but should be plaintext-able
634 * @param string $submessage HTML ok, but should be plaintext-able
636 abstract function warning($message, $submessage='');
639 * Output an install-time progress message
640 * @param string $message HTML ok, but should be plaintext-able
641 * @param boolean $error true if this should be marked as an error condition
643 abstract function updateStatus($status, $error=false);