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.
 
 
 
 
 

593 lines
19 KiB

  1. <?php
  2. /**
  3. * Information and debugging functions
  4. *
  5. * @license GPL 2 (http://www.gnu.org/licenses/gpl.html)
  6. * @author Andreas Gohr <andi@splitbrain.org>
  7. */
  8. use dokuwiki\Extension\AuthPlugin;
  9. use dokuwiki\Extension\Event;
  10. use dokuwiki\Utf8\PhpString;
  11. use dokuwiki\Debug\DebugHelper;
  12. use dokuwiki\HTTP\DokuHTTPClient;
  13. use dokuwiki\Logger;
  14. if (!defined('DOKU_MESSAGEURL')) {
  15. if (in_array('ssl', stream_get_transports())) {
  16. define('DOKU_MESSAGEURL', 'https://update.dokuwiki.org/check/');
  17. } else {
  18. define('DOKU_MESSAGEURL', 'http://update.dokuwiki.org/check/');
  19. }
  20. }
  21. /**
  22. * Check for new messages from upstream
  23. *
  24. * @author Andreas Gohr <andi@splitbrain.org>
  25. */
  26. function checkUpdateMessages()
  27. {
  28. global $conf;
  29. global $INFO;
  30. global $updateVersion;
  31. if (!$conf['updatecheck']) return;
  32. if ($conf['useacl'] && !$INFO['ismanager']) return;
  33. $cf = getCacheName($updateVersion, '.updmsg');
  34. $lm = @filemtime($cf);
  35. $is_http = !str_starts_with(DOKU_MESSAGEURL, 'https');
  36. // check if new messages needs to be fetched
  37. if ($lm < time() - (60 * 60 * 24) || $lm < @filemtime(DOKU_INC . DOKU_SCRIPT)) {
  38. @touch($cf);
  39. Logger::debug(
  40. sprintf(
  41. 'checkUpdateMessages(): downloading messages to %s%s',
  42. $cf,
  43. $is_http ? ' (without SSL)' : ' (with SSL)'
  44. )
  45. );
  46. $http = new DokuHTTPClient();
  47. $http->timeout = 12;
  48. $resp = $http->get(DOKU_MESSAGEURL . $updateVersion);
  49. if (is_string($resp) && ($resp == '' || str_ends_with(trim($resp), '%'))) {
  50. // basic sanity check that this is either an empty string response (ie "no messages")
  51. // or it looks like one of our messages, not WiFi login or other interposed response
  52. io_saveFile($cf, $resp);
  53. } else {
  54. Logger::debug("checkUpdateMessages(): unexpected HTTP response received", $http->error);
  55. }
  56. } else {
  57. Logger::debug("checkUpdateMessages(): messages up to date");
  58. }
  59. $data = io_readFile($cf);
  60. // show messages through the usual message mechanism
  61. $msgs = explode("\n%\n", $data);
  62. foreach ($msgs as $msg) {
  63. if ($msg) msg($msg, 2);
  64. }
  65. }
  66. /**
  67. * Return DokuWiki's version (split up in date and type)
  68. *
  69. * @author Andreas Gohr <andi@splitbrain.org>
  70. */
  71. function getVersionData()
  72. {
  73. $version = [];
  74. //import version string
  75. if (file_exists(DOKU_INC . 'VERSION')) {
  76. //official release
  77. $version['date'] = trim(io_readFile(DOKU_INC . 'VERSION'));
  78. $version['type'] = 'Release';
  79. } elseif (is_dir(DOKU_INC . '.git')) {
  80. $version['type'] = 'Git';
  81. $version['date'] = 'unknown';
  82. // First try to get date and commit hash by calling Git
  83. if (function_exists('shell_exec')) {
  84. $commitInfo = shell_exec("git log -1 --pretty=format:'%h %cd' --date=short");
  85. if ($commitInfo) {
  86. [$version['sha'], $date] = explode(' ', $commitInfo);
  87. $version['date'] = hsc($date);
  88. return $version;
  89. }
  90. }
  91. // we cannot use git on the shell -- let's do it manually!
  92. if (file_exists(DOKU_INC . '.git/HEAD')) {
  93. $headCommit = trim(file_get_contents(DOKU_INC . '.git/HEAD'));
  94. if (strpos($headCommit, 'ref: ') === 0) {
  95. // it is something like `ref: refs/heads/master`
  96. $headCommit = substr($headCommit, 5);
  97. $pathToHead = DOKU_INC . '.git/' . $headCommit;
  98. if (file_exists($pathToHead)) {
  99. $headCommit = trim(file_get_contents($pathToHead));
  100. } else {
  101. $packedRefs = file_get_contents(DOKU_INC . '.git/packed-refs');
  102. if (!preg_match("~([[:xdigit:]]+) $headCommit~", $packedRefs, $matches)) {
  103. # ref not found in pack file
  104. return $version;
  105. }
  106. $headCommit = $matches[1];
  107. }
  108. }
  109. // At this point $headCommit is a SHA
  110. $version['sha'] = $headCommit;
  111. // Get commit date from Git object
  112. $subDir = substr($headCommit, 0, 2);
  113. $fileName = substr($headCommit, 2);
  114. $gitCommitObject = DOKU_INC . ".git/objects/$subDir/$fileName";
  115. if (file_exists($gitCommitObject) && function_exists('zlib_decode')) {
  116. $commit = zlib_decode(file_get_contents($gitCommitObject));
  117. $committerLine = explode("\n", $commit)[3];
  118. $committerData = explode(' ', $committerLine);
  119. end($committerData);
  120. $ts = prev($committerData);
  121. if ($ts && $date = date('Y-m-d', $ts)) {
  122. $version['date'] = $date;
  123. }
  124. }
  125. }
  126. } else {
  127. global $updateVersion;
  128. $version['date'] = 'update version ' . $updateVersion;
  129. $version['type'] = 'snapshot?';
  130. }
  131. return $version;
  132. }
  133. /**
  134. * Return DokuWiki's version
  135. *
  136. * This returns the version in the form "Type Date (SHA)". Where type is either
  137. * "Release" or "Git" and date is the date of the release or the date of the
  138. * last commit. SHA is the short SHA of the last commit - this is only added on
  139. * git checkouts.
  140. *
  141. * If no version can be determined "snapshot? update version XX" is returned.
  142. * Where XX represents the update version number set in doku.php.
  143. *
  144. * @author Anika Henke <anika@selfthinker.org>
  145. * @return string The version string e.g. "Release 2023-04-04a"
  146. */
  147. function getVersion()
  148. {
  149. $version = getVersionData();
  150. $sha = empty($version['sha']) ? '' : ' (' . $version['sha'] . ')';
  151. return $version['type'] . ' ' . $version['date'] . $sha;
  152. }
  153. /**
  154. * Run a few sanity checks
  155. *
  156. * @author Andreas Gohr <andi@splitbrain.org>
  157. */
  158. function check()
  159. {
  160. global $conf;
  161. global $INFO;
  162. /* @var Input $INPUT */
  163. global $INPUT;
  164. if ($INFO['isadmin'] || $INFO['ismanager']) {
  165. msg('DokuWiki version: ' . getVersion(), 1);
  166. if (version_compare(phpversion(), '7.4.0', '<')) {
  167. msg('Your PHP version is too old (' . phpversion() . ' vs. 7.4+ needed)', -1);
  168. } else {
  169. msg('PHP version ' . phpversion(), 1);
  170. }
  171. } elseif (version_compare(phpversion(), '7.4.0', '<')) {
  172. msg('Your PHP version is too old', -1);
  173. }
  174. $mem = php_to_byte(ini_get('memory_limit'));
  175. if ($mem) {
  176. if ($mem === -1) {
  177. msg('PHP memory is unlimited', 1);
  178. } elseif ($mem < 16_777_216) {
  179. msg('PHP is limited to less than 16MB RAM (' . filesize_h($mem) . ').
  180. Increase memory_limit in php.ini', -1);
  181. } elseif ($mem < 20_971_520) {
  182. msg('PHP is limited to less than 20MB RAM (' . filesize_h($mem) . '),
  183. you might encounter problems with bigger pages. Increase memory_limit in php.ini', -1);
  184. } elseif ($mem < 33_554_432) {
  185. msg('PHP is limited to less than 32MB RAM (' . filesize_h($mem) . '),
  186. but that should be enough in most cases. If not, increase memory_limit in php.ini', 0);
  187. } else {
  188. msg('More than 32MB RAM (' . filesize_h($mem) . ') available.', 1);
  189. }
  190. }
  191. if (is_writable($conf['changelog'])) {
  192. msg('Changelog is writable', 1);
  193. } elseif (file_exists($conf['changelog'])) {
  194. msg('Changelog is not writable', -1);
  195. }
  196. if (isset($conf['changelog_old']) && file_exists($conf['changelog_old'])) {
  197. msg('Old changelog exists', 0);
  198. }
  199. if (file_exists($conf['changelog'] . '_failed')) {
  200. msg('Importing old changelog failed', -1);
  201. } elseif (file_exists($conf['changelog'] . '_importing')) {
  202. msg('Importing old changelog now.', 0);
  203. } elseif (file_exists($conf['changelog'] . '_import_ok')) {
  204. msg('Old changelog imported', 1);
  205. if (!plugin_isdisabled('importoldchangelog')) {
  206. msg('Importoldchangelog plugin not disabled after import', -1);
  207. }
  208. }
  209. if (is_writable(DOKU_CONF)) {
  210. msg('conf directory is writable', 1);
  211. } else {
  212. msg('conf directory is not writable', -1);
  213. }
  214. if ($conf['authtype'] == 'plain') {
  215. global $config_cascade;
  216. if (is_writable($config_cascade['plainauth.users']['default'])) {
  217. msg('conf/users.auth.php is writable', 1);
  218. } else {
  219. msg('conf/users.auth.php is not writable', 0);
  220. }
  221. }
  222. if (function_exists('mb_strpos')) {
  223. if (defined('UTF8_NOMBSTRING')) {
  224. msg('mb_string extension is available but will not be used', 0);
  225. } else {
  226. msg('mb_string extension is available and will be used', 1);
  227. if (ini_get('mbstring.func_overload') != 0) {
  228. msg('mb_string function overloading is enabled, this will cause problems and should be disabled', -1);
  229. }
  230. }
  231. } else {
  232. msg('mb_string extension not available - PHP only replacements will be used', 0);
  233. }
  234. if (!UTF8_PREGSUPPORT) {
  235. msg('PHP is missing UTF-8 support in Perl-Compatible Regular Expressions (PCRE)', -1);
  236. }
  237. if (!UTF8_PROPERTYSUPPORT) {
  238. msg('PHP is missing Unicode properties support in Perl-Compatible Regular Expressions (PCRE)', -1);
  239. }
  240. $loc = setlocale(LC_ALL, 0);
  241. if (!$loc) {
  242. msg('No valid locale is set for your PHP setup. You should fix this', -1);
  243. } elseif (stripos($loc, 'utf') === false) {
  244. msg('Your locale <code>' . hsc($loc) . '</code> seems not to be a UTF-8 locale,
  245. you should fix this if you encounter problems.', 0);
  246. } else {
  247. msg('Valid locale ' . hsc($loc) . ' found.', 1);
  248. }
  249. if ($conf['allowdebug']) {
  250. msg('Debugging support is enabled. If you don\'t need it you should set $conf[\'allowdebug\'] = 0', -1);
  251. } else {
  252. msg('Debugging support is disabled', 1);
  253. }
  254. if (!empty($INFO['userinfo']['name'])) {
  255. msg(sprintf(
  256. "You are currently logged in as %s (%s)",
  257. $INPUT->server->str('REMOTE_USER'),
  258. $INFO['userinfo']['name']
  259. ), 0);
  260. msg('You are part of the groups ' . implode(', ', $INFO['userinfo']['grps']), 0);
  261. } else {
  262. msg('You are currently not logged in', 0);
  263. }
  264. msg('Your current permission for this page is ' . $INFO['perm'], 0);
  265. if (file_exists($INFO['filepath']) && is_writable($INFO['filepath'])) {
  266. msg('The current page is writable by the webserver', 1);
  267. } elseif (!file_exists($INFO['filepath']) && is_writable(dirname($INFO['filepath']))) {
  268. msg('The current page can be created by the webserver', 1);
  269. } else {
  270. msg('The current page is not writable by the webserver', -1);
  271. }
  272. if ($INFO['writable']) {
  273. msg('The current page is writable by you', 1);
  274. } else {
  275. msg('The current page is not writable by you', -1);
  276. }
  277. // Check for corrupted search index
  278. $lengths = idx_listIndexLengths();
  279. $index_corrupted = false;
  280. foreach ($lengths as $length) {
  281. if (count(idx_getIndex('w', $length)) !== count(idx_getIndex('i', $length))) {
  282. $index_corrupted = true;
  283. break;
  284. }
  285. }
  286. foreach (idx_getIndex('metadata', '') as $index) {
  287. if (count(idx_getIndex($index . '_w', '')) !== count(idx_getIndex($index . '_i', ''))) {
  288. $index_corrupted = true;
  289. break;
  290. }
  291. }
  292. if ($index_corrupted) {
  293. msg(
  294. 'The search index is corrupted. It might produce wrong results and most
  295. probably needs to be rebuilt. See
  296. <a href="https://www.dokuwiki.org/faq:searchindex">faq:searchindex</a>
  297. for ways to rebuild the search index.',
  298. -1
  299. );
  300. } elseif (!empty($lengths)) {
  301. msg('The search index seems to be working', 1);
  302. } else {
  303. msg(
  304. 'The search index is empty. See
  305. <a href="https://www.dokuwiki.org/faq:searchindex">faq:searchindex</a>
  306. for help on how to fix the search index. If the default indexer
  307. isn\'t used or the wiki is actually empty this is normal.'
  308. );
  309. }
  310. // rough time check
  311. $http = new DokuHTTPClient();
  312. $http->max_redirect = 0;
  313. $http->timeout = 3;
  314. $http->sendRequest('https://www.dokuwiki.org', '', 'HEAD');
  315. $now = time();
  316. if (isset($http->resp_headers['date'])) {
  317. $time = strtotime($http->resp_headers['date']);
  318. $diff = $time - $now;
  319. if (abs($diff) < 4) {
  320. msg("Server time seems to be okay. Diff: {$diff}s", 1);
  321. } else {
  322. msg("Your server's clock seems to be out of sync!
  323. Consider configuring a sync with a NTP server. Diff: {$diff}s");
  324. }
  325. }
  326. }
  327. /**
  328. * Display a message to the user
  329. *
  330. * If HTTP headers were not sent yet the message is added
  331. * to the global message array else it's printed directly
  332. * using html_msgarea()
  333. *
  334. * Triggers INFOUTIL_MSG_SHOW
  335. *
  336. * @param string $message
  337. * @param int $lvl -1 = error, 0 = info, 1 = success, 2 = notify
  338. * @param string $line line number
  339. * @param string $file file number
  340. * @param int $allow who's allowed to see the message, see MSG_* constants
  341. * @see html_msgarea()
  342. */
  343. function msg($message, $lvl = 0, $line = '', $file = '', $allow = MSG_PUBLIC)
  344. {
  345. global $MSG, $MSG_shown;
  346. static $errors = [
  347. -1 => 'error',
  348. 0 => 'info',
  349. 1 => 'success',
  350. 2 => 'notify',
  351. ];
  352. $msgdata = [
  353. 'msg' => $message,
  354. 'lvl' => $errors[$lvl],
  355. 'allow' => $allow,
  356. 'line' => $line,
  357. 'file' => $file,
  358. ];
  359. $evt = new Event('INFOUTIL_MSG_SHOW', $msgdata);
  360. if ($evt->advise_before()) {
  361. /* Show msg normally - event could suppress message show */
  362. if ($msgdata['line'] || $msgdata['file']) {
  363. $basename = PhpString::basename($msgdata['file']);
  364. $msgdata['msg'] .= ' [' . $basename . ':' . $msgdata['line'] . ']';
  365. }
  366. if (!isset($MSG)) $MSG = [];
  367. $MSG[] = $msgdata;
  368. if (isset($MSG_shown) || headers_sent()) {
  369. if (function_exists('html_msgarea')) {
  370. html_msgarea();
  371. } else {
  372. echo "ERROR(" . $msgdata['lvl'] . ") " . $msgdata['msg'] . "\n";
  373. }
  374. unset($GLOBALS['MSG']);
  375. }
  376. }
  377. $evt->advise_after();
  378. unset($evt);
  379. }
  380. /**
  381. * Determine whether the current user is allowed to view the message
  382. * in the $msg data structure
  383. *
  384. * @param array $msg dokuwiki msg structure:
  385. * msg => string, the message;
  386. * lvl => int, level of the message (see msg() function);
  387. * allow => int, flag used to determine who is allowed to see the message, see MSG_* constants
  388. * @return bool
  389. */
  390. function info_msg_allowed($msg)
  391. {
  392. global $INFO, $auth;
  393. // is the message public? - everyone and anyone can see it
  394. if (empty($msg['allow']) || ($msg['allow'] == MSG_PUBLIC)) return true;
  395. // restricted msg, but no authentication
  396. if (!$auth instanceof AuthPlugin) return false;
  397. switch ($msg['allow']) {
  398. case MSG_USERS_ONLY:
  399. return !empty($INFO['userinfo']);
  400. case MSG_MANAGERS_ONLY:
  401. return $INFO['ismanager'];
  402. case MSG_ADMINS_ONLY:
  403. return $INFO['isadmin'];
  404. default:
  405. trigger_error(
  406. 'invalid msg allow restriction. msg="' . $msg['msg'] . '" allow=' . $msg['allow'] . '"',
  407. E_USER_WARNING
  408. );
  409. return $INFO['isadmin'];
  410. }
  411. }
  412. /**
  413. * print debug messages
  414. *
  415. * little function to print the content of a var
  416. *
  417. * @param string $msg
  418. * @param bool $hidden
  419. *
  420. * @author Andreas Gohr <andi@splitbrain.org>
  421. */
  422. function dbg($msg, $hidden = false)
  423. {
  424. if ($hidden) {
  425. echo "<!--\n";
  426. print_r($msg);
  427. echo "\n-->";
  428. } else {
  429. echo '<pre class="dbg">';
  430. echo hsc(print_r($msg, true));
  431. echo '</pre>';
  432. }
  433. }
  434. /**
  435. * Print info to debug log file
  436. *
  437. * @param string $msg
  438. * @param string $header
  439. *
  440. * @author Andreas Gohr <andi@splitbrain.org>
  441. * @deprecated 2020-08-13
  442. */
  443. function dbglog($msg, $header = '')
  444. {
  445. dbg_deprecated('\\dokuwiki\\Logger');
  446. // was the msg as single line string? use it as header
  447. if ($header === '' && is_string($msg) && strpos($msg, "\n") === false) {
  448. $header = $msg;
  449. $msg = '';
  450. }
  451. Logger::getInstance(Logger::LOG_DEBUG)->log(
  452. $header,
  453. $msg
  454. );
  455. }
  456. /**
  457. * Log accesses to deprecated fucntions to the debug log
  458. *
  459. * @param string $alternative The function or method that should be used instead
  460. * @triggers INFO_DEPRECATION_LOG
  461. */
  462. function dbg_deprecated($alternative = '')
  463. {
  464. DebugHelper::dbgDeprecatedFunction($alternative, 2);
  465. }
  466. /**
  467. * Print a reversed, prettyprinted backtrace
  468. *
  469. * @author Gary Owen <gary_owen@bigfoot.com>
  470. */
  471. function dbg_backtrace()
  472. {
  473. // Get backtrace
  474. $backtrace = debug_backtrace();
  475. // Unset call to debug_print_backtrace
  476. array_shift($backtrace);
  477. // Iterate backtrace
  478. $calls = [];
  479. $depth = count($backtrace) - 1;
  480. foreach ($backtrace as $i => $call) {
  481. if (isset($call['file'])) {
  482. $location = $call['file'] . ':' . ($call['line'] ?? '0');
  483. } else {
  484. $location = '[anonymous]';
  485. }
  486. if (isset($call['class'])) {
  487. $function = $call['class'] . $call['type'] . $call['function'];
  488. } else {
  489. $function = $call['function'];
  490. }
  491. $params = [];
  492. if (isset($call['args'])) {
  493. foreach ($call['args'] as $arg) {
  494. if (is_object($arg)) {
  495. $params[] = '[Object ' . get_class($arg) . ']';
  496. } elseif (is_array($arg)) {
  497. $params[] = '[Array]';
  498. } elseif (is_null($arg)) {
  499. $params[] = '[NULL]';
  500. } else {
  501. $params[] = '"' . $arg . '"';
  502. }
  503. }
  504. }
  505. $params = implode(', ', $params);
  506. $calls[$depth - $i] = sprintf(
  507. '%s(%s) called at %s',
  508. $function,
  509. str_replace("\n", '\n', $params),
  510. $location
  511. );
  512. }
  513. ksort($calls);
  514. return implode("\n", $calls);
  515. }
  516. /**
  517. * Remove all data from an array where the key seems to point to sensitive data
  518. *
  519. * This is used to remove passwords, mail addresses and similar data from the
  520. * debug output
  521. *
  522. * @param array $data
  523. *
  524. * @author Andreas Gohr <andi@splitbrain.org>
  525. */
  526. function debug_guard(&$data)
  527. {
  528. foreach ($data as $key => $value) {
  529. if (preg_match('/(notify|pass|auth|secret|ftp|userinfo|token|buid|mail|proxy)/i', $key)) {
  530. $data[$key] = '***';
  531. continue;
  532. }
  533. if (is_array($value)) debug_guard($data[$key]);
  534. }
  535. }