]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - lib/installer.php
Merge branch '0.9.x' into twitstream
[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  * @copyright 2009 Free Software Foundation, Inc http://www.fsf.org
36  * @license  GNU Affero General Public License http://www.gnu.org/licenses/
37  * @version  0.9.x
38  * @link     http://status.net
39  */
40
41 abstract class Installer
42 {
43     /** Web site info */
44     public $sitename, $server, $path, $fancy;
45     /** DB info */
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;
51
52     public static $dbModules = array(
53         'mysql' => array(
54             'name' => 'MySQL',
55             'check_module' => 'mysqli',
56             'installer' => 'mysql_db_installer',
57         ),
58         'pgsql' => array(
59             'name' => 'PostgreSQL',
60             'check_module' => 'pgsql',
61             'installer' => 'pgsql_db_installer',
62         ),
63     );
64
65     /**
66      * Attempt to include a PHP file and report if it worked, while
67      * suppressing the annoying warning messages on failure.
68      */
69     private function haveIncludeFile($filename) {
70         $old = error_reporting(error_reporting() & ~E_WARNING);
71         $ok = include_once($filename);
72         error_reporting($old);
73         return $ok;
74     }
75     
76     /**
77      * Check if all is ready for installation
78      *
79      * @return void
80      */
81     function checkPrereqs()
82     {
83         $pass = true;
84
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.');
90                 } else {
91                     $this->warning('Config file "config.php" already exists.');
92                 }
93                 $pass = false;
94             }
95         }
96
97         if (version_compare(PHP_VERSION, '5.2.3', '<')) {
98             $this->warning('Require PHP version 5.2.3 or greater.');
99             $pass = false;
100         }
101
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.');
112             $pass = false;
113         }
114
115         $reqs = array('gd', 'curl',
116                       'xmlwriter', 'mbstring', 'xml', 'dom', 'simplexml');
117
118         foreach ($reqs as $req) {
119             if (!$this->checkExtension($req)) {
120                 $this->warning(sprintf('Cannot load required extension: <code>%s</code>', $req));
121                 $pass = false;
122             }
123         }
124
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'];
130             }
131         }
132
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));
136             $pass = false;
137         }
138
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));
143             $pass = false;
144         }
145
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));
153                 $pass = false;
154             }
155         }
156
157         return $pass;
158     }
159
160     /**
161      * Checks if a php extension is both installed and loaded
162      *
163      * @param string $name of extension to check
164      *
165      * @return boolean whether extension is installed and loaded
166      */
167     function checkExtension($name)
168     {
169         if (extension_loaded($name)) {
170             return true;
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;
177             }
178             return @dl($soname);
179         } else {
180             return false;
181         }
182     }
183
184     /**
185      * Basic validation on the database paramters
186      * Side effects: error output if not valid
187      * 
188      * @return boolean success
189      */
190     function validateDb()
191     {
192         $fail = false;
193
194         if (empty($this->host)) {
195             $this->updateStatus("No hostname specified.", true);
196             $fail = true;
197         }
198
199         if (empty($this->database)) {
200             $this->updateStatus("No database specified.", true);
201             $fail = true;
202         }
203
204         if (empty($this->username)) {
205             $this->updateStatus("No username specified.", true);
206             $fail = true;
207         }
208
209         if (empty($this->sitename)) {
210             $this->updateStatus("No sitename specified.", true);
211             $fail = true;
212         }
213
214         return !$fail;
215     }
216
217     /**
218      * Basic validation on the administrator user paramters
219      * Side effects: error output if not valid
220      * 
221      * @return boolean success
222      */
223     function validateAdmin()
224     {
225         $fail = false;
226
227         if (empty($this->adminNick)) {
228             $this->updateStatus("No initial StatusNet user nickname specified.", true);
229             $fail = true;
230         }
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);
234             $fail = true;
235         }
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);
242             $fail = true;
243         }
244
245         if (empty($this->adminPass)) {
246             $this->updateStatus("No initial StatusNet user password specified.", true);
247             $fail = true;
248         }
249
250         return !$fail;
251     }
252
253     /**
254      * Set up the database with the appropriate function for the selected type...
255      * Saves database info into $this->db.
256      * 
257      * @return mixed array of database connection params on success, false on failure
258      */
259     function setupDatabase()
260     {
261         if ($this->db) {
262             throw new Exception("Bad order of operations: DB already set up.");
263         }
264         $method = self::$dbModules[$this->dbtype]['installer'];
265         $db = call_user_func(array($this, $method),
266                              $this->host,
267                              $this->database,
268                              $this->username,
269                              $this->password);
270         $this->db = $db;
271         return $this->db;
272     }
273
274     /**
275      * Set up a database on PostgreSQL.
276      * Will output status updates during the operation.
277      * 
278      * @param string $host
279      * @param string $database
280      * @param string $username
281      * @param string $password
282      * @return mixed array of database connection params on success, false on failure
283      * 
284      * @fixme escape things in the connection string in case we have a funny pass etc
285      */
286     function Pgsql_Db_installer($host, $database, $username, $password)
287     {
288         $connstring = "dbname=$database host=$host user=$username";
289
290         //No password would mean trust authentication used.
291         if (!empty($password)) {
292             $connstring .= " password=$password";
293         }
294         $this->updateStatus("Starting installation...");
295         $this->updateStatus("Checking database...");
296         $conn = pg_connect($connstring);
297
298         if ($conn ===false) {
299             $this->updateStatus("Failed to connect to database: $connstring");
300             return false;
301         }
302
303         //ensure database encoding is UTF8
304         $record = pg_fetch_object(pg_query($conn, 'SHOW server_encoding'));
305         if ($record->server_encoding != 'UTF8') {
306             $this->updateStatus("StatusNet requires UTF8 character encoding. Your database is ". htmlentities($record->server_encoding));
307             return false;
308         }
309
310         $this->updateStatus("Running database script...");
311         //wrap in transaction;
312         pg_query($conn, 'BEGIN');
313         $res = $this->runDbScript('statusnet_pg.sql', $conn, 'pgsql');
314
315         if ($res === false) {
316             $this->updateStatus("Can't run database script.", true);
317             return false;
318         }
319         foreach (array('sms_carrier' => 'SMS carrier',
320                     'notice_source' => 'notice source',
321                     'foreign_services' => 'foreign service')
322               as $scr => $name) {
323             $this->updateStatus(sprintf("Adding %s data to database...", $name));
324             $res = $this->runDbScript($scr.'.sql', $conn, 'pgsql');
325             if ($res === false) {
326                 $this->updateStatus(sprintf("Can't run %s script.", $name), true);
327                 return false;
328             }
329         }
330         pg_query($conn, 'COMMIT');
331
332         if (empty($password)) {
333             $sqlUrl = "pgsql://$username@$host/$database";
334         } else {
335             $sqlUrl = "pgsql://$username:$password@$host/$database";
336         }
337
338         $db = array('type' => 'pgsql', 'database' => $sqlUrl);
339
340         return $db;
341     }
342
343     /**
344      * Set up a database on MySQL.
345      * Will output status updates during the operation.
346      * 
347      * @param string $host
348      * @param string $database
349      * @param string $username
350      * @param string $password
351      * @return mixed array of database connection params on success, false on failure
352      * 
353      * @fixme escape things in the connection string in case we have a funny pass etc
354      */
355     function Mysql_Db_installer($host, $database, $username, $password)
356     {
357         $this->updateStatus("Starting installation...");
358         $this->updateStatus("Checking database...");
359
360         $conn = mysqli_init();
361         if (!$conn->real_connect($host, $username, $password)) {
362             $this->updateStatus("Can't connect to server '$host' as '$username'.", true);
363             return false;
364         }
365         $this->updateStatus("Changing to database...");
366         if (!$conn->select_db($database)) {
367             $this->updateStatus("Can't change to database.", true);
368             return false;
369         }
370
371         $this->updateStatus("Running database script...");
372         $res = $this->runDbScript('statusnet.sql', $conn);
373         if ($res === false) {
374             $this->updateStatus("Can't run database script.", true);
375             return false;
376         }
377         foreach (array('sms_carrier' => 'SMS carrier',
378                     'notice_source' => 'notice source',
379                     'foreign_services' => 'foreign service')
380               as $scr => $name) {
381             $this->updateStatus(sprintf("Adding %s data to database...", $name));
382             $res = $this->runDbScript($scr.'.sql', $conn);
383             if ($res === false) {
384                 $this->updateStatus(sprintf("Can't run %d script.", $name), true);
385                 return false;
386             }
387         }
388
389         $sqlUrl = "mysqli://$username:$password@$host/$database";
390         $db = array('type' => 'mysql', 'database' => $sqlUrl);
391         return $db;
392     }
393
394     /**
395      * Return a parseable PHP literal for the given value.
396      * This will include quotes for strings, etc.
397      *
398      * @param mixed $val
399      * @return string
400      */
401     function phpVal($val)
402     {
403         return var_export($val, true);
404     }
405
406     /**
407      * Return an array of parseable PHP literal for the given values.
408      * These will include quotes for strings, etc.
409      *
410      * @param mixed $val
411      * @return array
412      */
413     function phpVals($map)
414     {
415         return array_map(array($this, 'phpVal'), $map);
416     }
417
418     /**
419      * Write a stock configuration file.
420      *
421      * @return boolean success
422      * 
423      * @fixme escape variables in output in case we have funny chars, apostrophes etc
424      */
425     function writeConf()
426     {
427         $vals = $this->phpVals(array(
428             'sitename' => $this->sitename,
429             'server' => $this->server,
430             'path' => $this->path,
431             'db_database' => $this->db['database'],
432             'db_type' => $this->db['type'],
433         ));
434
435         // assemble configuration file in a string
436         $cfg =  "<?php\n".
437                 "if (!defined('STATUSNET') && !defined('LACONICA')) { exit(1); }\n\n".
438
439                 // site name
440                 "\$config['site']['name'] = {$vals['sitename']};\n\n".
441
442                 // site location
443                 "\$config['site']['server'] = {$vals['server']};\n".
444                 "\$config['site']['path'] = {$vals['path']}; \n\n".
445
446                 // checks if fancy URLs are enabled
447                 ($this->fancy ? "\$config['site']['fancy'] = true;\n\n":'').
448
449                 // database
450                 "\$config['db']['database'] = {$vals['db_database']};\n\n".
451                 ($this->db['type'] == 'pgsql' ? "\$config['db']['quote_identifiers'] = true;\n\n":'').
452                 "\$config['db']['type'] = {$vals['db_type']};\n\n";
453
454         // Normalize line endings for Windows servers
455         $cfg = str_replace("\n", PHP_EOL, $cfg);
456
457         // write configuration file out to install directory
458         $res = file_put_contents(INSTALLDIR.'/config.php', $cfg);
459
460         return $res;
461     }
462
463     /**
464      * Install schema into the database
465      *
466      * @param string $filename location of database schema file
467      * @param dbconn $conn     connection to database
468      * @param string $type     type of database, currently mysql or pgsql
469      *
470      * @return boolean - indicating success or failure
471      */
472     function runDbScript($filename, $conn, $type = 'mysqli')
473     {
474         $sql = trim(file_get_contents(INSTALLDIR . '/db/' . $filename));
475         $stmts = explode(';', $sql);
476         foreach ($stmts as $stmt) {
477             $stmt = trim($stmt);
478             if (!mb_strlen($stmt)) {
479                 continue;
480             }
481             // FIXME: use PEAR::DB or PDO instead of our own switch
482             switch ($type) {
483             case 'mysqli':
484                 $res = $conn->query($stmt);
485                 if ($res === false) {
486                     $error = $conn->error;
487                 }
488                 break;
489             case 'pgsql':
490                 $res = pg_query($conn, $stmt);
491                 if ($res === false) {
492                     $error = pg_last_error();
493                 }
494                 break;
495             default:
496                 $this->updateStatus("runDbScript() error: unknown database type ". $type ." provided.");
497             }
498             if ($res === false) {
499                 $this->updateStatus("ERROR ($error) for SQL '$stmt'");
500                 return $res;
501             }
502         }
503         return true;
504     }
505
506     /**
507      * Create the initial admin user account.
508      * Side effect: may load portions of StatusNet framework.
509      * Side effect: outputs program info
510      */
511     function registerInitialUser()
512     {
513         define('STATUSNET', true);
514         define('LACONICA', true); // compatibility
515
516         require_once INSTALLDIR . '/lib/common.php';
517
518         $data = array('nickname' => $this->adminNick,
519                       'password' => $this->adminPass,
520                       'fullname' => $this->adminNick);
521         if ($this->adminEmail) {
522             $data['email'] = $this->adminEmail;
523         }
524         $user = User::register($data);
525
526         if (empty($user)) {
527             return false;
528         }
529
530         // give initial user carte blanche
531
532         $user->grantRole('owner');
533         $user->grantRole('moderator');
534         $user->grantRole('administrator');
535         
536         // Attempt to do a remote subscribe to update@status.net
537         // Will fail if instance is on a private network.
538
539         if ($this->adminUpdates && class_exists('Ostatus_profile')) {
540             try {
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);
546             }
547         }
548
549         return true;
550     }
551
552     /**
553      * The beef of the installer!
554      * Create database, config file, and admin user.
555      * 
556      * Prerequisites: validation of input data.
557      * 
558      * @return boolean success
559      */
560     function doInstall()
561     {
562         $this->db = $this->setupDatabase();
563
564         if (!$this->db) {
565             // database connection failed, do not move on to create config file.
566             return false;
567         }
568
569         if (!$this->skipConfig) {
570             $this->updateStatus("Writing config file...");
571             $res = $this->writeConf();
572
573             if (!$res) {
574                 $this->updateStatus("Can't write config file.", true);
575                 return false;
576             }
577         }
578
579         if (!empty($this->adminNick)) {
580             // Okay, cross fingers and try to register an initial user
581             if ($this->registerInitialUser()) {
582                 $this->updateStatus(
583                     "An initial user with the administrator role has been created."
584                 );
585             } else {
586                 $this->updateStatus(
587                     "Could not create initial StatusNet user (administrator).",
588                     true
589                 );
590                 return false;
591             }
592         }
593
594         /*
595             TODO https needs to be considered
596         */
597         $link = "http://".$this->server.'/'.$this->path;
598
599         $this->updateStatus("StatusNet has been installed at $link");
600         $this->updateStatus(
601             "<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>."
602         );
603
604         return true;
605     }
606
607     /**
608      * Output a pre-install-time warning message
609      * @param string $message HTML ok, but should be plaintext-able
610      * @param string $submessage HTML ok, but should be plaintext-able
611      */
612     abstract function warning($message, $submessage='');
613
614     /**
615      * Output an install-time progress message
616      * @param string $message HTML ok, but should be plaintext-able
617      * @param boolean $error true if this should be marked as an error condition
618      */
619     abstract function updateStatus($status, $error=false);
620
621 }