]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - lib/installer.php
Merge branch 'master' of gitorious.org:statusnet/mainline
[quix0rs-gnu-social.git] / lib / installer.php
1 <?php
2
3 /**
4  * StatusNet - the distributed open-source microblogging tool
5  * Copyright (C) 2009, StatusNet, Inc.
6  *
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.
11  *
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.
16  *
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/>.
19  *
20  * @category Installation
21  * @package  Installation
22  *
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  * @license  GNU Affero General Public License http://www.gnu.org/licenses/
36  * @version  0.9.x
37  * @link     http://status.net
38  */
39
40 abstract class Installer
41 {
42     /** Web site info */
43     public $sitename, $server, $path, $fancy;
44     /** DB info */
45     public $host, $dbname, $dbtype, $username, $password, $db;
46     /** Administrator info */
47     public $adminNick, $adminPass, $adminEmail, $adminUpdates;
48     /** Should we skip writing the configuration file? */
49     public $skipConfig = false;
50
51     public static $dbModules = array(
52         'mysql' => array(
53             'name' => 'MySQL',
54             'check_module' => 'mysqli',
55             'installer' => 'mysql_db_installer',
56         ),
57         'pgsql' => array(
58             'name' => 'PostgreSQL',
59             'check_module' => 'pgsql',
60             'installer' => 'pgsql_db_installer',
61         ),
62     );
63
64     /**
65      * Attempt to include a PHP file and report if it worked, while
66      * suppressing the annoying warning messages on failure.
67      */
68     private function haveIncludeFile($filename) {
69         $old = error_reporting(error_reporting() & ~E_WARNING);
70         $ok = include_once($filename);
71         error_reporting($old);
72         return $ok;
73     }
74     
75     /**
76      * Check if all is ready for installation
77      *
78      * @return void
79      */
80     function checkPrereqs()
81     {
82         $pass = true;
83
84         $config = INSTALLDIR.'/config.php';
85         if (file_exists($config)) {
86             if (!is_writable($config) || filesize($config) > 0) {
87                 $this->warning('Config file "config.php" already exists.');
88                 $pass = false;
89             }
90         }
91
92         if (version_compare(PHP_VERSION, '5.2.3', '<')) {
93             $errors[] = 'Require PHP version 5.2.3 or greater.';
94             $pass = false;
95         }
96
97         // Look for known library bugs
98         $str = "abcdefghijklmnopqrstuvwxyz";
99         $replaced = preg_replace('/[\p{Cc}\p{Cs}]/u', '*', $str);
100         if ($str != $replaced) {
101             $this->warning('PHP is linked to a version of the PCRE library ' .
102                            'that does not support Unicode properties. ' .
103                            'If you are running Red Hat Enterprise Linux / ' .
104                            'CentOS 5.4 or earlier, see <a href="' .
105                            'http://status.net/wiki/Red_Hat_Enterprise_Linux#PCRE_library' .
106                            '">our documentation page</a> on fixing this.');
107             $pass = false;
108         }
109
110         $reqs = array('gd', 'curl',
111                       'xmlwriter', 'mbstring', 'xml', 'dom', 'simplexml');
112
113         foreach ($reqs as $req) {
114             if (!$this->checkExtension($req)) {
115                 $this->warning(sprintf('Cannot load required extension: <code>%s</code>', $req));
116                 $pass = false;
117             }
118         }
119
120         // Make sure we have at least one database module available
121         $missingExtensions = array();
122         foreach (self::$dbModules as $type => $info) {
123             if (!$this->checkExtension($info['check_module'])) {
124                 $missingExtensions[] = $info['check_module'];
125             }
126         }
127
128         if (count($missingExtensions) == count(self::$dbModules)) {
129             $req = implode(', ', $missingExtensions);
130             $this->warning(sprintf('Cannot find a database extension. You need at least one of %s.', $req));
131             $pass = false;
132         }
133
134         // @fixme this check seems to be insufficient with Windows ACLs
135         if (!is_writable(INSTALLDIR)) {
136             $this->warning(sprintf('Cannot write config file to: <code>%s</code></p>', INSTALLDIR),
137                            sprintf('On your server, try this command: <code>chmod a+w %s</code>', INSTALLDIR));
138             $pass = false;
139         }
140
141         // Check the subdirs used for file uploads
142         $fileSubdirs = array('avatar', 'background', 'file');
143         foreach ($fileSubdirs as $fileSubdir) {
144             $fileFullPath = INSTALLDIR."/$fileSubdir/";
145             if (!is_writable($fileFullPath)) {
146                 $this->warning(sprintf('Cannot write to %s directory: <code>%s</code>', $fileSubdir, $fileFullPath),
147                                sprintf('On your server, try this command: <code>chmod a+w %s</code>', $fileFullPath));
148                 $pass = false;
149             }
150         }
151
152         return $pass;
153     }
154
155     /**
156      * Checks if a php extension is both installed and loaded
157      *
158      * @param string $name of extension to check
159      *
160      * @return boolean whether extension is installed and loaded
161      */
162     function checkExtension($name)
163     {
164         if (extension_loaded($name)) {
165             return true;
166         } elseif (function_exists('dl') && ini_get('enable_dl') && !ini_get('safe_mode')) {
167             // dl will throw a fatal error if it's disabled or we're in safe mode.
168             // More fun, it may not even exist under some SAPIs in 5.3.0 or later...
169             $soname = $name . '.' . PHP_SHLIB_SUFFIX;
170             if (PHP_SHLIB_SUFFIX == 'dll') {
171                 $soname = "php_" . $soname;
172             }
173             return @dl($soname);
174         } else {
175             return false;
176         }
177     }
178
179     /**
180      * Basic validation on the database paramters
181      * Side effects: error output if not valid
182      * 
183      * @return boolean success
184      */
185     function validateDb()
186     {
187         $fail = false;
188
189         if (empty($this->host)) {
190             $this->updateStatus("No hostname specified.", true);
191             $fail = true;
192         }
193
194         if (empty($this->database)) {
195             $this->updateStatus("No database specified.", true);
196             $fail = true;
197         }
198
199         if (empty($this->username)) {
200             $this->updateStatus("No username specified.", true);
201             $fail = true;
202         }
203
204         if (empty($this->sitename)) {
205             $this->updateStatus("No sitename specified.", true);
206             $fail = true;
207         }
208
209         return !$fail;
210     }
211
212     /**
213      * Basic validation on the administrator user paramters
214      * Side effects: error output if not valid
215      * 
216      * @return boolean success
217      */
218     function validateAdmin()
219     {
220         $fail = false;
221
222         if (empty($this->adminNick)) {
223             $this->updateStatus("No initial StatusNet user nickname specified.", true);
224             $fail = true;
225         }
226         if ($this->adminNick && !preg_match('/^[0-9a-z]{1,64}$/', $this->adminNick)) {
227             $this->updateStatus('The user nickname "' . htmlspecialchars($this->adminNick) .
228                          '" is invalid; should be plain letters and numbers no longer than 64 characters.', true);
229             $fail = true;
230         }
231         // @fixme hardcoded list; should use User::allowed_nickname()
232         // if/when it's safe to have loaded the infrastructure here
233         $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');
234         if (in_array($this->adminNick, $blacklist)) {
235             $this->updateStatus('The user nickname "' . htmlspecialchars($this->adminNick) .
236                          '" is reserved.', true);
237             $fail = true;
238         }
239
240         if (empty($this->adminPass)) {
241             $this->updateStatus("No initial StatusNet user password specified.", true);
242             $fail = true;
243         }
244
245         return !$fail;
246     }
247
248     /**
249      * Set up the database with the appropriate function for the selected type...
250      * Saves database info into $this->db.
251      * 
252      * @return mixed array of database connection params on success, false on failure
253      */
254     function setupDatabase()
255     {
256         if ($this->db) {
257             throw new Exception("Bad order of operations: DB already set up.");
258         }
259         $method = self::$dbModules[$this->dbtype]['installer'];
260         $db = call_user_func(array($this, $method),
261                              $this->host,
262                              $this->database,
263                              $this->username,
264                              $this->password);
265         $this->db = $db;
266         return $this->db;
267     }
268
269     /**
270      * Set up a database on PostgreSQL.
271      * Will output status updates during the operation.
272      * 
273      * @param string $host
274      * @param string $database
275      * @param string $username
276      * @param string $password
277      * @return mixed array of database connection params on success, false on failure
278      * 
279      * @fixme escape things in the connection string in case we have a funny pass etc
280      */
281     function Pgsql_Db_installer($host, $database, $username, $password)
282     {
283         $connstring = "dbname=$database host=$host user=$username";
284
285         //No password would mean trust authentication used.
286         if (!empty($password)) {
287             $connstring .= " password=$password";
288         }
289         $this->updateStatus("Starting installation...");
290         $this->updateStatus("Checking database...");
291         $conn = pg_connect($connstring);
292
293         if ($conn ===false) {
294             $this->updateStatus("Failed to connect to database: $connstring");
295             return false;
296         }
297
298         //ensure database encoding is UTF8
299         $record = pg_fetch_object(pg_query($conn, 'SHOW server_encoding'));
300         if ($record->server_encoding != 'UTF8') {
301             $this->updateStatus("StatusNet requires UTF8 character encoding. Your database is ". htmlentities($record->server_encoding));
302             return false;
303         }
304
305         $this->updateStatus("Running database script...");
306         //wrap in transaction;
307         pg_query($conn, 'BEGIN');
308         $res = $this->runDbScript('statusnet_pg.sql', $conn, 'pgsql');
309
310         if ($res === false) {
311             $this->updateStatus("Can't run database script.", true);
312             return false;
313         }
314         foreach (array('sms_carrier' => 'SMS carrier',
315                     'notice_source' => 'notice source',
316                     'foreign_services' => 'foreign service')
317               as $scr => $name) {
318             $this->updateStatus(sprintf("Adding %s data to database...", $name));
319             $res = $this->runDbScript($scr.'.sql', $conn, 'pgsql');
320             if ($res === false) {
321                 $this->updateStatus(sprintf("Can't run %d script.", $name), true);
322                 return false;
323             }
324         }
325         pg_query($conn, 'COMMIT');
326
327         if (empty($password)) {
328             $sqlUrl = "pgsql://$username@$host/$database";
329         } else {
330             $sqlUrl = "pgsql://$username:$password@$host/$database";
331         }
332
333         $db = array('type' => 'pgsql', 'database' => $sqlUrl);
334
335         return $db;
336     }
337
338     /**
339      * Set up a database on MySQL.
340      * Will output status updates during the operation.
341      * 
342      * @param string $host
343      * @param string $database
344      * @param string $username
345      * @param string $password
346      * @return mixed array of database connection params on success, false on failure
347      * 
348      * @fixme escape things in the connection string in case we have a funny pass etc
349      */
350     function Mysql_Db_installer($host, $database, $username, $password)
351     {
352         $this->updateStatus("Starting installation...");
353         $this->updateStatus("Checking database...");
354
355         $conn = mysqli_init();
356         if (!$conn->real_connect($host, $username, $password)) {
357             $this->updateStatus("Can't connect to server '$host' as '$username'.", true);
358             return false;
359         }
360         $this->updateStatus("Changing to database...");
361         if (!$conn->select_db($database)) {
362             $this->updateStatus("Can't change to database.", true);
363             return false;
364         }
365
366         $this->updateStatus("Running database script...");
367         $res = $this->runDbScript('statusnet.sql', $conn);
368         if ($res === false) {
369             $this->updateStatus("Can't run database script.", true);
370             return false;
371         }
372         foreach (array('sms_carrier' => 'SMS carrier',
373                     'notice_source' => 'notice source',
374                     'foreign_services' => 'foreign service')
375               as $scr => $name) {
376             $this->updateStatus(sprintf("Adding %s data to database...", $name));
377             $res = $this->runDbScript($scr.'.sql', $conn);
378             if ($res === false) {
379                 $this->updateStatus(sprintf("Can't run %d script.", $name), true);
380                 return false;
381             }
382         }
383
384         $sqlUrl = "mysqli://$username:$password@$host/$database";
385         $db = array('type' => 'mysql', 'database' => $sqlUrl);
386         return $db;
387     }
388
389     /**
390      * Write a stock configuration file.
391      *
392      * @return boolean success
393      * 
394      * @fixme escape variables in output in case we have funny chars, apostrophes etc
395      */
396     function writeConf()
397     {
398         // assemble configuration file in a string
399         $cfg =  "<?php\n".
400                 "if (!defined('STATUSNET') && !defined('LACONICA')) { exit(1); }\n\n".
401
402                 // site name
403                 "\$config['site']['name'] = '{$this->sitename}';\n\n".
404
405                 // site location
406                 "\$config['site']['server'] = '{$this->server}';\n".
407                 "\$config['site']['path'] = '{$this->path}'; \n\n".
408
409                 // checks if fancy URLs are enabled
410                 ($this->fancy ? "\$config['site']['fancy'] = true;\n\n":'').
411
412                 // database
413                 "\$config['db']['database'] = '{$this->db['database']}';\n\n".
414                 ($this->db['type'] == 'pgsql' ? "\$config['db']['quote_identifiers'] = true;\n\n":'').
415                 "\$config['db']['type'] = '{$this->db['type']}';\n\n";
416
417         // Normalize line endings for Windows servers
418         $cfg = str_replace("\n", PHP_EOL, $cfg);
419
420         // write configuration file out to install directory
421         $res = file_put_contents(INSTALLDIR.'/config.php', $cfg);
422
423         return $res;
424     }
425
426     /**
427      * Install schema into the database
428      *
429      * @param string $filename location of database schema file
430      * @param dbconn $conn     connection to database
431      * @param string $type     type of database, currently mysql or pgsql
432      *
433      * @return boolean - indicating success or failure
434      */
435     function runDbScript($filename, $conn, $type = 'mysqli')
436     {
437         $sql = trim(file_get_contents(INSTALLDIR . '/db/' . $filename));
438         $stmts = explode(';', $sql);
439         foreach ($stmts as $stmt) {
440             $stmt = trim($stmt);
441             if (!mb_strlen($stmt)) {
442                 continue;
443             }
444             // FIXME: use PEAR::DB or PDO instead of our own switch
445             switch ($type) {
446             case 'mysqli':
447                 $res = $conn->query($stmt);
448                 if ($res === false) {
449                     $error = $conn->error();
450                 }
451                 break;
452             case 'pgsql':
453                 $res = pg_query($conn, $stmt);
454                 if ($res === false) {
455                     $error = pg_last_error();
456                 }
457                 break;
458             default:
459                 $this->updateStatus("runDbScript() error: unknown database type ". $type ." provided.");
460             }
461             if ($res === false) {
462                 $this->updateStatus("ERROR ($error) for SQL '$stmt'");
463                 return $res;
464             }
465         }
466         return true;
467     }
468
469     /**
470      * Create the initial admin user account.
471      * Side effect: may load portions of StatusNet framework.
472      * Side effect: outputs program info
473      */
474     function registerInitialUser()
475     {
476         define('STATUSNET', true);
477         define('LACONICA', true); // compatibility
478
479         require_once INSTALLDIR . '/lib/common.php';
480
481         $data = array('nickname' => $this->adminNick,
482                       'password' => $this->adminPass,
483                       'fullname' => $this->adminNick);
484         if ($this->adminEmail) {
485             $data['email'] = $this->adminEmail;
486         }
487         $user = User::register($data);
488
489         if (empty($user)) {
490             return false;
491         }
492
493         // give initial user carte blanche
494
495         $user->grantRole('owner');
496         $user->grantRole('moderator');
497         $user->grantRole('administrator');
498         
499         // Attempt to do a remote subscribe to update@status.net
500         // Will fail if instance is on a private network.
501
502         if ($this->adminUpdates && class_exists('Ostatus_profile')) {
503             try {
504                 $oprofile = Ostatus_profile::ensureProfileURL('http://update.status.net/');
505                 Subscription::start($user->getProfile(), $oprofile->localProfile());
506                 $this->updateStatus("Set up subscription to <a href='http://update.status.net/'>update@status.net</a>.");
507             } catch (Exception $e) {
508                 $this->updateStatus("Could not set up subscription to <a href='http://update.status.net/'>update@status.net</a>.", true);
509             }
510         }
511
512         return true;
513     }
514
515     /**
516      * The beef of the installer!
517      * Create database, config file, and admin user.
518      * 
519      * Prerequisites: validation of input data.
520      * 
521      * @return boolean success
522      */
523     function doInstall()
524     {
525         $this->db = $this->setupDatabase();
526
527         if (!$this->db) {
528             // database connection failed, do not move on to create config file.
529             return false;
530         }
531
532         if (!$this->skipConfig) {
533             $this->updateStatus("Writing config file...");
534             $res = $this->writeConf();
535
536             if (!$res) {
537                 $this->updateStatus("Can't write config file.", true);
538                 return false;
539             }
540         }
541
542         if (!empty($this->adminNick)) {
543             // Okay, cross fingers and try to register an initial user
544             if ($this->registerInitialUser()) {
545                 $this->updateStatus(
546                     "An initial user with the administrator role has been created."
547                 );
548             } else {
549                 $this->updateStatus(
550                     "Could not create initial StatusNet user (administrator).",
551                     true
552                 );
553                 return false;
554             }
555         }
556
557         /*
558             TODO https needs to be considered
559         */
560         $link = "http://".$this->server.'/'.$this->path;
561
562         $this->updateStatus("StatusNet has been installed at $link");
563         $this->updateStatus(
564             "<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>."
565         );
566
567         return true;
568     }
569
570     /**
571      * Output a pre-install-time warning message
572      * @param string $message HTML ok, but should be plaintext-able
573      * @param string $submessage HTML ok, but should be plaintext-able
574      */
575     abstract function warning($message, $submessage='');
576
577     /**
578      * Output an install-time progress message
579      * @param string $message HTML ok, but should be plaintext-able
580      * @param boolean $error true if this should be marked as an error condition
581      */
582     abstract function updateStatus($status, $error=false);
583
584 }