gnusocial.php 17 KB

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