Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
0.00% covered (danger)
0.00%
0 / 195
0.00% covered (danger)
0.00%
0 / 4
CRAP
0.00% covered (danger)
0.00%
0 / 1
OlzNewsDetailParams
n/a
0 / 0
n/a
0 / 0
0
n/a
0 / 0
OlzNewsDetail
0.00% covered (danger)
0.00%
0 / 195
0.00% covered (danger)
0.00%
0 / 4
930
0.00% covered (danger)
0.00%
0 / 1
 hasAccess
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 searchSqlWhenHasAccess
0.00% covered (danger)
0.00%
0 / 33
0.00% covered (danger)
0.00%
0 / 1
2
 getHtmlWhenHasAccess
0.00% covered (danger)
0.00%
0 / 156
0.00% covered (danger)
0.00%
0 / 1
756
 getNewsEntryById
0.00% covered (danger)
0.00%
0 / 5
0.00% covered (danger)
0.00%
0 / 1
2
1<?php
2
3// =============================================================================
4// Alle Neuigkeiten rund um die OL Zimmerberg
5// =============================================================================
6
7namespace Olz\News\Components\OlzNewsDetail;
8
9use Doctrine\Common\Collections\Criteria;
10use Olz\Components\Common\OlzRootComponent;
11use Olz\Components\Page\OlzFooter\OlzFooter;
12use Olz\Components\Page\OlzHeader\OlzHeader;
13use Olz\Entity\News\NewsEntry;
14use Olz\News\Components\OlzArticleMetadata\OlzArticleMetadata;
15use Olz\News\Components\OlzAuthorBadge\OlzAuthorBadge;
16use Olz\News\Utils\NewsUtils;
17use Olz\Utils\HttpParams;
18
19/** @extends HttpParams<array{von?: ?string}> */
20class OlzNewsDetailParams extends HttpParams {
21}
22
23/** @extends OlzRootComponent<array<string, mixed>> */
24class OlzNewsDetail extends OlzRootComponent {
25    public function hasAccess(): bool {
26        return true;
27    }
28
29    public function searchSqlWhenHasAccess(array $terms): string|array|null {
30        $code_href = $this->envUtils()->getCodeHref();
31        $today_iso = $this->dateUtils()->getIsoToday();
32        $db = $this->dbUtils()->getDb();
33        $pretty_format_sql = "CASE ".implode('', array_map(function ($entry) use ($db) {
34            $esc_ident = $db->real_escape_string($entry['ident']);
35            $esc_name = $db->real_escape_string($entry['name']);
36            return "WHEN format = '{$esc_ident}' THEN '{$esc_name}'";
37        }, NewsUtils::ALL_FORMAT_OPTIONS))." ELSE format END";
38        $where = implode(' AND ', array_map(function ($term) {
39            $date_sql = $this->searchUtils()->getDateSql('published_date', $term) ?? '0';
40            return <<<ZZZZZZZZZZ
41                (
42                    title LIKE '%{$term}%'
43                    OR teaser LIKE '%{$term}%'
44                    OR content LIKE '%{$term}%'
45                    OR {$date_sql}
46                )
47                ZZZZZZZZZZ;
48        }, $terms));
49        return [
50            'with' => [
51                <<<ZZZZZZZZZZ
52                    base_news AS (
53                        SELECT
54                            CONCAT('{$code_href}news/', id) AS link,
55                            CONCAT('{$code_href}assets/icns/entry_type_', format, '_20.svg') AS icon,
56                            published_date AS date,
57                            CONCAT('News (', {$pretty_format_sql}, '): ', title) AS title,
58                            CONCAT(IFNULL(teaser, ''), ' ', IFNULL(content, '')) AS text,
59                            DATEDIFF(published_date, '{$today_iso}') AS diffdays
60                        FROM news
61                        WHERE
62                            on_off = '1'
63                            AND {$this->newsUtils()->getIsNotArchivedSql()}
64                            AND {$where}
65                    )
66                    ZZZZZZZZZZ,
67            ],
68            'query' => <<<'ZZZZZZZZZZ'
69                    SELECT
70                        link, icon, date, title, text,
71                        CASE
72                            WHEN diffdays < -400 THEN 0.7
73                            WHEN diffdays < -100 THEN 1.0 + (diffdays + 100) * 0.3 / 300.0
74                            WHEN diffdays < 100 THEN 1.0
75                            ELSE 0.1
76                        END AS time_relevance
77                    FROM base_news
78                ZZZZZZZZZZ,
79        ];
80    }
81
82    public function getHtmlWhenHasAccess(mixed $args): string {
83        $this->httpUtils()->validateGetParams(OlzNewsDetailParams::class);
84        $code_href = $this->envUtils()->getCodeHref();
85        $db = $this->dbUtils()->getDb();
86        $entityManager = $this->dbUtils()->getEntityManager();
87        $user = $this->authUtils()->getCurrentUser();
88        $id = $args['id'] ?? null;
89
90        $news_repo = $entityManager->getRepository(NewsEntry::class);
91        $is_not_archived = $this->newsUtils()->getIsNotArchivedCriteria();
92        $criteria = Criteria::create()
93            ->where(Criteria::expr()->andX(
94                $is_not_archived,
95                Criteria::expr()->eq('id', $id),
96                Criteria::expr()->eq('on_off', 1),
97            ))
98            ->setFirstResult(0)
99            ->setMaxResults(1)
100        ;
101        $news_entries = $news_repo->matching($criteria);
102        $num_news_entries = $news_entries->count();
103        $is_archived = $num_news_entries !== 1;
104
105        if ($is_archived && !$this->authUtils()->hasPermission('any')) {
106            $this->httpUtils()->dieWithHttpError(404);
107            throw new \Exception('should already have failed');
108        }
109
110        $article_metadata = "";
111        try {
112            $article_metadata = OlzArticleMetadata::render(['id' => $id]);
113        } catch (\Exception $exc) {
114            $this->httpUtils()->dieWithHttpError(404);
115            throw new \Exception('should already have failed');
116        }
117
118        $news_entry = $this->getNewsEntryById($id);
119
120        if (!$news_entry) {
121            $this->httpUtils()->dieWithHttpError(404);
122            throw new \Exception('should already have failed');
123        }
124
125        $format = $news_entry->getFormat();
126        $title = $news_entry->getTitle();
127        $teaser = $news_entry->getTeaser() ?? '';
128        $content = $news_entry->getContent() ?? '';
129        $published_date = $news_entry->getPublishedDate();
130
131        // Markdown
132        // TODO: Do NOT ever allow!
133        $html_input = ($format === 'forum' || $published_date->format('Y') > '2020')
134            ? 'escape' : 'allow';
135        $teaser = $this->htmlUtils()->renderMarkdown($teaser, [
136            'html_input' => $html_input,
137        ]);
138        $content = $this->htmlUtils()->renderMarkdown($content, [
139            'html_input' => $html_input,
140        ]);
141
142        // Datei- & Bildpfade
143        $teaser = $news_entry->replaceImagePaths($teaser);
144        $teaser = $news_entry->replaceFilePaths($teaser);
145        $content = $news_entry->replaceImagePaths($content);
146        $content = $news_entry->replaceFilePaths($content);
147
148        $description = trim(strip_tags($teaser)) ?: trim(strip_tags($content));
149        $out = OlzHeader::render([
150            'back_link' => "{$code_href}news",
151            'title' => "{$title} - News",
152            'description' => $description,
153            'norobots' => $is_archived,
154            'canonical_url' => "{$code_href}news/{$id}",
155            'additional_headers' => [
156                $article_metadata,
157            ],
158        ]);
159
160        $found_entry = array_find(
161            NewsUtils::ALL_FORMAT_OPTIONS,
162            fn ($entry) => $entry['ident'] === $format,
163        );
164        $this->generalUtils()->checkNotNull($found_entry, "No such format: {$format}");
165        $name = $found_entry['name'];
166        $icon = $found_entry['icon'] ?? null;
167        $icon_html = "<img src='{$code_href}assets/icns/{$icon}' alt='' class='format-icon'>";
168        $pretty_format = "{$icon_html}{$name}";
169
170        $pretty_date = $this->dateUtils()->olzDate("tt.mm.jjjj", $news_entry->getPublishedDate());
171        $author_user = $news_entry->getAuthorUser();
172        $author_role = $news_entry->getAuthorRole();
173        $author_name = $news_entry->getAuthorName();
174        $author_email = $news_entry->getAuthorEmail();
175        $pretty_author = OlzAuthorBadge::render([
176            'news_id' => $news_entry->getId() ?: 0,
177            'user' => $author_user,
178            'role' => $author_role,
179            'name' => $author_name,
180            'email' => $author_email,
181        ]);
182        $image_ids = $news_entry->getImageIds();
183        $num_images = count($image_ids);
184        $download_all_link = $this->authUtils()->hasPermission('any')
185            ? "<a href='{$code_href}news/{$id}/all.zip'>Alle herunterladen</a>" : '';
186
187        $out .= <<<ZZZZZZZZZZ
188            <div class='content-right'>
189                <div style='padding:4px 3px 10px 3px;'>
190                    <div id='format-info'><b>Format: </b>{$pretty_format}</div>
191                    <div><b>Datum: </b>{$pretty_date}</div>
192                    <div><b>Autor: </b>{$pretty_author}</div>
193                    <div><b>Anzahl Bilder: </b>{$num_images}</div>
194                    <div class='pretty'>{$download_all_link}</div>
195                </div>
196            </div>
197            <div class='content-middle'>
198            ZZZZZZZZZZ;
199
200        $db->query("UPDATE news SET `counter`=`counter` + 1 WHERE `id`='{$id}'");
201
202        $published_date = $this->dateUtils()->olzDate("tt.mm.jj", $published_date);
203
204        $is_owner = $user && intval($news_entry->getOwnerUser()?->getId() ?? 0) === intval($user->getId());
205        $has_all_permissions = $this->authUtils()->hasPermission('all');
206        $can_edit = $is_owner || $has_all_permissions;
207        $edit_admin = '';
208        if ($can_edit) {
209            $json_id = json_encode($id);
210            $has_blog = $this->authUtils()->hasPermission('kaderblog', $user);
211            $has_roles = !empty($this->authUtils()->getAuthenticatedRoles());
212            $json_mode = htmlentities(json_encode($has_roles ? ($has_blog ? 'account_with_all' : 'account_with_aktuell') : ($has_blog ? 'account_with_blog' : 'account')) ?: '');
213            $edit_admin = <<<ZZZZZZZZZZ
214                <div>
215                    <button
216                        id='edit-news-button'
217                        class='btn btn-primary'
218                        onclick='return olz.editNews({$json_id}{$json_mode})'
219                    >
220                        <img src='{$code_href}assets/icns/edit_white_16.svg' class='noborder' />
221                        Bearbeiten
222                    </button>
223                </div>
224                ZZZZZZZZZZ;
225        }
226
227        $out .= "<h1>{$edit_admin}{$title}</h1>";
228
229        $gallery = '';
230        $num_images = count($image_ids);
231        if ($num_images > 0) {
232            $gallery .= "<div class='lightgallery gallery-container'>";
233            foreach ($image_ids as $image_id) {
234                $gallery .= "<div class='gallery-image'>";
235                $gallery .= $this->imageUtils()->olzImage(
236                    'news',
237                    $id,
238                    $image_id,
239                    128,
240                    'gallery[myset]'
241                );
242                $gallery .= "</div>";
243            }
244            $gallery .= "</div>";
245        }
246
247        if ($format === 'aktuell') {
248            $out .= "<p><b>{$teaser}</b><p>{$content}</p><br/><br/>{$gallery}\n";
249        } elseif ($format === 'kaderblog') {
250            $out .= "<p>{$content}</p><br/><br/>{$gallery}\n";
251        } elseif ($format === 'forum') {
252            $out .= "<p><b>{$teaser}</b><p>{$content}</p><br/><br/>{$gallery}\n";
253        } elseif ($format === 'galerie') {
254            $out .= "<p>{$content}</p>{$gallery}\n";
255        } elseif ($format === 'video') {
256            $youtube_url = $news_entry->getExternalUrl() ?? '';
257            $res0 = preg_match("/^https\\:\\/\\/(www\\.)?youtu\\.be\\/([a-zA-Z0-9\\-\\_]{6,})/", $youtube_url, $matches0);
258            $res1 = preg_match("/^https\\:\\/\\/(www\\.)?youtube\\.com\\/watch\\?v\\=([a-zA-Z0-9\\-\\_]{6,})/", $youtube_url, $matches1);
259            $youtube_match = null;
260            if ($res0) {
261                $youtube_match = $matches0[2];
262            }
263            if ($res1) {
264                $youtube_match = $matches1[2];
265            }
266
267            $out .= "<div class='video-container'>";
268            $out .= "<div style='background-image:url({$code_href}assets/icns/movie_dot.svg);background-repeat:repeat-x;margin:0px;padding:0px;height:24px;'></div>\n";
269            if ($youtube_match != null) {
270                $out .= "<iframe width='560' height='315' src='https://www.youtube.com/embed/{$youtube_match}' frameborder='0' allow='accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture' allowfullscreen></iframe>";
271            } else {
272                $this->log()->error("Invalid YouTube link (ID:{$id}): {$youtube_url}");
273                $out .= "Fehlerhafter YouTube-Link!";
274            }
275            $out .= "<div style='background-image:url({$code_href}assets/icns/movie_dot.svg);background-repeat:repeat-x;margin:0px;padding:0px;height:24px;'></div>";
276            $out .= "</div>";
277        } else {
278            $out .= "<div class='lightgallery'><p><b>{$teaser}</b><p>{$content}</p></div>\n";
279        }
280
281        // Reactions
282        $json_id = json_encode($id);
283        $out .= "<div id='news-reactions'></div><script>olz.initNewsReactions({$json_id});</script>";
284
285        $out .= "</div>"; // content-middle
286
287        $out .= OlzFooter::render();
288
289        return $out;
290    }
291
292    protected function getNewsEntryById(int $id): ?NewsEntry {
293        $news_repo = $this->entityManager()->getRepository(NewsEntry::class);
294        return $news_repo->findOneBy([
295            'id' => $id,
296            'on_off' => 1,
297        ]);
298    }
299}