1<?php
2/**
3 * webtrees: online genealogy
4 * Copyright (C) 2019 webtrees development team
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation, either version 3 of the License, or
8 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 * You should have received a copy of the GNU General Public License
14 * along with this program. If not, see <http://www.gnu.org/licenses/>.
15 */
16namespace Fisharebest\Webtrees;
17
18/**
19 * A GEDCOM source (SOUR) object.
20 */
21class Source extends GedcomRecord
22{
23    const RECORD_TYPE = 'SOUR';
24    const URL_PREFIX  = 'source.php?sid=';
25
26    /**
27     * Each object type may have its own special rules, and re-implement this function.
28     *
29     * @param int $access_level
30     *
31     * @return bool
32     */
33    protected function canShowByType($access_level)
34    {
35        // Hide sources if they are attached to private repositories ...
36        preg_match_all('/\n1 REPO @(.+)@/', $this->gedcom, $matches);
37        foreach ($matches[1] as $match) {
38            $repo = Repository::getInstance($match, $this->tree);
39            if ($repo && !$repo->canShow($access_level)) {
40                return false;
41            }
42        }
43
44        // ... otherwise apply default behaviour
45        return parent::canShowByType($access_level);
46    }
47
48    /**
49     * Generate a private version of this record
50     *
51     * @param int $access_level
52     *
53     * @return string
54     */
55    protected function createPrivateGedcomRecord($access_level)
56    {
57        return '0 @' . $this->xref . "@ SOUR\n1 TITL " . I18N::translate('Private');
58    }
59
60    /**
61     * Fetch data from the database
62     *
63     * @param string $xref
64     * @param int    $tree_id
65     *
66     * @return null|string
67     */
68    protected static function fetchGedcomRecord($xref, $tree_id)
69    {
70        return Database::prepare(
71            "SELECT s_gedcom FROM `##sources` WHERE s_id = :xref AND s_file = :tree_id"
72        )->execute(array(
73            'xref'    => $xref,
74            'tree_id' => $tree_id,
75        ))->fetchOne();
76    }
77
78    /**
79     * Extract names from the GEDCOM record.
80     */
81    public function extractNames()
82    {
83        parent::extractNamesFromFacts(1, 'TITL', $this->getFacts('TITL'));
84    }
85}
86