xref: /dokuwiki/inc/parserutils.php (revision bf0c93c21103a02f9efe4c427b9fefd6c5732666)
1c112d578Sandi<?php
2c112d578Sandi/**
3b8595a66SAndreas Gohr * Utilities for accessing the parser
4c112d578Sandi *
5c112d578Sandi * @license    GPL 2 (http://www.gnu.org/licenses/gpl.html)
6c112d578Sandi * @author     Harry Fuecks <hfuecks@gmail.com>
7c112d578Sandi * @author     Andreas Gohr <andi@splitbrain.org>
8c112d578Sandi */
9c112d578Sandi
10fa8adffeSAndreas Gohrif(!defined('DOKU_INC')) die('meh.');
11c112d578Sandi
12c112d578Sandi/**
13c112d578Sandi * Returns the parsed Wikitext in XHTML for the given id and revision.
14c112d578Sandi *
15c112d578Sandi * If $excuse is true an explanation is returned if the file
16c112d578Sandi * wasn't found
17c112d578Sandi *
18c112d578Sandi * @author Andreas Gohr <andi@splitbrain.org>
19c112d578Sandi */
20c112d578Sandifunction p_wiki_xhtml($id, $rev='', $excuse=true){
21c112d578Sandi    $file = wikiFN($id,$rev);
22c112d578Sandi    $ret  = '';
23c112d578Sandi
24c112d578Sandi    //ensure $id is in global $ID (needed for parsing)
251e76272cSandi    global $ID;
263ff8773bSAndreas Gohr    $keep = $ID;
271e76272cSandi    $ID   = $id;
28c112d578Sandi
29c112d578Sandi    if($rev){
30c112d578Sandi        if(@file_exists($file)){
31bde4e341SGalaxyMaster            $ret = p_render('xhtml',p_get_instructions(io_readWikiPage($file,$id,$rev)),$info); //no caching on old revisions
32c112d578Sandi        }elseif($excuse){
33c112d578Sandi            $ret = p_locale_xhtml('norev');
34c112d578Sandi        }
35c112d578Sandi    }else{
36c112d578Sandi        if(@file_exists($file)){
374b5f4f4eSchris            $ret = p_cached_output($file,'xhtml',$id);
38c112d578Sandi        }elseif($excuse){
39c112d578Sandi            $ret = p_locale_xhtml('newpage');
40c112d578Sandi        }
41c112d578Sandi    }
42c112d578Sandi
433ff8773bSAndreas Gohr    //restore ID (just in case)
443ff8773bSAndreas Gohr    $ID = $keep;
453ff8773bSAndreas Gohr
46c112d578Sandi    return $ret;
47c112d578Sandi}
48c112d578Sandi
49c112d578Sandi/**
506b7b33dcShfuecks * Returns starting summary for a page (e.g. the first few
516b7b33dcShfuecks * paragraphs), marked up in XHTML.
526b7b33dcShfuecks *
536b7b33dcShfuecks * If $excuse is true an explanation is returned if the file
546b7b33dcShfuecks * wasn't found
556b7b33dcShfuecks *
566b7b33dcShfuecks * @param string wiki page id
576b7b33dcShfuecks * @param reference populated with page title from heading or page id
588716966dSAndreas Gohr * @deprecated
598716966dSAndreas Gohr * @author Harry Fuecks <hfuecks@gmail.com>
606b7b33dcShfuecks */
616b7b33dcShfuecksfunction p_wiki_xhtml_summary($id, &$title, $rev='', $excuse=true){
626b7b33dcShfuecks    $file = wikiFN($id,$rev);
636b7b33dcShfuecks    $ret  = '';
646b7b33dcShfuecks
656b7b33dcShfuecks    //ensure $id is in global $ID (needed for parsing)
666b7b33dcShfuecks    global $ID;
676b7b33dcShfuecks    $keep = $ID;
686b7b33dcShfuecks    $ID   = $id;
696b7b33dcShfuecks
706b7b33dcShfuecks    if($rev){
716b7b33dcShfuecks        if(@file_exists($file)){
726b7b33dcShfuecks            //no caching on old revisions
73bde4e341SGalaxyMaster            $ins = p_get_instructions(io_readWikiPage($file,$id,$rev));
746b7b33dcShfuecks        }elseif($excuse){
756b7b33dcShfuecks            $ret = p_locale_xhtml('norev');
766b7b33dcShfuecks            //restore ID (just in case)
776b7b33dcShfuecks            $ID = $keep;
786b7b33dcShfuecks            return $ret;
796b7b33dcShfuecks        }
806b7b33dcShfuecks
816b7b33dcShfuecks    }else{
826b7b33dcShfuecks
836b7b33dcShfuecks        if(@file_exists($file)){
846b7b33dcShfuecks            // The XHTML for a summary is not cached so use the instruction cache
856b7b33dcShfuecks            $ins = p_cached_instructions($file);
866b7b33dcShfuecks        }elseif($excuse){
876b7b33dcShfuecks            $ret = p_locale_xhtml('newpage');
886b7b33dcShfuecks            //restore ID (just in case)
896b7b33dcShfuecks            $ID = $keep;
906b7b33dcShfuecks            return $ret;
916b7b33dcShfuecks        }
926b7b33dcShfuecks    }
936b7b33dcShfuecks
946b7b33dcShfuecks    $ret = p_render('xhtmlsummary',$ins,$info);
956b7b33dcShfuecks
966b7b33dcShfuecks    if ( $info['sum_pagetitle'] ) {
976b7b33dcShfuecks        $title = $info['sum_pagetitle'];
986b7b33dcShfuecks    } else {
996b7b33dcShfuecks        $title = $id;
1006b7b33dcShfuecks    }
1016b7b33dcShfuecks
1026b7b33dcShfuecks    $ID = $keep;
1036b7b33dcShfuecks    return $ret;
1046b7b33dcShfuecks}
1056b7b33dcShfuecks
1066b7b33dcShfuecks/**
107c112d578Sandi * Returns the specified local text in parsed format
108c112d578Sandi *
109c112d578Sandi * @author Andreas Gohr <andi@splitbrain.org>
110c112d578Sandi */
111c112d578Sandifunction p_locale_xhtml($id){
112c112d578Sandi    //fetch parsed locale
1134b5f4f4eSchris    $html = p_cached_output(localeFN($id));
114c112d578Sandi    return $html;
115c112d578Sandi}
116c112d578Sandi
117c112d578Sandi/**
1184b5f4f4eSchris *     *** DEPRECATED ***
1194b5f4f4eSchris *
1204b5f4f4eSchris * use p_cached_output()
1214b5f4f4eSchris *
122c112d578Sandi * Returns the given file parsed to XHTML
123c112d578Sandi *
124c112d578Sandi * Uses and creates a cachefile
125c112d578Sandi *
1264b5f4f4eSchris * @deprecated
127c112d578Sandi * @author Andreas Gohr <andi@splitbrain.org>
1289dc2c2afSandi * @todo   rewrite to use mode instead of hardcoded XHTML
129c112d578Sandi */
130c112d578Sandifunction p_cached_xhtml($file){
1314b5f4f4eSchris    return p_cached_output($file);
1324b5f4f4eSchris}
1334b5f4f4eSchris
1344b5f4f4eSchris/**
1354b5f4f4eSchris * Returns the given file parsed into the requested output format
1364b5f4f4eSchris *
1374b5f4f4eSchris * @author Andreas Gohr <andi@splitbrain.org>
1384b5f4f4eSchris * @author Chris Smith <chris@jalakai.co.uk>
1394b5f4f4eSchris */
1404b5f4f4eSchrisfunction p_cached_output($file, $format='xhtml', $id='') {
141c112d578Sandi    global $conf;
142c112d578Sandi
1434b5f4f4eSchris    $cache = new cache_renderer($id, $file, $format);
1444b5f4f4eSchris    if ($cache->useCache()) {
14585767031SAndreas Gohr        $parsed = $cache->retrieveCache(false);
146ea2a4271SAndreas Gohr        if($conf['allowdebug'] && $format=='xhtml') $parsed .= "\n<!-- cachefile {$cache->cache} used -->\n";
147c112d578Sandi    } else {
1484b5f4f4eSchris        $parsed = p_render($format, p_cached_instructions($file,false,$id), $info);
149c112d578Sandi
1509dc2c2afSandi        if ($info['cache']) {
1514b5f4f4eSchris            $cache->storeCache($parsed);               //save cachefile
152ea2a4271SAndreas Gohr            if($conf['allowdebug'] && $format=='xhtml') $parsed .= "\n<!-- no cachefile used, but created {$cache->cache} -->\n";
153c112d578Sandi        }else{
1544b5f4f4eSchris            $cache->removeCache();                     //try to delete cachefile
155ea2a4271SAndreas Gohr            if($conf['allowdebug'] && $format=='xhtml') $parsed .= "\n<!-- no cachefile used, caching forbidden -->\n";
156c112d578Sandi        }
157c112d578Sandi    }
158c112d578Sandi
159c112d578Sandi    return $parsed;
160c112d578Sandi}
161c112d578Sandi
162c112d578Sandi/**
163c112d578Sandi * Returns the render instructions for a file
164c112d578Sandi *
165c112d578Sandi * Uses and creates a serialized cache file
166c112d578Sandi *
167c112d578Sandi * @author Andreas Gohr <andi@splitbrain.org>
168c112d578Sandi */
1694b5f4f4eSchrisfunction p_cached_instructions($file,$cacheonly=false,$id='') {
170c112d578Sandi    global $conf;
17147b2d319SAndreas Gohr    static $run = null;
17247b2d319SAndreas Gohr    if(is_null($run)) $run = array();
173c112d578Sandi
1744b5f4f4eSchris    $cache = new cache_instructions($id, $file);
175c112d578Sandi
17647b2d319SAndreas Gohr    if ($cacheonly || $cache->useCache() || isset($run[$file])) {
1774b5f4f4eSchris        return $cache->retrieveCache();
178c112d578Sandi    } else if (@file_exists($file)) {
179c112d578Sandi        // no cache - do some work
180bde4e341SGalaxyMaster        $ins = p_get_instructions(io_readWikiPage($file,$id));
181cbaf4259SChris Smith        if ($cache->storeCache($ins)) {
18247b2d319SAndreas Gohr            $run[$file] = true; // we won't rebuild these instructions in the same run again
183cbaf4259SChris Smith        } else {
184cbaf4259SChris Smith            msg('Unable to save cache file. Hint: disk full; file permissions; safe_mode setting.',-1);
185cbaf4259SChris Smith        }
186c112d578Sandi        return $ins;
187c112d578Sandi    }
188c112d578Sandi
1893b3f8916SAndreas Gohr    return null;
190c112d578Sandi}
191c112d578Sandi
192c112d578Sandi/**
193c112d578Sandi * turns a page into a list of instructions
194c112d578Sandi *
195c112d578Sandi * @author Harry Fuecks <hfuecks@gmail.com>
196c112d578Sandi * @author Andreas Gohr <andi@splitbrain.org>
197c112d578Sandi */
1986bbae538Sandifunction p_get_instructions($text){
199c112d578Sandi
200107b01d6Sandi    $modes = p_get_parsermodes();
201ee20e7d1Sandi
202c112d578Sandi    // Create the parser
20367f9913dSAndreas Gohr    $Parser = new Doku_Parser();
204c112d578Sandi
205c112d578Sandi    // Add the Handler
20667f9913dSAndreas Gohr    $Parser->Handler = new Doku_Handler();
207c112d578Sandi
208107b01d6Sandi    //add modes to parser
209107b01d6Sandi    foreach($modes as $mode){
210107b01d6Sandi        $Parser->addMode($mode['mode'],$mode['obj']);
211c112d578Sandi    }
212c112d578Sandi
213c112d578Sandi    // Do the parsing
214677844afSchris    trigger_event('PARSER_WIKITEXT_PREPROCESS', $text);
215a2d649c4Sandi    $p = $Parser->parse($text);
216ee20e7d1Sandi    //  dbg($p);
217a2d649c4Sandi    return $p;
218c112d578Sandi}
219c112d578Sandi
220c112d578Sandi/**
22139a89382SEsther Brunner * returns the metadata of a page
22239a89382SEsther Brunner *
2234a819402SMichael Hamann * @param string $id The id of the page the metadata should be returned from
2244a819402SMichael Hamann * @param string $key The key of the metdata value that shall be read (by default everything) - separate hierarchies by " " like "date created"
2254a819402SMichael Hamann * @param boolean $render If the page should be rendererd when the cache can't be used - default true
2264a819402SMichael Hamann * @return mixed The requested metadata fields
2274a819402SMichael Hamann *
22839a89382SEsther Brunner * @author Esther Brunner <esther@kaffeehaus.ch>
22998214867SMichael Hamann * @author Michael Hamann <michael@content-space.de>
23039a89382SEsther Brunner */
2314a819402SMichael Hamannfunction p_get_metadata($id, $key='', $render=true){
2321172f8dcSAdrian Lang    global $ID;
2336afe8dcaSchris
2340a7e3bceSchris    // cache the current page
2350a7e3bceSchris    // Benchmarking shows the current page's metadata is generally the only page metadata
2360a7e3bceSchris    // accessed several times. This may catch a few other pages, but that shouldn't be an issue.
2370a7e3bceSchris    $cache = ($ID == $id);
2380a7e3bceSchris    $meta = p_read_metadata($id, $cache);
23939a89382SEsther Brunner
24098214867SMichael Hamann    // prevent recursive calls in the cache
24198214867SMichael Hamann    static $recursion = false;
2424a819402SMichael Hamann    if (!$recursion && $render){
24398214867SMichael Hamann        $recursion = true;
24498214867SMichael Hamann
24598214867SMichael Hamann        $cachefile = new cache_renderer($id, wikiFN($id), 'metadata');
24698214867SMichael Hamann
24798214867SMichael Hamann        if (page_exists($id) && !$cachefile->useCache()){
24869ba640bSMichael Hamann            $old_meta = $meta;
24939a89382SEsther Brunner            $meta = p_render_metadata($id, $meta);
25069ba640bSMichael Hamann            // only update the file when the metadata has been changed
25169ba640bSMichael Hamann            if ($meta == $old_meta || p_save_metadata($id, $meta)) {
25298214867SMichael Hamann                // store a timestamp in order to make sure that the cachefile is touched
25398214867SMichael Hamann                $cachefile->storeCache(time());
25498214867SMichael Hamann            } else {
25598214867SMichael Hamann                msg('Unable to save metadata file. Hint: disk full; file permissions; safe_mode setting.',-1);
25698214867SMichael Hamann            }
25798214867SMichael Hamann        }
25898214867SMichael Hamann
25998214867SMichael Hamann        $recursion = false;
2606afe8dcaSchris    }
26139a89382SEsther Brunner
262ebf65d37SAdrian Lang    $val = $meta['current'];
263ebf65d37SAdrian Lang
26439a89382SEsther Brunner    // filter by $key
265569a0019SAdrian Lang    foreach(preg_split('/\s+/', $key, 2, PREG_SPLIT_NO_EMPTY) as $cur_key) {
266ebf65d37SAdrian Lang        if (!isset($val[$cur_key])) {
267ebf65d37SAdrian Lang            return null;
26866d29756SChris Smith        }
269ebf65d37SAdrian Lang        $val = $val[$cur_key];
27039a89382SEsther Brunner    }
271ebf65d37SAdrian Lang    return $val;
27239a89382SEsther Brunner}
27339a89382SEsther Brunner
27439a89382SEsther Brunner/**
27539a89382SEsther Brunner * sets metadata elements of a page
27639a89382SEsther Brunner *
277a365baeeSDominik Eckelmann * @see http://www.dokuwiki.org/devel:metadata#functions_to_get_and_set_metadata
278a365baeeSDominik Eckelmann *
279a365baeeSDominik Eckelmann * @param String  $id         is the ID of a wiki page
280a365baeeSDominik Eckelmann * @param Array   $data       is an array with key ⇒ value pairs to be set in the metadata
281a365baeeSDominik Eckelmann * @param Boolean $render     whether or not the page metadata should be generated with the renderer
282a365baeeSDominik Eckelmann * @param Boolean $persistent indicates whether or not the particular metadata value will persist through
283a365baeeSDominik Eckelmann *                            the next metadata rendering.
284a365baeeSDominik Eckelmann * @return boolean true on success
285a365baeeSDominik Eckelmann *
28639a89382SEsther Brunner * @author Esther Brunner <esther@kaffeehaus.ch>
28739a89382SEsther Brunner */
2880a7e3bceSchrisfunction p_set_metadata($id, $data, $render=false, $persistent=true){
28939a89382SEsther Brunner    if (!is_array($data)) return false;
29039a89382SEsther Brunner
2910a7e3bceSchris    global $ID;
2920a7e3bceSchris
2930a7e3bceSchris    // cache the current page
2940a7e3bceSchris    $cache = ($ID == $id);
2950a7e3bceSchris    $orig = p_read_metadata($id, $cache);
29639a89382SEsther Brunner
29739a89382SEsther Brunner    // render metadata first?
2980a7e3bceSchris    $meta = $render ? p_render_metadata($id, $orig) : $orig;
29939a89382SEsther Brunner
30039a89382SEsther Brunner    // now add the passed metadata
30139a89382SEsther Brunner    $protected = array('description', 'date', 'contributor');
30239a89382SEsther Brunner    foreach ($data as $key => $value){
30339a89382SEsther Brunner
30439a89382SEsther Brunner        // be careful with sub-arrays of $meta['relation']
30539a89382SEsther Brunner        if ($key == 'relation'){
3060a7e3bceSchris
30739a89382SEsther Brunner            foreach ($value as $subkey => $subvalue){
30866d29756SChris Smith                $meta['current'][$key][$subkey] = !empty($meta['current'][$key][$subkey]) ? array_merge($meta['current'][$key][$subkey], $subvalue) : $subvalue;
3090a7e3bceSchris                if ($persistent)
31066d29756SChris Smith                    $meta['persistent'][$key][$subkey] = !empty($meta['persistent'][$key][$subkey]) ? array_merge($meta['persistent'][$key][$subkey], $subvalue) : $subvalue;
31139a89382SEsther Brunner            }
31239a89382SEsther Brunner
31339a89382SEsther Brunner            // be careful with some senisitive arrays of $meta
31439a89382SEsther Brunner        } elseif (in_array($key, $protected)){
3150a7e3bceSchris
31666d29756SChris Smith            // these keys, must have subkeys - a legitimate value must be an array
31739a89382SEsther Brunner            if (is_array($value)) {
31866d29756SChris Smith                $meta['current'][$key] = !empty($meta['current'][$key]) ? array_merge($meta['current'][$key],$value) : $value;
3190a7e3bceSchris
3200a7e3bceSchris                if ($persistent) {
32166d29756SChris Smith                    $meta['persistent'][$key] = !empty($meta['persistent'][$key]) ? array_merge($meta['persistent'][$key],$value) : $value;
3220a7e3bceSchris                }
32339a89382SEsther Brunner            }
32439a89382SEsther Brunner
32539a89382SEsther Brunner            // no special treatment for the rest
32639a89382SEsther Brunner        } else {
3270a7e3bceSchris            $meta['current'][$key] = $value;
3280a7e3bceSchris            if ($persistent) $meta['persistent'][$key] = $value;
32939a89382SEsther Brunner        }
33039a89382SEsther Brunner    }
33139a89382SEsther Brunner
33239a89382SEsther Brunner    // save only if metadata changed
33339a89382SEsther Brunner    if ($meta == $orig) return true;
3346afe8dcaSchris
3351172f8dcSAdrian Lang    return p_save_metadata($id, $meta);
33639a89382SEsther Brunner}
33739a89382SEsther Brunner
33839a89382SEsther Brunner/**
3393d1f9ec3SMichael Klier * Purges the non-persistant part of the meta data
3403d1f9ec3SMichael Klier * used on page deletion
3413d1f9ec3SMichael Klier *
3423d1f9ec3SMichael Klier * @author Michael Klier <chi@chimeric.de>
3433d1f9ec3SMichael Klier */
3443d1f9ec3SMichael Klierfunction p_purge_metadata($id) {
3453d1f9ec3SMichael Klier    $meta = p_read_metadata($id);
3463d1f9ec3SMichael Klier    foreach($meta['current'] as $key => $value) {
3473d1f9ec3SMichael Klier        if(is_array($meta[$key])) {
3483d1f9ec3SMichael Klier            $meta['current'][$key] = array();
3493d1f9ec3SMichael Klier        } else {
3503d1f9ec3SMichael Klier            $meta['current'][$key] = '';
3513d1f9ec3SMichael Klier        }
3521172f8dcSAdrian Lang
3533d1f9ec3SMichael Klier    }
3541172f8dcSAdrian Lang    return p_save_metadata($id, $meta);
3553d1f9ec3SMichael Klier}
3563d1f9ec3SMichael Klier
3573d1f9ec3SMichael Klier/**
3580a7e3bceSchris * read the metadata from source/cache for $id
3590a7e3bceSchris * (internal use only - called by p_get_metadata & p_set_metadata)
3600a7e3bceSchris *
3610a7e3bceSchris * @author   Christopher Smith <chris@jalakai.co.uk>
3620a7e3bceSchris *
3630a7e3bceSchris * @param    string   $id      absolute wiki page id
3640a7e3bceSchris * @param    bool     $cache   whether or not to cache metadata in memory
3650a7e3bceSchris *                             (only use for metadata likely to be accessed several times)
3660a7e3bceSchris *
3670a7e3bceSchris * @return   array             metadata
3680a7e3bceSchris */
3690a7e3bceSchrisfunction p_read_metadata($id,$cache=false) {
3700a7e3bceSchris    global $cache_metadata;
3710a7e3bceSchris
3723a50618cSgweissbach    if (isset($cache_metadata[(string)$id])) return $cache_metadata[(string)$id];
3730a7e3bceSchris
3740a7e3bceSchris    $file = metaFN($id, '.meta');
3750a7e3bceSchris    $meta = @file_exists($file) ? unserialize(io_readFile($file, false)) : array('current'=>array(),'persistent'=>array());
3760a7e3bceSchris
3770a7e3bceSchris    if ($cache) {
3783a50618cSgweissbach        $cache_metadata[(string)$id] = $meta;
3790a7e3bceSchris    }
3800a7e3bceSchris
3810a7e3bceSchris    return $meta;
3820a7e3bceSchris}
3830a7e3bceSchris
3840a7e3bceSchris/**
3851172f8dcSAdrian Lang * This is the backend function to save a metadata array to a file
3861172f8dcSAdrian Lang *
3871172f8dcSAdrian Lang * @param    string   $id      absolute wiki page id
3881172f8dcSAdrian Lang * @param    array    $meta    metadata
3891172f8dcSAdrian Lang *
3901172f8dcSAdrian Lang * @return   bool              success / fail
3911172f8dcSAdrian Lang */
3921172f8dcSAdrian Langfunction p_save_metadata($id, $meta) {
3931172f8dcSAdrian Lang    // sync cached copies, including $INFO metadata
3941172f8dcSAdrian Lang    global $cache_metadata, $INFO;
3951172f8dcSAdrian Lang
3961172f8dcSAdrian Lang    if (isset($cache_metadata[$id])) $cache_metadata[$id] = $meta;
3971172f8dcSAdrian Lang    if (!empty($INFO) && ($id == $INFO['id'])) { $INFO['meta'] = $meta['current']; }
3981172f8dcSAdrian Lang
3991172f8dcSAdrian Lang    return io_saveFile(metaFN($id, '.meta'), serialize($meta));
4001172f8dcSAdrian Lang}
4011172f8dcSAdrian Lang
4021172f8dcSAdrian Lang/**
40339a89382SEsther Brunner * renders the metadata of a page
40439a89382SEsther Brunner *
40539a89382SEsther Brunner * @author Esther Brunner <esther@kaffeehaus.ch>
40639a89382SEsther Brunner */
40739a89382SEsther Brunnerfunction p_render_metadata($id, $orig){
40848924015SAndreas Gohr    // make sure the correct ID is in global ID
40948924015SAndreas Gohr    global $ID;
41048924015SAndreas Gohr    $keep = $ID;
41148924015SAndreas Gohr    $ID   = $id;
41248924015SAndreas Gohr
4130a7e3bceSchris    // add an extra key for the event - to tell event handlers the page whose metadata this is
4140a7e3bceSchris    $orig['page'] = $id;
4150a7e3bceSchris    $evt = new Doku_Event('PARSER_METADATA_RENDER', $orig);
4160a7e3bceSchris    if ($evt->advise_before()) {
4170a7e3bceSchris
41839a89382SEsther Brunner        require_once DOKU_INC."inc/parser/metadata.php";
41939a89382SEsther Brunner
42039a89382SEsther Brunner        // get instructions
4214b5f4f4eSchris        $instructions = p_cached_instructions(wikiFN($id),false,$id);
42248924015SAndreas Gohr        if(is_null($instructions)){
42348924015SAndreas Gohr            $ID = $keep;
42448924015SAndreas Gohr            return null; // something went wrong with the instructions
42548924015SAndreas Gohr        }
42639a89382SEsther Brunner
42739a89382SEsther Brunner        // set up the renderer
42867f9913dSAndreas Gohr        $renderer = new Doku_Renderer_metadata();
4290a7e3bceSchris        $renderer->meta = $orig['current'];
4300a7e3bceSchris        $renderer->persistent = $orig['persistent'];
43139a89382SEsther Brunner
43239a89382SEsther Brunner        // loop through the instructions
43339a89382SEsther Brunner        foreach ($instructions as $instruction){
43439a89382SEsther Brunner            // execute the callback against the renderer
4353b748871SAndreas Gohr            call_user_func_array(array(&$renderer, $instruction[0]), (array) $instruction[1]);
43639a89382SEsther Brunner        }
43739a89382SEsther Brunner
4380a7e3bceSchris        $evt->result = array('current'=>$renderer->meta,'persistent'=>$renderer->persistent);
4390a7e3bceSchris    }
4400a7e3bceSchris    $evt->advise_after();
4410a7e3bceSchris
44248924015SAndreas Gohr    $ID = $keep;
4430a7e3bceSchris    return $evt->result;
44439a89382SEsther Brunner}
44539a89382SEsther Brunner
44639a89382SEsther Brunner/**
447107b01d6Sandi * returns all available parser syntax modes in correct order
448107b01d6Sandi *
449107b01d6Sandi * @author Andreas Gohr <andi@splitbrain.org>
450107b01d6Sandi */
451107b01d6Sandifunction p_get_parsermodes(){
452107b01d6Sandi    global $conf;
453107b01d6Sandi
454107b01d6Sandi    //reuse old data
455107b01d6Sandi    static $modes = null;
456107b01d6Sandi    if($modes != null){
457107b01d6Sandi        return $modes;
458107b01d6Sandi    }
459107b01d6Sandi
460107b01d6Sandi    //import parser classes and mode definitions
461107b01d6Sandi    require_once DOKU_INC . 'inc/parser/parser.php';
462107b01d6Sandi
463107b01d6Sandi    // we now collect all syntax modes and their objects, then they will
464107b01d6Sandi    // be sorted and added to the parser in correct order
465107b01d6Sandi    $modes = array();
466107b01d6Sandi
467107b01d6Sandi    // add syntax plugins
468107b01d6Sandi    $pluginlist = plugin_list('syntax');
469107b01d6Sandi    if(count($pluginlist)){
470107b01d6Sandi        global $PARSER_MODES;
471107b01d6Sandi        $obj = null;
472107b01d6Sandi        foreach($pluginlist as $p){
473c90b2fb1Schris            if(!$obj =& plugin_load('syntax',$p)) continue; //attempt to load plugin into $obj
474107b01d6Sandi            $PARSER_MODES[$obj->getType()][] = "plugin_$p"; //register mode type
475107b01d6Sandi            //add to modes
476107b01d6Sandi            $modes[] = array(
477107b01d6Sandi                    'sort' => $obj->getSort(),
478107b01d6Sandi                    'mode' => "plugin_$p",
479107b01d6Sandi                    'obj'  => $obj,
480107b01d6Sandi                    );
481a46d0d65SAndreas Gohr            unset($obj); //remove the reference
482107b01d6Sandi        }
483107b01d6Sandi    }
484107b01d6Sandi
485107b01d6Sandi    // add default modes
486107b01d6Sandi    $std_modes = array('listblock','preformatted','notoc','nocache',
487107b01d6Sandi            'header','table','linebreak','footnote','hr',
488107b01d6Sandi            'unformatted','php','html','code','file','quote',
489e77ea1bcSAndreas Gohr            'internallink','rss','media','externallink',
490e77ea1bcSAndreas Gohr            'emaillink','windowssharelink','eol');
491e77ea1bcSAndreas Gohr    if($conf['typography']){
492e77ea1bcSAndreas Gohr        $std_modes[] = 'quotes';
493e77ea1bcSAndreas Gohr        $std_modes[] = 'multiplyentity';
494e77ea1bcSAndreas Gohr    }
495107b01d6Sandi    foreach($std_modes as $m){
496107b01d6Sandi        $class = "Doku_Parser_Mode_$m";
497107b01d6Sandi        $obj   = new $class();
498107b01d6Sandi        $modes[] = array(
499107b01d6Sandi                'sort' => $obj->getSort(),
500107b01d6Sandi                'mode' => $m,
501107b01d6Sandi                'obj'  => $obj
502107b01d6Sandi                );
503107b01d6Sandi    }
504107b01d6Sandi
505107b01d6Sandi    // add formatting modes
506107b01d6Sandi    $fmt_modes = array('strong','emphasis','underline','monospace',
507107b01d6Sandi            'subscript','superscript','deleted');
508107b01d6Sandi    foreach($fmt_modes as $m){
509107b01d6Sandi        $obj   = new Doku_Parser_Mode_formatting($m);
510107b01d6Sandi        $modes[] = array(
511107b01d6Sandi                'sort' => $obj->getSort(),
512107b01d6Sandi                'mode' => $m,
513107b01d6Sandi                'obj'  => $obj
514107b01d6Sandi                );
515107b01d6Sandi    }
516107b01d6Sandi
517107b01d6Sandi    // add modes which need files
518107b01d6Sandi    $obj     = new Doku_Parser_Mode_smiley(array_keys(getSmileys()));
519107b01d6Sandi    $modes[] = array('sort' => $obj->getSort(), 'mode' => 'smiley','obj'  => $obj );
520107b01d6Sandi    $obj     = new Doku_Parser_Mode_acronym(array_keys(getAcronyms()));
521107b01d6Sandi    $modes[] = array('sort' => $obj->getSort(), 'mode' => 'acronym','obj'  => $obj );
522107b01d6Sandi    $obj     = new Doku_Parser_Mode_entity(array_keys(getEntities()));
523107b01d6Sandi    $modes[] = array('sort' => $obj->getSort(), 'mode' => 'entity','obj'  => $obj );
524107b01d6Sandi
525107b01d6Sandi    // add optional camelcase mode
526107b01d6Sandi    if($conf['camelcase']){
527107b01d6Sandi        $obj     = new Doku_Parser_Mode_camelcaselink();
528107b01d6Sandi        $modes[] = array('sort' => $obj->getSort(), 'mode' => 'camelcaselink','obj'  => $obj );
529107b01d6Sandi    }
530107b01d6Sandi
531107b01d6Sandi    //sort modes
532107b01d6Sandi    usort($modes,'p_sort_modes');
533107b01d6Sandi
534107b01d6Sandi    return $modes;
535107b01d6Sandi}
536107b01d6Sandi
537107b01d6Sandi/**
538107b01d6Sandi * Callback function for usort
539107b01d6Sandi *
540107b01d6Sandi * @author Andreas Gohr <andi@splitbrain.org>
541107b01d6Sandi */
542107b01d6Sandifunction p_sort_modes($a, $b){
543107b01d6Sandi    if($a['sort'] == $b['sort']) return 0;
544107b01d6Sandi    return ($a['sort'] < $b['sort']) ? -1 : 1;
545107b01d6Sandi}
546107b01d6Sandi
547107b01d6Sandi/**
548ac83b9d8Sandi * Renders a list of instruction to the specified output mode
549c112d578Sandi *
5507a8cc57eSElan Ruusamäe * In the $info array is information from the renderer returned
5519dc2c2afSandi *
552c112d578Sandi * @author Harry Fuecks <hfuecks@gmail.com>
553c112d578Sandi * @author Andreas Gohr <andi@splitbrain.org>
554c112d578Sandi */
5559dc2c2afSandifunction p_render($mode,$instructions,&$info){
556c112d578Sandi    if(is_null($instructions)) return '';
557c112d578Sandi
558d968d3e5SChris Smith    $Renderer =& p_get_renderer($mode);
559d968d3e5SChris Smith    if (is_null($Renderer)) return null;
560c327d6c4SAndreas Gohr
561d968d3e5SChris Smith    $Renderer->reset();
562c112d578Sandi
563c112d578Sandi    $Renderer->smileys = getSmileys();
564c112d578Sandi    $Renderer->entities = getEntities();
565c112d578Sandi    $Renderer->acronyms = getAcronyms();
566c112d578Sandi    $Renderer->interwiki = getInterwiki();
567c112d578Sandi
568c112d578Sandi    // Loop through the instructions
569c112d578Sandi    foreach ( $instructions as $instruction ) {
570c112d578Sandi        // Execute the callback against the Renderer
571c112d578Sandi        call_user_func_array(array(&$Renderer, $instruction[0]),$instruction[1]);
572c112d578Sandi    }
5739dc2c2afSandi
5749dc2c2afSandi    //set info array
5759dc2c2afSandi    $info = $Renderer->info;
5769dc2c2afSandi
577677844afSchris    // Post process and return the output
578677844afSchris    $data = array($mode,& $Renderer->doc);
579677844afSchris    trigger_event('RENDERER_CONTENT_POSTPROCESS',$data);
580c112d578Sandi    return $Renderer->doc;
581c112d578Sandi}
582c112d578Sandi
583d968d3e5SChris Smithfunction & p_get_renderer($mode) {
5847aea91afSChris Smith    global $conf, $plugin_controller;
585d968d3e5SChris Smith
586d968d3e5SChris Smith    $rname = !empty($conf['renderer_'.$mode]) ? $conf['renderer_'.$mode] : $mode;
587d968d3e5SChris Smith
588d968d3e5SChris Smith    // try default renderer first:
589d968d3e5SChris Smith    $file = DOKU_INC."inc/parser/$rname.php";
590d968d3e5SChris Smith    if(@file_exists($file)){
591d968d3e5SChris Smith        require_once $file;
592d968d3e5SChris Smith        $rclass = "Doku_Renderer_$rname";
593d968d3e5SChris Smith
594d968d3e5SChris Smith        if ( !class_exists($rclass) ) {
595d968d3e5SChris Smith            trigger_error("Unable to resolve render class $rclass",E_USER_WARNING);
596d968d3e5SChris Smith            msg("Renderer '$rname' for $mode not valid",-1);
597d968d3e5SChris Smith            return null;
598d968d3e5SChris Smith        }
59967f9913dSAndreas Gohr        $Renderer = new $rclass();
600d968d3e5SChris Smith    }else{
6017b27382cSGina Haeussge        // Maybe a plugin/component is available?
6027b27382cSGina Haeussge        list($plugin, $component) = $plugin_controller->_splitName($rname);
6037b27382cSGina Haeussge        if (!$plugin_controller->isdisabled($plugin)){
604f6ec8df8SAdrian Lang            $Renderer =& $plugin_controller->load('renderer',$rname);
6057aea91afSChris Smith        }
6067aea91afSChris Smith
607d968d3e5SChris Smith        if(is_null($Renderer)){
608d968d3e5SChris Smith            msg("No renderer '$rname' found for mode '$mode'",-1);
609d968d3e5SChris Smith            return null;
610d968d3e5SChris Smith        }
611d968d3e5SChris Smith    }
612d968d3e5SChris Smith
613d968d3e5SChris Smith    return $Renderer;
614d968d3e5SChris Smith}
615d968d3e5SChris Smith
616bb0a59d4Sjan/**
617bb0a59d4Sjan * Gets the first heading from a file
618bb0a59d4Sjan *
619fc18c0fbSchris * @param   string   $id       dokuwiki page id
620fc18c0fbSchris * @param   bool     $render   rerender if first heading not known
6210770c0e5SChris Smith *                             default: true  -- must be set to false for calls from the metadata renderer to
6220770c0e5SChris Smith *                                               protects against loops and excessive resource usage when pages
6230770c0e5SChris Smith *                                               for which only a first heading is required will attempt to
6240770c0e5SChris Smith *                                               render metadata for all the pages for which they require first
6250770c0e5SChris Smith *                                               headings ... and so on.
626fc18c0fbSchris *
62795dbfe57SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
628*bf0c93c2SMichael Hamann * @author Michael Hamann <michael@content-space.de>
629bb0a59d4Sjan */
6300770c0e5SChris Smithfunction p_get_first_heading($id, $render=true){
631*bf0c93c2SMichael Hamann    // counter how many titles have been requested using p_get_metadata
632*bf0c93c2SMichael Hamann    static $count = 0;
633*bf0c93c2SMichael Hamann    // the index of all titles, only loaded when many titles are requested
634*bf0c93c2SMichael Hamann    static $title_index = null;
635*bf0c93c2SMichael Hamann    // cache for titles requested using p_get_metadata
636*bf0c93c2SMichael Hamann    static $title_cache = array();
637*bf0c93c2SMichael Hamann
638*bf0c93c2SMichael Hamann    $id = cleanID($id);
639*bf0c93c2SMichael Hamann
640*bf0c93c2SMichael Hamann    // check if this title has already been requested
641*bf0c93c2SMichael Hamann    if (isset($title_cache[$id]))
642*bf0c93c2SMichael Hamann      return $title_cache[$id];
643*bf0c93c2SMichael Hamann
644*bf0c93c2SMichael Hamann    // check if already too many titles have been requested and probably
645*bf0c93c2SMichael Hamann    // using the title index is better
646*bf0c93c2SMichael Hamann    if ($count > 10) {
647*bf0c93c2SMichael Hamann        if (is_null($title_index)) {
648*bf0c93c2SMichael Hamann            $pages  = array_map('rtrim', idx_getIndex('page', ''));
649*bf0c93c2SMichael Hamann            $titles = array_map('rtrim', idx_getIndex('title', ''));
650*bf0c93c2SMichael Hamann            // check for corrupt title index #FS2076
651*bf0c93c2SMichael Hamann            if(count($pages) != count($titles)){
652*bf0c93c2SMichael Hamann                $titles = array_fill(0,count($pages),'');
653*bf0c93c2SMichael Hamann                @unlink($conf['indexdir'].'/title.idx'); // will be rebuilt in inc/init.php
654*bf0c93c2SMichael Hamann            }
655*bf0c93c2SMichael Hamann            $title_index = array_combine($pages, $titles);
656*bf0c93c2SMichael Hamann        }
657*bf0c93c2SMichael Hamann        return $title_index[$id];
658*bf0c93c2SMichael Hamann    }
659*bf0c93c2SMichael Hamann
660*bf0c93c2SMichael Hamann    ++$count;
661*bf0c93c2SMichael Hamann    $title_cache[$id] = p_get_metadata($id,'title',$render);
662*bf0c93c2SMichael Hamann    return $title_cache[$id];
663bb0a59d4Sjan}
664bb0a59d4Sjan
6658f7d700cSchris/**
6668f7d700cSchris * Wrapper for GeSHi Code Highlighter, provides caching of its output
6678f7d700cSchris *
6685d568b99SChris Smith * @param  string   $code       source code to be highlighted
6695d568b99SChris Smith * @param  string   $language   language to provide highlighting
6705d568b99SChris Smith * @param  string   $wrapper    html element to wrap the returned highlighted text
6715d568b99SChris Smith *
6728f7d700cSchris * @author Christopher Smith <chris@jalakai.co.uk>
67335fbe9efSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
6748f7d700cSchris */
6755d568b99SChris Smithfunction p_xhtml_cached_geshi($code, $language, $wrapper='pre') {
676f8121585SChris Smith    global $conf, $config_cascade;
67735fbe9efSAndreas Gohr    $language = strtolower($language);
6785d568b99SChris Smith
6795d568b99SChris Smith    // remove any leading or trailing blank lines
6805d568b99SChris Smith    $code = preg_replace('/^\s*?\n|\s*?\n$/','',$code);
6815d568b99SChris Smith
6828f7d700cSchris    $cache = getCacheName($language.$code,".code");
68335fbe9efSAndreas Gohr    $ctime = @filemtime($cache);
68435fbe9efSAndreas Gohr    if($ctime && !$_REQUEST['purge'] &&
685f8121585SChris Smith            $ctime > filemtime(DOKU_INC.'inc/geshi.php') &&                 // geshi changed
686f8121585SChris Smith            $ctime > @filemtime(DOKU_INC.'inc/geshi/'.$language.'.php') &&  // language syntax definition changed
687f8121585SChris Smith            $ctime > filemtime(reset($config_cascade['main']['default']))){ // dokuwiki changed
6888f7d700cSchris        $highlighted_code = io_readFile($cache, false);
6898f7d700cSchris
6908f7d700cSchris    } else {
6918f7d700cSchris
69235fbe9efSAndreas Gohr        $geshi = new GeSHi($code, $language, DOKU_INC . 'inc/geshi');
6938f7d700cSchris        $geshi->set_encoding('utf-8');
6948f7d700cSchris        $geshi->enable_classes();
6958f7d700cSchris        $geshi->set_header_type(GESHI_HEADER_PRE);
6968f7d700cSchris        $geshi->set_link_target($conf['target']['extern']);
6978f7d700cSchris
6985d568b99SChris Smith        // remove GeSHi's wrapper element (we'll replace it with our own later)
6995d568b99SChris Smith        // we need to use a GeSHi wrapper to avoid <BR> throughout the highlighted text
70069ddc332SAnika Henke        $highlighted_code = trim(preg_replace('!^<pre[^>]*>|</pre>$!','',$geshi->parse_code()),"\n\r");
7018f7d700cSchris        io_saveFile($cache,$highlighted_code);
7028f7d700cSchris    }
7038f7d700cSchris
7045d568b99SChris Smith    // add a wrapper element if required
7055d568b99SChris Smith    if ($wrapper) {
7065d568b99SChris Smith        return "<$wrapper class=\"code $language\">$highlighted_code</$wrapper>";
7075d568b99SChris Smith    } else {
7088f7d700cSchris        return $highlighted_code;
7098f7d700cSchris    }
7105d568b99SChris Smith}
7118f7d700cSchris
712