You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 

664 lines
18 KiB

  1. <?php
  2. /**
  3. * Initialize some defaults needed for DokuWiki
  4. */
  5. use dokuwiki\Extension\PluginController;
  6. use dokuwiki\ErrorHandler;
  7. use dokuwiki\Input\Input;
  8. use dokuwiki\Extension\Event;
  9. use dokuwiki\Extension\EventHandler;
  10. /**
  11. * timing Dokuwiki execution
  12. *
  13. * @param integer $start
  14. *
  15. * @return mixed
  16. */
  17. function delta_time($start = 0)
  18. {
  19. return microtime(true) - ((float)$start);
  20. }
  21. define('DOKU_START_TIME', delta_time());
  22. global $config_cascade;
  23. $config_cascade = [];
  24. // if available load a preload config file
  25. $preload = fullpath(__DIR__) . '/preload.php';
  26. if (file_exists($preload)) include($preload);
  27. // define the include path
  28. if (!defined('DOKU_INC')) define('DOKU_INC', fullpath(__DIR__ . '/../') . '/');
  29. // define Plugin dir
  30. if (!defined('DOKU_PLUGIN')) define('DOKU_PLUGIN', DOKU_INC . 'lib/plugins/');
  31. // define config path (packagers may want to change this to /etc/dokuwiki/)
  32. if (!defined('DOKU_CONF')) define('DOKU_CONF', DOKU_INC . 'conf/');
  33. // check for error reporting override or set error reporting to sane values
  34. if (!defined('DOKU_E_LEVEL') && file_exists(DOKU_CONF . 'report_e_all')) {
  35. define('DOKU_E_LEVEL', E_ALL);
  36. }
  37. if (!defined('DOKU_E_LEVEL')) {
  38. error_reporting(E_ALL & ~E_NOTICE & ~E_DEPRECATED & ~E_STRICT);
  39. } else {
  40. error_reporting(DOKU_E_LEVEL);
  41. }
  42. // avoid caching issues #1594
  43. header('Vary: Cookie');
  44. // init memory caches
  45. global $cache_revinfo;
  46. $cache_revinfo = [];
  47. global $cache_wikifn;
  48. $cache_wikifn = [];
  49. global $cache_cleanid;
  50. $cache_cleanid = [];
  51. global $cache_authname;
  52. $cache_authname = [];
  53. global $cache_metadata;
  54. $cache_metadata = [];
  55. // always include 'inc/config_cascade.php'
  56. // previously in preload.php set fields of $config_cascade will be merged with the defaults
  57. include(DOKU_INC . 'inc/config_cascade.php');
  58. //prepare config array()
  59. global $conf;
  60. $conf = [];
  61. // load the global config file(s)
  62. foreach (['default', 'local', 'protected'] as $config_group) {
  63. if (empty($config_cascade['main'][$config_group])) continue;
  64. foreach ($config_cascade['main'][$config_group] as $config_file) {
  65. if (file_exists($config_file)) {
  66. include($config_file);
  67. }
  68. }
  69. }
  70. //prepare license array()
  71. global $license;
  72. $license = [];
  73. // load the license file(s)
  74. foreach (['default', 'local'] as $config_group) {
  75. if (empty($config_cascade['license'][$config_group])) continue;
  76. foreach ($config_cascade['license'][$config_group] as $config_file) {
  77. if (file_exists($config_file)) {
  78. include($config_file);
  79. }
  80. }
  81. }
  82. // set timezone (as in pre 5.3.0 days)
  83. date_default_timezone_set(@date_default_timezone_get());
  84. // define baseURL
  85. if (!defined('DOKU_REL')) define('DOKU_REL', getBaseURL(false));
  86. if (!defined('DOKU_URL')) define('DOKU_URL', getBaseURL(true));
  87. if (!defined('DOKU_BASE')) {
  88. if ($conf['canonical']) {
  89. define('DOKU_BASE', DOKU_URL);
  90. } else {
  91. define('DOKU_BASE', DOKU_REL);
  92. }
  93. }
  94. // define whitespace
  95. if (!defined('NL')) define('NL', "\n");
  96. if (!defined('DOKU_LF')) define('DOKU_LF', "\n");
  97. if (!defined('DOKU_TAB')) define('DOKU_TAB', "\t");
  98. // define cookie and session id, append server port when securecookie is configured FS#1664
  99. if (!defined('DOKU_COOKIE')) {
  100. $serverPort = $_SERVER['SERVER_PORT'] ?? '';
  101. define('DOKU_COOKIE', 'DW' . md5(DOKU_REL . (($conf['securecookie']) ? $serverPort : '')));
  102. unset($serverPort);
  103. }
  104. // define main script
  105. if (!defined('DOKU_SCRIPT')) define('DOKU_SCRIPT', 'doku.php');
  106. if (!defined('DOKU_TPL')) {
  107. /**
  108. * @deprecated 2012-10-13 replaced by more dynamic method
  109. * @see tpl_basedir()
  110. */
  111. define('DOKU_TPL', DOKU_BASE . 'lib/tpl/' . $conf['template'] . '/');
  112. }
  113. if (!defined('DOKU_TPLINC')) {
  114. /**
  115. * @deprecated 2012-10-13 replaced by more dynamic method
  116. * @see tpl_incdir()
  117. */
  118. define('DOKU_TPLINC', DOKU_INC . 'lib/tpl/' . $conf['template'] . '/');
  119. }
  120. // make session rewrites XHTML compliant
  121. @ini_set('arg_separator.output', '&amp;');
  122. // make sure global zlib does not interfere FS#1132
  123. @ini_set('zlib.output_compression', 'off');
  124. // increase PCRE backtrack limit
  125. @ini_set('pcre.backtrack_limit', '20971520');
  126. // enable gzip compression if supported
  127. $httpAcceptEncoding = $_SERVER['HTTP_ACCEPT_ENCODING'] ?? '';
  128. $conf['gzip_output'] &= (strpos($httpAcceptEncoding, 'gzip') !== false);
  129. global $ACT;
  130. if (
  131. $conf['gzip_output'] &&
  132. !defined('DOKU_DISABLE_GZIP_OUTPUT') &&
  133. function_exists('ob_gzhandler') &&
  134. // Disable compression when a (compressed) sitemap might be delivered
  135. // See https://bugs.dokuwiki.org/index.php?do=details&task_id=2576
  136. $ACT != 'sitemap'
  137. ) {
  138. ob_start('ob_gzhandler');
  139. }
  140. // init session
  141. if (!headers_sent() && !defined('NOSESSION')) {
  142. if (!defined('DOKU_SESSION_NAME')) define('DOKU_SESSION_NAME', "DokuWiki");
  143. if (!defined('DOKU_SESSION_LIFETIME')) define('DOKU_SESSION_LIFETIME', 0);
  144. if (!defined('DOKU_SESSION_PATH')) {
  145. $cookieDir = empty($conf['cookiedir']) ? DOKU_REL : $conf['cookiedir'];
  146. define('DOKU_SESSION_PATH', $cookieDir);
  147. }
  148. if (!defined('DOKU_SESSION_DOMAIN')) define('DOKU_SESSION_DOMAIN', '');
  149. // start the session
  150. init_session();
  151. // load left over messages
  152. if (isset($_SESSION[DOKU_COOKIE]['msg'])) {
  153. $MSG = $_SESSION[DOKU_COOKIE]['msg'];
  154. unset($_SESSION[DOKU_COOKIE]['msg']);
  155. }
  156. }
  157. // don't let cookies ever interfere with request vars
  158. $_REQUEST = array_merge($_GET, $_POST);
  159. // we don't want a purge URL to be digged
  160. if (isset($_REQUEST['purge']) && !empty($_SERVER['HTTP_REFERER'])) unset($_REQUEST['purge']);
  161. // precalculate file creation modes
  162. init_creationmodes();
  163. // make real paths and check them
  164. init_paths();
  165. init_files();
  166. // setup plugin controller class (can be overwritten in preload.php)
  167. global $plugin_controller_class, $plugin_controller;
  168. if (empty($plugin_controller_class)) $plugin_controller_class = PluginController::class;
  169. // autoloader
  170. require_once(DOKU_INC . 'inc/load.php');
  171. // from now on everything is an exception
  172. ErrorHandler::register();
  173. // disable gzip if not available
  174. define('DOKU_HAS_BZIP', function_exists('bzopen'));
  175. define('DOKU_HAS_GZIP', function_exists('gzopen'));
  176. if ($conf['compression'] == 'bz2' && !DOKU_HAS_BZIP) {
  177. $conf['compression'] = 'gz';
  178. }
  179. if ($conf['compression'] == 'gz' && !DOKU_HAS_GZIP) {
  180. $conf['compression'] = 0;
  181. }
  182. // input handle class
  183. global $INPUT;
  184. $INPUT = new Input();
  185. // initialize plugin controller
  186. $plugin_controller = new $plugin_controller_class();
  187. // initialize the event handler
  188. global $EVENT_HANDLER;
  189. $EVENT_HANDLER = new EventHandler();
  190. $local = $conf['lang'];
  191. Event::createAndTrigger('INIT_LANG_LOAD', $local, 'init_lang', true);
  192. // setup authentication system
  193. if (!defined('NOSESSION')) {
  194. auth_setup();
  195. }
  196. // setup mail system
  197. mail_setup();
  198. $nil = null;
  199. Event::createAndTrigger('DOKUWIKI_INIT_DONE', $nil, null, false);
  200. /**
  201. * Initializes the session
  202. *
  203. * Makes sure the passed session cookie is valid, invalid ones are ignored an a new session ID is issued
  204. *
  205. * @link http://stackoverflow.com/a/33024310/172068
  206. * @link http://php.net/manual/en/session.configuration.php#ini.session.sid-length
  207. */
  208. function init_session()
  209. {
  210. global $conf;
  211. session_name(DOKU_SESSION_NAME);
  212. session_set_cookie_params([
  213. 'lifetime' => DOKU_SESSION_LIFETIME,
  214. 'path' => DOKU_SESSION_PATH,
  215. 'domain' => DOKU_SESSION_DOMAIN,
  216. 'secure' => ($conf['securecookie'] && is_ssl()),
  217. 'httponly' => true,
  218. 'samesite' => 'Lax',
  219. ]);
  220. // make sure the session cookie contains a valid session ID
  221. if (isset($_COOKIE[DOKU_SESSION_NAME]) && !preg_match('/^[-,a-zA-Z0-9]{22,256}$/', $_COOKIE[DOKU_SESSION_NAME])) {
  222. unset($_COOKIE[DOKU_SESSION_NAME]);
  223. }
  224. session_start();
  225. }
  226. /**
  227. * Checks paths from config file
  228. */
  229. function init_paths()
  230. {
  231. global $conf;
  232. $paths = [
  233. 'datadir' => 'pages',
  234. 'olddir' => 'attic',
  235. 'mediadir' => 'media',
  236. 'mediaolddir' => 'media_attic',
  237. 'metadir' => 'meta',
  238. 'mediametadir' => 'media_meta',
  239. 'cachedir' => 'cache',
  240. 'indexdir' => 'index',
  241. 'lockdir' => 'locks',
  242. 'tmpdir' => 'tmp',
  243. 'logdir' => 'log',
  244. ];
  245. foreach ($paths as $c => $p) {
  246. $path = empty($conf[$c]) ? $conf['savedir'] . '/' . $p : $conf[$c];
  247. $conf[$c] = init_path($path);
  248. if (empty($conf[$c])) {
  249. $path = fullpath($path);
  250. nice_die("The $c ('$p') at $path is not found, isn't accessible or writable.
  251. You should check your config and permission settings.
  252. Or maybe you want to <a href=\"install.php\">run the
  253. installer</a>?");
  254. }
  255. }
  256. // path to old changelog only needed for upgrading
  257. $conf['changelog_old'] = init_path(
  258. $conf['changelog'] ?? $conf['savedir'] . '/changes.log'
  259. );
  260. if ($conf['changelog_old'] == '') {
  261. unset($conf['changelog_old']);
  262. }
  263. // hardcoded changelog because it is now a cache that lives in meta
  264. $conf['changelog'] = $conf['metadir'] . '/_dokuwiki.changes';
  265. $conf['media_changelog'] = $conf['metadir'] . '/_media.changes';
  266. }
  267. /**
  268. * Load the language strings
  269. *
  270. * @param string $langCode language code, as passed by event handler
  271. */
  272. function init_lang($langCode)
  273. {
  274. //prepare language array
  275. global $lang, $config_cascade;
  276. $lang = [];
  277. //load the language files
  278. require(DOKU_INC . 'inc/lang/en/lang.php');
  279. foreach ($config_cascade['lang']['core'] as $config_file) {
  280. if (file_exists($config_file . 'en/lang.php')) {
  281. include($config_file . 'en/lang.php');
  282. }
  283. }
  284. if ($langCode && $langCode != 'en') {
  285. if (file_exists(DOKU_INC . "inc/lang/$langCode/lang.php")) {
  286. require(DOKU_INC . "inc/lang/$langCode/lang.php");
  287. }
  288. foreach ($config_cascade['lang']['core'] as $config_file) {
  289. if (file_exists($config_file . "$langCode/lang.php")) {
  290. include($config_file . "$langCode/lang.php");
  291. }
  292. }
  293. }
  294. }
  295. /**
  296. * Checks the existence of certain files and creates them if missing.
  297. */
  298. function init_files()
  299. {
  300. global $conf;
  301. $files = [$conf['indexdir'] . '/page.idx'];
  302. foreach ($files as $file) {
  303. if (!file_exists($file)) {
  304. $fh = @fopen($file, 'a');
  305. if ($fh) {
  306. fclose($fh);
  307. if ($conf['fperm']) chmod($file, $conf['fperm']);
  308. } else {
  309. nice_die("$file is not writable. Check your permissions settings!");
  310. }
  311. }
  312. }
  313. }
  314. /**
  315. * Returns absolute path
  316. *
  317. * This tries the given path first, then checks in DOKU_INC.
  318. * Check for accessibility on directories as well.
  319. *
  320. * @author Andreas Gohr <andi@splitbrain.org>
  321. *
  322. * @param string $path
  323. *
  324. * @return bool|string
  325. */
  326. function init_path($path)
  327. {
  328. // check existence
  329. $p = fullpath($path);
  330. if (!file_exists($p)) {
  331. $p = fullpath(DOKU_INC . $path);
  332. if (!file_exists($p)) {
  333. return '';
  334. }
  335. }
  336. // check writability
  337. if (!@is_writable($p)) {
  338. return '';
  339. }
  340. // check accessability (execute bit) for directories
  341. if (@is_dir($p) && !file_exists("$p/.")) {
  342. return '';
  343. }
  344. return $p;
  345. }
  346. /**
  347. * Sets the internal config values fperm and dperm which, when set,
  348. * will be used to change the permission of a newly created dir or
  349. * file with chmod. Considers the influence of the system's umask
  350. * setting the values only if needed.
  351. */
  352. function init_creationmodes()
  353. {
  354. global $conf;
  355. // Legacy support for old umask/dmask scheme
  356. unset($conf['dmask']);
  357. unset($conf['fmask']);
  358. unset($conf['umask']);
  359. $conf['fperm'] = false;
  360. $conf['dperm'] = false;
  361. // get system umask, fallback to 0 if none available
  362. $umask = @umask();
  363. if (!$umask) $umask = 0000;
  364. // check what is set automatically by the system on file creation
  365. // and set the fperm param if it's not what we want
  366. $auto_fmode = 0666 & ~$umask;
  367. if ($auto_fmode != $conf['fmode']) $conf['fperm'] = $conf['fmode'];
  368. // check what is set automatically by the system on directory creation
  369. // and set the dperm param if it's not what we want.
  370. $auto_dmode = 0777 & ~$umask;
  371. if ($auto_dmode != $conf['dmode']) $conf['dperm'] = $conf['dmode'];
  372. }
  373. /**
  374. * Returns the full absolute URL to the directory where
  375. * DokuWiki is installed in (includes a trailing slash)
  376. *
  377. * !! Can not access $_SERVER values through $INPUT
  378. * !! here as this function is called before $INPUT is
  379. * !! initialized.
  380. *
  381. * @author Andreas Gohr <andi@splitbrain.org>
  382. *
  383. * @param null|bool $abs Return an absolute URL? (null defaults to $conf['canonical'])
  384. *
  385. * @return string
  386. */
  387. function getBaseURL($abs = null)
  388. {
  389. global $conf;
  390. $abs ??= $conf['canonical'];
  391. if (!empty($conf['basedir'])) {
  392. $dir = $conf['basedir'];
  393. } elseif (substr($_SERVER['SCRIPT_NAME'], -4) == '.php') {
  394. $dir = dirname($_SERVER['SCRIPT_NAME']);
  395. } elseif (substr($_SERVER['PHP_SELF'], -4) == '.php') {
  396. $dir = dirname($_SERVER['PHP_SELF']);
  397. } elseif ($_SERVER['DOCUMENT_ROOT'] && $_SERVER['SCRIPT_FILENAME']) {
  398. $dir = preg_replace(
  399. '/^' . preg_quote($_SERVER['DOCUMENT_ROOT'], '/') . '/',
  400. '',
  401. $_SERVER['SCRIPT_FILENAME']
  402. );
  403. $dir = dirname('/' . $dir);
  404. } else {
  405. $dir = ''; //probably wrong, but we assume it's in the root
  406. }
  407. $dir = str_replace('\\', '/', $dir); // bugfix for weird WIN behaviour
  408. $dir = preg_replace('#//+#', '/', "/$dir/"); // ensure leading and trailing slashes
  409. //handle script in lib/exe dir
  410. $dir = preg_replace('!lib/exe/$!', '', $dir);
  411. //handle script in lib/plugins dir
  412. $dir = preg_replace('!lib/plugins/.*$!', '', $dir);
  413. //finish here for relative URLs
  414. if (!$abs) return $dir;
  415. //use config if available, trim any slash from end of baseurl to avoid multiple consecutive slashes in the path
  416. if (!empty($conf['baseurl'])) return rtrim($conf['baseurl'], '/') . $dir;
  417. //split hostheader into host and port
  418. if (isset($_SERVER['HTTP_HOST'])) {
  419. if (
  420. (!empty($conf['trustedproxy'])) && isset($_SERVER['HTTP_X_FORWARDED_HOST'])
  421. && preg_match('/' . $conf['trustedproxy'] . '/', $_SERVER['REMOTE_ADDR'])
  422. ) {
  423. $cur_host = $_SERVER['HTTP_X_FORWARDED_HOST'];
  424. } else {
  425. $cur_host = $_SERVER['HTTP_HOST'];
  426. }
  427. $parsed_host = parse_url('http://' . $cur_host);
  428. $host = $parsed_host['host'] ?? '';
  429. $port = $parsed_host['port'] ?? '';
  430. } elseif (isset($_SERVER['SERVER_NAME'])) {
  431. $parsed_host = parse_url('http://' . $_SERVER['SERVER_NAME']);
  432. $host = $parsed_host['host'] ?? '';
  433. $port = $parsed_host['port'] ?? '';
  434. } else {
  435. $host = php_uname('n');
  436. $port = '';
  437. }
  438. if (!is_ssl()) {
  439. $proto = 'http://';
  440. if ($port == '80') {
  441. $port = '';
  442. }
  443. } else {
  444. $proto = 'https://';
  445. if ($port == '443') {
  446. $port = '';
  447. }
  448. }
  449. if ($port !== '') $port = ':' . $port;
  450. return $proto . $host . $port . $dir;
  451. }
  452. /**
  453. * Check if accessed via HTTPS
  454. *
  455. * Apache leaves ,$_SERVER['HTTPS'] empty when not available, IIS sets it to 'off'.
  456. * 'false' and 'disabled' are just guessing
  457. *
  458. * @returns bool true when SSL is active
  459. */
  460. function is_ssl()
  461. {
  462. global $conf;
  463. // check if we are behind a reverse proxy
  464. if (
  465. (!empty($conf['trustedproxy'])) && isset($_SERVER['HTTP_X_FORWARDED_PROTO'])
  466. && preg_match('/' . $conf['trustedproxy'] . '/', $_SERVER['REMOTE_ADDR'])
  467. && ($_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https')
  468. ) {
  469. return true;
  470. }
  471. if (preg_match('/^(|off|false|disabled)$/i', $_SERVER['HTTPS'] ?? 'off')) {
  472. return false;
  473. }
  474. return true;
  475. }
  476. /**
  477. * checks it is windows OS
  478. * @return bool
  479. */
  480. function isWindows()
  481. {
  482. return strtoupper(substr(PHP_OS, 0, 3)) === 'WIN';
  483. }
  484. /**
  485. * print a nice message even if no styles are loaded yet.
  486. *
  487. * @param integer|string $msg
  488. */
  489. function nice_die($msg)
  490. {
  491. echo<<<EOT
  492. <!DOCTYPE html>
  493. <html>
  494. <head><title>DokuWiki Setup Error</title></head>
  495. <body style="font-family: Arial, sans-serif">
  496. <div style="width:60%; margin: auto; background-color: #fcc;
  497. border: 1px solid #faa; padding: 0.5em 1em;">
  498. <h1 style="font-size: 120%">DokuWiki Setup Error</h1>
  499. <p>$msg</p>
  500. </div>
  501. </body>
  502. </html>
  503. EOT;
  504. if (defined('DOKU_UNITTEST')) {
  505. throw new RuntimeException('nice_die: ' . $msg);
  506. }
  507. exit(1);
  508. }
  509. /**
  510. * A realpath() replacement
  511. *
  512. * This function behaves similar to PHP's realpath() but does not resolve
  513. * symlinks or accesses upper directories
  514. *
  515. * @author Andreas Gohr <andi@splitbrain.org>
  516. * @author <richpageau at yahoo dot co dot uk>
  517. * @link http://php.net/manual/en/function.realpath.php#75992
  518. *
  519. * @param string $path
  520. * @param bool $exists
  521. *
  522. * @return bool|string
  523. */
  524. function fullpath($path, $exists = false)
  525. {
  526. static $run = 0;
  527. $root = '';
  528. $iswin = (isWindows() || !empty($GLOBALS['DOKU_UNITTEST_ASSUME_WINDOWS']));
  529. // find the (indestructable) root of the path - keeps windows stuff intact
  530. if ($path[0] == '/') {
  531. $root = '/';
  532. } elseif ($iswin) {
  533. // match drive letter and UNC paths
  534. if (preg_match('!^([a-zA-z]:)(.*)!', $path, $match)) {
  535. $root = $match[1] . '/';
  536. $path = $match[2];
  537. } elseif (preg_match('!^(\\\\\\\\[^\\\\/]+\\\\[^\\\\/]+[\\\\/])(.*)!', $path, $match)) {
  538. $root = $match[1];
  539. $path = $match[2];
  540. }
  541. }
  542. $path = str_replace('\\', '/', $path);
  543. // if the given path wasn't absolute already, prepend the script path and retry
  544. if (!$root) {
  545. $base = dirname($_SERVER['SCRIPT_FILENAME']);
  546. $path = $base . '/' . $path;
  547. if ($run == 0) { // avoid endless recursion when base isn't absolute for some reason
  548. $run++;
  549. return fullpath($path, $exists);
  550. }
  551. }
  552. $run = 0;
  553. // canonicalize
  554. $path = explode('/', $path);
  555. $newpath = [];
  556. foreach ($path as $p) {
  557. if ($p === '' || $p === '.') continue;
  558. if ($p === '..') {
  559. array_pop($newpath);
  560. continue;
  561. }
  562. $newpath[] = $p;
  563. }
  564. $finalpath = $root . implode('/', $newpath);
  565. // check for existence when needed (except when unit testing)
  566. if ($exists && !defined('DOKU_UNITTEST') && !file_exists($finalpath)) {
  567. return false;
  568. }
  569. return $finalpath;
  570. }