gnusocial.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565
  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 true if now enabled, false if just loaded
  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. $key = 'disable-' . $name;
  90. if (common_config('plugins', $key)) {
  91. return false;
  92. }
  93. if (isset(self::$modules[$name])) {
  94. // We have already loaded this module. Don't try to
  95. // do it again with (possibly) different values.
  96. // Försten till kvarn får mala.
  97. return true;
  98. }
  99. $moduleclass = "{$name}Plugin";
  100. if (!class_exists($moduleclass)) {
  101. $files = [
  102. "local/plugins/{$moduleclass}.php",
  103. "local/plugins/{$name}/{$moduleclass}.php",
  104. "plugins/{$moduleclass}.php",
  105. "plugins/{$name}/{$moduleclass}.php"
  106. ];
  107. foreach ($files as $file) {
  108. $fullpath = INSTALLDIR . '/' . $file;
  109. if (@file_exists($fullpath)) {
  110. include_once $fullpath;
  111. break;
  112. }
  113. }
  114. if (!class_exists($moduleclass)) {
  115. throw new ServerException("Plugin $name not found.", 500);
  116. }
  117. }
  118. // Doesn't this $inst risk being garbage collected or something?
  119. // TODO: put into a static array that makes sure $inst isn't lost.
  120. $inst = new $moduleclass();
  121. foreach ($attrs as $aname => $avalue) {
  122. $inst->$aname = $avalue;
  123. }
  124. // Record activated modules for later display/config dump
  125. self::$modules[$name] = $attrs;
  126. return true;
  127. }
  128. public static function delPlugin($name)
  129. {
  130. //$name = ucfirst($name);
  131. // Remove our module if it was previously loaded
  132. if (isset(self::$modules[$name])) {
  133. unset(self::$modules[$name]);
  134. }
  135. // make sure addPlugin and addModule will avoid this
  136. common_config_set('plugins', 'disable-' . $name, true);
  137. return true;
  138. }
  139. /**
  140. * Get a list of activated modules in this process.
  141. * @return array of (string $name, array $args) pairs
  142. */
  143. public static function getActiveModules()
  144. {
  145. return self::$modules;
  146. }
  147. /**
  148. * Initialize, or re-initialize, GNU social global configuration
  149. * and modules.
  150. *
  151. * If switching site configurations during script execution, be
  152. * careful when working with leftover objects -- global settings
  153. * affect many things and they may not behave as you expected.
  154. *
  155. * @param $server optional web server hostname for picking config
  156. * @param $path optional URL path for picking config
  157. * @param $conffile optional configuration file path
  158. *
  159. * @throws ConfigException
  160. * @throws NoConfigException if config file can't be found
  161. * @throws ServerException
  162. */
  163. public static function init($server = null, $path = null, $conffile = null)
  164. {
  165. Router::clear();
  166. self::initDefaults($server, $path);
  167. self::loadConfigFile($conffile);
  168. $sprofile = common_config('site', 'profile');
  169. if (!empty($sprofile)) {
  170. self::loadSiteProfile($sprofile);
  171. }
  172. // Load settings from database; note we need autoload for this
  173. Config::loadSettings();
  174. self::fillConfigVoids();
  175. self::verifyLoadedConfig();
  176. self::initModules();
  177. }
  178. /**
  179. * Get identifier of the currently active site configuration
  180. * @return string
  181. */
  182. public static function currentSite()
  183. {
  184. return common_config('site', 'nickname');
  185. }
  186. /**
  187. * Change site configuration to site specified by nickname,
  188. * if set up via Status_network. If not, sites other than
  189. * the current will fail horribly.
  190. *
  191. * May throw exception or trigger a fatal error if the given
  192. * site is missing or configured incorrectly.
  193. *
  194. * @param string $nickname
  195. * @return bool
  196. * @throws ConfigException
  197. * @throws NoConfigException
  198. * @throws ServerException
  199. */
  200. public static function switchSite($nickname)
  201. {
  202. if ($nickname == self::currentSite()) {
  203. return true;
  204. }
  205. $sn = Status_network::getKV('nickname', $nickname);
  206. if (empty($sn)) {
  207. return false;
  208. //throw new Exception("No such site nickname '$nickname'");
  209. }
  210. $server = $sn->getServerName();
  211. self::init($server);
  212. }
  213. /**
  214. * Pull all local sites from status_network table.
  215. *
  216. * Behavior undefined if site is not configured via Status_network.
  217. *
  218. * @return array of nicknames
  219. */
  220. public static function findAllSites()
  221. {
  222. $sites = [];
  223. $sn = new Status_network();
  224. $sn->find();
  225. while ($sn->fetch()) {
  226. $sites[] = $sn->nickname;
  227. }
  228. return $sites;
  229. }
  230. /**
  231. * Fire initialization events for all instantiated modules.
  232. */
  233. protected static function initModules()
  234. {
  235. // User config may have already added some of these modules, with
  236. // maybe configured parameters. The self::addModule function will
  237. // ignore the new call if it has already been instantiated.
  238. // Load core modules
  239. foreach (common_config('plugins', 'core') as $name => $params) {
  240. call_user_func('self::addModule', $name, $params);
  241. }
  242. // Load default plugins
  243. foreach (common_config('plugins', 'default') as $name => $params) {
  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/util/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. }