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.
 
 
 
 
 

830 lines
27 KiB

  1. <?php
  2. /**
  3. * Utilities for accessing the parser
  4. *
  5. * @license GPL 2 (http://www.gnu.org/licenses/gpl.html)
  6. * @author Harry Fuecks <hfuecks@gmail.com>
  7. * @author Andreas Gohr <andi@splitbrain.org>
  8. */
  9. use dokuwiki\Extension\PluginInterface;
  10. use dokuwiki\Cache\CacheInstructions;
  11. use dokuwiki\Cache\CacheRenderer;
  12. use dokuwiki\ChangeLog\PageChangeLog;
  13. use dokuwiki\Extension\PluginController;
  14. use dokuwiki\Extension\Event;
  15. use dokuwiki\Extension\SyntaxPlugin;
  16. use dokuwiki\Parsing\Parser;
  17. use dokuwiki\Parsing\ParserMode\Acronym;
  18. use dokuwiki\Parsing\ParserMode\Camelcaselink;
  19. use dokuwiki\Parsing\ParserMode\Entity;
  20. use dokuwiki\Parsing\ParserMode\Formatting;
  21. use dokuwiki\Parsing\ParserMode\Smiley;
  22. /**
  23. * How many pages shall be rendered for getting metadata during one request
  24. * at maximum? Note that this limit isn't respected when METADATA_RENDER_UNLIMITED
  25. * is passed as render parameter to p_get_metadata.
  26. */
  27. if (!defined('P_GET_METADATA_RENDER_LIMIT')) define('P_GET_METADATA_RENDER_LIMIT', 5);
  28. /** Don't render metadata even if it is outdated or doesn't exist */
  29. define('METADATA_DONT_RENDER', 0);
  30. /**
  31. * Render metadata when the page is really newer or the metadata doesn't exist.
  32. * Uses just a simple check, but should work pretty well for loading simple
  33. * metadata values like the page title and avoids rendering a lot of pages in
  34. * one request. The P_GET_METADATA_RENDER_LIMIT is used in this mode.
  35. * Use this if it is unlikely that the metadata value you are requesting
  36. * does depend e.g. on pages that are included in the current page using
  37. * the include plugin (this is very likely the case for the page title, but
  38. * not for relation references).
  39. */
  40. define('METADATA_RENDER_USING_SIMPLE_CACHE', 1);
  41. /**
  42. * Render metadata using the metadata cache logic. The P_GET_METADATA_RENDER_LIMIT
  43. * is used in this mode. Use this mode when you are requesting more complex
  44. * metadata. Although this will cause rendering more often it might actually have
  45. * the effect that less current metadata is returned as it is more likely than in
  46. * the simple cache mode that metadata needs to be rendered for all pages at once
  47. * which means that when the metadata for the page is requested that actually needs
  48. * to be updated the limit might have been reached already.
  49. */
  50. define('METADATA_RENDER_USING_CACHE', 2);
  51. /**
  52. * Render metadata without limiting the number of pages for which metadata is
  53. * rendered. Use this mode with care, normally it should only be used in places
  54. * like the indexer or in cli scripts where the execution time normally isn't
  55. * limited. This can be combined with the simple cache using
  56. * METADATA_RENDER_USING_CACHE | METADATA_RENDER_UNLIMITED.
  57. */
  58. define('METADATA_RENDER_UNLIMITED', 4);
  59. /**
  60. * Returns the parsed Wikitext in XHTML for the given id and revision.
  61. *
  62. * If $excuse is true an explanation is returned if the file
  63. * wasn't found
  64. *
  65. * @param string $id page id
  66. * @param string|int $rev revision timestamp or empty string
  67. * @param bool $excuse
  68. * @param string $date_at
  69. *
  70. * @return null|string
  71. * @author Andreas Gohr <andi@splitbrain.org>
  72. *
  73. */
  74. function p_wiki_xhtml($id, $rev = '', $excuse = true, $date_at = '')
  75. {
  76. $file = wikiFN($id, $rev);
  77. $ret = '';
  78. //ensure $id is in global $ID (needed for parsing)
  79. global $ID;
  80. $keep = $ID;
  81. $ID = $id;
  82. if ($rev || $date_at) {
  83. if (file_exists($file)) {
  84. //no caching on old revisions
  85. $ret = p_render('xhtml', p_get_instructions(io_readWikiPage($file, $id, $rev)), $info, $date_at);
  86. } elseif ($excuse) {
  87. $ret = p_locale_xhtml('norev');
  88. }
  89. } elseif (file_exists($file)) {
  90. $ret = p_cached_output($file, 'xhtml', $id);
  91. } elseif ($excuse) {
  92. //check if the page once existed
  93. $changelog = new PageChangeLog($id);
  94. if ($changelog->hasRevisions()) {
  95. $ret = p_locale_xhtml('onceexisted');
  96. } else {
  97. $ret = p_locale_xhtml('newpage');
  98. }
  99. }
  100. //restore ID (just in case)
  101. $ID = $keep;
  102. return $ret;
  103. }
  104. /**
  105. * Returns the specified local text in parsed format
  106. *
  107. * @param string $id page id
  108. * @return null|string
  109. * @author Andreas Gohr <andi@splitbrain.org>
  110. *
  111. */
  112. function p_locale_xhtml($id)
  113. {
  114. //fetch parsed locale
  115. $data = ['id' => $id, 'html' => ''];
  116. $event = new Event('PARSER_LOCALE_XHTML', $data);
  117. if ($event->advise_before()) {
  118. $data['html'] = p_cached_output(localeFN($data['id']));
  119. }
  120. $event->advise_after();
  121. return $data['html'];
  122. }
  123. /**
  124. * Returns the given file parsed into the requested output format
  125. *
  126. * @param string $file filename, path to file
  127. * @param string $format
  128. * @param string $id page id
  129. * @return null|string
  130. * @author Andreas Gohr <andi@splitbrain.org>
  131. * @author Chris Smith <chris@jalakai.co.uk>
  132. *
  133. */
  134. function p_cached_output($file, $format = 'xhtml', $id = '')
  135. {
  136. global $conf;
  137. $cache = new CacheRenderer($id, $file, $format);
  138. if ($cache->useCache()) {
  139. $parsed = $cache->retrieveCache(false);
  140. if ($conf['allowdebug'] && $format == 'xhtml') {
  141. $parsed .= "\n<!-- cachefile {$cache->cache} used -->\n";
  142. }
  143. } else {
  144. $parsed = p_render($format, p_cached_instructions($file, false, $id), $info);
  145. if (!empty($info['cache']) && $cache->storeCache($parsed)) { // storeCache() attempts to save cachefile
  146. if ($conf['allowdebug'] && $format == 'xhtml') {
  147. $parsed .= "\n<!-- no cachefile used, but created {$cache->cache} -->\n";
  148. }
  149. } else {
  150. $cache->removeCache(); //try to delete cachefile
  151. if ($conf['allowdebug'] && $format == 'xhtml') {
  152. $parsed .= "\n<!-- no cachefile used, caching forbidden -->\n";
  153. }
  154. }
  155. }
  156. return $parsed;
  157. }
  158. /**
  159. * Returns the render instructions for a file
  160. *
  161. * Uses and creates a serialized cache file
  162. *
  163. * @param string $file filename, path to file
  164. * @param bool $cacheonly
  165. * @param string $id page id
  166. * @return array|null
  167. * @author Andreas Gohr <andi@splitbrain.org>
  168. *
  169. */
  170. function p_cached_instructions($file, $cacheonly = false, $id = '')
  171. {
  172. static $run = null;
  173. if (is_null($run)) $run = [];
  174. $cache = new CacheInstructions($id, $file);
  175. if ($cacheonly || $cache->useCache() || (isset($run[$file]) && !defined('DOKU_UNITTEST'))) {
  176. return $cache->retrieveCache();
  177. } elseif (file_exists($file)) {
  178. // no cache - do some work
  179. $ins = p_get_instructions(io_readWikiPage($file, $id));
  180. if ($cache->storeCache($ins)) {
  181. $run[$file] = true; // we won't rebuild these instructions in the same run again
  182. } else {
  183. msg('Unable to save cache file. Hint: disk full; file permissions; safe_mode setting.', -1);
  184. }
  185. return $ins;
  186. }
  187. return null;
  188. }
  189. /**
  190. * turns a page into a list of instructions
  191. *
  192. * @param string $text raw wiki syntax text
  193. * @return array a list of instruction arrays
  194. * @author Harry Fuecks <hfuecks@gmail.com>
  195. * @author Andreas Gohr <andi@splitbrain.org>
  196. *
  197. */
  198. function p_get_instructions($text)
  199. {
  200. $modes = p_get_parsermodes();
  201. // Create the parser and handler
  202. $Parser = new Parser(new Doku_Handler());
  203. //add modes to parser
  204. foreach ($modes as $mode) {
  205. $Parser->addMode($mode['mode'], $mode['obj']);
  206. }
  207. // Do the parsing
  208. Event::createAndTrigger('PARSER_WIKITEXT_PREPROCESS', $text);
  209. return $Parser->parse($text);
  210. }
  211. /**
  212. * returns the metadata of a page
  213. *
  214. * @param string $id The id of the page the metadata should be returned from
  215. * @param string $key The key of the metdata value that shall be read (by default everything)
  216. * separate hierarchies by " " like "date created"
  217. * @param int $render If the page should be rendererd - possible values:
  218. * METADATA_DONT_RENDER, METADATA_RENDER_USING_SIMPLE_CACHE, METADATA_RENDER_USING_CACHE
  219. * METADATA_RENDER_UNLIMITED (also combined with the previous two options),
  220. * default: METADATA_RENDER_USING_CACHE
  221. * @return mixed The requested metadata fields
  222. *
  223. * @author Esther Brunner <esther@kaffeehaus.ch>
  224. * @author Michael Hamann <michael@content-space.de>
  225. */
  226. function p_get_metadata($id, $key = '', $render = METADATA_RENDER_USING_CACHE)
  227. {
  228. global $ID;
  229. static $render_count = 0;
  230. // track pages that have already been rendered in order to avoid rendering the same page
  231. // again
  232. static $rendered_pages = [];
  233. // cache the current page
  234. // Benchmarking shows the current page's metadata is generally the only page metadata
  235. // accessed several times. This may catch a few other pages, but that shouldn't be an issue.
  236. $cache = ($ID == $id);
  237. $meta = p_read_metadata($id, $cache);
  238. if (!is_numeric($render)) {
  239. if ($render) {
  240. $render = METADATA_RENDER_USING_SIMPLE_CACHE;
  241. } else {
  242. $render = METADATA_DONT_RENDER;
  243. }
  244. }
  245. // prevent recursive calls in the cache
  246. static $recursion = false;
  247. if (!$recursion && $render != METADATA_DONT_RENDER && !isset($rendered_pages[$id]) && page_exists($id)) {
  248. $recursion = true;
  249. $cachefile = new CacheRenderer($id, wikiFN($id), 'metadata');
  250. $do_render = false;
  251. if ($render & METADATA_RENDER_UNLIMITED || $render_count < P_GET_METADATA_RENDER_LIMIT) {
  252. if ($render & METADATA_RENDER_USING_SIMPLE_CACHE) {
  253. $pagefn = wikiFN($id);
  254. $metafn = metaFN($id, '.meta');
  255. if (!file_exists($metafn) || @filemtime($pagefn) > @filemtime($cachefile->cache)) {
  256. $do_render = true;
  257. }
  258. } elseif (!$cachefile->useCache()) {
  259. $do_render = true;
  260. }
  261. }
  262. if ($do_render) {
  263. if (!defined('DOKU_UNITTEST')) {
  264. ++$render_count;
  265. $rendered_pages[$id] = true;
  266. }
  267. $old_meta = $meta;
  268. $meta = p_render_metadata($id, $meta);
  269. // only update the file when the metadata has been changed
  270. if ($meta == $old_meta || p_save_metadata($id, $meta)) {
  271. // store a timestamp in order to make sure that the cachefile is touched
  272. // this timestamp is also stored when the meta data is still the same
  273. $cachefile->storeCache(time());
  274. } else {
  275. msg('Unable to save metadata file. Hint: disk full; file permissions; safe_mode setting.', -1);
  276. }
  277. }
  278. $recursion = false;
  279. }
  280. $val = $meta['current'] ?? null;
  281. // filter by $key
  282. foreach (preg_split('/\s+/', $key, 2, PREG_SPLIT_NO_EMPTY) as $cur_key) {
  283. if (!isset($val[$cur_key])) {
  284. return null;
  285. }
  286. $val = $val[$cur_key];
  287. }
  288. return $val;
  289. }
  290. /**
  291. * sets metadata elements of a page
  292. *
  293. * @see http://www.dokuwiki.org/devel:metadata#functions_to_get_and_set_metadata
  294. *
  295. * @param string $id is the ID of a wiki page
  296. * @param array $data is an array with key ⇒ value pairs to be set in the metadata
  297. * @param boolean $render whether or not the page metadata should be generated with the renderer
  298. * @param boolean $persistent indicates whether or not the particular metadata value will persist through
  299. * the next metadata rendering.
  300. * @return boolean true on success
  301. *
  302. * @author Esther Brunner <esther@kaffeehaus.ch>
  303. * @author Michael Hamann <michael@content-space.de>
  304. */
  305. function p_set_metadata($id, $data, $render = false, $persistent = true)
  306. {
  307. if (!is_array($data)) return false;
  308. global $ID, $METADATA_RENDERERS;
  309. // if there is currently a renderer change the data in the renderer instead
  310. if (isset($METADATA_RENDERERS[$id])) {
  311. $orig =& $METADATA_RENDERERS[$id];
  312. $meta = $orig;
  313. } else {
  314. // cache the current page
  315. $cache = ($ID == $id);
  316. $orig = p_read_metadata($id, $cache);
  317. // render metadata first?
  318. $meta = $render ? p_render_metadata($id, $orig) : $orig;
  319. }
  320. // now add the passed metadata
  321. $protected = ['description', 'date', 'contributor'];
  322. foreach ($data as $key => $value) {
  323. // be careful with sub-arrays of $meta['relation']
  324. if ($key == 'relation') {
  325. foreach ($value as $subkey => $subvalue) {
  326. if (isset($meta['current'][$key][$subkey]) && is_array($meta['current'][$key][$subkey])) {
  327. $meta['current'][$key][$subkey] = array_replace($meta['current'][$key][$subkey], (array)$subvalue);
  328. } else {
  329. $meta['current'][$key][$subkey] = $subvalue;
  330. }
  331. if ($persistent) {
  332. if (isset($meta['persistent'][$key][$subkey]) && is_array($meta['persistent'][$key][$subkey])) {
  333. $meta['persistent'][$key][$subkey] = array_replace(
  334. $meta['persistent'][$key][$subkey],
  335. (array)$subvalue
  336. );
  337. } else {
  338. $meta['persistent'][$key][$subkey] = $subvalue;
  339. }
  340. }
  341. }
  342. // be careful with some senisitive arrays of $meta
  343. } elseif (in_array($key, $protected)) {
  344. // these keys, must have subkeys - a legitimate value must be an array
  345. if (is_array($value)) {
  346. $meta['current'][$key] = empty($meta['current'][$key]) ?
  347. $value :
  348. array_replace((array)$meta['current'][$key], $value);
  349. if ($persistent) {
  350. $meta['persistent'][$key] = empty($meta['persistent'][$key]) ?
  351. $value :
  352. array_replace((array)$meta['persistent'][$key], $value);
  353. }
  354. }
  355. // no special treatment for the rest
  356. } else {
  357. $meta['current'][$key] = $value;
  358. if ($persistent) $meta['persistent'][$key] = $value;
  359. }
  360. }
  361. // save only if metadata changed
  362. if ($meta == $orig) return true;
  363. if (isset($METADATA_RENDERERS[$id])) {
  364. // set both keys individually as the renderer has references to the individual keys
  365. $METADATA_RENDERERS[$id]['current'] = $meta['current'];
  366. $METADATA_RENDERERS[$id]['persistent'] = $meta['persistent'];
  367. return true;
  368. } else {
  369. return p_save_metadata($id, $meta);
  370. }
  371. }
  372. /**
  373. * Purges the non-persistant part of the meta data
  374. * used on page deletion
  375. *
  376. * @param string $id page id
  377. * @return bool success / fail
  378. * @author Michael Klier <chi@chimeric.de>
  379. *
  380. */
  381. function p_purge_metadata($id)
  382. {
  383. $meta = p_read_metadata($id);
  384. foreach ($meta['current'] as $key => $value) {
  385. if (isset($meta[$key]) && is_array($meta[$key])) {
  386. $meta['current'][$key] = [];
  387. } else {
  388. $meta['current'][$key] = '';
  389. }
  390. }
  391. return p_save_metadata($id, $meta);
  392. }
  393. /**
  394. * read the metadata from source/cache for $id
  395. * (internal use only - called by p_get_metadata & p_set_metadata)
  396. *
  397. * @param string $id absolute wiki page id
  398. * @param bool $cache whether or not to cache metadata in memory
  399. * (only use for metadata likely to be accessed several times)
  400. *
  401. * @return array metadata
  402. * @author Christopher Smith <chris@jalakai.co.uk>
  403. *
  404. */
  405. function p_read_metadata($id, $cache = false)
  406. {
  407. global $cache_metadata;
  408. if (isset($cache_metadata[(string)$id])) return $cache_metadata[(string)$id];
  409. $file = metaFN($id, '.meta');
  410. $meta = file_exists($file) ?
  411. unserialize(io_readFile($file, false)) :
  412. ['current' => [], 'persistent' => []];
  413. if ($cache) {
  414. $cache_metadata[(string)$id] = $meta;
  415. }
  416. return $meta;
  417. }
  418. /**
  419. * This is the backend function to save a metadata array to a file
  420. *
  421. * @param string $id absolute wiki page id
  422. * @param array $meta metadata
  423. *
  424. * @return bool success / fail
  425. */
  426. function p_save_metadata($id, $meta)
  427. {
  428. // sync cached copies, including $INFO metadata
  429. global $cache_metadata, $INFO;
  430. if (isset($cache_metadata[$id])) $cache_metadata[$id] = $meta;
  431. if (!empty($INFO) && isset($INFO['id']) && ($id == $INFO['id'])) {
  432. $INFO['meta'] = $meta['current'];
  433. }
  434. return io_saveFile(metaFN($id, '.meta'), serialize($meta));
  435. }
  436. /**
  437. * renders the metadata of a page
  438. *
  439. * @param string $id page id
  440. * @param array $orig the original metadata
  441. * @return array|null array('current'=> array,'persistent'=> array);
  442. * @author Esther Brunner <esther@kaffeehaus.ch>
  443. *
  444. */
  445. function p_render_metadata($id, $orig)
  446. {
  447. // make sure the correct ID is in global ID
  448. global $ID, $METADATA_RENDERERS;
  449. // avoid recursive rendering processes for the same id
  450. if (isset($METADATA_RENDERERS[$id])) {
  451. return $orig;
  452. }
  453. // store the original metadata in the global $METADATA_RENDERERS so p_set_metadata can use it
  454. $METADATA_RENDERERS[$id] =& $orig;
  455. $keep = $ID;
  456. $ID = $id;
  457. // add an extra key for the event - to tell event handlers the page whose metadata this is
  458. $orig['page'] = $id;
  459. $evt = new Event('PARSER_METADATA_RENDER', $orig);
  460. if ($evt->advise_before()) {
  461. // get instructions
  462. $instructions = p_cached_instructions(wikiFN($id), false, $id);
  463. if (is_null($instructions)) {
  464. $ID = $keep;
  465. unset($METADATA_RENDERERS[$id]);
  466. return null; // something went wrong with the instructions
  467. }
  468. // set up the renderer
  469. $renderer = new Doku_Renderer_metadata();
  470. $renderer->meta =& $orig['current'];
  471. $renderer->persistent =& $orig['persistent'];
  472. // loop through the instructions
  473. foreach ($instructions as $instruction) {
  474. // execute the callback against the renderer
  475. call_user_func_array([&$renderer, $instruction[0]], (array)$instruction[1]);
  476. }
  477. $evt->result = ['current' => &$renderer->meta, 'persistent' => &$renderer->persistent];
  478. }
  479. $evt->advise_after();
  480. // clean up
  481. $ID = $keep;
  482. unset($METADATA_RENDERERS[$id]);
  483. return $evt->result;
  484. }
  485. /**
  486. * returns all available parser syntax modes in correct order
  487. *
  488. * @return array[] with for each plugin the array('sort' => sortnumber, 'mode' => mode string, 'obj' => plugin object)
  489. * @author Andreas Gohr <andi@splitbrain.org>
  490. *
  491. */
  492. function p_get_parsermodes()
  493. {
  494. global $conf;
  495. //reuse old data
  496. static $modes = null;
  497. if ($modes != null && !defined('DOKU_UNITTEST')) {
  498. return $modes;
  499. }
  500. //import parser classes and mode definitions
  501. require_once DOKU_INC . 'inc/parser/parser.php';
  502. // we now collect all syntax modes and their objects, then they will
  503. // be sorted and added to the parser in correct order
  504. $modes = [];
  505. // add syntax plugins
  506. $pluginlist = plugin_list('syntax');
  507. if ($pluginlist !== []) {
  508. global $PARSER_MODES;
  509. foreach ($pluginlist as $p) {
  510. /** @var SyntaxPlugin $obj */
  511. $obj = plugin_load('syntax', $p);
  512. if (!$obj instanceof PluginInterface) continue;
  513. $PARSER_MODES[$obj->getType()][] = "plugin_$p"; //register mode type
  514. //add to modes
  515. $modes[] = [
  516. 'sort' => $obj->getSort(),
  517. 'mode' => "plugin_$p",
  518. 'obj' => $obj,
  519. ];
  520. unset($obj); //remove the reference
  521. }
  522. }
  523. // add default modes
  524. $std_modes = [
  525. 'listblock', 'preformatted', 'notoc', 'nocache', 'header', 'table', 'linebreak', 'footnote', 'hr',
  526. 'unformatted', 'code', 'file', 'quote', 'internallink', 'rss', 'media', 'externallink',
  527. 'emaillink', 'windowssharelink', 'eol'
  528. ];
  529. if ($conf['typography']) {
  530. $std_modes[] = 'quotes';
  531. $std_modes[] = 'multiplyentity';
  532. }
  533. foreach ($std_modes as $m) {
  534. $class = 'dokuwiki\\Parsing\\ParserMode\\' . ucfirst($m);
  535. $obj = new $class();
  536. $modes[] = ['sort' => $obj->getSort(), 'mode' => $m, 'obj' => $obj];
  537. }
  538. // add formatting modes
  539. $fmt_modes = [
  540. 'strong', 'emphasis', 'underline', 'monospace', 'subscript', 'superscript', 'deleted'
  541. ];
  542. foreach ($fmt_modes as $m) {
  543. $obj = new Formatting($m);
  544. $modes[] = [
  545. 'sort' => $obj->getSort(),
  546. 'mode' => $m,
  547. 'obj' => $obj
  548. ];
  549. }
  550. // add modes which need files
  551. $obj = new Smiley(array_keys(getSmileys()));
  552. $modes[] = ['sort' => $obj->getSort(), 'mode' => 'smiley', 'obj' => $obj];
  553. $obj = new Acronym(array_keys(getAcronyms()));
  554. $modes[] = ['sort' => $obj->getSort(), 'mode' => 'acronym', 'obj' => $obj];
  555. $obj = new Entity(array_keys(getEntities()));
  556. $modes[] = ['sort' => $obj->getSort(), 'mode' => 'entity', 'obj' => $obj];
  557. // add optional camelcase mode
  558. if ($conf['camelcase']) {
  559. $obj = new Camelcaselink();
  560. $modes[] = ['sort' => $obj->getSort(), 'mode' => 'camelcaselink', 'obj' => $obj];
  561. }
  562. //sort modes
  563. usort($modes, 'p_sort_modes');
  564. return $modes;
  565. }
  566. /**
  567. * Callback function for usort
  568. *
  569. * @param array $a
  570. * @param array $b
  571. * @return int $a is lower/equal/higher than $b
  572. * @author Andreas Gohr <andi@splitbrain.org>
  573. *
  574. */
  575. function p_sort_modes($a, $b)
  576. {
  577. return $a['sort'] <=> $b['sort'];
  578. }
  579. /**
  580. * Renders a list of instruction to the specified output mode
  581. *
  582. * In the $info array is information from the renderer returned
  583. *
  584. * @param string $mode
  585. * @param array|null|false $instructions
  586. * @param array $info returns render info like enabled toc and cache
  587. * @param string $date_at
  588. * @return null|string rendered output
  589. * @author Andreas Gohr <andi@splitbrain.org>
  590. *
  591. * @author Harry Fuecks <hfuecks@gmail.com>
  592. */
  593. function p_render($mode, $instructions, &$info, $date_at = '')
  594. {
  595. if (is_null($instructions)) return '';
  596. if ($instructions === false) return '';
  597. $Renderer = p_get_renderer($mode);
  598. if (is_null($Renderer)) return null;
  599. $Renderer->reset();
  600. if ($date_at) {
  601. $Renderer->date_at = $date_at;
  602. }
  603. $Renderer->smileys = getSmileys();
  604. $Renderer->entities = getEntities();
  605. $Renderer->acronyms = getAcronyms();
  606. $Renderer->interwiki = getInterwiki();
  607. // Loop through the instructions
  608. foreach ($instructions as $instruction) {
  609. // Execute the callback against the Renderer
  610. if (method_exists($Renderer, $instruction[0])) {
  611. call_user_func_array([&$Renderer, $instruction[0]], $instruction[1] ?: []);
  612. }
  613. }
  614. //set info array
  615. $info = $Renderer->info;
  616. // Post process and return the output
  617. $data = [$mode, & $Renderer->doc];
  618. Event::createAndTrigger('RENDERER_CONTENT_POSTPROCESS', $data);
  619. return $Renderer->doc;
  620. }
  621. /**
  622. * Figure out the correct renderer class to use for $mode,
  623. * instantiate and return it
  624. *
  625. * @param string $mode Mode of the renderer to get
  626. * @return null|Doku_Renderer The renderer
  627. *
  628. * @author Christopher Smith <chris@jalakai.co.uk>
  629. */
  630. function p_get_renderer($mode)
  631. {
  632. /** @var PluginController $plugin_controller */
  633. global $conf, $plugin_controller;
  634. $rname = empty($conf['renderer_' . $mode]) ? $mode : $conf['renderer_' . $mode];
  635. $rclass = "Doku_Renderer_$rname";
  636. // if requested earlier or a bundled renderer
  637. if (class_exists($rclass)) {
  638. return new $rclass();
  639. }
  640. // not bundled, see if its an enabled renderer plugin & when $mode is 'xhtml', the renderer can supply that format.
  641. /** @var Doku_Renderer $Renderer */
  642. $Renderer = $plugin_controller->load('renderer', $rname);
  643. if ($Renderer && is_a($Renderer, 'Doku_Renderer') && ($mode != 'xhtml' || $mode == $Renderer->getFormat())) {
  644. return $Renderer;
  645. }
  646. // there is a configuration error!
  647. // not bundled, not a valid enabled plugin, use $mode to try to fallback to a bundled renderer
  648. $rclass = "Doku_Renderer_$mode";
  649. if (class_exists($rclass)) {
  650. // viewers should see renderered output, so restrict the warning to admins only
  651. $msg = "No renderer '$rname' found for mode '$mode', check your plugins";
  652. if ($mode == 'xhtml') {
  653. $msg .= " and the 'renderer_xhtml' config setting";
  654. }
  655. $msg .= ".<br/>Attempting to fallback to the bundled renderer.";
  656. msg($msg, -1, '', '', MSG_ADMINS_ONLY);
  657. $Renderer = new $rclass();
  658. $Renderer->nocache(); // fallback only (and may include admin alerts), don't cache
  659. return $Renderer;
  660. }
  661. // fallback failed, alert the world
  662. msg("No renderer '$rname' found for mode '$mode'", -1);
  663. return null;
  664. }
  665. /**
  666. * Gets the first heading from a file
  667. *
  668. * @param string $id dokuwiki page id
  669. * @param int $render rerender if first heading not known
  670. * default: METADATA_RENDER_USING_SIMPLE_CACHE
  671. * Possible values: METADATA_DONT_RENDER,
  672. * METADATA_RENDER_USING_SIMPLE_CACHE,
  673. * METADATA_RENDER_USING_CACHE,
  674. * METADATA_RENDER_UNLIMITED
  675. * @return string|null The first heading
  676. *
  677. * @author Andreas Gohr <andi@splitbrain.org>
  678. * @author Michael Hamann <michael@content-space.de>
  679. */
  680. function p_get_first_heading($id, $render = METADATA_RENDER_USING_SIMPLE_CACHE)
  681. {
  682. return p_get_metadata(cleanID($id), 'title', $render);
  683. }
  684. /**
  685. * Wrapper for GeSHi Code Highlighter, provides caching of its output
  686. *
  687. * @param string $code source code to be highlighted
  688. * @param string $language language to provide highlighting
  689. * @param string $wrapper html element to wrap the returned highlighted text
  690. * @return string xhtml code
  691. *
  692. * @author Christopher Smith <chris@jalakai.co.uk>
  693. * @author Andreas Gohr <andi@splitbrain.org>
  694. */
  695. function p_xhtml_cached_geshi($code, $language, $wrapper = 'pre', array $options = null)
  696. {
  697. global $conf, $config_cascade, $INPUT;
  698. $language = strtolower($language);
  699. // remove any leading or trailing blank lines
  700. $code = preg_replace('/^\s*?\n|\s*?\n$/', '', $code);
  701. $optionsmd5 = md5(serialize($options));
  702. $cache = getCacheName($language . $code . $optionsmd5, ".code");
  703. $ctime = @filemtime($cache);
  704. if (
  705. $ctime && !$INPUT->bool('purge') &&
  706. $ctime > filemtime(DOKU_INC . 'vendor/composer/installed.json') && // libraries changed
  707. $ctime > filemtime(reset($config_cascade['main']['default']))
  708. ) { // dokuwiki changed
  709. $highlighted_code = io_readFile($cache, false);
  710. } else {
  711. $geshi = new GeSHi($code, $language);
  712. $geshi->set_encoding('utf-8');
  713. $geshi->enable_classes();
  714. $geshi->set_header_type(GESHI_HEADER_PRE);
  715. $geshi->set_link_target($conf['target']['extern']);
  716. if ($options !== null) {
  717. foreach ($options as $function => $params) {
  718. if (is_callable([$geshi, $function])) {
  719. $geshi->$function($params);
  720. }
  721. }
  722. }
  723. // remove GeSHi's wrapper element (we'll replace it with our own later)
  724. // we need to use a GeSHi wrapper to avoid <BR> throughout the highlighted text
  725. $highlighted_code = trim(preg_replace('!^<pre[^>]*>|</pre>$!', '', $geshi->parse_code()), "\n\r");
  726. io_saveFile($cache, $highlighted_code);
  727. }
  728. // add a wrapper element if required
  729. if ($wrapper) {
  730. return "<$wrapper class=\"code $language\">$highlighted_code</$wrapper>";
  731. } else {
  732. return $highlighted_code;
  733. }
  734. }