]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - lib/statusnet.php
Merge branch '1.0.x' of gitorious.org:statusnet/mainline into 1.0.x
[quix0rs-gnu-social.git] / lib / statusnet.php
1 <?php
2 /**
3  * StatusNet - the distributed open-source microblogging tool
4  * Copyright (C) 2009-2010 StatusNet, Inc.
5  *
6  * This program is free software: you can redistribute it and/or modify
7  * it under the terms of the GNU Affero General Public License as published by
8  * the Free Software Foundation, either version 3 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU Affero General Public License for more details.
15  *
16  * You should have received a copy of the GNU Affero General Public License
17  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
18  *
19  */
20
21 if (!defined('STATUSNET') && !defined('LACONICA')) {
22     exit(1);
23 }
24
25 global $config, $_server, $_path;
26
27 /**
28  * Global configuration setup and management.
29  */
30 class StatusNet
31 {
32     protected static $have_config;
33     protected static $is_api;
34     protected static $is_ajax;
35     protected static $plugins = array();
36
37     /**
38      * Configure and instantiate a plugin into the current configuration.
39      * Class definitions will be loaded from standard paths if necessary.
40      * Note that initialization events won't be fired until later.
41      *
42      * @param string $name class name & plugin file/subdir name
43      * @param array $attrs key/value pairs of public attributes to set on plugin instance
44      *
45      * @throws ServerException if plugin can't be found
46      */
47     public static function addPlugin($name, $attrs = null)
48     {
49         $name = ucfirst($name);
50         $pluginclass = "{$name}Plugin";
51
52         if (!class_exists($pluginclass)) {
53
54             $files = array("local/plugins/{$pluginclass}.php",
55                            "local/plugins/{$name}/{$pluginclass}.php",
56                            "local/{$pluginclass}.php",
57                            "local/{$name}/{$pluginclass}.php",
58                            "plugins/{$pluginclass}.php",
59                            "plugins/{$name}/{$pluginclass}.php");
60
61             foreach ($files as $file) {
62                 $fullpath = INSTALLDIR.'/'.$file;
63                 if (@file_exists($fullpath)) {
64                     include_once($fullpath);
65                     break;
66                 }
67             }
68             if (!class_exists($pluginclass)) {
69                 throw new ServerException("Plugin $name not found.", 500);
70             }
71         }
72
73         $inst = new $pluginclass();
74         if (!empty($attrs)) {
75             foreach ($attrs as $aname => $avalue) {
76                 $inst->$aname = $avalue;
77             }
78         }
79
80         // Record activated plugins for later display/config dump
81         self::$plugins[] = array($name, $attrs);
82
83         return true;
84     }
85
86     /**
87      * Get a list of activated plugins in this process.
88      * @return array of (string $name, array $args) pairs
89      */
90     public static function getActivePlugins()
91     {
92         return self::$plugins;
93     }
94
95     /**
96      * Initialize, or re-initialize, StatusNet global configuration
97      * and plugins.
98      *
99      * If switching site configurations during script execution, be
100      * careful when working with leftover objects -- global settings
101      * affect many things and they may not behave as you expected.
102      *
103      * @param $server optional web server hostname for picking config
104      * @param $path optional URL path for picking config
105      * @param $conffile optional configuration file path
106      *
107      * @throws NoConfigException if config file can't be found
108      */
109     public static function init($server=null, $path=null, $conffile=null)
110     {
111         StatusNet::initDefaults($server, $path);
112         StatusNet::loadConfigFile($conffile);
113
114         // Load settings from database; note we need autoload for this
115         Config::loadSettings();
116
117         self::initPlugins();
118     }
119
120     /**
121      * Get identifier of the currently active site configuration
122      * @return string
123      */
124     public static function currentSite()
125     {
126         return common_config('site', 'nickname');
127     }
128
129     /**
130      * Change site configuration to site specified by nickname,
131      * if set up via Status_network. If not, sites other than
132      * the current will fail horribly.
133      *
134      * May throw exception or trigger a fatal error if the given
135      * site is missing or configured incorrectly.
136      *
137      * @param string $nickname
138      */
139     public static function switchSite($nickname)
140     {
141         if ($nickname == StatusNet::currentSite()) {
142             return true;
143         }
144
145         $sn = Status_network::staticGet('nickname', $nickname);
146         if (empty($sn)) {
147             return false;
148             throw new Exception("No such site nickname '$nickname'");
149         }
150
151         $server = $sn->getServerName();
152         StatusNet::init($server);
153     }
154
155     /**
156      * Pull all local sites from status_network table.
157      *
158      * Behavior undefined if site is not configured via Status_network.
159      *
160      * @return array of nicknames
161      */
162     public static function findAllSites()
163     {
164         $sites = array();
165         $sn = new Status_network();
166         $sn->find();
167         while ($sn->fetch()) {
168             $sites[] = $sn->nickname;
169         }
170         return $sites;
171     }
172
173     /**
174      * Fire initialization events for all instantiated plugins.
175      */
176     protected static function initPlugins()
177     {
178         // Load default plugins
179         foreach (common_config('plugins', 'default') as $name => $params) {
180             $key = 'disable-' . $name;
181             if (common_config('plugins', $key)) {
182                 continue;
183             }
184
185             if (is_null($params)) {
186                 addPlugin($name);
187             } else if (is_array($params)) {
188                 if (count($params) == 0) {
189                     addPlugin($name);
190                 } else {
191                     $keys = array_keys($params);
192                     if (is_string($keys[0])) {
193                         addPlugin($name, $params);
194                     } else {
195                         foreach ($params as $paramset) {
196                             addPlugin($name, $paramset);
197                         }
198                     }
199                 }
200             }
201         }
202
203         // XXX: if plugins should check the schema at runtime, do that here.
204         if (common_config('db', 'schemacheck') == 'runtime') {
205             Event::handle('CheckSchema');
206         }
207
208         // Give plugins a chance to initialize in a fully-prepared environment
209         Event::handle('InitializePlugin');
210     }
211
212     /**
213      * Quick-check if configuration has been established.
214      * Useful for functions which may get used partway through
215      * initialization to back off from fancier things.
216      *
217      * @return bool
218      */
219     public function haveConfig()
220     {
221         return self::$have_config;
222     }
223
224     public function isApi()
225     {
226         return self::$is_api;
227     }
228
229     public function setApi($mode)
230     {
231         self::$is_api = $mode;
232     }
233
234     public function isAjax()
235     {
236         return self::$is_ajax;
237     }
238
239     public function setAjax($mode)
240     {
241         self::$is_ajax = $mode;
242     }
243
244     /**
245      * Build default configuration array
246      * @return array
247      */
248     protected static function defaultConfig()
249     {
250         global $_server, $_path;
251         require(INSTALLDIR.'/lib/default.php');
252         return $default;
253     }
254
255     /**
256      * Establish default configuration based on given or default server and path
257      * Sets global $_server, $_path, and $config
258      */
259     public static function initDefaults($server, $path)
260     {
261         global $_server, $_path, $config;
262
263         Event::clearHandlers();
264         self::$plugins = array();
265
266         // try to figure out where we are. $server and $path
267         // can be set by including module, else we guess based
268         // on HTTP info.
269
270         if (isset($server)) {
271             $_server = $server;
272         } else {
273             $_server = array_key_exists('SERVER_NAME', $_SERVER) ?
274               strtolower($_SERVER['SERVER_NAME']) :
275             null;
276         }
277
278         if (isset($path)) {
279             $_path = $path;
280         } else {
281             $_path = (array_key_exists('SERVER_NAME', $_SERVER) && array_key_exists('SCRIPT_NAME', $_SERVER)) ?
282               self::_sn_to_path($_SERVER['SCRIPT_NAME']) :
283             null;
284         }
285
286         // Set config values initially to default values
287         $default = self::defaultConfig();
288         $config = $default;
289
290         // default configuration, overwritten in config.php
291         // Keep DB_DataObject's db config synced to ours...
292
293         $config['db'] = &PEAR::getStaticProperty('DB_DataObject','options');
294
295         $config['db'] = $default['db'];
296
297         // Backward compatibility
298
299         $config['site']['design'] =& $config['design'];
300
301         if (function_exists('date_default_timezone_set')) {
302             /* Work internally in UTC */
303             date_default_timezone_set('UTC');
304         }
305     }
306
307     protected function _sn_to_path($sn)
308     {
309         $past_root = substr($sn, 1);
310         $last_slash = strrpos($past_root, '/');
311         if ($last_slash > 0) {
312             $p = substr($past_root, 0, $last_slash);
313         } else {
314             $p = '';
315         }
316         return $p;
317     }
318
319     /**
320      * Load the default or specified configuration file.
321      * Modifies global $config and may establish plugins.
322      *
323      * @throws NoConfigException
324      */
325     protected function loadConfigFile($conffile=null)
326     {
327         global $_server, $_path, $config;
328
329         // From most general to most specific:
330         // server-wide, then vhost-wide, then for a path,
331         // finally for a dir (usually only need one of the last two).
332
333         if (isset($conffile)) {
334             $config_files = array($conffile);
335         } else {
336             $config_files = array('/etc/statusnet/statusnet.php',
337                                   '/etc/statusnet/laconica.php',
338                                   '/etc/laconica/laconica.php',
339                                   '/etc/statusnet/'.$_server.'.php',
340                                   '/etc/laconica/'.$_server.'.php');
341
342             if (strlen($_path) > 0) {
343                 $config_files[] = '/etc/statusnet/'.$_server.'_'.$_path.'.php';
344                 $config_files[] = '/etc/laconica/'.$_server.'_'.$_path.'.php';
345             }
346
347             $config_files[] = INSTALLDIR.'/config.php';
348         }
349
350         self::$have_config = false;
351
352         foreach ($config_files as $_config_file) {
353             if (@file_exists($_config_file)) {
354                 // Ignore 0-byte config files
355                 if (filesize($_config_file) > 0) {
356                     include($_config_file);
357                     self::$have_config = true;
358                 }
359             }
360         }
361
362         if (!self::$have_config) {
363             throw new NoConfigException("No configuration file found.",
364                                         $config_files);
365         }
366
367         // Fixup for statusnet.ini
368         $_db_name = substr($config['db']['database'], strrpos($config['db']['database'], '/') + 1);
369
370         if ($_db_name != 'statusnet' && !array_key_exists('ini_'.$_db_name, $config['db'])) {
371             $config['db']['ini_'.$_db_name] = INSTALLDIR.'/classes/statusnet.ini';
372         }
373
374         // Backwards compatibility
375         if (array_key_exists('memcached', $config)) {
376             if ($config['memcached']['enabled']) {
377                 addPlugin('Memcache', array('servers' => $config['memcached']['server']));
378             }
379
380             if (!empty($config['memcached']['base'])) {
381                 $config['cache']['base'] = $config['memcached']['base'];
382             }
383         }
384         if (array_key_exists('xmpp', $config)) {
385             if ($config['xmpp']['enabled']) {
386                 addPlugin('xmpp', array(
387                     'server' => $config['xmpp']['server'],
388                     'port' => $config['xmpp']['port'],
389                     'user' => $config['xmpp']['user'],
390                     'resource' => $config['xmpp']['resource'],
391                     'encryption' => $config['xmpp']['encryption'],
392                     'password' => $config['xmpp']['password'],
393                     'host' => $config['xmpp']['host'],
394                     'debug' => $config['xmpp']['debug'],
395                     'public' => $config['xmpp']['public']
396                 ));
397             }
398         }
399     }
400
401     /**
402      * Are we running from the web with HTTPS?
403      *
404      * @return boolean true if we're running with HTTPS; else false
405      */
406
407     static function isHTTPS()
408     {
409         // There are some exceptions to this; add them here!
410         if(empty($_SERVER['HTTPS'])) {
411             return false;
412         } else {
413             return $_SERVER['HTTPS'] !== 'off';
414         }
415     }
416 }
417
418 class NoConfigException extends Exception
419 {
420     public $configFiles;
421
422     function __construct($msg, $configFiles) {
423         parent::__construct($msg);
424         $this->configFiles = $configFiles;
425     }
426 }