aboutsummaryrefslogtreecommitdiffstatshomepage
path: root/lib/plugins/extension/Installer.php
blob: 1de59cd5342b2c87b64c3b85b3891123d8747d52 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
<?php

namespace dokuwiki\plugin\extension;

use dokuwiki\HTTP\DokuHTTPClient;
use dokuwiki\Utf8\PhpString;
use RecursiveDirectoryIterator;
use RecursiveIteratorIterator;
use splitbrain\PHPArchive\ArchiveCorruptedException;
use splitbrain\PHPArchive\ArchiveIllegalCompressionException;
use splitbrain\PHPArchive\ArchiveIOException;
use splitbrain\PHPArchive\Tar;
use splitbrain\PHPArchive\Zip;

/**
 * Install and deinstall extensions
 *
 * This manages all the file operations and downloads needed to install an extension.
 */
class Installer
{
    /** @var string[] a list of temporary directories used during this installation */
    protected array $temporary = [];

    /** @var bool if changes have been made that require a cache purge */
    protected $isDirty = false;

    /** @var bool Replace existing files? */
    protected $overwrite = false;

    /** @var string The last used URL to install an extension */
    protected $sourceUrl = '';

    protected $processed = [];

    public const STATUS_SKIPPED = 'skipped';
    public const STATUS_UPDATED = 'updated';
    public const STATUS_INSTALLED = 'installed';


    /**
     * Initialize a new extension installer
     *
     * @param bool $overwrite
     */
    public function __construct($overwrite = false)
    {
        $this->overwrite = $overwrite;
    }

    /**
     * Destructor
     *
     * deletes any dangling temporary directories
     */
    public function __destruct()
    {
        foreach ($this->temporary as $dir) {
            io_rmdir($dir, true);
        }
        $this->cleanUp();
    }

    /**
     * Install an extension by ID
     *
     * This will simply call installExtension after constructing an extension from the ID
     *
     * The $skipInstalled parameter should only be used when installing dependencies
     *
     * @param string $id the extension ID
     * @param bool $skipInstalled Ignore the overwrite setting and skip installed extensions
     * @throws Exception
     */
    public function installFromId($id, $skipInstalled = false)
    {
        $extension = Extension::createFromId($id);
        if ($skipInstalled && $extension->isInstalled()) return;
        $this->installExtension($extension);
    }

    /**
     * Install an extension
     *
     * This will simply call installFromUrl() with the URL from the extension
     *
     * @param Extension $extension
     * @throws Exception
     */
    public function installExtension(Extension $extension)
    {
        $url = $extension->getDownloadURL();
        if (!$url) {
            throw new Exception('error_nourl', [$extension->getId()]);
        }
        $this->installFromUrl($url);
    }

    /**
     * Install extensions from a given URL
     *
     * @param string $url the URL to the archive
     * @param null $base the base directory name to use
     * @throws Exception
     */
    public function installFromUrl($url, $base = null)
    {
        $this->sourceUrl = $url;
        $archive = $this->downloadArchive($url);
        $this->installFromArchive(
            $archive,
            $base
        );
    }

    /**
     * Install extensions from a user upload
     *
     * @param string $field name of the upload file
     * @throws Exception
     */
    public function installFromUpload($field)
    {
        $this->sourceUrl = '';
        if ($_FILES[$field]['error']) {
            throw new Exception('msg_upload_failed', [$_FILES[$field]['error']]);
        }

        $tmp = $this->mkTmpDir();
        if (!move_uploaded_file($_FILES[$field]['tmp_name'], "$tmp/upload.archive")) {
            throw new Exception('msg_upload_failed', ['move failed']);
        }
        $this->installFromArchive(
            "$tmp/upload.archive",
            $this->fileToBase($_FILES[$field]['name']),
        );
    }

    /**
     * Install extensions from an archive
     *
     * The archive is extracted to a temporary directory and then the contained extensions are installed.
     * This is is the ultimate installation procedure and all other install methods will end up here.
     *
     * @param string $archive the path to the archive
     * @param string $base the base directory name to use
     * @throws Exception
     */
    public function installFromArchive($archive, $base = null)
    {
        if ($base === null) $base = $this->fileToBase($archive);
        $target = $this->mkTmpDir() . '/' . $base;
        $this->extractArchive($archive, $target);
        $extensions = $this->findExtensions($target, $base);
        foreach ($extensions as $extension) {
            // check installation status
            if ($extension->isInstalled()) {
                if (!$this->overwrite) {
                    $this->processed[$extension->getId()] = self::STATUS_SKIPPED;
                    continue;
                }
                $status = self::STATUS_UPDATED;
            } else {
                $status = self::STATUS_INSTALLED;
            }

            // check PHP requirements
            $this->ensurePhpCompatibility($extension);

            // install dependencies first
            foreach ($extension->getDependencyList() as $id) {
                if (isset($this->processed[$id])) continue;
                if ($id == $extension->getId()) continue; // avoid circular dependencies
                $this->installFromId($id, true);
            }

            // now install the extension
            $this->dircopy(
                $extension->getCurrentDir(),
                $extension->getInstallDir()
            );
            $this->isDirty = true;
            $extension->getManager()->storeUpdate($this->sourceUrl);
            $this->removeDeletedFiles($extension);
            $this->processed[$extension->getId()] = $status;
        }

        $this->cleanUp();
    }

    /**
     * Uninstall an extension
     *
     * @param Extension $extension
     * @throws Exception
     */
    public function uninstall(Extension $extension)
    {
        // FIXME check if dependencies are still needed

        if (!$extension->isInstalled()) {
            throw new Exception('error_notinstalled', [$extension->getId()]);
        }

        if ($extension->isProtected()) {
            throw new Exception('error_uninstall_protected', [$extension->getId()]);
        }

        if (!io_rmdir($extension->getInstallDir(), true)) {
            throw new Exception('msg_delete_failed', [$extension->getId()]);
        }
        self::purgeCache();
    }

    /**
     * Download an archive to a protected path
     *
     * @param string $url The url to get the archive from
     * @return string The path where the archive was saved
     * @throws Exception
     */
    public function downloadArchive($url)
    {
        // check the url
        if (!preg_match('/https?:\/\//i', $url)) {
            throw new Exception('error_badurl');
        }

        // try to get the file from the path (used as plugin name fallback)
        $file = parse_url($url, PHP_URL_PATH);
        $file = $file ? PhpString::basename($file) : md5($url);

        // download
        $http = new DokuHTTPClient();
        $http->max_bodysize = 0;
        $http->timeout = 25; //max. 25 sec
        $http->keep_alive = false; // we do single ops here, no need for keep-alive
        $http->agent = 'DokuWiki HTTP Client (Extension Manager)';

        $data = $http->get($url);
        if ($data === false) throw new Exception('error_download', [$url, $http->error, $http->status]);

        // get filename from headers
        if (preg_match(
            '/attachment;\s*filename\s*=\s*"([^"]*)"/i',
            (string)($http->resp_headers['content-disposition'] ?? ''),
            $match
        )) {
            $file = PhpString::basename($match[1]);
        }

        // clean up filename
        $file = $this->fileToBase($file);

        // create tmp directory for download
        $tmp = $this->mkTmpDir();

        // save the file
        if (@file_put_contents("$tmp/$file", $data) === false) {
            throw new Exception('error_save');
        }

        return "$tmp/$file";
    }


    /**
     * Delete outdated files
     */
    public function removeDeletedFiles(Extension $extension)
    {
        $extensiondir = $extension->getInstallDir();
        $definitionfile = $extensiondir . '/deleted.files';
        if (!file_exists($definitionfile)) return;

        $list = file($definitionfile);
        foreach ($list as $line) {
            $line = trim(preg_replace('/#.*$/', '', $line));
            $line = str_replace('..', '', $line); // do not run out of the extension directory
            if (!$line) continue;

            $file = $extensiondir . '/' . $line;
            if (!file_exists($file)) continue;

            io_rmdir($file, true);
        }
    }

    /**
     * Purge all caches
     */
    public static function purgeCache()
    {
        // expire dokuwiki caches
        // touching local.php expires wiki page, JS and CSS caches
        global $config_cascade;
        @touch(reset($config_cascade['main']['local']));

        if (function_exists('opcache_reset')) {
            opcache_reset();
        }
    }

    /**
     * Get the list of processed extensions and their status during an installation run
     *
     * @return array id => status
     */
    public function getProcessed()
    {
        return $this->processed;
    }


    /**
     * Ensure that the given extension is compatible with the current PHP version
     *
     * Throws an exception if the extension is not compatible
     *
     * @param Extension $extension
     * @throws Exception
     */
    protected function ensurePhpCompatibility(Extension $extension)
    {
        $min = $extension->getMinimumPHPVersion();
        if ($min && version_compare(PHP_VERSION, $min, '<')) {
            throw new Exception('error_minphp', [$extension->getId(), $min, PHP_VERSION]);
        }

        $max = $extension->getMaximumPHPVersion();
        if ($max && version_compare(PHP_VERSION, $max, '>')) {
            throw new Exception('error_maxphp', [$extension->getId(), $max, PHP_VERSION]);
        }
    }


    /**
     * Get a base name from an archive name (we don't trust)
     *
     * @param string $file
     * @return string
     */
    protected function fileToBase($file)
    {
        $base = PhpString::basename($file);
        $base = preg_replace('/\.(tar\.gz|tar\.bz|tar\.bz2|tar|tgz|tbz|zip)$/', '', $base);
        return preg_replace('/\W+/', '', $base);
    }

    /**
     * Returns a temporary directory
     *
     * The directory is registered for cleanup when the class is destroyed
     *
     * @return string
     * @throws Exception
     */
    protected function mkTmpDir()
    {
        try {
            $dir = io_mktmpdir();
        } catch (\Exception $e) {
            throw new Exception('error_dircreate', [], $e);
        }
        if (!$dir) throw new Exception('error_dircreate');
        $this->temporary[] = $dir;
        return $dir;
    }

    /**
     * Find all extensions in a given directory
     *
     * This allows us to install extensions from archives that contain multiple extensions and
     * also caters for the fact that archives may or may not contain subdirectories for the extension(s).
     *
     * @param string $dir
     * @return Extension[]
     */
    protected function findExtensions($dir, $base = null)
    {
        // first check for plugin.info.txt or template.info.txt
        $extensions = [];
        $iterator = new RecursiveDirectoryIterator($dir);
        foreach (new RecursiveIteratorIterator($iterator) as $file) {
            if (
                $file->getFilename() === 'plugin.info.txt' ||
                $file->getFilename() === 'template.info.txt'
            ) {
                $extensions[] = Extension::createFromDirectory($file->getPath());
            }
        }
        if ($extensions) return $extensions;

        // still nothing? we assume this to be a single extension that is either
        // directly in the given directory or in single subdirectory
        $base = $base ?? PhpString::basename($dir);
        $files = glob($dir . '/*');
        if (count($files) === 1 && is_dir($files[0])) {
            $dir = $files[0];
        }
        return [Extension::createFromDirectory($dir, null, $base)];
    }

    /**
     * Extract the given archive to the given target directory
     *
     * Auto-guesses the archive type
     * @throws Exception
     */
    protected function extractArchive($archive, $target)
    {
        $fh = fopen($archive, 'rb');
        if (!$fh) throw new Exception('error_archive_read', [$archive]);
        $magic = fread($fh, 5);
        fclose($fh);

        if (strpos($magic, "\x50\x4b\x03\x04") === 0) {
            $archiver = new Zip();
        } else {
            $archiver = new Tar();
        }
        try {
            $archiver->open($archive);
            $archiver->extract($target);
        } catch (ArchiveIOException|ArchiveCorruptedException|ArchiveIllegalCompressionException $e) {
            throw new Exception('error_archive_extract', [$archive, $e->getMessage()], $e);
        }
    }

    /**
     * Copy with recursive sub-directory support
     *
     * @param string $src filename path to file
     * @param string $dst filename path to file
     * @throws Exception
     */
    protected function dircopy($src, $dst)
    {
        global $conf;

        if (is_dir($src)) {
            if (!$dh = @opendir($src)) {
                throw new Exception('error_copy_read', [$src]);
            }

            if (io_mkdir_p($dst)) {
                while (false !== ($f = readdir($dh))) {
                    if ($f == '..' || $f == '.') continue;
                    $this->dircopy("$src/$f", "$dst/$f");
                }
            } else {
                throw new Exception('error_copy_mkdir', [$dst]);
            }

            closedir($dh);
        } else {
            $existed = file_exists($dst);

            if (!@copy($src, $dst)) {
                throw new Exception('error_copy_copy', [$src, $dst]);
            }
            if (!$existed && $conf['fperm']) chmod($dst, $conf['fperm']);
            @touch($dst, filemtime($src));
        }
    }

    /**
     * Reset caches if needed
     */
    protected function cleanUp()
    {
        if ($this->isDirty) {
            self::purgeCache();
            $this->isDirty = false;
        }
    }
}