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