<?php
/**
 * action plugin for simplified XHTML Ruby notation
 * (full page post processing required due to ruby in headers and ToC)
 *
 * @license	GPLv3 (http://www.gnu.org/licenses/gpl.html)
 * @link	   http://www.dokuwiki.org/plugin:xhtmlruby
 * @author	 Mike "Pomax" Kamermans <pomax@nihongoresources.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_xhtmlruby extends DokuWiki_Action_Plugin {

	var $version = '2009-10-26';

	// configurable options
	var $parse_wiki_text = false;
	var $parse_toc_text = false;

	// for now, we operate on Japanese only - TODO: bopomofo and hangul rubification
	var $re_kanji = "[\x{4E00}-\x{9FFF}\x{3005}\x{30F6}]+";
	var $re_kana = "[\x{3040}-\x{30FF}]*";
		
	// s/// patterns
	var $re_search = "";
	var $re_replace = "";

	function getInfo() {
	  return array(
		'author' => 'Mike "Pomax" Kamermans',
		'email'  => 'pomax@nihongoresources.com',
		'date'   => $this->version,
		'name'   => 'xhtmlruby',
		'desc'   => 'Converts Japanese 漢字(ふり) into xhtml 1.1 <ruby><rb>漢字</rb><rp>(</rp><rt>ふり</rt><rp>)</rp></ruby> markup',
		'url'	=> 'n/a');
	}

	/**
	 * Postprocesses the html that was built from that, to rubify kanji that have associated furigana.
	 */
	function register(&$controller) 
	{
		// initialise variables
		$this->re_search = "/(".$this->re_kanji.")\((".$this->re_kana.")\)/u";
		$this->re_replace = "<ruby><rb>$1</rb><rp>(</rp><rt>$2</rt><rp>)</rp></ruby>";
		
		// initialise ini variables
		$inivars = parse_ini_file(DOKU_INC.'lib/plugins/xhtmlruby/conf.ini');
		if($inivars['parse_toc_text']==true) { $this->parse_toc_text = true; }
		if($inivars['parse_wiki_text']==true) { $this->parse_wiki_text = true; }

		// uses a custom hook that needs to be added in html.php, see documentation
		if($this->parse_toc_text===true) { 
			$controller->register_hook('HTML_TOC_ITEM', 'AFTER', $this, '_rubify_tocitem'); }
		
		if($this->parse_wiki_text===true) {
			$controller->register_hook('RENDERER_CONTENT_POSTPROCESS', 'AFTER', $this, '_rubify'); }
	}

	/**
	 * rubify for ToC items
	 */
	function _rubify_tocitem(&$event, $param)
	{
		$item = &$event->data;
		$item = preg_replace($this->re_search,$this->re_replace,$item);
	}

	/**
	 * rubify for wiki text
	 */
	function _rubify(&$event, $param)
	{
		// reference to data and associated data type
		$data = &$event->data[1];
		$datatype = &$event->data[0];
		
		// do nothing if the data is not not xhtml (this only generates xhtml ruby markup)
		if ($datatype != 'xhtml')  { return; }

		// and finally, perform the postprocessing 'en place'
		$data = preg_replace($this->re_search,$this->re_replace,$data);
	}
}
?>
