Returns a DataList of all previous Versions of a document (check the
LastEdited date of each object to find the correct one).

@static
@param DMSDocument $doc

@return DataList List of Document objects
325724
public static function get_versions(DMSDocument $doc)
    {
        if (!DMSDocument_versions::$enable_versions) {
            user_error("DMSDocument versions are disabled", E_USER_WARNING);
        }
        return DMSDocument_versions::get()->filter(array('DocumentID' => $doc->ID));
    }
194989
protected function getDefaultSchemaList(ServerDoc $doc) : array
    {
        $propertyList = [
            'code' => [
                'type' => 'integer',
            ],
        ];

        $errorList = array_merge($doc->getServerErrorList(), $doc->getGlobalErrorList());
        $errorList = array_reduce(
            array_map(
                function (MethodDoc $methodDoc) {
                    return $methodDoc->getCustomErrorList();
                },
                $doc->getMethodList()
            ),
            function (array $carry, array $subErrorList) {
                $carry = array_merge($carry, $subErrorList);

                return $carry;
            },
            $errorList
        );
        $codeList = array_unique(
            array_map(
                function (ErrorDoc $errorDoc) {
                    return $errorDoc->getCode();
                },
                $errorList
            )
        );

        if (count($codeList) > 0) {
            $propertyList['code']['enum'] = array_values($codeList);
        }

        return [
            'Default-Error' => [
                'allOf' => [
                    $this->shapeNormalizer->getErrorShapeDefinition(),
                    [
                        'type' => 'object',
                        'properties' => $propertyList,
                    ],
                ],
            ],
        ];
    }
1236000
public function references($document)
    {
        if ($this->currentField) {
            $mapping = $this->class->getFieldMapping($this->currentField);
            $dbRef = $this->dm->createDBRef($document, $mapping);

            if (isset($mapping['simple']) && $mapping['simple']) {
                $this->query[$mapping['name']] = $dbRef;
            } else {
                $keys = array('ref' => true, 'id' => true, 'db' => true);

                if (isset($mapping['targetDocument'])) {
                    unset($keys['ref'], $keys['db']);
                }

                foreach ($keys as $key => $value) {
                    $this->query[$this->currentField . '.$' . $key] = $dbRef['$' . $key];
                }
            }
        } else {
            $dbRef = $this->dm->createDBRef($document);
            $this->query = $dbRef;
        }

        return $this;
    }
1044796
public static function document($doc)
    {
        $type = 1;
        $valid = self::cpf($doc);
        if ($valid == false) {
            $type = 2;
            $valid = self::cnpj($doc);
        }
        if ($valid == false) {
            return false;
        }
        return ['type' => $type, 'valid' => $valid];
    }
521725
public function replaceMultiple($docs) {
		$request = new CPS_ReplaceRequest($docs);
		$this->_lastResponse = $this->_connection->sendRequest($request);
		return count($this->_lastResponse->getModifiedIds());
	}
263577
public function getDocumentChangeSet($document)
    {
        $oid = spl_object_hash($document);
        if (isset($this->documentChangeSets[$oid])) {
            return $this->documentChangeSets[$oid];
        }
        return array();
    }
393394
private function manageEditDocumentStoreProperties(&$params, &$dmsLoader, &$manageCategory, &$arrMessages, &$blnShowStart, $documentId)
  {
    $params->loadRootCategory = true; // get complete path to root, for checking inherited access rights
    $params->loadAccessRights = true;
    $params->loadDocuments = false;
    $category = $dmsLoader->loadCategory($manageCategory, $params);
    
    if (!$category->isEditableForCurrentMember())
    {
      $arrMessages['errors'][] = $GLOBALS['TL_LANG']['DMS']['ERR']['manage_document_not_allowed'];
      $blnShowStart = true;
    }
    else
    {
      $document = $dmsLoader->loadDocument($documentId, $params);
      $documentOriginal = clone $document;
      
      // load existing documents for file name
      $params->loadCategory = true; // need the category of existing documents
      $arrDocuments = $dmsLoader->loadDocuments($document->fileName, $document->fileType, $params);
      $params->loadCategory = false;
      
      $existingDocuments = array();
      foreach ($arrDocuments as $existingDocument)
      {
        if ($existingDocument->id != $documentId)
        {
          $existingDocuments[] = $existingDocument;
        }
      }
      
      $documentVersionMajor = $this->Input->post('documentVersionMajor');
      $documentVersionMinor = $this->Input->post('documentVersionMinor');
      $documentVersionPatch = $this->Input->post('documentVersionPatch');
      
      $document->name = $this->Input->post('documentName');
      $document->description = $this->Input->post('documentDescription');
      $document->keywords = $this->Input->post('documentKeywords');
      $document->versionMajor = $documentVersionMajor;
      $document->versionMinor = $documentVersionMinor;
      $document->versionPatch = $documentVersionPatch;
      $document->lasteditMemberId = $this->Member->id;
      $document->lasteditDate = time();
      if ($category->isPublishableForCurrentMember())
      {
        $document->published = (bool) $this->Input->post('documentPublish');
      }
      
      $versionChanged = false;
      if ($documentVersionMajor != $documentOriginal->versionMajor ||
        $documentVersionMinor != $documentOriginal->versionMinor ||
        $documentVersionPatch != $documentOriginal->versionPatch)
      {
        $versionChanged = true;
      }
      
      if (strlen($document->name) == 0)
      {
        $arrMessages['errors'][] = $GLOBALS['TL_LANG']['DMS']['ERR']['edit_no_name_set'];
        $document->name = $documentOriginal->name;
      }
      if ($versionChanged)
      {
        if (strlen($documentVersionMajor) == 0 || !is_numeric($documentVersionMajor) ||
          strlen($documentVersionMinor) == 0 || !is_numeric($documentVersionMinor) ||
          strlen($documentVersionPatch) == 0 || !is_numeric($documentVersionPatch))
        {
          $document->versionMajor = $documentOriginal->versionMajor;
          $document->versionMinor = $documentOriginal->versionMinor;
          $document->versionPatch = $documentOriginal->versionPatch;
          $arrMessages['errors'][] = $GLOBALS['TL_LANG']['DMS']['ERR']['edit_no_version_set'];
        }
        
        foreach ($existingDocuments as $existingDocument)
        {
          // will be true, if one is true (keep true status, if once set)
          if ($existingDocument->versionMajor == $documentVersionMajor &&
            $existingDocument->versionMinor == $documentVersionMinor &&
            $existingDocument->versionPatch == $documentVersionPatch)
          {
            $document->versionMajor = $documentOriginal->versionMajor;
            $document->versionMinor = $documentOriginal->versionMinor;
            $document->versionPatch = $documentOriginal->versionPatch;
            $arrMessages['errors'][] = $GLOBALS['TL_LANG']['DMS']['ERR']['edit_version_already_used'];
          }
        }
      }
      
      // HOOK: verify the edited document from frontend
      if (isset($GLOBALS['TL_HOOKS']['dmsVerifyEditedDocument']) && is_array($GLOBALS['TL_HOOKS']['dmsVerifyEditedDocument']))
      {
        foreach ($GLOBALS['TL_HOOKS']['dmsVerifyEditedDocument'] as $callback)
        {
          $this->import($callback[0]);
          $arrMessages = $this->{$callback[0]}->{$callback[1]}($arrMessages, $existingDocuments, $this->Input);
        }
      }
      
      if (count($arrMessages['errors']) > 0)
      {
        $this->Template = new \FrontendTemplate("mod_dms_mgmt_manage_document_edit");
        $this->Template->setData($this->arrData);
      }
      else
      {
        // HOOK: modify the edited document from frontend
        if (isset($GLOBALS['TL_HOOKS']['dmsModifyEditedDocument']) && is_array($GLOBALS['TL_HOOKS']['dmsModifyEditedDocument']))
        {
          foreach ($GLOBALS['TL_HOOKS']['dmsModifyEditedDocument'] as $callback)
          {
            $this->import($callback[0]);
            $document = $this->{$callback[0]}->{$callback[1]}($document, $this->Input);
          }
        }

        // update document
        $dmsWriter = \DmsWriter::getInstance();
        $document = $dmsWriter->updateDocument($document);
        
        $arrMessages['successes'][] = $GLOBALS['TL_LANG']['DMS']['SUCCESS']['document_successfully_edited'];
        
        // rename the file if the version changed
        if ($versionChanged)
        {
          $filePath = \DmsConfig::getDocumentFilePath($documentOriginal->getFileNameVersioned());
          if (file_exists(TL_ROOT . '/' . $filePath))
          {
            rename($filePath, \DmsConfig::getDocumentFilePath($document->getFileNameVersioned()));
            $arrMessages['successes'][] = $GLOBALS['TL_LANG']['DMS']['SUCCESS']['document_file_successfully_renamed'];
          }
          else
          {
            $arrMessages['errors'][] = $GLOBALS['TL_LANG']['DMS']['ERR']['edit_file_not_exists'];
          }
        }
        
        $this->Template = new \FrontendTemplate("mod_dms_mgmt_manage_document_edit_processed");
        $this->Template->setData($this->arrData);
      }
      
      $this->Template->category = $category;
      $this->Template->document = $document;
      $this->Template->existingDocuments = $existingDocuments;
      
      $blnShowStart = false;
    }
  }
1174455
public function prepareUpdateData($document)
    {
        $class = $this->dm->getClassMetadata(get_class($document));
        $changeset = $this->uow->getDocumentChangeSet($document);

        $updateData = array();
        foreach ($changeset as $fieldName => $change) {
            $mapping = $class->fieldMappings[$fieldName];

            // skip non embedded document identifiers
            if ( ! $class->isEmbeddedDocument && ! empty($mapping['id'])) {
                continue;
            }

            list($old, $new) = $change;

            // @Inc
            if ($mapping['type'] === 'increment') {
                if ($new === null) {
                    if ($mapping['nullable'] === true) {
                        $updateData['$set'][$mapping['name']] = null;
                    } else {
                        $updateData['$unset'][$mapping['name']] = true;
                    }
                } elseif ($new >= $old) {
                    $updateData['$inc'][$mapping['name']] = $new - $old;
                } else {
                    $updateData['$inc'][$mapping['name']] = ($old - $new) * -1;
                }

            // @Field, @String, @Date, etc.
            } elseif ( ! isset($mapping['association'])) {
                if (isset($new) || $mapping['nullable'] === true) {
                    $updateData['$set'][$mapping['name']] = (is_null($new) ? null : Type::getType($mapping['type'])->convertToDatabaseValue($new));
                } else {
                    $updateData['$unset'][$mapping['name']] = true;
                }

            // @EmbedOne
            } elseif (isset($mapping['association']) && $mapping['association'] === ClassMetadata::EMBED_ONE) {
                // If we have a new embedded document then lets set the whole thing
                if ($new && $this->uow->isScheduledForInsert($new)) {
                    $updateData['$set'][$mapping['name']] = $this->prepareEmbeddedDocumentValue($mapping, $new);

                // If we don't have a new value then lets unset the embedded document
                } elseif ( ! $new) {
                    $updateData['$unset'][$mapping['name']] = true;

                // Update existing embedded document
                } else {
                    $update = $this->prepareUpdateData($new);
                    foreach ($update as $cmd => $values) {
                        foreach ($values as $key => $value) {
                            $updateData[$cmd][$mapping['name'] . '.' . $key] = $value;
                        }
                    }
                }

            // @EmbedMany
            } elseif (isset($mapping['association']) && $mapping['association'] === ClassMetadata::EMBED_MANY) {
                if (null !== $new) {
                    foreach ($new as $key => $embeddedDoc) {
                        if ( ! $this->uow->isScheduledForInsert($embeddedDoc)) {
                            $update = $this->prepareUpdateData($embeddedDoc);
                            foreach ($update as $cmd => $values) {
                                foreach ($values as $name => $value) {
                                    $updateData[$cmd][$mapping['name'] . '.' . $key . '.' . $name] = $value;
                                }
                            }
                        }
                    }
                }

            // @ReferenceOne
            } elseif (isset($mapping['association']) && $mapping['association'] === ClassMetadata::REFERENCE_ONE && $mapping['isOwningSide']) {
                if (isset($new) || $mapping['nullable'] === true) {
                    $updateData['$set'][$mapping['name']] = (is_null($new) ? null : $this->prepareReferencedDocumentValue($mapping, $new));
                } else {
                    $updateData['$unset'][$mapping['name']] = true;
                }

            // @ReferenceMany
            } elseif (isset($mapping['association']) && $mapping['association'] === ClassMetadata::REFERENCE_MANY) {
                // Do nothing right now
            }
        }
        return $updateData;
    }
697516
private function getDocumentActualData(ClassMetadata $class, $document)
    {
        $actualData = [];
        foreach ($class->reflFields as $fieldName => $reflProperty) {
            // do not set the version info fields if they have values, they are not to be managed by the user in write scenarios.
            if ($fieldName === $class->versionNameField
                || $fieldName === $class->versionCreatedField
            ) {
                continue;
            }
            $value = $reflProperty->getValue($document);
            $actualData[$fieldName] = $value;
        }

        return $actualData;
    }
282449
protected function docToArray(array $doc)
    {
        $values = [];

        foreach ($doc as $key => $value) {

            if ( ! is_array($value)) {
                $values[$key][] = $value;

                continue;
            }

            $values[$key] = $value;
        }

        return $values;
    }
1166498
public function getCurrentDocumentSet()
    {
        if ($id = $this->getRequest()->getVar('dsid')) {
            return DMSDocumentSet::get()->byId($id);
        }
        return singleton('DMSDocumentSet');
    }
1119904
public function getDocumentActualData(object $document) : array
    {
        $class      = $this->dm->getClassMetadata(get_class($document));
        $actualData = [];
        foreach ($class->reflFields as $name => $refProp) {
            $mapping = $class->fieldMappings[$name];
            // skip not saved fields
            if (isset($mapping['notSaved']) && $mapping['notSaved'] === true) {
                continue;
            }
            $value = $refProp->getValue($document);
            if ((isset($mapping['association']) && $mapping['type'] === 'many')
                && $value !== null && ! ($value instanceof PersistentCollectionInterface)) {
                // If $actualData[$name] is not a Collection then use an ArrayCollection.
                if (! $value instanceof Collection) {
                    $value = new ArrayCollection($value);
                }

                // Inject PersistentCollection
                $coll = $this->dm->getConfiguration()->getPersistentCollectionFactory()->create($this->dm, $mapping, $value);
                $coll->setOwner($document, $mapping);
                $coll->setDirty(! $value->isEmpty());
                $class->reflFields[$name]->setValue($document, $coll);
                $actualData[$name] = $coll;
            } else {
                $actualData[$name] = $value;
            }
        }
        return $actualData;
    }
202614
public function generate(DocumentManager $dm, object $document)
    {
        $uuid = $this->generateV4();
        return $this->generateV5($uuid, $this->salt ?: php_uname('n'));
    }
492601
protected function getDocuments() {
        if (!$this->_documents) {
            $this->_documents = new DocumentList($this->version, $this->solution['sid']);
        }

        return $this->_documents;
    }
414841
private function UDB3Media($document)
    {
        $media = [];

        if ($document) {
            $item = $document->getBody();
            // At the moment we do not include any media coming from UDB2.
            // If the mediaObject property contains data it's coming from UDB3.
            $item->mediaObject = isset($item->mediaObject) ? $item->mediaObject : [];
        }

        return $media;
    }
499103
public function serialize(Document $document)
    {
        return [
            'id' => $document->getUuid(),
            'type' => $document->getType(),
            'data' => Document::DOCUMENT_TYPE_RESOURCE === $document->getType() ?
                $this->resourceSerializer->serialize($document->getData()) :
                $document->getData(),
            'drop' => $document->getDrop()->getUuid(),
            'user' => $document->getUser() ? $this->userSerializer->serialize($document->getUser()) : null,
            'dropDate' => $document->getDropDate() ? $document->getDropDate()->format('Y-m-d H:i') : null,
            'toolDocuments' => $this->getToolDocuments($document),
        ];
    }
289820
protected function getServerErrorsExtraSchemaList(ServerDoc $doc) : array
    {
        $list = [];
        foreach ($doc->getGlobalErrorList() as $errorDoc) {
            $key = $this->definitionRefResolver->getErrorDefinitionId(
                $errorDoc,
                DefinitionRefResolver::CUSTOM_ERROR_DEFINITION_TYPE
            );
            $list[$key] = $this->errorDocNormalizer->normalize($errorDoc);
        }

        foreach ($doc->getServerErrorList() as $errorDoc) {
            $key = $this->definitionRefResolver->getErrorDefinitionId(
                $errorDoc,
                DefinitionRefResolver::SERVER_ERROR_DEFINITION_TYPE
            );
            $list[$key] = $this->errorDocNormalizer->normalize($errorDoc);
        }

        return $list;
    }