]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - lib/statusnet.php
Autoloaded library files do not need explicit require_once
[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, array $attrs=array())
48     {
49         $name = ucfirst($name);
50
51         if (isset(self::$plugins[$name])) {
52             // We have already loaded this plugin. Don't try to
53             // do it again with (possibly) different values.
54             // Försten till kvarn får mala.
55             return true;
56         }
57
58         $pluginclass = "{$name}Plugin";
59
60         if (!class_exists($pluginclass)) {
61
62             $files = array("local/plugins/{$pluginclass}.php",
63                            "local/plugins/{$name}/{$pluginclass}.php",
64                            "local/{$pluginclass}.php",
65                            "local/{$name}/{$pluginclass}.php",
66                            "plugins/{$pluginclass}.php",
67                            "plugins/{$name}/{$pluginclass}.php");
68
69             foreach ($files as $file) {
70                 $fullpath = INSTALLDIR.'/'.$file;
71                 if (@file_exists($fullpath)) {
72                     include_once($fullpath);
73                     break;
74                 }
75             }
76             if (!class_exists($pluginclass)) {
77                 throw new ServerException("Plugin $name not found.", 500);
78             }
79         }
80
81         // Doesn't this $inst risk being garbage collected or something?
82         // TODO: put into a static array that makes sure $inst isn't lost.
83         $inst = new $pluginclass();
84         foreach ($attrs as $aname => $avalue) {
85             $inst->$aname = $avalue;
86         }
87
88         // Record activated plugins for later display/config dump
89         self::$plugins[$name] = $attrs;
90
91         return true;
92     }
93
94     /**
95      * Get a list of activated plugins in this process.
96      * @return array of (string $name, array $args) pairs
97      */
98     public static function getActivePlugins()
99     {
100         return self::$plugins;
101     }
102
103     /**
104      * Initialize, or re-initialize, StatusNet global configuration
105      * and plugins.
106      *
107      * If switching site configurations during script execution, be
108      * careful when working with leftover objects -- global settings
109      * affect many things and they may not behave as you expected.
110      *
111      * @param $server optional web server hostname for picking config
112      * @param $path optional URL path for picking config
113      * @param $conffile optional configuration file path
114      *
115      * @throws NoConfigException if config file can't be found
116      */
117     public static function init($server=null, $path=null, $conffile=null)
118     {
119         Router::clear();
120
121         self::initDefaults($server, $path);
122         self::loadConfigFile($conffile);
123
124         $sprofile = common_config('site', 'profile');
125         if (!empty($sprofile)) {
126             self::loadSiteProfile($sprofile);
127         }
128         // Load settings from database; note we need autoload for this
129         Config::loadSettings();
130
131         self::initPlugins();
132     }
133
134     /**
135      * Get identifier of the currently active site configuration
136      * @return string
137      */
138     public static function currentSite()
139     {
140         return common_config('site', 'nickname');
141     }
142
143     /**
144      * Change site configuration to site specified by nickname,
145      * if set up via Status_network. If not, sites other than
146      * the current will fail horribly.
147      *
148      * May throw exception or trigger a fatal error if the given
149      * site is missing or configured incorrectly.
150      *
151      * @param string $nickname
152      */
153     public static function switchSite($nickname)
154     {
155         if ($nickname == StatusNet::currentSite()) {
156             return true;
157         }
158
159         $sn = Status_network::getKV('nickname', $nickname);
160         if (empty($sn)) {
161             return false;
162             throw new Exception("No such site nickname '$nickname'");
163         }
164
165         $server = $sn->getServerName();
166         StatusNet::init($server);
167     }
168
169     /**
170      * Pull all local sites from status_network table.
171      *
172      * Behavior undefined if site is not configured via Status_network.
173      *
174      * @return array of nicknames
175      */
176     public static function findAllSites()
177     {
178         $sites = array();
179         $sn = new Status_network();
180         $sn->find();
181         while ($sn->fetch()) {
182             $sites[] = $sn->nickname;
183         }
184         return $sites;
185     }
186
187     /**
188      * Fire initialization events for all instantiated plugins.
189      */
190     protected static function initPlugins()
191     {
192         // User config may have already added some of these plugins, with
193         // maybe configured parameters. The self::addPlugin function will
194         // ignore the new call if it has already been instantiated.
195
196         // Load core plugins
197         foreach (common_config('plugins', 'core') as $name => $params) {
198             call_user_func('self::addPlugin', $name, $params);
199         }
200
201         // Load default plugins
202         foreach (common_config('plugins', 'default') as $name => $params) {
203             $key = 'disable-' . $name;
204             if (common_config('plugins', $key)) {
205                 continue;
206             }
207
208             // TODO: We should be able to avoid this is_null and assume $params
209             // is an array, since that's how it is typed in addPlugin
210             if (is_null($params)) {
211                 self::addPlugin($name);
212             } else if (is_array($params)) {
213                 if (count($params) == 0) {
214                     self::addPlugin($name);
215                 } else {
216                     $keys = array_keys($params);
217                     if (is_string($keys[0])) {
218                         self::addPlugin($name, $params);
219                     } else {
220                         foreach ($params as $paramset) {
221                             self::addPlugin($name, $paramset);
222                         }
223                     }
224                 }
225             }
226         }
227
228         // XXX: if plugins should check the schema at runtime, do that here.
229         if (common_config('db', 'schemacheck') == 'runtime') {
230             Event::handle('CheckSchema');
231         }
232
233         // Give plugins a chance to initialize in a fully-prepared environment
234         Event::handle('InitializePlugin');
235     }
236
237     /**
238      * Quick-check if configuration has been established.
239      * Useful for functions which may get used partway through
240      * initialization to back off from fancier things.
241      *
242      * @return bool
243      */
244     public static function haveConfig()
245     {
246         return self::$have_config;
247     }
248
249     public static function isApi()
250     {
251         return self::$is_api;
252     }
253
254     public static function setApi($mode)
255     {
256         self::$is_api = $mode;
257     }
258
259     public static function isAjax()
260     {
261         return self::$is_ajax;
262     }
263
264     public static function setAjax($mode)
265     {
266         self::$is_ajax = $mode;
267     }
268
269     /**
270      * Build default configuration array
271      * @return array
272      */
273     protected static function defaultConfig()
274     {
275         global $_server, $_path;
276         require(INSTALLDIR.'/lib/default.php');
277         return $default;
278     }
279
280     /**
281      * Establish default configuration based on given or default server and path
282      * Sets global $_server, $_path, and $config
283      */
284     public static function initDefaults($server, $path)
285     {
286         global $_server, $_path, $config, $_PEAR;
287
288         Event::clearHandlers();
289         self::$plugins = array();
290
291         // try to figure out where we are. $server and $path
292         // can be set by including module, else we guess based
293         // on HTTP info.
294
295         if (isset($server)) {
296             $_server = $server;
297         } else {
298             $_server = array_key_exists('SERVER_NAME', $_SERVER) ?
299               strtolower($_SERVER['SERVER_NAME']) :
300             null;
301         }
302
303         if (isset($path)) {
304             $_path = $path;
305         } else {
306             $_path = (array_key_exists('SERVER_NAME', $_SERVER) && array_key_exists('SCRIPT_NAME', $_SERVER)) ?
307               self::_sn_to_path($_SERVER['SCRIPT_NAME']) :
308             null;
309         }
310
311         // Set config values initially to default values
312         $default = self::defaultConfig();
313         $config = $default;
314
315         // default configuration, overwritten in config.php
316         // Keep DB_DataObject's db config synced to ours...
317
318         $config['db'] = &$_PEAR->getStaticProperty('DB_DataObject','options');
319
320         $config['db'] = $default['db'];
321
322         if (function_exists('date_default_timezone_set')) {
323             /* Work internally in UTC */
324             date_default_timezone_set('UTC');
325         }
326     }
327
328     public static function loadSiteProfile($name)
329     {
330         global $config;
331         $settings = SiteProfile::getSettings($name);
332         $config = array_merge($config, $settings);
333     }
334
335     protected static function _sn_to_path($sn)
336     {
337         $past_root = substr($sn, 1);
338         $last_slash = strrpos($past_root, '/');
339         if ($last_slash > 0) {
340             $p = substr($past_root, 0, $last_slash);
341         } else {
342             $p = '';
343         }
344         return $p;
345     }
346
347     /**
348      * Load the default or specified configuration file.
349      * Modifies global $config and may establish plugins.
350      *
351      * @throws NoConfigException
352      */
353     protected static function loadConfigFile($conffile=null)
354     {
355         global $_server, $_path, $config;
356
357         // From most general to most specific:
358         // server-wide, then vhost-wide, then for a path,
359         // finally for a dir (usually only need one of the last two).
360
361         if (isset($conffile)) {
362             $config_files = array($conffile);
363         } else {
364             $config_files = array('/etc/statusnet/statusnet.php',
365                                   '/etc/statusnet/laconica.php',
366                                   '/etc/laconica/laconica.php',
367                                   '/etc/statusnet/'.$_server.'.php',
368                                   '/etc/laconica/'.$_server.'.php');
369
370             if (strlen($_path) > 0) {
371                 $config_files[] = '/etc/statusnet/'.$_server.'_'.$_path.'.php';
372                 $config_files[] = '/etc/laconica/'.$_server.'_'.$_path.'.php';
373             }
374
375             $config_files[] = INSTALLDIR.'/config.php';
376         }
377
378         self::$have_config = false;
379
380         foreach ($config_files as $_config_file) {
381             if (@file_exists($_config_file)) {
382                 // Ignore 0-byte config files
383                 if (filesize($_config_file) > 0) {
384                     common_log(LOG_INFO, "Including config file: " . $_config_file);
385                     include($_config_file);
386                     self::$have_config = true;
387                 }
388             }
389         }
390
391         if (!self::$have_config) {
392             throw new NoConfigException("No configuration file found.",
393                                         $config_files);
394         }
395
396         // Check for database server; must exist!
397
398         if (empty($config['db']['database'])) {
399             throw new ServerException("No database server for this site.");
400         }
401     }
402
403     /**
404      * Are we running from the web with HTTPS?
405      *
406      * @return boolean true if we're running with HTTPS; else false
407      */
408
409     static function isHTTPS()
410     {
411         // There are some exceptions to this; add them here!
412         if(empty($_SERVER['HTTPS'])) {
413             return false;
414         } else {
415             return $_SERVER['HTTPS'] !== 'off';
416         }
417     }
418 }
419
420 class NoConfigException extends Exception
421 {
422     public $configFiles;
423
424     function __construct($msg, $configFiles) {
425         parent::__construct($msg);
426         $this->configFiles = $configFiles;
427     }
428 }