/** * @see MetadataDataObjectAdapter::injectMetadataIntoDataObject() * @param $metadataDescription MetadataDescription * @param $dataObject Citation * @param $replace boolean whether existing meta-data should be replaced * @return DataObject */ function &injectMetadataIntoDataObject(&$metadataDescription, &$dataObject, $replace) { // Did we get an existing citation object or should we create a new one? if (is_null($dataObject)) { import('citation.Citation'); $dataObject = new Citation(); } // Add new meta-data statements to the citation. Add the schema // name space to each property name so that it becomes unique // across schemas. $metadataSchemaNamespace = $this->getMetadataNamespace(); $nullVar = null; foreach ($metadataDescription->getPropertyNames() as $propertyName) { $dataObjectKey = $metadataSchemaNamespace . ':' . $propertyName; if ($metadataDescription->hasStatement($propertyName)) { // Directly retrieve the internal data so that we don't // have to care about cardinality and translation. $value =& $metadataDescription->getData($propertyName); if (in_array($propertyName, array('person-group[@person-group-type="author"]', 'person-group[@person-group-type="editor"]'))) { // Convert MetadataDescription objects to simple key/value arrays. assert(is_array($value)); foreach ($value as $key => $nameComposite) { assert(is_a($nameComposite, 'MetadataDescription')); $value[$key] =& $nameComposite->getAllData(); } } $dataObject->setData($dataObjectKey, $value); unset($value); } elseif ($replace && $dataObject->hasData($dataObjectKey)) { // Delete existing property data $dataObject->setData($dataObjectKey, $nullVar); } } return $dataObject; }
function indexAction() { $this->metas(array('DC.Title' => 'Citations')); $this->view->citations = $table = new Citation(); $s = $table->select()->order('date DESC'); $this->view->model = new Strass_Pages_Model_Rowset($s, 10, $this->_getParam('page')); $this->actions->append("Enregistrer un citation", array('action' => 'enregistrer')); }
/** * Inject the given meta-data into a new citation object. * @param $metadataDescription MetadataDescription * @return Citation */ protected function &getCitation($citationDescription) { // Instantiate the citation and inject the meta-data. import('lib.pkp.classes.citation.Citation'); $citation = new Citation('raw citation'); $citation->setAssocType($this->assocType); $citation->setAssocId($this->assocId); $citation->injectMetadata($citationDescription); return $citation; }
/** * @return Citation[] */ public function find() { $result = parent::find(); $citations = array(); foreach ($result as $row) { $citation = new Citation($row); $repo = new PublicationRepository($this->db); $citation->setCitationPublication($repo->where('id', '=', $citation->getCitationId())->findSingle()); $citations[] = $citation; } return $citations; }
function indexAction() { $this->metas(array('DC.Title' => 'Administration')); $this->actions->append("Paramètres du site", array('action' => 'parametres')); $this->view->indicateurs = $m = new Wtk_Table_Model('label', 'url', 'compteur', 'level'); $config = Zend_Registry::get('config'); $m->append('Version', null, Strass_Version::PROJET, array('version-produit', 'notice')); $m->append('Version des données', null, Strass_Version::dataCurrent(), array('version-data', strass_admin_count_level(Strass_Version::DATA - Strass_Version::dataCurrent(), 1, 1))); $m->append('Association', null, strtoupper($config->system->association), 'notice'); $t = new Inscriptions(); $count = $t->countRows(); $m->append("Inscriptions à valider", $this->_helper->Url('valider', 'membres'), $count, strass_admin_count_level($count, 1, 5)); $t = new Unites(); $count = $t->countRows(); $m->append("Unités", $this->_helper->Url('unites'), $count, strass_admin_count_level(0 - $count, 0, 0)); $t = new Individus(); $count = $t->countRows(); $m->append("Fiches d'individu", $this->_helper->Url('index', 'individus'), $count, 'notice'); $t = new Users(); $count = $t->countRows(); $m->append("Membres", $this->_helper->Url('index', 'individus', null, array('filtre' => 'membres')), $count, 'notice'); $t = new Citation(); $count = $t->countRows(); $m->append("Citations", $this->_helper->Url('index', 'citation'), $count, 'notice'); $this->view->log = $m = new Wtk_Table_Model('date', 'level', 'logger', 'label', 'url', 'prenom-nom', 'fiche', 'detail-url'); $t = new Logs(); $events = $t->fetchAll($t->select()->order('date DESC')->limit(20)); foreach ($events as $e) { $url = $this->_helper->Url('event', null, null, array('id' => $e->id)); $u = $e->findParentUsers(); if ($u) { $i = $u->findParentIndividus(); $pn = $i->getFullname(); $fiche = $this->_helper->Url('fiche', 'individus', null, array('individu' => $i->slug)); } else { $pn = 'Visiteur'; $fiche = null; } $m->append($e->date, strtolower($e->level), $e->logger, $e->message, $e->url, $pn, $fiche, $url); } $this->view->connexions = $m = new Wtk_Table_Model('date', 'prenom-nom', 'fiche'); $t = new Users(); $users = $t->fetchAll($t->select()->where('last_login')->order('last_login DESC')->limit(8)); foreach ($users as $u) { $i = $u->findParentIndividus(); $m->append($u->last_login, $i->getFullname(false, false), $this->_helper->Url('fiche', 'individus', null, array('individu' => $i->slug))); } }
/** * Import citations from a raw citation list to the object * described by the given association type and id. * @param $request Request * @param $assocType int * @param $assocId int * @param $rawCitationList string * @return integer the number of spawned citation checking processes */ function importCitations(&$request, $assocType, $assocId, $rawCitationList) { assert(is_numeric($assocType) && is_numeric($assocId)); $assocType = (int) $assocType; $assocId = (int) $assocId; // Remove existing citations. $this->deleteObjectsByAssocId($assocType, $assocId); // Tokenize raw citations import('lib.pkp.classes.citation.CitationListTokenizerFilter'); $citationTokenizer = new CitationListTokenizerFilter(); $citationStrings = $citationTokenizer->execute($rawCitationList); // Instantiate and persist citations $citations = array(); if (is_array($citationStrings)) { foreach ($citationStrings as $seq => $citationString) { $citation = new Citation($citationString); // Initialize the citation with the raw // citation string. $citation->setRawCitation($citationString); // Set the object association $citation->setAssocType($assocType); $citation->setAssocId($assocId); // Set the counter $citation->setSeq($seq + 1); $this->insertObject($citation); $citations[$citation->getId()] = $citation; unset($citation); } } // Check new citations in parallel. $noOfProcesses = (int) Config::getVar('general', 'citation_checking_max_processes'); $processDao =& DAORegistry::getDAO('ProcessDAO'); return $processDao->spawnProcesses($request, 'api.citation.CitationApiHandler', 'checkAllCitations', PROCESS_TYPE_CITATION_CHECKING, $noOfProcesses); }
public function testCitationCrud() { $nameSchema = new NlmNameSchema(); $nameDescription = new MetadataDescription($nameSchema, ASSOC_TYPE_AUTHOR); $nameDescription->addStatement('given-names', $value = 'Peter'); $nameDescription->addStatement('given-names', $value = 'B'); $nameDescription->addStatement('surname', $value = 'Bork'); $nameDescription->addStatement('prefix', $value = 'Mr.'); $citationSchema = new NlmCitationSchema(); $citationDescription = new MetadataDescription($citationSchema, ASSOC_TYPE_CITATION); $citationDescription->addStatement('person-group[@person-group-type="author"]', $nameDescription); $citationDescription->addStatement('article-title', $value = 'PHPUnit in a nutshell', 'en_US'); $citationDescription->addStatement('article-title', $value = 'PHPUnit in Kürze', 'de_DE'); $citationDescription->addStatement('date', $value = '2009-08-17'); $citationDescription->addStatement('size', $value = 320); $citationDescription->addStatement('uri', $value = 'http://phpunit.org/nutshell'); $citation = new Citation('raw citation'); $citation->setAssocType(ASSOC_TYPE_ARTICLE); $citation->setAssocId(999999); $citation->setEditedCitation('edited citation'); $citation->setParseScore(50); $citation->injectMetadata($citationDescription); // Create citation $citationId = $this->citationDAO->insertCitation($citation); self::assertTrue(is_numeric($citationId)); self::assertTrue($citationId > 0); // Retrieve citation $citationById = $this->citationDAO->getCitation($citationId); $citationById->getMetadataFieldNames(); // Initializes internal state for comparison. self::assertEquals($citation, $citationById); $citationsByAssocIdDaoFactory = $this->citationDAO->getCitationsByAssocId(ASSOC_TYPE_ARTICLE, 999999); $citationsByAssocId = $citationsByAssocIdDaoFactory->toArray(); self::assertEquals(1, count($citationsByAssocId)); $citationsByAssocId[0]->getMetadataFieldNames(); // Initializes internal state for comparison. self::assertEquals($citation, $citationsByAssocId[0]); // Update citation $citationDescription->removeStatement('date'); $citationDescription->addStatement('article-title', $value = 'PHPUnit rápido', 'pt_BR'); $updatedCitation = new Citation('another raw citation'); $updatedCitation->setId($citationId); $updatedCitation->setAssocType(ASSOC_TYPE_ARTICLE); $updatedCitation->setAssocId(999998); $updatedCitation->setEditedCitation('another edited citation'); $updatedCitation->setParseScore(50); $updatedCitation->injectMetadata($citationDescription); $this->citationDAO->updateCitation($updatedCitation); $citationAfterUpdate = $this->citationDAO->getCitation($citationId); $citationAfterUpdate->getMetadataFieldNames(); // Initializes internal state for comparison. self::assertEquals($updatedCitation, $citationAfterUpdate); // Delete citation $this->citationDAO->deleteCitationsByAssocId(ASSOC_TYPE_ARTICLE, 999998); self::assertNull($this->citationDAO->getCitation($citationId)); }
/** * @see MetadataDataObjectAdapter::injectMetadataIntoDataObject() * @param $metadataDescription MetadataDescription * @param $dataObject Citation * @param $replace boolean whether existing meta-data should be replaced * @return DataObject */ function &injectMetadataIntoDataObject(&$metadataDescription, &$dataObject, $replace) { // Did we get an existing citation object or should we create a new one? if (is_null($dataObject)) { import('lib.pkp.classes.citation.Citation'); $dataObject = new Citation(); } // Add new meta-data statements to the citation. Add the schema // name space to each property name so that it becomes unique // across schemas. $metadataSchemaNamespace = $this->getMetadataNamespace(); $nullVar = null; foreach ($metadataDescription->getPropertyNames() as $propertyName) { $dataObjectKey = $metadataSchemaNamespace . ':' . $propertyName; if ($metadataDescription->hasStatement($propertyName)) { // Directly retrieve the internal data so that we don't // have to care about cardinality and translation. $value =& $metadataDescription->getData($propertyName); if (in_array($propertyName, array('person-group[@person-group-type="author"]', 'person-group[@person-group-type="editor"]'))) { assert(is_array($value)); // Dereference the value to make sure that we don't destroy // the original MetadataDescription. $tmpValue = $value; unset($value); $value =& $tmpValue; // Convert MetadataDescription objects to simple key/value arrays. foreach ($value as $key => $name) { if (is_a($name, 'MetadataDescription')) { // A name can either be a full name description... $value[$key] =& $name->getAllData(); } else { // ...or an 'et-al' string. assert($name == PERSON_STRING_FILTER_ETAL); // No need to change the value encoding. } } } $dataObject->setData($dataObjectKey, $value); unset($value); } elseif ($replace && $dataObject->hasData($dataObjectKey)) { // Delete existing property data $dataObject->setData($dataObjectKey, $nullVar); } } return $dataObject; }
public function testCitationCrud() { $nameSchema = new NlmNameSchema(); $nameDescription = new MetadataDescription($nameSchema, ASSOC_TYPE_AUTHOR); $nameDescription->addStatement('given-names', $value = 'Peter'); $nameDescription->addStatement('given-names', $value = 'B'); $nameDescription->addStatement('surname', $value = 'Bork'); $nameDescription->addStatement('prefix', $value = 'Mr.'); $citationSchema = new NlmCitationSchema(); $citationDescription = new MetadataDescription($citationSchema, ASSOC_TYPE_CITATION); $citationDescription->addStatement('person-group[@person-group-type="author"]', $nameDescription); $citationDescription->addStatement('article-title', $value = 'PHPUnit in a nutshell', 'en_US'); $citationDescription->addStatement('article-title', $value = 'PHPUnit in Kürze', 'de_DE'); $citationDescription->addStatement('date', $value = '2009-08-17'); $citationDescription->addStatement('size', $value = 320); $citationDescription->addStatement('uri', $value = 'http://phpunit.org/nutshell'); $citation = new Citation('raw citation'); $citation->setAssocType(ASSOC_TYPE_ARTICLE); $citation->setAssocId(5); $citation->setEditedCitation('edited citation'); $citation->setParseScore(50); $citation->injectMetadata($citationDescription); $citationId = $this->citationDAO->insertCitation($citation); self::assertTrue(is_numeric($citationId)); self::assertTrue($citationId > 0); }
/** * @covers CitationParserService::parse */ public function testParse() { $citation = new Citation(METADATA_GENRE_JOURNALARTICLE, 'rawCitation'); // Set an "unclean" article title and add a comment // to test whether parse() cleans this up. $citation->setArticleTitle('Article Title with Punctuation.'); $citation->addComment('Comment with Punctuation.'); // Mock CitationParserService->parseInternal() which will usually // be implemented by sub-classes. $mockCPService =& $this->getMock('CitationParserService', array('parseInternal')); // Set up the parseInternal() method $mockCPService->expects($this->once())->method('parseInternal')->with($this->equalTo($mockCPService->getCitationString($citation)))->will($this->returnValue($citation)); // Call the SUT $citation = $mockCPService->parse($citation); // Test whether the citation has been cleaned up. self::assertEquals('Article Title with Punctuation', $citation->getArticleTitle()); self::assertEquals(array('Comment with Punctuation'), $citation->getComments()); }
public static function nonPatentLiterature($text, $citedBy = null, $country = null, $citationDate = null) { $citation = new Citation(Citation::NON_PATENT_LITERATURE); $citation->setText($text); $citation->setCitedBy($citedBy); $citation->setCitationDate($citationDate); $citation->setCountry($country); return $citation; }
/** * Custom implementation of Form::validate() that validates * meta-data form data and injects it into the internal citation * object. * * NB: The configuration of the internal citation object * would normally be done in readInputData(). Validation and * injection can easily be done in one step. It therefore avoids * code duplication and improves performance to do both here. */ function validate() { // Make sure that this method is not called twice which // would corrupt internal state. assert(empty($this->_metadataDescriptions)); parent::validate(); // Validate form data and inject it into // the associated citation object. $citation =& $this->getCitation(); $citation->setRawCitation($this->getData('rawCitation')); if ($this->getData('citationApproved') == 'citationApproved') { // Editor's shortcut to the approved state, e.g. for manually edited citations. $citation->setCitationState(CITATION_APPROVED); } elseif (in_array($this->getData('citationState'), Citation::_getSupportedCitationStates())) { // Reset citation state if necessary if ($this->getData('citationState') == CITATION_APPROVED) { $this->setData('citationState', CITATION_LOOKED_UP); } $citation->setCitationState($this->getData('citationState')); } // Extract data from citation form fields and inject it into the citation import('lib.pkp.classes.metadata.MetadataDescription'); $metadataSchemas = $citation->getSupportedMetadataSchemas(); foreach ($metadataSchemas as $metadataSchema) { /* @var $metadataSchema MetadataSchema */ // Instantiate a meta-data description for the given schema $metadataDescription = new MetadataDescription($metadataSchema->getClassName(), ASSOC_TYPE_CITATION); // Set the meta-data statements foreach ($metadataSchema->getProperties() as $propertyName => $property) { $fieldName = $metadataSchema->getNamespacedPropertyId($propertyName); $fieldValue = trim($this->getData($fieldName)); if (empty($fieldValue)) { // Delete empty statements so that previously set // statements (if any) will be deleted. $metadataDescription->removeStatement($propertyName); if ($property->getMandatory()) { // A mandatory field is missing - add a validation error. $this->addError($fieldName, __($property->getValidationMessage())); $this->addErrorField($fieldName); } } else { // Try to convert the field value to (a) strongly // typed object(s) if applicable. Start with the most // specific allowed type so that we always get the // most strongly typed result possible. $allowedTypes = $property->getAllowedTypes(); switch (true) { case isset($allowedTypes[METADATA_PROPERTY_TYPE_VOCABULARY]) && is_numeric($fieldValue): case isset($allowedTypes[METADATA_PROPERTY_TYPE_INTEGER]) && is_numeric($fieldValue): $typedFieldValues = array((int) $fieldValue); break; case isset($allowedTypes[METADATA_PROPERTY_TYPE_DATE]): import('lib.pkp.classes.metadata.DateStringNormalizerFilter'); $dateStringFilter = new DateStringNormalizerFilter(); assert($dateStringFilter->supportsAsInput($fieldValue)); $typedFieldValues = array($dateStringFilter->execute($fieldValue)); break; case isset($allowedTypes[METADATA_PROPERTY_TYPE_COMPOSITE]): // We currently only support name composites $allowedAssocIds = $allowedTypes[METADATA_PROPERTY_TYPE_COMPOSITE]; if (in_array(ASSOC_TYPE_AUTHOR, $allowedAssocIds)) { $assocType = ASSOC_TYPE_AUTHOR; } elseif (in_array(ASSOC_TYPE_EDITOR, $allowedAssocIds)) { $assocType = ASSOC_TYPE_EDITOR; } else { assert(false); } // Try to transform the field to a name composite. import('lib.pkp.plugins.metadata.nlm30.filter.PersonStringNlm30NameSchemaFilter'); $personStringFilter = new PersonStringNlm30NameSchemaFilter($assocType, PERSON_STRING_FILTER_MULTIPLE); assert($personStringFilter->supportsAsInput($fieldValue)); $typedFieldValues =& $personStringFilter->execute($fieldValue); break; default: $typedFieldValues = array($fieldValue); } // Inject data into the meta-data description and thereby // implicitly validate the field value. foreach ($typedFieldValues as $typedFieldValue) { if (!$metadataDescription->addStatement($propertyName, $typedFieldValue)) { // Add form field error $this->addError($fieldName, __($property->getValidationMessage())); $this->addErrorField($fieldName); } unset($typedFieldValue); } unset($typedFieldValues); } } // Inject the meta-data into the citation. $citation->injectMetadata($metadataDescription); // Save the meta-data description for later usage. $this->_metadataDescriptions[] =& $metadataDescription; unset($metadataDescription); } return $this->isValid(); }
/** * @covers CitationDAO */ public function testCitationCrud() { $citationDao = DAORegistry::getDAO('CitationDAO'); /* @var $citationDao CitationDAO */ $nameSchemaName = 'lib.pkp.plugins.metadata.nlm30.schema.Nlm30NameSchema'; $nameDescription = new MetadataDescription($nameSchemaName, ASSOC_TYPE_AUTHOR); $nameDescription->addStatement('given-names', $value = 'Peter'); $nameDescription->addStatement('given-names', $value = 'B'); $nameDescription->addStatement('surname', $value = 'Bork'); $nameDescription->addStatement('prefix', $value = 'Mr.'); $citationSchemaName = 'lib.pkp.plugins.metadata.nlm30.schema.Nlm30CitationSchema'; $citationDescription = new MetadataDescription($citationSchemaName, ASSOC_TYPE_CITATION); $citationDescription->addStatement('person-group[@person-group-type="author"]', $nameDescription); $citationDescription->addStatement('article-title', $value = 'PHPUnit in a nutshell', 'en_US'); $citationDescription->addStatement('article-title', $value = 'PHPUnit in Kürze', 'de_DE'); $citationDescription->addStatement('date', $value = '2009-08-17'); $citationDescription->addStatement('size', $value = 320); $citationDescription->addStatement('uri', $value = 'http://phpunit.org/nutshell'); // Add a simple source description. $sourceDescription = new MetadataDescription($citationSchemaName, ASSOC_TYPE_CITATION); $sourceDescription->setDisplayName('test'); $sourceDescription->addStatement('article-title', $value = 'a simple source description', 'en_US'); $sourceDescription->setSeq(0); $citation = new Citation('raw citation'); $citation->setAssocType(ASSOC_TYPE_ARTICLE); $citation->setAssocId(999999); $citation->setSeq(50); $citation->addSourceDescription($sourceDescription); $citation->injectMetadata($citationDescription); // Create citation. $citationId = $citationDao->insertObject($citation); self::assertTrue(is_numeric($citationId)); self::assertTrue($citationId > 0); // Retrieve citation. $citationById = $citationDao->getObjectById($citationId); // Fix state differences for comparison. $citation->removeSupportedMetadataAdapter($citationSchemaName); $citationById->removeSupportedMetadataAdapter($citationSchemaName); $citationById->_extractionAdaptersLoaded = true; $citationById->_injectionAdaptersLoaded = true; $sourceDescription->setAssocId($citationId); $sourceDescription->removeSupportedMetadataAdapter($citationSchemaName); $sourceDescriptions = $citationById->getSourceDescriptions(); $sourceDescriptions['test']->getMetadataSchema(); // this will instantiate the meta-data schema internally. self::assertEquals($citation, $citationById); $citationsByAssocIdDaoFactory = $citationDao->getObjectsByAssocId(ASSOC_TYPE_ARTICLE, 999999); $citationsByAssocId = $citationsByAssocIdDaoFactory->toArray(); self::assertEquals(1, count($citationsByAssocId)); // Fix state differences for comparison. $citationsByAssocId[0]->_extractionAdaptersLoaded = true; $citationsByAssocId[0]->_injectionAdaptersLoaded = true; $citationsByAssocId[0]->removeSupportedMetadataAdapter($citationSchemaName); $sourceDescriptionsByAssocId = $citationsByAssocId[0]->getSourceDescriptions(); $sourceDescriptionsByAssocId['test']->getMetadataSchema(); // this will instantiate the meta-data schema internally. self::assertEquals($citation, $citationsByAssocId[0]); // Update citation. $citationDescription->removeStatement('date'); $citationDescription->addStatement('article-title', $value = 'PHPUnit rápido', 'pt_BR'); // Update source descriptions. $sourceDescription->addStatement('article-title', $value = 'edited source description', 'en_US', true); $updatedCitation = new Citation('another raw citation'); $updatedCitation->setId($citationId); $updatedCitation->setAssocType(ASSOC_TYPE_ARTICLE); $updatedCitation->setAssocId(999998); $updatedCitation->setSeq(50); $updatedCitation->addSourceDescription($sourceDescription); $updatedCitation->injectMetadata($citationDescription); $citationDao->updateObject($updatedCitation); $citationAfterUpdate = $citationDao->getObjectById($citationId); // Fix state differences for comparison. $updatedCitation->removeSupportedMetadataAdapter($citationSchemaName); $citationAfterUpdate->removeSupportedMetadataAdapter($citationSchemaName); $citationAfterUpdate->_extractionAdaptersLoaded = true; $citationAfterUpdate->_injectionAdaptersLoaded = true; $sourceDescriptionsAfterUpdate = $citationAfterUpdate->getSourceDescriptions(); $sourceDescriptionsAfterUpdate['test']->getMetadataSchema(); // this will instantiate the meta-data schema internally. $sourceDescription->removeSupportedMetadataAdapter($citationSchemaName); self::assertEquals($updatedCitation, $citationAfterUpdate); // Delete citation $citationDao->deleteObjectsByAssocId(ASSOC_TYPE_ARTICLE, 999998); self::assertNull($citationDao->getObjectById($citationId)); }
/** * Our construct function. */ public function __construct( $parser, $frame, $args ) { parent::__construct($parser, $frame, $args); }
function initView($view) { $view->document->addStyleComponents('citation'); $t = new Citation(); $view->citation = $t->findRandom(); }
/** * Take an array of citation parse/lookup results and derive a citation * with one "best" set of values. * * We determine the best values within the citations that have a score above * the given threshold. Citations with a score below the threshold will be * ignored. * * For these citations we count the frequency of values per meta-data property. * The most frequent value will be chosen as "best" value. * * If two values have the same frequency then decide based on the score. If * this is still ambivalent then return the first of the remaining values. * * @param $scoredCitations * @param $scoreThreshold integer a number between 0 (=no threshold) and 100 * @return Citation one citation with the "best" values set */ function &_guessValues(&$scoredCitations, $scoreThreshold) { assert($scoreThreshold >= 0 && $scoreThreshold <= 100); // Create the target citation description. $targetDescription = new MetadataDescription('lib.pkp.plugins.metadata.nlm30.schema.Nlm30CitationSchema', ASSOC_TYPE_CITATION); // Step 1: List all values and max scores that have been identified for a given element // but only include values from results above a given scoring threshold // Initialize variables for the first step. $valuesByPropertyName = array(); $maxScoresByPropertyNameAndValue = array(); // Sort the scored citations by score with the highest score first. krsort($scoredCitations); foreach ($scoredCitations as $currentScore => $citationsForCurrentScore) { // Check whether the current score is below the threshold, if so // stop the loop. We've sorted our citations by score so the remaining // citations all have scores below the threshold and we can forget // about them. if ($currentScore < $scoreThreshold) { break; } foreach ($citationsForCurrentScore as $citationForCurrentScore) { $statements = $citationForCurrentScore->getStatements(); // Add the property values and scores of this citation // to the overall property lists foreach ($statements as $propertyName => $value) { // Initialize sub-arrays if necessary if (!isset($valuesByPropertyName[$propertyName])) { $valuesByPropertyName[$propertyName] = array(); } if (!isset($maxScoresByPropertyNameAndValue[$propertyName])) { $maxScoresByPropertyNameAndValue[$propertyName] = array(); } // Add the value for the given property, as we want to count // value frequencies later, we explicitly allow duplicates. $serializedValue = serialize($value); $valuesByPropertyName[$propertyName][] = $serializedValue; // As we have ordered our citations descending by score, the // first score found for a value is also the maximum score. if (!isset($maxScoresByPropertyNameAndValue[$propertyName][$serializedValue])) { $maxScoresByPropertyNameAndValue[$propertyName][$serializedValue] = $currentScore; } } } } // Step 2: Find out the values that occur most frequently for each element // and order these by score. foreach ($valuesByPropertyName as $propertyName => $values) { // Count the occurrences of each value within the given element $valueFrequencies = array_count_values($values); // Order the most frequent values to the beginning of the array arsort($valueFrequencies); // Get the most frequent values (may be several if there are more than one // with the same frequency). $scoresOfMostFrequentValues = array(); $previousValueFrequency = 0; foreach ($valueFrequencies as $value => $valueFrequency) { // Only extract the most frequent values, jump out of the // loop when less frequent values start. if ($previousValueFrequency > $valueFrequency) { break; } $previousValueFrequency = $valueFrequency; $scoresOfMostFrequentValues[$value] = $maxScoresByPropertyNameAndValue[$propertyName][$value]; } // Now we can order the most frequent values by score, starting // with the highest score. arsort($scoresOfMostFrequentValues); // Now get the first key which represents the value with the // highest frequency and the highest score. reset($scoresOfMostFrequentValues); $bestValue = unserialize(key($scoresOfMostFrequentValues)); // Set the found "best" element value in the result citation. $statements = array($propertyName => $bestValue); $success = $targetDescription->setStatements($statements); assert($success); } // Instantiate the target citation $targetCitation = new Citation(); $targetCitation->injectMetadata($targetDescription); return $targetCitation; }
/** * Set the citationState * @param $citationState integer */ function setCitationState($citationState) { assert(in_array($citationState, Citation::_getSupportedCitationStates())); $this->_citationState = $citationState; }
/** * Save citation */ function execute() { $citation =& $this->getCitation(); $citation->setEditedCitation($this->getData('editedCitation')); if (in_array($this->getData('citationState'), Citation::_getSupportedCitationStates())) { $citation->setCitationState($this->getData('citationState')); } // Extract data from citation form fields and inject it into the citation $metadataAdapters = $citation->getSupportedMetadataAdapters(); foreach ($metadataAdapters as $metadataAdapter) { // Instantiate a meta-data description for the given schema $metadataSchema =& $metadataAdapter->getMetadataSchema(); import('metadata.MetadataDescription'); $metadataDescription = new MetadataDescription($metadataSchema, ASSOC_TYPE_CITATION); // Set the meta-data statements $metadataSchemaNamespace = $metadataSchema->getNamespace(); foreach ($metadataSchema->getProperties() as $propertyName => $property) { $fieldName = $metadataSchema->getNamespacedPropertyId($propertyName); $fieldValue = trim($this->getData($fieldName)); if (empty($fieldValue)) { $metadataDescription->removeStatement($propertyName); } else { $foundValidType = false; foreach ($property->getTypes() as $type) { // Some property types need to be converted first switch ($type) { // We currently only support name composites case array(METADATA_PROPERTY_TYPE_COMPOSITE => ASSOC_TYPE_AUTHOR): case array(METADATA_PROPERTY_TYPE_COMPOSITE => ASSOC_TYPE_EDITOR): import('metadata.nlm.PersonStringNlmNameSchemaFilter'); $personStringFilter = new PersonStringNlmNameSchemaFilter($type[METADATA_PROPERTY_TYPE_COMPOSITE], PERSON_STRING_FILTER_MULTIPLE); assert($personStringFilter->supportsAsInput($fieldValue)); $fieldValue =& $personStringFilter->execute($fieldValue); $foundValidType = true; break; case METADATA_PROPERTY_TYPE_INTEGER: $fieldValue = array((int) $fieldValue); $foundValidType = true; break; case METADATA_PROPERTY_TYPE_DATE: import('metadata.DateStringNormalizerFilter'); $dateStringFilter = new DateStringNormalizerFilter(); assert($dateStringFilter->supportsAsInput($fieldValue)); $fieldValue = array($dateStringFilter->execute($fieldValue)); $foundValidType = true; break; default: if ($property->isValid($fieldValue)) { $fieldValue = array($fieldValue); $foundValidType = true; break; } } // Break the outer loop once we found a valid // interpretation for our form field. if ($foundValidType) { break; } } foreach ($fieldValue as $fieldValueStatement) { $metadataDescription->addStatement($propertyName, $fieldValueStatement); unset($fieldValueStatement); } } } // Inject the meta-data into the citation $citation->injectMetadata($metadataDescription, true); } // Persist citation $citationDAO =& DAORegistry::getDAO('CitationDAO'); if (is_numeric($citation->getId())) { $citationDAO->updateCitation($citation); } else { $citationDAO->insertCitation($citation); } return true; }
/** * This will retrieve a citation object from the * grids data source based on the request arguments. * If no citation can be found then this will raise * a fatal error. * @param $args array * @param $createIfMissing boolean If this is set to true * then a citation object will be instantiated if no * citation id is in the request. * @return Citation */ function &getCitationFromArgs($request, &$args, $createIfMissing = false) { // Identify the citation id and retrieve the // corresponding element from the grid's data source. if (isset($args['citationId'])) { $citation =& $this->getRowDataElement($request, $args['citationId']); if (is_null($citation)) { fatalError('Invalid citation id!'); } } else { if ($createIfMissing) { // It seems that a new citation is being edited/updated import('lib.pkp.classes.citation.Citation'); $citation = new Citation(); $citation->setAssocType($this->getAssocType()); $citation->setAssocId($this->getAssocId()); } else { fatalError('Missing citation id!'); } } return $citation; }
/** * This will retrieve a citation object from the * grids data source based on the request arguments. * If no citation can be found then this will raise * a fatal error. * @param $args array * @param $createIfMissing boolean If this is set to true * then a citation object will be instantiated if no * citation id is in the request. * @return Citation */ function &_getCitationFromArgs(&$args, $createIfMissing = false) { // Identify the citation id and retrieve the // corresponding element from the grid's data source. if (!isset($args['citationId'])) { if ($createIfMissing) { // It seems that a new citation is being edited/updated import('citation.Citation'); $citation = new Citation(); $citation->setAssocType(ASSOC_TYPE_ARTICLE); $article =& $this->getArticle(); $citation->setAssocId($article->getId()); } else { fatalError('Missing citation id!'); } } else { $citation =& $this->getRowDataElement($args['citationId']); if (is_null($citation)) { fatalError('Invalid citation id!'); } } return $citation; }