<?php
/**
 * TOC Plugin
 *
 * @license    GPL 2 (http://www.gnu.org/licenses/gpl.html)
 * @author     Andriy Lesyuk <andriy.lesyuk@softjourn.com>
 */

if(!defined('DOKU_INC')) die();
if(!defined('DOKU_PLUGIN')) define('DOKU_PLUGIN',DOKU_INC.'lib/plugins/');

require_once(DOKU_PLUGIN.'action.php');

class action_plugin_toc extends DokuWiki_Action_Plugin {

    /**
     * Return some info
     */
    function getInfo() {
        return array(
            'author' => 'Andriy Lesyuk',
            'email'  => 'andriy.lesyuk@softjourn.com',
            'date'   => '2009-04-13',
            'name'   => 'TOC Action Plugin',
            'desc'   => 'Inserts TOC in the place you specified in your Wiki page'
        );
    }

    /**
     * Register event handlers
     */
    function register(&$controller) {
        $controller->register_hook('TPL_ACT_RENDER', 'BEFORE', $this, 'handle_act_render', array());
        $controller->register_hook('TPL_CONTENT_DISPLAY', 'BEFORE', $this, 'handle_content_display', array());
    }

    function handle_act_render(&$event, $param) {
        global $ID;
        global $INFO;
        if (p_get_metadata($ID, 'movetoc')) {
            $INFO['prependTOC'] = false;
        }
    }

    /**
     * Replace <!-- TOC --> with the toc
     */
    function handle_content_display(&$event, $param) {
        $toc = tpl_toc(true);
        if ($toc) {
            $event->data = str_replace('<!-- TOC -->', '<div class="inlinetoc">'.$toc."</div>", $event->data);
        }
    }

}
