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