4 * StatusNet - the distributed open-source microblogging tool
5 * Copyright (C) 2009, 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 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 Free Software Foundation, Inc http://www.fsf.org
36 * @license GNU Affero General Public License http://www.gnu.org/licenses/
38 * @link http://status.net
41 abstract class Installer
44 public $sitename, $server, $path, $fancy;
46 public $host, $dbname, $dbtype, $username, $password, $db;
47 /** Administrator info */
48 public $adminNick, $adminPass, $adminEmail, $adminUpdates;
49 /** Should we skip writing the configuration file? */
50 public $skipConfig = false;
52 public static $dbModules = array(
55 'check_module' => 'mysqli',
56 'scheme' => 'mysqli', // DSN prefix for PEAR::DB
59 'name' => 'PostgreSQL',
60 'check_module' => 'pgsql',
61 'scheme' => 'pgsql', // DSN prefix for PEAR::DB
66 * Attempt to include a PHP file and report if it worked, while
67 * suppressing the annoying warning messages on failure.
69 private function haveIncludeFile($filename) {
70 $old = error_reporting(error_reporting() & ~E_WARNING);
71 $ok = include_once($filename);
72 error_reporting($old);
77 * Check if all is ready for installation
81 function checkPrereqs()
85 $config = INSTALLDIR.'/config.php';
86 if (file_exists($config)) {
87 if (!is_writable($config) || filesize($config) > 0) {
88 if (filesize($config) == 0) {
89 $this->warning('Config file "config.php" already exists and is empty, but is not writable.');
91 $this->warning('Config file "config.php" already exists.');
97 if (version_compare(PHP_VERSION, '5.2.3', '<')) {
98 $this->warning('Require PHP version 5.2.3 or greater.');
102 // Look for known library bugs
103 $str = "abcdefghijklmnopqrstuvwxyz";
104 $replaced = preg_replace('/[\p{Cc}\p{Cs}]/u', '*', $str);
105 if ($str != $replaced) {
106 $this->warning('PHP is linked to a version of the PCRE library ' .
107 'that does not support Unicode properties. ' .
108 'If you are running Red Hat Enterprise Linux / ' .
109 'CentOS 5.4 or earlier, see <a href="' .
110 'http://status.net/wiki/Red_Hat_Enterprise_Linux#PCRE_library' .
111 '">our documentation page</a> on fixing this.');
115 $reqs = array('gd', 'curl',
116 'xmlwriter', 'mbstring', 'xml', 'dom', 'simplexml');
118 foreach ($reqs as $req) {
119 if (!$this->checkExtension($req)) {
120 $this->warning(sprintf('Cannot load required extension: <code>%s</code>', $req));
125 // Make sure we have at least one database module available
126 $missingExtensions = array();
127 foreach (self::$dbModules as $type => $info) {
128 if (!$this->checkExtension($info['check_module'])) {
129 $missingExtensions[] = $info['check_module'];
133 if (count($missingExtensions) == count(self::$dbModules)) {
134 $req = implode(', ', $missingExtensions);
135 $this->warning(sprintf('Cannot find a database extension. You need at least one of %s.', $req));
139 // @fixme this check seems to be insufficient with Windows ACLs
140 if (!is_writable(INSTALLDIR)) {
141 $this->warning(sprintf('Cannot write config file to: <code>%s</code></p>', INSTALLDIR),
142 sprintf('On your server, try this command: <code>chmod a+w %s</code>', INSTALLDIR));
146 // Check the subdirs used for file uploads
147 $fileSubdirs = array('avatar', 'background', 'file');
148 foreach ($fileSubdirs as $fileSubdir) {
149 $fileFullPath = INSTALLDIR."/$fileSubdir/";
150 if (!is_writable($fileFullPath)) {
151 $this->warning(sprintf('Cannot write to %s directory: <code>%s</code>', $fileSubdir, $fileFullPath),
152 sprintf('On your server, try this command: <code>chmod a+w %s</code>', $fileFullPath));
161 * Checks if a php extension is both installed and loaded
163 * @param string $name of extension to check
165 * @return boolean whether extension is installed and loaded
167 function checkExtension($name)
169 if (extension_loaded($name)) {
171 } elseif (function_exists('dl') && ini_get('enable_dl') && !ini_get('safe_mode')) {
172 // dl will throw a fatal error if it's disabled or we're in safe mode.
173 // More fun, it may not even exist under some SAPIs in 5.3.0 or later...
174 $soname = $name . '.' . PHP_SHLIB_SUFFIX;
175 if (PHP_SHLIB_SUFFIX == 'dll') {
176 $soname = "php_" . $soname;
185 * Basic validation on the database paramters
186 * Side effects: error output if not valid
188 * @return boolean success
190 function validateDb()
194 if (empty($this->host)) {
195 $this->updateStatus("No hostname specified.", true);
199 if (empty($this->database)) {
200 $this->updateStatus("No database specified.", true);
204 if (empty($this->username)) {
205 $this->updateStatus("No username specified.", true);
209 if (empty($this->sitename)) {
210 $this->updateStatus("No sitename specified.", true);
218 * Basic validation on the administrator user paramters
219 * Side effects: error output if not valid
221 * @return boolean success
223 function validateAdmin()
227 if (empty($this->adminNick)) {
228 $this->updateStatus("No initial StatusNet user nickname specified.", true);
231 if ($this->adminNick && !preg_match('/^[0-9a-z]{1,64}$/', $this->adminNick)) {
232 $this->updateStatus('The user nickname "' . htmlspecialchars($this->adminNick) .
233 '" is invalid; should be plain letters and numbers no longer than 64 characters.', true);
236 // @fixme hardcoded list; should use User::allowed_nickname()
237 // if/when it's safe to have loaded the infrastructure here
238 $blacklist = array('main', 'admin', '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');
239 if (in_array($this->adminNick, $blacklist)) {
240 $this->updateStatus('The user nickname "' . htmlspecialchars($this->adminNick) .
241 '" is reserved.', true);
245 if (empty($this->adminPass)) {
246 $this->updateStatus("No initial StatusNet user password specified.", true);
254 * Set up the database with the appropriate function for the selected type...
255 * Saves database info into $this->db.
257 * @fixme escape things in the connection string in case we have a funny pass etc
258 * @return mixed array of database connection params on success, false on failure
260 function setupDatabase()
263 throw new Exception("Bad order of operations: DB already set up.");
265 $this->updateStatus("Starting installation...");
267 if (empty($password)) {
270 $auth = ":$this->password";
272 $scheme = self::$dbModules[$this->dbtype]['scheme'];
274 $this->updateStatus("Checking database...");
275 $conn = $this->connectDatabase($dsn);
276 if (DB::isError($conn)) {
277 $this->updateStatus("Database connection error: " . $conn->getMessage(), true);
281 // ensure database encoding is UTF8
282 if ($this->dbtype == 'mysql') {
283 // @fixme utf8m4 support for mysql 5.5?
284 // Force the comms charset to utf8 for sanity
285 $conn->execute('SET names utf8');
286 } else if ($this->dbtype == 'pgsql') {
287 $record = $conn->getRow('SHOW server_encoding');
288 if ($record->server_encoding != 'UTF8') {
289 $this->updateStatus("StatusNet requires UTF8 character encoding. Your database is ". htmlentities($record->server_encoding));
294 $res = $this->updateStatus("Creating database tables...");
295 if (!$this->createCoreTables($conn)) {
296 $this->updateStatus("Error creating tables.", true);
300 foreach (array('sms_carrier' => 'SMS carrier',
301 'notice_source' => 'notice source',
302 'foreign_services' => 'foreign service')
304 $this->updateStatus(sprintf("Adding %s data to database...", $name));
305 $res = $this->runDbScript($scr.'.sql', $conn);
306 if ($res === false) {
307 $this->updateStatus(sprintf("Can't run %d script.", $name), true);
312 $db = array('type' => $this->dbtype, 'database' => $dsn);
317 * Open a connection to the database.
322 function connectDatabase($dsn)
324 require_once 'DB.php';
325 return DB::connect($dsn);
329 * Create core tables on the given database connection.
331 * @param DB_common $conn
333 function createCoreTables(DB_common $conn)
335 $schema = Schema::get($conn);
336 $tableDefs = $this->getCoreSchema();
337 foreach ($tableDefs as $name => $def) {
338 $schema->ensureTable($name, $def);
343 * Fetch the core table schema definitions.
345 * @return array of table names => table def arrays
347 function getCoreSchema()
350 include INSTALLDIR . '/db/core.php';
355 * Write a stock configuration file.
357 * @return boolean success
359 * @fixme escape variables in output in case we have funny chars, apostrophes etc
363 // assemble configuration file in a string
365 "if (!defined('STATUSNET') && !defined('LACONICA')) { exit(1); }\n\n".
368 "\$config['site']['name'] = '{$this->sitename}';\n\n".
371 "\$config['site']['server'] = '{$this->server}';\n".
372 "\$config['site']['path'] = '{$this->path}'; \n\n".
374 // checks if fancy URLs are enabled
375 ($this->fancy ? "\$config['site']['fancy'] = true;\n\n":'').
378 "\$config['db']['database'] = '{$this->db['database']}';\n\n".
379 ($this->db['type'] == 'pgsql' ? "\$config['db']['quote_identifiers'] = true;\n\n":'').
380 "\$config['db']['type'] = '{$this->db['type']}';\n\n";
382 // Normalize line endings for Windows servers
383 $cfg = str_replace("\n", PHP_EOL, $cfg);
385 // write configuration file out to install directory
386 $res = file_put_contents(INSTALLDIR.'/config.php', $cfg);
392 * Install schema into the database
394 * @param string $filename location of database schema file
395 * @param DB_common $conn connection to database
397 * @return boolean - indicating success or failure
399 function runDbScript($filename, DB_common $conn)
401 $sql = trim(file_get_contents(INSTALLDIR . '/db/' . $filename));
402 $stmts = explode(';', $sql);
403 foreach ($stmts as $stmt) {
405 if (!mb_strlen($stmt)) {
408 $res = $conn->execute($stmt);
409 if (DB::isError($res)) {
410 $error = $result->getMessage();
411 $this->updateStatus("ERROR ($error) for SQL '$stmt'");
419 * Create the initial admin user account.
420 * Side effect: may load portions of StatusNet framework.
421 * Side effect: outputs program info
423 function registerInitialUser()
425 define('STATUSNET', true);
426 define('LACONICA', true); // compatibility
428 require_once INSTALLDIR . '/lib/common.php';
430 $data = array('nickname' => $this->adminNick,
431 'password' => $this->adminPass,
432 'fullname' => $this->adminNick);
433 if ($this->adminEmail) {
434 $data['email'] = $this->adminEmail;
436 $user = User::register($data);
442 // give initial user carte blanche
444 $user->grantRole('owner');
445 $user->grantRole('moderator');
446 $user->grantRole('administrator');
448 // Attempt to do a remote subscribe to update@status.net
449 // Will fail if instance is on a private network.
451 if ($this->adminUpdates && class_exists('Ostatus_profile')) {
453 $oprofile = Ostatus_profile::ensureProfileURL('http://update.status.net/');
454 Subscription::start($user->getProfile(), $oprofile->localProfile());
455 $this->updateStatus("Set up subscription to <a href='http://update.status.net/'>update@status.net</a>.");
456 } catch (Exception $e) {
457 $this->updateStatus("Could not set up subscription to <a href='http://update.status.net/'>update@status.net</a>.", true);
465 * The beef of the installer!
466 * Create database, config file, and admin user.
468 * Prerequisites: validation of input data.
470 * @return boolean success
474 $this->db = $this->setupDatabase();
477 // database connection failed, do not move on to create config file.
481 if (!$this->skipConfig) {
482 $this->updateStatus("Writing config file...");
483 $res = $this->writeConf();
486 $this->updateStatus("Can't write config file.", true);
491 if (!empty($this->adminNick)) {
492 // Okay, cross fingers and try to register an initial user
493 if ($this->registerInitialUser()) {
495 "An initial user with the administrator role has been created."
499 "Could not create initial StatusNet user (administrator).",
507 TODO https needs to be considered
509 $link = "http://".$this->server.'/'.$this->path;
511 $this->updateStatus("StatusNet has been installed at $link");
513 "<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>."
520 * Output a pre-install-time warning message
521 * @param string $message HTML ok, but should be plaintext-able
522 * @param string $submessage HTML ok, but should be plaintext-able
524 abstract function warning($message, $submessage='');
527 * Output an install-time progress message
528 * @param string $message HTML ok, but should be plaintext-able
529 * @param boolean $error true if this should be marked as an error condition
531 abstract function updateStatus($status, $error=false);