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