1<?php
2
3/**
4 * DokuWiki Plugin linkfavicon (Renderer Component)
5 *
6 * @license GPL 2 http://www.gnu.org/licenses/gpl-2.0.html
7 * @author Shao Yanmin <shaoyan.alpha@gmail.com>
8 */
9class renderer_plugin_linkfavicon extends Doku_Renderer_xhtml
10{
11    function canRender($format) {
12        return ($format=='xhtml');
13    }
14
15    /**
16     * Render an external link
17     *
18     * @param string $url full URL with scheme
19     * @param string|array $name name for the link, array for media file
20     * @param bool $returnonly whether to return html or write to doc attribute
21     * @return void|string writes to doc attribute or returns html depends on $returnonly
22     */
23    public function externallink($url, $name = null, $returnonly = false)
24    {
25        $result = parent::externallink($url, $name, true);
26
27        // Presume that the result contains class="urlextern" when it's an external link
28        if (strpos($result, 'urlextern') !== false) {
29            $result = preg_replace('/(<a\s[^>]*class="[^"]*)"/', '$1 linkfavicon"', $result, 1);
30            $parsedUrl = parse_url($url);
31            $domain = $parsedUrl['host'];
32
33            $iconUrl = 'https://www.faviconextractor.com/favicon/' . $domain;
34            // $iconUrl = 'https://www.google.com/s2/favicons?domain=' . $domain . '&sz=16';
35            // $iconUrl = 'https://icons.duckduckgo.com/ip3/' . $domain . '.ico';
36
37            $result = preg_replace('/(<a\s[^>]*href="[^"]*")/', '$1 data-linkfavicon="' . $iconUrl . '"', $result, 1);
38        }
39
40        if ($returnonly) {
41            return $result;
42        } else {
43            $this->doc .= $result;
44        }
45    }
46}
47