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