1<?php
2/**
3 * Move Plugin Page Rewriter
4 *
5 * @license    GPL 2 (http://www.gnu.org/licenses/gpl.html)
6 * @author     Michael Hamann <michael@content-space.de>
7 * @author     Gary Owen <gary@isection.co.uk>
8 * @author     Andreas Gohr <gohr@cosmocode.de>
9 */
10// must be run within Dokuwiki
11if(!defined('DOKU_INC')) die();
12
13// load required handler class
14require_once(dirname(__FILE__) . '/handler.php');
15
16/**
17 * Class helper_plugin_move_rewrite
18 *
19 * This class handles the rewriting of wiki text to update the links
20 */
21class helper_plugin_move_rewrite extends DokuWiki_Plugin {
22
23    /**
24     * Under what key is move data to be saved in metadata
25     */
26    const METAKEY = 'plugin_move';
27
28    /**
29     * What is they filename of the lockfile
30     */
31    const LOCKFILENAME = '_plugin_move.lock';
32
33    /**
34     * @var string symbol to make move operations easily recognizable in change log
35     */
36    public $symbol = '↷';
37
38    /**
39     * This function loads and returns the persistent metadata for the move plugin. If there is metadata for the
40     * pagemove plugin (not the old one but the version that immediately preceeded the move plugin) it will be migrated.
41     *
42     * @param string $id The id of the page the metadata shall be loaded for
43     * @return array|null The metadata of the page
44     */
45    public function getMoveMeta($id) {
46        $all_meta = p_get_metadata($id, '', METADATA_DONT_RENDER);
47
48        /* todo migrate old move data
49        if(isset($all_meta['plugin_pagemove']) && !is_null($all_meta['plugin_pagemove'])) {
50            if(isset($all_meta[self::METAKEY])) {
51                $all_meta[self::METAKEY] = array_merge_recursive($all_meta['plugin_pagemove'], $all_meta[self::METAKEY]);
52            } else {
53                $all_meta[self::METAKEY] = $all_meta['plugin_pagemove'];
54            }
55            p_set_metadata($id, array(self::METAKEY => $all_meta[self::METAKEY], 'plugin_pagemove' => null), false, true);
56        }
57        */
58
59        $meta = isset($all_meta[self::METAKEY]) ? $all_meta[self::METAKEY] : array();
60        if(!isset($meta['origin'])) {
61            $meta['origin'] = '';
62        }
63        if(!isset($meta['pages'])) {
64            $meta['pages'] = array();
65        }
66        if(!isset($meta['media'])) {
67            $meta['media'] = array();
68        }
69
70        return $meta;
71    }
72
73    /**
74     * Remove any existing move meta data for the given page
75     *
76     * @param $id
77     */
78    public function unsetMoveMeta($id) {
79        p_set_metadata($id, array(self::METAKEY => array()), false, true);
80    }
81
82    /**
83     * Add info about a moved document to the metadata of an affected page
84     *
85     * @param string $id   affected page
86     * @param string $src  moved document's original id
87     * @param string $dst  moved document's new id
88     * @param string $type 'media' or 'page'
89     * @throws Exception on wrong argument
90     */
91    public function setMoveMeta($id, $src, $dst, $type) {
92        $this->setMoveMetas($id, array($src => $dst), $type);
93    }
94
95    /**
96     * Add info about several moved documents to the metadata of an affected page
97     *
98     * @param string $id    affected page
99     * @param array  $moves list of moves (src is key, dst is value)
100     * @param string $type  'media' or 'page'
101     * @throws Exception
102     */
103    public function setMoveMetas($id, $moves, $type) {
104        if($type != 'pages' && $type != 'media') {
105            throw new Exception('wrong type specified');
106        }
107        if(!page_exists($id, '', false)) {
108            return;
109        }
110
111        $meta = $this->getMoveMeta($id);
112        foreach($moves as $src => $dst) {
113            $meta[$type][] = array($src, $dst);
114        }
115
116        p_set_metadata($id, array(self::METAKEY => $meta), false, true);
117    }
118
119    /**
120     * Store info about the move of a page in its own meta data
121     *
122     * This has to be called before the move is executed
123     *
124     * @param string $id moved page's original (and still current) id
125     */
126    public function setSelfMoveMeta($id) {
127        $meta = $this->getMoveMeta($id);
128        // was this page moved multiple times? keep the orignal name til rewriting occured
129        if(isset($meta['origin']) && $meta['origin'] !== '') {
130            return;
131        }
132        $meta['origin'] = $id;
133
134        p_set_metadata($id, array(self::METAKEY => $meta), false, true);
135    }
136
137    /**
138     * Check if rewrites may be executed within this process right now
139     *
140     * @return bool
141     */
142    public static function isLocked() {
143        global $PLUGIN_MOVE_WORKING;
144        global $conf;
145        $lockfile = $conf['lockdir'] . self::LOCKFILENAME;
146        return ((isset($PLUGIN_MOVE_WORKING) && $PLUGIN_MOVE_WORKING > 0) || file_exists($lockfile));
147    }
148
149    /**
150     * Do not allow any rewrites in this process right now
151     */
152    public static function addLock() {
153        global $PLUGIN_MOVE_WORKING;
154        global $conf;
155        $PLUGIN_MOVE_WORKING = $PLUGIN_MOVE_WORKING ? $PLUGIN_MOVE_WORKING + 1 : 1;
156        $lockfile = $conf['lockdir'] . self::LOCKFILENAME;
157        if (!file_exists($lockfile)) {
158            io_savefile($lockfile, "1\n");
159        } else {
160            $stack = intval(file_get_contents($lockfile));
161            ++$stack;
162            io_savefile($lockfile, strval($stack));
163        }
164    }
165
166    /**
167     * Allow rerites in this process again, unless some other lock exists
168     */
169    public static function removeLock() {
170        global $PLUGIN_MOVE_WORKING;
171        global $conf;
172        $PLUGIN_MOVE_WORKING = $PLUGIN_MOVE_WORKING ? $PLUGIN_MOVE_WORKING - 1 : 0;
173        $lockfile = $conf['lockdir'] . self::LOCKFILENAME;
174        if (!file_exists($lockfile)) {
175            throw new Exception("removeLock failed: lockfile missing");
176        } else {
177            $stack = intval(file_get_contents($lockfile));
178            if($stack === 1) {
179                unlink($lockfile);
180            } else {
181                --$stack;
182                io_savefile($lockfile, strval($stack));
183            }
184        }
185    }
186
187    /**
188     * Allow rewrites in this process again.
189     *
190     * @author Michael Große <grosse@cosmocode.de>
191     */
192    public static function removeAllLocks() {
193        global $conf;
194        $lockfile = $conf['lockdir'] . self::LOCKFILENAME;
195        if (file_exists($lockfile)) {
196            unlink($lockfile);
197        }
198        unset($GLOBALS['PLUGIN_MOVE_WORKING']);
199    }
200
201
202    /**
203     * Rewrite a text in order to fix the content after the given moves.
204     *
205     * @param string $id   The id of the wiki page, if the page itself was moved the old id
206     * @param string $text The text to be rewritten
207     * @return string        The rewritten wiki text
208     */
209    public function rewrite($id, $text) {
210        $meta = $this->getMoveMeta($id);
211
212        $handlers = array();
213        $pages    = $meta['pages'];
214        $media    = $meta['media'];
215        $origin   = $meta['origin'];
216        if($origin == '') $origin = $id;
217
218        $data = array(
219            'id'          => $id,
220            'origin'      => &$origin,
221            'pages'       => &$pages,
222            'media_moves' => &$media,
223            'handlers'    => &$handlers
224        );
225
226        /*
227         * PLUGIN_MOVE_HANDLERS REGISTER event:
228         *
229         * Plugin handlers can be registered in the $handlers array, the key is the plugin name as it is given to the handler
230         * The handler needs to be a valid callback, it will get the following parameters:
231         * $match, $state, $pos, $pluginname, $handler. The first three parameters are equivalent to the parameters
232         * of the handle()-function of syntax plugins, the $pluginname is just the plugin name again so handler functions
233         * that handle multiple plugins can distinguish for which the match is. The last parameter is the handler object
234         * which is an instance of helper_plugin_move_handle
235         */
236        trigger_event('PLUGIN_MOVE_HANDLERS_REGISTER', $data);
237
238        $modes = p_get_parsermodes();
239
240        // Create the parser
241        $Parser = new Doku_Parser();
242
243        // Add the Handler
244        /** @var $Parser->Handler helper_plugin_move_handler */
245        $Parser->Handler = $this->loadHelper('move_handler');
246        $Parser->Handler->init($id, $origin, $pages, $media, $handlers);
247
248        //add modes to parser
249        foreach($modes as $mode) {
250            $Parser->addMode($mode['mode'], $mode['obj']);
251        }
252
253        return $Parser->parse($text);
254    }
255
256    /**
257     * Rewrite the text of a page according to the recorded moves, the rewritten text is saved
258     *
259     * @param string      $id   The id of the page that shall be rewritten
260     * @param string|null $text Old content of the page. When null is given the content is loaded from disk
261     * @return string|bool The rewritten content, false on error
262     */
263    public function rewritePage($id, $text = null, $save = true) {
264        $meta = $this->getMoveMeta($id);
265        if(is_null($text)) {
266            $text = rawWiki($id);
267        }
268
269        if($meta['pages'] || $meta['media']) {
270            $old_text = $text;
271            $text     = $this->rewrite($id, $text);
272
273            $changed = ($old_text != $text);
274            $file    = wikiFN($id, '', false);
275            if ($save === true) {
276                if(is_writable($file) || !$changed) {
277                    if($changed) {
278                        // Wait a second when the page has just been rewritten
279                        $oldRev = filemtime(wikiFN($id));
280                        if($oldRev == time()) sleep(1);
281
282                        saveWikiText($id, $text, $this->symbol . ' ' . $this->getLang('linkchange'), $this->getConf('minor'));
283                    }
284                    $this->unsetMoveMeta($id);
285                } else {
286                    // FIXME: print error here or fail silently?
287                    msg('Error: Page ' . hsc($id) . ' needs to be rewritten because of page renames but is not writable.', -1);
288                    return false;
289                }
290            }
291        }
292
293        return $text;
294    }
295
296}
297