]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - lib/statusnet.php
Comment and typing improvements
[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             if (is_null($params)) {
209                 self::addPlugin($name);
210             } else if (is_array($params)) {
211                 if (count($params) == 0) {
212                     self::addPlugin($name);
213                 } else {
214                     $keys = array_keys($params);
215                     if (is_string($keys[0])) {
216                         self::addPlugin($name, $params);
217                     } else {
218                         foreach ($params as $paramset) {
219                             self::addPlugin($name, $paramset);
220                         }
221                     }
222                 }
223             }
224         }
225
226         // XXX: if plugins should check the schema at runtime, do that here.
227         if (common_config('db', 'schemacheck') == 'runtime') {
228             Event::handle('CheckSchema');
229         }
230
231         // Give plugins a chance to initialize in a fully-prepared environment
232         Event::handle('InitializePlugin');
233     }
234
235     /**
236      * Quick-check if configuration has been established.
237      * Useful for functions which may get used partway through
238      * initialization to back off from fancier things.
239      *
240      * @return bool
241      */
242     public static function haveConfig()
243     {
244         return self::$have_config;
245     }
246
247     public static function isApi()
248     {
249         return self::$is_api;
250     }
251
252     public static function setApi($mode)
253     {
254         self::$is_api = $mode;
255     }
256
257     public static function isAjax()
258     {
259         return self::$is_ajax;
260     }
261
262     public static function setAjax($mode)
263     {
264         self::$is_ajax = $mode;
265     }
266
267     /**
268      * Build default configuration array
269      * @return array
270      */
271     protected static function defaultConfig()
272     {
273         global $_server, $_path;
274         require(INSTALLDIR.'/lib/default.php');
275         return $default;
276     }
277
278     /**
279      * Establish default configuration based on given or default server and path
280      * Sets global $_server, $_path, and $config
281      */
282     public static function initDefaults($server, $path)
283     {
284         global $_server, $_path, $config, $_PEAR;
285
286         Event::clearHandlers();
287         self::$plugins = array();
288
289         // try to figure out where we are. $server and $path
290         // can be set by including module, else we guess based
291         // on HTTP info.
292
293         if (isset($server)) {
294             $_server = $server;
295         } else {
296             $_server = array_key_exists('SERVER_NAME', $_SERVER) ?
297               strtolower($_SERVER['SERVER_NAME']) :
298             null;
299         }
300
301         if (isset($path)) {
302             $_path = $path;
303         } else {
304             $_path = (array_key_exists('SERVER_NAME', $_SERVER) && array_key_exists('SCRIPT_NAME', $_SERVER)) ?
305               self::_sn_to_path($_SERVER['SCRIPT_NAME']) :
306             null;
307         }
308
309         // Set config values initially to default values
310         $default = self::defaultConfig();
311         $config = $default;
312
313         // default configuration, overwritten in config.php
314         // Keep DB_DataObject's db config synced to ours...
315
316         $config['db'] = &$_PEAR->getStaticProperty('DB_DataObject','options');
317
318         $config['db'] = $default['db'];
319
320         if (function_exists('date_default_timezone_set')) {
321             /* Work internally in UTC */
322             date_default_timezone_set('UTC');
323         }
324     }
325
326     public static function loadSiteProfile($name)
327     {
328         global $config;
329         $settings = SiteProfile::getSettings($name);
330         $config = array_merge($config, $settings);
331     }
332
333     protected static function _sn_to_path($sn)
334     {
335         $past_root = substr($sn, 1);
336         $last_slash = strrpos($past_root, '/');
337         if ($last_slash > 0) {
338             $p = substr($past_root, 0, $last_slash);
339         } else {
340             $p = '';
341         }
342         return $p;
343     }
344
345     /**
346      * Load the default or specified configuration file.
347      * Modifies global $config and may establish plugins.
348      *
349      * @throws NoConfigException
350      */
351     protected static function loadConfigFile($conffile=null)
352     {
353         global $_server, $_path, $config;
354
355         // From most general to most specific:
356         // server-wide, then vhost-wide, then for a path,
357         // finally for a dir (usually only need one of the last two).
358
359         if (isset($conffile)) {
360             $config_files = array($conffile);
361         } else {
362             $config_files = array('/etc/statusnet/statusnet.php',
363                                   '/etc/statusnet/laconica.php',
364                                   '/etc/laconica/laconica.php',
365                                   '/etc/statusnet/'.$_server.'.php',
366                                   '/etc/laconica/'.$_server.'.php');
367
368             if (strlen($_path) > 0) {
369                 $config_files[] = '/etc/statusnet/'.$_server.'_'.$_path.'.php';
370                 $config_files[] = '/etc/laconica/'.$_server.'_'.$_path.'.php';
371             }
372
373             $config_files[] = INSTALLDIR.'/config.php';
374         }
375
376         self::$have_config = false;
377
378         foreach ($config_files as $_config_file) {
379             if (@file_exists($_config_file)) {
380                 // Ignore 0-byte config files
381                 if (filesize($_config_file) > 0) {
382                     common_log(LOG_INFO, "Including config file: " . $_config_file);
383                     include($_config_file);
384                     self::$have_config = true;
385                 }
386             }
387         }
388
389         if (!self::$have_config) {
390             throw new NoConfigException("No configuration file found.",
391                                         $config_files);
392         }
393
394         // Check for database server; must exist!
395
396         if (empty($config['db']['database'])) {
397             throw new ServerException("No database server for this site.");
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 }