gnusocial.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504
  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. defined('GNUSOCIAL') || die();
  17. global $config, $_server, $_path;
  18. /**
  19. * Global configuration setup and management.
  20. */
  21. class GNUsocial
  22. {
  23. protected static $config_files = array();
  24. protected static $have_config;
  25. protected static $is_api;
  26. protected static $is_ajax;
  27. protected static $plugins = array();
  28. /**
  29. * Configure and instantiate a plugin into the current configuration.
  30. * Class definitions will be loaded from standard paths if necessary.
  31. * Note that initialization events won't be fired until later.
  32. *
  33. * @param string $name class name & plugin file/subdir name
  34. * @param array $attrs key/value pairs of public attributes to set on plugin instance
  35. *
  36. * @throws ServerException if plugin can't be found
  37. */
  38. public static function addPlugin($name, array $attrs=array())
  39. {
  40. $name = ucfirst($name);
  41. if (isset(self::$plugins[$name])) {
  42. // We have already loaded this plugin. Don't try to
  43. // do it again with (possibly) different values.
  44. // Försten till kvarn får mala.
  45. return true;
  46. }
  47. $pluginclass = "{$name}Plugin";
  48. if (!class_exists($pluginclass)) {
  49. $files = array("local/plugins/{$pluginclass}.php",
  50. "local/plugins/{$name}/{$pluginclass}.php",
  51. "local/{$pluginclass}.php",
  52. "local/{$name}/{$pluginclass}.php",
  53. "plugins/{$pluginclass}.php",
  54. "plugins/{$name}/{$pluginclass}.php");
  55. foreach ($files as $file) {
  56. $fullpath = INSTALLDIR.'/'.$file;
  57. if (@file_exists($fullpath)) {
  58. include_once($fullpath);
  59. break;
  60. }
  61. }
  62. if (!class_exists($pluginclass)) {
  63. throw new ServerException("Plugin $name not found.", 500);
  64. }
  65. }
  66. // Doesn't this $inst risk being garbage collected or something?
  67. // TODO: put into a static array that makes sure $inst isn't lost.
  68. $inst = new $pluginclass();
  69. foreach ($attrs as $aname => $avalue) {
  70. $inst->$aname = $avalue;
  71. }
  72. // Record activated plugins for later display/config dump
  73. self::$plugins[$name] = $attrs;
  74. return true;
  75. }
  76. public static function delPlugin($name)
  77. {
  78. // Remove our plugin if it was previously loaded
  79. $name = ucfirst($name);
  80. if (isset(self::$plugins[$name])) {
  81. unset(self::$plugins[$name]);
  82. }
  83. // make sure initPlugins will avoid this
  84. common_config_set('plugins', 'disable-'.$name, true);
  85. return true;
  86. }
  87. /**
  88. * Get a list of activated plugins in this process.
  89. * @return array of (string $name, array $args) pairs
  90. */
  91. public static function getActivePlugins()
  92. {
  93. return self::$plugins;
  94. }
  95. /**
  96. * Initialize, or re-initialize, GNU social global configuration
  97. * and plugins.
  98. *
  99. * If switching site configurations during script execution, be
  100. * careful when working with leftover objects -- global settings
  101. * affect many things and they may not behave as you expected.
  102. *
  103. * @param $server optional web server hostname for picking config
  104. * @param $path optional URL path for picking config
  105. * @param $conffile optional configuration file path
  106. *
  107. * @throws NoConfigException if config file can't be found
  108. */
  109. public static function init($server=null, $path=null, $conffile=null)
  110. {
  111. Router::clear();
  112. self::initDefaults($server, $path);
  113. self::loadConfigFile($conffile);
  114. $sprofile = common_config('site', 'profile');
  115. if (!empty($sprofile)) {
  116. self::loadSiteProfile($sprofile);
  117. }
  118. // Load settings from database; note we need autoload for this
  119. Config::loadSettings();
  120. self::fillConfigVoids();
  121. self::verifyLoadedConfig();
  122. self::initPlugins();
  123. }
  124. /**
  125. * Get identifier of the currently active site configuration
  126. * @return string
  127. */
  128. public static function currentSite()
  129. {
  130. return common_config('site', 'nickname');
  131. }
  132. /**
  133. * Change site configuration to site specified by nickname,
  134. * if set up via Status_network. If not, sites other than
  135. * the current will fail horribly.
  136. *
  137. * May throw exception or trigger a fatal error if the given
  138. * site is missing or configured incorrectly.
  139. *
  140. * @param string $nickname
  141. */
  142. public static function switchSite($nickname)
  143. {
  144. if ($nickname == self::currentSite()) {
  145. return true;
  146. }
  147. $sn = Status_network::getKV('nickname', $nickname);
  148. if (empty($sn)) {
  149. return false;
  150. throw new Exception("No such site nickname '$nickname'");
  151. }
  152. $server = $sn->getServerName();
  153. self::init($server);
  154. }
  155. /**
  156. * Pull all local sites from status_network table.
  157. *
  158. * Behavior undefined if site is not configured via Status_network.
  159. *
  160. * @return array of nicknames
  161. */
  162. public static function findAllSites()
  163. {
  164. $sites = array();
  165. $sn = new Status_network();
  166. $sn->find();
  167. while ($sn->fetch()) {
  168. $sites[] = $sn->nickname;
  169. }
  170. return $sites;
  171. }
  172. /**
  173. * Fire initialization events for all instantiated plugins.
  174. */
  175. protected static function initPlugins()
  176. {
  177. // User config may have already added some of these plugins, with
  178. // maybe configured parameters. The self::addPlugin function will
  179. // ignore the new call if it has already been instantiated.
  180. // Load core plugins
  181. foreach (common_config('plugins', 'core') as $name => $params) {
  182. call_user_func('self::addPlugin', $name, $params);
  183. }
  184. // Load default plugins
  185. foreach (common_config('plugins', 'default') as $name => $params) {
  186. $key = 'disable-' . $name;
  187. if (common_config('plugins', $key)) {
  188. continue;
  189. }
  190. // TODO: We should be able to avoid this is_null and assume $params
  191. // is an array, since that's how it is typed in addPlugin
  192. if (is_null($params)) {
  193. self::addPlugin($name);
  194. } else if (is_array($params)) {
  195. if (count($params) == 0) {
  196. self::addPlugin($name);
  197. } else {
  198. $keys = array_keys($params);
  199. if (is_string($keys[0])) {
  200. self::addPlugin($name, $params);
  201. } else {
  202. foreach ($params as $paramset) {
  203. self::addPlugin($name, $paramset);
  204. }
  205. }
  206. }
  207. }
  208. }
  209. // XXX: if plugins should check the schema at runtime, do that here.
  210. if (common_config('db', 'schemacheck') == 'runtime') {
  211. Event::handle('CheckSchema');
  212. }
  213. // Give plugins a chance to initialize in a fully-prepared environment
  214. Event::handle('InitializePlugin');
  215. }
  216. /**
  217. * Quick-check if configuration has been established.
  218. * Useful for functions which may get used partway through
  219. * initialization to back off from fancier things.
  220. *
  221. * @return bool
  222. */
  223. public static function haveConfig()
  224. {
  225. return self::$have_config;
  226. }
  227. /**
  228. * Returns a list of configuration files that have
  229. * been loaded for this instance of GNU social.
  230. */
  231. public static function configFiles()
  232. {
  233. return self::$config_files;
  234. }
  235. public static function isApi()
  236. {
  237. return self::$is_api;
  238. }
  239. public static function setApi($mode)
  240. {
  241. self::$is_api = $mode;
  242. }
  243. public static function isAjax()
  244. {
  245. return self::$is_ajax;
  246. }
  247. public static function setAjax($mode)
  248. {
  249. self::$is_ajax = $mode;
  250. }
  251. /**
  252. * Build default configuration array
  253. * @return array
  254. */
  255. protected static function defaultConfig()
  256. {
  257. global $_server, $_path;
  258. require(INSTALLDIR.'/lib/default.php');
  259. return $default;
  260. }
  261. /**
  262. * Establish default configuration based on given or default server and path
  263. * Sets global $_server, $_path, and $config
  264. */
  265. public static function initDefaults($server, $path)
  266. {
  267. global $_server, $_path, $config, $_PEAR;
  268. Event::clearHandlers();
  269. self::$plugins = array();
  270. // try to figure out where we are. $server and $path
  271. // can be set by including module, else we guess based
  272. // on HTTP info.
  273. if (isset($server)) {
  274. $_server = $server;
  275. } else {
  276. $_server = array_key_exists('SERVER_NAME', $_SERVER) ?
  277. strtolower($_SERVER['SERVER_NAME']) :
  278. null;
  279. }
  280. if (isset($path)) {
  281. $_path = $path;
  282. } else {
  283. $_path = (array_key_exists('SERVER_NAME', $_SERVER) && array_key_exists('SCRIPT_NAME', $_SERVER)) ?
  284. self::_sn_to_path($_SERVER['SCRIPT_NAME']) :
  285. null;
  286. }
  287. // Set config values initially to default values
  288. $default = self::defaultConfig();
  289. $config = $default;
  290. // default configuration, overwritten in config.php
  291. // Keep DB_DataObject's db config synced to ours...
  292. $config['db'] = &$_PEAR->getStaticProperty('DB_DataObject','options');
  293. $config['db'] = $default['db'];
  294. }
  295. public static function loadSiteProfile($name)
  296. {
  297. global $config;
  298. $settings = SiteProfile::getSettings($name);
  299. $config = array_replace_recursive($config, $settings);
  300. }
  301. protected static function _sn_to_path($sn)
  302. {
  303. $past_root = substr($sn, 1);
  304. $last_slash = strrpos($past_root, '/');
  305. if ($last_slash > 0) {
  306. $p = substr($past_root, 0, $last_slash);
  307. } else {
  308. $p = '';
  309. }
  310. return $p;
  311. }
  312. /**
  313. * Load the default or specified configuration file.
  314. * Modifies global $config and may establish plugins.
  315. *
  316. * @throws NoConfigException
  317. */
  318. protected static function loadConfigFile($conffile=null)
  319. {
  320. global $_server, $_path, $config;
  321. // From most general to most specific:
  322. // server-wide, then vhost-wide, then for a path,
  323. // finally for a dir (usually only need one of the last two).
  324. if (isset($conffile)) {
  325. $config_files = array($conffile);
  326. } else {
  327. $config_files = array('/etc/gnusocial/config.php',
  328. '/etc/gnusocial/config.d/'.$_server.'.php');
  329. if (strlen($_path) > 0) {
  330. $config_files[] = '/etc/gnusocial/config.d/'.$_server.'_'.$_path.'.php';
  331. }
  332. $config_files[] = INSTALLDIR.'/config.php';
  333. }
  334. self::$have_config = false;
  335. foreach ($config_files as $_config_file) {
  336. if (@file_exists($_config_file)) {
  337. // Ignore 0-byte config files
  338. if (filesize($_config_file) > 0) {
  339. include($_config_file);
  340. self::$config_files[] = $_config_file;
  341. self::$have_config = true;
  342. }
  343. }
  344. }
  345. if (!self::$have_config) {
  346. throw new NoConfigException("No configuration file found.",
  347. $config_files);
  348. }
  349. // Check for database server; must exist!
  350. if (empty($config['db']['database'])) {
  351. throw new ServerException("No database server for this site.");
  352. }
  353. }
  354. static function fillConfigVoids()
  355. {
  356. // special cases on empty configuration options
  357. if (!common_config('thumbnail', 'dir')) {
  358. common_config_set('thumbnail', 'dir', File::path('thumb'));
  359. }
  360. }
  361. /**
  362. * Verify that the loaded config is good. Not complete, but will
  363. * throw exceptions on common configuration problems I hope.
  364. *
  365. * Might make changes to the filesystem, to created dirs, but will
  366. * not make database changes.
  367. */
  368. static function verifyLoadedConfig()
  369. {
  370. $mkdirs = [];
  371. if (common_config('htmlpurifier', 'Cache.DefinitionImpl') === 'Serializer'
  372. && !is_dir(common_config('htmlpurifier', 'Cache.SerializerPath'))) {
  373. $mkdirs[common_config('htmlpurifier', 'Cache.SerializerPath')] = 'HTMLPurifier Serializer cache';
  374. }
  375. // go through our configurable storage directories
  376. foreach (['attachments', 'thumbnail'] as $dirtype) {
  377. $dir = common_config($dirtype, 'dir');
  378. if (!empty($dir) && !is_dir($dir)) {
  379. $mkdirs[$dir] = $dirtype;
  380. }
  381. }
  382. // try to create those that are not directories
  383. foreach ($mkdirs as $dir=>$description) {
  384. if (is_file($dir)) {
  385. throw new ConfigException('Expected directory for '._ve($description).' is a file!');
  386. }
  387. if (!mkdir($dir)) {
  388. throw new ConfigException('Could not create directory for '._ve($description).': '._ve($dir));
  389. }
  390. if (!chmod($dir, 0775)) {
  391. common_log(LOG_WARNING, 'Could not chmod 0775 on directory for '._ve($description).': '._ve($dir));
  392. }
  393. }
  394. if (!is_array(common_config('public', 'autosource'))) {
  395. throw new ConfigException('Configuration option public/autosource is not an array.');
  396. }
  397. }
  398. /**
  399. * Are we running from the web with HTTPS?
  400. *
  401. * @return boolean true if we're running with HTTPS; else false
  402. */
  403. static function isHTTPS()
  404. {
  405. if (common_config('site', 'sslproxy')) {
  406. return true;
  407. }
  408. // There are some exceptions to this; add them here!
  409. if (empty($_SERVER['HTTPS'])) {
  410. return false;
  411. }
  412. // If it is _not_ "off", it is on, so "true".
  413. return strtolower($_SERVER['HTTPS']) !== 'off';
  414. }
  415. /**
  416. * Can we use HTTPS? Then do! Only return false if it's not configured ("never").
  417. */
  418. static function useHTTPS()
  419. {
  420. return self::isHTTPS() || common_config('site', 'ssl') != 'never';
  421. }
  422. }
  423. class NoConfigException extends Exception
  424. {
  425. public $configFiles;
  426. function __construct($msg, $configFiles) {
  427. parent::__construct($msg);
  428. $this->configFiles = $configFiles;
  429. }
  430. }