xref: /plugin/include/helper.php (revision 4dd0672c16302e106b3c590da03bdac21d12c1af)
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
16class helper_plugin_include extends DokuWiki_Plugin { // DokuWiki_Helper_Plugin
17
18    var $includes     = array();
19    var $toplevel_id  = NULL;
20    var $toplevel     = NULL;
21    var $defaults     = array();
22
23    /**
24     * Constructor loads default config settings once
25     */
26    function helper_plugin_include() {
27        $this->defaults['firstsec']  = $this->getConf('firstseconly');
28        $this->defaults['editbtn']   = $this->getConf('showeditbtn');
29        $this->defaults['taglogos']  = $this->getConf('showtaglogos');
30        $this->defaults['footer']    = $this->getConf('showfooter');
31        $this->defaults['redirect']  = $this->getConf('doredirect');
32        $this->defaults['date']      = $this->getConf('showdate');
33        $this->defaults['user']      = $this->getConf('showuser');
34        $this->defaults['comments']  = $this->getConf('showcomments');
35        $this->defaults['linkbacks'] = $this->getConf('linkbacks');
36        $this->defaults['tags']      = $this->getConf('tags');
37        $this->defaults['link']      = $this->getConf('showlink');
38    }
39
40    function getInfo() {
41        return array(
42                'author' => 'Gina Häußge, Michael Klier, Esther Brunner',
43                'email'  => 'dokuwiki@chimeric.de',
44                'date'   => @file_get_contents(DOKU_PLUGIN . 'blog/VERSION'),
45                'name'   => 'Include Plugin (helper class)',
46                'desc'   => 'Functions to include another page in a wiki page',
47                'url'    => 'http://wiki.splitbrain.org/plugin:include',
48                );
49    }
50
51    /**
52     * Available methods for other plugins
53     */
54    function getMethods() {
55        $result = array();
56        $result[] = array(
57                'name'   => 'get_flags',
58                'desc'   => 'overrides standard values for showfooter and firstseconly settings',
59                'params' => array('flags' => 'array'),
60                );
61        return $result;
62    }
63
64    /**
65     * Overrides standard values for showfooter and firstseconly settings
66     */
67    function get_flags($setflags) {
68        // load defaults
69        $flags = array();
70        $flags = $this->defaults;
71        foreach ($setflags as $flag) {
72            switch ($flag) {
73                case 'footer':
74                    $flags['footer'] = 1;
75                    break;
76                case 'nofooter':
77                    $flags['footer'] = 0;
78                    break;
79                case 'firstseconly':
80                case 'firstsectiononly':
81                    $flags['firstsec'] = 1;
82                    break;
83                case 'fullpage':
84                    $flags['firstsec'] = 0;
85                    break;
86                case 'noheader':
87                    $flags['noheader'] = 1;
88                    break;
89                case 'editbtn':
90                case 'editbutton':
91                    $flags['editbtn'] = 1;
92                    break;
93                case 'noeditbtn':
94                case 'noeditbutton':
95                    $flags['editbtn'] = 0;
96                    break;
97                case 'permalink':
98                    $flags['permalink'] = 1;
99                    break;
100                case 'nopermalink':
101                    $flags['permalink'] = 0;
102                    break;
103                case 'redirect':
104                    $flags['redirect'] = 1;
105                    break;
106                case 'noredirect':
107                    $flags['redirect'] = 0;
108                    break;
109            }
110        }
111        return $flags;
112    }
113
114    /**
115     * Parses the instructions list of the page which contains the includes
116     *
117     * @author Michael Klier <chi@chimeric.de>
118     */
119    function parse_instructions($id, &$ins) {
120        $num = count($ins);
121
122        $lvl      = false;
123        $prev_lvl = false;
124        $mode  = '';
125        $page  = '';
126        $flags = array();
127        $range = false;
128
129        for($i=0; $i<$num; $i++) {
130            // set current level
131            if($ins[$i][0] == 'section_open') {
132                $lvl = $ins[$i][1][0];
133                if($i > $range) $prev_lvl = $lvl;
134            }
135            if($ins[$i][0] == 'plugin' && $ins[$i][1][0] == 'include_include' ) {
136                // found no previous section set lvl to 0
137                if(!$lvl) $lvl = 0;
138
139                // check if toplevel is set already
140                if(!isset($this->toplevel)) $this->toplevel = $lvl;
141
142                $mode  = $ins[$i][1][1][0];
143                $page  = $ins[$i][1][1][1];
144                $sect  = $ins[$i][1][1][2];
145                $flags = $ins[$i][1][1][3];
146
147                // check if we left the range of possible sub includes and reset lvl to toplevel
148                if($range && ($i > $range)) {
149                    if($prev_lvl) {
150                        $lvl = $prev_lvl;
151                        $prev_lvl = false;
152                    } else {
153                        $lvl = $this->toplevel;
154                    }
155                }
156
157                $page = $this->_apply_macro($page);
158                resolve_pageid(getNS($id), $page, $exists); // resolve shortcuts
159                $flags  = $this->get_flags($flags);
160
161                $ins_inc = $this->_get_instructions($page, $sect, $mode, $lvl, $flags);
162
163                if(!empty($ins_inc)) {
164                    // combine instructions and reset counter
165                    $ins_start = array_slice($ins, 0, $i+1);
166                    $ins_end   = array_slice($ins, $i+1);
167                    $range = $i + count($ins_inc);
168                    $ins = array_merge($ins_start, $ins_inc, $ins_end);
169                    $num = count($ins);
170                }
171            }
172        }
173    }
174
175    /**
176     * Returns the converted instructions of a give page/section
177     *
178     * @author Michael Klier <chi@chimeric.de>
179     */
180    function _get_instructions($page, $sect, $mode, $lvl, $flags) {
181        global $ID;
182
183        if($ID == $page || !page_exists($page) || (page_exists($page) && auth_quickaclcheck($page) < AUTH_READ)) return array();
184        $key = (!$sect) ? $page . '#' . $sect : $page;
185
186        // prevent recursion
187        if(!$this->includes[$key]) {
188            $ins = p_cached_instructions(wikiFN($page));
189            $this->includes[$key] = true;
190            $this->_convert_instructions($ins, $lvl, $page, $sect, $flags);
191            return $ins;
192        }
193    }
194
195    /**
196     * Converts instructions of the included page
197     *
198     * The funcion iterates over the given list of instructions and generates
199     * an index of header and section indicies. It also removes document
200     * start/end instructions, converts links, and removes unwanted
201     * instructions like tags, comments, linkbacks.
202     *
203     * Later all header/section levels are convertet to match the current
204     * inclusion level.
205     *
206     * @author Michael Klier <chi@chimeric.de>
207     */
208    function _convert_instructions(&$ins, $lvl, $page, $sect, $flags) {
209
210        // filter instructions if needed
211        if(!empty($sect)) {
212            $this->_get_section($ins, $sect);   // section required
213        } elseif($flags['firstsec']) {
214            $this->_get_firstsec($ins, $page);  // only first section
215        }
216
217        $ns  = getNS($page);
218        $num = count($ins);
219
220        $conv_idx = array(); // conversion index
221        $lvl_max  = false;   // max level
222        $first_header = -1;
223
224        for($i=0; $i<$num; $i++) {
225            switch($ins[$i][0]) {
226                case 'document_start':
227                case 'document_end':
228                case 'section_edit':
229                    unset($ins[$i]);
230                    break;
231                case 'header':
232                    $conv_idx[] = $i;
233                    // get index of first header
234                    if($first_header == -1) $first_header = $i;
235                    // get max level if this instructions set
236                    if(!$lvl_max || ($ins[$i][1][1] < $lvl_max)) {
237                        $lvl_max = $ins[$i][1][1];
238                    }
239                    break;
240                case 'section_open':
241                    $conv_idx[] = $i;
242                    break;
243                case 'internallink':
244                case 'internalmedia':
245                    if($ins[$i][1][0]{0} == '.') {
246                        if($ins[$i][1][0]{1} == '.') {
247                            $ins[$i][1][0] = getNS($ns) . ':' . substr($ins[$i][1][0], 2); // parent namespace
248                        } else {
249                            $ins[$i][1][0] = $ns . ':' . substr($ins[$i][1][0], 1); // current namespace
250                        }
251                    } elseif (strpos($ins[$i][1][0], ':') === false) {
252                        $ins[$i][1][0] = $ns . ':' . $ins[$i][1][0]; // relative links
253                    }
254                    break;
255                case 'plugin':
256                    // FIXME skip other plugins?
257                    if($ins[$i][1][0] == 'tag_tag') unset($ins[$i]);                // skip tags
258                    if($ins[$i][1][0] == 'discussion_comments') unset($ins[$i]);    // skip comments
259                    if($ins[$i][1][0] == 'linkback') unset($ins[$i]);               // skip linkbacks
260                    break;
261                default:
262                    break;
263            }
264        }
265
266        // calculate difference between header/section level and include level
267        $diff = 0;
268        if($lvl_max) {
269            // max level equals inclusion level diff is 1
270            if($lvl_max == $lvl) {
271                $diff = 1;
272            }
273            // max level is les than inclusion level, we have to convert downwards
274            if($lvl_max < $lvl) {
275                $diff = (($lvl - $lvl_max) + 1);
276            }
277            // max level is greate inclusion level, we have to convert upwards
278            if($lvl_max > $lvl) {
279                if($lvl == 0) {
280                    // we had no previous section pretend it was 1
281                    $diff = (1 - $lvl_max);
282                } elseif(($lvl - $lvl_max) == -1) {
283                    // we don't need to convert anything up diff is 0
284                    $diff = 0;
285                } else {
286                    // convert everything up
287                    $diff = ($lvl - $lvl_max);
288                }
289            }
290        }
291
292        // convert headers and set footer/permalink
293        $has_permalink = false;
294        $footer_lvl    = false;
295        foreach($conv_idx as $idx) {
296            if($ins[$idx][0] == 'header') {
297                $new_lvl = (($ins[$idx][1][1] + $diff) > 5) ? 5 : ($ins[$idx][1][1] + $diff);
298                $ins[$idx][1][1] = $new_lvl;
299
300                // get section title if we only include one section
301                if(($sect && !$sect_title) && ($idx == $first_header)) {
302                    $sect_title = $ins[$idx][1][0];
303                }
304
305                // set permalink
306                if($flags['link'] && !$has_permalink && ($idx == $first_header)) {
307                    $this->_permalink($ins[$idx], $page, $sect);
308                    $has_permalink = true;
309                }
310            } else {
311                // it's a section
312                $new_lvl = (($ins[$idx][1][0] + $diff) > 5) ? 5 : ($ins[$idx][1][0] + $diff);
313                $ins[$idx][1][0] = $new_lvl;
314            }
315
316            // set footer level
317            if(!$footer_lvl && ($idx == $first_header)) $footer_lvl = $new_lvl;
318        }
319
320        // add edit button
321        if($flags['editbtn']) $this->_editbtn($ins, $page, $sect, $sect_title);
322
323        // add footer
324        if($flags['footer']) $this->_footer($ins, $page, $sect, $sect_title, $flags, $footer_lvl);
325
326        // add instructions entry divs
327        array_unshift($ins, array('plugin', array('include_div', array('open'))));
328        array_push($ins, array('plugin', array('include_div', array('close'))));
329
330        // close previous section if any and re-open after inclusion
331        if($lvl != 0) {
332            array_unshift($ins, array('section_close'));
333            $ins[] = array('section_open', array($lvl));
334        }
335    }
336
337    /**
338     * Appends instruction item for the include plugin footer
339     *
340     * @author Michael Klier <chi@chimeric.de>
341     */
342    function _footer(&$ins, $page, $sect, $sect_title, $flags, $footer_lvl) {
343        $footer = array();
344        $footer[0] = 'plugin';
345        $footer[1] = array('include_footer', array($page, $sect, $sect_title, $flags, $this->toplevel_id, $footer_lvl));
346        $ins[] = $footer;
347    }
348
349    /**
350     * Appends instruction item for an edit button
351     *
352     * @author Michael Klier <chi@chimeric.de>
353     */
354    function _editbtn(&$ins, $page, $sect, $sect_title) {
355        $editbtn = array();
356        $editbtn[0] = 'plugin';
357        $editbtn[1] = array('include_editbtn', array($page, $sect, $sect_title, $this->toplevel_id));
358        $ins[] = $editbtn;
359    }
360
361    /**
362     * Get a section including its subsections
363     *
364     * @author Michael Klier <chi@chimeric.de>
365     */
366    function _get_section(&$ins, $sect) {
367        $num = count($ins);
368        $offset = false;
369        $lvl    = false;
370
371        for($i=0; $i<$num; $i++) {
372            if ($ins[$i][0] == 'header') {
373
374                // found the right header
375                if (cleanID($ins[$i][1][0]) == $sect) {
376                    $offset = $i;
377                    $lvl    = $ins[$i][1][1];
378                } elseif ($offset && $lvl && ($ins[$i][1][1] <= $lvl)) {
379                    $ins = array_slice($ins, $offset, ($i - $offset));
380                }
381            }
382        }
383    }
384
385    /**
386     * Only display the first section of a page and a readmore link
387     *
388     * @author Michael Klier <chi@chimeric.de>
389     */
390    function _get_firstsec(&$ins, $page) {
391        $num = count($ins);
392        for($i=0; $i<$num; $i++) {
393            if($ins[$i][0] == 'section_close') {
394                $ins = array_slice($ins, 0, $i);
395                $ins[] = array('p_open', array());
396                $ins[] = array('internallink',array($page, $this->getLang('readmore')));
397                $ins[] = array('p_close', array());
398                $ins[] = array('section_close');
399                return;
400            }
401        }
402    }
403
404    /**
405     * Makes user or date dependent includes possible
406     */
407    function _apply_macro($id) {
408        global $INFO;
409        global $auth;
410
411        // if we don't have an auth object, do nothing
412        if (!$auth) return $id;
413
414        $user     = $_SERVER['REMOTE_USER'];
415        $userdata = $auth->getUserData($user);
416        $group    = $userdata['grps'][0];
417
418        $replace = array(
419                '@USER@'  => cleanID($user),
420                '@NAME@'  => cleanID($INFO['userinfo']['name']),
421                '@GROUP@' => cleanID($group),
422                '@YEAR@'  => date('Y'),
423                '@MONTH@' => date('m'),
424                '@DAY@'   => date('d'),
425                );
426        return str_replace(array_keys($replace), array_values($replace), $id);
427    }
428
429    /**
430     * Create instruction item for a permalink header
431     *
432     * @param   string  $text: Headline text
433     * @param   integer $level: Headline level
434     * @param   integer $pos: I wish I knew what this is for... (me too ;-))
435     *
436     * @author Gina Haeussge <osd@foosel.net>
437     * @author Michael Klier <chi@chimeric.de>
438     */
439    function _permalink(&$ins, $page, $sect) {
440        $ins[0] = 'plugin';
441        $ins[1] = array('include_header', array($ins[1][0], $ins[1][1], $page, $sect));
442    }
443
444    /**
445     * Optionally display logo for the first tag found in the included page
446     *
447     * FIXME erm what was this for again?
448     */
449    function _showTagLogos() {
450        if ((!$this->getConf('showtaglogos'))
451                || (plugin_isdisabled('tag'))
452                || (!$taghelper =& plugin_load('helper', 'tag')))
453            return '';
454
455        $subject = p_get_metadata($this->page['id'], 'subject');
456        if (is_array($subject)) $tag = $subject[0];
457        else list($tag, $rest) = explode(' ', $subject, 2);
458        $title = str_replace('_', ' ', noNS($tag));
459        resolve_pageid($taghelper->namespace, $tag, $exists); // resolve shortcuts
460
461        $logosrc = mediaFN($logoID);
462        $types = array('.png', '.jpg', '.gif'); // auto-detect filetype
463        foreach ($types as $type) {
464            if (!@file_exists($logosrc.$type)) continue;
465            $logoID   = $tag.$type;
466            $logosrc .= $type;
467            list($w, $h, $t, $a) = getimagesize($logosrc);
468            return ' style="min-height: '.$h.'px">'.
469                '<img class="mediaright" src="'.ml($logoID).'" alt="'.$title.'"/';
470        }
471        return '';
472    }
473}
474//vim:ts=4:sw=4:et:enc=utf-8:
475