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