xref: /plugin/upgrade/admin.php (revision 9bbe795a9b6df9f69d0d47c1980743682c4c7b78)
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        // we need SSL - only newer HTTPClients check that themselves
219        if(!in_array('ssl', stream_get_transports())) {
220            $this->_warn($this->getLang('vs_ssl'));
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'), $plugininfo['date']);
270                $ok = false;
271            }
272        }
273
274        // next release will need 5.3
275        if($tgzversionnum > '2014-09-29z') {
276            $minphp = '5.3.0';
277        } else {
278            $minphp = '5.2.0';
279        }
280
281        // check if PHP is up to date
282        if(version_compare(phpversion(), $minphp, '<')) {
283            $this->_warn($this->getLang('vs_php'));
284            $ok = false;
285        }
286
287        return $ok;
288    }
289
290    /**
291     * Download the tarball
292     *
293     * @return bool
294     */
295    private function _step_download() {
296        $this->_say($this->getLang('dl_from'), $this->tgzurl);
297
298        @set_time_limit(120);
299        @ignore_user_abort();
300
301        $http          = new DokuHTTPClient();
302        $http->timeout = 120;
303        $data          = $http->get($this->tgzurl);
304
305        if(!$data) {
306            $this->_warn($http->error);
307            $this->_warn($this->getLang('dl_fail'));
308            return false;
309        }
310
311        if(!io_saveFile($this->tgzfile, $data)) {
312            $this->_warn($this->getLang('dl_fail'));
313            return false;
314        }
315
316        $this->_say($this->getLang('dl_done'), filesize_h(strlen($data)));
317
318        return true;
319    }
320
321    /**
322     * Unpack the tarball
323     *
324     * @return bool
325     */
326    private function _step_unpack() {
327        $this->_say('<b>'.$this->getLang('pk_extract').'</b>');
328
329        @set_time_limit(120);
330        @ignore_user_abort();
331
332        try {
333            $tar = new VerboseTar();
334            $tar->open($this->tgzfile);
335            $tar->extract($this->tgzdir, 1);
336            $tar->close();
337        } catch (Exception $e) {
338            $this->_warn($e->getMessage());
339            $this->_warn($this->getLang('pk_fail'));
340            return false;
341        }
342
343        $this->_say($this->getLang('pk_done'));
344
345        $this->_say(
346            $this->getLang('pk_version'),
347            hsc(file_get_contents($this->tgzdir.'/VERSION')),
348            getVersion()
349        );
350        return true;
351    }
352
353    /**
354     * Check permissions of files to change
355     *
356     * @return bool
357     */
358    private function _step_check() {
359        $this->_say($this->getLang('ck_start'));
360        $ok = $this->_traverse('', true);
361        if($ok) {
362            $this->_say('<b>'.$this->getLang('ck_done').'</b>');
363        } else {
364            $this->_warn('<b>'.$this->getLang('ck_fail').'</b>');
365        }
366        return $ok;
367    }
368
369    /**
370     * Copy over new files
371     *
372     * @return bool
373     */
374    private function _step_copy() {
375        $this->_say($this->getLang('cp_start'));
376        $ok = $this->_traverse('', false);
377        if($ok) {
378            $this->_say('<b>'.$this->getLang('cp_done').'</b>');
379            $this->_rmold();
380            $this->_say('<b>'.$this->getLang('finish').'</b>');
381        } else {
382            $this->_warn('<b>'.$this->getLang('cp_fail').'</b>');
383        }
384        return $ok;
385    }
386
387    /**
388     * Delete outdated files
389     */
390    private function _rmold() {
391        $list = file($this->tgzdir.'data/deleted.files');
392        foreach($list as $line) {
393            $line = trim(preg_replace('/#.*$/', '', $line));
394            if(!$line) continue;
395            $file = DOKU_INC.$line;
396            if(!file_exists($file)) continue;
397            if((is_dir($file) && $this->_rdel($file)) ||
398                @unlink($file)
399            ) {
400                $this->_say($this->getLang('rm_done'), hsc($line));
401            } else {
402                $this->_warn($this->getLang('rm_fail'), hsc($line));
403            }
404        }
405        // delete install
406        @unlink(DOKU_INC.'install.php');
407
408        // make sure update message will be gone
409        @touch(DOKU_INC.'doku.php');
410    }
411
412    /**
413     * Traverse over the given dir and compare it to the DokuWiki dir
414     *
415     * Checks what files need an update, tests for writability and copies
416     *
417     * @param string $dir
418     * @param bool   $dryrun do not copy but only check permissions
419     * @return bool
420     */
421    private function _traverse($dir, $dryrun) {
422        $base = $this->tgzdir;
423        $ok   = true;
424
425        $dh = @opendir($base.'/'.$dir);
426        if(!$dh) return false;
427        while(($file = readdir($dh)) !== false) {
428            if($file == '.' || $file == '..') continue;
429            $from = "$base/$dir/$file";
430            $to   = DOKU_INC."$dir/$file";
431
432            if(is_dir($from)) {
433                if($dryrun) {
434                    // just check for writability
435                    if(!is_dir($to)) {
436                        if(is_dir(dirname($to)) && !is_writable(dirname($to))) {
437                            $this->_warn('<b>'.$this->getLang('tv_noperm').'</b>', hsc("$dir/$file"));
438                            $ok = false;
439                        }
440                    }
441                }
442
443                // recursion
444                if(!$this->_traverse("$dir/$file", $dryrun)) {
445                    $ok = false;
446                }
447            } else {
448                $fmd5 = md5(@file_get_contents($from));
449                $tmd5 = md5(@file_get_contents($to));
450                if($fmd5 != $tmd5 || !file_exists($to)) {
451                    if($dryrun) {
452                        // just check for writability
453                        if((file_exists($to) && !is_writable($to)) ||
454                            (!file_exists($to) && is_dir(dirname($to)) && !is_writable(dirname($to)))
455                        ) {
456
457                            $this->_warn('<b>'.$this->getLang('tv_noperm').'</b>', hsc("$dir/$file"));
458                            $ok = false;
459                        } else {
460                            $this->_say($this->getLang('tv_upd'), hsc("$dir/$file"));
461                        }
462                    } else {
463                        // check dir
464                        if(io_mkdir_p(dirname($to))) {
465                            // copy
466                            if(!copy($from, $to)) {
467                                $this->_warn('<b>'.$this->getLang('tv_nocopy').'</b>', hsc("$dir/$file"));
468                                $ok = false;
469                            } else {
470                                $this->_say($this->getLang('tv_done'), hsc("$dir/$file"));
471                            }
472                        } else {
473                            $this->_warn('<b>'.$this->getLang('tv_nodir').'</b>', hsc("$dir"));
474                            $ok = false;
475                        }
476                    }
477                }
478            }
479        }
480        closedir($dh);
481        return $ok;
482    }
483}
484
485// vim:ts=4:sw=4:et:enc=utf-8:
486