3 * StatusNet - the distributed open-source microblogging tool
4 * Copyright (C) 2009-2010 StatusNet, Inc.
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.
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.
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/>.
21 if (!defined('STATUSNET') && !defined('LACONICA')) {
25 global $config, $_server, $_path;
28 * Global configuration setup and management.
32 protected static $have_config;
33 protected static $is_api;
34 protected static $is_ajax;
35 protected static $plugins = array();
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.
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
45 * @throws ServerException if plugin can't be found
47 public static function addPlugin($name, array $attrs=array())
49 $name = ucfirst($name);
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.
58 $pluginclass = "{$name}Plugin";
60 if (!class_exists($pluginclass)) {
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");
69 foreach ($files as $file) {
70 $fullpath = INSTALLDIR.'/'.$file;
71 if (@file_exists($fullpath)) {
72 include_once($fullpath);
76 if (!class_exists($pluginclass)) {
77 throw new ServerException("Plugin $name not found.", 500);
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;
88 // Record activated plugins for later display/config dump
89 self::$plugins[$name] = $attrs;
94 public static function delPlugin($name)
96 // Remove our plugin if it was previously loaded
97 $name = ucfirst($name);
98 if (isset(self::$plugins[$name])) {
99 unset(self::$plugins[$name]);
102 // make sure initPlugins will avoid this
103 common_config_set('plugins', 'disable-'.$name, true);
109 * Get a list of activated plugins in this process.
110 * @return array of (string $name, array $args) pairs
112 public static function getActivePlugins()
114 return self::$plugins;
118 * Initialize, or re-initialize, StatusNet global configuration
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.
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
129 * @throws NoConfigException if config file can't be found
131 public static function init($server=null, $path=null, $conffile=null)
135 self::initDefaults($server, $path);
136 self::loadConfigFile($conffile);
138 $sprofile = common_config('site', 'profile');
139 if (!empty($sprofile)) {
140 self::loadSiteProfile($sprofile);
142 // Load settings from database; note we need autoload for this
143 Config::loadSettings();
149 * Get identifier of the currently active site configuration
152 public static function currentSite()
154 return common_config('site', 'nickname');
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.
162 * May throw exception or trigger a fatal error if the given
163 * site is missing or configured incorrectly.
165 * @param string $nickname
167 public static function switchSite($nickname)
169 if ($nickname == StatusNet::currentSite()) {
173 $sn = Status_network::getKV('nickname', $nickname);
176 throw new Exception("No such site nickname '$nickname'");
179 $server = $sn->getServerName();
180 StatusNet::init($server);
184 * Pull all local sites from status_network table.
186 * Behavior undefined if site is not configured via Status_network.
188 * @return array of nicknames
190 public static function findAllSites()
193 $sn = new Status_network();
195 while ($sn->fetch()) {
196 $sites[] = $sn->nickname;
202 * Fire initialization events for all instantiated plugins.
204 protected static function initPlugins()
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.
211 foreach (common_config('plugins', 'core') as $name => $params) {
212 call_user_func('self::addPlugin', $name, $params);
215 // Load default plugins
216 foreach (common_config('plugins', 'default') as $name => $params) {
217 $key = 'disable-' . $name;
218 if (common_config('plugins', $key)) {
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);
230 $keys = array_keys($params);
231 if (is_string($keys[0])) {
232 self::addPlugin($name, $params);
234 foreach ($params as $paramset) {
235 self::addPlugin($name, $paramset);
242 // XXX: if plugins should check the schema at runtime, do that here.
243 if (common_config('db', 'schemacheck') == 'runtime') {
244 Event::handle('CheckSchema');
247 // Give plugins a chance to initialize in a fully-prepared environment
248 Event::handle('InitializePlugin');
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.
258 public static function haveConfig()
260 return self::$have_config;
263 public static function isApi()
265 return self::$is_api;
268 public static function setApi($mode)
270 self::$is_api = $mode;
273 public static function isAjax()
275 return self::$is_ajax;
278 public static function setAjax($mode)
280 self::$is_ajax = $mode;
284 * Build default configuration array
287 protected static function defaultConfig()
289 global $_server, $_path;
290 require(INSTALLDIR.'/lib/default.php');
295 * Establish default configuration based on given or default server and path
296 * Sets global $_server, $_path, and $config
298 public static function initDefaults($server, $path)
300 global $_server, $_path, $config, $_PEAR;
302 Event::clearHandlers();
303 self::$plugins = array();
305 // try to figure out where we are. $server and $path
306 // can be set by including module, else we guess based
309 if (isset($server)) {
312 $_server = array_key_exists('SERVER_NAME', $_SERVER) ?
313 strtolower($_SERVER['SERVER_NAME']) :
320 $_path = (array_key_exists('SERVER_NAME', $_SERVER) && array_key_exists('SCRIPT_NAME', $_SERVER)) ?
321 self::_sn_to_path($_SERVER['SCRIPT_NAME']) :
325 // Set config values initially to default values
326 $default = self::defaultConfig();
329 // default configuration, overwritten in config.php
330 // Keep DB_DataObject's db config synced to ours...
332 $config['db'] = &$_PEAR->getStaticProperty('DB_DataObject','options');
334 $config['db'] = $default['db'];
336 if (function_exists('date_default_timezone_set')) {
337 /* Work internally in UTC */
338 date_default_timezone_set('UTC');
342 public static function loadSiteProfile($name)
345 $settings = SiteProfile::getSettings($name);
346 $config = array_replace_recursive($config, $settings);
349 protected static function _sn_to_path($sn)
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);
362 * Load the default or specified configuration file.
363 * Modifies global $config and may establish plugins.
365 * @throws NoConfigException
367 protected static function loadConfigFile($conffile=null)
369 global $_server, $_path, $config;
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).
375 if (isset($conffile)) {
376 $config_files = array($conffile);
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');
384 if (strlen($_path) > 0) {
385 $config_files[] = '/etc/statusnet/'.$_server.'_'.$_path.'.php';
386 $config_files[] = '/etc/laconica/'.$_server.'_'.$_path.'.php';
389 $config_files[] = INSTALLDIR.'/config.php';
392 self::$have_config = false;
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;
405 if (!self::$have_config) {
406 throw new NoConfigException("No configuration file found.",
410 // Check for database server; must exist!
412 if (empty($config['db']['database'])) {
413 throw new ServerException("No database server for this site.");
418 * Are we running from the web with HTTPS?
420 * @return boolean true if we're running with HTTPS; else false
423 static function isHTTPS()
425 // There are some exceptions to this; add them here!
426 if(empty($_SERVER['HTTPS'])) {
429 return $_SERVER['HTTPS'] !== 'off';
434 class NoConfigException extends Exception
438 function __construct($msg, $configFiles) {
439 parent::__construct($msg);
440 $this->configFiles = $configFiles;