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