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