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