1<?php
2
3namespace dokuwiki\plugin\prosemirror\parser;
4
5use dokuwiki\File\PageResolver;
6
7class InternalLinkNode extends LinkNode
8{
9    public function toSyntax()
10    {
11        return $this->getDefaultLinkSyntax($this->attrs['data-inner']);
12    }
13
14    public static function render(\renderer_plugin_prosemirror $renderer, $originalId, $name)
15    {
16        global $ID;
17        $additionalAttributes = [];
18
19        $resolvedAttributes = self::resolveLink($originalId, $ID);
20        $additionalAttributes['data-resolvedTitle'] = $resolvedAttributes['id'];
21        $additionalAttributes['data-resolvedID'] = $resolvedAttributes['id'];
22        if (!is_array($name)) {
23            $additionalAttributes['data-resolvedName'] = $name ?: $resolvedAttributes['heading'];
24            if ($resolvedAttributes['exists']) {
25                $class = 'wikilink1';
26            } else {
27                $class = 'wikilink2';
28            }
29            $additionalAttributes['data-resolvedClass'] = $class;
30        }
31
32        self::renderToJSON(
33            $renderer,
34            'internallink',
35            $originalId,
36            $name,
37            $additionalAttributes
38        );
39    }
40
41    public static function resolveLink($inner, $curId)
42    {
43        $params = '';
44        $parts = explode('?', $inner, 2);
45        $resolvedPageId = $parts[0];
46        if (count($parts) === 2) {
47            $params = $parts[1];
48        }
49        $xhtml_renderer = p_get_renderer('xhtml');
50        $default = $xhtml_renderer->_simpleTitle($parts[0]);
51        $resolver = new PageResolver($curId);
52        $resolvedPageId = $resolver->resolveId($resolvedPageId);
53
54        if (useHeading('content')) {
55            $heading = p_get_first_heading($resolvedPageId);
56        }
57        if (empty($heading)) {
58            $heading = $default;
59        }
60
61        $url = wl($resolvedPageId, $params);
62
63        return [
64            'id' => $resolvedPageId,
65            'exists' => page_exists($resolvedPageId),
66            'heading' => $heading,
67            'url' => $url,
68        ];
69    }
70
71    protected static function getLinkTitle($title, $default, $id)
72    {
73        if (null === $title || trim($title) == '') {
74            if (useHeading('content') && $id) {
75                $heading = p_get_first_heading($id);
76                if (!blank($heading)) {
77                    return hsc($heading);
78                }
79            }
80            return hsc($default);
81        }
82        return hsc($title);
83    }
84}
85