]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - lib/gnusocial.php
*** Privacy Leak fixed: ***
[quix0rs-gnu-social.git] / lib / gnusocial.php
1 <?php
2 // This file is part of GNU social - https://www.gnu.org/software/social
3 //
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.
8 //
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.
13 //
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/>.
16
17 defined('GNUSOCIAL') || die();
18
19 global $config, $_server, $_path;
20
21 /**
22  * Global configuration setup and management.
23  */
24 class GNUsocial
25 {
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();
31
32     /**
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.
36      *
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
39      *
40      * @throws ServerException if plugin can't be found
41      */
42     public static function addPlugin($name, array $attrs=array())
43     {
44         $name = ucfirst($name);
45
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.
50             return true;
51         }
52
53         $pluginclass = "{$name}Plugin";
54
55         if (!class_exists($pluginclass)) {
56
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");
63
64             foreach ($files as $file) {
65                 $fullpath = INSTALLDIR.'/'.$file;
66                 if (@file_exists($fullpath)) {
67                     include_once($fullpath);
68                     break;
69                 }
70             }
71             if (!class_exists($pluginclass)) {
72                 throw new ServerException("Plugin $name not found.", 500);
73             }
74         }
75
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;
81         }
82
83         // Record activated plugins for later display/config dump
84         self::$plugins[$name] = $attrs;
85
86         return true;
87     }
88
89     public static function delPlugin($name)
90     {
91         // Remove our plugin if it was previously loaded
92         $name = ucfirst($name);
93         if (isset(self::$plugins[$name])) {
94             unset(self::$plugins[$name]);
95         }
96
97         // make sure initPlugins will avoid this
98         common_config_set('plugins', 'disable-'.$name, true);
99
100         return true;
101     }
102
103     /**
104      * Get a list of activated plugins in this process.
105      * @return array of (string $name, array $args) pairs
106      */
107     public static function getActivePlugins()
108     {
109         return self::$plugins;
110     }
111
112     /**
113      * Initialize, or re-initialize, GNU social global configuration
114      * and plugins.
115      *
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.
119      *
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
123      *
124      * @throws NoConfigException if config file can't be found
125      */
126     public static function init($server=null, $path=null, $conffile=null)
127     {
128         Router::clear();
129
130         self::initDefaults($server, $path);
131         self::loadConfigFile($conffile);
132
133         $sprofile = common_config('site', 'profile');
134         if (!empty($sprofile)) {
135             self::loadSiteProfile($sprofile);
136         }
137         // Load settings from database; note we need autoload for this
138         Config::loadSettings();
139
140         self::fillConfigVoids();
141         self::verifyLoadedConfig();
142
143         self::initPlugins();
144     }
145
146     /**
147      * Get identifier of the currently active site configuration
148      * @return string
149      */
150     public static function currentSite()
151     {
152         return common_config('site', 'nickname');
153     }
154
155     /**
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.
159      *
160      * May throw exception or trigger a fatal error if the given
161      * site is missing or configured incorrectly.
162      *
163      * @param string $nickname
164      */
165     public static function switchSite($nickname)
166     {
167         if ($nickname == self::currentSite()) {
168             return true;
169         }
170
171         $sn = Status_network::getKV('nickname', $nickname);
172         if (empty($sn)) {
173             return false;
174             throw new Exception("No such site nickname '$nickname'");
175         }
176
177         $server = $sn->getServerName();
178         self::init($server);
179     }
180
181     /**
182      * Pull all local sites from status_network table.
183      *
184      * Behavior undefined if site is not configured via Status_network.
185      *
186      * @return array of nicknames
187      */
188     public static function findAllSites()
189     {
190         $sites = array();
191         $sn = new Status_network();
192         $sn->find();
193         while ($sn->fetch()) {
194             $sites[] = $sn->nickname;
195         }
196         return $sites;
197     }
198
199     /**
200      * Fire initialization events for all instantiated plugins.
201      */
202     protected static function initPlugins()
203     {
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.
207
208         // Load core plugins
209         foreach (common_config('plugins', 'core') as $name => $params) {
210             call_user_func('self::addPlugin', $name, $params);
211         }
212
213         // Load default plugins
214         foreach (common_config('plugins', 'default') as $name => $params) {
215             $key = 'disable-' . $name;
216             if (common_config('plugins', $key)) {
217                 continue;
218             }
219
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);
227                 } else {
228                     $keys = array_keys($params);
229                     if (is_string($keys[0])) {
230                         self::addPlugin($name, $params);
231                     } else {
232                         foreach ($params as $paramset) {
233                             self::addPlugin($name, $paramset);
234                         }
235                     }
236                 }
237             }
238         }
239
240         // XXX: if plugins should check the schema at runtime, do that here.
241         if (common_config('db', 'schemacheck') == 'runtime') {
242             Event::handle('CheckSchema');
243         }
244
245         // Give plugins a chance to initialize in a fully-prepared environment
246         Event::handle('InitializePlugin');
247     }
248
249     /**
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.
253      *
254      * @return bool
255      */
256     public static function haveConfig()
257     {
258         return self::$have_config;
259     }
260
261     /**
262      * Returns a list of configuration files that have
263      * been loaded for this instance of GNU social.
264      */
265     public static function configFiles()
266     {
267         return self::$config_files;
268     }
269
270     public static function isApi()
271     {
272         return self::$is_api;
273     }
274
275     public static function setApi($mode)
276     {
277         self::$is_api = $mode;
278     }
279
280     public static function isAjax()
281     {
282         return self::$is_ajax;
283     }
284
285     public static function setAjax($mode)
286     {
287         self::$is_ajax = $mode;
288     }
289
290     /**
291      * Build default configuration array
292      * @return array
293      */
294     protected static function defaultConfig()
295     {
296         global $_server, $_path;
297         require(INSTALLDIR.'/lib/default.php');
298         return $default;
299     }
300
301     /**
302      * Establish default configuration based on given or default server and path
303      * Sets global $_server, $_path, and $config
304      */
305     public static function initDefaults($server, $path)
306     {
307         global $_server, $_path, $config, $_PEAR;
308
309         Event::clearHandlers();
310         self::$plugins = array();
311
312         // try to figure out where we are. $server and $path
313         // can be set by including module, else we guess based
314         // on HTTP info.
315
316         if (isset($server)) {
317             $_server = $server;
318         } else {
319             $_server = array_key_exists('SERVER_NAME', $_SERVER) ?
320               strtolower($_SERVER['SERVER_NAME']) :
321             null;
322         }
323
324         if (isset($path)) {
325             $_path = $path;
326         } else {
327             $_path = (array_key_exists('SERVER_NAME', $_SERVER) && array_key_exists('SCRIPT_NAME', $_SERVER)) ?
328               self::_sn_to_path($_SERVER['SCRIPT_NAME']) :
329             null;
330         }
331
332         // Set config values initially to default values
333         $default = self::defaultConfig();
334         $config = $default;
335
336         // default configuration, overwritten in config.php
337         // Keep DB_DataObject's db config synced to ours...
338
339         $config['db'] = &$_PEAR->getStaticProperty('DB_DataObject','options');
340
341         $config['db'] = $default['db'];
342     }
343
344     public static function loadSiteProfile($name)
345     {
346         global $config;
347         $settings = SiteProfile::getSettings($name);
348         $config = array_replace_recursive($config, $settings);
349     }
350
351     protected static function _sn_to_path($sn)
352     {
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);
357         } else {
358             $p = '';
359         }
360         return $p;
361     }
362
363     /**
364      * Load the default or specified configuration file.
365      * Modifies global $config and may establish plugins.
366      *
367      * @throws NoConfigException
368      */
369     protected static function loadConfigFile($conffile=null)
370     {
371         global $_server, $_path, $config;
372
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).
376
377         if (isset($conffile)) {
378             $config_files = array($conffile);
379         } else {
380             $config_files = array('/etc/gnusocial/config.php',
381                                   '/etc/gnusocial/config.d/'.$_server.'.php');
382
383             if (strlen($_path) > 0) {
384                 $config_files[] = '/etc/gnusocial/config.d/'.$_server.'_'.$_path.'.php';
385             }
386
387             $config_files[] = INSTALLDIR.'/config.php';
388         }
389
390         self::$have_config = false;
391
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;
399                 }
400             }
401         }
402
403         if (!self::$have_config) {
404             throw new NoConfigException("No configuration file found.",
405                                         $config_files);
406         }
407
408         // Check for database server; must exist!
409
410         if (empty($config['db']['database'])) {
411             throw new ServerException("No database server for this site.");
412         }
413     }
414
415     static function fillConfigVoids()
416     {
417         // special cases on empty configuration options
418         if (!common_config('thumbnail', 'dir')) {
419             common_config_set('thumbnail', 'dir', File::path('thumb'));
420         }
421     }
422
423     /**
424      * Verify that the loaded config is good. Not complete, but will
425      * throw exceptions on common configuration problems I hope.
426      *
427      * Might make changes to the filesystem, to created dirs, but will
428      * not make database changes.
429      */
430     static function verifyLoadedConfig()
431     {
432         $mkdirs = [];
433
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';
437         }
438
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;
444             }
445         }
446
447         // try to create those that are not directories
448         foreach ($mkdirs as $dir=>$description) {
449             if (is_file($dir)) {
450                 throw new ConfigException('Expected directory for '._ve($description).' is a file!');
451             }
452             if (!mkdir($dir)) {
453                 throw new ConfigException('Could not create directory for '._ve($description).': '._ve($dir));
454             }
455             if (!chmod($dir, 0775)) {
456                 common_log(LOG_WARNING, 'Could not chmod 0775 on directory for '._ve($description).': '._ve($dir));
457             }
458         }
459
460         if (!is_array(common_config('public', 'autosource'))) {
461             throw new ConfigException('Configuration option public/autosource is not an array.');
462         }
463     }
464
465     /**
466      * Are we running from the web with HTTPS?
467      *
468      * @return boolean true if we're running with HTTPS; else false
469      */
470
471     static function isHTTPS()
472     {
473         if (common_config('site', 'sslproxy')) {
474             return true;
475         }
476
477         // There are some exceptions to this; add them here!
478         if (empty($_SERVER['HTTPS'])) {
479             return false;
480         }
481
482         // If it is _not_ "off", it is on, so "true".
483         return strtolower($_SERVER['HTTPS']) !== 'off';
484     }
485
486     /**
487      * Can we use HTTPS? Then do! Only return false if it's not configured ("never").
488      */
489     static function useHTTPS()
490     {
491         return self::isHTTPS() || common_config('site', 'ssl') != 'never';
492     }
493 }
494
495 class NoConfigException extends Exception
496 {
497     public $configFiles;
498
499     function __construct($msg, $configFiles) {
500         parent::__construct($msg);
501         $this->configFiles = $configFiles;
502     }
503 }