xref: /dokuwiki/lib/plugins/extension/GuiExtension.php (revision ccb7e6fcc548be15c1a71499a7bb16e4d9d08a13)
1<?php
2
3namespace dokuwiki\plugin\extension;
4
5class GuiExtension extends Gui
6{
7    public const THUMB_WIDTH = 120;
8    public const THUMB_HEIGHT = 70;
9
10
11    protected Extension $extension;
12
13    public function __construct(Extension $extension)
14    {
15        parent::__construct();
16        $this->extension = $extension;
17    }
18
19
20    public function render()
21    {
22
23        $classes = $this->getClasses();
24
25        $html = "<section class=\"$classes\" data-ext=\"{$this->extension->getId()}\">";
26
27        $html .= '<div class="screenshot">';
28        $html .= $this->thumbnail();
29        $html .= '<span class="id" title="' . hsc($this->extension->getBase()) . '">' .
30            hsc($this->extension->getBase()) . '</span>';
31        $html .= $this->popularity();
32        $html .= '</div>';
33
34        $html .= '<div class="main">';
35        $html .= $this->main();
36        $html .= '</div>';
37
38        $html .= '<div class="notices">';
39        $html .= $this->notices();
40        $html .= '</div>';
41
42        $html .= '<div class="details">';
43        $html .= $this->details();
44        $html .= '</div>';
45
46        $html .= '<div class="actions">';
47        // show the available update if there is one
48        if ($this->extension->isUpdateAvailable()) {
49            $html .= ' <div class="available">' . $this->getLang('available_version') . ' ' .
50                '<span class="version">' . hsc($this->extension->getLastUpdate()) . '</span></div>';
51        }
52
53        $html .= $this->actions();
54        $html .= '</div>';
55
56
57        $html .= '</section>';
58
59        return $html;
60    }
61
62    // region sections
63
64    /**
65     * Get the link and image tag for the screenshot/thumbnail
66     *
67     * @return string The HTML code
68     */
69    protected function thumbnail()
70    {
71        $screen = $this->extension->getScreenshotURL();
72        $thumb = $this->extension->getThumbnailURL();
73
74        $link = [];
75        $img = [
76            'width' => self::THUMB_WIDTH,
77            'height' => self::THUMB_HEIGHT,
78            'class' => 'shot',
79            'loading' => 'lazy',
80            'alt' => '',
81        ];
82
83        if ($screen && $this->isValidURL($screen)) {
84            $link = [
85                'href' => $screen,
86                'target' => '_blank',
87                'class' => 'extension_screenshot',
88                'title' => sprintf($this->getLang('screenshot'), $this->extension->getDisplayName())
89            ];
90
91            $img['src'] = $thumb;
92            $img['alt'] = $link['title'];
93        } elseif ($this->extension->isTemplate()) {
94            $img['src'] = DOKU_BASE . 'lib/plugins/extension/images/template.png';
95        } else {
96            $img['src'] = DOKU_BASE . 'lib/plugins/extension/images/plugin.png';
97        }
98
99        $html = '';
100        if ($link) $html .= '<a ' . buildAttributes($link) . '>';
101        $html .= '<img ' . buildAttributes($img) . ' />';
102        if ($link) $html .= '</a>';
103
104        return $html;
105    }
106
107    /**
108     * The main information about the extension
109     *
110     * @return string
111     */
112    protected function main()
113    {
114        $html = '';
115        $html .= '<h2>';
116        $html .= '<div>';
117        $html .= sprintf($this->getLang('extensionby'), hsc($this->extension->getDisplayName()), $this->author());
118        $html .= '</div>';
119
120        $html .= '<div class="version">';
121        if ($this->extension->isBundled()) {
122            $html .= hsc('<' . $this->getLang('status_bundled') . '>');
123        } elseif ($this->extension->getInstalledVersion()) {
124            $html .= hsc($this->extension->getInstalledVersion());
125        }
126        $html .= '</div>';
127        $html .= '</h2>';
128
129        $html .= '<p>' . hsc($this->extension->getDescription()) . '</p>';
130        $html .= $this->mainLinks();
131
132        return $html;
133    }
134
135    /**
136     * Display the available notices for the extension
137     *
138     * @return string
139     */
140    protected function notices()
141    {
142        $notices = Notice::list($this->extension);
143
144        $html = '<ul>';
145        foreach ($notices as $type => $messages) {
146            foreach ($messages as $message) {
147                $message = hsc($message);
148                $message = nl2br($message);
149                $message = preg_replace('/`([^`]+)`/', '<bdi>$1</bdi>', $message);
150                $message = sprintf(
151                    '<span class="icon">%s</span><span>%s</span>',
152                    inlineSVG(Notice::icon($type)),
153                    $message
154                );
155                $html .= '<li class="' . $type . '"><div class="li">' . $message . '</div></li>';
156            }
157        }
158        $html .= '</ul>';
159        return $html;
160    }
161
162    /**
163     * Generate the link bar HTML code
164     *
165     * @return string The HTML code
166     */
167    public function mainLinks()
168    {
169        $html = '<div class="linkbar">';
170
171
172        $params = $this->prepareLinkAttributes($this->extension->getURL(), 'homepage');
173        if ($params) {
174            $html .= ' <a ' . buildAttributes($params, true) . '>' . $this->getLang('homepage_link') . '</a>';
175        }
176
177        $params = $this->prepareLinkAttributes($this->extension->getBugtrackerURL(), 'bugs');
178        if ($params) {
179            $html .= ' <a ' . buildAttributes($params, true) . '>' . $this->getLang('bugs_features') . '</a>';
180        }
181
182        $params = $this->prepareLinkAttributes($this->extension->getDonationURL(), 'donate');
183        if ($params) {
184            $html .= ' <a ' . buildAttributes($params, true) . '>' . $this->getLang('donate_action') . '</a>';
185        }
186
187
188        $html .= '</div>';
189
190        return $html;
191    }
192
193    /**
194     * Create the details section
195     *
196     * @return string
197     */
198    protected function details()
199    {
200        $html = '<details>';
201        $html .= '<summary>' . $this->getLang('details') . '</summary>';
202
203
204        $default = $this->getLang('unknown');
205        $list = [];
206
207        if (!$this->extension->isBundled()) {
208            $list['downloadurl'] = $this->shortlink($this->extension->getDownloadURL(), 'download', $default);
209            $list['repository'] = $this->shortlink($this->extension->getSourcerepoURL(), 'repo', $default);
210        }
211
212        if ($this->extension->isInstalled()) {
213            if ($this->extension->isBundled()) {
214                $list['installed_version'] = $this->getLang('status_bundled');
215            } else {
216                if ($this->extension->getInstalledVersion()) {
217                    $list['installed_version'] = hsc($this->extension->getInstalledVersion());
218                }
219                if (!$this->extension->isBundled()) {
220                    $installDate = $this->extension->getManager()->getInstallDate();
221                    $list['installed'] = $installDate ? dformat($installDate->getTimestamp()) : $default;
222
223                    $updateDate = $this->extension->getManager()->getLastUpdate();
224                    $list['install_date'] = $updateDate ? dformat($updateDate->getTimestamp()) : $default;
225                }
226            }
227        }
228
229        if (!$this->extension->isInstalled() || $this->extension->isUpdateAvailable()) {
230            $list['available_version'] = $this->extension->getLastUpdate()
231                ? hsc($this->extension->getLastUpdate())
232                : $default;
233        }
234
235
236        if (!$this->extension->isBundled() && $this->extension->getCompatibleVersions()) {
237            $list['compatible'] = implode(', ', array_map(
238                static fn($date, $version) => '<bdi>' . hsc($version['label']) . ' (' . hsc($date) . ')</bdi>',
239                array_keys($this->extension->getCompatibleVersions()),
240                array_values($this->extension->getCompatibleVersions())
241            ));
242        }
243
244        $list['provides'] = implode(', ', array_map(hsc(...), $this->extension->getComponentTypes()));
245
246        $tags = $this->extension->getTags();
247        if ($tags) {
248            $list['tags'] = implode(', ', array_map(function ($tag) {
249                $url = $this->tabURL('search', ['q' => 'tag:' . $tag]);
250                return '<bdi><a href="' . $url . '">' . hsc($tag) . '</a></bdi>';
251            }, $tags));
252        }
253
254        if ($this->extension->getDependencyList()) {
255            $list['depends'] = $this->linkExtensions($this->extension->getDependencyList());
256        }
257
258        if ($this->extension->getSimilarList()) {
259            $list['similar'] = $this->linkExtensions($this->extension->getSimilarList());
260        }
261
262        if ($this->extension->getConflictList()) {
263            $list['conflicts'] = $this->linkExtensions($this->extension->getConflictList());
264        }
265
266        $html .= '<dl>';
267        foreach ($list as $key => $value) {
268            $html .= '<dt>' . rtrim($this->getLang($key), ':') . '</dt>';
269            $html .= '<dd>' . $value . '</dd>';
270        }
271        $html .= '</dl>';
272
273        $html .= '</details>';
274        return $html;
275    }
276
277    /**
278     * Generate a link to the author of the extension
279     *
280     * @return string The HTML code of the link
281     */
282    protected function author()
283    {
284        if (!$this->extension->getAuthor()) {
285            return '<em class="author">' . $this->getLang('unknown_author') . '</em>';
286        }
287
288        $names = explode(',', $this->extension->getAuthor());
289        $names = array_map(trim(...), $names);
290        if (count($names) > 2) {
291            $names = array_slice($names, 0, 2);
292            $names[] = '…';
293        }
294        $name = implode(', ', $names);
295
296        $mailid = $this->extension->getEmailID();
297        if ($mailid) {
298            $url = $this->tabURL('search', ['q' => 'authorid:' . $mailid]);
299            $html = '<a href="' . $url . '" class="author" title="' . $this->getLang('author_hint') . '" >' .
300                '<img src="//www.gravatar.com/avatar/' . hsc($mailid) .
301                '?s=60&amp;d=mm" width="20" height="20" alt="" /> ' .
302                hsc($name) . '</a>';
303        } else {
304            $html = '<span class="author">' . hsc($this->extension->getAuthor()) . '</span>';
305        }
306        return '<bdi>' . $html . '</bdi>';
307    }
308
309    /**
310     * The popularity bar
311     *
312     * @return string
313     */
314    protected function popularity()
315    {
316        $popularity = $this->extension->getPopularity();
317        if (!$popularity) return '';
318        if ($this->extension->isBundled()) return '';
319
320        $popimg = '<img src="' . DOKU_BASE . 'lib/plugins/extension/images/fire.svg" alt="��" />';
321
322        if ($popularity > 0.25) {
323            $title = $this->getLang('popularity_high');
324            $emoji = str_repeat($popimg, 3);
325        } elseif ($popularity > 0.15) {
326            $title = $this->getLang('popularity_medium');
327            $emoji = str_repeat($popimg, 2);
328        } elseif ($popularity > 0.05) {
329            $title = $this->getLang('popularity_low');
330            $emoji = str_repeat($popimg, 1);
331        } else {
332            return '';
333        }
334        $title .= ' (' . round($popularity * 100) . '%)';
335
336        return '<span class="popularity" title="' . $title . '">' . $emoji . '</span>';
337    }
338
339    /**
340     * Generate the action buttons
341     *
342     * @return string
343     */
344    protected function actions()
345    {
346        $html = '';
347        $actions = [];
348
349        // check permissions
350        try {
351            Installer::ensurePermissions($this->extension);
352        } catch (\Exception) {
353            return '';
354        }
355
356        // gather available actions
357        if ($this->extension->isInstalled()) {
358            if (!$this->extension->isProtected()) $actions[] = 'uninstall';
359            if ($this->extension->getDownloadURL()) {
360                $actions[] = $this->extension->isUpdateAvailable() ? 'update' : 'reinstall';
361            }
362            // no enable/disable for templates
363            if (!$this->extension->isProtected() && !$this->extension->isTemplate()) {
364                $actions[] = $this->extension->isEnabled() ? 'disable' : 'enable';
365            }
366        } elseif ($this->extension->getDownloadURL()) {
367            $actions[] = 'install';
368        }
369
370        // output the buttons
371        foreach ($actions as $action) {
372            $attr = [
373                'class' => 'button ' . $action,
374                'type' => 'submit',
375                'name' => 'fn[' . $action . '][' . $this->extension->getID() . ']',
376            ];
377            $html .= '<button ' . buildAttributes($attr) . '>' . $this->getLang('btn_' . $action) . '</button>';
378        }
379
380        return $html;
381    }
382
383
384    // endregion
385    // region utility functions
386
387    /**
388     * Create the classes representing the state of the extension
389     *
390     * @return string
391     */
392    protected function getClasses()
393    {
394        $classes = ['extension', $this->extension->getType()];
395        if ($this->extension->isInstalled()) $classes[] = 'installed';
396        if ($this->extension->isUpdateAvailable()) $classes[] = 'update';
397        $classes[] = $this->extension->isEnabled() ? 'enabled' : 'disabled';
398        return implode(' ', $classes);
399    }
400
401    /**
402     * Check whether the given URL is a safe http(s) URL
403     *
404     * Remote repository data must not be able to smuggle in other schemes
405     * such as javascript: which would execute in the admin's session.
406     *
407     * @param string $url The URL to check
408     * @return bool
409     */
410    protected function isValidURL($url)
411    {
412        return (bool)preg_match('#^https?://#i', (string)$url);
413    }
414
415    /**
416     * Create an attributes array for a link
417     *
418     * Handles interwiki links to dokuwiki.org
419     *
420     * @param string $url The URL to link to
421     * @param string $class Additional classes to add
422     * @return array Empty when the URL is missing or not a safe http(s) URL
423     */
424    protected function prepareLinkAttributes($url, $class)
425    {
426        global $conf;
427
428        if (!$this->isValidURL($url)) return [];
429
430        $attributes = [
431            'href' => $url,
432            'class' => 'urlextern',
433            'target' => $conf['target']['extern'],
434            'rel' => 'noopener',
435            'title' => $url,
436        ];
437
438        if ($conf['relnofollow']) {
439            $attributes['rel'] .= ' ugc nofollow';
440        }
441
442        if (preg_match('/^https?:\/\/(www\.)?dokuwiki\.org\//i', $url)) {
443            $attributes['class'] = 'interwiki iw_doku';
444            $attributes['target'] = $conf['target']['interwiki'];
445            $attributes['rel'] = '';
446        }
447
448        $attributes['class'] .= ' ' . $class;
449        return $attributes;
450    }
451
452    /**
453     * Create a link from the given URL
454     *
455     * Shortens the URL for display
456     *
457     * @param string $url
458     * @param string $class Additional classes to add
459     * @param string $fallback If URL is empty return this fallback (raw HTML)
460     * @return string  HTML link
461     */
462    protected function shortlink($url, $class, $fallback = '')
463    {
464        $params = $this->prepareLinkAttributes($url, $class);
465        if (!$params) return $fallback;
466
467        $link = parse_url($url);
468        $base = $link['host'];
469        if (!empty($link['port'])) $base .= $base . ':' . $link['port'];
470        $long = $link['path'];
471        if (!empty($link['query'])) $long .= $link['query'];
472
473        $name = shorten($base, $long, 55);
474
475        $html = '<a ' . buildAttributes($params, true) . '>' . hsc($name) . '</a>';
476        return $html;
477    }
478
479    /**
480     * Generate a list of links for extensions
481     *
482     * Links to the search tab with the extension name
483     *
484     * @param array $extensions The extension names
485     * @return string The HTML code
486     */
487    public function linkExtensions($extensions)
488    {
489        $html = '';
490        foreach ($extensions as $link) {
491            $html .= '<bdi><a href="' .
492                $this->tabURL('search', ['q' => 'ext:' . $link]) . '">' .
493                hsc($link) . '</a></bdi>, ';
494        }
495        return rtrim($html, ', ');
496    }
497
498    // endregion
499}
500