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