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_mediasyntax extends DokuWiki_Plugin { // DokuWiki_Helper_Plugin
19
20    var $includes     = array();
21    var $hasparts     = array();
22    var $toplevel_id  = NULL;
23    var $toplevel     = 0;
24    var $defaults     = array();
25    var $include_key  = '';
26    var $sec_close    = true;
27
28    /**
29     * Constructor loads default config settings once
30     */
31    function helper_plugin_mediasyntax() {
32        $this->defaults['firstsec']  = $this->getConf('firstseconly');
33        $this->defaults['editbtn']   = $this->getConf('showeditbtn');
34        $this->defaults['taglogos']  = $this->getConf('showtaglogos');
35        $this->defaults['footer']    = $this->getConf('showfooter');
36        $this->defaults['redirect']  = $this->getConf('doredirect');
37        $this->defaults['date']      = $this->getConf('showdate');
38        $this->defaults['user']      = $this->getConf('showuser');
39        $this->defaults['comments']  = $this->getConf('showcomments');
40        $this->defaults['linkbacks'] = $this->getConf('showlinkbacks');
41        $this->defaults['tags']      = $this->getConf('showtags');
42        $this->defaults['link']      = $this->getConf('showlink');
43        $this->defaults['permalink'] = $this->getConf('showpermalink');
44        $this->defaults['indent']    = $this->getConf('doindent');
45    }
46
47    /**
48     * Available methods for other plugins
49     */
50    function getMethods() {
51        $result = array();
52        $result[] = array(
53                'name'   => 'get_flags',
54                'desc'   => 'overrides standard values for showfooter and firstseconly settings',
55                'params' => array('flags' => 'array'),
56                );
57        return $result;
58    }
59
60    /**
61     * Overrides standard values for showfooter and firstseconly settings
62     */
63    function get_flags($setflags) {
64        // load defaults
65        $flags = array();
66        $flags = $this->defaults;
67        foreach ($setflags as $flag) {
68            switch ($flag) {
69                case 'footer':
70                    $flags['footer'] = 1;
71                    break;
72                case 'nofooter':
73                    $flags['footer'] = 0;
74                    break;
75                case 'firstseconly':
76                case 'firstsectiononly':
77                    $flags['firstsec'] = 1;
78                    break;
79                case 'fullpage':
80                    $flags['firstsec'] = 0;
81                    break;
82                case 'noheader':
83                    $flags['noheader'] = 1;
84                    break;
85                case 'editbtn':
86                case 'editbutton':
87                    $flags['editbtn'] = 1;
88                    break;
89                case 'noeditbtn':
90                case 'noeditbutton':
91                    $flags['editbtn'] = 0;
92                    break;
93                case 'permalink':
94                    $flags['permalink'] = 1;
95                    break;
96                case 'nopermalink':
97                    $flags['permalink'] = 0;
98                    break;
99                case 'redirect':
100                    $flags['redirect'] = 1;
101                    break;
102                case 'noredirect':
103                    $flags['redirect'] = 0;
104                    break;
105                case 'link':
106                    $flags['link'] = 1;
107                    break;
108                case 'nolink':
109                    $flags['link'] = 0;
110                    break;
111                case 'user':
112                    $flags['user'] = 1;
113                    break;
114                case 'nouser':
115                    $flags['user'] = 0;
116                    break;
117                case 'comments':
118                    $flags['comments'] = 1;
119                    break;
120                case 'nocomments':
121                    $flags['comments'] = 0;
122                    break;
123                case 'linkbacks':
124                    $flags['linkbacks'] = 1;
125                    break;
126                case 'nolinkbacks':
127                    $flags['linkbacks'] = 0;
128                    break;
129                case 'tags':
130                    $flags['tags'] = 1;
131                    break;
132                case 'notags':
133                    $flags['tags'] = 0;
134                    break;
135                case 'date':
136                    $flags['date'] = 1;
137                    break;
138                case 'nodate':
139                    $flags['date'] = 0;
140                    break;
141                case 'indent':
142                    $flags['indent'] = 1;
143                    break;
144                case 'noindent':
145                    $flags['indent'] = 0;
146                    break;
147            }
148        }
149        return $flags;
150    }
151
152    /**
153     * Parses the instructions list of the page which contains the includes
154     *
155     * @author Michael Klier <chi@chimeric.de>
156     */
157    function parse_instructions($id, &$ins) {
158        global $conf;
159        global $INFO;
160
161        $num = count($ins);
162
163        $lvl      = false;
164        $prev_lvl = 0;
165        $mode     = '';
166        $page     = '';
167        $flags    = array();
168        $range    = false;
169        $scope    = $id;
170
171        for($i=0; $i<$num; $i++) {
172            // set current level
173            if($ins[$i][0] == 'section_open') {
174                $lvl = $ins[$i][1][0];
175                if($i > $range) $prev_lvl = $lvl;
176            }
177
178            if($ins[$i][0] == 'plugin' && $ins[$i][1][0] == 'mediasyntax_include' ) {
179                // found no previous section set lvl to 0
180                if(!$lvl) $lvl = 0;
181
182                $mode  = $ins[$i][1][1][0];
183
184                if($mode == 'namespace') {
185                    $ns    = str_replace(':', '/', cleanID($ins[$i][1][1][1]));
186                    $sect  = '';
187                    $flags = $ins[$i][1][1][3];
188
189                    $pages = array();
190                    search($pages, $conf['datadir'], 'search_list', '', $ns);
191                    sort($pages);
192
193                    if(!empty($pages)) {
194                        $ins_inc = array();
195                        foreach($pages as $page) {
196                            $this->_append_includeins($ins_inc, $page['id'], $flags);
197                        }
198                        $ins_start = array_slice($ins, 0, $i+1);
199                        $ins_end   = array_slice($ins, $i+1);
200                        $ins       = array_merge($ins_start, $ins_inc, $ins_end);
201                    }
202                    unset($ins[$i]);
203                    $i--;
204                }
205
206                if($mode == 'tagtopic') {
207                    $this->taghelper =& plugin_load('helper', 'tag');
208                    if(!$this->taghelper) {
209                        msg('You have to install the tag plugin to use this functionality!', -1);
210                        return;
211                    }
212                    $tag   = $ins[$i][1][1][1];
213                    $sect  = '';
214                    $flags = $ins[$i][1][1][3];
215
216                    $pages = array();
217                    $pages = $this->taghelper->getTopic('', null, $tag);
218
219                    if(!empty($pages)) {
220                        $ins_inc = array();
221                        foreach($pages as $title => $page) {
222                            $this->_append_includeins($ins_inc, $page['id'], $flags);
223                        }
224                        $ins_start = array_slice($ins, 0, $i+1);
225                        $ins_end   = array_slice($ins, $i+1);
226                        $ins       = array_merge($ins_start, $ins_inc, $ins_end);
227                    }
228                    unset($ins[$i]);
229                    $i--;
230                }
231
232                if($mode == 'page' || $mode == 'section')
233                {
234                    $page = cleanID($this->_apply_macro($ins[$i][1][1][1]));
235                    $perm = auth_quickaclcheck($page);
236
237                    array_push($this->hasparts, $page);
238
239                    if($perm >= AUTH_READ)
240                    {
241
242                      $sect  = $ins[$i][1][1][2];
243                      $flags = $ins[$i][1][1][3];
244
245                      resolve_pageid(getNS($scope), $page, $exists); // resolve shortcuts
246                      $ins[$i][1][1][4] = $scope;
247                      $scope = $page;
248                      $flags = $this->get_flags($flags);
249
250                      if(!page_exists($page))
251                      {
252                          if($flags['footer'])
253                          {
254                              $ins[$i] = $this->_footer($page, $sect, '', $flags, 0);
255                          }
256                          else
257                          {
258                              unset($ins[$i]);
259                          }
260                      }
261                      else
262                      {
263                          $ins_inc = $this->_get_instructions($page, $sect, $mode, $lvl, $flags);
264                          if(!empty($ins_inc))
265                          {
266                              // combine instructions and reset counter
267                              $ins_start = array_slice($ins, 0, $i+1);
268                              $ins_end   = array_slice($ins, $i+1);
269                              $range = $i + count($ins_inc);
270                              $ins = array_merge($ins_start, $ins_inc, $ins_end);
271                              $num = count($ins);
272                          }
273                      }
274                   }
275                }
276            }
277
278            // check if we left the range of possible sub includes and reset lvl and scope to toplevel_id
279            if($range && ($i >= $range))
280            {
281                $lvl = ($prev_lvl == 0) ? 0 : $prev_lvl;
282                $range    = false;
283                // reset scope to toplevel_id
284                $scope = $this->toplevel_id;
285            }
286        }
287
288        if(!empty($INFO['userinfo'])) {
289            $include_key = $INFO['userinfo']['name'] . '|' . implode('|', $INFO['userinfo']['grps']);
290        } else {
291            $include_key = '@ALL';
292        }
293
294        // handle meta data
295        $meta = array();
296        $meta = p_get_metadata($id, 'plugin_mediasyntax');
297        $meta['pages'] = array_unique($this->hasparts);
298        $meta['keys'][$include_key] = true;
299        $ins_meta    = array();
300        $ins_meta[0] = 'plugin';
301        $ins_meta[1] = array('include_meta', array($meta));
302        array_push($ins, $ins_meta);
303    }
304
305    /**
306     * Returns the converted instructions of a give page/section
307     *
308     * @author Michael Klier <chi@chimeric.de>
309     */
310    function _get_instructions($page, $sect, $mode, $lvl, $flags) {
311        $key = ($sect) ? $page . '#' . $sect : $page;
312
313        // prevent recursion
314        if(!$this->includes[$key]) {
315            $ins = p_cached_instructions(wikiFN($page));
316            $this->includes[$key] = true;
317            $this->_convert_instructions($ins, $lvl, $page, $sect, $flags);
318            return $ins;
319        }
320    }
321
322    /**
323     * Converts instructions of the included page
324     *
325     * The funcion iterates over the given list of instructions and generates
326     * an index of header and section indicies. It also removes document
327     * start/end instructions, converts links, and removes unwanted
328     * instructions like tags, comments, linkbacks.
329     *
330     * Later all header/section levels are convertet to match the current
331     * inclusion level.
332     *
333     * @author Michael Klier <chi@chimeric.de>
334     */
335    function _convert_instructions(&$ins, $lvl, $page, $sect, $flags) {
336
337        // filter instructions if needed
338        if(!empty($sect)) {
339            $this->_get_section($ins, $sect);   // section required
340        }
341
342        if($flags['firstsec']) {
343            $this->_get_firstsec($ins, $page);  // only first section
344        }
345
346        $ns  = getNS($page);
347        $num = count($ins);
348
349        $conv_idx = array(); // conversion index
350        $lvl_max  = false;   // max level
351        $first_header = -1;
352        $no_header  = false;
353        $sect_title = false;
354
355        for($i=0; $i<$num; $i++) {
356            switch($ins[$i][0]) {
357                case 'document_start':
358                case 'document_end':
359                case 'section_edit':
360                    unset($ins[$i]);
361                    break;
362                case 'header':
363                    // get section title of first section
364                    if($sect && !$sect_title) {
365                        $sect_title = $ins[$i][1][0];
366                    }
367                    // check if we need to skip the first header
368                    if((!$no_header) && $flags['noheader']) {
369                        $no_header = true;
370                    }
371
372                    $conv_idx[] = $i;
373                    // get index of first header
374                    if($first_header == -1) $first_header = $i;
375                    // get max level of this instructions set
376                    if(!$lvl_max || ($ins[$i][1][1] < $lvl_max)) {
377                        $lvl_max = $ins[$i][1][1];
378                    }
379                    break;
380                case 'section_open':
381                    $conv_idx[] = $i;
382                    break;
383                case 'internallink':
384                case 'internalmedia':
385                    if($ins[$i][1][0]{0} == '.') {
386                        if($ins[$i][1][0]{1} == '.') {
387                            $ins[$i][1][0] = getNS($ns) . ':' . substr($ins[$i][1][0], 2); // parent namespace
388                        } else {
389                            $ins[$i][1][0] = $ns . ':' . substr($ins[$i][1][0], 1); // current namespace
390                        }
391                    } elseif (strpos($ins[$i][1][0], ':') === false) {
392                        $ins[$i][1][0] = $ns . ':' . $ins[$i][1][0]; // relative links
393                    }
394                    break;
395                case 'plugin':
396                    // FIXME skip other plugins?
397                    switch($ins[$i][1][0]) {
398                        case 'tag_tag':                 // skip tags
399                        case 'discussion_comments':     // skip comments
400                        case 'linkback':                // skip linkbacks
401                        case 'data_entry':              // skip data plugin
402                        case 'meta':                    // skip meta plugin
403                            unset($ins[$i]);
404                            break;
405                    }
406                    break;
407                default:
408                    break;
409            }
410        }
411
412        // calculate difference between header/section level and include level
413        $diff = 0;
414        if (!isset($lvl_max)) $lvl_max = 0; // if no level found in target, set to 0
415        $diff = $lvl - $lvl_max + 1;
416        if ($no_header) $diff -= 1;  // push up one level if "noheader"
417
418        // convert headers and set footer/permalink
419        $hdr_deleted   = false;
420        $has_permalink = false;
421        $footer_lvl    = false;
422        foreach($conv_idx as $idx) {
423            if($ins[$idx][0] == 'header') {
424                if($no_header && !$hdr_deleted) {
425                    unset ($ins[$idx]);
426                    $hdr_deleted = true;
427                    continue;
428                }
429
430                if($flags['indent']) {
431                    $lvl_new = (($ins[$idx][1][1] + $diff) > 5) ? 5 : ($ins[$idx][1][1] + $diff);
432                    $ins[$idx][1][1] = $lvl_new;
433                }
434
435                // set permalink
436                if($flags['link'] && !$has_permalink && ($idx == $first_header)) {
437                    $this->_permalink($ins[$idx], $page, $sect, $flags);
438                    $has_permalink = true;
439                }
440
441                // set footer level
442                if(!$footer_lvl && ($idx == $first_header) && !$no_header) {
443                    if($flags['indent']) {
444                        $footer_lvl = $lvl_new;
445                    } else {
446                        $footer_lvl = $lvl_max;
447                    }
448                }
449            } else {
450                // it's a section
451                if($flags['indent']) {
452                    $lvl_new = (($ins[$idx][1][0] + $diff) > 5) ? 5 : ($ins[$idx][1][0] + $diff);
453                    $ins[$idx][1][0] = $lvl_new;
454                }
455
456                // check if noheader is used and set the footer level to the first section
457                if($no_header && !$footer_lvl) {
458                    if($flags['indent']) {
459                        $footer_lvl = $lvl_new;
460                    } else {
461                        $footer_lvl = $lvl_max;
462                    }
463                }
464            }
465        }
466
467        // add edit button
468        if($flags['editbtn'] && (auth_quickaclcheck($page) >= AUTH_EDIT)) {
469            $this->_editbtn($ins, $page, $sect, $sect_title);
470        }
471
472        // add footer
473        if($flags['footer']) {
474            $ins[] = $this->_footer($page, $sect, $sect_title, $flags, $footer_lvl);
475        }
476
477        // add instructions entry divs
478        array_unshift($ins, array('plugin', array('include_div', array('open', $page))));
479        array_push($ins, array('plugin', array('include_div', array('close'))));
480
481        // close previous section if any and re-open after inclusion
482        if($lvl != 0 && $this->sec_close) {
483            array_unshift($ins, array('section_close', array()));
484            $ins[] = array('section_open', array($lvl));
485        }
486    }
487
488    /**
489     * Creates include instructions for the namespace/tagtopic modes
490     *
491     * @author Michael Klier <chi@chimeric.de>
492     */
493    function _append_includeins(&$ins, $id, $flags) {
494        if(auth_quickaclcheck($id) >= AUTH_READ) {
495            array_push($this->hasparts, $id);
496            $ins_tmp[0]       = 'plugin';
497            $ins_tmp[1][0]    = 'mediasyntax_include';
498            $ins_tmp[1][1][0] = 'page';
499            $ins_tmp[1][1][1] = $id;
500            $ins_tmp[1][1][2] = '';
501            $ins_tmp[1][1][3] = $flags;
502            $ins = array_merge($ins, array($ins_tmp));
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) {
512        $footer = array();
513        $footer[0] = 'plugin';
514        $footer[1] = array('mediasyntax_footer', array($page, $sect, $sect_title, $flags, $this->toplevel_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) {
524        $editbtn = array();
525        $editbtn[0] = 'plugin';
526        $editbtn[1] = array('mediasyntax_editbtn', array($page, $sect, $sect_title, $this->toplevel_id));
527        $ins[] = $editbtn;
528    }
529
530    /**
531     * Convert instruction item for a permalink header
532     *
533     * @author Michael Klier <chi@chimeric.de>
534     */
535    function _permalink(&$ins, $page, $sect, $flags) {
536        $ins[0] = 'plugin';
537        $ins[1] = array('mediasyntax_header', array($ins[1][0], $ins[1][1], $page, $sect, $flags));
538    }
539
540    /**
541     * Get a section including its subsections
542     *
543     * @author Michael Klier <chi@chimeric.de>
544     */
545    function _get_section(&$ins, $sect) {
546        $num = count($ins);
547        $offset = false;
548        $lvl    = false;
549        $end    = false;
550
551        for($i=0; $i<$num; $i++) {
552            if ($ins[$i][0] == 'header') {
553
554                // found the right header
555                if (cleanID($ins[$i][1][0]) == $sect) {
556                    $offset = $i;
557                    $lvl    = $ins[$i][1][1];
558                } elseif ($offset && $lvl && ($ins[$i][1][1] <= $lvl)) {
559                    $end = $i - $offset;
560                    break;
561                }
562            }
563        }
564        $offset = $offset ? $offset : 0;
565        $end = $end ? $end : ($num - 1);
566        if(is_array($ins)) {
567            $ins = array_slice($ins, $offset, $end);
568        }
569    }
570
571    /**
572     * Only display the first section of a page and a readmore link
573     *
574     * @author Michael Klier <chi@chimeric.de>
575     */
576    function _get_firstsec(&$ins, $page) {
577        $num = count($ins);
578        $first_sect = false;
579        for($i=0; $i<$num; $i++) {
580            if($ins[$i][0] == 'section_close') {
581                $first_sect = $i;
582            }
583            if(($first_sect) && ($ins[$i][0] == 'section_open')) {
584                $ins = array_slice($ins, 0, $first_sect);
585                $ins[] = array('p_open', array());
586                $ins[] = array('internallink', array($page, $this->getLang('readmore')));
587                $ins[] = array('p_close', array());
588                $ins[] = array('section_close', array());
589                return;
590            }
591        }
592    }
593
594    /**
595     * Makes user or date dependent includes possible
596     */
597    function _apply_macro($id) {
598        global $INFO;
599        global $auth;
600
601        // if we don't have an auth object, do nothing
602        if (!$auth) return $id;
603
604        $user     = $_SERVER['REMOTE_USER'];
605        $group    = $INFO['userinfo']['grps'][0];
606
607        $replace = array(
608                '@USER@'  => cleanID($user),
609                '@NAME@'  => cleanID($INFO['userinfo']['name']),
610                '@GROUP@' => cleanID($group),
611                '@YEAR@'  => date('Y'),
612                '@MONTH@' => date('m'),
613                '@DAY@'   => date('d'),
614                );
615        return str_replace(array_keys($replace), array_values($replace), $id);
616    }
617}
618//vim:ts=4:sw=4:et:enc=utf-8:
619