<?php
/**
 * Regex Template plugin, Choose template from regex on $ID
 * @author     Cédric Villemain <cedric.villemain@dalibo.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_regex_template extends DokuWiki_Action_Plugin {

  /**
   * return some info
   */
  function getInfo(){
	  return confToHash(dirname(__FILE__).'/info.txt');
  }

  /**
   * register the eventhandlers
   */
  function register(&$contr){
    $contr->register_hook('HTML_PAGE_FROMTEMPLATE', 'BEFORE', $this, 'regex_template', array());
  }

  function regex_template(&$event, $param) {
	global $ID;
	global $conf;
	global $INFO;

	$path = dirname(wikiFN($ID));

	if(@file_exists($path.'/_template.txt')){
	  $tpl = io_readFile($path.'/_template.txt');
	}else{
	  // search upper namespaces for templates
	  $len = strlen(rtrim($conf['datadir'],'/'));
	  while (strlen($path) >= $len){
		if(@file_exists($path.'/__template.txt')){
		  $tpl = io_readFile($path.'/__template.txt');
		  break;
		}
		$path = substr($path, 0, strrpos($path, '/'));
	  }
	}

	$array_regex = (array)explode("\n",$conf['plugin']['regex_template']['reg_tpl_regex']);
	reset($array_regex);
	foreach ($array_regex as $regex) {
	  list($pattern, $replacement) = explode(',', $regex);
	  $my_new_ID = @preg_replace($pattern, $replacement, $ID);
	  $my_new_file = wikiFN($my_new_ID);
	  if(@file_exists($my_new_file)){
		$tpl = io_readFile($my_new_file);
		break;
	  }
	}

	if(!$tpl) return '';

	// replace placeholders
	$tpl = str_replace('@ID@',$ID,$tpl);
	$tpl = str_replace('@NS@',getNS($id),$tpl);
	$tpl = str_replace('@PAGE@',strtr(noNS($ID),'_',' '),$tpl);
	$tpl = str_replace('@USER@',$_SERVER['REMOTE_USER'],$tpl);
	$tpl = str_replace('@NAME@',$INFO['userinfo']['name'],$tpl);
	$tpl = str_replace('@MAIL@',$INFO['userinfo']['mail'],$tpl);
	$tpl = str_replace('@DATE@',$conf['dformat'],$tpl);
	// we need the callback to work around strftime's char limit
	$tpl = preg_replace_callback('/%./',create_function('$m','return strftime($m[0]);'),$tpl);

	$event->result=$tpl;
	$event->preventDefault();
  }
}
