1<?php
2
3/*
4 * This file is part of the clockoon/dokuwiki-commonmark-plugin package.
5 *
6 * (c) Sungbin Jeon <clockoon@gmail.com>
7 *
8 * Original code based on the followings:
9 * - CommonMark JS reference parser (https://bitly.com/commonmark-js) (c) John MacFarlane
10 * - league/commonmark (https://github.com/thephpleague/commonmark) (c) Colin O'Dell <colinodell@gmail.com>
11 *
12 * For the full copyright and license information, please view the LICENSE
13 * file that was distributed with this source code.
14 */
15
16namespace DokuWiki\Plugin\Commonmark\Extension\Renderer\Inline;
17
18use League\CommonMark\Renderer\NodeRendererInterface;
19use League\CommonMark\Renderer\ChildNodeRendererInterface;
20use League\CommonMark\Node\Node;
21use League\CommonMark\Extension\CommonMark\Node\Inline\Image;
22use League\Config\ConfigurationAwareInterface;
23use League\Config\ConfigurationInterface;
24
25use League\CommonMark\Util\RegexHelper;
26
27final class ImageRenderer implements NodeRendererInterface, ConfigurationAwareInterface
28{
29    /**
30     * @var ConfigurationInterface
31     */
32    protected $config;
33
34    /**
35     * @param Image                    $inline
36     * @param ChildNodeRendererInterface $DWRenderer
37     *
38     * @return string
39     */
40    public function render(Node $node, ChildNodeRendererInterface $DWRenderer): string
41    {
42        Image::assertInstanceOf($node);
43
44        $attrs = $node->data->get('attributes');
45
46        $forbidUnsafeLinks = !$this->config->get('allow_unsafe_links');
47        if ($forbidUnsafeLinks && RegexHelper::isLinkPotentiallyUnsafe($inline->getUrl())) {
48            $attrs['src'] = '';
49        } else {
50            $attrs['src'] = $node->getUrl();
51        }
52
53        $alt = $DWRenderer->renderNodes($node->children());
54        $alt = \preg_replace('/\<[^>]*alt="([^"]*)"[^>]*\>/', '$1', $alt);
55        $attrs['alt'] = \preg_replace('/\<[^>]*\>/', '', $alt);
56
57        if (isset($node->data['title'])) {
58            $attrs['title'] = $node->data['title'];
59        }
60
61        $result = '{{' . $attrs['src'];
62        $attrs['alt'] ? $result.= '|' . $attrs['alt'] . '}}' : $result.= '}}';
63
64        return $result;
65    }
66
67    public function setConfiguration(ConfigurationInterface $configuration): void
68    {
69        $this->config = $configuration;
70    }
71}
72