.
*/
declare(strict_types=1);
namespace Fisharebest\Webtrees;
use Closure;
use Exception;
use Fisharebest\Webtrees\Functions\FunctionsPrint;
use Fisharebest\Webtrees\Http\RequestHandlers\GedcomRecordPage;
use Fisharebest\Webtrees\Services\PendingChangesService;
use Illuminate\Database\Capsule\Manager as DB;
use Illuminate\Database\Query\Builder;
use Illuminate\Database\Query\Expression;
use Illuminate\Database\Query\JoinClause;
use Illuminate\Support\Collection;
use Throwable;
use Transliterator;
use function addcslashes;
use function app;
use function array_shift;
use function assert;
use function count;
use function date;
use function e;
use function explode;
use function in_array;
use function md5;
use function preg_match;
use function preg_match_all;
use function preg_replace;
use function preg_replace_callback;
use function preg_split;
use function route;
use function str_pad;
use function strip_tags;
use function strpos;
use function strtoupper;
use function trim;
use const PREG_SET_ORDER;
use const STR_PAD_LEFT;
/**
* A GEDCOM object.
*/
class GedcomRecord
{
public const RECORD_TYPE = 'UNKNOWN';
protected const ROUTE_NAME = GedcomRecordPage::class;
/** @var string The record identifier */
protected $xref;
/** @var Tree The family tree to which this record belongs */
protected $tree;
/** @var string GEDCOM data (before any pending edits) */
protected $gedcom;
/** @var string|null GEDCOM data (after any pending edits) */
protected $pending;
/** @var Fact[] facts extracted from $gedcom/$pending */
protected $facts;
/** @var string[][] All the names of this individual */
protected $getAllNames;
/** @var int|null Cached result */
protected $getPrimaryName;
/** @var int|null Cached result */
protected $getSecondaryName;
/**
* Create a GedcomRecord object from raw GEDCOM data.
*
* @param string $xref
* @param string $gedcom an empty string for new/pending records
* @param string|null $pending null for a record with no pending edits,
* empty string for records with pending deletions
* @param Tree $tree
*/
public function __construct(string $xref, string $gedcom, ?string $pending, Tree $tree)
{
$this->xref = $xref;
$this->gedcom = $gedcom;
$this->pending = $pending;
$this->tree = $tree;
$this->parseFacts();
}
/**
* A closure which will create a record from a database row.
*
* @deprecated since 2.0.4. Will be removed in 2.1.0 - Use Factory::gedcomRecord()
*
* @param Tree $tree
*
* @return Closure
*/
public static function rowMapper(Tree $tree): Closure
{
return Factory::gedcomRecord()->mapper($tree);
}
/**
* A closure which will filter out private records.
*
* @return Closure
*/
public static function accessFilter(): Closure
{
return static function (GedcomRecord $record): bool {
return $record->canShow();
};
}
/**
* A closure which will compare records by name.
*
* @return Closure
*/
public static function nameComparator(): Closure
{
return static function (GedcomRecord $x, GedcomRecord $y): int {
if ($x->canShowName()) {
if ($y->canShowName()) {
return I18N::strcasecmp($x->sortName(), $y->sortName());
}
return -1; // only $y is private
}
if ($y->canShowName()) {
return 1; // only $x is private
}
return 0; // both $x and $y private
};
}
/**
* A closure which will compare records by change time.
*
* @param int $direction +1 to sort ascending, -1 to sort descending
*
* @return Closure
*/
public static function lastChangeComparator(int $direction = 1): Closure
{
return static function (GedcomRecord $x, GedcomRecord $y) use ($direction): int {
return $direction * ($x->lastChangeTimestamp() <=> $y->lastChangeTimestamp());
};
}
/**
* Get an instance of a GedcomRecord object. For single records,
* we just receive the XREF. For bulk records (such as lists
* and search results) we can receive the GEDCOM data as well.
*
* @deprecated since 2.0.4. Will be removed in 2.1.0 - Use Factory::gedcomRecord()
*
* @param string $xref
* @param Tree $tree
* @param string|null $gedcom
*
* @return GedcomRecord|Individual|Family|Source|Repository|Media|Note|Submitter|null
*/
public static function getInstance(string $xref, Tree $tree, string $gedcom = null)
{
return Factory::gedcomRecord()->make($xref, $tree, $gedcom);
}
/**
* Get the GEDCOM tag for this record.
*
* @return string
*/
public function tag(): string
{
preg_match('/^0 @[^@]*@ (\w+)/', $this->gedcom(), $match);
return $match[1] ?? static::RECORD_TYPE;
}
/**
* Get the XREF for this record
*
* @return string
*/
public function xref(): string
{
return $this->xref;
}
/**
* Get the tree to which this record belongs
*
* @return Tree
*/
public function tree(): Tree
{
return $this->tree;
}
/**
* Application code should access data via Fact objects.
* This function exists to support old code.
*
* @return string
*/
public function gedcom(): string
{
return $this->pending ?? $this->gedcom;
}
/**
* Does this record have a pending change?
*
* @return bool
*/
public function isPendingAddition(): bool
{
return $this->pending !== null;
}
/**
* Does this record have a pending deletion?
*
* @return bool
*/
public function isPendingDeletion(): bool
{
return $this->pending === '';
}
/**
* Generate a "slug" to use in pretty URLs.
*
* @return string
*/
public function slug(): string
{
$slug = strip_tags($this->fullName());
try {
$transliterator = Transliterator::create('Any-Latin;Latin-ASCII');
$slug = $transliterator->transliterate($slug);
} catch (Throwable $ex) {
// ext-intl not installed?
// Transliteration algorithms not present in lib-icu?
}
$slug = preg_replace('/[^A-Za-z0-9]+/', '-', $slug);
return trim($slug, '-') ?: '-';
}
/**
* Generate a URL to this record.
*
* @return string
*/
public function url(): string
{
return route(static::ROUTE_NAME, [
'xref' => $this->xref(),
'tree' => $this->tree->name(),
'slug' => $this->slug(),
]);
}
/**
* Can the details of this record be shown?
*
* @param int|null $access_level
*
* @return bool
*/
public function canShow(int $access_level = null): bool
{
$access_level = $access_level ?? Auth::accessLevel($this->tree);
// We use this value to bypass privacy checks. For example,
// when downloading data or when calculating privacy itself.
if ($access_level === Auth::PRIV_HIDE) {
return true;
}
$cache_key = 'show-' . $this->xref . '-' . $this->tree->id() . '-' . $access_level;
return app('cache.array')->remember($cache_key, function () use ($access_level) {
return $this->canShowRecord($access_level);
});
}
/**
* Can the name of this record be shown?
*
* @param int|null $access_level
*
* @return bool
*/
public function canShowName(int $access_level = null): bool
{
return $this->canShow($access_level);
}
/**
* Can we edit this record?
*
* @return bool
*/
public function canEdit(): bool
{
if ($this->isPendingDeletion()) {
return false;
}
if (Auth::isManager($this->tree)) {
return true;
}
return Auth::isEditor($this->tree) && strpos($this->gedcom, "\n1 RESN locked") === false;
}
/**
* Remove private data from the raw gedcom record.
* Return both the visible and invisible data. We need the invisible data when editing.
*
* @param int $access_level
*
* @return string
*/
public function privatizeGedcom(int $access_level): string
{
if ($access_level === Auth::PRIV_HIDE) {
// We may need the original record, for example when downloading a GEDCOM or clippings cart
return $this->gedcom;
}
if ($this->canShow($access_level)) {
// The record is not private, but the individual facts may be.
// Include the entire first line (for NOTE records)
[$gedrec] = explode("\n", $this->gedcom . $this->pending, 2);
// Check each of the facts for access
foreach ($this->facts([], false, $access_level) as $fact) {
$gedrec .= "\n" . $fact->gedcom();
}
return $gedrec;
}
// We cannot display the details, but we may be able to display
// limited data, such as links to other records.
return $this->createPrivateGedcomRecord($access_level);
}
/**
* Default for "other" object types
*
* @return void
*/
public function extractNames(): void
{
$this->addName(static::RECORD_TYPE, $this->getFallBackName(), '');
}
/**
* Derived classes should redefine this function, otherwise the object will have no name
*
* @return string[][]
*/
public function getAllNames(): array
{
if ($this->getAllNames === null) {
$this->getAllNames = [];
if ($this->canShowName()) {
// Ask the record to extract its names
$this->extractNames();
// No name found? Use a fallback.
if (!$this->getAllNames) {
$this->addName(static::RECORD_TYPE, $this->getFallBackName(), '');
}
} else {
$this->addName(static::RECORD_TYPE, I18N::translate('Private'), '');
}
}
return $this->getAllNames;
}
/**
* If this object has no name, what do we call it?
*
* @return string
*/
public function getFallBackName(): string
{
return e($this->xref());
}
/**
* Which of the (possibly several) names of this record is the primary one.
*
* @return int
*/
public function getPrimaryName(): int
{
static $language_script;
if ($language_script === null) {
$language_script = $language_script ?? I18N::locale()->script()->code();
}
if ($this->getPrimaryName === null) {
// Generally, the first name is the primary one....
$this->getPrimaryName = 0;
// ...except when the language/name use different character sets
foreach ($this->getAllNames() as $n => $name) {
if (I18N::textScript($name['sort']) === $language_script) {
$this->getPrimaryName = $n;
break;
}
}
}
return $this->getPrimaryName;
}
/**
* Which of the (possibly several) names of this record is the secondary one.
*
* @return int
*/
public function getSecondaryName(): int
{
if ($this->getSecondaryName === null) {
// Generally, the primary and secondary names are the same
$this->getSecondaryName = $this->getPrimaryName();
// ....except when there are names with different character sets
$all_names = $this->getAllNames();
if (count($all_names) > 1) {
$primary_script = I18N::textScript($all_names[$this->getPrimaryName()]['sort']);
foreach ($all_names as $n => $name) {
if ($n !== $this->getPrimaryName() && $name['type'] !== '_MARNM' && I18N::textScript($name['sort']) !== $primary_script) {
$this->getSecondaryName = $n;
break;
}
}
}
}
return $this->getSecondaryName;
}
/**
* Allow the choice of primary name to be overidden, e.g. in a search result
*
* @param int|null $n
*
* @return void
*/
public function setPrimaryName(int $n = null): void
{
$this->getPrimaryName = $n;
$this->getSecondaryName = null;
}
/**
* Allow native PHP functions such as array_unique() to work with objects
*
* @return string
*/
public function __toString()
{
return $this->xref . '@' . $this->tree->id();
}
/**
* /**
* Get variants of the name
*
* @return string
*/
public function fullName(): string
{
if ($this->canShowName()) {
$tmp = $this->getAllNames();
return $tmp[$this->getPrimaryName()]['full'];
}
return I18N::translate('Private');
}
/**
* Get a sortable version of the name. Do not display this!
*
* @return string
*/
public function sortName(): string
{
// The sortable name is never displayed, no need to call canShowName()
$tmp = $this->getAllNames();
return $tmp[$this->getPrimaryName()]['sort'];
}
/**
* Get the full name in an alternative character set
*
* @return string|null
*/
public function alternateName(): ?string
{
if ($this->canShowName() && $this->getPrimaryName() !== $this->getSecondaryName()) {
$all_names = $this->getAllNames();
return $all_names[$this->getSecondaryName()]['full'];
}
return null;
}
/**
* Format this object for display in a list
*
* @return string
*/
public function formatList(): string
{
$html = '';
$html .= '' . $this->fullName() . '';
$html .= $this->formatListDetails();
$html .= '';
return $html;
}
/**
* This function should be redefined in derived classes to show any major
* identifying characteristics of this record.
*
* @return string
*/
public function formatListDetails(): string
{
return '';
}
/**
* Extract/format the first fact from a list of facts.
*
* @param string[] $facts
* @param int $style
*
* @return string
*/
public function formatFirstMajorFact(array $facts, int $style): string
{
foreach ($this->facts($facts, true) as $event) {
// Only display if it has a date or place (or both)
if ($event->date()->isOK() && $event->place()->gedcomName() !== '') {
$joiner = ' — ';
} else {
$joiner = '';
}
if ($event->date()->isOK() || $event->place()->gedcomName() !== '') {
switch ($style) {
case 1:
return '
' . $event->label() . ' ' . FunctionsPrint::formatFactDate($event, $this, false, false) . $joiner . FunctionsPrint::formatFactPlace($event) . '';
case 2:
return '