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;
95 * Get a list of activated plugins in this process.
96 * @return array of (string $name, array $args) pairs
98 public static function getActivePlugins()
100 return self::$plugins;
104 * Initialize, or re-initialize, StatusNet global configuration
107 * If switching site configurations during script execution, be
108 * careful when working with leftover objects -- global settings
109 * affect many things and they may not behave as you expected.
111 * @param $server optional web server hostname for picking config
112 * @param $path optional URL path for picking config
113 * @param $conffile optional configuration file path
115 * @throws NoConfigException if config file can't be found
117 public static function init($server=null, $path=null, $conffile=null)
121 self::initDefaults($server, $path);
122 self::loadConfigFile($conffile);
124 $sprofile = common_config('site', 'profile');
125 if (!empty($sprofile)) {
126 self::loadSiteProfile($sprofile);
128 // Load settings from database; note we need autoload for this
129 Config::loadSettings();
135 * Get identifier of the currently active site configuration
138 public static function currentSite()
140 return common_config('site', 'nickname');
144 * Change site configuration to site specified by nickname,
145 * if set up via Status_network. If not, sites other than
146 * the current will fail horribly.
148 * May throw exception or trigger a fatal error if the given
149 * site is missing or configured incorrectly.
151 * @param string $nickname
153 public static function switchSite($nickname)
155 if ($nickname == StatusNet::currentSite()) {
159 $sn = Status_network::getKV('nickname', $nickname);
162 throw new Exception("No such site nickname '$nickname'");
165 $server = $sn->getServerName();
166 StatusNet::init($server);
170 * Pull all local sites from status_network table.
172 * Behavior undefined if site is not configured via Status_network.
174 * @return array of nicknames
176 public static function findAllSites()
179 $sn = new Status_network();
181 while ($sn->fetch()) {
182 $sites[] = $sn->nickname;
188 * Fire initialization events for all instantiated plugins.
190 protected static function initPlugins()
192 // User config may have already added some of these plugins, with
193 // maybe configured parameters. The self::addPlugin function will
194 // ignore the new call if it has already been instantiated.
197 foreach (common_config('plugins', 'core') as $name => $params) {
198 call_user_func('self::addPlugin', $name, $params);
201 // Load default plugins
202 foreach (common_config('plugins', 'default') as $name => $params) {
203 $key = 'disable-' . $name;
204 if (common_config('plugins', $key)) {
208 // TODO: We should be able to avoid this is_null and assume $params
209 // is an array, since that's how it is typed in addPlugin
210 if (is_null($params)) {
211 self::addPlugin($name);
212 } else if (is_array($params)) {
213 if (count($params) == 0) {
214 self::addPlugin($name);
216 $keys = array_keys($params);
217 if (is_string($keys[0])) {
218 self::addPlugin($name, $params);
220 foreach ($params as $paramset) {
221 self::addPlugin($name, $paramset);
228 // XXX: if plugins should check the schema at runtime, do that here.
229 if (common_config('db', 'schemacheck') == 'runtime') {
230 Event::handle('CheckSchema');
233 // Give plugins a chance to initialize in a fully-prepared environment
234 Event::handle('InitializePlugin');
238 * Quick-check if configuration has been established.
239 * Useful for functions which may get used partway through
240 * initialization to back off from fancier things.
244 public static function haveConfig()
246 return self::$have_config;
249 public static function isApi()
251 return self::$is_api;
254 public static function setApi($mode)
256 self::$is_api = $mode;
259 public static function isAjax()
261 return self::$is_ajax;
264 public static function setAjax($mode)
266 self::$is_ajax = $mode;
270 * Build default configuration array
273 protected static function defaultConfig()
275 global $_server, $_path;
276 require(INSTALLDIR.'/lib/default.php');
281 * Establish default configuration based on given or default server and path
282 * Sets global $_server, $_path, and $config
284 public static function initDefaults($server, $path)
286 global $_server, $_path, $config, $_PEAR;
288 Event::clearHandlers();
289 self::$plugins = array();
291 // try to figure out where we are. $server and $path
292 // can be set by including module, else we guess based
295 if (isset($server)) {
298 $_server = array_key_exists('SERVER_NAME', $_SERVER) ?
299 strtolower($_SERVER['SERVER_NAME']) :
306 $_path = (array_key_exists('SERVER_NAME', $_SERVER) && array_key_exists('SCRIPT_NAME', $_SERVER)) ?
307 self::_sn_to_path($_SERVER['SCRIPT_NAME']) :
311 // Set config values initially to default values
312 $default = self::defaultConfig();
315 // default configuration, overwritten in config.php
316 // Keep DB_DataObject's db config synced to ours...
318 $config['db'] = &$_PEAR->getStaticProperty('DB_DataObject','options');
320 $config['db'] = $default['db'];
322 if (function_exists('date_default_timezone_set')) {
323 /* Work internally in UTC */
324 date_default_timezone_set('UTC');
328 public static function loadSiteProfile($name)
331 $settings = SiteProfile::getSettings($name);
332 $config = array_replace_recursive($config, $settings);
335 protected static function _sn_to_path($sn)
337 $past_root = substr($sn, 1);
338 $last_slash = strrpos($past_root, '/');
339 if ($last_slash > 0) {
340 $p = substr($past_root, 0, $last_slash);
348 * Load the default or specified configuration file.
349 * Modifies global $config and may establish plugins.
351 * @throws NoConfigException
353 protected static function loadConfigFile($conffile=null)
355 global $_server, $_path, $config;
357 // From most general to most specific:
358 // server-wide, then vhost-wide, then for a path,
359 // finally for a dir (usually only need one of the last two).
361 if (isset($conffile)) {
362 $config_files = array($conffile);
364 $config_files = array('/etc/statusnet/statusnet.php',
365 '/etc/statusnet/laconica.php',
366 '/etc/laconica/laconica.php',
367 '/etc/statusnet/'.$_server.'.php',
368 '/etc/laconica/'.$_server.'.php');
370 if (strlen($_path) > 0) {
371 $config_files[] = '/etc/statusnet/'.$_server.'_'.$_path.'.php';
372 $config_files[] = '/etc/laconica/'.$_server.'_'.$_path.'.php';
375 $config_files[] = INSTALLDIR.'/config.php';
378 self::$have_config = false;
380 foreach ($config_files as $_config_file) {
381 if (@file_exists($_config_file)) {
382 // Ignore 0-byte config files
383 if (filesize($_config_file) > 0) {
384 common_log(LOG_INFO, "Including config file: " . $_config_file);
385 include($_config_file);
386 self::$have_config = true;
391 if (!self::$have_config) {
392 throw new NoConfigException("No configuration file found.",
396 // Check for database server; must exist!
398 if (empty($config['db']['database'])) {
399 throw new ServerException("No database server for this site.");
404 * Are we running from the web with HTTPS?
406 * @return boolean true if we're running with HTTPS; else false
409 static function isHTTPS()
411 // There are some exceptions to this; add them here!
412 if(empty($_SERVER['HTTPS'])) {
415 return $_SERVER['HTTPS'] !== 'off';
420 class NoConfigException extends Exception
424 function __construct($msg, $configFiles) {
425 parent::__construct($msg);
426 $this->configFiles = $configFiles;