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