xref: /plugin/include/helper.php (revision e200f7a891cea3052273ef46e9950ed0b771ff68)
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    }
43
44    /**
45     * Available methods for other plugins
46     */
47    function getMethods() {
48        $result = array();
49        $result[] = array(
50                'name'   => 'get_flags',
51                'desc'   => 'overrides standard values for showfooter and firstseconly settings',
52                'params' => array('flags' => 'array'),
53                );
54        return $result;
55    }
56
57    /**
58     * Overrides standard values for showfooter and firstseconly settings
59     */
60    function get_flags($setflags) {
61        // load defaults
62        $flags = array();
63        $flags = $this->defaults;
64        foreach ($setflags as $flag) {
65            switch ($flag) {
66                case 'footer':
67                    $flags['footer'] = 1;
68                    break;
69                case 'nofooter':
70                    $flags['footer'] = 0;
71                    break;
72                case 'firstseconly':
73                case 'firstsectiononly':
74                    $flags['firstsec'] = 1;
75                    break;
76                case 'fullpage':
77                    $flags['firstsec'] = 0;
78                    break;
79                case 'noheader':
80                    $flags['noheader'] = 1;
81                    break;
82                case 'editbtn':
83                case 'editbutton':
84                    $flags['editbtn'] = 1;
85                    break;
86                case 'noeditbtn':
87                case 'noeditbutton':
88                    $flags['editbtn'] = 0;
89                    break;
90                case 'permalink':
91                    $flags['permalink'] = 1;
92                    break;
93                case 'nopermalink':
94                    $flags['permalink'] = 0;
95                    break;
96                case 'redirect':
97                    $flags['redirect'] = 1;
98                    break;
99                case 'noredirect':
100                    $flags['redirect'] = 0;
101                    break;
102                case 'link':
103                    $flags['link'] = 1;
104                    break;
105                case 'nolink':
106                    $flags['link'] = 0;
107                    break;
108                case 'user':
109                    $flags['user'] = 1;
110                    break;
111                case 'nouser':
112                    $flags['user'] = 0;
113                    break;
114                case 'comments':
115                    $flags['comments'] = 1;
116                    break;
117                case 'nocomments':
118                    $flags['comments'] = 0;
119                    break;
120                case 'linkbacks':
121                    $flags['linkbacks'] = 1;
122                    break;
123                case 'nolinkbacks':
124                    $flags['linkbacks'] = 0;
125                    break;
126                case 'tags':
127                    $flags['tags'] = 1;
128                    break;
129                case 'notags':
130                    $flags['tags'] = 0;
131                    break;
132                case 'date':
133                    $flags['date'] = 1;
134                    break;
135                case 'nodate':
136                    $flags['date'] = 0;
137                    break;
138                case 'indent':
139                    $flags['indent'] = 1;
140                    break;
141                case 'noindent':
142                    $flags['indent'] = 0;
143                    break;
144            }
145        }
146        return $flags;
147    }
148
149    /**
150     * Returns the converted instructions of a give page/section
151     *
152     * @author Michael Klier <chi@chimeric.de>
153     * @author Michael Hamann <michael@content-space.de>
154     */
155    function _get_instructions($page, $sect, $mode, $lvl, $flags, $root_id = null) {
156        $key = ($sect) ? $page . '#' . $sect : $page;
157        $this->includes[$key] = true; // legacy code for keeping compatibility with other plugins
158
159        // keep compatibility with other plugins that don't know the $root_id parameter
160        if (is_null($root_id)) {
161            global $ID;
162            $root_id = $ID;
163        }
164
165        $ins = p_cached_instructions(wikiFN($page));
166        $this->_convert_instructions($ins, $lvl, $page, $sect, $flags, $root_id);
167        return $ins;
168    }
169
170    /**
171     * Converts instructions of the included page
172     *
173     * The funcion iterates over the given list of instructions and generates
174     * an index of header and section indicies. It also removes document
175     * start/end instructions, converts links, and removes unwanted
176     * instructions like tags, comments, linkbacks.
177     *
178     * Later all header/section levels are convertet to match the current
179     * inclusion level.
180     *
181     * @author Michael Klier <chi@chimeric.de>
182     */
183    function _convert_instructions(&$ins, $lvl, $page, $sect, $flags, $root_id) {
184        global $conf;
185
186        // filter instructions if needed
187        if(!empty($sect)) {
188            $this->_get_section($ins, $sect);   // section required
189        }
190
191        if($flags['firstsec']) {
192            $this->_get_firstsec($ins, $page);  // only first section
193        }
194
195        $ns  = getNS($page);
196        $num = count($ins);
197
198        $conv_idx = array(); // conversion index
199        $lvl_max  = false;   // max level
200        $first_header = -1;
201        $no_header  = false;
202        $sect_title = false;
203
204        for($i=0; $i<$num; $i++) {
205            switch($ins[$i][0]) {
206                case 'document_start':
207                case 'document_end':
208                case 'section_edit':
209                    unset($ins[$i]);
210                    break;
211                case 'header':
212                    // get section title of first section
213                    if($sect && !$sect_title) {
214                        $sect_title = $ins[$i][1][0];
215                    }
216                    // check if we need to skip the first header
217                    if((!$no_header) && $flags['noheader']) {
218                        $no_header = true;
219                    }
220
221                    $conv_idx[] = $i;
222                    // get index of first header
223                    if($first_header == -1) $first_header = $i;
224                    // get max level of this instructions set
225                    if(!$lvl_max || ($ins[$i][1][1] < $lvl_max)) {
226                        $lvl_max = $ins[$i][1][1];
227                    }
228                    break;
229                case 'section_open':
230                    $conv_idx[] = $i;
231                    break;
232                case 'internallink':
233                case 'internalmedia':
234                    if($ins[$i][1][0]{0} == '.') {
235                        if($ins[$i][1][0]{1} == '.') {
236                            $ins[$i][1][0] = getNS($ns) . ':' . substr($ins[$i][1][0], 2); // parent namespace
237                        } else {
238                            $ins[$i][1][0] = $ns . ':' . substr($ins[$i][1][0], 1); // current namespace
239                        }
240                    } elseif (strpos($ins[$i][1][0], ':') === false) {
241                        $ins[$i][1][0] = $ns . ':' . $ins[$i][1][0]; // relative links
242                    }
243                    break;
244                case 'plugin':
245                    // FIXME skip other plugins?
246                    switch($ins[$i][1][0]) {
247                        case 'tag_tag':                 // skip tags
248                        case 'discussion_comments':     // skip comments
249                        case 'linkback':                // skip linkbacks
250                        case 'data_entry':              // skip data plugin
251                        case 'meta':                    // skip meta plugin
252                            unset($ins[$i]);
253                            break;
254                        // adapt indentation level of nested includes
255                        case 'include_include':
256                            $ins[$i][1][1][4] += $lvl;
257                            break;
258                    }
259                    break;
260                default:
261                    break;
262            }
263        }
264
265        // calculate difference between header/section level and include level
266        $diff = 0;
267        if (!isset($lvl_max)) $lvl_max = 0; // if no level found in target, set to 0
268        $diff = $lvl - $lvl_max + 1;
269        if ($no_header) $diff -= 1;  // push up one level if "noheader"
270
271        // convert headers and set footer/permalink
272        $hdr_deleted      = false;
273        $has_permalink    = false;
274        $footer_lvl       = false;
275        $contains_secedit = false;
276        $section_close_at = false;
277        foreach($conv_idx as $idx) {
278            if($ins[$idx][0] == 'header') {
279                if ($section_close_at === false) {
280                    // store the index of the first heading (the begin of the first section)
281                    $section_close_at = $idx;
282                }
283
284                if($no_header && !$hdr_deleted) {
285                    unset ($ins[$idx]);
286                    $hdr_deleted = true;
287                    continue;
288                }
289
290                if($flags['indent']) {
291                    $lvl_new = (($ins[$idx][1][1] + $diff) > 5) ? 5 : ($ins[$idx][1][1] + $diff);
292                    $ins[$idx][1][1] = $lvl_new;
293                }
294
295                if($ins[$idx][1][1] <= $conf['maxseclevel'])
296                    $contains_secedit = true;
297
298                // set permalink
299                if($flags['link'] && !$has_permalink && ($idx == $first_header)) {
300                    $this->_permalink($ins[$idx], $page, $sect, $flags);
301                    $has_permalink = true;
302                }
303
304                // set footer level
305                if(!$footer_lvl && ($idx == $first_header) && !$no_header) {
306                    if($flags['indent']) {
307                        $footer_lvl = $lvl_new;
308                    } else {
309                        $footer_lvl = $lvl_max;
310                    }
311                }
312            } else {
313                // it's a section
314                if($flags['indent']) {
315                    $lvl_new = (($ins[$idx][1][0] + $diff) > 5) ? 5 : ($ins[$idx][1][0] + $diff);
316                    $ins[$idx][1][0] = $lvl_new;
317                }
318
319                // check if noheader is used and set the footer level to the first section
320                if($no_header && !$footer_lvl) {
321                    if($flags['indent']) {
322                        $footer_lvl = $lvl_new;
323                    } else {
324                        $footer_lvl = $lvl_max;
325                    }
326                }
327            }
328        }
329
330        // close last open section of the included page if there is any
331        if ($contains_secedit) {
332            array_push($ins, array('plugin', array('include_close_last_secedit', array())));
333        }
334
335        // add edit button
336        if($flags['editbtn'] && (auth_quickaclcheck($page) >= AUTH_EDIT)) {
337            $this->_editbtn($ins, $page, $sect, $sect_title, $root_id);
338        }
339
340        // add footer
341        if($flags['footer']) {
342            $ins[] = $this->_footer($page, $sect, $sect_title, $flags, $footer_lvl, $root_id);
343        }
344
345        // wrap content at the beginning of the include that is not in a section in a section
346        if ($lvl > 0 && $section_close_at !== 0) {
347            if ($section_close_at === false) {
348                $ins[] = array('section_close', array());
349            } else {
350                $section_close_idx = array_search($section_close_at, array_keys($ins));
351                $before_ins = array_slice($ins, 0, $section_close_idx);
352                $after_ins = array_slice($ins, $section_close_idx);
353                $ins = array_merge($before_ins, array(array('section_close', array())), $after_ins);
354            }
355            array_unshift($ins, array('section_open', array($lvl)));
356        }
357
358        // add instructions entry divs
359        array_unshift($ins, array('plugin', array('include_div', array('open', $page))));
360        array_push($ins, array('plugin', array('include_div', array('close'))));
361
362        // close previous section if any and re-open after inclusion
363        if($lvl != 0 && $this->sec_close) {
364            array_unshift($ins, array('section_close', array()));
365            $ins[] = array('section_open', array($lvl));
366        }
367    }
368
369    /**
370     * Appends instruction item for the include plugin footer
371     *
372     * @author Michael Klier <chi@chimeric.de>
373     */
374    function _footer($page, $sect, $sect_title, $flags, $footer_lvl, $root_id) {
375        $footer = array();
376        $footer[0] = 'plugin';
377        $footer[1] = array('include_footer', array($page, $sect, $sect_title, $flags, $root_id, $footer_lvl));
378        return $footer;
379    }
380
381    /**
382     * Appends instruction item for an edit button
383     *
384     * @author Michael Klier <chi@chimeric.de>
385     */
386    function _editbtn(&$ins, $page, $sect, $sect_title, $root_id) {
387        $editbtn = array();
388        $editbtn[0] = 'plugin';
389        $editbtn[1] = array('include_editbtn', array($page, $sect, $sect_title, $root_id));
390        $ins[] = $editbtn;
391    }
392
393    /**
394     * Convert instruction item for a permalink header
395     *
396     * @author Michael Klier <chi@chimeric.de>
397     */
398    function _permalink(&$ins, $page, $sect, $flags) {
399        $ins[0] = 'plugin';
400        $ins[1] = array('include_header', array($ins[1][0], $ins[1][1], $page, $sect, $flags));
401    }
402
403    /**
404     * Get a section including its subsections
405     *
406     * @author Michael Klier <chi@chimeric.de>
407     */
408    function _get_section(&$ins, $sect) {
409        $num = count($ins);
410        $offset = false;
411        $lvl    = false;
412        $end    = false;
413
414        for($i=0; $i<$num; $i++) {
415            if ($ins[$i][0] == 'header') {
416
417                // found the right header
418                if (cleanID($ins[$i][1][0]) == $sect) {
419                    $offset = $i;
420                    $lvl    = $ins[$i][1][1];
421                } elseif ($offset && $lvl && ($ins[$i][1][1] <= $lvl)) {
422                    $end = $i - $offset;
423                    break;
424                }
425            }
426        }
427        $offset = $offset ? $offset : 0;
428        $end = $end ? $end : ($num - 1);
429        if(is_array($ins)) {
430            $ins = array_slice($ins, $offset, $end);
431        }
432    }
433
434    /**
435     * Only display the first section of a page and a readmore link
436     *
437     * @author Michael Klier <chi@chimeric.de>
438     */
439    function _get_firstsec(&$ins, $page) {
440        $num = count($ins);
441        $first_sect = false;
442        for($i=0; $i<$num; $i++) {
443            if($ins[$i][0] == 'section_close') {
444                $first_sect = $i;
445            }
446            if(($first_sect) && ($ins[$i][0] == 'section_open')) {
447                $ins = array_slice($ins, 0, $first_sect);
448                $ins[] = array('p_open', array());
449                $ins[] = array('internallink', array($page, $this->getLang('readmore')));
450                $ins[] = array('p_close', array());
451                $ins[] = array('section_close', array());
452                return;
453            }
454        }
455    }
456
457    /**
458     * Gives a list of pages for a given include statement
459     *
460     * @author Michael Hamann <michael@content-space.de>
461     */
462    function _get_included_pages($mode, $page, $sect, $parent_id) {
463        global $conf;
464        $pages = array();
465        switch($mode) {
466        case 'namespace':
467            $ns    = str_replace(':', '/', cleanID($page));
468            search($pagearrays, $conf['datadir'], 'search_list', '', $ns);
469            if (is_array($pagearrays)) {
470                foreach ($pagearrays as $pagearray) {
471                    $pages[] = $pagearray['id'];
472                }
473            }
474            break;
475        case 'tagtopic':
476            if (!$this->taghelper)
477                $this->taghelper =& plugin_load('helper', 'tag');
478            if(!$this->taghelper) {
479                msg('You have to install the tag plugin to use this functionality!', -1);
480                return array();
481            }
482            $tag   = $page;
483            $sect  = '';
484            $pagearrays = $this->taghelper->getTopic('', null, $tag);
485            foreach ($pagearrays as $pagearray) {
486                $pages[] = $pagearray['id'];
487            }
488            break;
489        default:
490            $page = $this->_apply_macro($page);
491            resolve_pageid(getNS($parent_id), $page, $exists); // resolve shortcuts and clean ID
492            if (auth_quickaclcheck($page) >= AUTH_READ)
493                $pages[] = $page;
494        }
495
496        sort($pages);
497
498        $result = array();
499        foreach ($pages as $page) {
500            $perm = auth_quickaclcheck($page);
501            $exists = page_exists($page);
502            $result[] = array('id' => $page, 'exists' => $exists, 'can_edit' => ($perm >= AUTH_EDIT), 'parent_id' => $parent_id);
503        }
504        return $result;
505    }
506
507    /**
508     * This function generates the list of all included pages from a list of metadata
509     * instructions.
510     */
511    function _get_included_pages_from_meta_instructions($instructions) {
512        $pages = array();
513        foreach ($instructions as $instruction) {
514            extract($instruction);
515            $pages = array_merge($pages, $this->_get_included_pages($mode, $page, $sect, $parent_id));
516        }
517        return $pages;
518    }
519
520    /**
521     * Makes user or date dependent includes possible
522     */
523    function _apply_macro($id) {
524        global $INFO;
525        global $auth;
526
527        // if we don't have an auth object, do nothing
528        if (!$auth) return $id;
529
530        $user     = $_SERVER['REMOTE_USER'];
531        $group    = $INFO['userinfo']['grps'][0];
532
533        $replace = array(
534                '@USER@'  => cleanID($user),
535                '@NAME@'  => cleanID($INFO['userinfo']['name']),
536                '@GROUP@' => cleanID($group),
537                '@YEAR@'  => date('Y'),
538                '@MONTH@' => date('m'),
539                '@DAY@'   => date('d'),
540                );
541        return str_replace(array_keys($replace), array_values($replace), $id);
542    }
543}
544// vim:ts=4:sw=4:et:
545