xref: /plugin/upgrade/admin.php (revision 06dc93a8e6157d08190145bd5f2a2d5f3b563ea0)
1<?php
2/**
3 * DokuWiki Plugin upgrade (Admin Component)
4 *
5 * @license GPL 2 http://www.gnu.org/licenses/gpl-2.0.html
6 * @author  Andreas Gohr <andi@splitbrain.org>
7 */
8
9// must be run within Dokuwiki
10if(!defined('DOKU_INC')) die();
11if(!defined('DOKU_PLUGIN')) define('DOKU_PLUGIN', DOKU_INC.'lib/plugins/');
12require_once DOKU_PLUGIN.'admin.php';
13require_once DOKU_PLUGIN.'upgrade/VerboseTarLib.class.php';
14
15class admin_plugin_upgrade extends DokuWiki_Admin_Plugin {
16    private $tgzurl;
17    private $tgzfile;
18    private $tgzdir;
19    private $tgzversion;
20    private $pluginversion;
21
22    public function __construct() {
23        global $conf;
24
25        $branch = 'stable';
26
27        $this->tgzurl        = "https://github.com/splitbrain/dokuwiki/archive/$branch.tar.gz";
28        $this->tgzfile       = $conf['tmpdir'].'/dokuwiki-upgrade.tgz';
29        $this->tgzdir        = $conf['tmpdir'].'/dokuwiki-upgrade/';
30        $this->tgzversion    = "https://raw.githubusercontent.com/splitbrain/dokuwiki/$branch/VERSION";
31        $this->pluginversion = "https://raw.githubusercontent.com/splitbrain/dokuwiki-plugin-upgrade/master/plugin.info.txt";
32    }
33
34    public function getMenuSort() {
35        return 555;
36    }
37
38    public function handle() {
39        if($_REQUEST['step'] && !checkSecurityToken()) {
40            unset($_REQUEST['step']);
41        }
42    }
43
44    public function html() {
45        $abrt = false;
46        $next = false;
47
48        echo '<h1>'.$this->getLang('menu').'</h1>';
49
50        global $conf;
51        if($conf['safemodehack']) {
52            $abrt = false;
53            $next = false;
54            echo $this->locale_xhtml('safemode');
55            return;
56        }
57
58        $this->_say('<div id="plugin__upgrade">');
59        // enable auto scroll
60        ?>
61        <script language="javascript" type="text/javascript">
62            var plugin_upgrade = window.setInterval(function () {
63                var obj = document.getElementById('plugin__upgrade');
64                if (obj) obj.scrollTop = obj.scrollHeight;
65            }, 25);
66        </script>
67        <?php
68
69        // handle current step
70        $this->_stepit($abrt, $next);
71
72        // disable auto scroll
73        ?>
74        <script language="javascript" type="text/javascript">
75            window.setTimeout(function () {
76                window.clearInterval(plugin_upgrade);
77            }, 50);
78        </script>
79        <?php
80        $this->_say('</div>');
81
82        echo '<form action="" method="get" id="plugin__upgrade_form">';
83        echo '<input type="hidden" name="do" value="admin" />';
84        echo '<input type="hidden" name="page" value="upgrade" />';
85        echo '<input type="hidden" name="sectok" value="'.getSecurityToken().'" />';
86        if($next) echo '<input type="submit" name="step['.$next.']" value="'.$this->getLang('btn_continue').' ➡" class="button continue" />';
87        if($abrt) echo '<input type="submit" name="step[cancel]" value="✖ '.$this->getLang('btn_abort').'" class="button abort" />';
88        echo '</form>';
89
90        $this->_progress($next);
91    }
92
93    /**
94     * Display a progress bar of all steps
95     *
96     * @param string $next the next step
97     */
98    private function _progress($next) {
99        $steps  = array('version', 'download', 'unpack', 'check', 'upgrade');
100        $active = true;
101        $count = 0;
102
103        echo '<div id="plugin__upgrade_meter"><ol>';
104        foreach($steps as $step) {
105            $count++;
106            if($step == $next) $active = false;
107            if($active) {
108                echo '<li class="active">';
109                echo '<span class="step">✔</span>';
110            } else {
111                echo '<li>';
112                echo '<span class="step">'.$count.'</span>';
113            }
114
115            echo '<span class="stage">'.$this->getLang('step_'.$step).'</span>';
116            echo '</li>';
117        }
118        echo '</ol></div>';
119    }
120
121    /**
122     * Decides the current step and executes it
123     *
124     * @param bool $abrt
125     * @param bool $next
126     */
127    private function _stepit(&$abrt, &$next) {
128
129        if(isset($_REQUEST['step']) && is_array($_REQUEST['step'])) {
130            $step = array_shift(array_keys($_REQUEST['step']));
131        } else {
132            $step = '';
133        }
134
135        if($step == 'cancel') {
136            # cleanup
137            @unlink($this->tgzfile);
138            $this->_rdel($this->tgzdir);
139            $step = '';
140        }
141
142        if($step) {
143            $abrt = true;
144            $next = false;
145            if($step == 'version') {
146                $this->_step_version();
147                $next = 'download';
148            } elseif(!file_exists($this->tgzfile)) {
149                if($this->_step_download()) $next = 'unpack';
150            } elseif(!is_dir($this->tgzdir)) {
151                if($this->_step_unpack()) $next = 'check';
152            } elseif($step != 'upgrade') {
153                if($this->_step_check()) $next = 'upgrade';
154            } elseif($step == 'upgrade') {
155                if($this->_step_copy()) $next = 'cancel';
156            } else {
157                echo 'uhm. what happened? where am I? This should not happen';
158            }
159        } else {
160            # first time run, show intro
161            echo $this->locale_xhtml('step0');
162            $abrt = false;
163            $next = 'version';
164        }
165    }
166
167    /**
168     * Output the given arguments using vsprintf and flush buffers
169     */
170    public static function _say() {
171        $args = func_get_args();
172        echo '<img src="'.DOKU_BASE.'lib/images/blank.gif" width="16" height="16" alt="" /> ';
173        echo vsprintf(array_shift($args)."<br />\n", $args);
174        flush();
175        ob_flush();
176    }
177
178    /**
179     * Print a warning using the given arguments with vsprintf and flush buffers
180     */
181    public static function _warn() {
182        $args = func_get_args();
183        echo '<img src="'.DOKU_BASE.'lib/images/error.png" width="16" height="16" alt="!" /> ';
184        echo vsprintf(array_shift($args)."<br />\n", $args);
185        flush();
186        ob_flush();
187    }
188
189    /**
190     * Recursive delete
191     *
192     * @author Jon Hassall
193     * @link   http://de.php.net/manual/en/function.unlink.php#87045
194     */
195    private function _rdel($dir) {
196        if(!$dh = @opendir($dir)) {
197            return false;
198        }
199        while(false !== ($obj = readdir($dh))) {
200            if($obj == '.' || $obj == '..') continue;
201
202            if(!@unlink($dir.'/'.$obj)) {
203                $this->_rdel($dir.'/'.$obj);
204            }
205        }
206        closedir($dh);
207        return @rmdir($dir);
208    }
209
210    /**
211     * Check various versions
212     *
213     * @return bool
214     */
215    private function _step_version() {
216        $ok = true;
217
218        // check if PHP is up to date
219        if(version_compare(phpversion(), '5.2.0', '<')) {
220            $this->_warn($this->getLang('vs_php'));
221            $ok = false;
222        }
223
224        // get the available version
225        $http       = new DokuHTTPClient();
226        $tgzversion = $http->get($this->tgzversion);
227        if(!$tgzversion) {
228            $this->_warn($this->getLang('vs_tgzno').' '.hsc($http->error));
229            $ok = false;
230        }
231        if(!preg_match('/(^| )(\d\d\d\d-\d\d-\d\d[a-z]*)( |$)/i', $tgzversion, $m)) {
232            $this->_warn($this->getLang('vs_tgzno'));
233            $ok            = false;
234            $tgzversionnum = 0;
235        } else {
236            $tgzversionnum = $m[2];
237            $this->_say($this->getLang('vs_tgz'), $tgzversion);
238        }
239
240        // get the current version
241        $version = getVersion();
242        if(!preg_match('/(^| )(\d\d\d\d-\d\d-\d\d[a-z]*)( |$)/i', $version, $m)) {
243            $versionnum = 0;
244        } else {
245            $versionnum = $m[2];
246        }
247        $this->_say($this->getLang('vs_local'), $version);
248
249        // compare versions
250        if(!$versionnum) {
251            $this->_warn($this->getLang('vs_localno'));
252            $ok = false;
253        } else if($tgzversionnum) {
254            if($tgzversionnum < $versionnum) {
255                $this->_warn($this->getLang('vs_newer'));
256                $ok = false;
257            } elseif($tgzversionnum == $versionnum) {
258                $this->_warn($this->getLang('vs_same'));
259                $ok = false;
260            }
261        }
262
263        // check plugin version
264        $pluginversion = $http->get($this->pluginversion);
265        if($pluginversion) {
266            $plugininfo = linesToHash(explode("\n", $pluginversion));
267            $myinfo     = $this->getInfo();
268            if($plugininfo['date'] > $myinfo['date']) {
269                $this->_warn($this->getLang('vs_plugin'));
270                $ok = false;
271            }
272        }
273
274        return $ok;
275    }
276
277    /**
278     * Download the tarball
279     *
280     * @return bool
281     */
282    private function _step_download() {
283        $this->_say($this->getLang('dl_from'), $this->tgzurl);
284
285        @set_time_limit(120);
286        @ignore_user_abort();
287
288        $http          = new DokuHTTPClient();
289        $http->timeout = 120;
290        $data          = $http->get($this->tgzurl);
291
292        if(!$data) {
293            $this->_warn($http->error);
294            $this->_warn($this->getLang('dl_fail'));
295            return false;
296        }
297
298        if(!io_saveFile($this->tgzfile, $data)) {
299            $this->_warn($this->getLang('dl_fail'));
300            return false;
301        }
302
303        $this->_say($this->getLang('dl_done'), filesize_h(strlen($data)));
304
305        return true;
306    }
307
308    /**
309     * Unpack the tarball
310     *
311     * @return bool
312     */
313    private function _step_unpack() {
314        $this->_say('<b>'.$this->getLang('pk_extract').'</b>');
315
316        @set_time_limit(120);
317        @ignore_user_abort();
318
319        try {
320            $tar = new VerboseTar();
321            $tar->open($this->tgzfile);
322            $tar->extract($this->tgzdir, 1);
323            $tar->close();
324        } catch (Exception $e) {
325            $this->_warn($e->getMessage());
326            $this->_warn($this->getLang('pk_fail'));
327            return false;
328        }
329
330        $this->_say($this->getLang('pk_done'));
331
332        $this->_say(
333            $this->getLang('pk_version'),
334            hsc(file_get_contents($this->tgzdir.'/VERSION')),
335            getVersion()
336        );
337        return true;
338    }
339
340    /**
341     * Check permissions of files to change
342     *
343     * @return bool
344     */
345    private function _step_check() {
346        $this->_say($this->getLang('ck_start'));
347        $ok = $this->_traverse('', true);
348        if($ok) {
349            $this->_say('<b>'.$this->getLang('ck_done').'</b>');
350        } else {
351            $this->_warn('<b>'.$this->getLang('ck_fail').'</b>');
352        }
353        return $ok;
354    }
355
356    /**
357     * Copy over new files
358     *
359     * @return bool
360     */
361    private function _step_copy() {
362        $this->_say($this->getLang('cp_start'));
363        $ok = $this->_traverse('', false);
364        if($ok) {
365            $this->_say('<b>'.$this->getLang('cp_done').'</b>');
366            $this->_rmold();
367            $this->_say('<b>'.$this->getLang('finish').'</b>');
368        } else {
369            $this->_warn('<b>'.$this->getLang('cp_fail').'</b>');
370        }
371        return $ok;
372    }
373
374    /**
375     * Delete outdated files
376     */
377    private function _rmold() {
378        $list = file($this->tgzdir.'data/deleted.files');
379        foreach($list as $line) {
380            $line = trim(preg_replace('/#.*$/', '', $line));
381            if(!$line) continue;
382            $file = DOKU_INC.$line;
383            if(!file_exists($file)) continue;
384            if((is_dir($file) && $this->_rdel($file)) ||
385                @unlink($file)
386            ) {
387                $this->_say($this->getLang('rm_done'), hsc($line));
388            } else {
389                $this->_warn($this->getLang('rm_fail'), hsc($line));
390            }
391        }
392    }
393
394    /**
395     * Traverse over the given dir and compare it to the DokuWiki dir
396     *
397     * Checks what files need an update, tests for writability and copies
398     *
399     * @param string $dir
400     * @param bool   $dryrun do not copy but only check permissions
401     * @return bool
402     */
403    private function _traverse($dir, $dryrun) {
404        $base = $this->tgzdir;
405        $ok   = true;
406
407        $dh = @opendir($base.'/'.$dir);
408        if(!$dh) return false;
409        while(($file = readdir($dh)) !== false) {
410            if($file == '.' || $file == '..') continue;
411            $from = "$base/$dir/$file";
412            $to   = DOKU_INC."$dir/$file";
413
414            if(is_dir($from)) {
415                if($dryrun) {
416                    // just check for writability
417                    if(!is_dir($to)) {
418                        if(is_dir(dirname($to)) && !is_writable(dirname($to))) {
419                            $this->_warn('<b>'.$this->getLang('tv_noperm').'</b>', hsc("$dir/$file"));
420                            $ok = false;
421                        }
422                    }
423                }
424
425                // recursion
426                if(!$this->_traverse("$dir/$file", $dryrun)) {
427                    $ok = false;
428                }
429            } else {
430                $fmd5 = md5(@file_get_contents($from));
431                $tmd5 = md5(@file_get_contents($to));
432                if($fmd5 != $tmd5 || !file_exists($to)) {
433                    if($dryrun) {
434                        // just check for writability
435                        if((file_exists($to) && !is_writable($to)) ||
436                            (!file_exists($to) && is_dir(dirname($to)) && !is_writable(dirname($to)))
437                        ) {
438
439                            $this->_warn('<b>'.$this->getLang('tv_noperm').'</b>', hsc("$dir/$file"));
440                            $ok = false;
441                        } else {
442                            $this->_say($this->getLang('tv_upd'), hsc("$dir/$file"));
443                        }
444                    } else {
445                        // check dir
446                        if(io_mkdir_p(dirname($to))) {
447                            // copy
448                            if(!copy($from, $to)) {
449                                $this->_warn('<b>'.$this->getLang('tv_nocopy').'</b>', hsc("$dir/$file"));
450                                $ok = false;
451                            } else {
452                                $this->_say($this->getLang('tv_done'), hsc("$dir/$file"));
453                            }
454                        } else {
455                            $this->_warn('<b>'.$this->getLang('tv_nodir').'</b>', hsc("$dir"));
456                            $ok = false;
457                        }
458                    }
459                }
460            }
461        }
462        closedir($dh);
463        return $ok;
464    }
465}
466
467// vim:ts=4:sw=4:et:enc=utf-8:
468