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