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