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 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, $adminUpdates;
51 /** Should we skip writing the configuration file? */
52 public $skipConfig = false;
54 public static $dbModules = array(
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.2.3', '<')) {
100 $this->warning('Require PHP version 5.2.3 or greater.');
104 // Look for known library bugs
105 $str = "abcdefghijklmnopqrstuvwxyz";
106 $replaced = preg_replace('/[\p{Cc}\p{Cs}]/u', '*', $str);
107 if ($str != $replaced) {
108 $this->warning('PHP is linked to a version of the PCRE library ' .
109 'that does not support Unicode properties. ' .
110 'If you are running Red Hat Enterprise Linux / ' .
111 'CentOS 5.4 or earlier, see <a href="' .
112 'http://status.net/wiki/Red_Hat_Enterprise_Linux#PCRE_library' .
113 '">our documentation page</a> on fixing this.');
117 $reqs = array('gd', 'curl',
118 'xmlwriter', 'mbstring', 'xml', 'dom', 'simplexml');
120 foreach ($reqs as $req) {
121 if (!$this->checkExtension($req)) {
122 $this->warning(sprintf('Cannot load required extension: <code>%s</code>', $req));
127 // Make sure we have at least one database module available
128 $missingExtensions = array();
129 foreach (self::$dbModules as $type => $info) {
130 if (!$this->checkExtension($info['check_module'])) {
131 $missingExtensions[] = $info['check_module'];
135 if (count($missingExtensions) == count(self::$dbModules)) {
136 $req = implode(', ', $missingExtensions);
137 $this->warning(sprintf('Cannot find a database extension. You need at least one of %s.', $req));
141 // @fixme this check seems to be insufficient with Windows ACLs
142 if (!is_writable(INSTALLDIR)) {
143 $this->warning(sprintf('Cannot write config file to: <code>%s</code></p>', INSTALLDIR),
144 sprintf('On your server, try this command: <code>chmod a+w %s</code>', INSTALLDIR));
148 // Check the subdirs used for file uploads
149 $fileSubdirs = array('avatar', 'background', 'file');
150 foreach ($fileSubdirs as $fileSubdir) {
151 $fileFullPath = INSTALLDIR."/$fileSubdir/";
152 if (!is_writable($fileFullPath)) {
153 $this->warning(sprintf('Cannot write to %s directory: <code>%s</code>', $fileSubdir, $fileFullPath),
154 sprintf('On your server, try this command: <code>chmod a+w %s</code>', $fileFullPath));
163 * Checks if a php extension is both installed and loaded
165 * @param string $name of extension to check
167 * @return boolean whether extension is installed and loaded
169 function checkExtension($name)
171 if (extension_loaded($name)) {
173 } elseif (function_exists('dl') && ini_get('enable_dl') && !ini_get('safe_mode')) {
174 // dl will throw a fatal error if it's disabled or we're in safe mode.
175 // More fun, it may not even exist under some SAPIs in 5.3.0 or later...
176 $soname = $name . '.' . PHP_SHLIB_SUFFIX;
177 if (PHP_SHLIB_SUFFIX == 'dll') {
178 $soname = "php_" . $soname;
187 * Basic validation on the database paramters
188 * Side effects: error output if not valid
190 * @return boolean success
192 function validateDb()
196 if (empty($this->host)) {
197 $this->updateStatus("No hostname specified.", true);
201 if (empty($this->database)) {
202 $this->updateStatus("No database specified.", true);
206 if (empty($this->username)) {
207 $this->updateStatus("No username specified.", true);
211 if (empty($this->sitename)) {
212 $this->updateStatus("No sitename specified.", true);
220 * Basic validation on the administrator user paramters
221 * Side effects: error output if not valid
223 * @return boolean success
225 function validateAdmin()
229 if (empty($this->adminNick)) {
230 $this->updateStatus("No initial StatusNet user nickname specified.", true);
233 if ($this->adminNick && !preg_match('/^[0-9a-z]{1,64}$/', $this->adminNick)) {
234 $this->updateStatus('The user nickname "' . htmlspecialchars($this->adminNick) .
235 '" is invalid; should be plain letters and numbers no longer than 64 characters.', true);
238 // @fixme hardcoded list; should use Nickname::isValid()
239 // if/when it's safe to have loaded the infrastructure here
240 $blacklist = array('main', 'panel', 'twitter', 'settings', 'rsd.xml', 'favorited', 'featured', 'favoritedrss', 'featuredrss', 'rss', 'getfile', 'api', 'groups', 'group', 'peopletag', 'tag', 'user', 'message', 'conversation', 'bookmarklet', 'notice', 'attachment', 'search', 'index.php', 'doc', 'opensearch', 'robots.txt', 'xd_receiver.html', 'facebook');
241 if (in_array($this->adminNick, $blacklist)) {
242 $this->updateStatus('The user nickname "' . htmlspecialchars($this->adminNick) .
243 '" is reserved.', true);
247 if (empty($this->adminPass)) {
248 $this->updateStatus("No initial StatusNet user password specified.", true);
256 * Make sure a site profile was selected
258 * @return type boolean success
260 function validateSiteProfile()
262 if (empty($this->siteProfile)) {
263 $this->updateStatus("No site profile selected.", true);
271 * Set up the database with the appropriate function for the selected type...
272 * Saves database info into $this->db.
274 * @fixme escape things in the connection string in case we have a funny pass etc
275 * @return mixed array of database connection params on success, false on failure
277 function setupDatabase()
280 throw new Exception("Bad order of operations: DB already set up.");
282 $this->updateStatus("Starting installation...");
284 if (empty($this->password)) {
287 $auth = ":$this->password";
289 $scheme = self::$dbModules[$this->dbtype]['scheme'];
290 $dsn = "{$scheme}://{$this->username}{$auth}@{$this->host}/{$this->database}";
292 $this->updateStatus("Checking database...");
293 $conn = $this->connectDatabase($dsn);
295 // ensure database encoding is UTF8
296 if ($this->dbtype == 'mysql') {
297 // @fixme utf8m4 support for mysql 5.5?
298 // Force the comms charset to utf8 for sanity
299 // This doesn't currently work. :P
300 //$conn->executes('set names utf8');
301 } else if ($this->dbtype == 'pgsql') {
302 $record = $conn->getRow('SHOW server_encoding');
303 if ($record->server_encoding != 'UTF8') {
304 $this->updateStatus("StatusNet requires UTF8 character encoding. Your database is ". htmlentities($record->server_encoding));
309 $res = $this->updateStatus("Creating database tables...");
310 if (!$this->createCoreTables($conn)) {
311 $this->updateStatus("Error creating tables.", true);
315 foreach (array('sms_carrier' => 'SMS carrier',
316 'notice_source' => 'notice source',
317 'foreign_services' => 'foreign service')
319 $this->updateStatus(sprintf("Adding %s data to database...", $name));
320 $res = $this->runDbScript($scr.'.sql', $conn);
321 if ($res === false) {
322 $this->updateStatus(sprintf("Can't run %s script.", $name), true);
327 $db = array('type' => $this->dbtype, 'database' => $dsn);
332 * Open a connection to the database.
337 function connectDatabase($dsn)
340 return $_DB->connect($dsn);
344 * Create core tables on the given database connection.
346 * @param DB_common $conn
348 function createCoreTables(DB_common $conn)
350 $schema = Schema::get($conn);
351 $tableDefs = $this->getCoreSchema();
352 foreach ($tableDefs as $name => $def) {
353 if (defined('DEBUG_INSTALLER')) {
356 $schema->ensureTable($name, $def);
362 * Fetch the core table schema definitions.
364 * @return array of table names => table def arrays
366 function getCoreSchema()
369 include INSTALLDIR . '/db/core.php';
374 * Return a parseable PHP literal for the given value.
375 * This will include quotes for strings, etc.
380 function phpVal($val)
382 return var_export($val, true);
386 * Return an array of parseable PHP literal for the given values.
387 * These will include quotes for strings, etc.
392 function phpVals($map)
394 return array_map(array($this, 'phpVal'), $map);
398 * Write a stock configuration file.
400 * @return boolean success
402 * @fixme escape variables in output in case we have funny chars, apostrophes etc
406 $vals = $this->phpVals(array(
407 'sitename' => $this->sitename,
408 'server' => $this->server,
409 'path' => $this->path,
410 'ssl' => in_array($this->ssl, array('never', 'sometimes', 'always'))
413 'db_database' => $this->db['database'],
414 'db_type' => $this->db['type']
417 // assemble configuration file in a string
419 "if (!defined('GNUSOCIAL')) { exit(1); }\n\n".
422 "\$config['site']['name'] = {$vals['sitename']};\n\n".
425 "\$config['site']['server'] = {$vals['server']};\n".
426 "\$config['site']['path'] = {$vals['path']}; \n\n".
427 "\$config['site']['ssl'] = {$vals['ssl']}; \n\n".
429 // checks if fancy URLs are enabled
430 ($this->fancy ? "\$config['site']['fancy'] = true;\n\n":'').
433 "\$config['db']['database'] = {$vals['db_database']};\n\n".
434 ($this->db['type'] == 'pgsql' ? "\$config['db']['quote_identifiers'] = true;\n\n":'').
435 "\$config['db']['type'] = {$vals['db_type']};\n\n";
437 // Normalize line endings for Windows servers
438 $cfg = str_replace("\n", PHP_EOL, $cfg);
440 // write configuration file out to install directory
441 $res = file_put_contents(INSTALLDIR.'/config.php', $cfg);
447 * Write the site profile. We do this after creating the initial user
448 * in case the site profile is set to single user. This gets around the
449 * 'chicken-and-egg' problem of the system requiring a valid user for
450 * single user mode, before the intial user is actually created. Yeah,
451 * we should probably do this in smarter way.
453 * @return int res number of bytes written
455 function writeSiteProfile()
457 $vals = $this->phpVals(array(
458 'site_profile' => $this->siteProfile,
459 'nickname' => $this->adminNick
464 "\$config['site']['profile'] = {$vals['site_profile']};\n";
466 if ($this->siteProfile == "singleuser") {
467 $cfg .= "\$config['singleuser']['nickname'] = {$vals['nickname']};\n\n";
472 // Normalize line endings for Windows servers
473 $cfg = str_replace("\n", PHP_EOL, $cfg);
475 // write configuration file out to install directory
476 $res = file_put_contents(INSTALLDIR.'/config.php', $cfg, FILE_APPEND);
482 * Install schema into the database
484 * @param string $filename location of database schema file
485 * @param DB_common $conn connection to database
487 * @return boolean - indicating success or failure
489 function runDbScript($filename, DB_common $conn)
491 $sql = trim(file_get_contents(INSTALLDIR . '/db/' . $filename));
492 $stmts = explode(';', $sql);
493 foreach ($stmts as $stmt) {
495 if (!mb_strlen($stmt)) {
499 $res = $conn->simpleQuery($stmt);
500 } catch (Exception $e) {
501 $error = $e->getMessage();
502 $this->updateStatus("ERROR ($error) for SQL '$stmt'");
510 * Create the initial admin user account.
511 * Side effect: may load portions of StatusNet framework.
512 * Side effect: outputs program info
514 function registerInitialUser()
516 require_once INSTALLDIR . '/lib/common.php';
518 $data = array('nickname' => $this->adminNick,
519 'password' => $this->adminPass,
520 'fullname' => $this->adminNick);
521 if ($this->adminEmail) {
522 $data['email'] = $this->adminEmail;
524 $user = User::register($data);
530 // give initial user carte blanche
532 $user->grantRole('owner');
533 $user->grantRole('moderator');
534 $user->grantRole('administrator');
536 // Attempt to do a remote subscribe to update@status.net
537 // Will fail if instance is on a private network.
539 if ($this->adminUpdates && class_exists('Ostatus_profile')) {
541 $oprofile = Ostatus_profile::ensureProfileURL('http://update.status.net/');
542 Subscription::start($user->getProfile(), $oprofile->localProfile());
543 $this->updateStatus("Set up subscription to <a href='http://update.status.net/'>update@status.net</a>.");
544 } catch (Exception $e) {
545 $this->updateStatus("Could not set up subscription to <a href='http://update.status.net/'>update@status.net</a>.", true);
553 * The beef of the installer!
554 * Create database, config file, and admin user.
556 * Prerequisites: validation of input data.
558 * @return boolean success
564 $this->updateStatus("Initializing...");
565 ini_set('display_errors', 1);
566 error_reporting(E_ALL);
567 if (!defined('GNUSOCIAL')) {
568 define('GNUSOCIAL', true);
570 if (!defined('STATUSNET')) {
571 define('STATUSNET', true);
574 require_once INSTALLDIR . '/lib/framework.php';
575 StatusNet::initDefaults($this->server, $this->path);
577 if ($this->siteProfile == "singleuser") {
578 // Until we use ['site']['profile']==='singleuser' everywhere
579 $config['singleuser']['enabled'] = true;
583 $this->db = $this->setupDatabase();
585 // database connection failed, do not move on to create config file.
588 } catch (Exception $e) {
589 // Lower-level DB error!
590 $this->updateStatus("Database error: " . $e->getMessage(), true);
594 // Make sure we can write to the file twice
595 $oldUmask = umask(000);
597 if (!$this->skipConfig) {
598 $this->updateStatus("Writing config file...");
599 $res = $this->writeConf();
602 $this->updateStatus("Can't write config file.", true);
607 if (!empty($this->adminNick)) {
608 // Okay, cross fingers and try to register an initial user
609 if ($this->registerInitialUser()) {
611 "An initial user with the administrator role has been created."
615 "Could not create initial GNU social user.",
622 if (!$this->skipConfig) {
623 $this->updateStatus("Setting site profile...");
624 $res = $this->writeSiteProfile();
627 $this->updateStatus("Can't write to config file.", true);
632 // Restore original umask
634 // Set permissions back to something decent
635 chmod(INSTALLDIR.'/config.php', 0644);
637 $scheme = $this->ssl === 'always' ? 'https' : 'http';
638 $link = "{$scheme}://{$this->server}/{$this->path}";
640 $this->updateStatus("StatusNet has been installed at $link");
642 "<strong>DONE!</strong> You can visit your <a href='$link'>new StatusNet site</a> (login as '$this->adminNick'). If this is your first StatusNet install, you may want to poke around our <a href='http://status.net/wiki/Getting_started'>Getting Started guide</a>."
649 * Output a pre-install-time warning message
650 * @param string $message HTML ok, but should be plaintext-able
651 * @param string $submessage HTML ok, but should be plaintext-able
653 abstract function warning($message, $submessage='');
656 * Output an install-time progress message
657 * @param string $message HTML ok, but should be plaintext-able
658 * @param boolean $error true if this should be marked as an error condition
660 abstract function updateStatus($status, $error=false);