parserutils.php 27 KB

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