1<?php
2/**
3 * DokuWiki Plugin safefnrecode (Action Component)
4 *
5 * @license GPL 2 http://www.gnu.org/licenses/gpl-2.0.html
6 * @author  Andreas Gohr <andi@splitbrain.org>
7 */
8
9class action_plugin_safefnrecode extends DokuWiki_Action_Plugin
10{
11
12    /** @inheritdoc */
13    public function register(Doku_Event_Handler $controller)
14    {
15        $controller->register_hook('INDEXER_TASKS_RUN', 'BEFORE', $this, 'handleIndexerTasksRun');
16    }
17
18    /**
19     * Handle indexer event
20     *
21     * @param Doku_Event $event
22     * @param $param
23     */
24    public function handleIndexerTasksRun(Doku_Event $event, $param)
25    {
26        global $conf;
27        if ($conf['fnencode'] != 'safe') return;
28
29        if (!file_exists($conf['datadir'].'_safefn.recoded')) {
30            $this->recode($conf['datadir']);
31            touch($conf['datadir'].'_safefn.recoded');
32        }
33
34        if (!file_exists($conf['olddir'].'_safefn.recoded')) {
35            $this->recode($conf['olddir']);
36            touch($conf['olddir'].'_safefn.recoded');
37        }
38
39        if (!file_exists($conf['metadir'].'_safefn.recoded')) {
40            $this->recode($conf['metadir']);
41            touch($conf['metadir'].'_safefn.recoded');
42        }
43
44        if (!file_exists($conf['mediadir'].'_safefn.recoded')) {
45            $this->recode($conf['mediadir']);
46            touch($conf['mediadir'].'_safefn.recoded');
47        }
48    }
49
50    /**
51     * Recursive function to rename all safe encoded files to use the new
52     * square bracket post indicator
53     */
54    private function recode($dir)
55    {
56        $dh = opendir($dir);
57        if (!$dh) return;
58        while (($file = readdir($dh)) !== false) {
59            if ($file == '.' || $file == '..') continue;           # cur and upper dir
60            if (is_dir("$dir/$file")) $this->recode("$dir/$file"); #recurse
61            if (strpos($file, '%') === false) continue;             # no encoding used
62            $new = preg_replace('/(%[^\]]*?)\./', '\1]', $file);    # new post indicator
63            if (preg_match('/%[^\]]+$/', $new)) $new .= ']';        # fix end FS#2122
64            rename("$dir/$file", "$dir/$new");                     # rename it
65        }
66        closedir($dh);
67    }
68}
69