xref: /plugin/include/helper.php (revision af4127421aae8e21a0d5722ad0fc1b0701a15e3b)
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        if (page_exists($page)) {
166            $ins = p_cached_instructions(wikiFN($page));
167        } else {
168            $ins = array();
169        }
170
171        $this->_convert_instructions($ins, $lvl, $page, $sect, $flags, $root_id);
172        return $ins;
173    }
174
175    /**
176     * Converts instructions of the included page
177     *
178     * The funcion iterates over the given list of instructions and generates
179     * an index of header and section indicies. It also removes document
180     * start/end instructions, converts links, and removes unwanted
181     * instructions like tags, comments, linkbacks.
182     *
183     * Later all header/section levels are convertet to match the current
184     * inclusion level.
185     *
186     * @author Michael Klier <chi@chimeric.de>
187     */
188    function _convert_instructions(&$ins, $lvl, $page, $sect, $flags, $root_id) {
189        global $conf;
190
191        // filter instructions if needed
192        if(!empty($sect)) {
193            $this->_get_section($ins, $sect);   // section required
194        }
195
196        if($flags['firstsec']) {
197            $this->_get_firstsec($ins, $page);  // only first section
198        }
199
200        $ns  = getNS($page);
201        $num = count($ins);
202
203        $conv_idx = array(); // conversion index
204        $lvl_max  = false;   // max level
205        $first_header = -1;
206        $no_header  = false;
207        $sect_title = false;
208
209        for($i=0; $i<$num; $i++) {
210            switch($ins[$i][0]) {
211                case 'document_start':
212                case 'document_end':
213                case 'section_edit':
214                    unset($ins[$i]);
215                    break;
216                case 'header':
217                    // get section title of first section
218                    if($sect && !$sect_title) {
219                        $sect_title = $ins[$i][1][0];
220                    }
221                    // check if we need to skip the first header
222                    if((!$no_header) && $flags['noheader']) {
223                        $no_header = true;
224                    }
225
226                    $conv_idx[] = $i;
227                    // get index of first header
228                    if($first_header == -1) $first_header = $i;
229                    // get max level of this instructions set
230                    if(!$lvl_max || ($ins[$i][1][1] < $lvl_max)) {
231                        $lvl_max = $ins[$i][1][1];
232                    }
233                    break;
234                case 'section_open':
235                    $conv_idx[] = $i;
236                    break;
237                case 'internallink':
238                case 'internalmedia':
239                    // make sure parameters aren't touched
240                    $link_params = '';
241                    $link_id = $ins[$i][1][0];
242                    $link_parts = explode('?', $link_id, 2);
243                    if (count($link_parts) === 2) {
244                        $link_id = $link_parts[0];
245                        $link_params = $link_parts[1];
246                    }
247                    // resolve the id without cleaning it
248                    $link_id = resolve_id($ns, $link_id, false);
249                    // this id is internal (i.e. absolute) now, add ':' to make resolve_id work again
250                    if ($link_id{0} != ':') $link_id = ':'.$link_id;
251                    // restore parameters
252                    $ins[$i][1][0] = ($link_params != '') ? $link_id.'?'.$link_params : $link_id;
253                    break;
254                case 'plugin':
255                    // FIXME skip other plugins?
256                    switch($ins[$i][1][0]) {
257                        case 'tag_tag':                 // skip tags
258                        case 'discussion_comments':     // skip comments
259                        case 'linkback':                // skip linkbacks
260                        case 'data_entry':              // skip data plugin
261                        case 'meta':                    // skip meta plugin
262                            unset($ins[$i]);
263                            break;
264                        // adapt indentation level of nested includes
265                        case 'include_include':
266                            $ins[$i][1][1][4] += $lvl;
267                            break;
268                    }
269                    break;
270                default:
271                    break;
272            }
273        }
274
275        // calculate difference between header/section level and include level
276        $diff = 0;
277        if (!isset($lvl_max)) $lvl_max = 0; // if no level found in target, set to 0
278        $diff = $lvl - $lvl_max + 1;
279        if ($no_header) $diff -= 1;  // push up one level if "noheader"
280
281        // convert headers and set footer/permalink
282        $hdr_deleted      = false;
283        $has_permalink    = false;
284        $footer_lvl       = false;
285        $contains_secedit = false;
286        $section_close_at = false;
287        foreach($conv_idx as $idx) {
288            if($ins[$idx][0] == 'header') {
289                if ($section_close_at === false) {
290                    // store the index of the first heading (the begin of the first section)
291                    $section_close_at = $idx;
292                }
293
294                if($no_header && !$hdr_deleted) {
295                    unset ($ins[$idx]);
296                    $hdr_deleted = true;
297                    continue;
298                }
299
300                if($flags['indent']) {
301                    $lvl_new = (($ins[$idx][1][1] + $diff) > 5) ? 5 : ($ins[$idx][1][1] + $diff);
302                    $ins[$idx][1][1] = $lvl_new;
303                }
304
305                if($ins[$idx][1][1] <= $conf['maxseclevel'])
306                    $contains_secedit = true;
307
308                // set permalink
309                if($flags['link'] && !$has_permalink && ($idx == $first_header)) {
310                    $this->_permalink($ins[$idx], $page, $sect, $flags);
311                    $has_permalink = true;
312                }
313
314                // set footer level
315                if(!$footer_lvl && ($idx == $first_header) && !$no_header) {
316                    if($flags['indent']) {
317                        $footer_lvl = $lvl_new;
318                    } else {
319                        $footer_lvl = $lvl_max;
320                    }
321                }
322            } else {
323                // it's a section
324                if($flags['indent']) {
325                    $lvl_new = (($ins[$idx][1][0] + $diff) > 5) ? 5 : ($ins[$idx][1][0] + $diff);
326                    $ins[$idx][1][0] = $lvl_new;
327                }
328
329                // check if noheader is used and set the footer level to the first section
330                if($no_header && !$footer_lvl) {
331                    if($flags['indent']) {
332                        $footer_lvl = $lvl_new;
333                    } else {
334                        $footer_lvl = $lvl_max;
335                    }
336                }
337            }
338        }
339
340        // close last open section of the included page if there is any
341        if ($contains_secedit) {
342            array_push($ins, array('plugin', array('include_close_last_secedit', array())));
343        }
344
345        // add edit button
346        if($flags['editbtn']) {
347            $perm = auth_quickaclcheck($page);
348            $can_edit = page_exists($page) ? $perm >= AUTH_EDIT : $perm >= AUTH_CREATE;
349            if ($can_edit)
350                $this->_editbtn($ins, $page, $sect, $sect_title, $root_id);
351        }
352
353        // add footer
354        if($flags['footer']) {
355            $ins[] = $this->_footer($page, $sect, $sect_title, $flags, $footer_lvl, $root_id);
356        }
357
358        // wrap content at the beginning of the include that is not in a section in a section
359        if ($lvl > 0 && $section_close_at !== 0 && $flags['indent']) {
360            if ($section_close_at === false) {
361                $ins[] = array('section_close', array());
362                array_unshift($ins, array('section_open', array($lvl)));
363            } else {
364                $section_close_idx = array_search($section_close_at, array_keys($ins));
365                if ($section_close_idx > 0) {
366                    $before_ins = array_slice($ins, 0, $section_close_idx);
367                    $after_ins = array_slice($ins, $section_close_idx);
368                    $ins = array_merge($before_ins, array(array('section_close', array())), $after_ins);
369                    array_unshift($ins, array('section_open', array($lvl)));
370                }
371            }
372        }
373
374        // add instructions entry wrapper
375        array_unshift($ins, array('plugin', array('include_wrap', array('open', $page))));
376        array_push($ins, array('plugin', array('include_wrap', array('close'))));
377
378        // close previous section if any and re-open after inclusion
379        if($lvl != 0 && $this->sec_close) {
380            array_unshift($ins, array('section_close', array()));
381            $ins[] = array('section_open', array($lvl));
382        }
383    }
384
385    /**
386     * Appends instruction item for the include plugin footer
387     *
388     * @author Michael Klier <chi@chimeric.de>
389     */
390    function _footer($page, $sect, $sect_title, $flags, $footer_lvl, $root_id) {
391        $footer = array();
392        $footer[0] = 'plugin';
393        $footer[1] = array('include_footer', array($page, $sect, $sect_title, $flags, $root_id, $footer_lvl));
394        return $footer;
395    }
396
397    /**
398     * Appends instruction item for an edit button
399     *
400     * @author Michael Klier <chi@chimeric.de>
401     */
402    function _editbtn(&$ins, $page, $sect, $sect_title, $root_id) {
403        $editbtn = array();
404        $editbtn[0] = 'plugin';
405        $editbtn[1] = array('include_editbtn', array($page, $sect, $sect_title, $root_id));
406        $ins[] = $editbtn;
407    }
408
409    /**
410     * Convert instruction item for a permalink header
411     *
412     * @author Michael Klier <chi@chimeric.de>
413     */
414    function _permalink(&$ins, $page, $sect, $flags) {
415        $ins[0] = 'plugin';
416        $ins[1] = array('include_header', array($ins[1][0], $ins[1][1], $page, $sect, $flags));
417    }
418
419    /**
420     * Get a section including its subsections
421     *
422     * @author Michael Klier <chi@chimeric.de>
423     */
424    function _get_section(&$ins, $sect) {
425        $num = count($ins);
426        $offset = false;
427        $lvl    = false;
428        $end    = false;
429
430        for($i=0; $i<$num; $i++) {
431            if ($ins[$i][0] == 'header') {
432
433                // found the right header
434                if (cleanID($ins[$i][1][0]) == $sect) {
435                    $offset = $i;
436                    $lvl    = $ins[$i][1][1];
437                } elseif ($offset && $lvl && ($ins[$i][1][1] <= $lvl)) {
438                    $end = $i - $offset;
439                    break;
440                }
441            }
442        }
443        $offset = $offset ? $offset : 0;
444        $end = $end ? $end : ($num - 1);
445        if(is_array($ins)) {
446            $ins = array_slice($ins, $offset, $end);
447        }
448    }
449
450    /**
451     * Only display the first section of a page and a readmore link
452     *
453     * @author Michael Klier <chi@chimeric.de>
454     */
455    function _get_firstsec(&$ins, $page) {
456        $num = count($ins);
457        $first_sect = false;
458        for($i=0; $i<$num; $i++) {
459            if($ins[$i][0] == 'section_close') {
460                $first_sect = $i;
461            }
462            if(($first_sect) && ($ins[$i][0] == 'section_open')) {
463                $ins = array_slice($ins, 0, $first_sect);
464                $ins[] = array('p_open', array());
465                $ins[] = array('internallink', array($page, $this->getLang('readmore')));
466                $ins[] = array('p_close', array());
467                $ins[] = array('section_close', array());
468                return;
469            }
470        }
471    }
472
473    /**
474     * Gives a list of pages for a given include statement
475     *
476     * @author Michael Hamann <michael@content-space.de>
477     */
478    function _get_included_pages($mode, $page, $sect, $parent_id) {
479        global $conf;
480        $pages = array();
481        switch($mode) {
482        case 'namespace':
483            $ns    = str_replace(':', '/', cleanID($page));
484            search($pagearrays, $conf['datadir'], 'search_list', '', $ns);
485            if (is_array($pagearrays)) {
486                foreach ($pagearrays as $pagearray) {
487                    $pages[] = $pagearray['id'];
488                }
489            }
490            break;
491        case 'tagtopic':
492            if (!$this->taghelper)
493                $this->taghelper =& plugin_load('helper', 'tag');
494            if(!$this->taghelper) {
495                msg('You have to install the tag plugin to use this functionality!', -1);
496                return array();
497            }
498            $tag   = $page;
499            $sect  = '';
500            $pagearrays = $this->taghelper->getTopic('', null, $tag);
501            foreach ($pagearrays as $pagearray) {
502                $pages[] = $pagearray['id'];
503            }
504            break;
505        default:
506            $page = $this->_apply_macro($page);
507            resolve_pageid(getNS($parent_id), $page, $exists); // resolve shortcuts and clean ID
508            if (auth_quickaclcheck($page) >= AUTH_READ)
509                $pages[] = $page;
510        }
511
512        sort($pages);
513
514        $result = array();
515        foreach ($pages as $page) {
516            $perm = auth_quickaclcheck($page);
517            $exists = page_exists($page);
518            $result[] = array('id' => $page, 'exists' => $exists, 'can_edit' => ($perm >= AUTH_EDIT), 'parent_id' => $parent_id);
519        }
520        return $result;
521    }
522
523    /**
524     * This function generates the list of all included pages from a list of metadata
525     * instructions.
526     */
527    function _get_included_pages_from_meta_instructions($instructions) {
528        $pages = array();
529        foreach ($instructions as $instruction) {
530            extract($instruction);
531            $pages = array_merge($pages, $this->_get_included_pages($mode, $page, $sect, $parent_id));
532        }
533        return $pages;
534    }
535
536    /**
537     * Makes user or date dependent includes possible
538     */
539    function _apply_macro($id) {
540        global $INFO;
541        global $auth;
542
543        // if we don't have an auth object, do nothing
544        if (!$auth) return $id;
545
546        $user     = $_SERVER['REMOTE_USER'];
547        $group    = $INFO['userinfo']['grps'][0];
548
549        $replace = array(
550                '@USER@'  => cleanID($user),
551                '@NAME@'  => cleanID($INFO['userinfo']['name']),
552                '@GROUP@' => cleanID($group),
553                '@YEAR@'  => date('Y'),
554                '@MONTH@' => date('m'),
555                '@DAY@'   => date('d'),
556                );
557        return str_replace(array_keys($replace), array_values($replace), $id);
558    }
559}
560// vim:ts=4:sw=4:et:
561