xref: /plugin/include/helper.php (revision 6d657b495a40af52d88e45e0b3558bf603c87d36)
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['firstsec']  = $this->getConf('firstseconly');
30        $this->defaults['editbtn']   = $this->getConf('showeditbtn');
31        $this->defaults['taglogos']  = $this->getConf('showtaglogos');
32        $this->defaults['footer']    = $this->getConf('showfooter');
33        $this->defaults['redirect']  = $this->getConf('doredirect');
34        $this->defaults['date']      = $this->getConf('showdate');
35        $this->defaults['user']      = $this->getConf('showuser');
36        $this->defaults['comments']  = $this->getConf('showcomments');
37        $this->defaults['linkbacks'] = $this->getConf('showlinkbacks');
38        $this->defaults['tags']      = $this->getConf('showtags');
39        $this->defaults['link']      = $this->getConf('showlink');
40        $this->defaults['permalink'] = $this->getConf('showpermalink');
41        $this->defaults['indent']    = $this->getConf('doindent');
42        $this->defaults['linkonly']  = $this->getConf('linkonly');
43        $this->defaults['title']     = $this->getConf('title');
44        $this->defaults['pageexists']  = $this->getConf('pageexists');
45        $this->defaults['parlink']   = $this->getConf('parlink');
46        $this->defaults['inline']    = false;
47    }
48
49    /**
50     * Available methods for other plugins
51     */
52    function getMethods() {
53        $result = array();
54        $result[] = array(
55                'name'   => 'get_flags',
56                'desc'   => 'overrides standard values for showfooter and firstseconly settings',
57                'params' => array('flags' => 'array'),
58                );
59        return $result;
60    }
61
62    /**
63     * Overrides standard values for showfooter and firstseconly settings
64     */
65    function get_flags($setflags) {
66        // load defaults
67        $flags = array();
68        $flags = $this->defaults;
69        foreach ($setflags as $flag) {
70            switch ($flag) {
71                case 'footer':
72                    $flags['footer'] = 1;
73                    break;
74                case 'nofooter':
75                    $flags['footer'] = 0;
76                    break;
77                case 'firstseconly':
78                case 'firstsectiononly':
79                    $flags['firstsec'] = 1;
80                    break;
81                case 'fullpage':
82                    $flags['firstsec'] = 0;
83                    break;
84                case 'noheader':
85                    $flags['noheader'] = 1;
86                    break;
87                case 'editbtn':
88                case 'editbutton':
89                    $flags['editbtn'] = 1;
90                    break;
91                case 'noeditbtn':
92                case 'noeditbutton':
93                    $flags['editbtn'] = 0;
94                    break;
95                case 'permalink':
96                    $flags['permalink'] = 1;
97                    break;
98                case 'nopermalink':
99                    $flags['permalink'] = 0;
100                    break;
101                case 'redirect':
102                    $flags['redirect'] = 1;
103                    break;
104                case 'noredirect':
105                    $flags['redirect'] = 0;
106                    break;
107                case 'link':
108                    $flags['link'] = 1;
109                    break;
110                case 'nolink':
111                    $flags['link'] = 0;
112                    break;
113                case 'user':
114                    $flags['user'] = 1;
115                    break;
116                case 'nouser':
117                    $flags['user'] = 0;
118                    break;
119                case 'comments':
120                    $flags['comments'] = 1;
121                    break;
122                case 'nocomments':
123                    $flags['comments'] = 0;
124                    break;
125                case 'linkbacks':
126                    $flags['linkbacks'] = 1;
127                    break;
128                case 'nolinkbacks':
129                    $flags['linkbacks'] = 0;
130                    break;
131                case 'tags':
132                    $flags['tags'] = 1;
133                    break;
134                case 'notags':
135                    $flags['tags'] = 0;
136                    break;
137                case 'date':
138                    $flags['date'] = 1;
139                    break;
140                case 'nodate':
141                    $flags['date'] = 0;
142                    break;
143                case 'indent':
144                    $flags['indent'] = 1;
145                    break;
146                case 'noindent':
147                    $flags['indent'] = 0;
148                    break;
149                case 'linkonly':
150                    $flags['linkonly'] = 1;
151                    break;
152                case 'nolinkonly':
153                case 'include_content':
154                    $flags['linkonly'] = 0;
155                    break;
156                case 'inline':
157                    $flags['inline'] = 1;
158                    break;
159                case 'title':
160                    $flags['title'] = 1;
161                    break;
162                case 'pageexists':
163                    $flags['pageexists'] = 1;
164                    break;
165                case 'existlink':
166                    $flags['pageexists'] = 1;
167                    $flags['linkonly'] = 1;
168                    break;
169                case 'noparlink':
170                    $flags['parlink'] = 0;
171                    break;
172            }
173        }
174        // the include_content URL parameter overrides flags
175        if (isset($_REQUEST['include_content']))
176            $flags['linkonly'] = 0;
177        return $flags;
178    }
179
180    /**
181     * Returns the converted instructions of a give page/section
182     *
183     * @author Michael Klier <chi@chimeric.de>
184     * @author Michael Hamann <michael@content-space.de>
185     */
186    function _get_instructions($page, $sect, $mode, $lvl, $flags, $root_id = null) {
187        $key = ($sect) ? $page . '#' . $sect : $page;
188        $this->includes[$key] = true; // legacy code for keeping compatibility with other plugins
189
190        // keep compatibility with other plugins that don't know the $root_id parameter
191        if (is_null($root_id)) {
192            global $ID;
193            $root_id = $ID;
194        }
195
196        if ($flags['linkonly']) {
197            if (page_exists($page) || $flags['pageexists']  == 0) {
198                $title = '';
199                if ($flags['title'])
200                    $title = p_get_first_heading($page);
201                if($flags['parlink']) {
202                    $ins = array(
203                        array('p_open', array()),
204                        array('internallink', array(':'.$key, $title)),
205                        array('p_close', array()),
206                    );
207                } else {
208                    $ins = array(array('internallink', array(':'.$key,$title)));
209                }
210            }else {
211                $ins = array();
212            }
213        } else {
214            if (page_exists($page)) {
215                global $ID;
216                $backupID = $ID;
217                $ID = $page; // Change the global $ID as otherwise plugins like the discussion plugin will save data for the wrong page
218                $ins = p_cached_instructions(wikiFN($page));
219                $ID = $backupID;
220            } else {
221                $ins = array();
222            }
223
224            $this->_convert_instructions($ins, $lvl, $page, $sect, $flags, $root_id);
225        }
226        return $ins;
227    }
228
229    /**
230     * Converts instructions of the included page
231     *
232     * The funcion iterates over the given list of instructions and generates
233     * an index of header and section indicies. It also removes document
234     * start/end instructions, converts links, and removes unwanted
235     * instructions like tags, comments, linkbacks.
236     *
237     * Later all header/section levels are convertet to match the current
238     * inclusion level.
239     *
240     * @author Michael Klier <chi@chimeric.de>
241     */
242    function _convert_instructions(&$ins, $lvl, $page, $sect, $flags, $root_id) {
243        global $conf;
244
245        // filter instructions if needed
246        if(!empty($sect)) {
247            $this->_get_section($ins, $sect);   // section required
248        }
249
250        if($flags['firstsec']) {
251            $this->_get_firstsec($ins, $page);  // only first section
252        }
253
254        $ns  = getNS($page);
255        $num = count($ins);
256
257        $conv_idx = array(); // conversion index
258        $lvl_max  = false;   // max level
259        $first_header = -1;
260        $no_header  = false;
261        $sect_title = false;
262        $endpos     = null; // end position of the raw wiki text
263
264        for($i=0; $i<$num; $i++) {
265            switch($ins[$i][0]) {
266                case 'document_start':
267                case 'document_end':
268                case 'section_edit':
269                    unset($ins[$i]);
270                    break;
271                case 'header':
272                    // get section title of first section
273                    if($sect && !$sect_title) {
274                        $sect_title = $ins[$i][1][0];
275                    }
276                    // check if we need to skip the first header
277                    if((!$no_header) && $flags['noheader']) {
278                        $no_header = true;
279                    }
280
281                    $conv_idx[] = $i;
282                    // get index of first header
283                    if($first_header == -1) $first_header = $i;
284                    // get max level of this instructions set
285                    if(!$lvl_max || ($ins[$i][1][1] < $lvl_max)) {
286                        $lvl_max = $ins[$i][1][1];
287                    }
288                    break;
289                case 'section_open':
290                    if ($flags['inline'])
291                        unset($ins[$i]);
292                    else
293                        $conv_idx[] = $i;
294                    break;
295                case 'section_close':
296                    if ($flags['inline'])
297                        unset($ins[$i]);
298                    break;
299                case 'internallink':
300                case 'internalmedia':
301                    // make sure parameters aren't touched
302                    $link_params = '';
303                    $link_id = $ins[$i][1][0];
304                    $link_parts = explode('?', $link_id, 2);
305                    if (count($link_parts) === 2) {
306                        $link_id = $link_parts[0];
307                        $link_params = $link_parts[1];
308                    }
309                    // resolve the id without cleaning it
310                    $link_id = resolve_id($ns, $link_id, false);
311                    // this id is internal (i.e. absolute) now, add ':' to make resolve_id work again
312                    if ($link_id{0} != ':') $link_id = ':'.$link_id;
313                    // restore parameters
314                    $ins[$i][1][0] = ($link_params != '') ? $link_id.'?'.$link_params : $link_id;
315                    break;
316                case 'plugin':
317                    // FIXME skip other plugins?
318                    switch($ins[$i][1][0]) {
319                        case 'tag_tag':                 // skip tags
320                        case 'discussion_comments':     // skip comments
321                        case 'linkback':                // skip linkbacks
322                        case 'data_entry':              // skip data plugin
323                        case 'meta':                    // skip meta plugin
324                            unset($ins[$i]);
325                            break;
326                        // adapt indentation level of nested includes
327                        case 'include_include':
328                            if (!$flags['inline'] && $flags['indent'])
329                                $ins[$i][1][1][4] += $lvl;
330                            break;
331                        /*
332                         * if there is already a closelastsecedit instruction (was added by one of the section
333                         * functions), store its position but delete it as it can't be determined yet if it is needed,
334                         * i.e. if there is a header which generates a section edit (depends on the levels, level
335                         * adjustments, $no_header, ...)
336                         */
337                        case 'include_closelastsecedit':
338                            $endpos = $ins[$i][1][1][0];
339                            unset($ins[$i]);
340                            break;
341                    }
342                    break;
343                default:
344                    break;
345            }
346        }
347
348        // calculate difference between header/section level and include level
349        $diff = 0;
350        if (!isset($lvl_max)) $lvl_max = 0; // if no level found in target, set to 0
351        $diff = $lvl - $lvl_max + 1;
352        if ($no_header) $diff -= 1;  // push up one level if "noheader"
353
354        // convert headers and set footer/permalink
355        $hdr_deleted      = false;
356        $has_permalink    = false;
357        $footer_lvl       = false;
358        $contains_secedit = false;
359        $section_close_at = false;
360        foreach($conv_idx as $idx) {
361            if($ins[$idx][0] == 'header') {
362                if ($section_close_at === false) {
363                    // store the index of the first heading (the begin of the first section)
364                    $section_close_at = $idx;
365                }
366
367                if($no_header && !$hdr_deleted) {
368                    unset ($ins[$idx]);
369                    $hdr_deleted = true;
370                    continue;
371                }
372
373                if($flags['indent']) {
374                    $lvl_new = (($ins[$idx][1][1] + $diff) > 5) ? 5 : ($ins[$idx][1][1] + $diff);
375                    $ins[$idx][1][1] = $lvl_new;
376                }
377
378                if($ins[$idx][1][1] <= $conf['maxseclevel'])
379                    $contains_secedit = true;
380
381                // set permalink
382                if($flags['link'] && !$has_permalink && ($idx == $first_header)) {
383                    $this->_permalink($ins[$idx], $page, $sect, $flags);
384                    $has_permalink = true;
385                }
386
387                // set footer level
388                if(!$footer_lvl && ($idx == $first_header) && !$no_header) {
389                    if($flags['indent']) {
390                        $footer_lvl = $lvl_new;
391                    } else {
392                        $footer_lvl = $lvl_max;
393                    }
394                }
395            } else {
396                // it's a section
397                if($flags['indent']) {
398                    $lvl_new = (($ins[$idx][1][0] + $diff) > 5) ? 5 : ($ins[$idx][1][0] + $diff);
399                    $ins[$idx][1][0] = $lvl_new;
400                }
401
402                // check if noheader is used and set the footer level to the first section
403                if($no_header && !$footer_lvl) {
404                    if($flags['indent']) {
405                        $footer_lvl = $lvl_new;
406                    } else {
407                        $footer_lvl = $lvl_max;
408                    }
409                }
410            }
411        }
412
413        // close last open section of the included page if there is any
414        if ($contains_secedit) {
415            array_push($ins, array('plugin', array('include_closelastsecedit', array($endpos))));
416        }
417
418        // add edit button
419        if($flags['editbtn']) {
420            $this->_editbtn($ins, $page, $sect, $sect_title, ($flags['redirect'] ? $root_id : false));
421        }
422
423        // add footer
424        if($flags['footer']) {
425            $ins[] = $this->_footer($page, $sect, $sect_title, $flags, $footer_lvl, $root_id);
426        }
427
428        // wrap content at the beginning of the include that is not in a section in a section
429        if ($lvl > 0 && $section_close_at !== 0 && $flags['indent'] && !$flags['inline']) {
430            if ($section_close_at === false) {
431                $ins[] = array('section_close', array());
432                array_unshift($ins, array('section_open', array($lvl)));
433            } else {
434                $section_close_idx = array_search($section_close_at, array_keys($ins));
435                if ($section_close_idx > 0) {
436                    $before_ins = array_slice($ins, 0, $section_close_idx);
437                    $after_ins = array_slice($ins, $section_close_idx);
438                    $ins = array_merge($before_ins, array(array('section_close', array())), $after_ins);
439                    array_unshift($ins, array('section_open', array($lvl)));
440                }
441            }
442        }
443
444        // add instructions entry wrapper
445        array_unshift($ins, array('plugin', array('include_wrap', array('open', $page, $flags['redirect']))));
446        array_push($ins, array('plugin', array('include_wrap', array('close'))));
447
448        // close previous section if any and re-open after inclusion
449        if($lvl != 0 && $this->sec_close && !$flags['inline']) {
450            array_unshift($ins, array('section_close', array()));
451            $ins[] = array('section_open', array($lvl));
452        }
453    }
454
455    /**
456     * Appends instruction item for the include plugin footer
457     *
458     * @author Michael Klier <chi@chimeric.de>
459     */
460    function _footer($page, $sect, $sect_title, $flags, $footer_lvl, $root_id) {
461        $footer = array();
462        $footer[0] = 'plugin';
463        $footer[1] = array('include_footer', array($page, $sect, $sect_title, $flags, $root_id, $footer_lvl));
464        return $footer;
465    }
466
467    /**
468     * Appends instruction item for an edit button
469     *
470     * @author Michael Klier <chi@chimeric.de>
471     */
472    function _editbtn(&$ins, $page, $sect, $sect_title, $root_id) {
473        $title = ($sect) ? $sect_title : $page;
474        $editbtn = array();
475        $editbtn[0] = 'plugin';
476        $editbtn[1] = array('include_editbtn', array($title));
477        $ins[] = $editbtn;
478    }
479
480    /**
481     * Convert instruction item for a permalink header
482     *
483     * @author Michael Klier <chi@chimeric.de>
484     */
485    function _permalink(&$ins, $page, $sect, $flags) {
486        $ins[0] = 'plugin';
487        $ins[1] = array('include_header', array($ins[1][0], $ins[1][1], $ins[1][2], $page, $sect, $flags));
488    }
489
490    /**
491     * Get a section including its subsections
492     *
493     * @author Michael Klier <chi@chimeric.de>
494     */
495    function _get_section(&$ins, $sect) {
496        $num = count($ins);
497        $offset = false;
498        $lvl    = false;
499        $end    = false;
500        $endpos = null; // end position in the input text, needed for section edit buttons
501
502        $check = array(); // used for sectionID() in order to get the same ids as the xhtml renderer
503
504        for($i=0; $i<$num; $i++) {
505            if ($ins[$i][0] == 'header') {
506
507                // found the right header
508                if (sectionID($ins[$i][1][0], $check) == $sect) {
509                    $offset = $i;
510                    $lvl    = $ins[$i][1][1];
511                } elseif ($offset && $lvl && ($ins[$i][1][1] <= $lvl)) {
512                    $end = $i - $offset;
513                    $endpos = $ins[$i][1][2]; // the position directly after the found section, needed for the section edit button
514                    break;
515                }
516            }
517        }
518        $offset = $offset ? $offset : 0;
519        $end = $end ? $end : ($num - 1);
520        if(is_array($ins)) {
521            $ins = array_slice($ins, $offset, $end);
522            // store the end position in the include_closelastsecedit instruction so it can generate a matching button
523            $ins[] = array('plugin', array('include_closelastsecedit', array($endpos)));
524        }
525    }
526
527    /**
528     * Only display the first section of a page and a readmore link
529     *
530     * @author Michael Klier <chi@chimeric.de>
531     */
532    function _get_firstsec(&$ins, $page) {
533        $num = count($ins);
534        $first_sect = false;
535        $endpos = null; // end position in the input text
536        for($i=0; $i<$num; $i++) {
537            if($ins[$i][0] == 'section_close') {
538                $first_sect = $i;
539            }
540            if ($ins[$i][0] == 'header') {
541                /*
542                 * Store the position of the last header that is encountered. As section_close/open-instruction are
543                 * always (unless some plugin modifies this) around a header instruction this means that the last
544                 * position that is stored here is exactly the position of the section_close/open at which the content
545                 * is truncated.
546                 */
547                $endpos = $ins[$i][1][2];
548            }
549            // only truncate the content and add the read more link when there is really
550            // more than that first section
551            if(($first_sect) && ($ins[$i][0] == 'section_open')) {
552                $ins = array_slice($ins, 0, $first_sect);
553                $ins[] = array('plugin', array('include_readmore', array($page)));
554                $ins[] = array('section_close', array());
555                // store the end position in the include_closelastsecedit instruction so it can generate a matching button
556                $ins[] = array('plugin', array('include_closelastsecedit', array($endpos)));
557                return;
558            }
559        }
560    }
561
562    /**
563     * Gives a list of pages for a given include statement
564     *
565     * @author Michael Hamann <michael@content-space.de>
566     */
567    function _get_included_pages($mode, $page, $sect, $parent_id) {
568        global $conf;
569        $pages = array();
570        switch($mode) {
571        case 'namespace':
572            $ns    = str_replace(':', '/', cleanID($page));
573            search($pagearrays, $conf['datadir'], 'search_list', '', $ns);
574            if (is_array($pagearrays)) {
575                foreach ($pagearrays as $pagearray) {
576                    $pages[] = $pagearray['id'];
577                }
578            }
579            break;
580        case 'tagtopic':
581            if (!$this->taghelper)
582                $this->taghelper =& plugin_load('helper', 'tag');
583            if(!$this->taghelper) {
584                msg('You have to install the tag plugin to use this functionality!', -1);
585                return array();
586            }
587            $tag   = $page;
588            $sect  = '';
589            $pagearrays = $this->taghelper->getTopic('', null, $tag);
590            foreach ($pagearrays as $pagearray) {
591                $pages[] = $pagearray['id'];
592            }
593            break;
594        default:
595            $page = $this->_apply_macro($page);
596            resolve_pageid(getNS($parent_id), $page, $exists); // resolve shortcuts and clean ID
597            if (auth_quickaclcheck($page) >= AUTH_READ)
598                $pages[] = $page;
599        }
600
601        sort($pages);
602
603        $result = array();
604        foreach ($pages as $page) {
605            $exists = page_exists($page);
606            $result[] = array('id' => $page, 'exists' => $exists, 'parent_id' => $parent_id);
607        }
608        return $result;
609    }
610
611    /**
612     * This function generates the list of all included pages from a list of metadata
613     * instructions.
614     */
615    function _get_included_pages_from_meta_instructions($instructions) {
616        $pages = array();
617        foreach ($instructions as $instruction) {
618            extract($instruction);
619            $pages = array_merge($pages, $this->_get_included_pages($mode, $page, $sect, $parent_id));
620        }
621        return $pages;
622    }
623
624    /**
625     * Makes user or date dependent includes possible
626     */
627    function _apply_macro($id) {
628        global $INFO;
629        global $auth;
630
631        // if we don't have an auth object, do nothing
632        if (!$auth) return $id;
633
634        $user     = $_SERVER['REMOTE_USER'];
635        $group    = $INFO['userinfo']['grps'][0];
636
637        $time_stamp = time();
638        if(preg_match('/@DATE(\w+)@/',$id,$matches)) {
639            switch($matches[1]) {
640            case 'PMONTH':
641                $time_stamp = strtotime("-1 month");
642                break;
643            case 'NMONTH':
644                $time_stamp = strtotime("+1 month");
645                break;
646            case 'NWEEK':
647                $time_stamp = strtotime("+1 week");
648                break;
649            case 'PWEEK':
650                $time_stamp = strtotime("-1 week");
651                break;
652            case 'TOMORROW':
653                $time_stamp = strtotime("+1 day");
654                break;
655            case 'YESTERDAY':
656                $time_stamp = strtotime("-1 day");
657                break;
658            case 'NYEAR':
659                $time_stamp = strtotime("+1 year");
660                break;
661            case 'PYEAR':
662                $time_stamp = strtotime("-1 year");
663                break;
664            }
665            $id = preg_replace('/@DATE(\w+)@/','', $id);
666        }
667
668        $replace = array(
669                '@USER@'  => cleanID($user),
670                '@NAME@'  => cleanID($INFO['userinfo']['name']),
671                '@GROUP@' => cleanID($group),
672                '@YEAR@'  => date('Y',$time_stamp),
673                '@MONTH@' => date('m',$time_stamp),
674                '@WEEK@' => date('W',$time_stamp),
675                '@DAY@'   => date('d',$time_stamp),
676                '@YEARPMONTH@' => date('Ym',strtotime("-1 month")),
677                '@PMONTH@' => date('m',strtotime("-1 month")),
678                '@NMONTH@' => date('m',strtotime("+1 month")),
679                '@YEARNMONTH@' => date('Ym',strtotime("+1 month")),
680                '@YEARPWEEK@' => date('YW',strtotime("-1 week")),
681                '@PWEEK@' => date('W',strtotime("-1 week")),
682                '@NWEEK@' => date('W',strtotime("+1 week")),
683                '@YEARNWEEK@' => date('YW',strtotime("+1 week")),
684                );
685        return str_replace(array_keys($replace), array_values($replace), $id);
686    }
687}
688// vim:ts=4:sw=4:et:
689