xref: /plugin/upgrade/admin.php (revision c37aa5dc1bc1cdf4f77c09704b350df69d559396)
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        // we need SSL - only newer HTTPClients check that themselves
225        if(!in_array('ssl', stream_get_transports())) {
226            $this->_warn($this->getLang('vs_ssl'));
227            $ok = false;
228        }
229
230        // get the available version
231        $http       = new DokuHTTPClient();
232        $tgzversion = $http->get($this->tgzversion);
233        if(!$tgzversion) {
234            $this->_warn($this->getLang('vs_tgzno').' '.hsc($http->error));
235            $ok = false;
236        }
237        if(!preg_match('/(^| )(\d\d\d\d-\d\d-\d\d[a-z]*)( |$)/i', $tgzversion, $m)) {
238            $this->_warn($this->getLang('vs_tgzno'));
239            $ok            = false;
240            $tgzversionnum = 0;
241        } else {
242            $tgzversionnum = $m[2];
243            $this->_say($this->getLang('vs_tgz'), $tgzversion);
244        }
245
246        // get the current version
247        $version = getVersion();
248        if(!preg_match('/(^| )(\d\d\d\d-\d\d-\d\d[a-z]*)( |$)/i', $version, $m)) {
249            $versionnum = 0;
250        } else {
251            $versionnum = $m[2];
252        }
253        $this->_say($this->getLang('vs_local'), $version);
254
255        // compare versions
256        if(!$versionnum) {
257            $this->_warn($this->getLang('vs_localno'));
258            $ok = false;
259        } else if($tgzversionnum) {
260            if($tgzversionnum < $versionnum) {
261                $this->_warn($this->getLang('vs_newer'));
262                $ok = false;
263            } elseif($tgzversionnum == $versionnum) {
264                $this->_warn($this->getLang('vs_same'));
265                $ok = false;
266            }
267        }
268
269        // check plugin version
270        $pluginversion = $http->get($this->pluginversion);
271        if($pluginversion) {
272            $plugininfo = linesToHash(explode("\n", $pluginversion));
273            $myinfo     = $this->getInfo();
274            if($plugininfo['date'] > $myinfo['date']) {
275                $this->_warn($this->getLang('vs_plugin'));
276                $ok = false;
277            }
278        }
279
280        return $ok;
281    }
282
283    /**
284     * Download the tarball
285     *
286     * @return bool
287     */
288    private function _step_download() {
289        $this->_say($this->getLang('dl_from'), $this->tgzurl);
290
291        @set_time_limit(120);
292        @ignore_user_abort();
293
294        $http          = new DokuHTTPClient();
295        $http->timeout = 120;
296        $data          = $http->get($this->tgzurl);
297
298        if(!$data) {
299            $this->_warn($http->error);
300            $this->_warn($this->getLang('dl_fail'));
301            return false;
302        }
303
304        if(!io_saveFile($this->tgzfile, $data)) {
305            $this->_warn($this->getLang('dl_fail'));
306            return false;
307        }
308
309        $this->_say($this->getLang('dl_done'), filesize_h(strlen($data)));
310
311        return true;
312    }
313
314    /**
315     * Unpack the tarball
316     *
317     * @return bool
318     */
319    private function _step_unpack() {
320        $this->_say('<b>'.$this->getLang('pk_extract').'</b>');
321
322        @set_time_limit(120);
323        @ignore_user_abort();
324
325        try {
326            $tar = new VerboseTar();
327            $tar->open($this->tgzfile);
328            $tar->extract($this->tgzdir, 1);
329            $tar->close();
330        } catch (Exception $e) {
331            $this->_warn($e->getMessage());
332            $this->_warn($this->getLang('pk_fail'));
333            return false;
334        }
335
336        $this->_say($this->getLang('pk_done'));
337
338        $this->_say(
339            $this->getLang('pk_version'),
340            hsc(file_get_contents($this->tgzdir.'/VERSION')),
341            getVersion()
342        );
343        return true;
344    }
345
346    /**
347     * Check permissions of files to change
348     *
349     * @return bool
350     */
351    private function _step_check() {
352        $this->_say($this->getLang('ck_start'));
353        $ok = $this->_traverse('', true);
354        if($ok) {
355            $this->_say('<b>'.$this->getLang('ck_done').'</b>');
356        } else {
357            $this->_warn('<b>'.$this->getLang('ck_fail').'</b>');
358        }
359        return $ok;
360    }
361
362    /**
363     * Copy over new files
364     *
365     * @return bool
366     */
367    private function _step_copy() {
368        $this->_say($this->getLang('cp_start'));
369        $ok = $this->_traverse('', false);
370        if($ok) {
371            $this->_say('<b>'.$this->getLang('cp_done').'</b>');
372            $this->_rmold();
373            $this->_say('<b>'.$this->getLang('finish').'</b>');
374        } else {
375            $this->_warn('<b>'.$this->getLang('cp_fail').'</b>');
376        }
377        return $ok;
378    }
379
380    /**
381     * Delete outdated files
382     */
383    private function _rmold() {
384        $list = file($this->tgzdir.'data/deleted.files');
385        foreach($list as $line) {
386            $line = trim(preg_replace('/#.*$/', '', $line));
387            if(!$line) continue;
388            $file = DOKU_INC.$line;
389            if(!file_exists($file)) continue;
390            if((is_dir($file) && $this->_rdel($file)) ||
391                @unlink($file)
392            ) {
393                $this->_say($this->getLang('rm_done'), hsc($line));
394            } else {
395                $this->_warn($this->getLang('rm_fail'), hsc($line));
396            }
397        }
398    }
399
400    /**
401     * Traverse over the given dir and compare it to the DokuWiki dir
402     *
403     * Checks what files need an update, tests for writability and copies
404     *
405     * @param string $dir
406     * @param bool   $dryrun do not copy but only check permissions
407     * @return bool
408     */
409    private function _traverse($dir, $dryrun) {
410        $base = $this->tgzdir;
411        $ok   = true;
412
413        $dh = @opendir($base.'/'.$dir);
414        if(!$dh) return false;
415        while(($file = readdir($dh)) !== false) {
416            if($file == '.' || $file == '..') continue;
417            $from = "$base/$dir/$file";
418            $to   = DOKU_INC."$dir/$file";
419
420            if(is_dir($from)) {
421                if($dryrun) {
422                    // just check for writability
423                    if(!is_dir($to)) {
424                        if(is_dir(dirname($to)) && !is_writable(dirname($to))) {
425                            $this->_warn('<b>'.$this->getLang('tv_noperm').'</b>', hsc("$dir/$file"));
426                            $ok = false;
427                        }
428                    }
429                }
430
431                // recursion
432                if(!$this->_traverse("$dir/$file", $dryrun)) {
433                    $ok = false;
434                }
435            } else {
436                $fmd5 = md5(@file_get_contents($from));
437                $tmd5 = md5(@file_get_contents($to));
438                if($fmd5 != $tmd5 || !file_exists($to)) {
439                    if($dryrun) {
440                        // just check for writability
441                        if((file_exists($to) && !is_writable($to)) ||
442                            (!file_exists($to) && is_dir(dirname($to)) && !is_writable(dirname($to)))
443                        ) {
444
445                            $this->_warn('<b>'.$this->getLang('tv_noperm').'</b>', hsc("$dir/$file"));
446                            $ok = false;
447                        } else {
448                            $this->_say($this->getLang('tv_upd'), hsc("$dir/$file"));
449                        }
450                    } else {
451                        // check dir
452                        if(io_mkdir_p(dirname($to))) {
453                            // copy
454                            if(!copy($from, $to)) {
455                                $this->_warn('<b>'.$this->getLang('tv_nocopy').'</b>', hsc("$dir/$file"));
456                                $ok = false;
457                            } else {
458                                $this->_say($this->getLang('tv_done'), hsc("$dir/$file"));
459                            }
460                        } else {
461                            $this->_warn('<b>'.$this->getLang('tv_nodir').'</b>', hsc("$dir"));
462                            $ok = false;
463                        }
464                    }
465                }
466            }
467        }
468        closedir($dh);
469        return $ok;
470    }
471}
472
473// vim:ts=4:sw=4:et:enc=utf-8:
474