1<?php
2/**
3 * Regex Template plugin, Choose template from regex on $ID
4 * @author     Cédric Villemain <cedric.villemain@dalibo.com>
5 */
6
7if(!defined('DOKU_INC')) die();
8
9if(!defined('DOKU_PLUGIN')) define('DOKU_PLUGIN',DOKU_INC.'lib/plugins/');
10require_once(DOKU_PLUGIN.'action.php');
11
12class action_plugin_regex_template extends DokuWiki_Action_Plugin {
13
14  /**
15   * return some info
16   */
17  function getInfo(){
18	  return confToHash(dirname(__FILE__).'/info.txt');
19  }
20
21  /**
22   * register the eventhandlers
23   */
24  function register(&$contr){
25    $contr->register_hook('HTML_PAGE_FROMTEMPLATE', 'BEFORE', $this, 'regex_template', array());
26  }
27
28  function regex_template(&$event, $param) {
29	global $ID;
30	global $conf;
31	global $INFO;
32
33	$path = dirname(wikiFN($ID));
34
35	if(@file_exists($path.'/_template.txt')){
36	  $tpl = io_readFile($path.'/_template.txt');
37	}else{
38	  // search upper namespaces for templates
39	  $len = strlen(rtrim($conf['datadir'],'/'));
40	  while (strlen($path) >= $len){
41		if(@file_exists($path.'/__template.txt')){
42		  $tpl = io_readFile($path.'/__template.txt');
43		  break;
44		}
45		$path = substr($path, 0, strrpos($path, '/'));
46	  }
47	}
48
49	$array_regex = (array)explode("\n",$conf['plugin']['regex_template']['reg_tpl_regex']);
50	reset($array_regex);
51	foreach ($array_regex as $regex) {
52	  list($pattern, $replacement) = explode(',', $regex);
53	  $my_new_ID = @preg_replace($pattern, $replacement, $ID);
54	  $my_new_file = wikiFN($my_new_ID);
55	  if(@file_exists($my_new_file)){
56		$tpl = io_readFile($my_new_file);
57		break;
58	  }
59	}
60
61	if(!$tpl) return '';
62
63	// replace placeholders
64	$tpl = str_replace('@ID@',$ID,$tpl);
65	$tpl = str_replace('@NS@',getNS($id),$tpl);
66	$tpl = str_replace('@PAGE@',strtr(noNS($ID),'_',' '),$tpl);
67	$tpl = str_replace('@USER@',$_SERVER['REMOTE_USER'],$tpl);
68	$tpl = str_replace('@NAME@',$INFO['userinfo']['name'],$tpl);
69	$tpl = str_replace('@MAIL@',$INFO['userinfo']['mail'],$tpl);
70	$tpl = str_replace('@DATE@',$conf['dformat'],$tpl);
71	// we need the callback to work around strftime's char limit
72	$tpl = preg_replace_callback('/%./',create_function('$m','return strftime($m[0]);'),$tpl);
73
74	$event->result=$tpl;
75	$event->preventDefault();
76  }
77}
78