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