xref: /webtrees/app/Services/HomePageService.php (revision 19d319e7095703d7954023b55f1661a16d1edff3)
1<?php
2
3/**
4 * webtrees: online genealogy
5 * Copyright (C) 2019 webtrees development team
6 * This program is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation, either version 3 of the License, or
9 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <http://www.gnu.org/licenses/>.
16 */
17
18declare(strict_types=1);
19
20namespace Fisharebest\Webtrees\Services;
21
22use Fisharebest\Webtrees\Auth;
23use Fisharebest\Webtrees\Contracts\UserInterface;
24use Fisharebest\Webtrees\Exceptions\HttpAccessDeniedException;
25use Fisharebest\Webtrees\Exceptions\HttpNotFoundException;
26use Fisharebest\Webtrees\Module\ModuleBlockInterface;
27use Fisharebest\Webtrees\Module\ModuleInterface;
28use Fisharebest\Webtrees\Tree;
29use Illuminate\Database\Capsule\Manager as DB;
30use Illuminate\Support\Collection;
31use Psr\Http\Message\ServerRequestInterface;
32use stdClass;
33
34use function assert;
35use function is_numeric;
36
37/**
38 * Logic and content for the home-page blocks.
39 */
40class HomePageService
41{
42    /** @var ModuleService */
43    private $module_service;
44
45    /**
46     * HomePageController constructor.
47     *
48     * @param ModuleService $module_service
49     */
50    public function __construct(ModuleService $module_service)
51    {
52        $this->module_service = $module_service;
53    }
54
55    /**
56     * Load a block and check we have permission to edit it.
57     *
58     * @param ServerRequestInterface $request
59     * @param UserInterface          $user
60     *
61     * @return ModuleBlockInterface
62     */
63    public function treeBlock(ServerRequestInterface $request, UserInterface $user): ModuleBlockInterface
64    {
65        $tree = $request->getAttribute('tree');
66        assert($tree instanceof Tree);
67
68        $block_id = (int) $request->getQueryParams()['block_id'];
69
70        $block = DB::table('block')
71            ->where('block_id', '=', $block_id)
72            ->where('gedcom_id', '=', $tree->id())
73            ->whereNull('user_id')
74            ->first();
75
76        if (!$block instanceof stdClass) {
77            throw new HttpNotFoundException();
78        }
79
80        $module = $this->module_service->findByName($block->module_name);
81
82        if (!$module instanceof ModuleBlockInterface) {
83            throw new HttpNotFoundException();
84        }
85
86        if ($block->user_id !== $user->id() && !Auth::isAdmin()) {
87            throw new HttpAccessDeniedException();
88        }
89
90        return $module;
91    }
92
93    /**
94     * Load a block and check we have permission to edit it.
95     *
96     * @param ServerRequestInterface $request
97     * @param UserInterface          $user
98     *
99     * @return ModuleBlockInterface
100     */
101    public function userBlock(ServerRequestInterface $request, UserInterface $user): ModuleBlockInterface
102    {
103        $block_id = (int) $request->getQueryParams()['block_id'];
104
105        $block = DB::table('block')
106            ->where('block_id', '=', $block_id)
107            ->where('user_id', '=', $user->id())
108            ->whereNull('gedcom_id')
109            ->first();
110
111        if (!$block instanceof stdClass) {
112            throw new HttpNotFoundException('This block does not exist');
113        }
114
115        $module = $this->module_service->findByName($block->module_name);
116
117        if (!$module instanceof ModuleBlockInterface) {
118            throw new HttpNotFoundException($block->module_name . ' is not a block');
119        }
120
121        $block_owner_id = (int) $block->user_id;
122
123        if ($block_owner_id !== $user->id() && !Auth::isAdmin()) {
124            throw new HttpAccessDeniedException('You are not allowed to edit this block');
125        }
126
127        return $module;
128    }
129
130    /**
131     * Get a specific block.
132     *
133     * @param Tree $tree
134     * @param int  $block_id
135     *
136     * @return ModuleBlockInterface
137     */
138    public function getBlockModule(Tree $tree, int $block_id): ModuleBlockInterface
139    {
140        $active_blocks = $this->module_service->findByComponent(ModuleBlockInterface::class, $tree, Auth::user());
141
142        $module_name = DB::table('block')
143            ->where('block_id', '=', $block_id)
144            ->value('module_name');
145
146        $block = $active_blocks->first(static function (ModuleInterface $module) use ($module_name): bool {
147            return $module->name() === $module_name;
148        });
149
150        if ($block instanceof ModuleBlockInterface) {
151            return $block;
152        }
153
154        throw new HttpNotFoundException('Block not found');
155    }
156
157    /**
158     * Get all the available blocks for a tree page.
159     *
160     * @param Tree          $tree
161     * @param UserInterface $user
162     *
163     * @return Collection<string,ModuleBlockInterface>
164     */
165    public function availableTreeBlocks(Tree $tree, UserInterface $user): Collection
166    {
167        return $this->module_service->findByComponent(ModuleBlockInterface::class, $tree, $user)
168            ->filter(static function (ModuleBlockInterface $block): bool {
169                return $block->isTreeBlock();
170            })
171            ->mapWithKeys(static function (ModuleBlockInterface $block): array {
172                return [$block->name() => $block];
173            });
174    }
175
176    /**
177     * Get all the available blocks for a user page.
178     *
179     * @param Tree          $tree
180     * @param UserInterface $user
181     *
182     * @return Collection<string,ModuleBlockInterface>
183     */
184    public function availableUserBlocks(Tree $tree, UserInterface $user): Collection
185    {
186        return $this->module_service->findByComponent(ModuleBlockInterface::class, $tree, $user)
187            ->filter(static function (ModuleBlockInterface $block): bool {
188                return $block->isUserBlock();
189            })
190            ->mapWithKeys(static function (ModuleBlockInterface $block): array {
191                return [$block->name() => $block];
192            });
193    }
194
195    /**
196     * Get the blocks for a specified tree.
197     *
198     * @param Tree          $tree
199     * @param UserInterface $user
200     * @param string        $location "main" or "side"
201     *
202     * @return Collection<string,ModuleBlockInterface>
203     */
204    public function treeBlocks(Tree $tree, UserInterface $user, string $location): Collection
205    {
206        $rows = DB::table('block')
207            ->where('gedcom_id', '=', $tree->id())
208            ->where('location', '=', $location)
209            ->orderBy('block_order')
210            ->pluck('module_name', 'block_id');
211
212        return $this->filterActiveBlocks($rows, $this->availableTreeBlocks($tree, $user));
213    }
214
215    /**
216     * Make sure that default blocks exist for a tree.
217     *
218     * @return void
219     */
220    public function checkDefaultTreeBlocksExist(): void
221    {
222        $has_blocks = DB::table('block')
223            ->where('gedcom_id', '=', -1)
224            ->exists();
225
226        // No default settings?  Create them.
227        if (!$has_blocks) {
228            foreach ([ModuleBlockInterface::MAIN_BLOCKS, ModuleBlockInterface::SIDE_BLOCKS] as $location) {
229                foreach (ModuleBlockInterface::DEFAULT_TREE_PAGE_BLOCKS[$location] as $block_order => $class) {
230                    $module_name = $this->module_service->findByInterface($class)->first()->name();
231
232                    DB::table('block')->insert([
233                        'gedcom_id'   => -1,
234                        'location'    => $location,
235                        'block_order' => $block_order,
236                        'module_name' => $module_name,
237                    ]);
238                }
239            }
240        }
241    }
242
243    /**
244     * Get the blocks for a specified user.
245     *
246     * @param Tree          $tree
247     * @param UserInterface $user
248     * @param string        $location "main" or "side"
249     *
250     * @return Collection<string,ModuleBlockInterface>
251     */
252    public function userBlocks(Tree $tree, UserInterface $user, string $location): Collection
253    {
254        $rows = DB::table('block')
255            ->where('user_id', '=', $user->id())
256            ->where('location', '=', $location)
257            ->orderBy('block_order')
258            ->pluck('module_name', 'block_id');
259
260        return $this->filterActiveBlocks($rows, $this->availableUserBlocks($tree, $user));
261    }
262
263    /**
264     * Make sure that default blocks exist for a user.
265     *
266     * @return void
267     */
268    public function checkDefaultUserBlocksExist(): void
269    {
270        $has_blocks = DB::table('block')
271            ->where('user_id', '=', -1)
272            ->exists();
273
274        // No default settings?  Create them.
275        if (!$has_blocks) {
276            foreach ([ModuleBlockInterface::MAIN_BLOCKS, ModuleBlockInterface::SIDE_BLOCKS] as $location) {
277                foreach (ModuleBlockInterface::DEFAULT_USER_PAGE_BLOCKS[$location] as $block_order => $class) {
278                    $module = $this->module_service->findByInterface($class)->first();
279
280                    if ($module instanceof ModuleBlockInterface) {
281                        DB::table('block')->insert([
282                            'user_id'     => -1,
283                            'location'    => $location,
284                            'block_order' => $block_order,
285                            'module_name' => $module->name(),
286                        ]);
287                    }
288                }
289            }
290        }
291    }
292
293    /**
294     * Save the updated blocks for a user.
295     *
296     * @param int                $user_id
297     * @param Collection<string> $main_block_ids
298     * @param Collection<string> $side_block_ids
299     *
300     * @return void
301     */
302    public function updateUserBlocks(int $user_id, Collection $main_block_ids, Collection $side_block_ids): void
303    {
304        $existing_block_ids = DB::table('block')
305            ->where('user_id', '=', $user_id)
306            ->whereIn('location', [ModuleBlockInterface::MAIN_BLOCKS, ModuleBlockInterface::SIDE_BLOCKS])
307            ->pluck('block_id');
308
309        // Deleted blocks
310        foreach ($existing_block_ids as $existing_block_id) {
311            if (!$main_block_ids->contains($existing_block_id) && !$side_block_ids->contains($existing_block_id)) {
312                DB::table('block_setting')
313                    ->where('block_id', '=', $existing_block_id)
314                    ->delete();
315
316                DB::table('block')
317                    ->where('block_id', '=', $existing_block_id)
318                    ->delete();
319            }
320        }
321
322        $updates = [
323            ModuleBlockInterface::MAIN_BLOCKS => $main_block_ids,
324            ModuleBlockInterface::SIDE_BLOCKS => $side_block_ids,
325        ];
326
327        foreach ($updates as $location => $updated_blocks) {
328            foreach ($updated_blocks as $block_order => $block_id) {
329                if (is_numeric($block_id)) {
330                    // Updated block
331                    DB::table('block')
332                        ->where('block_id', '=', $block_id)
333                        ->update([
334                            'block_order' => $block_order,
335                            'location'    => $location,
336                        ]);
337                } else {
338                    // New block
339                    DB::table('block')->insert([
340                        'user_id'     => $user_id,
341                        'location'    => $location,
342                        'block_order' => $block_order,
343                        'module_name' => $block_id,
344                    ]);
345                }
346            }
347        }
348    }
349
350    /**
351     * Save the updated blocks for a tree.
352     *
353     * @param int                $tree_id
354     * @param Collection<string> $main_block_ids
355     * @param Collection<string> $side_block_ids
356     *
357     * @return void
358     */
359    public function updateTreeBlocks(int $tree_id, Collection $main_block_ids, Collection $side_block_ids): void
360    {
361        $existing_block_ids = DB::table('block')
362            ->where('gedcom_id', '=', $tree_id)
363            ->whereIn('location', [ModuleBlockInterface::MAIN_BLOCKS, ModuleBlockInterface::SIDE_BLOCKS])
364            ->pluck('block_id');
365
366        // Deleted blocks
367        foreach ($existing_block_ids as $existing_block_id) {
368            if (!$main_block_ids->contains($existing_block_id) && !$side_block_ids->contains($existing_block_id)) {
369                DB::table('block_setting')
370                    ->where('block_id', '=', $existing_block_id)
371                    ->delete();
372
373                DB::table('block')
374                    ->where('block_id', '=', $existing_block_id)
375                    ->delete();
376            }
377        }
378
379        $updates = [
380            ModuleBlockInterface::MAIN_BLOCKS => $main_block_ids,
381            ModuleBlockInterface::SIDE_BLOCKS => $side_block_ids,
382        ];
383
384        foreach ($updates as $location => $updated_blocks) {
385            foreach ($updated_blocks as $block_order => $block_id) {
386                if (is_numeric($block_id)) {
387                    // Updated block
388                    DB::table('block')
389                        ->where('block_id', '=', $block_id)
390                        ->update([
391                            'block_order' => $block_order,
392                            'location'    => $location,
393                        ]);
394                } else {
395                    // New block
396                    DB::table('block')->insert([
397                        'gedcom_id'   => $tree_id,
398                        'location'    => $location,
399                        'block_order' => $block_order,
400                        'module_name' => $block_id,
401                    ]);
402                }
403            }
404        }
405    }
406
407    /**
408     * Take a list of block names, and return block (module) objects.
409     *
410     * @param Collection<string>                      $blocks
411     * @param Collection<string,ModuleBlockInterface> $active_blocks
412     *
413     * @return Collection<string,ModuleBlockInterface>
414     */
415    private function filterActiveBlocks(Collection $blocks, Collection $active_blocks): Collection
416    {
417        return $blocks->map(static function (string $block_name) use ($active_blocks): ?ModuleBlockInterface {
418            return $active_blocks->filter(static function (ModuleInterface $block) use ($block_name): bool {
419                return $block->name() === $block_name;
420            })->first();
421        })->filter();
422    }
423}
424