1<?php 2 3use dokuwiki\Extension\Plugin; 4use dokuwiki\Cache\Cache; 5 6/** 7 * Redirect2 - DokuWiki Redirect Manager 8 * 9 * @license GPL 2 (http://www.gnu.org/licenses/gpl.html) 10 * @author Satoshi Sahara <sahara.satoshi@gmail.com> 11 */ 12class helper_plugin_redirect2 extends Plugin 13{ 14 public $ConfFile; // path/to/redirection config file 15 public $pattern = NULL; 16 17 /** 18 * Setup the redirection map from config file 19 * 20 * syntax of the config file 21 * [status] ptnSearch ptnDestination 22 * 23 * status: 301 or 302 24 * ptnSearch: old id pattern of page or media 25 * ptnDestination: new id pattern of page or media 26 * 27 */ 28 public function __construct() 29 { 30 $this->ConfFile = DOKU_CONF.'redirect.conf'; 31 32 if ($this->pattern != NULL) return; 33 34 $cache = new Cache('##redirect2##', '.conf'); 35 $depends = array('files' => array($this->ConfFile)); 36 37 if ($cache->useCache($depends)) { 38 $this->pattern = unserialize($cache->retrieveCache(false)); 39 //error_log('Redirect2 : loaded from cache '.$cache->cache); 40 } elseif ($this->_loadConfig()) { 41 // cache has expired 42 //error_log('Redirect2 : loaded from file '.$this->ConfFile); 43 $cache->storeCache(serialize($this->pattern)); 44 } 45 } 46 47 public function __destruct() 48 { 49 $this->pattern = NULL; 50 } 51 52 protected function _loadConfig() 53 { 54 if (!file_exists($this->ConfFile)) return false; 55 56 $lines = @file($this->ConfFile); 57 if (!$lines) return false; 58 foreach ($lines as $line) { 59 if (preg_match('/^#/',$line)) continue; 60 $line = str_replace('\\#','#', $line); 61 $line = preg_replace('/\s#.*$/','', $line); 62 $line = trim($line); 63 if (empty($line)) continue; 64 65 $token = preg_split('/\s+/', $line, 3); 66 if (count($token) == 3) { 67 $status = ($token[0] == 301) ? 301 : 302; 68 array_shift($token); 69 } else $status =302; 70 71 if (count($token) != 2) continue; 72 if (strpos($token[0], '%') !== 0) { // not regular expression 73 // get clean match pattern, keeping leading and tailing ":" 74 $head = (substr($token[0],0,1)==':') ? ':' : ''; 75 $tail = (substr($token[0],-1) ==':') ? ':' : ''; 76 $ptn = $head . cleanID($token[0]) . $tail; 77 } else { 78 $ptn = $token[0]; 79 } 80 $this->pattern[$ptn] = array( 81 'destination' => $token[1], 'status' => $status, 82 ); 83 } 84 return ($this->pattern != NULL) ? true : false; 85 } 86 87} 88