]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - lib/statusnet.php
Merge branch '0.9.x' 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
35     /**
36      * Configure and instantiate a plugin into the current configuration.
37      * Class definitions will be loaded from standard paths if necessary.
38      * Note that initialization events won't be fired until later.
39      *
40      * @param string $name class name & plugin file/subdir name
41      * @param array $attrs key/value pairs of public attributes to set on plugin instance
42      *
43      * @throws ServerException if plugin can't be found
44      */
45     public static function addPlugin($name, $attrs = null)
46     {
47         $name = ucfirst($name);
48         $pluginclass = "{$name}Plugin";
49
50         if (!class_exists($pluginclass)) {
51
52             $files = array("local/plugins/{$pluginclass}.php",
53                            "local/plugins/{$name}/{$pluginclass}.php",
54                            "local/{$pluginclass}.php",
55                            "local/{$name}/{$pluginclass}.php",
56                            "plugins/{$pluginclass}.php",
57                            "plugins/{$name}/{$pluginclass}.php");
58
59             foreach ($files as $file) {
60                 $fullpath = INSTALLDIR.'/'.$file;
61                 if (@file_exists($fullpath)) {
62                     include_once($fullpath);
63                     break;
64                 }
65             }
66             if (!class_exists($pluginclass)) {
67                 throw new ServerException("Plugin $name not found.", 500);
68             }
69         }
70
71         $inst = new $pluginclass();
72         if (!empty($attrs)) {
73             foreach ($attrs as $aname => $avalue) {
74                 $inst->$aname = $avalue;
75             }
76         }
77         return true;
78     }
79
80     /**
81      * Initialize, or re-initialize, StatusNet global configuration
82      * and plugins.
83      *
84      * If switching site configurations during script execution, be
85      * careful when working with leftover objects -- global settings
86      * affect many things and they may not behave as you expected.
87      *
88      * @param $server optional web server hostname for picking config
89      * @param $path optional URL path for picking config
90      * @param $conffile optional configuration file path
91      *
92      * @throws NoConfigException if config file can't be found
93      */
94     public static function init($server=null, $path=null, $conffile=null)
95     {
96         StatusNet::initDefaults($server, $path);
97         StatusNet::loadConfigFile($conffile);
98
99         // Load settings from database; note we need autoload for this
100         Config::loadSettings();
101
102         self::initPlugins();
103     }
104
105     /**
106      * Get identifier of the currently active site configuration
107      * @return string
108      */
109     public static function currentSite()
110     {
111         return common_config('site', 'nickname');
112     }
113
114     /**
115      * Change site configuration to site specified by nickname,
116      * if set up via Status_network. If not, sites other than
117      * the current will fail horribly.
118      *
119      * May throw exception or trigger a fatal error if the given
120      * site is missing or configured incorrectly.
121      *
122      * @param string $nickname
123      */
124     public static function switchSite($nickname)
125     {
126         if ($nickname == StatusNet::currentSite()) {
127             return true;
128         }
129
130         $sn = Status_network::staticGet($nickname);
131         if (empty($sn)) {
132             return false;
133             throw new Exception("No such site nickname '$nickname'");
134         }
135
136         $server = $sn->getServerName();
137         StatusNet::init($server);
138     }
139
140     /**
141      * Pull all local sites from status_network table.
142      *
143      * Behavior undefined if site is not configured via Status_network.
144      *
145      * @return array of nicknames
146      */
147     public static function findAllSites()
148     {
149         $sites = array();
150         $sn = new Status_network();
151         $sn->find();
152         while ($sn->fetch()) {
153             $sites[] = $sn->nickname;
154         }
155         return $sites;
156     }
157
158
159     /**
160      * Fire initialization events for all instantiated plugins.
161      */
162     protected static function initPlugins()
163     {
164         // Load default plugins
165         foreach (common_config('plugins', 'default') as $name => $params) {
166             if (is_null($params)) {
167                 addPlugin($name);
168             } else if (is_array($params)) {
169                 if (count($params) == 0) {
170                     addPlugin($name);
171                 } else {
172                     $keys = array_keys($params);
173                     if (is_string($keys[0])) {
174                         addPlugin($name, $params);
175                     } else {
176                         foreach ($params as $paramset) {
177                             addPlugin($name, $paramset);
178                         }
179                     }
180                 }
181             }
182         }
183
184         // XXX: if plugins should check the schema at runtime, do that here.
185         if (common_config('db', 'schemacheck') == 'runtime') {
186             Event::handle('CheckSchema');
187         }
188
189         // Give plugins a chance to initialize in a fully-prepared environment
190         Event::handle('InitializePlugin');
191     }
192
193     /**
194      * Quick-check if configuration has been established.
195      * Useful for functions which may get used partway through
196      * initialization to back off from fancier things.
197      *
198      * @return bool
199      */
200     public function haveConfig()
201     {
202         return self::$have_config;
203     }
204
205     public function isApi()
206     {
207         return self::$is_api;
208     }
209     
210     public function setApi($mode)
211     {
212         self::$is_api = $mode;
213     }
214
215     /**
216      * Build default configuration array
217      * @return array
218      */
219     protected static function defaultConfig()
220     {
221         global $_server, $_path;
222         require(INSTALLDIR.'/lib/default.php');
223         return $default;
224     }
225
226     /**
227      * Establish default configuration based on given or default server and path
228      * Sets global $_server, $_path, and $config
229      */
230     protected static function initDefaults($server, $path)
231     {
232         global $_server, $_path, $config;
233
234         Event::clearHandlers();
235
236         // try to figure out where we are. $server and $path
237         // can be set by including module, else we guess based
238         // on HTTP info.
239
240         if (isset($server)) {
241             $_server = $server;
242         } else {
243             $_server = array_key_exists('SERVER_NAME', $_SERVER) ?
244               strtolower($_SERVER['SERVER_NAME']) :
245             null;
246         }
247
248         if (isset($path)) {
249             $_path = $path;
250         } else {
251             $_path = (array_key_exists('SERVER_NAME', $_SERVER) && array_key_exists('SCRIPT_NAME', $_SERVER)) ?
252               self::_sn_to_path($_SERVER['SCRIPT_NAME']) :
253             null;
254         }
255
256         // Set config values initially to default values
257         $default = self::defaultConfig();
258         $config = $default;
259
260         // default configuration, overwritten in config.php
261         // Keep DB_DataObject's db config synced to ours...
262
263         $config['db'] = &PEAR::getStaticProperty('DB_DataObject','options');
264
265         $config['db'] = $default['db'];
266
267         // Backward compatibility
268
269         $config['site']['design'] =& $config['design'];
270
271         if (function_exists('date_default_timezone_set')) {
272             /* Work internally in UTC */
273             date_default_timezone_set('UTC');
274         }
275     }
276
277     protected function _sn_to_path($sn)
278     {
279         $past_root = substr($sn, 1);
280         $last_slash = strrpos($past_root, '/');
281         if ($last_slash > 0) {
282             $p = substr($past_root, 0, $last_slash);
283         } else {
284             $p = '';
285         }
286         return $p;
287     }
288
289     /**
290      * Load the default or specified configuration file.
291      * Modifies global $config and may establish plugins.
292      *
293      * @throws NoConfigException
294      */
295     protected function loadConfigFile($conffile=null)
296     {
297         global $_server, $_path, $config;
298
299         // From most general to most specific:
300         // server-wide, then vhost-wide, then for a path,
301         // finally for a dir (usually only need one of the last two).
302
303         if (isset($conffile)) {
304             $config_files = array($conffile);
305         } else {
306             $config_files = array('/etc/statusnet/statusnet.php',
307                                   '/etc/statusnet/laconica.php',
308                                   '/etc/laconica/laconica.php',
309                                   '/etc/statusnet/'.$_server.'.php',
310                                   '/etc/laconica/'.$_server.'.php');
311
312             if (strlen($_path) > 0) {
313                 $config_files[] = '/etc/statusnet/'.$_server.'_'.$_path.'.php';
314                 $config_files[] = '/etc/laconica/'.$_server.'_'.$_path.'.php';
315             }
316
317             $config_files[] = INSTALLDIR.'/config.php';
318         }
319
320         self::$have_config = false;
321
322         foreach ($config_files as $_config_file) {
323             if (@file_exists($_config_file)) {
324                 include($_config_file);
325                 self::$have_config = true;
326             }
327         }
328
329         if (!self::$have_config) {
330             throw new NoConfigException("No configuration file found.",
331                                         $config_files);
332         }
333
334         // Fixup for statusnet.ini
335         $_db_name = substr($config['db']['database'], strrpos($config['db']['database'], '/') + 1);
336
337         if ($_db_name != 'statusnet' && !array_key_exists('ini_'.$_db_name, $config['db'])) {
338             $config['db']['ini_'.$_db_name] = INSTALLDIR.'/classes/statusnet.ini';
339         }
340
341         // Backwards compatibility
342         if (array_key_exists('memcached', $config)) {
343             if ($config['memcached']['enabled']) {
344                 if(class_exists('Memcached')) {
345                     addPlugin('Memcached', array('servers' => $config['memcached']['server']));
346                 } else {
347                     addPlugin('Memcache', array('servers' => $config['memcached']['server']));
348                 }
349             }
350
351             if (!empty($config['memcached']['base'])) {
352                 $config['cache']['base'] = $config['memcached']['base'];
353             }
354         }
355         if (array_key_exists('xmpp', $config)) {
356             if ($config['xmpp']['enabled']) {
357                 addPlugin('xmpp', array(
358                     'server' => $config['xmpp']['server'],
359                     'port' => $config['xmpp']['port'],
360                     'user' => $config['xmpp']['user'],
361                     'resource' => $config['xmpp']['resource'],
362                     'encryption' => $config['xmpp']['encryption'],
363                     'password' => $config['xmpp']['password'],
364                     'host' => $config['xmpp']['host'],
365                     'debug' => $config['xmpp']['debug'],
366                     'public' => $config['xmpp']['public']
367                 ));
368             }
369         }
370     }
371 }
372
373 class NoConfigException extends Exception
374 {
375     public $configFiles;
376
377     function __construct($msg, $configFiles) {
378         parent::__construct($msg);
379         $this->configFiles = $configFiles;
380     }
381 }