xref: /dokuwiki/inc/parser/metadata.php (revision 9a72776194fc27b31238ade37ba590b4e0217cf2)
1<?php
2/**
3 * Renderer for metadata
4 *
5 * @author Esther Brunner <wikidesign@gmail.com>
6 */
7if(!defined('DOKU_INC')) die('meh.');
8
9if(!defined('DOKU_LF')) {
10    // Some whitespace to help View > Source
11    define ('DOKU_LF', "\n");
12}
13
14if(!defined('DOKU_TAB')) {
15    // Some whitespace to help View > Source
16    define ('DOKU_TAB', "\t");
17}
18
19/**
20 * The MetaData Renderer
21 *
22 * Metadata is additional information about a DokuWiki page that gets extracted mainly from the page's content
23 * but also it's own filesystem data (like the creation time). All metadata is stored in the fields $meta and
24 * $persistent.
25 *
26 * Some simplified rendering to $doc is done to gather the page's (text-only) abstract.
27 */
28class Doku_Renderer_metadata extends Doku_Renderer {
29    /** the approximate byte lenght to capture for the abstract */
30    const ABSTRACT_LEN = 250;
31
32    /** the maximum UTF8 character length for the abstract */
33    const ABSTRACT_MAX = 500;
34
35    /** @var array transient meta data, will be reset on each rendering */
36    public $meta = array();
37
38    /** @var array persistent meta data, will be kept until explicitly deleted */
39    public $persistent = array();
40
41    /** @var array the list of headers used to create unique link ids */
42    protected $headers = array();
43
44    /** @var string temporary $doc store */
45    protected $store = '';
46
47    /** @var string keeps the first image reference */
48    protected $firstimage = '';
49
50    /** @var bool determines if enough data for the abstract was collected, yet */
51    public $capture = true;
52
53    /** @var int number of bytes captured for abstract */
54    protected $captured = 0;
55
56    /**
57     * Returns the format produced by this renderer.
58     *
59     * @return string always 'metadata'
60     */
61    function getFormat() {
62        return 'metadata';
63    }
64
65    /**
66     * Initialize the document
67     *
68     * Sets up some of the persistent info about the page if it doesn't exist, yet.
69     */
70    function document_start() {
71        global $ID;
72
73        $this->headers = array();
74
75        // external pages are missing create date
76        if(!$this->persistent['date']['created']) {
77            $this->persistent['date']['created'] = filectime(wikiFN($ID));
78        }
79        if(!isset($this->persistent['user'])) {
80            $this->persistent['user'] = '';
81        }
82        if(!isset($this->persistent['creator'])) {
83            $this->persistent['creator'] = '';
84        }
85        // reset metadata to persistent values
86        $this->meta = $this->persistent;
87    }
88
89    /**
90     * Finalize the document
91     *
92     * Stores collected data in the metadata
93     */
94    function document_end() {
95        global $ID;
96
97        // store internal info in metadata (notoc,nocache)
98        $this->meta['internal'] = $this->info;
99
100        if(!isset($this->meta['description']['abstract'])) {
101            // cut off too long abstracts
102            $this->doc = trim($this->doc);
103            if(strlen($this->doc) > self::ABSTRACT_MAX) {
104                $this->doc = utf8_substr($this->doc, 0, self::ABSTRACT_MAX).'…';
105            }
106            $this->meta['description']['abstract'] = $this->doc;
107        }
108
109        $this->meta['relation']['firstimage'] = $this->firstimage;
110
111        if(!isset($this->meta['date']['modified'])) {
112            $this->meta['date']['modified'] = filemtime(wikiFN($ID));
113        }
114
115    }
116
117    /**
118     * Render plain text data
119     *
120     * This function takes care of the amount captured data and will stop capturing when
121     * enough abstract data is available
122     *
123     * @param $text
124     */
125    function cdata($text) {
126        if(!$this->capture) return;
127
128        $this->doc .= $text;
129
130        $this->captured += strlen($text);
131        if($this->captured > self::ABSTRACT_LEN) $this->capture = false;
132    }
133
134    /**
135     * Add an item to the TOC
136     *
137     * @param string $id       the hash link
138     * @param string $text     the text to display
139     * @param int    $level    the nesting level
140     */
141    function toc_additem($id, $text, $level) {
142        global $conf;
143
144        //only add items within configured levels
145        if($level >= $conf['toptoclevel'] && $level <= $conf['maxtoclevel']) {
146            // the TOC is one of our standard ul list arrays ;-)
147            $this->meta['description']['tableofcontents'][] = array(
148                'hid'   => $id,
149                'title' => $text,
150                'type'  => 'ul',
151                'level' => $level - $conf['toptoclevel'] + 1
152            );
153        }
154
155    }
156
157    /**
158     * Render a heading
159     *
160     * @param string $text  the text to display
161     * @param int    $level header level
162     * @param int    $pos   byte position in the original source
163     */
164    function header($text, $level, $pos) {
165        if(!isset($this->meta['title'])) $this->meta['title'] = $text;
166
167        // add the header to the TOC
168        $hid = $this->_headerToLink($text, 'true');
169        $this->toc_additem($hid, $text, $level);
170
171        // add to summary
172        $this->cdata(DOKU_LF.$text.DOKU_LF);
173    }
174
175    /**
176     * Open a paragraph
177     */
178    function p_open() {
179        $this->cdata(DOKU_LF);
180    }
181
182    /**
183     * Close a paragraph
184     */
185    function p_close() {
186        $this->cdata(DOKU_LF);
187    }
188
189    /**
190     * Create a line break
191     */
192    function linebreak() {
193        $this->cdata(DOKU_LF);
194    }
195
196    /**
197     * Create a horizontal line
198     */
199    function hr() {
200        $this->cdata(DOKU_LF.'----------'.DOKU_LF);
201    }
202
203    /**
204     * Callback for footnote start syntax
205     *
206     * All following content will go to the footnote instead of
207     * the document. To achieve this the previous rendered content
208     * is moved to $store and $doc is cleared
209     *
210     * @author Andreas Gohr <andi@splitbrain.org>
211     */
212    function footnote_open() {
213        if($this->capture) {
214            // move current content to store and record footnote
215            $this->store = $this->doc;
216            $this->doc   = '';
217        }
218    }
219
220    /**
221     * Callback for footnote end syntax
222     *
223     * All rendered content is moved to the $footnotes array and the old
224     * content is restored from $store again
225     *
226     * @author Andreas Gohr
227     */
228    function footnote_close() {
229        if($this->capture) {
230            // restore old content
231            $this->doc   = $this->store;
232            $this->store = '';
233        }
234    }
235
236    /**
237     * Open an unordered list
238     */
239    function listu_open() {
240        $this->cdata(DOKU_LF);
241    }
242
243    /**
244     * Open an ordered list
245     */
246    function listo_open() {
247        $this->cdata(DOKU_LF);
248    }
249
250    /**
251     * Open a list item
252     *
253     * @param int $level the nesting level
254     */
255    function listitem_open($level) {
256        $this->cdata(str_repeat(DOKU_TAB, $level).'* ');
257    }
258
259    /**
260     * Close a list item
261     */
262    function listitem_close() {
263        $this->cdata(DOKU_LF);
264    }
265
266    /**
267     * Output preformatted text
268     *
269     * @param string $text
270     */
271    function preformatted($text) {
272        $this->cdata($text);
273    }
274
275    /**
276     * Start a block quote
277     */
278    function quote_open() {
279        $this->cdata(DOKU_LF.DOKU_TAB.'"');
280    }
281
282    /**
283     * Stop a block quote
284     */
285    function quote_close() {
286        $this->cdata('"'.DOKU_LF);
287    }
288
289    /**
290     * Display text as file content, optionally syntax highlighted
291     *
292     * @param string $text text to show
293     * @param string $lang programming language to use for syntax highlighting
294     * @param string $file file path label
295     */
296    function file($text, $lang = null, $file = null) {
297        $this->cdata(DOKU_LF.$text.DOKU_LF);
298    }
299
300    /**
301     * Display text as code content, optionally syntax highlighted
302     *
303     * @param string $text     text to show
304     * @param string $language programming language to use for syntax highlighting
305     * @param string $file     file path label
306     */
307    function code($text, $language = null, $file = null) {
308        $this->cdata(DOKU_LF.$text.DOKU_LF);
309    }
310
311    /**
312     * Format an acronym
313     *
314     * Uses $this->acronyms
315     *
316     * @param string $acronym
317     */
318    function acronym($acronym) {
319        $this->cdata($acronym);
320    }
321
322    /**
323     * Format a smiley
324     *
325     * Uses $this->smiley
326     *
327     * @param string $smiley
328     */
329    function smiley($smiley) {
330        $this->cdata($smiley);
331    }
332
333    /**
334     * Format an entity
335     *
336     * Entities are basically small text replacements
337     *
338     * Uses $this->entities
339     *
340     * @param string $entity
341     */
342    function entity($entity) {
343        $this->cdata($entity);
344    }
345
346    /**
347     * Typographically format a multiply sign
348     *
349     * Example: ($x=640, $y=480) should result in "640×480"
350     *
351     * @param string|int $x first value
352     * @param string|int $y second value
353     */
354    function multiplyentity($x, $y) {
355        $this->cdata($x.'×'.$y);
356    }
357
358    /**
359     * Render an opening single quote char (language specific)
360     */
361    function singlequoteopening() {
362        global $lang;
363        $this->cdata($lang['singlequoteopening']);
364    }
365
366    /**
367     * Render a closing single quote char (language specific)
368     */
369    function singlequoteclosing() {
370        global $lang;
371        $this->cdata($lang['singlequoteclosing']);
372    }
373
374    /**
375     * Render an apostrophe char (language specific)
376     */
377    function apostrophe() {
378        global $lang;
379        $this->cdata($lang['apostrophe']);
380    }
381
382    /**
383     * Render an opening double quote char (language specific)
384     */
385    function doublequoteopening() {
386        global $lang;
387        $this->cdata($lang['doublequoteopening']);
388    }
389
390    /**
391     * Render an closinging double quote char (language specific)
392     */
393    function doublequoteclosing() {
394        global $lang;
395        $this->cdata($lang['doublequoteclosing']);
396    }
397
398    /**
399     * Render a CamelCase link
400     *
401     * @param string $link The link name
402     * @see http://en.wikipedia.org/wiki/CamelCase
403     */
404    function camelcaselink($link) {
405        $this->internallink($link, $link);
406    }
407
408    /**
409     * Render a page local link
410     *
411     * @param string $hash hash link identifier
412     * @param string $name name for the link
413     */
414    function locallink($hash, $name = null) {
415        if(is_array($name)) {
416            $this->_firstimage($name['src']);
417            if($name['type'] == 'internalmedia') $this->_recordMediaUsage($name['src']);
418        }
419    }
420
421    /**
422     * keep track of internal links in $this->meta['relation']['references']
423     *
424     * @param string       $id   page ID to link to. eg. 'wiki:syntax'
425     * @param string|array $name name for the link, array for media file
426     */
427    function internallink($id, $name = null) {
428        global $ID;
429
430        if(is_array($name)) {
431            $this->_firstimage($name['src']);
432            if($name['type'] == 'internalmedia') $this->_recordMediaUsage($name['src']);
433        }
434
435        $parts = explode('?', $id, 2);
436        if(count($parts) === 2) {
437            $id = $parts[0];
438        }
439
440        $default = $this->_simpleTitle($id);
441
442        // first resolve and clean up the $id
443        resolve_pageid(getNS($ID), $id, $exists);
444        @list($page) = explode('#', $id, 2);
445
446        // set metadata
447        $this->meta['relation']['references'][$page] = $exists;
448        // $data = array('relation' => array('isreferencedby' => array($ID => true)));
449        // p_set_metadata($id, $data);
450
451        // add link title to summary
452        if($this->capture) {
453            $name = $this->_getLinkTitle($name, $default, $id);
454            $this->doc .= $name;
455        }
456    }
457
458    /**
459     * Render an external link
460     *
461     * @param string       $url  full URL with scheme
462     * @param string|array $name name for the link, array for media file
463     */
464    function externallink($url, $name = null) {
465        if(is_array($name)) {
466            $this->_firstimage($name['src']);
467            if($name['type'] == 'internalmedia') $this->_recordMediaUsage($name['src']);
468        }
469
470        if($this->capture) {
471            $this->doc .= $this->_getLinkTitle($name, '<'.$url.'>');
472        }
473    }
474
475    /**
476     * Render an interwiki link
477     *
478     * You may want to use $this->_resolveInterWiki() here
479     *
480     * @param string       $match     original link - probably not much use
481     * @param string|array $name      name for the link, array for media file
482     * @param string       $wikiName  indentifier (shortcut) for the remote wiki
483     * @param string       $wikiUri   the fragment parsed from the original link
484     */
485    function interwikilink($match, $name = null, $wikiName, $wikiUri) {
486        if(is_array($name)) {
487            $this->_firstimage($name['src']);
488            if($name['type'] == 'internalmedia') $this->_recordMediaUsage($name['src']);
489        }
490
491        if($this->capture) {
492            list($wikiUri) = explode('#', $wikiUri, 2);
493            $name = $this->_getLinkTitle($name, $wikiUri);
494            $this->doc .= $name;
495        }
496    }
497
498    /**
499     * Link to windows share
500     *
501     * @param string       $url  the link
502     * @param string|array $name name for the link, array for media file
503     */
504    function windowssharelink($url, $name = null) {
505        if(is_array($name)) {
506            $this->_firstimage($name['src']);
507            if($name['type'] == 'internalmedia') $this->_recordMediaUsage($name['src']);
508        }
509
510        if($this->capture) {
511            if($name) $this->doc .= $name;
512            else $this->doc .= '<'.$url.'>';
513        }
514    }
515
516    /**
517     * Render a linked E-Mail Address
518     *
519     * Should honor $conf['mailguard'] setting
520     *
521     * @param string       $address Email-Address
522     * @param string|array $name    name for the link, array for media file
523     */
524    function emaillink($address, $name = null) {
525        if(is_array($name)) {
526            $this->_firstimage($name['src']);
527            if($name['type'] == 'internalmedia') $this->_recordMediaUsage($name['src']);
528        }
529
530        if($this->capture) {
531            if($name) $this->doc .= $name;
532            else $this->doc .= '<'.$address.'>';
533        }
534    }
535
536    /**
537     * Render an internal media file
538     *
539     * @param string $src     media ID
540     * @param string $title   descriptive text
541     * @param string $align   left|center|right
542     * @param int    $width   width of media in pixel
543     * @param int    $height  height of media in pixel
544     * @param string $cache   cache|recache|nocache
545     * @param string $linking linkonly|detail|nolink
546     */
547    function internalmedia($src, $title = null, $align = null, $width = null,
548                           $height = null, $cache = null, $linking = null) {
549        if($this->capture && $title) $this->doc .= '['.$title.']';
550        $this->_firstimage($src);
551        $this->_recordMediaUsage($src);
552    }
553
554    /**
555     * Render an external media file
556     *
557     * @param string $src     full media URL
558     * @param string $title   descriptive text
559     * @param string $align   left|center|right
560     * @param int    $width   width of media in pixel
561     * @param int    $height  height of media in pixel
562     * @param string $cache   cache|recache|nocache
563     * @param string $linking linkonly|detail|nolink
564     */
565    function externalmedia($src, $title = null, $align = null, $width = null,
566                           $height = null, $cache = null, $linking = null) {
567        if($this->capture && $title) $this->doc .= '['.$title.']';
568        $this->_firstimage($src);
569    }
570
571    /**
572     * Render the output of an RSS feed
573     *
574     * @param string $url    URL of the feed
575     * @param array  $params Finetuning of the output
576     */
577    function rss($url, $params) {
578        $this->meta['relation']['haspart'][$url] = true;
579
580        $this->meta['date']['valid']['age'] =
581            isset($this->meta['date']['valid']['age']) ?
582                min($this->meta['date']['valid']['age'], $params['refresh']) :
583                $params['refresh'];
584    }
585
586    #region Utils
587
588    /**
589     * Removes any Namespace from the given name but keeps
590     * casing and special chars
591     *
592     * @author Andreas Gohr <andi@splitbrain.org>
593     */
594    function _simpleTitle($name) {
595        global $conf;
596
597        if(is_array($name)) return '';
598
599        if($conf['useslash']) {
600            $nssep = '[:;/]';
601        } else {
602            $nssep = '[:;]';
603        }
604        $name = preg_replace('!.*'.$nssep.'!', '', $name);
605        //if there is a hash we use the anchor name only
606        $name = preg_replace('!.*#!', '', $name);
607        return $name;
608    }
609
610    /**
611     * Creates a linkid from a headline
612     *
613     * @author Andreas Gohr <andi@splitbrain.org>
614     * @param string  $title   The headline title
615     * @param boolean $create  Create a new unique ID?
616     * @return string
617     */
618    function _headerToLink($title, $create = false) {
619        if($create) {
620            return sectionID($title, $this->headers);
621        } else {
622            $check = false;
623            return sectionID($title, $check);
624        }
625    }
626
627    /**
628     * Construct a title and handle images in titles
629     *
630     * @author Harry Fuecks <hfuecks@gmail.com>
631     * @param string|array $title    either string title or media array
632     * @param string       $default  default title if nothing else is found
633     * @param null|string  $id       linked page id (used to extract title from first heading)
634     * @return string title text
635     */
636    function _getLinkTitle($title, $default, $id = null) {
637        if(is_array($title)) {
638            if($title['title']) {
639                return '['.$title['title'].']';
640            } else {
641                return $default;
642            }
643        } else if(is_null($title) || trim($title) == '') {
644            if(useHeading('content') && $id) {
645                $heading = p_get_first_heading($id, METADATA_DONT_RENDER);
646                if($heading) return $heading;
647            }
648            return $default;
649        } else {
650            return $title;
651        }
652    }
653
654    /**
655     * Remember first image
656     *
657     * @param string $src image URL or ID
658     */
659    function _firstimage($src) {
660        if($this->firstimage) return;
661        global $ID;
662
663        list($src) = explode('#', $src, 2);
664        if(!media_isexternal($src)) {
665            resolve_mediaid(getNS($ID), $src, $exists);
666        }
667        if(preg_match('/.(jpe?g|gif|png)$/i', $src)) {
668            $this->firstimage = $src;
669        }
670    }
671
672    /**
673     * Store list of used media files in metadata
674     *
675     * @param string $src media ID
676     */
677    function _recordMediaUsage($src) {
678        global $ID;
679
680        list ($src) = explode('#', $src, 2);
681        if(media_isexternal($src)) return;
682        resolve_mediaid(getNS($ID), $src, $exists);
683        $this->meta['relation']['media'][$src] = $exists;
684    }
685
686    #endregion
687}
688
689//Setup VIM: ex: et ts=4 :
690