Generate a new XREF, unique across all family trees

@return string
493641
public function getNewXref(): string
    {
        // Lock the row, so that only one new XREF may be generated at a time.
        DB::table('site_setting')
            ->where('setting_name', '=', 'next_xref')
            ->lockForUpdate()
            ->get();

        $prefix = 'X';

        $increment = 1.0;
        do {
            $num = (int) Site::getPreference('next_xref') + (int) $increment;

            // This exponential increment allows us to scan over large blocks of
            // existing data in a reasonable time.
            $increment *= 1.01;

            $xref = $prefix . $num;

            // Records may already exist with this sequence number.
            $already_used =
                DB::table('individuals')->where('i_id', '=', $xref)->exists() ||
                DB::table('families')->where('f_id', '=', $xref)->exists() ||
                DB::table('sources')->where('s_id', '=', $xref)->exists() ||
                DB::table('media')->where('m_id', '=', $xref)->exists() ||
                DB::table('other')->where('o_id', '=', $xref)->exists() ||
                DB::table('change')->where('xref', '=', $xref)->exists();
        } while ($already_used);

        Site::setPreference('next_xref', (string) $num);

        return $xref;
    }
1079483
protected function resolveXRef($name)
    {
        if (($obj = $this->elements[$name]) instanceof ElementXRef && !is_null($this->document)) {
            /** @var ElementXRef $obj */
            $object = $this->document->getObjectById($obj->getId());

            if (is_null($object)) {
                return new ElementMissing(null, null);
            }

            // Update elements list for future calls.
            $this->elements[$name] = $object;
        }

        return $this->elements[$name];
    }
1252283
public function generar()
    {
        // si ya se había generado se entrega directamente
        if ($this->xml_data)
            return $this->xml_data;
        // generar XML del envío
        $xmlEnvio = (new \sasco\LibreDTE\XML())->generate([
            'ConsumoFolios' => [
                '@attributes' => [
                    'xmlns' => 'http://www.sii.cl/SiiDte',
                    'xmlns:xsi' => 'http://www.w3.org/2001/XMLSchema-instance',
                    'xsi:schemaLocation' => 'http://www.sii.cl/SiiDte ConsumoFolio_v10.xsd',
                    'version' => '1.0',
                ],
                'DocumentoConsumoFolios' => [
                    '@attributes' => [
                        'ID' => $this->id,
                    ],
                    'Caratula' => $this->caratula,
                    'Resumen' => $this->getResumen(),
                ],
            ]
        ])->saveXML();
        // firmar XML del envío y entregar
        $this->xml_data = $this->Firma ? $this->Firma->signXML($xmlEnvio, '#'.$this->id, 'DocumentoConsumoFolios', true) : $xmlEnvio;
        return $this->xml_data;
    }
964498
public function getUniqueReference()
    {
        if ($this->uniqueReference === null) {
            $modelName = basename(str_replace("\\", "/", $this->getModelClassName()));

            if (!isset(self::$uniqueReferencesUsed[$modelName])) {
                self::$uniqueReferencesUsed[$modelName] = 0;
            }

            self::$uniqueReferencesUsed[$modelName]++;

            $this->uniqueReference = $modelName . (self::$uniqueReferencesUsed[$modelName] > 1 ? self::$uniqueReferencesUsed[$modelName] : "");
        }

        return $this->uniqueReference;
    }
1057297
public static function getIntance($xref, Tree $tree, $gedcom = null){
		$dfam = null;
		$fam = fw\Family::getInstance($xref, $tree, $gedcom);
		if($fam){
			$dfam = new Family($fam);
		}
		return $dfam;
	}
171590
public function copy(){
        $copy = parent::copy();
        $copy->delimiter = $this->delimiter;
        $copy->prefix = $this->prefix;
        $copy->suffix = $this->suffix;
        return $copy;
    }
548118
private function allAncestors($xref1, $xref2, $tree_id): array
    {
        $ancestors = [
            $xref1,
            $xref2,
        ];

        $queue = [
            $xref1,
            $xref2,
        ];
        while (!empty($queue)) {
            $parents = DB::table('link AS l1')
                ->join('link AS l2', static function (JoinClause $join): void {
                    $join
                        ->on('l1.l_to', '=', 'l2.l_to')
                        ->on('l1.l_file', '=', 'l2.l_file');
                })
                ->where('l1.l_file', '=', $tree_id)
                ->where('l1.l_type', '=', 'FAMC')
                ->where('l2.l_type', '=', 'FAMS')
                ->whereIn('l1.l_from', $queue)
                ->pluck('l2.l_from');

            $queue = [];
            foreach ($parents as $parent) {
                if (!in_array($parent, $ancestors, true)) {
                    $ancestors[] = $parent;
                    $queue[]     = $parent;
                }
            }
        }

        return $ancestors;
    }
202791
private function createRawXmlDocument()
    {
        $xmlDocument = new \DOMDocument;
        $xmlDocument->encoding = 'UTF-8';
        $xmlDocument->strictErrorChecking = false;
        $xmlDocument->formatOutput = true;
        $libXmlState = libxml_use_internal_errors(true);
        $xmlDocument->loadHTML($this->getUnifiedHtml());
        libxml_clear_errors();
        libxml_use_internal_errors($libXmlState);
        $xmlDocument->normalizeDocument();

        return $xmlDocument;
    }
842056
function createXprop() {
    if( 'xcal' == $this->format )
      return false;
    if( 0 >= count( $this->xprop ))
      return;
    $xprop = null;
    $toolbox = new calendarComponent();
    $toolbox->setConfig( 'language', $this->getConfig( 'language' ));
    $toolbox->setConfig( 'nl',       $this->getConfig( 'nl' ));
    $toolbox->_createFormat(         $this->getConfig( 'format' ));
    foreach( $this->xprop as $label => $xpropPart ) {
      $attributes = $toolbox->_createParams( $xpropPart['params'], array( 'LANGUAGE' ));
      if( is_array( $xpropPart['value'] )) {
        foreach( $xpropPart['value'] as $pix => $theXpart )
          $xpropPart['value'][$pix] = $toolbox->_strrep( $theXpart );
        $xpropPart['value']  = implode( ',', $xpropPart['value'] );
      }
      else
        $xpropPart['value'] = $toolbox->_strrep( $xpropPart['value'] );
      $xprop   .= $toolbox->_createElement( strtoupper( $label ), $attributes, $xpropPart['value'] );
    }
    return $xprop;
  }
1361184
protected function decodeXref($startxref, $xref=array()) {
        $this->xref_seen_offsets[] = $startxref;
        if (!isset($xref['xref_location'])) {
            $xref['xref_location'] = $startxref;
            $xref['max_object'] = 0;
        }
        // extract xref data (object indexes and offsets)
        $xoffset = $startxref + 5;
        // initialize object number
        $obj_num = 0;
        $offset = $xoffset;
        while (preg_match('/^([0-9]+)[\s]([0-9]+)[\s]?([nf]?)/im', $this->pdfdata, $matches, PREG_OFFSET_CAPTURE, $offset) > 0) {
            $offset = (strlen($matches[0][0]) + $matches[0][1]);
            if ($matches[3][0] == 'n') {
                // create unique object index: [object number]_[generation number]
                $gen_num = intval($matches[2][0]);
                $index = $obj_num.'_'.$gen_num;
                // check if object already exist
                if (!isset($xref['xref'][$obj_num][$gen_num])) {
                    // store object offset position
                    $xref['xref'][$obj_num][$gen_num] = intval($matches[1][0]);
                }
                ++$obj_num;
                $offset += 2;
            } elseif ($matches[3][0] == 'f') {
                ++$obj_num;
                $offset += 2;
            } else {
                // object number (index)
                $obj_num = intval($matches[1][0]);
            }
        }
        unset($matches);
        $xref['max_object'] = max($xref['max_object'], $obj_num);
        // get trailer data
        if (preg_match('/trailer[\s]*<<(.*)>>[\s\r\n]+(?:[%].*[\r\n]+)*startxref[\s\r\n]+/isU', $this->pdfdata, $matches, PREG_OFFSET_CAPTURE, $xoffset) > 0) {
            $trailer_data = $matches[1][0];
            if (!isset($xref['trailer']) OR empty($xref['trailer'])) {
                // get only the last updated version
                $xref['trailer'] = array();
                $xref['trailer'][0] = PDF_TYPE_DICTIONARY;
                $xref['trailer'][1] = array();
                // parse trailer_data
                if (preg_match('/Size[\s]+([0-9]+)/i', $trailer_data, $matches) > 0) {
                    $xref['trailer'][1]['/Size'] = array(PDF_TYPE_NUMERIC, intval($matches[1]));
                }
                if (preg_match('/Root[\s]+([0-9]+)[\s]+([0-9]+)[\s]+R/i', $trailer_data, $matches) > 0) {
                    $xref['trailer'][1]['/Root'] = array(PDF_TYPE_OBJREF, intval($matches[1]), intval($matches[2]));
                }
                if (preg_match('/Encrypt[\s]+([0-9]+)[\s]+([0-9]+)[\s]+R/i', $trailer_data, $matches) > 0) {
                    $xref['trailer'][1]['/Encrypt'] = array(PDF_TYPE_OBJREF, intval($matches[1]), intval($matches[2]));
                }
                if (preg_match('/Info[\s]+([0-9]+)[\s]+([0-9]+)[\s]+R/i', $trailer_data, $matches) > 0) {
                    $xref['trailer'][1]['/Info'] = array(PDF_TYPE_OBJREF, intval($matches[1]), intval($matches[2]));
                }
                if (preg_match('/ID[\s]*[\[][\s]*[<]([^>]*)[>][\s]*[<]([^>]*)[>]/i', $trailer_data, $matches) > 0) {
                    $xref['trailer'][1]['/ID'] = array(PDF_TYPE_ARRAY, array());
                    $xref['trailer'][1]['/ID'][1][0] = array(PDF_TYPE_HEX, $matches[1]);
                    $xref['trailer'][1]['/ID'][1][1] = array(PDF_TYPE_HEX, $matches[2]);
                }
            }
            if (preg_match('/Prev[\s]+([0-9]+)/i', $trailer_data, $matches) > 0) {
                // get previous xref
                $prevoffset = intval($matches[1]);
                if (!in_array($prevoffset, $this->xref_seen_offsets)) {
                    $this->xref_seen_offsets[] = $prevoffset;
                    $xref = $this->getXrefData($prevoffset, $xref);
                }
            }
            unset($matches);
        } else {
            $this->Error('Unable to find trailer');
        }
        return $xref;
    }
594280
public function renderCreateIndexes()
    {
        $indexes = $this->getTableIndexes();
        if (!$indexes) {
            return '';
        }
        $source = '';
        foreach ($indexes as $index) {
            $columns = $this->serializeArrayToAttributes($index->getColumns());
            $name    = $this->serializeIndexNameToAttribute($index->getName());
            if ($index->isPrimary()) {
                $source .= "\n" . '$table->primary(' . $columns . ', ' . $name . ');';
            } elseif ($index->isUnique()) {
                $source .= "\n" . '$table->unique(' . $columns . ', ' . $name . ');';
            } else {
                $source .= "\n" . '$table->index(' . $columns . ', ' . $name . ');';
            }
        }

        return trim($source);
    }
564859
function deep_copy() {
    $frame = new Frame($this->get_node()->cloneNode());
    $frame->set_style(clone $this->_frame->get_original_style());
    $deco = Frame_Factory::decorate_frame($frame, $this->_dompdf);
    $deco->set_root($this->_root);

    foreach ($this->get_children() as $child)
      $deco->append_child($child->deep_copy());

    return $deco;
  }
1286808
public function unique()
    {
        $count = count($this->sfa);
        $unique = new SplFixedArray($count);
        $newCount = 0;
        $lastUnique = null;

        foreach ($this->sfa as $el) {
            for($i = $newCount; $i >= 0; $i--) {
                // going from back to forward to find sequence of duplicates faster
                if ($unique[$i] === $el) {
                    continue 2;
                }
            }
            $unique[$newCount++] = $el;
        }

        $unique->setSize($newCount);
        return new static($unique);
    }
613654
public function buildLineages() {				
		$indis = \Fisharebest\Webtrees\Query\QueryName::individuals($this->tree, $this->surname, null, null, false, false);
		
		if(count($indis) == 0) return null;
		
		$root_lineages = array();
		
		foreach($indis as $indi) {
			$pid = $indi->getXref();
			if(!isset($this->used_indis[$pid])){
				//Find the root of the lineage
				/** @var Fisharebest\Webtrees\Individual $indiFirst  */
				$indiFirst= $this->getLineageRootIndividual($indi);
				if($indiFirst){
					$this->used_indis[$indiFirst->getXref()] = true;
					if($indiFirst->canShow()){
						//Check if the root individual has brothers and sisters, without parents
						$indiChildFamily = $indiFirst->getPrimaryChildFamily();
						if($indiChildFamily !== null){
							$root_node = new LineageRootNode(null); 
							$root_node->addFamily($indiChildFamily);
						}
						else{
							$root_node = new LineageRootNode($indiFirst);
						}
						$root_node = $this->buildLineage($root_node);		
						if($root_node) $root_lineages[] = $root_node;
					}
				}
			}
		}
		
		return $root_lineages;		
	}
1268707
protected function buildXmlStructure()
	{
		$buffer = array();

		foreach ($this->from as $table)
		{
			// Replace the magic prefix if found.
			$table = $this->getGenericTableName($table);

			// Get the details columns information.
			$fields = $this->db->getTableColumns($table, false);
			$keys   = $this->db->getTableKeys($table);

			$buffer[] = '  <table_structure name="' . $table . '">';

			foreach ($fields as $field)
			{
				$buffer[] = '   <field Field="' . $field->Field . '" Type="' . $field->Type . '" Null="' . $field->Null . '" Key="' .
					$field->Key . '"' . (isset($field->Default) ? ' Default="' . $field->Default . '"' : '') . ' Extra="' . $field->Extra . '"' .
					' />';
			}

			foreach ($keys as $key)
			{
				$buffer[] = '   <key Table="' . $table . '" Non_unique="' . $key->Non_unique . '" Key_name="' . $key->Key_name . '"' .
					' Seq_in_index="' . $key->Seq_in_index . '" Column_name="' . $key->Column_name . '" Collation="' . $key->Collation . '"' .
					' Null="' . $key->Null . '" Index_type="' . $key->Index_type . '"' .
					' Comment="' . htmlspecialchars($key->Comment, ENT_COMPAT, 'UTF-8') . '"' .
					' />';
			}

			$buffer[] = '  </table_structure>';
		}

		return $buffer;
	}
115409
public function readableInfo() {
        $o = '';
        // type
        $o .= $this->getXMLDBKeyName($this->type);
        // fields
        $o .= ' (' . implode(', ', $this->fields) . ')';
        // foreign key
        if ($this->type == XMLDB_KEY_FOREIGN ||
            $this->type == XMLDB_KEY_FOREIGN_UNIQUE) {
            $o .= ' references ' . $this->reftable . ' (' . implode(', ', $this->reffields) . ')';
        }

        return $o;
    }
1069416
private function generateCacheFile()
    {
        $previousErrorSetting = libxml_use_internal_errors(true);
        libxml_clear_errors();
        if (@$this->domDocument->schemaValidate($this->xmlSchemaFile)) {
            $this->domDocument->preserveWhiteSpace = false;
            // Reload the XML to strip whitespace from XIncluded XML.
            $this->domDocument->loadXML($this->domDocument->saveXML());

            $xslDocument = new DOMDocument('1.0', 'UTF-8');
            $xslDocument->load(__DIR__.'/Resources/xsl/flexmodel-cache.xsl');

            $processor = new XSLTProcessor();
            $processor->setParameter('', 'checksum', md5($this->domDocument->saveXML()));
            $processor->importStyleSheet($xslDocument);
            $processor->registerPHPFunctions();

            $configuration = $processor->transformToXML($this->domDocument);
            file_put_contents($this->getCacheFile(), $configuration);

            $this->loadConfiguration(false);
        } else {
            $errors = libxml_get_errors();
            foreach ($errors as $error) {
                trigger_error(sprintf('Line %s: %s in "%s"', $error->line, trim($error->message), $error->file), E_USER_WARNING);
            }
            libxml_clear_errors();
        }
        libxml_use_internal_errors($previousErrorSetting);
    }