xref: /dokuwiki/lib/plugins/extension/Installer.php (revision 160d3688fe2b70ebe88d464cba3417440127a155)
1<?php
2
3namespace dokuwiki\plugin\extension;
4
5use dokuwiki\HTTP\DokuHTTPClient;
6use dokuwiki\Utf8\PhpString;
7use RecursiveDirectoryIterator;
8use RecursiveIteratorIterator;
9use splitbrain\PHPArchive\ArchiveCorruptedException;
10use splitbrain\PHPArchive\ArchiveIllegalCompressionException;
11use splitbrain\PHPArchive\ArchiveIOException;
12use splitbrain\PHPArchive\Tar;
13use splitbrain\PHPArchive\Zip;
14
15/**
16 * Install and deinstall extensions
17 *
18 * This manages all the file operations and downloads needed to install an extension.
19 */
20class Installer
21{
22    /** @var string[] a list of temporary directories used during this installation */
23    protected array $temporary = [];
24
25    /** @var bool if changes have been made that require a cache purge */
26    protected $isDirty = false;
27
28    /** @var bool Replace existing files? */
29    protected $overwrite = false;
30
31    /** @var string The last used URL to install an extension */
32    protected $sourceUrl = '';
33
34    protected $processed = [];
35
36    public const STATUS_SKIPPED = 'skipped';
37    public const STATUS_UPDATED = 'updated';
38    public const STATUS_INSTALLED = 'installed';
39
40
41    /**
42     * Initialize a new extension installer
43     *
44     * @param bool $overwrite
45     */
46    public function __construct($overwrite = false)
47    {
48        $this->overwrite = $overwrite;
49    }
50
51    /**
52     * Destructor
53     *
54     * deletes any dangling temporary directories
55     */
56    public function __destruct()
57    {
58        foreach ($this->temporary as $dir) {
59            io_rmdir($dir, true);
60        }
61        $this->cleanUp();
62    }
63
64    /**
65     * Install an extension by ID
66     *
67     * This will simply call installExtension after constructing an extension from the ID
68     *
69     * The $skipInstalled parameter should only be used when installing dependencies
70     *
71     * @param string $id the extension ID
72     * @param bool $skipInstalled Ignore the overwrite setting and skip installed extensions
73     * @throws Exception
74     */
75    public function installFromId($id, $skipInstalled = false)
76    {
77        $extension = Extension::createFromId($id);
78        if ($skipInstalled && $extension->isInstalled()) return;
79        $this->installExtension($extension);
80    }
81
82    /**
83     * Install an extension
84     *
85     * This will simply call installFromUrl() with the URL from the extension
86     *
87     * @param Extension $extension
88     * @throws Exception
89     */
90    public function installExtension(Extension $extension)
91    {
92        $url = $extension->getDownloadURL();
93        if (!$url) {
94            throw new Exception('error_nourl', [$extension->getId()]);
95        }
96        $this->installFromUrl($url);
97    }
98
99    /**
100     * Install extensions from a given URL
101     *
102     * @param string $url the URL to the archive
103     * @param null $base the base directory name to use
104     * @throws Exception
105     */
106    public function installFromUrl($url, $base = null)
107    {
108        $this->sourceUrl = $url;
109        $archive = $this->downloadArchive($url);
110        $this->installFromArchive(
111            $archive,
112            $base
113        );
114    }
115
116    /**
117     * Install extensions from a user upload
118     *
119     * @param string $field name of the upload file
120     * @throws Exception
121     */
122    public function installFromUpload($field)
123    {
124        $this->sourceUrl = '';
125        if ($_FILES[$field]['error']) {
126            throw new Exception('msg_upload_failed', [$_FILES[$field]['error']]);
127        }
128
129        $tmp = $this->mkTmpDir();
130        if (!move_uploaded_file($_FILES[$field]['tmp_name'], "$tmp/upload.archive")) {
131            throw new Exception('msg_upload_failed', ['move failed']);
132        }
133        $this->installFromArchive(
134            "$tmp/upload.archive",
135            $this->fileToBase($_FILES[$field]['name']),
136        );
137    }
138
139    /**
140     * Install extensions from an archive
141     *
142     * The archive is extracted to a temporary directory and then the contained extensions are installed.
143     * This is is the ultimate installation procedure and all other install methods will end up here.
144     *
145     * @param string $archive the path to the archive
146     * @param string $base the base directory name to use
147     * @throws Exception
148     */
149    public function installFromArchive($archive, $base = null)
150    {
151        if ($base === null) $base = $this->fileToBase($archive);
152        $target = $this->mkTmpDir() . '/' . $base;
153        $this->extractArchive($archive, $target);
154        $extensions = $this->findExtensions($target, $base);
155        foreach ($extensions as $extension) {
156            // check installation status
157            if ($extension->isInstalled()) {
158                if (!$this->overwrite) {
159                    $this->processed[$extension->getId()] = self::STATUS_SKIPPED;
160                    continue;
161                }
162                $status = self::STATUS_UPDATED;
163            } else {
164                $status = self::STATUS_INSTALLED;
165            }
166
167            // FIXME check PHP requirements
168
169            // install dependencies first
170            foreach ($extension->getDependencyList() as $id) {
171                if (isset($this->processed[$id])) continue;
172                if ($id == $extension->getId()) continue; // avoid circular dependencies
173                $this->installFromId($id, true);
174            }
175
176            // now install the extension
177            $this->dircopy(
178                $extension->getCurrentDir(),
179                $extension->getInstallDir()
180            );
181            $this->isDirty = true;
182            $extension->getManager()->storeUpdate($this->sourceUrl);
183            $this->removeDeletedFiles($extension);
184            $this->processed[$extension->getId()] = $status;
185        }
186
187        $this->cleanUp();
188    }
189
190    /**
191     * Uninstall an extension
192     *
193     * @param Extension $extension
194     * @throws Exception
195     */
196    public function uninstall(Extension $extension)
197    {
198        // FIXME check if dependencies are still needed
199
200        if (!$extension->isInstalled()) {
201            throw new Exception('error_notinstalled', [$extension->getId()]);
202        }
203
204        if ($extension->isProtected()) {
205            throw new Exception('error_uninstall_protected', [$extension->getId()]);
206        }
207
208        if (!io_rmdir($extension->getInstallDir(), true)) {
209            throw new Exception('msg_delete_failed', [$extension->getId()]);
210        }
211        self::purgeCache();
212    }
213
214    /**
215     * Download an archive to a protected path
216     *
217     * @param string $url The url to get the archive from
218     * @return string The path where the archive was saved
219     * @throws Exception
220     */
221    public function downloadArchive($url)
222    {
223        // check the url
224        if (!preg_match('/https?:\/\//i', $url)) {
225            throw new Exception('error_badurl');
226        }
227
228        // try to get the file from the path (used as plugin name fallback)
229        $file = parse_url($url, PHP_URL_PATH);
230        $file = $file ? PhpString::basename($file) : md5($url);
231
232        // download
233        $http = new DokuHTTPClient();
234        $http->max_bodysize = 0;
235        $http->timeout = 25; //max. 25 sec
236        $http->keep_alive = false; // we do single ops here, no need for keep-alive
237        $http->agent = 'DokuWiki HTTP Client (Extension Manager)';
238
239        $data = $http->get($url);
240        if ($data === false) throw new Exception('error_download', [$url, $http->error, $http->status]);
241
242        // get filename from headers
243        if (preg_match(
244            '/attachment;\s*filename\s*=\s*"([^"]*)"/i',
245            (string)($http->resp_headers['content-disposition'] ?? ''),
246            $match
247        )) {
248            $file = PhpString::basename($match[1]);
249        }
250
251        // clean up filename
252        $file = $this->fileToBase($file);
253
254        // create tmp directory for download
255        $tmp = $this->mkTmpDir();
256
257        // save the file
258        if (@file_put_contents("$tmp/$file", $data) === false) {
259            throw new Exception('error_save');
260        }
261
262        return "$tmp/$file";
263    }
264
265
266    /**
267     * Delete outdated files
268     */
269    public function removeDeletedFiles(Extension $extension)
270    {
271        $extensiondir = $extension->getInstallDir();
272        $definitionfile = $extensiondir . '/deleted.files';
273        if (!file_exists($definitionfile)) return;
274
275        $list = file($definitionfile);
276        foreach ($list as $line) {
277            $line = trim(preg_replace('/#.*$/', '', $line));
278            $line = str_replace('..', '', $line); // do not run out of the extension directory
279            if (!$line) continue;
280
281            $file = $extensiondir . '/' . $line;
282            if (!file_exists($file)) continue;
283
284            io_rmdir($file, true);
285        }
286    }
287
288    /**
289     * Purge all caches
290     */
291    public static function purgeCache()
292    {
293        // expire dokuwiki caches
294        // touching local.php expires wiki page, JS and CSS caches
295        global $config_cascade;
296        @touch(reset($config_cascade['main']['local']));
297
298        if (function_exists('opcache_reset')) {
299            opcache_reset();
300        }
301    }
302
303    /**
304     * Get the list of processed extensions and their status during an installation run
305     *
306     * @return array id => status
307     */
308    public function getProcessed()
309    {
310        return $this->processed;
311    }
312
313    /**
314     * Get a base name from an archive name (we don't trust)
315     *
316     * @param string $file
317     * @return string
318     */
319    protected function fileToBase($file)
320    {
321        $base = PhpString::basename($file);
322        $base = preg_replace('/\.(tar\.gz|tar\.bz|tar\.bz2|tar|tgz|tbz|zip)$/', '', $base);
323        return preg_replace('/\W+/', '', $base);
324    }
325
326    /**
327     * Returns a temporary directory
328     *
329     * The directory is registered for cleanup when the class is destroyed
330     *
331     * @return string
332     * @throws Exception
333     */
334    protected function mkTmpDir()
335    {
336        try {
337            $dir = io_mktmpdir();
338        } catch (\Exception $e) {
339            throw new Exception('error_dircreate', [], $e);
340        }
341        if (!$dir) throw new Exception('error_dircreate');
342        $this->temporary[] = $dir;
343        return $dir;
344    }
345
346    /**
347     * Find all extensions in a given directory
348     *
349     * This allows us to install extensions from archives that contain multiple extensions and
350     * also caters for the fact that archives may or may not contain subdirectories for the extension(s).
351     *
352     * @param string $dir
353     * @return Extension[]
354     */
355    protected function findExtensions($dir, $base = null)
356    {
357        // first check for plugin.info.txt or template.info.txt
358        $extensions = [];
359        $iterator = new RecursiveDirectoryIterator($dir);
360        foreach (new RecursiveIteratorIterator($iterator) as $file) {
361            if (
362                $file->getFilename() === 'plugin.info.txt' ||
363                $file->getFilename() === 'template.info.txt'
364            ) {
365                $extensions[] = Extension::createFromDirectory($file->getPath());
366            }
367        }
368        if ($extensions) return $extensions;
369
370        // still nothing? we assume this to be a single extension that is either
371        // directly in the given directory or in single subdirectory
372        $base = $base ?? PhpString::basename($dir);
373        $files = glob($dir . '/*');
374        if (count($files) === 1 && is_dir($files[0])) {
375            $dir = $files[0];
376        }
377        return [Extension::createFromDirectory($dir, null, $base)];
378    }
379
380    /**
381     * Extract the given archive to the given target directory
382     *
383     * Auto-guesses the archive type
384     * @throws Exception
385     */
386    protected function extractArchive($archive, $target)
387    {
388        $fh = fopen($archive, 'rb');
389        if (!$fh) throw new Exception('error_archive_read', [$archive]);
390        $magic = fread($fh, 5);
391        fclose($fh);
392
393        if (strpos($magic, "\x50\x4b\x03\x04") === 0) {
394            $archiver = new Zip();
395        } else {
396            $archiver = new Tar();
397        }
398        try {
399            $archiver->open($archive);
400            $archiver->extract($target);
401        } catch (ArchiveIOException|ArchiveCorruptedException|ArchiveIllegalCompressionException $e) {
402            throw new Exception('error_archive_extract', [$archive, $e->getMessage()], $e);
403        }
404    }
405
406    /**
407     * Copy with recursive sub-directory support
408     *
409     * @param string $src filename path to file
410     * @param string $dst filename path to file
411     * @throws Exception
412     */
413    protected function dircopy($src, $dst)
414    {
415        global $conf;
416
417        if (is_dir($src)) {
418            if (!$dh = @opendir($src)) {
419                throw new Exception('error_copy_read', [$src]);
420            }
421
422            if (io_mkdir_p($dst)) {
423                while (false !== ($f = readdir($dh))) {
424                    if ($f == '..' || $f == '.') continue;
425                    $this->dircopy("$src/$f", "$dst/$f");
426                }
427            } else {
428                throw new Exception('error_copy_mkdir', [$dst]);
429            }
430
431            closedir($dh);
432        } else {
433            $existed = file_exists($dst);
434
435            if (!@copy($src, $dst)) {
436                throw new Exception('error_copy_copy', [$src, $dst]);
437            }
438            if (!$existed && $conf['fperm']) chmod($dst, $conf['fperm']);
439            @touch($dst, filemtime($src));
440        }
441    }
442
443    /**
444     * Reset caches if needed
445     */
446    protected function cleanUp()
447    {
448        if ($this->isDirty) {
449            self::purgeCache();
450            $this->isDirty = false;
451        }
452    }
453}
454