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