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