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