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