xref: /plugin/include/helper.php (revision 50579d3b8e4f485cae4aa75d383cc7b1238d7868)
1<?php
2/**
3 * @license    GPL 2 (http://www.gnu.org/licenses/gpl.html)
4 * @author     Esther Brunner <wikidesign@gmail.com>
5 */
6
7// must be run within Dokuwiki
8if (!defined('DOKU_INC')) die();
9
10if (!defined('DOKU_LF')) define('DOKU_LF', "\n");
11if (!defined('DOKU_TAB')) define('DOKU_TAB', "\t");
12if (!defined('DOKU_PLUGIN')) define('DOKU_PLUGIN', DOKU_INC.'lib/plugins/');
13
14class helper_plugin_include extends DokuWiki_Plugin { // DokuWiki_Helper_Plugin
15
16  var $pages     = array();   // filechain of included pages
17  var $page      = array();   // associative array with data about the page to include
18  var $ins       = array();   // instructions array
19  var $doc       = '';        // the final output XHTML string
20  var $mode      = 'section'; // inclusion mode: 'page' or 'section'
21  var $clevel    = 0;         // current section level
22  var $firstsec  = 0;         // show first section only
23  var $editbtn   = 1;         // show edit button
24  var $footer    = 1;         // show metaline below page
25  var $noheader  = 0;         // omit header
26  var $header    = array();   // included page / section header
27  var $renderer  = NULL;      // DokuWiki renderer object
28
29  // private variables
30  var $_offset   = NULL;
31
32  /**
33   * Constructor loads some config settings
34   */
35  function helper_plugin_include(){
36    $this->firstsec = $this->getConf('firstseconly');
37    $this->editbtn  = $this->getConf('showeditbtn');
38    $this->footer   = $this->getConf('showfooter');
39    $this->noheader = 0;
40    $this->header   = array();
41  }
42
43  function getInfo(){
44    return array(
45      'author' => 'Esther Brunner',
46      'email'  => 'wikidesign@gmail.com',
47      'date'   => '2007-08-11',
48      'name'   => 'Include Plugin (helper class)',
49      'desc'   => 'Functions to include another page in a wiki page',
50      'url'    => 'http://www.wikidesign/en/plugin/include/start',
51    );
52  }
53
54  function getMethods(){
55    $result = array();
56    $result[] = array(
57      'name'   => 'setPage',
58      'desc'   => 'sets the page to include',
59      'params' => array("page attributes, 'id' required, 'section' for filtering" => 'array'),
60      'return' => array('success' => 'boolean'),
61    );
62    $result[] = array(
63      'name'   => 'setMode',
64      'desc'   => 'sets inclusion mode: should indention be merged?',
65      'params' => array("'page' (original) or 'section' (merged indention)" => 'string'),
66    );
67    $result[] = array(
68      'name'   => 'setLevel',
69      'desc'   => 'sets the indention for the current section level',
70      'params' => array('level: 0 to 5' => 'integer'),
71      'return' => array('success' => 'boolean'),
72    );
73    $result[] = array(
74      'name'   => 'setFlags',
75      'desc'   => 'overrides standard values for showfooter and firstseconly settings',
76      'params' => array('flags' => 'array'),
77    );
78    $result[] = array(
79      'name'   => 'renderXHTML',
80      'desc'   => 'renders the XHTML output of the included page',
81      'params' => array('DokuWiki renderer' => 'object'),
82      'return' => array('XHTML' => 'string'),
83    );
84    return $result;
85  }
86
87  /**
88   * Sets the page to include if it is not already included (prevent recursion)
89   * and the current user is allowed to read it
90   */
91  function setPage($page){
92    global $ID;
93
94    $id     = $page['id'];
95    $fullid = $id.'#'.$page['section'];
96
97    if (!$id) return false;       // no page id given
98    if ($id == $ID) return false; // page can't include itself
99
100    // prevent include recursion
101    if ((isset($this->pages[$id.'#'])) || (isset($this->pages[$fullid]))) return false;
102
103    // we need to make sure 'perm', 'file' and 'exists' are set
104    if (!isset($page['perm'])) $page['perm'] = auth_quickaclcheck($page['id']);
105    if (!isset($page['file'])) $page['file'] = wikiFN($page['id']);
106    if (!isset($page['exists'])) $page['exists'] = @file_exists($page['file']);
107
108    // check permission
109    if ($page['perm'] < AUTH_READ) return false;
110
111    // add the page to the filechain
112    $this->pages[$fullid] = $page;
113    $this->page =& $this->pages[$fullid];
114    return true;
115  }
116
117  /**
118   * Sets the inclusion mode: 'page' or 'section'
119   */
120  function setMode($mode){
121    $this->mode = $mode;
122  }
123
124  /**
125   * Sets the right indention for a given section level
126   */
127  function setLevel($level){
128    if ((is_numeric($level)) && ($level >= 0) && ($level <= 5)){
129      $this->clevel = $level;
130      return true;
131    }
132    return false;
133  }
134
135  /**
136   * Overrides standard values for showfooter and firstseconly settings
137   */
138  function setFlags($flags){
139    foreach ($flags as $flag){
140      switch ($flag){
141      case 'footer':
142        $this->footer = 1;
143        break;
144      case 'nofooter':
145        $this->footer = 0;
146        break;
147      case 'firstseconly':
148      case 'firstsectiononly':
149        $this->firstsec = 1;
150        break;
151      case 'fullpage':
152        $this->firstsec = 0;
153        break;
154      case 'noheader':
155        $this->noheader = 1;
156        break;
157      case 'editbtn':
158      case 'editbutton':
159        $this->editbtn = 1;
160        break;
161      case 'noeditbtn':
162      case 'noeditbutton':
163        $this->editbtn = 0;
164        break;
165      }
166    }
167  }
168
169  /**
170   * Builds the XHTML to embed the page to include
171   */
172  function renderXHTML(&$renderer){
173    if (!$this->page['id']) return ''; // page must be set first
174    if (!$this->page['exists'] && ($this->page['perm'] < AUTH_CREATE)) return '';
175
176    // prepare variables
177    $this->doc      = '';
178    $this->renderer =& $renderer;
179
180    // get instructions and render them on the fly
181    $this->ins = p_cached_instructions($this->page['file']);
182
183    // show only a given section?
184    if ($this->page['section'] && $this->page['exists']) $this->_getSection();
185
186    // convert relative links
187    $this->_convertInstructions();
188
189    // render the included page
190    $content = '<div class="entry-content">'.DOKU_LF.
191      $this->_cleanXHTML(p_render('xhtml', $this->ins, $info)).DOKU_LF.
192      '</div>'.DOKU_LF;
193
194    // embed the included page
195    $class = ($this->page['draft'] ? 'include draft' : 'include');
196    $renderer->doc .= '<div class="'.$class.' hentry"'.$this->_showTagLogos().'>'.DOKU_LF;
197    if (!$this->header && $this->clevel && ($this->mode == 'section'))
198      $renderer->doc .= '<div class="level'.$this->clevel.'">'.DOKU_LF;
199    if ((@file_exists(DOKU_PLUGIN.'editsections/action.php'))
200      && (!plugin_isdisabled('editsections'))){ // for Edit Section Reorganizer Plugin
201      $renderer->doc .= $this->_editButton().$content;
202    } else {
203      $renderer->doc .= $content.$this->_editButton();
204    }
205
206    // output meta line (if wanted) and remove page from filechain
207    $renderer->doc .= $this->_footer(array_pop($this->pages));
208
209    if (!$this->header && $this->clevel && ($this->mode == 'section'))
210      $renderer->doc .= '</div>'.DOKU_LF; // class="level?"
211    $renderer->doc .= '</div>'.DOKU_LF; // class="include hentry"
212
213    // reset defaults
214    $this->helper_plugin_include();
215
216    // return XHTML
217    return $this->doc;
218  }
219
220/* ---------- Private Methods ---------- */
221
222  /**
223   * Get a section including its subsections
224   */
225  function _getSection(){
226    foreach ($this->ins as $ins){
227      if ($ins[0] == 'header'){
228
229        // found the right header
230        if (cleanID($ins[1][0]) == $this->page['section']){
231          $level = $ins[1][1];
232          $i[] = $ins;
233
234        // next header of the same or higher level -> exit
235        } elseif ($ins[1][1] <= $level){
236          $this->ins = $i;
237          return true;
238        } elseif (isset($level)){
239          $i[] = $ins;
240        }
241
242      // add instructions from our section
243      } elseif (isset($level)){
244        $i[] = $ins;
245      }
246    }
247    $this->ins = $i;
248    return true;
249  }
250
251  /**
252   * Corrects relative internal links and media and
253   * converts headers of included pages to subheaders of the current page
254   */
255  function _convertInstructions(){
256    global $ID;
257
258    if (!$this->page['exists']) return false;
259
260    // check if included page is in same namespace
261    $ns      = getNS($this->page['id']);
262    $convert = (getNS($ID) == $ns ? false : true);
263
264    $n = count($this->ins);
265    for ($i = 0; $i < $n; $i++){
266      $current = $this->ins[$i][0];
267
268      // convert internal links and media from relative to absolute
269      if ($convert && (substr($current, 0, 8) == 'internal')){
270        $this->ins[$i][1][0] = $this->_convertInternalLink($this->ins[$i][1][0], $ns);
271
272      // set header level to current section level + header level
273      } elseif ($current == 'header'){
274        $this->_convertHeader($i);
275
276      // the same for sections
277      } elseif (($current == 'section_open') && ($this->mode == 'section')){
278        $this->ins[$i][1][0] = $this->_convertSectionLevel($this->ins[$i][1][0]);
279
280      // show only the first section?
281      } elseif ($this->firstsec && ($current == 'section_close')
282        && ($this->ins[$i-1][0] != 'section_open')){
283        $this->_readMore($i);
284        return true;
285      }
286    }
287    $this->_finishConvert();
288    return true;
289  }
290
291  /**
292   * Convert relative internal links and media
293   *
294   * @param    integer $i: counter for current instruction
295   * @param    string  $ns: namespace of included page
296   * @return   string  $link: converted, now absolute link
297   */
298  function _convertInternalLink($link, $ns){
299
300    // relative subnamespace
301    if ($link{0} == '.'){
302      if ($link{1} == '.') return getNS($ns).':'.substr($link, 2); // parent namespace
303      else return $ns.':'.substr($link, 1);                        // current namespace
304
305    // relative link
306    } elseif (strpos($link, ':') === false){
307      return $ns.':'.$link;
308
309    // absolute link - don't change
310    } else {
311      return $link;
312    }
313  }
314
315  /**
316   * Convert header level and add header to TOC
317   *
318   * @param    integer $i: counter for current instruction
319   * @return   boolean true
320   */
321  function _convertHeader($i){
322    global $conf;
323
324    $text = $this->ins[$i][1][0];
325    $hid  = $this->renderer->_headerToLink($text, 'true');
326    if (empty($this->header)){
327      $this->_offset = $this->clevel - $this->ins[$i][1][1] + 1;
328      $level = $this->_convertSectionLevel(1);
329      $this->header = array('hid' => $hid, 'title' => hsc($text), 'level' => $level);
330      if ($this->noheader){
331        unset($this->ins[$i]);
332        return true;
333      }
334    } else {
335      $level = $this->_convertSectionLevel($this->ins[$i][1][1]);
336    }
337    if ($this->mode == 'section') $this->ins[$i][1][1] = $level;
338
339    // add TOC item
340    if (($level >= $conf['toptoclevel']) && ($level <= $conf['maxtoclevel'])){
341      $this->renderer->toc[] = array(
342        'hid'   => $hid,
343        'title' => $text,
344        'type'  => 'ul',
345        'level' => $level - $conf['toptoclevel'] + 1
346      );
347    }
348    return true;
349  }
350
351  /**
352   * Convert the level of headers and sections
353   *
354   * @param    integer $in: current level
355   * @return   integer $out: converted level
356   */
357  function _convertSectionLevel($in){
358    $out = $in + $this->_offset;
359    if ($out >= 5) return 5;
360    if ($out <= $this->clevel + 1) return $this->clevel + 1;
361    return $out;
362  }
363
364  /**
365   * Adds a read more... link at the bottom of the first section
366   *
367   * @param    integer $i: counter for current instruction
368   * @return   boolean true
369   */
370  function _readMore($i){
371    $more = ((is_array($this->ins[$i+1])) && ($this->ins[$i+1][0] != 'document_end'));
372
373    if ($this->ins[0][0] == 'document_start') $this->ins = array_slice($this->ins, 1, $i);
374    else $this->ins = array_slice($this->ins, 0, $i);
375
376    if ($more){
377      array_unshift($this->ins, array('document_start', array(), 0));
378      $last = array_pop($this->ins);
379      $this->ins[] = array('p_open', array(), $last[2]);
380      $this->ins[] = array('internallink',array($this->page['id'], $this->getLang('readmore')),$last[2]);
381      $this->ins[] = array('p_close', array(), $last[2]);
382      $this->ins[] = $last;
383      $this->ins[] = array('document_end', array(), $last[2]);
384    } else {
385      $this->_finishConvert();
386    }
387    return true;
388  }
389
390  /**
391   * Adds 'document_start' and 'document_end' instructions if not already there
392   */
393  function _finishConvert(){
394    if ($this->ins[0][0] != 'document_start'){
395      array_unshift($this->ins, array('document_start', array(), 0));
396      $this->ins[] = array('document_end', array(), 0);
397    }
398  }
399
400  /**
401   * Remove TOC, section edit buttons and tags
402   */
403  function _cleanXHTML($xhtml){
404    preg_match('!<div class="tags">.*?</div>!s', $xhtml, $match);
405    $this->page['tags'] = $match[0];
406    $replace = array(
407      '!<div class="toc">.*?(</div>\n</div>)!s'   => '', // remove toc
408      '#<!-- SECTION "(.*?)" \[(\d+-\d*)\] -->#e' => '', // remove section edit buttons
409      '!<div class="tags">.*?(</div>)!s'          => '', // remove category tags
410    );
411    $xhtml  = preg_replace(array_keys($replace), array_values($replace), $xhtml);
412    return $xhtml;
413  }
414
415  /**
416   * Optionally display logo for the first tag found in the included page
417   */
418  function _showTagLogos(){
419    if (!$this->getConf('showtaglogos')) return '';
420
421    preg_match_all('/<a [^>]*title="(.*?)" rel="tag"[^>]*>([^<]*)</', $this->page['tags'], $tag);
422    $logoID  = getNS($tag[1][0]).':'.$tag[2][0];
423    $logosrc = mediaFN($logoID);
424    $types = array('.png', '.jpg', '.gif'); // auto-detect filetype
425    foreach ($types as $type){
426      if (!@file_exists($logosrc.$type)) continue;
427      $logoID  .= $type;
428      $logosrc .= $type;
429      list($w, $h, $t, $a) = getimagesize($logosrc);
430      return ' style="min-height: '.$h.'px">'.
431        '<img class="mediaright" src="'.ml($logoID).'" alt="'.$tag[2][0].'"/';
432    }
433    return '';
434  }
435
436  /**
437   * Display an edit button for the included page
438   */
439  function _editButton(){
440    if ($this->page['exists']){
441      if (($this->page['perm'] >= AUTH_EDIT) && (is_writable($this->page['file'])))
442        $action = 'edit';
443      else return '';
444    } elseif ($this->page['perm'] >= AUTH_CREATE){
445      $action = 'create';
446    }
447    if ($this->editbtn){
448      return '<div class="secedit">'.DOKU_LF.DOKU_TAB.
449        html_btn($action, $this->page['id'], '', array('do' => 'edit'), 'post').DOKU_LF.
450        '</div>'.DOKU_LF;
451    } else {
452      return '';
453    }
454  }
455
456  /**
457   * Returns the meta line below the included page
458   */
459  function _footer($page){
460    global $conf;
461
462    if (!$this->footer) return ''; // '<div class="inclmeta">&nbsp;</div>'.DOKU_LF;
463
464    $id   = $page['id'];
465    $meta = p_get_metadata($id);
466    $ret  = array();
467
468    // permalink
469    if ($this->getConf('showlink')){
470      $title = ($page['title'] ? $page['title'] : $meta['title']);
471      if (!$title) $title = str_replace('_', ' ', noNS($id));
472      $class = ($page['exists'] ? 'wikilink1' : 'wikilink2');
473      $link = array(
474        'url'    => wl($id),
475        'title'  => $id,
476        'name'   => hsc($title),
477        'target' => $conf['target']['wiki'],
478        'class'  => $class.' permalink',
479        'more'   => 'rel="bookmark"',
480      );
481      $ret[] = $this->renderer->_formatLink($link);
482    }
483
484    // date
485    if ($this->getConf('showdate')){
486      $date = ($page['date'] ? $page['date'] : $meta['date']['created']);
487      if ($date)
488        $ret[] = '<abbr class="published" title="'.gmdate('Y-m-d\TH:i:s\Z', $date).'">'.
489        date($conf['dformat'], $date).
490        '</abbr>';
491    }
492
493    // author
494    if ($this->getConf('showuser')){
495      $author   = ($page['user'] ? $page['user'] : $meta['creator']);
496      if ($author){
497        $userpage = cleanID($this->getConf('usernamespace').':'.$author);
498        resolve_pageid(getNS($ID), $id, $exists);
499        $class = ($exists ? 'wikilink1' : 'wikilink2');
500        $link = array(
501          'url'    => wl($userpage),
502          'title'  => $userpage,
503          'name'   => hsc($author),
504          'target' => $conf['target']['wiki'],
505          'class'  => $class.' url fn',
506          'pre'    => '<span class="vcard author">',
507          'suf'    => '</span>',
508        );
509        $ret[]    = $this->renderer->_formatLink($link);
510      }
511    }
512
513    // comments - let Discussion Plugin do the work for us
514    if (!$page['section'] && $this->getConf('showcomments')
515      && (!plugin_isdisabled('discussion'))
516      && ($discussion =& plugin_load('helper', 'discussion'))){
517      $disc = $discussion->td($id);
518      if ($disc) $ret[] = '<span class="comment">'.$disc.'</span>';
519    }
520
521    // linkbacks - let Linkback Plugin do the work for us
522    if (!$page['section'] && $this->getConf('showlinkbacks')
523      && (!plugin_isdisabled('linkback'))
524      && ($linkback =& plugin_load('helper', 'linkback'))){
525      $link = $linkback->td($id);
526      if ($link) $ret[] = '<span class="linkback">'.$link.'</span>';
527    }
528
529    $ret = implode(DOKU_LF.DOKU_TAB.'&middot; ', $ret);
530
531    // tags
532    if (($this->getConf('showtags')) && ($page['tags'])){
533      $ret = $this->page['tags'].DOKU_LF.DOKU_TAB.$ret;
534    }
535
536    if (!$ret) $ret = '&nbsp;';
537    $class = 'inclmeta';
538    if ($this->header && $this->clevel && ($this->mode == 'section'))
539      $class .= ' level'.$this->clevel;
540    return '<div class="'.$class.'">'.DOKU_LF.DOKU_TAB.$ret.DOKU_LF.'</div>'.DOKU_LF;
541  }
542
543}
544
545//Setup VIM: ex: et ts=4 enc=utf-8 :
546