2 // This file is part of GNU social - https://www.gnu.org/software/social
4 // GNU social is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU Affero General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
9 // GNU social is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU Affero General Public License for more details.
14 // You should have received a copy of the GNU Affero General Public License
15 // along with GNU social. If not, see <http://www.gnu.org/licenses/>.
17 defined('GNUSOCIAL') || die();
19 global $config, $_server, $_path;
22 * Global configuration setup and management.
26 protected static $config_files = array();
27 protected static $have_config;
28 protected static $is_api;
29 protected static $is_ajax;
30 protected static $plugins = array();
33 * Configure and instantiate a plugin into the current configuration.
34 * Class definitions will be loaded from standard paths if necessary.
35 * Note that initialization events won't be fired until later.
37 * @param string $name class name & plugin file/subdir name
38 * @param array $attrs key/value pairs of public attributes to set on plugin instance
40 * @throws ServerException if plugin can't be found
42 public static function addPlugin($name, array $attrs=array())
44 $name = ucfirst($name);
46 if (isset(self::$plugins[$name])) {
47 // We have already loaded this plugin. Don't try to
48 // do it again with (possibly) different values.
49 // Försten till kvarn får mala.
53 $pluginclass = "{$name}Plugin";
55 if (!class_exists($pluginclass)) {
57 $files = array("local/plugins/{$pluginclass}.php",
58 "local/plugins/{$name}/{$pluginclass}.php",
59 "local/{$pluginclass}.php",
60 "local/{$name}/{$pluginclass}.php",
61 "plugins/{$pluginclass}.php",
62 "plugins/{$name}/{$pluginclass}.php");
64 foreach ($files as $file) {
65 $fullpath = INSTALLDIR.'/'.$file;
66 if (@file_exists($fullpath)) {
67 include_once($fullpath);
71 if (!class_exists($pluginclass)) {
72 throw new ServerException("Plugin $name not found.", 500);
76 // Doesn't this $inst risk being garbage collected or something?
77 // TODO: put into a static array that makes sure $inst isn't lost.
78 $inst = new $pluginclass();
79 foreach ($attrs as $aname => $avalue) {
80 $inst->$aname = $avalue;
83 // Record activated plugins for later display/config dump
84 self::$plugins[$name] = $attrs;
89 public static function delPlugin($name)
91 // Remove our plugin if it was previously loaded
92 $name = ucfirst($name);
93 if (isset(self::$plugins[$name])) {
94 unset(self::$plugins[$name]);
97 // make sure initPlugins will avoid this
98 common_config_set('plugins', 'disable-'.$name, true);
104 * Get a list of activated plugins in this process.
105 * @return array of (string $name, array $args) pairs
107 public static function getActivePlugins()
109 return self::$plugins;
113 * Initialize, or re-initialize, GNU social global configuration
116 * If switching site configurations during script execution, be
117 * careful when working with leftover objects -- global settings
118 * affect many things and they may not behave as you expected.
120 * @param $server optional web server hostname for picking config
121 * @param $path optional URL path for picking config
122 * @param $conffile optional configuration file path
124 * @throws NoConfigException if config file can't be found
126 public static function init($server=null, $path=null, $conffile=null)
130 self::initDefaults($server, $path);
131 self::loadConfigFile($conffile);
133 $sprofile = common_config('site', 'profile');
134 if (!empty($sprofile)) {
135 self::loadSiteProfile($sprofile);
137 // Load settings from database; note we need autoload for this
138 Config::loadSettings();
140 self::fillConfigVoids();
141 self::verifyLoadedConfig();
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;
262 * Returns a list of configuration files that have
263 * been loaded for this instance of GNU social.
265 public static function configFiles()
267 return self::$config_files;
270 public static function isApi()
272 return self::$is_api;
275 public static function setApi($mode)
277 self::$is_api = $mode;
280 public static function isAjax()
282 return self::$is_ajax;
285 public static function setAjax($mode)
287 self::$is_ajax = $mode;
291 * Build default configuration array
294 protected static function defaultConfig()
296 global $_server, $_path;
297 require(INSTALLDIR.'/lib/default.php');
302 * Establish default configuration based on given or default server and path
303 * Sets global $_server, $_path, and $config
305 public static function initDefaults($server, $path)
307 global $_server, $_path, $config, $_PEAR;
309 Event::clearHandlers();
310 self::$plugins = array();
312 // try to figure out where we are. $server and $path
313 // can be set by including module, else we guess based
316 if (isset($server)) {
319 $_server = array_key_exists('SERVER_NAME', $_SERVER) ?
320 strtolower($_SERVER['SERVER_NAME']) :
327 $_path = (array_key_exists('SERVER_NAME', $_SERVER) && array_key_exists('SCRIPT_NAME', $_SERVER)) ?
328 self::_sn_to_path($_SERVER['SCRIPT_NAME']) :
332 // Set config values initially to default values
333 $default = self::defaultConfig();
336 // default configuration, overwritten in config.php
337 // Keep DB_DataObject's db config synced to ours...
339 $config['db'] = &$_PEAR->getStaticProperty('DB_DataObject','options');
341 $config['db'] = $default['db'];
344 public static function loadSiteProfile($name)
347 $settings = SiteProfile::getSettings($name);
348 $config = array_replace_recursive($config, $settings);
351 protected static function _sn_to_path($sn)
353 $past_root = substr($sn, 1);
354 $last_slash = strrpos($past_root, '/');
355 if ($last_slash > 0) {
356 $p = substr($past_root, 0, $last_slash);
364 * Load the default or specified configuration file.
365 * Modifies global $config and may establish plugins.
367 * @throws NoConfigException
369 protected static function loadConfigFile($conffile=null)
371 global $_server, $_path, $config;
373 // From most general to most specific:
374 // server-wide, then vhost-wide, then for a path,
375 // finally for a dir (usually only need one of the last two).
377 if (isset($conffile)) {
378 $config_files = array($conffile);
380 $config_files = array('/etc/gnusocial/config.php',
381 '/etc/gnusocial/config.d/'.$_server.'.php');
383 if (strlen($_path) > 0) {
384 $config_files[] = '/etc/gnusocial/config.d/'.$_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 include($_config_file);
397 self::$config_files[] = $_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.");
415 static function fillConfigVoids()
417 // special cases on empty configuration options
418 if (!common_config('thumbnail', 'dir')) {
419 common_config_set('thumbnail', 'dir', File::path('thumb'));
424 * Verify that the loaded config is good. Not complete, but will
425 * throw exceptions on common configuration problems I hope.
427 * Might make changes to the filesystem, to created dirs, but will
428 * not make database changes.
430 static function verifyLoadedConfig()
434 if (common_config('htmlpurifier', 'Cache.DefinitionImpl') === 'Serializer'
435 && !is_dir(common_config('htmlpurifier', 'Cache.SerializerPath'))) {
436 $mkdirs[common_config('htmlpurifier', 'Cache.SerializerPath')] = 'HTMLPurifier Serializer cache';
439 // go through our configurable storage directories
440 foreach (['attachments', 'thumbnail'] as $dirtype) {
441 $dir = common_config($dirtype, 'dir');
442 if (!empty($dir) && !is_dir($dir)) {
443 $mkdirs[$dir] = $dirtype;
447 // try to create those that are not directories
448 foreach ($mkdirs as $dir=>$description) {
450 throw new ConfigException('Expected directory for '._ve($description).' is a file!');
453 throw new ConfigException('Could not create directory for '._ve($description).': '._ve($dir));
455 if (!chmod($dir, 0775)) {
456 common_log(LOG_WARNING, 'Could not chmod 0775 on directory for '._ve($description).': '._ve($dir));
460 if (!is_array(common_config('public', 'autosource'))) {
461 throw new ConfigException('Configuration option public/autosource is not an array.');
466 * Are we running from the web with HTTPS?
468 * @return boolean true if we're running with HTTPS; else false
471 static function isHTTPS()
473 if (common_config('site', 'sslproxy')) {
477 // There are some exceptions to this; add them here!
478 if (empty($_SERVER['HTTPS'])) {
482 // If it is _not_ "off", it is on, so "true".
483 return strtolower($_SERVER['HTTPS']) !== 'off';
487 * Can we use HTTPS? Then do! Only return false if it's not configured ("never").
489 static function useHTTPS()
491 return self::isHTTPS() || common_config('site', 'ssl') != 'never';
495 class NoConfigException extends Exception
499 function __construct($msg, $configFiles) {
500 parent::__construct($msg);
501 $this->configFiles = $configFiles;