gnusocial.php 15 KB

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