]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - lib/installer.php
GNUSOCIAL is the new defined indicator
[quix0rs-gnu-social.git] / lib / installer.php
1 <?php
2
3 /**
4  * StatusNet - the distributed open-source microblogging tool
5  * Copyright (C) 2009-2010, 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   Mikael Nordfeldth <mmn@hethane.se>
32  * @author   Robin Millette <millette@controlyourself.ca>
33  * @author   Sarven Capadisli <csarven@status.net>
34  * @author   Tom Adams <tom@holizz.com>
35  * @author   Zach Copley <zach@status.net>
36  * @copyright 2009-2010 StatusNet, Inc http://status.net
37  * @copyright 2009 Free Software Foundation, Inc http://www.fsf.org
38  * @license  GNU Affero General Public License http://www.gnu.org/licenses/
39  * @version  1.0.x
40  * @link     http://status.net
41  */
42
43 abstract class Installer
44 {
45     /** Web site info */
46     public $sitename, $server, $path, $fancy, $siteProfile, $ssl;
47     /** DB info */
48     public $host, $database, $dbtype, $username, $password, $db;
49     /** Administrator info */
50     public $adminNick, $adminPass, $adminEmail, $adminUpdates;
51     /** Should we skip writing the configuration file? */
52     public $skipConfig = false;
53
54     public static $dbModules = array(
55         'mysql' => array(
56             'name' => 'MySQL',
57             'check_module' => 'mysqli',
58             'scheme' => 'mysqli', // DSN prefix for PEAR::DB
59         ),
60         'pgsql' => array(
61             'name' => 'PostgreSQL',
62             'check_module' => 'pgsql',
63             'scheme' => 'pgsql', // DSN prefix for PEAR::DB
64         ),
65     );
66
67     /**
68      * Attempt to include a PHP file and report if it worked, while
69      * suppressing the annoying warning messages on failure.
70      */
71     private function haveIncludeFile($filename) {
72         $old = error_reporting(error_reporting() & ~E_WARNING);
73         $ok = include_once($filename);
74         error_reporting($old);
75         return $ok;
76     }
77
78     /**
79      * Check if all is ready for installation
80      *
81      * @return void
82      */
83     function checkPrereqs()
84     {
85         $pass = true;
86
87         $config = INSTALLDIR.'/config.php';
88         if (file_exists($config)) {
89             if (!is_writable($config) || filesize($config) > 0) {
90                 if (filesize($config) == 0) {
91                     $this->warning('Config file "config.php" already exists and is empty, but is not writable.');
92                 } else {
93                     $this->warning('Config file "config.php" already exists.');
94                 }
95                 $pass = false;
96             }
97         }
98
99         if (version_compare(PHP_VERSION, '5.2.3', '<')) {
100             $this->warning('Require PHP version 5.2.3 or greater.');
101             $pass = false;
102         }
103
104         // Look for known library bugs
105         $str = "abcdefghijklmnopqrstuvwxyz";
106         $replaced = preg_replace('/[\p{Cc}\p{Cs}]/u', '*', $str);
107         if ($str != $replaced) {
108             $this->warning('PHP is linked to a version of the PCRE library ' .
109                            'that does not support Unicode properties. ' .
110                            'If you are running Red Hat Enterprise Linux / ' .
111                            'CentOS 5.4 or earlier, see <a href="' .
112                            'http://status.net/wiki/Red_Hat_Enterprise_Linux#PCRE_library' .
113                            '">our documentation page</a> on fixing this.');
114             $pass = false;
115         }
116
117         $reqs = array('gd', 'curl',
118                       'xmlwriter', 'mbstring', 'xml', 'dom', 'simplexml');
119
120         foreach ($reqs as $req) {
121             if (!$this->checkExtension($req)) {
122                 $this->warning(sprintf('Cannot load required extension: <code>%s</code>', $req));
123                 $pass = false;
124             }
125         }
126
127         // Make sure we have at least one database module available
128         $missingExtensions = array();
129         foreach (self::$dbModules as $type => $info) {
130             if (!$this->checkExtension($info['check_module'])) {
131                 $missingExtensions[] = $info['check_module'];
132             }
133         }
134
135         if (count($missingExtensions) == count(self::$dbModules)) {
136             $req = implode(', ', $missingExtensions);
137             $this->warning(sprintf('Cannot find a database extension. You need at least one of %s.', $req));
138             $pass = false;
139         }
140
141         // @fixme this check seems to be insufficient with Windows ACLs
142         if (!is_writable(INSTALLDIR)) {
143             $this->warning(sprintf('Cannot write config file to: <code>%s</code></p>', INSTALLDIR),
144                            sprintf('On your server, try this command: <code>chmod a+w %s</code>', INSTALLDIR));
145             $pass = false;
146         }
147
148         // Check the subdirs used for file uploads
149         $fileSubdirs = array('avatar', 'background', 'file');
150         foreach ($fileSubdirs as $fileSubdir) {
151             $fileFullPath = INSTALLDIR."/$fileSubdir/";
152             if (!is_writable($fileFullPath)) {
153                 $this->warning(sprintf('Cannot write to %s directory: <code>%s</code>', $fileSubdir, $fileFullPath),
154                                sprintf('On your server, try this command: <code>chmod a+w %s</code>', $fileFullPath));
155                 $pass = false;
156             }
157         }
158
159         return $pass;
160     }
161
162     /**
163      * Checks if a php extension is both installed and loaded
164      *
165      * @param string $name of extension to check
166      *
167      * @return boolean whether extension is installed and loaded
168      */
169     function checkExtension($name)
170     {
171         if (extension_loaded($name)) {
172             return true;
173         } elseif (function_exists('dl') && ini_get('enable_dl') && !ini_get('safe_mode')) {
174             // dl will throw a fatal error if it's disabled or we're in safe mode.
175             // More fun, it may not even exist under some SAPIs in 5.3.0 or later...
176             $soname = $name . '.' . PHP_SHLIB_SUFFIX;
177             if (PHP_SHLIB_SUFFIX == 'dll') {
178                 $soname = "php_" . $soname;
179             }
180             return @dl($soname);
181         } else {
182             return false;
183         }
184     }
185
186     /**
187      * Basic validation on the database paramters
188      * Side effects: error output if not valid
189      *
190      * @return boolean success
191      */
192     function validateDb()
193     {
194         $fail = false;
195
196         if (empty($this->host)) {
197             $this->updateStatus("No hostname specified.", true);
198             $fail = true;
199         }
200
201         if (empty($this->database)) {
202             $this->updateStatus("No database specified.", true);
203             $fail = true;
204         }
205
206         if (empty($this->username)) {
207             $this->updateStatus("No username specified.", true);
208             $fail = true;
209         }
210
211         if (empty($this->sitename)) {
212             $this->updateStatus("No sitename specified.", true);
213             $fail = true;
214         }
215
216         return !$fail;
217     }
218
219     /**
220      * Basic validation on the administrator user paramters
221      * Side effects: error output if not valid
222      *
223      * @return boolean success
224      */
225     function validateAdmin()
226     {
227         $fail = false;
228
229         if (empty($this->adminNick)) {
230             $this->updateStatus("No initial StatusNet user nickname specified.", true);
231             $fail = true;
232         }
233         if ($this->adminNick && !preg_match('/^[0-9a-z]{1,64}$/', $this->adminNick)) {
234             $this->updateStatus('The user nickname "' . htmlspecialchars($this->adminNick) .
235                          '" is invalid; should be plain letters and numbers no longer than 64 characters.', true);
236             $fail = true;
237         }
238         // @fixme hardcoded list; should use User::allowed_nickname()
239         // if/when it's safe to have loaded the infrastructure here
240         $blacklist = array('main', 'panel', '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');
241         if (in_array($this->adminNick, $blacklist)) {
242             $this->updateStatus('The user nickname "' . htmlspecialchars($this->adminNick) .
243                          '" is reserved.', true);
244             $fail = true;
245         }
246
247         if (empty($this->adminPass)) {
248             $this->updateStatus("No initial StatusNet user password specified.", true);
249             $fail = true;
250         }
251
252         return !$fail;
253     }
254
255     /**
256      * Make sure a site profile was selected
257      *
258      * @return type boolean success
259      */
260     function validateSiteProfile()
261     {
262         $fail = false;
263
264         $sprofile = $this->siteProfile;
265
266         if (empty($sprofile))  {
267             $this->updateStatus("No site profile selected.", true);
268             $fail = true;
269         }
270
271         return !$fail;
272     }
273
274     /**
275      * Set up the database with the appropriate function for the selected type...
276      * Saves database info into $this->db.
277      *
278      * @fixme escape things in the connection string in case we have a funny pass etc
279      * @return mixed array of database connection params on success, false on failure
280      */
281     function setupDatabase()
282     {
283         if ($this->db) {
284             throw new Exception("Bad order of operations: DB already set up.");
285         }
286         $this->updateStatus("Starting installation...");
287
288         if (empty($this->password)) {
289             $auth = '';
290         } else {
291             $auth = ":$this->password";
292         }
293         $scheme = self::$dbModules[$this->dbtype]['scheme'];
294         $dsn = "{$scheme}://{$this->username}{$auth}@{$this->host}/{$this->database}";
295
296         $this->updateStatus("Checking database...");
297         $conn = $this->connectDatabase($dsn);
298
299         // ensure database encoding is UTF8
300         if ($this->dbtype == 'mysql') {
301             // @fixme utf8m4 support for mysql 5.5?
302             // Force the comms charset to utf8 for sanity
303             // This doesn't currently work. :P
304             //$conn->executes('set names utf8');
305         } else if ($this->dbtype == 'pgsql') {
306             $record = $conn->getRow('SHOW server_encoding');
307             if ($record->server_encoding != 'UTF8') {
308                 $this->updateStatus("StatusNet requires UTF8 character encoding. Your database is ". htmlentities($record->server_encoding));
309                 return false;
310             }
311         }
312
313         $res = $this->updateStatus("Creating database tables...");
314         if (!$this->createCoreTables($conn)) {
315             $this->updateStatus("Error creating tables.", true);
316             return false;
317         }
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);
325             if ($res === false) {
326                 $this->updateStatus(sprintf("Can't run %s script.", $name), true);
327                 return false;
328             }
329         }
330
331         $db = array('type' => $this->dbtype, 'database' => $dsn);
332         return $db;
333     }
334
335     /**
336      * Open a connection to the database.
337      *
338      * @param <type> $dsn
339      * @return <type>
340      */
341     function connectDatabase($dsn)
342     {
343         // @fixme move this someplace more sensible
344         //set_include_path(INSTALLDIR . '/extlib' . PATH_SEPARATOR . get_include_path());
345         require_once 'DB.php';
346         return DB::connect($dsn);
347     }
348
349     /**
350      * Create core tables on the given database connection.
351      *
352      * @param DB_common $conn
353      */
354     function createCoreTables(DB_common $conn)
355     {
356         $schema = Schema::get($conn);
357         $tableDefs = $this->getCoreSchema();
358         foreach ($tableDefs as $name => $def) {
359             if (defined('DEBUG_INSTALLER')) {
360                 echo " $name ";
361             }
362             $schema->ensureTable($name, $def);
363         }
364         return true;
365     }
366
367     /**
368      * Fetch the core table schema definitions.
369      *
370      * @return array of table names => table def arrays
371      */
372     function getCoreSchema()
373     {
374         $schema = array();
375         include INSTALLDIR . '/db/core.php';
376         return $schema;
377     }
378
379     /**
380      * Return a parseable PHP literal for the given value.
381      * This will include quotes for strings, etc.
382      *
383      * @param mixed $val
384      * @return string
385      */
386     function phpVal($val)
387     {
388         return var_export($val, true);
389     }
390
391     /**
392      * Return an array of parseable PHP literal for the given values.
393      * These will include quotes for strings, etc.
394      *
395      * @param mixed $val
396      * @return array
397      */
398     function phpVals($map)
399     {
400         return array_map(array($this, 'phpVal'), $map);
401     }
402
403     /**
404      * Write a stock configuration file.
405      *
406      * @return boolean success
407      *
408      * @fixme escape variables in output in case we have funny chars, apostrophes etc
409      */
410     function writeConf()
411     {
412         $vals = $this->phpVals(array(
413             'sitename' => $this->sitename,
414             'server' => $this->server,
415             'path' => $this->path,
416             'ssl' => in_array($this->ssl, array('never', 'sometimes', 'always'))
417                      ? $this->ssl
418                      : 'never',
419             'db_database' => $this->db['database'],
420             'db_type' => $this->db['type']
421         ));
422
423         // assemble configuration file in a string
424         $cfg =  "<?php\n".
425                 "if (!defined('GNUSOCIAL')) { exit(1); }\n\n".
426
427                 // site name
428                 "\$config['site']['name'] = {$vals['sitename']};\n\n".
429
430                 // site location
431                 "\$config['site']['server'] = {$vals['server']};\n".
432                 "\$config['site']['path'] = {$vals['path']}; \n\n".
433                 "\$config['site']['ssl'] = {$vals['ssl']}; \n\n".
434
435                 // checks if fancy URLs are enabled
436                 ($this->fancy ? "\$config['site']['fancy'] = true;\n\n":'').
437
438                 // database
439                 "\$config['db']['database'] = {$vals['db_database']};\n\n".
440                 ($this->db['type'] == 'pgsql' ? "\$config['db']['quote_identifiers'] = true;\n\n":'').
441                 "\$config['db']['type'] = {$vals['db_type']};\n\n";
442
443         // Auto memcache support detection
444         $cfg .= '
445 foreach(array("Memcache", "Memcached") as $plugin) :
446     if (class_exists($plugin)) {
447         addPlugin($plugin);
448         break;
449     }
450 endforeach;
451 ';
452
453         // Normalize line endings for Windows servers
454         $cfg = str_replace("\n", PHP_EOL, $cfg);
455
456         // write configuration file out to install directory
457         $res = file_put_contents(INSTALLDIR.'/config.php', $cfg);
458
459         return $res;
460     }
461
462     /**
463      * Write the site profile. We do this after creating the initial user
464      * in case the site profile is set to single user. This gets around the
465      * 'chicken-and-egg' problem of the system requiring a valid user for
466      * single user mode, before the intial user is actually created. Yeah,
467      * we should probably do this in smarter way.
468      *
469      * @return int res number of bytes written
470      */
471     function writeSiteProfile()
472     {
473         $vals = $this->phpVals(array(
474             'site_profile' => $this->siteProfile,
475             'nickname' => $this->adminNick
476         ));
477
478         $cfg =
479         // site profile
480         "\$config['site']['profile'] = {$vals['site_profile']};\n";
481
482         if ($this->siteProfile == "singleuser") {
483             $cfg .= "\$config['singleuser']['nickname'] = {$vals['nickname']};\n\n";
484         } else {
485             $cfg .= "\n";
486         }
487
488         // Normalize line endings for Windows servers
489         $cfg = str_replace("\n", PHP_EOL, $cfg);
490
491         // write configuration file out to install directory
492         $res = file_put_contents(INSTALLDIR.'/config.php', $cfg, FILE_APPEND);
493
494         return $res;
495     }
496
497     /**
498      * Install schema into the database
499      *
500      * @param string    $filename location of database schema file
501      * @param DB_common $conn     connection to database
502      *
503      * @return boolean - indicating success or failure
504      */
505     function runDbScript($filename, DB_common $conn)
506     {
507         $sql = trim(file_get_contents(INSTALLDIR . '/db/' . $filename));
508         $stmts = explode(';', $sql);
509         foreach ($stmts as $stmt) {
510             $stmt = trim($stmt);
511             if (!mb_strlen($stmt)) {
512                 continue;
513             }
514             try {
515                 $res = $conn->simpleQuery($stmt);
516             } catch (Exception $e) {
517                 $error = $e->getMessage();
518                 $this->updateStatus("ERROR ($error) for SQL '$stmt'");
519                 return false;
520             }
521         }
522         return true;
523     }
524
525     /**
526      * Create the initial admin user account.
527      * Side effect: may load portions of StatusNet framework.
528      * Side effect: outputs program info
529      */
530     function registerInitialUser()
531     {
532         require_once INSTALLDIR . '/lib/common.php';
533
534         $data = array('nickname' => $this->adminNick,
535                       'password' => $this->adminPass,
536                       'fullname' => $this->adminNick);
537         if ($this->adminEmail) {
538             $data['email'] = $this->adminEmail;
539         }
540         $user = User::register($data);
541
542         if (empty($user)) {
543             return false;
544         }
545
546         // give initial user carte blanche
547
548         $user->grantRole('owner');
549         $user->grantRole('moderator');
550         $user->grantRole('administrator');
551
552         // Attempt to do a remote subscribe to update@status.net
553         // Will fail if instance is on a private network.
554
555         if ($this->adminUpdates && class_exists('Ostatus_profile')) {
556             try {
557                 $oprofile = Ostatus_profile::ensureProfileURL('http://update.status.net/');
558                 Subscription::start($user->getProfile(), $oprofile->localProfile());
559                 $this->updateStatus("Set up subscription to <a href='http://update.status.net/'>update@status.net</a>.");
560             } catch (Exception $e) {
561                 $this->updateStatus("Could not set up subscription to <a href='http://update.status.net/'>update@status.net</a>.", true);
562             }
563         }
564
565         return true;
566     }
567
568     /**
569      * The beef of the installer!
570      * Create database, config file, and admin user.
571      *
572      * Prerequisites: validation of input data.
573      *
574      * @return boolean success
575      */
576     function doInstall()
577     {
578         $this->updateStatus("Initializing...");
579         ini_set('display_errors', 1);
580         error_reporting(E_ALL);
581         if (!defined('GNUSOCIAL')) {
582             define('GNUSOCIAL', true);
583         }
584         if (!defined('STATUSNET')) {
585             define('STATUSNET', true);
586         }
587         require_once INSTALLDIR . '/lib/framework.php';
588         StatusNet::initDefaults($this->server, $this->path);
589
590         try {
591             $this->db = $this->setupDatabase();
592             if (!$this->db) {
593                 // database connection failed, do not move on to create config file.
594                 return false;
595             }
596         } catch (Exception $e) {
597             // Lower-level DB error!
598             $this->updateStatus("Database error: " . $e->getMessage(), true);
599             return false;
600         }
601
602         // Make sure we can write to the file twice
603         $oldUmask = umask(000); 
604
605         if (!$this->skipConfig) {
606             $this->updateStatus("Writing config file...");
607             $res = $this->writeConf();
608
609             if (!$res) {
610                 $this->updateStatus("Can't write config file.", true);
611                 return false;
612             }
613         }
614
615         if (!empty($this->adminNick)) {
616             // Okay, cross fingers and try to register an initial user
617             if ($this->registerInitialUser()) {
618                 $this->updateStatus(
619                     "An initial user with the administrator role has been created."
620                 );
621             } else {
622                 $this->updateStatus(
623                     "Could not create initial StatusNet user (administrator).",
624                     true
625                 );
626                 return false;
627             }
628         }
629
630         if (!$this->skipConfig) {
631             $this->updateStatus("Setting site profile...");
632             $res = $this->writeSiteProfile();
633
634             if (!$res) {
635                 $this->updateStatus("Can't write to config file.", true);
636                 return false;
637             }
638         }
639
640         // Restore original umask
641         umask($oldUmask);
642         // Set permissions back to something decent
643         chmod(INSTALLDIR.'/config.php', 0644);
644         
645         /*
646             TODO https needs to be considered
647         */
648         $link = "http://".$this->server.'/'.$this->path;
649
650         $this->updateStatus("StatusNet has been installed at $link");
651         $this->updateStatus(
652             "<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>."
653         );
654
655         return true;
656     }
657
658     /**
659      * Output a pre-install-time warning message
660      * @param string $message HTML ok, but should be plaintext-able
661      * @param string $submessage HTML ok, but should be plaintext-able
662      */
663     abstract function warning($message, $submessage='');
664
665     /**
666      * Output an install-time progress message
667      * @param string $message HTML ok, but should be plaintext-able
668      * @param boolean $error true if this should be marked as an error condition
669      */
670     abstract function updateStatus($status, $error=false);
671
672 }