<?php
/**
 * Display Title Dokuwiki Plugin (Syntax Component)
 *
 * Description: The Display Title Plugin can display the id or title of the current page or the title of an arbitrary page.
 *
 * Syntax: <<display id>>
 *         <<display title>>
 *         <<display title ID>>
 *         ID   (Optional): Arbitrary local wiki page id as would be passed to normal local wiki links.
 *
 * @license    The MIT License (https://opensource.org/licenses/MIT)
 * @author     Jay Jeckel <jeckelmail@gmail.com>
 *
 * Copyright (c) 2016 Jay Jeckel
 * Licensed under the MIT license: https://opensource.org/licenses/MIT
 * Permission is granted to use, copy, modify, and distribute the work.
 * Full license information available in the project LICENSE file.
 */

if (!defined('DOKU_INC')) { die(); }

class syntax_plugin_displaytitle extends DokuWiki_Syntax_Plugin
{
    function getInfo() { return confToHash(dirname(__FILE__) . '/plugin.info.txt'); }

    function getType() { return 'substition'; }

    function getSort() { return 5; }

    function connectTo($mode)
    {
        $pattern = '<<' . 'display' . '\s' . '(?:' . 'title' . '|' . 'id' . ')' . '>>';
        $this->Lexer->addSpecialPattern($pattern, $mode, 'plugin_displaytitle');

        $pattern = '<<' . 'display' . '\s' . 'title' . '\s' . '.+?' . '>>';
        $this->Lexer->addSpecialPattern($pattern, $mode, 'plugin_displaytitle');
    }

    function handle($match, $state, $pos, Doku_Handler $handler)
    {
        global $ID;

        list($key, $id) = explode(' ', trim(substr($match, 9, -2)), 2);
        if (empty($id) || strlen(trim($id)) == 0) { $id = $ID; }

        if ($key == 'id') { return $id; }

        $meta = p_get_metadata($id);
        return (empty($meta) || !isset($meta['title']) ? $id : $meta['title']);
    }

    function render($mode, Doku_Renderer $renderer, $data)
    {
        if ($mode != 'xhtml') { return false; }

        $renderer->doc .= $data;
        return true;
    }
}

//Setup VIM: ex: et ts=4 enc=utf-8 :
?>