summaryrefslogtreecommitdiff
path: root/app/Http/Controllers/HomePageController.php
blob: 7654bd6cd414e7e6ce62f5ea64e38da7cc3031a3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
<?php
/**
 * webtrees: online genealogy
 * Copyright (C) 2018 webtrees development team
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */
declare(strict_types=1);

namespace Fisharebest\Webtrees\Http\Controllers;

use Fisharebest\Webtrees\Auth;
use Fisharebest\Webtrees\Database;
use Fisharebest\Webtrees\DebugBar;
use Fisharebest\Webtrees\I18N;
use Fisharebest\Webtrees\Module;
use Fisharebest\Webtrees\Module\ModuleBlockInterface;
use Fisharebest\Webtrees\Tree;
use Fisharebest\Webtrees\User;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

/**
 * Controller for the user/tree's home page.
 */
class HomePageController extends AbstractBaseController
{
    /**
     * Show a form to edit block config options.
     *
     * @param Request $request
     * @param Tree    $tree
     * @param User    $user
     *
     * @return Response
     */
    public function treePageBlockEdit(Request $request, Tree $tree, User $user): Response
    {
        $block_id = (int) $request->get('block_id');
        $block    = $this->treeBlock($request, $user);
        $title    = $block->getTitle() . ' — ' . I18N::translate('Preferences');

        return $this->viewResponse('modules/edit-block-config', [
            'block'      => $block,
            'block_id'   => $block_id,
            'cancel_url' => route('tree-page', ['ged' => $tree->getName()]),
            'title'      => $title,
            'tree'       => $tree,
        ]);
    }

    /**
     * Update block config options.
     *
     * @param Request $request
     * @param Tree    $tree
     * @param User    $user
     *
     * @return RedirectResponse
     */
    public function treePageBlockUpdate(Request $request, Tree $tree, User $user): RedirectResponse
    {
        $block    = $this->treeBlock($request, $user);
        $block_id = (int) $request->get('block_id');

        $block->saveBlockConfiguration($request, $block_id);

        return new RedirectResponse(route('tree-page', ['ged' => $tree->getName()]));
    }

    /**
     * Load a block and check we have permission to edit it.
     *
     * @param Request $request
     * @param User    $user
     *
     * @return ModuleBlockInterface
     */
    private function treeBlock(Request $request, User $user): ModuleBlockInterface
    {
        $block_id = (int) $request->get('block_id');

        $block_info = Database::prepare(
            "SELECT module_Name, user_id FROM `##block` WHERE block_id = :block_id"
        )->execute([
            'block_id' => $block_id,
        ])->fetchOneRow();

        if ($block_info === null) {
            throw new NotFoundHttpException();
        }

        $block = Module::getModuleByName($block_info->module_name);

        if (!$block instanceof ModuleBlockInterface) {
            throw new NotFoundHttpException();
        }

        if ($block_info->user_id !== $user->getUserId() && !Auth::isAdmin()) {
            throw new AccessDeniedHttpException();
        }

        return $block;
    }

    /**
     * Show a form to edit block config options.
     *
     * @param Request $request
     * @param Tree    $tree
     * @param User    $user
     *
     * @return Response
     */
    public function userPageBlockEdit(Request $request, Tree $tree, User $user): Response
    {
        $block_id = (int) $request->get('block_id');
        $block    = $this->userBlock($request, $user);
        $title    = $block->getTitle() . ' — ' . I18N::translate('Preferences');

        return $this->viewResponse('modules/edit-block-config', [
            'block'      => $block,
            'block_id'   => $block_id,
            'cancel_url' => route('user-page', ['ged' => $tree->getName()]),
            'title'      => $title,
            'tree'       => $tree,
        ]);
    }

    /**
     * Update block config options.
     *
     * @param Request $request
     * @param Tree    $tree
     * @param User    $user
     *
     * @return RedirectResponse
     */
    public function userPageBlockUpdate(Request $request, Tree $tree, User $user): RedirectResponse
    {
        $block    = $this->userBlock($request, $user);
        $block_id = (int) $request->get('block_id');

        $block->saveBlockConfiguration($request, $block_id);

        return new RedirectResponse(route('user-page', ['ged' => $tree->getName()]));
    }

    /**
     * Load a block and check we have permission to edit it.
     *
     * @param Request $request
     * @param User    $user
     *
     * @return ModuleBlockInterface
     */
    private function userBlock(Request $request, User $user): ModuleBlockInterface
    {
        $block_id = (int) $request->get('block_id');

        $block_info = Database::prepare(
            "SELECT module_Name, user_id FROM `##block` WHERE block_id = :block_id"
        )->execute([
            'block_id' => $block_id,
        ])->fetchOneRow();

        if ($block_info === null) {
            throw new NotFoundHttpException('This block does not exist');
        }

        $block = Module::getModuleByName($block_info->module_name);

        if (!$block instanceof ModuleBlockInterface) {
            throw new NotFoundHttpException($block_info->module_name . ' is not a block');
        }

        $block_owner_id = (int) $block_info->user_id;

        if ($block_owner_id !== $user->getUserId() && !Auth::isAdmin()) {
            throw new AccessDeniedHttpException('You are not allowed to edit this block');
        }

        return $block;
    }

    /**
     * Show a tree's page.
     *
     * @param Tree $tree
     *
     * @return Response
     */
    public function treePage(Tree $tree): Response
    {
        $tree_id      = $tree->getTreeId();
        $access_level = Auth::accessLevel($tree);
        $main_blocks  = $this->getBlocksForTreePage($tree_id, $access_level, 'main');
        $side_blocks  = $this->getBlocksForTreePage($tree_id, $access_level, 'side');
        $title        = e($tree->getTitle());

        // @TODO - ModuleBlockInterface::getBlock() currently relies on these globals
        global $ctype;
        $ctype = 'gedcom';

        return $this->viewResponse('tree-page', [
            'main_blocks' => $main_blocks,
            'side_blocks' => $side_blocks,
            'title'       => $title,
            'meta_robots' => 'index,follow',
        ]);
    }

    /**
     * Load block asynchronously.
     *
     * @param Request $request
     * @param Tree    $tree
     *
     * @return Response
     */
    public function treePageBlock(Request $request, Tree $tree): Response
    {
        $block_id = (int) $request->get('block_id');

        $block = Database::prepare(
            "SELECT * FROM `##block` WHERE block_id = :block_id AND gedcom_id = :tree_id AND user_id IS NULL"
        )->execute([
            'block_id' => $block_id,
            'tree_id'  => $tree->getTreeId(),
        ])->fetchOneRow();

        $module = $this->getBlockModule($tree, $block_id);

        if ($block === null || $module === null) {
            return new Response('', Response::HTTP_NOT_FOUND);
        }

        // @TODO - ModuleBlockInterface::getBlock() currently relies on these globals
        global $ctype;
        $ctype = 'gedcom';

        $html = view('layouts/ajax', [
            'content' => $module->getBlock($tree, $block_id, true),
        ]);


        // Use HTTP headers and some jQuery to add debug to the current page.
        DebugBar::sendDataInHeaders();

        return new Response($html);
    }

    /**
     * Show a form to edit the default blocks for new trees.
     *
     * @return Response
     */
    public function treePageDefaultEdit(): Response
    {
        $main_blocks = $this->getBlocksForTreePage(-1, Auth::PRIV_NONE, 'main');
        $side_blocks = $this->getBlocksForTreePage(-1, Auth::PRIV_NONE, 'side');
        $all_blocks  = $this->getAvailableTreeBlocks();
        $title       = I18N::translate('Set the default blocks for new family trees');
        $url_cancel  = route('admin-control-panel');
        $url_save    = route('tree-page-default-update');

        return $this->viewResponse('edit-blocks-page', [
            'all_blocks'  => $all_blocks,
            'can_reset'   => false,
            'main_blocks' => $main_blocks,
            'side_blocks' => $side_blocks,
            'title'       => $title,
            'url_cancel'  => $url_cancel,
            'url_save'    => $url_save,
        ]);
    }

    /**
     * Save updated default blocks for new trees.
     *
     * @param Request $request
     *
     * @return RedirectResponse
     */
    public function treePageDefaultUpdate(Request $request): RedirectResponse
    {
        $main_blocks = (array) $request->get('main');
        $side_blocks = (array) $request->get('side');

        $this->updateTreeBlocks(-1, $main_blocks, $side_blocks);

        return new RedirectResponse(route('admin-control-panel'));
    }

    /**
     * Show a form to edit the blocks on a tree's page.
     *
     * @param Tree $tree
     *
     * @return Response
     */
    public function treePageEdit(Tree $tree): Response
    {
        $main_blocks = $this->getBlocksForTreePage($tree->getTreeId(), Auth::accessLevel($tree), 'main');
        $side_blocks = $this->getBlocksForTreePage($tree->getTreeId(), Auth::accessLevel($tree), 'side');
        $all_blocks  = $this->getAvailableTreeBlocks();
        $title       = I18N::translate('Change the “Home page” blocks');
        $url_cancel  = route('tree-page', ['ged' => $tree->getName()]);
        $url_save    = route('tree-page-update', ['ged' => $tree->getName()]);

        return $this->viewResponse('edit-blocks-page', [
            'all_blocks'  => $all_blocks,
            'can_reset'   => true,
            'main_blocks' => $main_blocks,
            'side_blocks' => $side_blocks,
            'title'       => $title,
            'url_cancel'  => $url_cancel,
            'url_save'    => $url_save,
        ]);
    }

    /**
     * Save updated blocks on a tree's page.
     *
     * @param Request $request
     * @param Tree    $tree
     *
     * @return RedirectResponse
     */
    public function treePageUpdate(Request $request, Tree $tree): RedirectResponse
    {
        $defaults = (bool) $request->get('defaults');

        if ($defaults) {
            $main_blocks = $this->getBlocksForTreePage(-1, AUth::PRIV_NONE, 'main');
            $side_blocks = $this->getBlocksForTreePage(-1, Auth::PRIV_NONE, 'side');
        } else {
            $main_blocks = (array) $request->get('main');
            $side_blocks = (array) $request->get('side');
        }

        $this->updateTreeBlocks($tree->getTreeId(), $main_blocks, $side_blocks);

        return new RedirectResponse(route('tree-page', ['ged' => $tree->getName()]));
    }

    /**
     * Show a users's page.
     *
     * @param Tree $tree
     * @param User $user
     *
     * @return Response
     */
    public function userPage(Tree $tree, User $user): Response
    {
        $tree_id      = $tree->getTreeId();
        $user_id      = $user->getUserId();
        $access_level = Auth::accessLevel($tree, $user);
        $main_blocks  = $this->getBlocksForUserPage($tree_id, $user_id, $access_level, 'main');
        $side_blocks  = $this->getBlocksForUserPage($tree_id, $user_id, $access_level, 'side');
        $title        = I18N::translate('My page');

        // @TODO - ModuleBlockInterface::getBlock() currently relies on these globals
        global $ctype;
        $ctype = 'user';

        return $this->viewResponse('user-page', [
            'main_blocks' => $main_blocks,
            'side_blocks' => $side_blocks,
            'title'       => $title,
        ]);
    }

    /**
     * Load block asynchronously.
     *
     * @param Request $request
     * @param Tree    $tree
     * @param User    $user
     *
     * @return Response
     */
    public function userPageBlock(Request $request, Tree $tree, User $user): Response
    {
        $block_id = (int) $request->get('block_id');

        $block = Database::prepare(
            "SELECT * FROM `##block` WHERE block_id = :block_id AND gedcom_id IS NULL AND user_id = :user_id"
        )->execute([
            'block_id' => $block_id,
            'user_id'  => $user->getUserId(),
        ])->fetchOneRow();

        $module = $this->getBlockModule($tree, $block_id);

        if ($block === null || $module === null) {
            return new Response('Block not found', Response::HTTP_NOT_FOUND);
        }

        // @TODO - ModuleBlockInterface::getBlock() relies on these globals :-(
        global $ctype;
        $ctype = 'user';

        $html = view('layouts/ajax', [
            'content' => $module->getBlock($tree, $block_id, true),
        ]);

        // Use HTTP headers and some jQuery to add debug to the current page.
        DebugBar::sendDataInHeaders();

        return new Response($html);
    }

    /**
     * Show a form to edit the default blocks for new uesrs.
     *
     * @return Response
     */
    public function userPageDefaultEdit(): Response
    {
        $main_blocks = $this->getBlocksForUserPage(-1, -1, Auth::PRIV_NONE, 'main');
        $side_blocks = $this->getBlocksForUserPage(-1, -1, Auth::PRIV_NONE, 'side');
        $all_blocks  = $this->getAvailableUserBlocks();
        $title       = I18N::translate('Set the default blocks for new users');
        $url_cancel  = route('admin-users');
        $url_save    = route('user-page-default-update');

        return $this->viewResponse('edit-blocks-page', [
            'all_blocks'  => $all_blocks,
            'can_reset'   => false,
            'main_blocks' => $main_blocks,
            'side_blocks' => $side_blocks,
            'title'       => $title,
            'url_cancel'  => $url_cancel,
            'url_save'    => $url_save,
        ]);
    }

    /**
     * Save the updated default blocks for new users.
     *
     * @param Request $request
     *
     * @return RedirectResponse
     */
    public function userPageDefaultUpdate(Request $request): RedirectResponse
    {
        $main_blocks = (array) $request->get('main');
        $side_blocks = (array) $request->get('side');

        $this->updateUserBlocks(-1, $main_blocks, $side_blocks);

        return new RedirectResponse(route('admin-control-panel'));
    }

    /**
     * Show a form to edit the blocks on the user's page.
     *
     * @param Tree $tree
     * @param User $user
     *
     * @return Response
     */
    public function userPageEdit(Tree $tree, User $user): Response
    {
        $main_blocks = $this->getBlocksForUserPage($tree->getTreeId(), $user->getUserId(), Auth::accessLevel($tree, $user), 'main');
        $side_blocks = $this->getBlocksForUserPage($tree->getTreeId(), $user->getUserId(), Auth::accessLevel($tree, $user), 'side');
        $all_blocks  = $this->getAvailableUserBlocks();
        $title       = I18N::translate('Change the “My page” blocks');
        $url_cancel  = route('user-page', ['ged' => $tree->getName()]);
        $url_save    = route('user-page-update', ['ged' => $tree->getName()]);

        return $this->viewResponse('edit-blocks-page', [
            'all_blocks'  => $all_blocks,
            'can_reset'   => true,
            'main_blocks' => $main_blocks,
            'side_blocks' => $side_blocks,
            'title'       => $title,
            'url_cancel'  => $url_cancel,
            'url_save'    => $url_save,
        ]);
    }

    /**
     * Save the updted blocks on a user's page.
     *
     * @param Request $request
     * @param Tree    $tree
     * @param User    $user
     *
     * @return RedirectResponse
     */
    public function userPageUpdate(Request $request, Tree $tree, User $user): RedirectResponse
    {
        $defaults = (bool) $request->get('defaults');

        if ($defaults) {
            $main_blocks = $this->getBlocksForUserPage(-1, -1, AUth::PRIV_NONE, 'main');
            $side_blocks = $this->getBlocksForUserPage(-1, -1, Auth::PRIV_NONE, 'side');
        } else {
            $main_blocks = (array) $request->get('main');
            $side_blocks = (array) $request->get('side');
        }

        $this->updateUserBlocks($user->getUserId(), $main_blocks, $side_blocks);

        return new RedirectResponse(route('user-page', ['ged' => $tree->getName()]));
    }

    /**
     * Show a form to edit the blocks for another user's page.
     *
     * @param Request $request
     *
     * @return Response
     */
    public function userPageUserEdit(Request $request): Response
    {
        $user_id     = (int) $request->get('user_id');
        $user        = User::find($user_id);
        $main_blocks = $this->getBlocksForUserPage(-1, $user_id, Auth::PRIV_NONE, 'main');
        $side_blocks = $this->getBlocksForUserPage(-1, $user_id, Auth::PRIV_NONE, 'side');
        $all_blocks  = $this->getAvailableUserBlocks();
        $title       = I18N::translate('Change the blocks on this user’s “My page”') . ' - ' . e($user->getUserName());
        $url_cancel  = route('admin-users');
        $url_save    = route('user-page-user-update', ['user_id' => $user_id]);

        return $this->viewResponse('edit-blocks-page', [
            'all_blocks'  => $all_blocks,
            'can_reset'   => false,
            'main_blocks' => $main_blocks,
            'side_blocks' => $side_blocks,
            'title'       => $title,
            'url_cancel'  => $url_cancel,
            'url_save'    => $url_save,
        ]);
    }

    /**
     * Save the updated blocks for another user's page.
     *
     * @param Request $request
     *
     * @return RedirectResponse
     */
    public function userPageUserUpdate(Request $request): RedirectResponse
    {
        $user_id     = (int) $request->get('user_id');
        $main_blocks = (array) $request->get('main');
        $side_blocks = (array) $request->get('side');

        $this->updateUserBlocks($user_id, $main_blocks, $side_blocks);

        return new RedirectResponse(route('admin-control-panel'));
    }

    /**
     * Get a specific block.
     *
     * @param Tree $tree
     * @param int  $block_id
     *
     * @return ModuleBlockInterface|null
     */
    private function getBlockModule(Tree $tree, int $block_id)
    {
        $active_blocks = Module::getActiveBlocks($tree);

        $module_name = Database::prepare(
            "SELECT module_name FROM `##block`" .
            " JOIN  `##module` USING (module_name)" .
            " WHERE block_id = :block_id AND status = 'enabled'"
        )->execute([
            'block_id' => $block_id,
        ])->fetchOne();

        return $active_blocks[$module_name] ?? null;
    }

    /**
     * Get all the available blocks for a tree page.
     *
     * @return ModuleBlockInterface[]
     */
    private function getAvailableTreeBlocks(): array
    {
        $blocks = Module::getAllModulesByComponent('block');
        $blocks = array_filter($blocks, function (ModuleBlockInterface $block): bool {
            return $block->isGedcomBlock();
        });

        return $blocks;
    }

    /**
     * Get all the available blocks for a user page.
     *
     * @return ModuleBlockInterface[]
     */
    private function getAvailableUserBlocks(): array
    {
        $blocks = Module::getAllModulesByComponent('block');
        $blocks = array_filter($blocks, function (ModuleBlockInterface $block): bool {
            return $block->isUserBlock();
        });

        return $blocks;
    }

    /**
     * Get the blocks for a specified tree (or the default tree).
     *
     * @param int    $tree_id
     * @param int    $access_level
     * @param string $location "main" or "side"
     *
     * @return ModuleBlockInterface[]
     */
    private function getBlocksForTreePage(int $tree_id, int $access_level, string $location): array
    {
        $rows = Database::prepare(
            "SELECT block_id, module_name" .
            " FROM  `##block`" .
            " JOIN  `##module` USING (module_name)" .
            " JOIN  `##module_privacy` USING (module_name, gedcom_id)" .
            " WHERE gedcom_id = :tree_id" .
            " AND   status = 'enabled'" .
            " AND   location = :location" .
            " AND   access_level >= :access_level" .
            " ORDER BY location, block_order"
        )->execute([
            'access_level' => $access_level,
            'location'     => $location,
            'tree_id'      => $tree_id,
        ])->fetchAssoc();

        return $this->filterActiveBlocks($rows, $this->getAvailableTreeBlocks());
    }

    /**
     * Get the blocks for a specified user (or the default user).
     *
     * @param int    $tree_id
     * @param int    $user_id
     * @param int    $access_level
     * @param string $location "main" or "side"
     *
     * @return ModuleBlockInterface[]
     */
    private function getBlocksForUserPage(int $tree_id, int $user_id, int $access_level, string $location): array
    {
        $rows = Database::prepare(
            "SELECT block_id, module_name" .
            " FROM  `##block`" .
            " JOIN  `##module` USING (module_name)" .
            " JOIN  `##module_privacy` USING (module_name)" .
            " WHERE user_id = :user_id" .
            " AND   status = 'enabled'" .
            " AND   location = :location" .
            " AND   `##module_privacy`.gedcom_id = :tree_id" .
            " AND   access_level >= :access_level" .
            " ORDER BY block_order"
        )->execute([
            'access_level' => $access_level,
            'location'     => $location,
            'user_id'      => $user_id,
            'tree_id'      => $tree_id,
        ])->fetchAssoc();

        return $this->filterActiveBlocks($rows, $this->getAvailableUserBlocks());
    }

    /**
     * Take a list of block names, and return block (module) objects.
     *
     * @param string[] $blocks
     * @param array    $active_blocks
     *
     * @return ModuleBlockInterface[]
     */
    private function filterActiveBlocks(array $blocks, array $active_blocks): array
    {
        return array_filter(array_map(function (string $module_name) use ($active_blocks) {
            return $active_blocks[$module_name] ?? false;
        }, $blocks));
    }

    /**
     * Save the updated blocks for a tree.
     *
     * @param int   $tree_id
     * @param array $main_blocks
     * @param array $side_blocks
     *
     * @return void
     */
    private function updateTreeBlocks(int $tree_id, array $main_blocks, array $side_blocks)
    {
        $existing_block_ids = Database::prepare(
            "SELECT block_id FROM `##block` WHERE gedcom_id = :tree_id"
        )->execute([
            'tree_id' => $tree_id,
        ])->fetchOneColumn();

        // Deleted blocks
        foreach ($existing_block_ids as $existing_block_id) {
            if (!in_array($existing_block_id, $main_blocks) && !in_array($existing_block_id, $side_blocks)) {
                Database::prepare(
                    "DELETE FROM `##block_setting` WHERE block_id = :block_id"
                )->execute([
                    'block_id' => $existing_block_id,
                ]);
                Database::prepare(
                    "DELETE FROM `##block` WHERE block_id = :block_id"
                )->execute([
                    'block_id' => $existing_block_id,
                ]);
            }
        }

        $updates = [
            'main' => $main_blocks,
            'side' => $side_blocks,
        ];

        foreach ($updates as $location => $updated_blocks) {
            foreach ($updated_blocks as $block_order => $block_id) {
                if (is_numeric($block_id)) {
                    // Updated block
                    Database::prepare(
                        "UPDATE `##block`" .
                        " SET block_order = :block_order, location = :location" .
                        " WHERE block_id = :block_id"
                    )->execute([
                        'block_order' => $block_order,
                        'block_id'    => $block_id,
                        'location'    => $location,
                    ]);
                } else {
                    // New block
                    Database::prepare(
                        "INSERT INTO `##block` (gedcom_id, location, block_order, module_name)" .
                        " VALUES (:tree_id, :location, :block_order, :module_name)"
                    )->execute([
                        'tree_id'     => $tree_id,
                        'location'    => $location,
                        'block_order' => $block_order,
                        'module_name' => $block_id,
                    ]);
                }
            }
        }
    }

    /**
     * Save the updated blocks for a user.
     *
     * @param int   $user_id
     * @param array $main_blocks
     * @param array $side_blocks
     *
     * @return void
     */
    private function updateUserBlocks(int $user_id, array $main_blocks, array $side_blocks)
    {
        $existing_block_ids = Database::prepare(
            "SELECT block_id FROM `##block` WHERE user_id = :user_id"
        )->execute([
            'user_id' => $user_id,
        ])->fetchOneColumn();

        // Deleted blocks
        foreach ($existing_block_ids as $existing_block_id) {
            if (!in_array($existing_block_id, $main_blocks) && !in_array($existing_block_id, $side_blocks)) {
                Database::prepare(
                    "DELETE FROM `##block_setting` WHERE block_id = :block_id"
                )->execute([
                    'block_id' => $existing_block_id,
                ]);
                Database::prepare(
                    "DELETE FROM `##block` WHERE block_id = :block_id"
                )->execute([
                    'block_id' => $existing_block_id,
                ]);
            }
        }

        foreach ([
             'main' => $main_blocks,
             'side' => $side_blocks,
         ] as $location => $updated_blocks) {
            foreach ($updated_blocks as $block_order => $block_id) {
                if (is_numeric($block_id)) {
                    // Updated block
                    Database::prepare(
                        "UPDATE `##block`" .
                        " SET block_order = :block_order, location = :location" .
                        " WHERE block_id = :block_id"
                    )->execute([
                        'block_order' => $block_order,
                        'block_id'    => $block_id,
                        'location'    => $location,
                    ]);
                } else {
                    // New block
                    Database::prepare(
                        "INSERT INTO `##block` (user_id, location, block_order, module_name)" .
                        " VALUES (:user_id, :location, :block_order, :module_name)"
                    )->execute([
                        'user_id'     => $user_id,
                        'location'    => $location,
                        'block_order' => $block_order,
                        'module_name' => $block_id,
                    ]);
                }
            }
        }
    }
}