gnusocial.php 18 KB

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