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