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('GNUSOCIAL')) { exit(1); }
23 global $config, $_server, $_path;
26 * Global configuration setup and management.
30 protected static $have_config;
31 protected static $is_api;
32 protected static $is_ajax;
33 protected static $plugins = array();
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.
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
43 * @throws ServerException if plugin can't be found
45 public static function addPlugin($name, array $attrs=array())
47 $name = ucfirst($name);
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.
56 $pluginclass = "{$name}Plugin";
58 if (!class_exists($pluginclass)) {
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");
67 foreach ($files as $file) {
68 $fullpath = INSTALLDIR.'/'.$file;
69 if (@file_exists($fullpath)) {
70 include_once($fullpath);
74 if (!class_exists($pluginclass)) {
75 throw new ServerException("Plugin $name not found.", 500);
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;
86 // Record activated plugins for later display/config dump
87 self::$plugins[$name] = $attrs;
92 public static function delPlugin($name)
94 // Remove our plugin if it was previously loaded
95 $name = ucfirst($name);
96 if (isset(self::$plugins[$name])) {
97 unset(self::$plugins[$name]);
100 // make sure initPlugins will avoid this
101 common_config_set('plugins', 'disable-'.$name, true);
107 * Get a list of activated plugins in this process.
108 * @return array of (string $name, array $args) pairs
110 public static function getActivePlugins()
112 return self::$plugins;
116 * Initialize, or re-initialize, GNU social global configuration
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.
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
127 * @throws NoConfigException if config file can't be found
129 public static function init($server=null, $path=null, $conffile=null)
133 self::initDefaults($server, $path);
134 self::loadConfigFile($conffile);
136 $sprofile = common_config('site', 'profile');
137 if (!empty($sprofile)) {
138 self::loadSiteProfile($sprofile);
140 // Load settings from database; note we need autoload for this
141 Config::loadSettings();
147 * Get identifier of the currently active site configuration
150 public static function currentSite()
152 return common_config('site', 'nickname');
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.
160 * May throw exception or trigger a fatal error if the given
161 * site is missing or configured incorrectly.
163 * @param string $nickname
165 public static function switchSite($nickname)
167 if ($nickname == self::currentSite()) {
171 $sn = Status_network::getKV('nickname', $nickname);
174 throw new Exception("No such site nickname '$nickname'");
177 $server = $sn->getServerName();
182 * Pull all local sites from status_network table.
184 * Behavior undefined if site is not configured via Status_network.
186 * @return array of nicknames
188 public static function findAllSites()
191 $sn = new Status_network();
193 while ($sn->fetch()) {
194 $sites[] = $sn->nickname;
200 * Fire initialization events for all instantiated plugins.
202 protected static function initPlugins()
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.
209 foreach (common_config('plugins', 'core') as $name => $params) {
210 call_user_func('self::addPlugin', $name, $params);
213 // Load default plugins
214 foreach (common_config('plugins', 'default') as $name => $params) {
215 $key = 'disable-' . $name;
216 if (common_config('plugins', $key)) {
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);
228 $keys = array_keys($params);
229 if (is_string($keys[0])) {
230 self::addPlugin($name, $params);
232 foreach ($params as $paramset) {
233 self::addPlugin($name, $paramset);
240 // XXX: if plugins should check the schema at runtime, do that here.
241 if (common_config('db', 'schemacheck') == 'runtime') {
242 Event::handle('CheckSchema');
245 // Give plugins a chance to initialize in a fully-prepared environment
246 Event::handle('InitializePlugin');
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.
256 public static function haveConfig()
258 return self::$have_config;
261 public static function isApi()
263 return self::$is_api;
266 public static function setApi($mode)
268 self::$is_api = $mode;
271 public static function isAjax()
273 return self::$is_ajax;
276 public static function setAjax($mode)
278 self::$is_ajax = $mode;
282 * Build default configuration array
285 protected static function defaultConfig()
287 global $_server, $_path;
288 require(INSTALLDIR.'/lib/default.php');
293 * Establish default configuration based on given or default server and path
294 * Sets global $_server, $_path, and $config
296 public static function initDefaults($server, $path)
298 global $_server, $_path, $config, $_PEAR;
300 Event::clearHandlers();
301 self::$plugins = array();
303 // try to figure out where we are. $server and $path
304 // can be set by including module, else we guess based
307 if (isset($server)) {
310 $_server = array_key_exists('SERVER_NAME', $_SERVER) ?
311 strtolower($_SERVER['SERVER_NAME']) :
318 $_path = (array_key_exists('SERVER_NAME', $_SERVER) && array_key_exists('SCRIPT_NAME', $_SERVER)) ?
319 self::_sn_to_path($_SERVER['SCRIPT_NAME']) :
323 // Set config values initially to default values
324 $default = self::defaultConfig();
327 // default configuration, overwritten in config.php
328 // Keep DB_DataObject's db config synced to ours...
330 $config['db'] = &$_PEAR->getStaticProperty('DB_DataObject','options');
332 $config['db'] = $default['db'];
334 if (function_exists('date_default_timezone_set')) {
335 /* Work internally in UTC */
336 date_default_timezone_set('UTC');
340 public static function loadSiteProfile($name)
343 $settings = SiteProfile::getSettings($name);
344 $config = array_replace_recursive($config, $settings);
347 protected static function _sn_to_path($sn)
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);
360 * Load the default or specified configuration file.
361 * Modifies global $config and may establish plugins.
363 * @throws NoConfigException
365 protected static function loadConfigFile($conffile=null)
367 global $_server, $_path, $config;
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).
373 if (isset($conffile)) {
374 $config_files = array($conffile);
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');
382 if (strlen($_path) > 0) {
383 $config_files[] = '/etc/statusnet/'.$_server.'_'.$_path.'.php';
384 $config_files[] = '/etc/laconica/'.$_server.'_'.$_path.'.php';
387 $config_files[] = INSTALLDIR.'/config.php';
390 self::$have_config = false;
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;
403 if (!self::$have_config) {
404 throw new NoConfigException("No configuration file found.",
408 // Check for database server; must exist!
410 if (empty($config['db']['database'])) {
411 throw new ServerException("No database server for this site.");
416 * Are we running from the web with HTTPS?
418 * @return boolean true if we're running with HTTPS; else false
421 static function isHTTPS()
423 // There are some exceptions to this; add them here!
424 if (empty($_SERVER['HTTPS'])) {
428 // If it is _not_ "off", it is on, so "true".
429 return strtolower($_SERVER['HTTPS']) !== 'off';
433 * Can we use HTTPS? Then do! Only return false if it's not configured ("never").
435 static function useHTTPS()
437 return self::isHTTPS() || common_config('site', 'ssl') != 'never';
441 class NoConfigException extends Exception
445 function __construct($msg, $configFiles) {
446 parent::__construct($msg);
447 $this->configFiles = $configFiles;