Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
0.00% covered (danger)
0.00%
0 / 194
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 / 194
0.00% covered (danger)
0.00%
0 / 4
870
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 / 155
0.00% covered (danger)
0.00%
0 / 1
702
 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
130        // TODO: Temporary fix for broken Markdown
131        $content = str_replace("\n", "\n\n", $content);
132        $content = str_replace("\n\n\n\n", "\n\n", $content);
133
134        // Markdown
135        $html_input = $format === 'forum' ? 'escape' : 'allow'; // TODO: Do NOT allow!
136        $teaser = $this->htmlUtils()->renderMarkdown($teaser, [
137            'html_input' => $html_input,
138        ]);
139        $content = $this->htmlUtils()->renderMarkdown($content, [
140            'html_input' => $html_input,
141        ]);
142
143        // Datei- & Bildpfade
144        $teaser = $news_entry->replaceImagePaths($teaser);
145        $teaser = $news_entry->replaceFilePaths($teaser);
146        $content = $news_entry->replaceImagePaths($content);
147        $content = $news_entry->replaceFilePaths($content);
148
149        $description = trim(strip_tags($teaser)) ?: trim(strip_tags($content));
150        $out = OlzHeader::render([
151            'back_link' => "{$code_href}news",
152            'title' => "{$title} - News",
153            'description' => $description,
154            'norobots' => $is_archived,
155            'canonical_url' => "{$code_href}news/{$id}",
156            'additional_headers' => [
157                $article_metadata,
158            ],
159        ]);
160
161        // TODO: Use array_find with PHP 8.4
162        $filtered = array_filter(
163            NewsUtils::ALL_FORMAT_OPTIONS,
164            fn ($entry) => $entry['ident'] === $format
165        );
166        // @phpstan-ignore-next-line
167        $found_entry = $filtered[array_keys($filtered)[0]];
168        $name = $found_entry['name'];
169        $icon = $found_entry['icon'] ?? null;
170        $icon_html = "<img src='{$code_href}assets/icns/{$icon}' alt='' class='format-icon'>";
171        $pretty_format = "{$icon_html}{$name}";
172
173        $pretty_date = $this->dateUtils()->olzDate("tt.mm.jjjj", $news_entry->getPublishedDate());
174        $author_user = $news_entry->getAuthorUser();
175        $author_role = $news_entry->getAuthorRole();
176        $author_name = $news_entry->getAuthorName();
177        $author_email = $news_entry->getAuthorEmail();
178        $pretty_author = OlzAuthorBadge::render([
179            'news_id' => $news_entry->getId() ?: 0,
180            'user' => $author_user,
181            'role' => $author_role,
182            'name' => $author_name,
183            'email' => $author_email,
184        ]);
185        $image_ids = $news_entry->getImageIds();
186        $num_images = count($image_ids);
187        $download_all_link = $this->authUtils()->hasPermission('any')
188            ? "<a href='{$code_href}news/{$id}/all.zip'>Alle herunterladen</a>" : '';
189
190        $out .= <<<ZZZZZZZZZZ
191            <div class='content-right'>
192                <div style='padding:4px 3px 10px 3px;'>
193                    <div id='format-info'><b>Format: </b>{$pretty_format}</div>
194                    <div><b>Datum: </b>{$pretty_date}</div>
195                    <div><b>Autor: </b>{$pretty_author}</div>
196                    <div><b>Anzahl Bilder: </b>{$num_images}</div>
197                    <div class='pretty'>{$download_all_link}</div>
198                </div>
199            </div>
200            <div class='content-middle'>
201            ZZZZZZZZZZ;
202
203        $db->query("UPDATE news SET `counter`=`counter` + 1 WHERE `id`='{$id}'");
204
205        $published_date = $news_entry->getPublishedDate();
206        $published_date = $this->dateUtils()->olzDate("tt.mm.jj", $published_date);
207
208        $is_owner = $user && intval($news_entry->getOwnerUser()?->getId() ?? 0) === intval($user->getId());
209        $has_all_permissions = $this->authUtils()->hasPermission('all');
210        $can_edit = $is_owner || $has_all_permissions;
211        $edit_admin = '';
212        if ($can_edit) {
213            $json_id = json_encode($id);
214            $has_blog = $this->authUtils()->hasPermission('kaderblog', $user);
215            $has_roles = !empty($this->authUtils()->getAuthenticatedRoles());
216            $json_mode = htmlentities(json_encode($has_roles ? ($has_blog ? 'account_with_all' : 'account_with_aktuell') : ($has_blog ? 'account_with_blog' : 'account')) ?: '');
217            $edit_admin = <<<ZZZZZZZZZZ
218                <div>
219                    <button
220                        id='edit-news-button'
221                        class='btn btn-primary'
222                        onclick='return olz.editNews({$json_id}{$json_mode})'
223                    >
224                        <img src='{$code_href}assets/icns/edit_white_16.svg' class='noborder' />
225                        Bearbeiten
226                    </button>
227                </div>
228                ZZZZZZZZZZ;
229        }
230
231        $out .= "<h1>{$edit_admin}{$title}</h1>";
232
233        $gallery = '';
234        $num_images = count($image_ids);
235        if ($num_images > 0) {
236            $gallery .= "<div class='lightgallery gallery-container'>";
237            foreach ($image_ids as $image_id) {
238                $gallery .= "<div class='gallery-image'>";
239                $gallery .= $this->imageUtils()->olzImage(
240                    'news',
241                    $id,
242                    $image_id,
243                    110,
244                    'gallery[myset]'
245                );
246                $gallery .= "</div>";
247            }
248            $gallery .= "</div>";
249        }
250
251        if ($format === 'aktuell') {
252            $out .= "<p><b>{$teaser}</b><p>{$content}</p><br/><br/>{$gallery}\n";
253        } elseif ($format === 'kaderblog') {
254            $out .= "<p>{$content}</p><br/><br/>{$gallery}\n";
255        } elseif ($format === 'forum') {
256            $out .= "<p><b>{$teaser}</b><p>{$content}</p><br/><br/>{$gallery}\n";
257        } elseif ($format === 'galerie') {
258            $out .= "<p>{$content}</p>{$gallery}\n";
259        } elseif ($format === 'video') {
260            $youtube_url = $news_entry->getExternalUrl() ?? '';
261            $res0 = preg_match("/^https\\:\\/\\/(www\\.)?youtu\\.be\\/([a-zA-Z0-9\\-\\_]{6,})/", $youtube_url, $matches0);
262            $res1 = preg_match("/^https\\:\\/\\/(www\\.)?youtube\\.com\\/watch\\?v\\=([a-zA-Z0-9\\-\\_]{6,})/", $youtube_url, $matches1);
263            $youtube_match = null;
264            if ($res0) {
265                $youtube_match = $matches0[2];
266            }
267            if ($res1) {
268                $youtube_match = $matches1[2];
269            }
270
271            $out .= "<div class='video-container'>";
272            $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";
273            if ($youtube_match != null) {
274                $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>";
275            } else {
276                $this->log()->error("Invalid YouTube link (ID:{$id}): {$youtube_url}");
277                $out .= "Fehlerhafter YouTube-Link!";
278            }
279            $out .= "<div style='background-image:url({$code_href}assets/icns/movie_dot.svg);background-repeat:repeat-x;margin:0px;padding:0px;height:24px;'></div>";
280            $out .= "</div>";
281        } else {
282            $out .= "<div class='lightgallery'><p><b>{$teaser}</b><p>{$content}</p></div>\n";
283        }
284        $out .= "</div>";
285
286        $out .= OlzFooter::render();
287
288        return $out;
289    }
290
291    protected function getNewsEntryById(int $id): ?NewsEntry {
292        $news_repo = $this->entityManager()->getRepository(NewsEntry::class);
293        return $news_repo->findOneBy([
294            'id' => $id,
295            'on_off' => 1,
296        ]);
297    }
298}