1<?php
2
3use dokuwiki\Extension\SyntaxPlugin;
4use FYKOS\dokuwiki\Extension\PluginNewsFeed\Model\ModelNews;
5use dokuwiki\Cache\Cache;
6
7/**
8 * Class syntax_plugin_newsfeed_feed
9 * @author Michal Červeňák <miso@fykos.cz>
10 */
11class syntax_plugin_newsfeed_feed extends SyntaxPlugin {
12
13    private helper_plugin_newsfeed $helper;
14
15    public function __construct() {
16        $this->helper = $this->loadHelper('newsfeed');
17    }
18
19    public function getType(): string {
20        return 'substition';
21    }
22
23    public function getPType(): string {
24        return 'block';
25    }
26
27    public function getAllowedTypes(): array {
28        return [];
29    }
30
31    public function getSort(): int {
32        return 24;
33    }
34
35    public function connectTo($mode): void {
36        $this->Lexer->addSpecialPattern('{{news-feed>.+?}}', $mode, 'plugin_newsfeed_feed');
37    }
38
39    public function handle($match, $state, $pos, Doku_Handler $handler): array {
40        preg_match_all('/([a-z-_]+)="([^".]*)"/', substr($match, 12, -2), $matches);
41        $parameters = [];
42        foreach ($matches[1] as $index => $match) {
43            $parameters[$match] = $matches[2][$index];
44        }
45        return [$state, $parameters];
46    }
47
48    public function render($format, Doku_Renderer $renderer, $data): bool {
49        if ($format !== 'xhtml') {
50            return true;
51        }
52
53        [$state, $param] = $data;
54        switch ($state) {
55            case DOKU_LEXER_SPECIAL:
56                $renderer->nocache();
57
58                $news = $this->helper->serviceNews->getById($param['id']);
59                if (is_null($news) || ($param['id'] == 0)) {
60                    $renderer->doc .= '<div class="alert alert-danger">' . $this->getLang('news_non_exist') .
61                        '</div>';
62                    return true;
63                }
64                $renderer->doc .= $this->getContent($news, $param);
65
66                return false;
67        }
68        return true;
69    }
70
71    /**
72     * @param $data ModelNews
73     * @param $params array
74     * @return string
75     */
76    private function getContent(ModelNews $data, array $params): string {
77        $f = $data->getCacheFile();
78        $cache = new Cache($f, '');
79        if ($cache->useCache()) {
80
81            $innerHtml = json_decode($cache->retrieveCache());
82        } else {
83            $innerHtml = $this->helper->renderer->renderContent($data, $params);
84
85            $cache->storeCache(json_encode($innerHtml));
86        }
87        $formHtml = $this->helper->renderer->renderEditFields($params);
88        return $this->helper->renderer->render($innerHtml, $formHtml, $data);
89    }
90}
91