Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
0.00% covered (danger)
0.00%
0 / 175
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 / 175
0.00% covered (danger)
0.00%
0 / 4
992
0.00% covered (danger)
0.00%
0 / 1
 getSearchTitle
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 getSearchResults
0.00% covered (danger)
0.00%
0 / 14
0.00% covered (danger)
0.00%
0 / 1
20
 getHtml
0.00% covered (danger)
0.00%
0 / 155
0.00% covered (danger)
0.00%
0 / 1
650
 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 getSearchTitle(): string {
26        return 'News';
27    }
28
29    public function getSearchResults(array $terms): array {
30        $results = [];
31        $code_href = $this->envUtils()->getCodeHref();
32        $news_repo = $this->entityManager()->getRepository(NewsEntry::class);
33        $news = $news_repo->search($terms);
34        foreach ($news as $news_entry) {
35            $id = $news_entry->getId();
36            $results[] = $this->searchUtils()->getScoredSearchResult([
37                'link' => "{$code_href}news/{$id}",
38                'icon' => $this->newsUtils()->getNewsFormatIcon($news_entry) ?: null,
39                'date' => $news_entry->getPublishedDate(),
40                'title' => $news_entry->getTitle() ?: '?',
41                'text' => $news_entry->getTeaser()." ".$news_entry->getContent(),
42            ], $terms);
43        }
44        return $results;
45    }
46
47    public function getHtml(mixed $args): string {
48        $this->httpUtils()->validateGetParams(OlzNewsDetailParams::class);
49        $code_href = $this->envUtils()->getCodeHref();
50        $db = $this->dbUtils()->getDb();
51        $entityManager = $this->dbUtils()->getEntityManager();
52        $user = $this->authUtils()->getCurrentUser();
53        $id = $args['id'] ?? null;
54
55        $news_repo = $entityManager->getRepository(NewsEntry::class);
56        $is_not_archived = $this->newsUtils()->getIsNotArchivedCriteria();
57        $criteria = Criteria::create()
58            ->where(Criteria::expr()->andX(
59                $is_not_archived,
60                Criteria::expr()->eq('id', $id),
61                Criteria::expr()->eq('on_off', 1),
62            ))
63            ->setFirstResult(0)
64            ->setMaxResults(1)
65        ;
66        $news_entries = $news_repo->matching($criteria);
67        $num_news_entries = $news_entries->count();
68        $is_archived = $num_news_entries !== 1;
69
70        if ($is_archived && !$this->authUtils()->hasPermission('any')) {
71            $this->httpUtils()->dieWithHttpError(404);
72            throw new \Exception('should already have failed');
73        }
74
75        $article_metadata = "";
76        try {
77            $article_metadata = OlzArticleMetadata::render(['id' => $id]);
78        } catch (\Exception $exc) {
79            $this->httpUtils()->dieWithHttpError(404);
80            throw new \Exception('should already have failed');
81        }
82
83        $news_entry = $this->getNewsEntryById($id);
84
85        if (!$news_entry) {
86            $this->httpUtils()->dieWithHttpError(404);
87            throw new \Exception('should already have failed');
88        }
89
90        $title = $news_entry->getTitle();
91        $out = OlzHeader::render([
92            'back_link' => "{$code_href}news",
93            'title' => "{$title} - News",
94            'description' => "Aktuelle Beiträge, Berichte von Anlässen und weitere Neuigkeiten von der OL Zimmerberg.",
95            'norobots' => $is_archived,
96            'canonical_url' => "{$code_href}news/{$id}",
97            'additional_headers' => [
98                $article_metadata,
99            ],
100        ]);
101
102        $format = $news_entry->getFormat();
103        // TODO: Use array_find with PHP 8.4
104        $filtered = array_filter(
105            NewsUtils::ALL_FORMAT_OPTIONS,
106            fn ($entry) => $entry['ident'] === $format
107        );
108        // @phpstan-ignore-next-line
109        $found_entry = $filtered[array_keys($filtered)[0]];
110        $name = $found_entry['name'];
111        $icon = $found_entry['icon'] ?? null;
112        $icon_html = "<img src='{$code_href}assets/icns/{$icon}' alt='' class='format-icon'>";
113        $pretty_format = "{$icon_html}{$name}";
114
115        $pretty_date = $this->dateUtils()->olzDate("tt.mm.jjjj", $news_entry->getPublishedDate());
116        $author_user = $news_entry->getAuthorUser();
117        $author_role = $news_entry->getAuthorRole();
118        $author_name = $news_entry->getAuthorName();
119        $author_email = $news_entry->getAuthorEmail();
120        $pretty_author = OlzAuthorBadge::render([
121            'news_id' => $news_entry->getId() ?: 0,
122            'user' => $author_user,
123            'role' => $author_role,
124            'name' => $author_name,
125            'email' => $author_email,
126        ]);
127        $image_ids = $news_entry->getImageIds();
128        $num_images = count($image_ids);
129        $download_all_link = $this->authUtils()->hasPermission('any')
130            ? "<a href='{$code_href}news/{$id}/all.zip'>Alle herunterladen</a>" : '';
131
132        $out .= <<<ZZZZZZZZZZ
133            <div class='content-right'>
134                <div style='padding:4px 3px 10px 3px;'>
135                    <div id='format-info'><b>Format: </b>{$pretty_format}</div>
136                    <div><b>Datum: </b>{$pretty_date}</div>
137                    <div><b>Autor: </b>{$pretty_author}</div>
138                    <div><b>Anzahl Bilder: </b>{$num_images}</div>
139                    <div class='pretty'>{$download_all_link}</div>
140                </div>
141            </div>
142            <div class='content-middle'>
143            ZZZZZZZZZZ;
144
145        $db->query("UPDATE news SET `counter`=`counter` + 1 WHERE `id`='{$id}'");
146
147        $title = $news_entry->getTitle();
148        $teaser = $news_entry->getTeaser() ?? '';
149        $content = $news_entry->getContent() ?? '';
150        $published_date = $news_entry->getPublishedDate();
151
152        $published_date = $this->dateUtils()->olzDate("tt.mm.jj", $published_date);
153
154        $is_owner = $user && intval($news_entry->getOwnerUser()?->getId() ?? 0) === intval($user->getId());
155        $has_all_permissions = $this->authUtils()->hasPermission('all');
156        $can_edit = $is_owner || $has_all_permissions;
157        $edit_admin = '';
158        if ($can_edit) {
159            $json_id = json_encode($id);
160            $has_blog = $this->authUtils()->hasPermission('kaderblog', $user);
161            $has_roles = !empty($this->authUtils()->getAuthenticatedRoles());
162            $json_mode = htmlentities(json_encode($has_roles ? ($has_blog ? 'account_with_all' : 'account_with_aktuell') : ($has_blog ? 'account_with_blog' : 'account')) ?: '');
163            $edit_admin = <<<ZZZZZZZZZZ
164                <div>
165                    <button
166                        id='edit-news-button'
167                        class='btn btn-primary'
168                        onclick='return olz.editNews({$json_id}{$json_mode})'
169                    >
170                        <img src='{$code_href}assets/icns/edit_white_16.svg' class='noborder' />
171                        Bearbeiten
172                    </button>
173                </div>
174                ZZZZZZZZZZ;
175        }
176
177        // TODO: Temporary fix for broken Markdown
178        $content = str_replace("\n", "\n\n", $content);
179        $content = str_replace("\n\n\n\n", "\n\n", $content);
180
181        // Markdown
182        $html_input = $format === 'forum' ? 'escape' : 'allow'; // TODO: Do NOT allow!
183        $teaser = $this->htmlUtils()->renderMarkdown($teaser, [
184            'html_input' => $html_input,
185        ]);
186        $content = $this->htmlUtils()->renderMarkdown($content, [
187            'html_input' => $html_input,
188        ]);
189
190        // Datei- & Bildpfade
191        $teaser = $news_entry->replaceImagePaths($teaser);
192        $teaser = $news_entry->replaceFilePaths($teaser);
193        $content = $news_entry->replaceImagePaths($content);
194        $content = $news_entry->replaceFilePaths($content);
195
196        $out .= "<h1>{$edit_admin}{$title}</h1>";
197
198        $gallery = '';
199        $num_images = count($image_ids);
200        if ($num_images > 0) {
201            $gallery .= "<div class='lightgallery gallery-container'>";
202            foreach ($image_ids as $image_id) {
203                $gallery .= "<div class='gallery-image'>";
204                $gallery .= $this->imageUtils()->olzImage(
205                    'news',
206                    $id,
207                    $image_id,
208                    110,
209                    'gallery[myset]'
210                );
211                $gallery .= "</div>";
212            }
213            $gallery .= "</div>";
214        }
215
216        if ($format === 'aktuell') {
217            $out .= "<p><b>{$teaser}</b><p>{$content}</p><br/><br/>{$gallery}\n";
218        } elseif ($format === 'kaderblog') {
219            $out .= "<p>{$content}</p><br/><br/>{$gallery}\n";
220        } elseif ($format === 'forum') {
221            $out .= "<p><b>{$teaser}</b><p>{$content}</p><br/><br/>{$gallery}\n";
222        } elseif ($format === 'galerie') {
223            $out .= "<p>{$content}</p>{$gallery}\n";
224        } elseif ($format === 'video') {
225            $youtube_url = $news_entry->getExternalUrl() ?? '';
226            $res0 = preg_match("/^https\\:\\/\\/(www\\.)?youtu\\.be\\/([a-zA-Z0-9\\-\\_]{6,})/", $youtube_url, $matches0);
227            $res1 = preg_match("/^https\\:\\/\\/(www\\.)?youtube\\.com\\/watch\\?v\\=([a-zA-Z0-9\\-\\_]{6,})/", $youtube_url, $matches1);
228            $youtube_match = null;
229            if ($res0) {
230                $youtube_match = $matches0[2];
231            }
232            if ($res1) {
233                $youtube_match = $matches1[2];
234            }
235
236            $out .= "<div class='video-container'>";
237            $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";
238            if ($youtube_match != null) {
239                $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>";
240            } else {
241                $this->log()->error("Invalid YouTube link (ID:{$id}): {$youtube_url}");
242                $out .= "Fehlerhafter YouTube-Link!";
243            }
244            $out .= "<div style='background-image:url({$code_href}assets/icns/movie_dot.svg);background-repeat:repeat-x;margin:0px;padding:0px;height:24px;'></div>";
245            $out .= "</div>";
246        } else {
247            $out .= "<div class='lightgallery'><p><b>{$teaser}</b><p>{$content}</p></div>\n";
248        }
249        $out .= "</div>";
250
251        $out .= OlzFooter::render();
252
253        return $out;
254    }
255
256    protected function getNewsEntryById(int $id): ?NewsEntry {
257        $news_repo = $this->entityManager()->getRepository(NewsEntry::class);
258        return $news_repo->findOneBy([
259            'id' => $id,
260            'on_off' => 1,
261        ]);
262    }
263}