xref: /plugin/include/helper.php (revision b0c45c9004a208f5b2dcb1da33787621a2a5b603)
1<?php
2/**
3 * @license    GPL 2 (http://www.gnu.org/licenses/gpl.html)
4 * @author     Esther Brunner <wikidesign@gmail.com>
5 * @author     Christopher Smith <chris@jalakai.co.uk>
6 * @author     Gina Häußge, Michael Klier <dokuwiki@chimeric.de>
7 */
8
9// must be run within Dokuwiki
10if (!defined('DOKU_INC')) die();
11
12if (!defined('DOKU_LF')) define('DOKU_LF', "\n");
13if (!defined('DOKU_TAB')) define('DOKU_TAB', "\t");
14if (!defined('DOKU_PLUGIN')) define('DOKU_PLUGIN', DOKU_INC.'lib/plugins/');
15
16require_once(DOKU_INC.'inc/search.php');
17
18class helper_plugin_include extends DokuWiki_Plugin { // DokuWiki_Helper_Plugin
19
20    var $defaults  = array();
21    var $sec_close = true;
22    var $taghelper = null;
23    var $includes  = array(); // deprecated - compatibility code for the blog plugin
24
25    /**
26     * Constructor loads default config settings once
27     */
28    function helper_plugin_include() {
29        $this->defaults['noheader']  = $this->getConf('noheader');
30        $this->defaults['firstsec']  = $this->getConf('firstseconly');
31        $this->defaults['editbtn']   = $this->getConf('showeditbtn');
32        $this->defaults['taglogos']  = $this->getConf('showtaglogos');
33        $this->defaults['footer']    = $this->getConf('showfooter');
34        $this->defaults['redirect']  = $this->getConf('doredirect');
35        $this->defaults['date']      = $this->getConf('showdate');
36        $this->defaults['mdate']     = $this->getConf('showmdate');
37        $this->defaults['user']      = $this->getConf('showuser');
38        $this->defaults['comments']  = $this->getConf('showcomments');
39        $this->defaults['linkbacks'] = $this->getConf('showlinkbacks');
40        $this->defaults['tags']      = $this->getConf('showtags');
41        $this->defaults['link']      = $this->getConf('showlink');
42        $this->defaults['permalink'] = $this->getConf('showpermalink');
43        $this->defaults['indent']    = $this->getConf('doindent');
44        $this->defaults['linkonly']  = $this->getConf('linkonly');
45        $this->defaults['title']     = $this->getConf('title');
46        $this->defaults['pageexists']  = $this->getConf('pageexists');
47        $this->defaults['parlink']   = $this->getConf('parlink');
48        $this->defaults['inline']    = false;
49        $this->defaults['order']     = $this->getConf('order');
50        $this->defaults['rsort']     = $this->getConf('rsort');
51        $this->defaults['depth']     = $this->getConf('depth');
52    }
53
54    /**
55     * Available methods for other plugins
56     */
57    function getMethods() {
58        $result = array();
59        $result[] = array(
60                'name'   => 'get_flags',
61                'desc'   => 'overrides standard values for showfooter and firstseconly settings',
62                'params' => array('flags' => 'array'),
63                );
64        return $result;
65    }
66
67    /**
68     * Overrides standard values for showfooter and firstseconly settings
69     */
70    function get_flags($setflags) {
71        // load defaults
72        $flags = $this->defaults;
73        foreach ($setflags as $flag) {
74            $value = '';
75            if (strpos($flag, '=') !== -1) {
76                list($flag, $value) = explode('=', $flag, 2);
77            }
78            switch ($flag) {
79                case 'footer':
80                    $flags['footer'] = 1;
81                    break;
82                case 'nofooter':
83                    $flags['footer'] = 0;
84                    break;
85                case 'firstseconly':
86                case 'firstsectiononly':
87                    $flags['firstsec'] = 1;
88                    break;
89                case 'fullpage':
90                    $flags['firstsec'] = 0;
91                    break;
92                case 'showheader':
93                case 'header':
94                    $flags['noheader'] = 0;
95                    break;
96                case 'noheader':
97                    $flags['noheader'] = 1;
98                    break;
99                case 'editbtn':
100                case 'editbutton':
101                    $flags['editbtn'] = 1;
102                    break;
103                case 'noeditbtn':
104                case 'noeditbutton':
105                    $flags['editbtn'] = 0;
106                    break;
107                case 'permalink':
108                    $flags['permalink'] = 1;
109                    break;
110                case 'nopermalink':
111                    $flags['permalink'] = 0;
112                    break;
113                case 'redirect':
114                    $flags['redirect'] = 1;
115                    break;
116                case 'noredirect':
117                    $flags['redirect'] = 0;
118                    break;
119                case 'link':
120                    $flags['link'] = 1;
121                    break;
122                case 'nolink':
123                    $flags['link'] = 0;
124                    break;
125                case 'user':
126                    $flags['user'] = 1;
127                    break;
128                case 'nouser':
129                    $flags['user'] = 0;
130                    break;
131                case 'comments':
132                    $flags['comments'] = 1;
133                    break;
134                case 'nocomments':
135                    $flags['comments'] = 0;
136                    break;
137                case 'linkbacks':
138                    $flags['linkbacks'] = 1;
139                    break;
140                case 'nolinkbacks':
141                    $flags['linkbacks'] = 0;
142                    break;
143                case 'tags':
144                    $flags['tags'] = 1;
145                    break;
146                case 'notags':
147                    $flags['tags'] = 0;
148                    break;
149                case 'date':
150                    $flags['date'] = 1;
151                    break;
152                case 'nodate':
153                    $flags['date'] = 0;
154                    break;
155                case 'mdate':
156                    $flags['mdate'] = 1;
157                    break;
158                case 'nomdate':
159                    $flags['mdate'] = 0;
160                    break;
161                case 'indent':
162                    $flags['indent'] = 1;
163                    break;
164                case 'noindent':
165                    $flags['indent'] = 0;
166                    break;
167                case 'linkonly':
168                    $flags['linkonly'] = 1;
169                    break;
170                case 'nolinkonly':
171                case 'include_content':
172                    $flags['linkonly'] = 0;
173                    break;
174                case 'inline':
175                    $flags['inline'] = 1;
176                    break;
177                case 'title':
178                    $flags['title'] = 1;
179                    break;
180                case 'notitle':
181                    $flags['title'] = 0;
182                    break;
183                case 'pageexists':
184                    $flags['pageexists'] = 1;
185                    break;
186                case 'nopageexists':
187                    $flags['pageexists'] = 0;
188                    break;
189                case 'existlink':
190                    $flags['pageexists'] = 1;
191                    $flags['linkonly'] = 1;
192                    break;
193                case 'parlink':
194                    $flags['parlink'] = 1;
195                    break;
196                case 'noparlink':
197                    $flags['parlink'] = 0;
198                    break;
199                case 'order':
200                    $flags['order'] = $value;
201                    break;
202                case 'sort':
203                    $flags['rsort'] = 0;
204                    break;
205                case 'rsort':
206                    $flags['rsort'] = 1;
207                    break;
208                case 'depth':
209                    $flags['depth'] = max(intval($value), 0);
210                    break;
211                case 'beforeeach':
212                    $flags['beforeeach'] = $value;
213                    break;
214                case 'aftereach':
215                    $flags['aftereach'] = $value;
216                    break;
217            }
218        }
219        // the include_content URL parameter overrides flags
220        if (isset($_REQUEST['include_content']))
221            $flags['linkonly'] = 0;
222        return $flags;
223    }
224
225    /**
226     * Returns the converted instructions of a give page/section
227     *
228     * @author Michael Klier <chi@chimeric.de>
229     * @author Michael Hamann <michael@content-space.de>
230     */
231    function _get_instructions($page, $sect, $mode, $lvl, $flags, $root_id = null, $included_pages = array()) {
232        $key = ($sect) ? $page . '#' . $sect : $page;
233        $this->includes[$key] = true; // legacy code for keeping compatibility with other plugins
234
235        // keep compatibility with other plugins that don't know the $root_id parameter
236        if (is_null($root_id)) {
237            global $ID;
238            $root_id = $ID;
239        }
240
241        if ($flags['linkonly']) {
242            if (page_exists($page) || $flags['pageexists']  == 0) {
243                $title = '';
244                if ($flags['title'])
245                    $title = p_get_first_heading($page);
246                if($flags['parlink']) {
247                    $ins = array(
248                        array('p_open', array()),
249                        array('internallink', array(':'.$key, $title)),
250                        array('p_close', array()),
251                    );
252                } else {
253                    $ins = array(array('internallink', array(':'.$key,$title)));
254                }
255            }else {
256                $ins = array();
257            }
258        } else {
259            if (page_exists($page)) {
260                global $ID;
261                $backupID = $ID;
262                $ID = $page; // Change the global $ID as otherwise plugins like the discussion plugin will save data for the wrong page
263                $ins = p_cached_instructions(wikiFN($page), false, $page);
264                $ID = $backupID;
265            } else {
266                $ins = array();
267            }
268
269            $this->_convert_instructions($ins, $lvl, $page, $sect, $flags, $root_id, $included_pages);
270        }
271        return $ins;
272    }
273
274    /**
275     * Converts instructions of the included page
276     *
277     * The funcion iterates over the given list of instructions and generates
278     * an index of header and section indicies. It also removes document
279     * start/end instructions, converts links, and removes unwanted
280     * instructions like tags, comments, linkbacks.
281     *
282     * Later all header/section levels are convertet to match the current
283     * inclusion level.
284     *
285     * @author Michael Klier <chi@chimeric.de>
286     */
287    function _convert_instructions(&$ins, $lvl, $page, $sect, $flags, $root_id, $included_pages = array()) {
288        global $conf;
289
290        // filter instructions if needed
291        if(!empty($sect)) {
292            $this->_get_section($ins, $sect);   // section required
293        }
294
295        if($flags['firstsec']) {
296            $this->_get_firstsec($ins, $page);  // only first section
297        }
298
299        $ns  = getNS($page);
300        $num = count($ins);
301
302        $conv_idx = array(); // conversion index
303        $lvl_max  = false;   // max level
304        $first_header = -1;
305        $no_header  = false;
306        $sect_title = false;
307        $endpos     = null; // end position of the raw wiki text
308
309        for($i=0; $i<$num; $i++) {
310            switch($ins[$i][0]) {
311                case 'document_start':
312                case 'document_end':
313                case 'section_edit':
314                    unset($ins[$i]);
315                    break;
316                case 'header':
317                    // get section title of first section
318                    if($sect && !$sect_title) {
319                        $sect_title = $ins[$i][1][0];
320                    }
321                    // check if we need to skip the first header
322                    if((!$no_header) && $flags['noheader']) {
323                        $no_header = true;
324                    }
325
326                    $conv_idx[] = $i;
327                    // get index of first header
328                    if($first_header == -1) $first_header = $i;
329                    // get max level of this instructions set
330                    if(!$lvl_max || ($ins[$i][1][1] < $lvl_max)) {
331                        $lvl_max = $ins[$i][1][1];
332                    }
333                    break;
334                case 'section_open':
335                    if ($flags['inline'])
336                        unset($ins[$i]);
337                    else
338                        $conv_idx[] = $i;
339                    break;
340                case 'section_close':
341                    if ($flags['inline'])
342                        unset($ins[$i]);
343                    break;
344                case 'internallink':
345                case 'internalmedia':
346                    // make sure parameters aren't touched
347                    $link_params = '';
348                    $link_id = $ins[$i][1][0];
349                    $link_parts = explode('?', $link_id, 2);
350                    if (count($link_parts) === 2) {
351                        $link_id = $link_parts[0];
352                        $link_params = $link_parts[1];
353                    }
354                    // resolve the id without cleaning it
355                    $link_id = resolve_id($ns, $link_id, false);
356                    // this id is internal (i.e. absolute) now, add ':' to make resolve_id work again
357                    if ($link_id{0} != ':') $link_id = ':'.$link_id;
358                    // restore parameters
359                    $ins[$i][1][0] = ($link_params != '') ? $link_id.'?'.$link_params : $link_id;
360                    if ($ins[$i][0] == 'internallink' && !empty($included_pages)) {
361                        // change links to included pages into local links
362                        $link_id = $ins[$i][1][0];
363                        $link_parts = explode('?', $link_id, 2);
364                        // only adapt links without parameters
365                        if (count($link_parts) === 1) {
366                            $link_parts = explode('#', $link_id, 2);
367                            $hash = '';
368                            if (count($link_parts) === 2) {
369                                list($link_id, $hash) = $link_parts;
370                            }
371                            $exists = false;
372                            resolve_pageid($ns, $link_id, $exists);
373                            if (array_key_exists($link_id, $included_pages)) {
374                                if ($hash) {
375                                    // hopefully the hash is also unique in the including page (otherwise this might be the wrong link target)
376                                    $ins[$i][0] = 'locallink';
377                                    $ins[$i][1][0] = $hash;
378                                } else {
379                                    // the include section ids are different from normal section ids (so they won't conflict) but this
380                                    // also means that the normal locallink function can't be used
381                                    $ins[$i][0] = 'plugin';
382                                    $ins[$i][1] = array('include_locallink', array($included_pages[$link_id]['hid'], $ins[$i][1][1]));
383                                }
384                            }
385                        }
386                    }
387                    break;
388                case 'plugin':
389                    // FIXME skip other plugins?
390                    switch($ins[$i][1][0]) {
391                        case 'tag_tag':                 // skip tags
392                        case 'discussion_comments':     // skip comments
393                        case 'linkback':                // skip linkbacks
394                        case 'data_entry':              // skip data plugin
395                        case 'meta':                    // skip meta plugin
396                        case 'indexmenu_tag':           // skip indexmenu sort tag
397                        case 'include_sorttag':         // skip include plugin sort tag
398                            unset($ins[$i]);
399                            break;
400                        // adapt indentation level of nested includes
401                        case 'include_include':
402                            if (!$flags['inline'] && $flags['indent'])
403                                $ins[$i][1][1][4] += $lvl;
404                            break;
405                        /*
406                         * if there is already a closelastsecedit instruction (was added by one of the section
407                         * functions), store its position but delete it as it can't be determined yet if it is needed,
408                         * i.e. if there is a header which generates a section edit (depends on the levels, level
409                         * adjustments, $no_header, ...)
410                         */
411                        case 'include_closelastsecedit':
412                            $endpos = $ins[$i][1][1][0];
413                            unset($ins[$i]);
414                            break;
415                    }
416                    break;
417                default:
418                    break;
419            }
420        }
421
422        // calculate difference between header/section level and include level
423        $diff = 0;
424        if (!isset($lvl_max)) $lvl_max = 0; // if no level found in target, set to 0
425        $diff = $lvl - $lvl_max + 1;
426        if ($no_header) $diff -= 1;  // push up one level if "noheader"
427
428        // convert headers and set footer/permalink
429        $hdr_deleted      = false;
430        $has_permalink    = false;
431        $footer_lvl       = false;
432        $contains_secedit = false;
433        $section_close_at = false;
434        foreach($conv_idx as $idx) {
435            if($ins[$idx][0] == 'header') {
436                if ($section_close_at === false) {
437                    // store the index of the first heading (the begin of the first section)
438                    $section_close_at = $idx;
439                }
440
441                if($no_header && !$hdr_deleted) {
442                    unset ($ins[$idx]);
443                    $hdr_deleted = true;
444                    continue;
445                }
446
447                if($flags['indent']) {
448                    $lvl_new = (($ins[$idx][1][1] + $diff) > 5) ? 5 : ($ins[$idx][1][1] + $diff);
449                    $ins[$idx][1][1] = $lvl_new;
450                }
451
452                if($ins[$idx][1][1] <= $conf['maxseclevel'])
453                    $contains_secedit = true;
454
455                // set permalink
456                if($flags['link'] && !$has_permalink && ($idx == $first_header)) {
457                    $this->_permalink($ins[$idx], $page, $sect, $flags);
458                    $has_permalink = true;
459                }
460
461                // set footer level
462                if(!$footer_lvl && ($idx == $first_header) && !$no_header) {
463                    if($flags['indent']) {
464                        $footer_lvl = $lvl_new;
465                    } else {
466                        $footer_lvl = $lvl_max;
467                    }
468                }
469            } else {
470                // it's a section
471                if($flags['indent']) {
472                    $lvl_new = (($ins[$idx][1][0] + $diff) > 5) ? 5 : ($ins[$idx][1][0] + $diff);
473                    $ins[$idx][1][0] = $lvl_new;
474                }
475
476                // check if noheader is used and set the footer level to the first section
477                if($no_header && !$footer_lvl) {
478                    if($flags['indent']) {
479                        $footer_lvl = $lvl_new;
480                    } else {
481                        $footer_lvl = $lvl_max;
482                    }
483                }
484            }
485        }
486
487        // close last open section of the included page if there is any
488        if ($contains_secedit) {
489            array_push($ins, array('plugin', array('include_closelastsecedit', array($endpos))));
490        }
491
492        // add edit button
493        if($flags['editbtn']) {
494            $this->_editbtn($ins, $page, $sect, $sect_title, ($flags['redirect'] ? $root_id : false));
495        }
496
497        // add footer
498        if($flags['footer']) {
499            $ins[] = $this->_footer($page, $sect, $sect_title, $flags, $footer_lvl, $root_id);
500        }
501
502        // wrap content at the beginning of the include that is not in a section in a section
503        if ($lvl > 0 && $section_close_at !== 0 && $flags['indent'] && !$flags['inline']) {
504            if ($section_close_at === false) {
505                $ins[] = array('section_close', array());
506                array_unshift($ins, array('section_open', array($lvl)));
507            } else {
508                $section_close_idx = array_search($section_close_at, array_keys($ins));
509                if ($section_close_idx > 0) {
510                    $before_ins = array_slice($ins, 0, $section_close_idx);
511                    $after_ins = array_slice($ins, $section_close_idx);
512                    $ins = array_merge($before_ins, array(array('section_close', array())), $after_ins);
513                    array_unshift($ins, array('section_open', array($lvl)));
514                }
515            }
516        }
517
518        // add instructions entry wrapper
519        $include_secid = (isset($flags['include_secid']) ? $flags['include_secid'] : NULL);
520        array_unshift($ins, array('plugin', array('include_wrap', array('open', $page, $flags['redirect'], $include_secid))));
521        if (isset($flags['beforeeach']))
522            array_unshift($ins, array('entity', array($flags['beforeeach'])));
523        array_push($ins, array('plugin', array('include_wrap', array('close'))));
524        if (isset($flags['aftereach']))
525            array_push($ins, array('entity', array($flags['aftereach'])));
526
527        // close previous section if any and re-open after inclusion
528        if($lvl != 0 && $this->sec_close && !$flags['inline']) {
529            array_unshift($ins, array('section_close', array()));
530            $ins[] = array('section_open', array($lvl));
531        }
532    }
533
534    /**
535     * Appends instruction item for the include plugin footer
536     *
537     * @author Michael Klier <chi@chimeric.de>
538     */
539    function _footer($page, $sect, $sect_title, $flags, $footer_lvl, $root_id) {
540        $footer = array();
541        $footer[0] = 'plugin';
542        $footer[1] = array('include_footer', array($page, $sect, $sect_title, $flags, $root_id, $footer_lvl));
543        return $footer;
544    }
545
546    /**
547     * Appends instruction item for an edit button
548     *
549     * @author Michael Klier <chi@chimeric.de>
550     */
551    function _editbtn(&$ins, $page, $sect, $sect_title, $root_id) {
552        $title = ($sect) ? $sect_title : $page;
553        $editbtn = array();
554        $editbtn[0] = 'plugin';
555        $editbtn[1] = array('include_editbtn', array($title));
556        $ins[] = $editbtn;
557    }
558
559    /**
560     * Convert instruction item for a permalink header
561     *
562     * @author Michael Klier <chi@chimeric.de>
563     */
564    function _permalink(&$ins, $page, $sect, $flags) {
565        $ins[0] = 'plugin';
566        $ins[1] = array('include_header', array($ins[1][0], $ins[1][1], $ins[1][2], $page, $sect, $flags));
567    }
568
569    /**
570     * Get a section including its subsections
571     *
572     * @author Michael Klier <chi@chimeric.de>
573     */
574    function _get_section(&$ins, $sect) {
575        $num = count($ins);
576        $offset = false;
577        $lvl    = false;
578        $end    = false;
579        $endpos = null; // end position in the input text, needed for section edit buttons
580
581        $check = array(); // used for sectionID() in order to get the same ids as the xhtml renderer
582
583        for($i=0; $i<$num; $i++) {
584            if ($ins[$i][0] == 'header') {
585
586                // found the right header
587                if (sectionID($ins[$i][1][0], $check) == $sect) {
588                    $offset = $i;
589                    $lvl    = $ins[$i][1][1];
590                } elseif ($offset && $lvl && ($ins[$i][1][1] <= $lvl)) {
591                    $end = $i - $offset;
592                    $endpos = $ins[$i][1][2]; // the position directly after the found section, needed for the section edit button
593                    break;
594                }
595            }
596        }
597        $offset = $offset ? $offset : 0;
598        $end = $end ? $end : ($num - 1);
599        if(is_array($ins)) {
600            $ins = array_slice($ins, $offset, $end);
601            // store the end position in the include_closelastsecedit instruction so it can generate a matching button
602            $ins[] = array('plugin', array('include_closelastsecedit', array($endpos)));
603        }
604    }
605
606    /**
607     * Only display the first section of a page and a readmore link
608     *
609     * @author Michael Klier <chi@chimeric.de>
610     */
611    function _get_firstsec(&$ins, $page) {
612        $num = count($ins);
613        $first_sect = false;
614        $endpos = null; // end position in the input text
615        for($i=0; $i<$num; $i++) {
616            if($ins[$i][0] == 'section_close') {
617                $first_sect = $i;
618            }
619            if ($ins[$i][0] == 'header') {
620                /*
621                 * Store the position of the last header that is encountered. As section_close/open-instruction are
622                 * always (unless some plugin modifies this) around a header instruction this means that the last
623                 * position that is stored here is exactly the position of the section_close/open at which the content
624                 * is truncated.
625                 */
626                $endpos = $ins[$i][1][2];
627            }
628            // only truncate the content and add the read more link when there is really
629            // more than that first section
630            if(($first_sect) && ($ins[$i][0] == 'section_open')) {
631                $ins = array_slice($ins, 0, $first_sect);
632                $ins[] = array('plugin', array('include_readmore', array($page)));
633                $ins[] = array('section_close', array());
634                // store the end position in the include_closelastsecedit instruction so it can generate a matching button
635                $ins[] = array('plugin', array('include_closelastsecedit', array($endpos)));
636                return;
637            }
638        }
639    }
640
641    /**
642     * Gives a list of pages for a given include statement
643     *
644     * @author Michael Hamann <michael@content-space.de>
645     */
646    function _get_included_pages($mode, $page, $sect, $parent_id, $flags) {
647        global $conf;
648        $pages = array();
649        switch($mode) {
650        case 'namespace':
651            $page  = cleanID($page);
652            $ns    = utf8_encodeFN(str_replace(':', '/', $page));
653            // depth is absolute depth, not relative depth, but 0 has a special meaning.
654            $depth = $flags['depth'] ? $flags['depth'] + substr_count($page, ':') + ($page ? 1 : 0) : 0;
655            search($pagearrays, $conf['datadir'], 'search_allpages', array('depth' => $depth), $ns);
656            if (is_array($pagearrays)) {
657                foreach ($pagearrays as $pagearray) {
658                    if (!isHiddenPage($pagearray['id'])) // skip hidden pages
659                        $pages[] = $pagearray['id'];
660                }
661            }
662            break;
663        case 'tagtopic':
664            if (!$this->taghelper)
665                $this->taghelper =& plugin_load('helper', 'tag');
666            if(!$this->taghelper) {
667                msg('You have to install the tag plugin to use this functionality!', -1);
668                return array();
669            }
670            $tag   = $page;
671            $sect  = '';
672            $pagearrays = $this->taghelper->getTopic('', null, $tag);
673            foreach ($pagearrays as $pagearray) {
674                $pages[] = $pagearray['id'];
675            }
676            break;
677        default:
678            $page = $this->_apply_macro($page);
679            resolve_pageid(getNS($parent_id), $page, $exists); // resolve shortcuts and clean ID
680            if (auth_quickaclcheck($page) >= AUTH_READ)
681                $pages[] = $page;
682        }
683
684        if (count($pages) > 1) {
685            if ($flags['order'] === 'id') {
686                if ($flags['rsort']) {
687                    usort($pages, array($this, '_r_strnatcasecmp'));
688                } else {
689                    natcasesort($pages);
690                }
691            } else {
692                $ordered_pages = array();
693                foreach ($pages as $page) {
694                    $key = '';
695                    switch ($flags['order']) {
696                        case 'title':
697                            $key = p_get_first_heading($page);
698                            break;
699                        case 'created':
700                            $key = p_get_metadata($page, 'date created', METADATA_DONT_RENDER);
701                            break;
702                        case 'modified':
703                            $key = p_get_metadata($page, 'date modified', METADATA_DONT_RENDER);
704                            break;
705                        case 'indexmenu':
706                            $key = p_get_metadata($page, 'indexmenu_n', METADATA_RENDER_USING_SIMPLE_CACHE);
707                            if ($key === null)
708                                $key = '';
709                            break;
710                        case 'custom':
711                            $key = p_get_metadata($page, 'include_n', METADATA_RENDER_USING_SIMPLE_CACHE);
712                            if ($key === null)
713                                $key = '';
714                            break;
715                    }
716                    $key .= '_'.$page;
717                    $ordered_pages[$key] = $page;
718                }
719                if ($flags['rsort']) {
720                    uksort($ordered_pages, array($this, '_r_strnatcasecmp'));
721                } else {
722                    uksort($ordered_pages, 'strnatcasecmp');
723                }
724                $pages = $ordered_pages;
725            }
726        }
727
728        $result = array();
729        foreach ($pages as $page) {
730            $exists = page_exists($page);
731            $result[] = array('id' => $page, 'exists' => $exists, 'parent_id' => $parent_id);
732        }
733        return $result;
734    }
735
736    /**
737     * String comparisons using a "natural order" algorithm in reverse order
738     *
739     * @link http://php.net/manual/en/function.strnatcmp.php
740     * @param string $a First string
741     * @param string $b Second string
742     * @return int Similar to other string comparison functions, this one returns &lt; 0 if
743     * str1 is greater than str2; &gt;
744     * 0 if str1 is lesser than
745     * str2, and 0 if they are equal.
746     */
747    function _r_strnatcasecmp($a, $b) {
748        return strnatcasecmp($b, $a);
749    }
750
751    /**
752     * This function generates the list of all included pages from a list of metadata
753     * instructions.
754     */
755    function _get_included_pages_from_meta_instructions($instructions) {
756        $pages = array();
757        foreach ($instructions as $instruction) {
758            $mode      = $instruction['mode'];
759            $page      = $instruction['page'];
760            $sect      = $instruction['sect'];
761            $parent_id = $instruction['parent_id'];
762            $flags     = $instruction['flags'];
763            $pages = array_merge($pages, $this->_get_included_pages($mode, $page, $sect, $parent_id, $flags));
764        }
765        return $pages;
766    }
767
768    /**
769     * Makes user or date dependent includes possible
770     */
771    function _apply_macro($id) {
772        global $INFO;
773        global $auth;
774
775        // if we don't have an auth object, do nothing
776        if (!$auth) return $id;
777
778        $user     = $_SERVER['REMOTE_USER'];
779        $group    = $INFO['userinfo']['grps'][0];
780
781        $time_stamp = time();
782        if(preg_match('/@DATE(\w+)@/',$id,$matches)) {
783            switch($matches[1]) {
784            case 'PMONTH':
785                $time_stamp = strtotime("-1 month");
786                break;
787            case 'NMONTH':
788                $time_stamp = strtotime("+1 month");
789                break;
790            case 'NWEEK':
791                $time_stamp = strtotime("+1 week");
792                break;
793            case 'PWEEK':
794                $time_stamp = strtotime("-1 week");
795                break;
796            case 'TOMORROW':
797                $time_stamp = strtotime("+1 day");
798                break;
799            case 'YESTERDAY':
800                $time_stamp = strtotime("-1 day");
801                break;
802            case 'NYEAR':
803                $time_stamp = strtotime("+1 year");
804                break;
805            case 'PYEAR':
806                $time_stamp = strtotime("-1 year");
807                break;
808            }
809            $id = preg_replace('/@DATE(\w+)@/','', $id);
810        }
811
812        $replace = array(
813                '@USER@'  => cleanID($user),
814                '@NAME@'  => cleanID($INFO['userinfo']['name']),
815                '@GROUP@' => cleanID($group),
816                '@YEAR@'  => date('Y',$time_stamp),
817                '@MONTH@' => date('m',$time_stamp),
818                '@WEEK@' => date('W',$time_stamp),
819                '@DAY@'   => date('d',$time_stamp),
820                '@YEARPMONTH@' => date('Ym',strtotime("-1 month")),
821                '@PMONTH@' => date('m',strtotime("-1 month")),
822                '@NMONTH@' => date('m',strtotime("+1 month")),
823                '@YEARNMONTH@' => date('Ym',strtotime("+1 month")),
824                '@YEARPWEEK@' => date('YW',strtotime("-1 week")),
825                '@PWEEK@' => date('W',strtotime("-1 week")),
826                '@NWEEK@' => date('W',strtotime("+1 week")),
827                '@YEARNWEEK@' => date('YW',strtotime("+1 week")),
828                );
829        return str_replace(array_keys($replace), array_values($replace), $id);
830    }
831}
832// vim:ts=4:sw=4:et:
833