gnusocial.php 15 KB

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