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