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