]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - lib/installer.php
Merge remote-tracking branch 'upstream/master' into social-master
[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-2014 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;
51     /** Should we skip writing the configuration file? */
52     public $skipConfig = false;
53
54     public static $dbModules = array(
55         'mysql' => array(
56             'name' => 'MariaDB (or MySQL 5.5+)',
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.5.0', '<')) {
100             $this->warning('Require PHP version 5.5.0 or greater.');
101             $pass = false;
102         }
103
104         $reqs = array('gd', 'curl', 'intl', 'json',
105                       'xmlwriter', 'mbstring', 'xml', 'dom', 'simplexml');
106
107         foreach ($reqs as $req) {
108             if (!$this->checkExtension($req)) {
109                 $this->warning(sprintf('Cannot load required extension: <code>%s</code>', $req));
110                 $pass = false;
111             }
112         }
113
114         // Make sure we have at least one database module available
115         $missingExtensions = array();
116         foreach (self::$dbModules as $type => $info) {
117             if (!$this->checkExtension($info['check_module'])) {
118                 $missingExtensions[] = $info['check_module'];
119             }
120         }
121
122         if (count($missingExtensions) == count(self::$dbModules)) {
123             $req = implode(', ', $missingExtensions);
124             $this->warning(sprintf('Cannot find a database extension. You need at least one of %s.', $req));
125             $pass = false;
126         }
127
128         // @fixme this check seems to be insufficient with Windows ACLs
129         if (!is_writable(INSTALLDIR)) {
130             $this->warning(sprintf('Cannot write config file to: <code>%s</code></p>', INSTALLDIR),
131                            sprintf('On your server, try this command: <code>chmod a+w %s</code>', INSTALLDIR));
132             $pass = false;
133         }
134
135         // Check the subdirs used for file uploads
136         $fileSubdirs = array('avatar', 'file');
137         foreach ($fileSubdirs as $fileSubdir) {
138             $fileFullPath = INSTALLDIR."/$fileSubdir";
139             if (!file_exists($fileFullPath)) {
140                 $pass = $pass && mkdir($fileFullPath);
141             } elseif (!is_dir($fileFullPath)) {
142                 $this->warning(sprintf('GNU social expected a directory but found something else on this path: %s', $fileFullPath),
143                                'Either make sure it goes to a directory or remove it and a directory will be created.');
144                 $pass = false;
145             } elseif (!is_writable($fileFullPath)) {
146                 $this->warning(sprintf('Cannot write to %s directory: <code>%s</code>', $fileSubdir, $fileFullPath),
147                                sprintf('On your server, try this command: <code>chmod a+w %s</code>', $fileFullPath));
148                 $pass = false;
149             }
150         }
151
152         return $pass;
153     }
154
155     /**
156      * Checks if a php extension is both installed and loaded
157      *
158      * @param string $name of extension to check
159      *
160      * @return boolean whether extension is installed and loaded
161      */
162     function checkExtension($name)
163     {
164         if (extension_loaded($name)) {
165             return true;
166         } elseif (function_exists('dl') && ini_get('enable_dl') && !ini_get('safe_mode')) {
167             // dl will throw a fatal error if it's disabled or we're in safe mode.
168             // More fun, it may not even exist under some SAPIs in 5.3.0 or later...
169             $soname = $name . '.' . PHP_SHLIB_SUFFIX;
170             if (PHP_SHLIB_SUFFIX == 'dll') {
171                 $soname = "php_" . $soname;
172             }
173             return @dl($soname);
174         } else {
175             return false;
176         }
177     }
178
179     /**
180      * Basic validation on the database paramters
181      * Side effects: error output if not valid
182      *
183      * @return boolean success
184      */
185     function validateDb()
186     {
187         $fail = false;
188
189         if (empty($this->host)) {
190             $this->updateStatus("No hostname specified.", true);
191             $fail = true;
192         }
193
194         if (empty($this->database)) {
195             $this->updateStatus("No database specified.", true);
196             $fail = true;
197         }
198
199         if (empty($this->username)) {
200             $this->updateStatus("No username specified.", true);
201             $fail = true;
202         }
203
204         if (empty($this->sitename)) {
205             $this->updateStatus("No sitename specified.", true);
206             $fail = true;
207         }
208
209         return !$fail;
210     }
211
212     /**
213      * Basic validation on the administrator user paramters
214      * Side effects: error output if not valid
215      *
216      * @return boolean success
217      */
218     function validateAdmin()
219     {
220         $fail = false;
221
222         if (empty($this->adminNick)) {
223             $this->updateStatus("No initial user nickname specified.", true);
224             $fail = true;
225         }
226         if ($this->adminNick && !preg_match('/^[0-9a-z]{1,64}$/', $this->adminNick)) {
227             $this->updateStatus('The user nickname "' . htmlspecialchars($this->adminNick) .
228                          '" is invalid; should be plain letters and numbers no longer than 64 characters.', true);
229             $fail = true;
230         }
231         // @fixme hardcoded list; should use Nickname::isValid()
232         // if/when it's safe to have loaded the infrastructure here
233         $blacklist = array('main', 'panel', 'twitter', 'settings', 'rsd.xml', 'favorited', 'featured', 'favoritedrss', 'featuredrss', 'rss', 'getfile', 'api', 'groups', 'group', 'peopletag', 'tag', 'user', 'message', 'conversation', 'notice', 'attachment', 'search', 'index.php', 'doc', 'opensearch', 'robots.txt', 'xd_receiver.html', 'facebook', 'activity');
234         if (in_array($this->adminNick, $blacklist)) {
235             $this->updateStatus('The user nickname "' . htmlspecialchars($this->adminNick) .
236                          '" is reserved.', true);
237             $fail = true;
238         }
239
240         if (empty($this->adminPass)) {
241             $this->updateStatus("No initial user password specified.", true);
242             $fail = true;
243         }
244
245         return !$fail;
246     }
247
248     /**
249      * Make sure a site profile was selected
250      *
251      * @return type boolean success
252      */
253     function validateSiteProfile()
254     {
255         if (empty($this->siteProfile))  {
256             $this->updateStatus("No site profile selected.", true);
257             return false;
258         }
259
260         return true;
261     }
262
263     /**
264      * Set up the database with the appropriate function for the selected type...
265      * Saves database info into $this->db.
266      *
267      * @fixme escape things in the connection string in case we have a funny pass etc
268      * @return mixed array of database connection params on success, false on failure
269      */
270     function setupDatabase()
271     {
272         if ($this->db) {
273             throw new Exception("Bad order of operations: DB already set up.");
274         }
275         $this->updateStatus("Starting installation...");
276
277         if (empty($this->password)) {
278             $auth = '';
279         } else {
280             $auth = ":$this->password";
281         }
282         $scheme = self::$dbModules[$this->dbtype]['scheme'];
283         $dsn = "{$scheme}://{$this->username}{$auth}@{$this->host}/{$this->database}";
284
285         $this->updateStatus("Checking database...");
286         $conn = $this->connectDatabase($dsn);
287
288         // ensure database encoding is UTF8
289         if ($this->dbtype == 'mysql') {
290             // @fixme utf8m4 support for mysql 5.5?
291             // Force the comms charset to utf8 for sanity
292             // This doesn't currently work. :P
293             //$conn->executes('set names utf8');
294         } else if ($this->dbtype == 'pgsql') {
295             $record = $conn->getRow('SHOW server_encoding');
296             if ($record->server_encoding != 'UTF8') {
297                 $this->updateStatus("GNU social requires UTF8 character encoding. Your database is ". htmlentities($record->server_encoding));
298                 return false;
299             }
300         }
301
302         if (!is_object($conn)) {
303             // No object at all
304             throw new Exception('Fatal error: conn is no object.');
305         } elseif (!$conn instanceof DB_common) {
306             // Is not the right instance
307             throw new Exception('Cannot connect to database: ' . $conn->getMessage());
308         }
309
310         $res = $this->updateStatus("Creating database tables...");
311         if (!$this->createCoreTables($conn)) {
312             $this->updateStatus("Error creating tables.", true);
313             return false;
314         }
315
316         foreach (array('sms_carrier' => 'SMS carrier',
317                     'notice_source' => 'notice source',
318                     'foreign_services' => 'foreign service')
319               as $scr => $name) {
320             $this->updateStatus(sprintf("Adding %s data to database...", $name));
321             $res = $this->runDbScript($scr.'.sql', $conn);
322             if ($res === false) {
323                 $this->updateStatus(sprintf("Can't run %s script.", $name), true);
324                 return false;
325             }
326         }
327
328         $db = array('type' => $this->dbtype, 'database' => $dsn);
329         return $db;
330     }
331
332     /**
333      * Open a connection to the database.
334      *
335      * @param <type> $dsn
336      * @return <type>
337      */
338     function connectDatabase($dsn)
339     {
340         global $_DB;
341         return $_DB->connect($dsn);
342     }
343
344     /**
345      * Create core tables on the given database connection.
346      *
347      * @param DB_common $conn
348      */
349     function createCoreTables(DB_common $conn)
350     {
351         $schema = Schema::get($conn);
352         $tableDefs = $this->getCoreSchema();
353         foreach ($tableDefs as $name => $def) {
354             if (defined('DEBUG_INSTALLER')) {
355                 echo " $name ";
356             }
357             $schema->ensureTable($name, $def);
358         }
359         return true;
360     }
361
362     /**
363      * Fetch the core table schema definitions.
364      *
365      * @return array of table names => table def arrays
366      */
367     function getCoreSchema()
368     {
369         $schema = array();
370         include INSTALLDIR . '/db/core.php';
371         return $schema;
372     }
373
374     /**
375      * Return a parseable PHP literal for the given value.
376      * This will include quotes for strings, etc.
377      *
378      * @param mixed $val
379      * @return string
380      */
381     function phpVal($val)
382     {
383         return var_export($val, true);
384     }
385
386     /**
387      * Return an array of parseable PHP literal for the given values.
388      * These will include quotes for strings, etc.
389      *
390      * @param mixed $val
391      * @return array
392      */
393     function phpVals($map)
394     {
395         return array_map(array($this, 'phpVal'), $map);
396     }
397
398     /**
399      * Write a stock configuration file.
400      *
401      * @return boolean success
402      *
403      * @fixme escape variables in output in case we have funny chars, apostrophes etc
404      */
405     function writeConf()
406     {
407         $vals = $this->phpVals(array(
408             'sitename' => $this->sitename,
409             'server' => $this->server,
410             'path' => $this->path,
411             'ssl' => in_array($this->ssl, array('never', 'sometimes', 'always'))
412                      ? $this->ssl
413                      : 'never',
414             'db_database' => $this->db['database'],
415             'db_type' => $this->db['type']
416         ));
417
418         // assemble configuration file in a string
419         $cfg =  "<?php\n".
420                 "if (!defined('GNUSOCIAL')) { exit(1); }\n\n".
421
422                 // site name
423                 "\$config['site']['name'] = {$vals['sitename']};\n\n".
424
425                 // site location
426                 "\$config['site']['server'] = {$vals['server']};\n".
427                 "\$config['site']['path'] = {$vals['path']}; \n\n".
428                 "\$config['site']['ssl'] = {$vals['ssl']}; \n\n".
429
430                 // checks if fancy URLs are enabled
431                 ($this->fancy ? "\$config['site']['fancy'] = true;\n\n":'').
432
433                 // database
434                 "\$config['db']['database'] = {$vals['db_database']};\n\n".
435                 ($this->db['type'] == 'pgsql' ? "\$config['db']['quote_identifiers'] = true;\n\n":'').
436                 "\$config['db']['type'] = {$vals['db_type']};\n\n".
437
438                 "// Uncomment below for better performance. Just remember you must run\n".
439                 "// php scripts/checkschema.php whenever your enabled plugins change!\n".
440                 "//\$config['db']['schemacheck'] = 'script';\n\n";
441
442         // Normalize line endings for Windows servers
443         $cfg = str_replace("\n", PHP_EOL, $cfg);
444
445         // write configuration file out to install directory
446         $res = file_put_contents(INSTALLDIR.'/config.php', $cfg);
447
448         return $res;
449     }
450
451     /**
452      * Write the site profile. We do this after creating the initial user
453      * in case the site profile is set to single user. This gets around the
454      * 'chicken-and-egg' problem of the system requiring a valid user for
455      * single user mode, before the intial user is actually created. Yeah,
456      * we should probably do this in smarter way.
457      *
458      * @return int res number of bytes written
459      */
460     function writeSiteProfile()
461     {
462         $vals = $this->phpVals(array(
463             'site_profile' => $this->siteProfile,
464             'nickname' => $this->adminNick
465         ));
466
467         $cfg =
468         // site profile
469         "\$config['site']['profile'] = {$vals['site_profile']};\n";
470
471         if ($this->siteProfile == "singleuser") {
472             $cfg .= "\$config['singleuser']['nickname'] = {$vals['nickname']};\n\n";
473         } else {
474             $cfg .= "\n";
475         }
476
477         // Normalize line endings for Windows servers
478         $cfg = str_replace("\n", PHP_EOL, $cfg);
479
480         // write configuration file out to install directory
481         $res = file_put_contents(INSTALLDIR.'/config.php', $cfg, FILE_APPEND);
482
483         return $res;
484     }
485
486     /**
487      * Install schema into the database
488      *
489      * @param string    $filename location of database schema file
490      * @param DB_common $conn     connection to database
491      *
492      * @return boolean - indicating success or failure
493      */
494     function runDbScript($filename, DB_common $conn)
495     {
496         $sql = trim(file_get_contents(INSTALLDIR . '/db/' . $filename));
497         $stmts = explode(';', $sql);
498         foreach ($stmts as $stmt) {
499             $stmt = trim($stmt);
500             if (!mb_strlen($stmt)) {
501                 continue;
502             }
503             try {
504                 $res = $conn->simpleQuery($stmt);
505             } catch (Exception $e) {
506                 $error = $e->getMessage();
507                 $this->updateStatus("ERROR ($error) for SQL '$stmt'");
508                 return false;
509             }
510         }
511         return true;
512     }
513
514     /**
515      * Create the initial admin user account.
516      * Side effect: may load portions of GNU social framework.
517      * Side effect: outputs program info
518      */
519     function registerInitialUser()
520     {
521         require_once INSTALLDIR . '/lib/common.php';
522
523         $data = array('nickname' => $this->adminNick,
524                       'password' => $this->adminPass,
525                       'fullname' => $this->adminNick);
526         if ($this->adminEmail) {
527             $data['email'] = $this->adminEmail;
528         }
529         try {
530             $user = User::register($data);
531         } catch (Exception $e) {
532             return false;
533         }
534
535         // give initial user carte blanche
536
537         $user->grantRole('owner');
538         $user->grantRole('moderator');
539         $user->grantRole('administrator');
540
541         return true;
542     }
543
544     /**
545      * The beef of the installer!
546      * Create database, config file, and admin user.
547      *
548      * Prerequisites: validation of input data.
549      *
550      * @return boolean success
551      */
552     function doInstall()
553     {
554         global $config;
555
556         $this->updateStatus("Initializing...");
557         ini_set('display_errors', 1);
558         error_reporting(E_ALL & ~E_STRICT & ~E_NOTICE);
559         if (!defined('GNUSOCIAL')) {
560             define('GNUSOCIAL', true);
561         }
562         if (!defined('STATUSNET')) {
563             define('STATUSNET', true);
564         }
565
566         require_once INSTALLDIR . '/lib/framework.php';
567         GNUsocial::initDefaults($this->server, $this->path);
568
569         if ($this->siteProfile == "singleuser") {
570             // Until we use ['site']['profile']==='singleuser' everywhere
571             $config['singleuser']['enabled'] = true;
572         }
573
574         try {
575             $this->db = $this->setupDatabase();
576             if (!$this->db) {
577                 // database connection failed, do not move on to create config file.
578                 return false;
579             }
580         } catch (Exception $e) {
581             // Lower-level DB error!
582             $this->updateStatus("Database error: " . $e->getMessage(), true);
583             return false;
584         }
585
586         // Make sure we can write to the file twice
587         $oldUmask = umask(000); 
588
589         if (!$this->skipConfig) {
590             $this->updateStatus("Writing config file...");
591             $res = $this->writeConf();
592
593             if (!$res) {
594                 $this->updateStatus("Can't write config file.", true);
595                 return false;
596             }
597         }
598
599         if (!empty($this->adminNick)) {
600             // Okay, cross fingers and try to register an initial user
601             if ($this->registerInitialUser()) {
602                 $this->updateStatus(
603                     "An initial user with the administrator role has been created."
604                 );
605             } else {
606                 $this->updateStatus(
607                     "Could not create initial user account.",
608                     true
609                 );
610                 return false;
611             }
612         }
613
614         if (!$this->skipConfig) {
615             $this->updateStatus("Setting site profile...");
616             $res = $this->writeSiteProfile();
617
618             if (!$res) {
619                 $this->updateStatus("Can't write to config file.", true);
620                 return false;
621             }
622         }
623
624         // Restore original umask
625         umask($oldUmask);
626         // Set permissions back to something decent
627         chmod(INSTALLDIR.'/config.php', 0644);
628         
629         $scheme = $this->ssl === 'always' ? 'https' : 'http';
630         $link = "{$scheme}://{$this->server}/{$this->path}";
631
632         $this->updateStatus("GNU social has been installed at $link");
633         $this->updateStatus(
634             '<strong>DONE!</strong> You can visit your <a href="'.htmlspecialchars($link).'">new GNU social site</a> (log in as "'.htmlspecialchars($this->adminNick).'"). If this is your first GNU social install, make your experience the best possible by visiting our resource site to join the <a href="https://gnu.io/social/resources/">mailing list or IRC</a>. <a href="'.htmlspecialchars($link).'/doc/faq">FAQ is found here</a>.'
635         );
636
637         return true;
638     }
639
640     /**
641      * Output a pre-install-time warning message
642      * @param string $message HTML ok, but should be plaintext-able
643      * @param string $submessage HTML ok, but should be plaintext-able
644      */
645     abstract function warning($message, $submessage='');
646
647     /**
648      * Output an install-time progress message
649      * @param string $message HTML ok, but should be plaintext-able
650      * @param boolean $error true if this should be marked as an error condition
651      */
652     abstract function updateStatus($status, $error=false);
653
654 }