From d032cfce2617fc8a3e8ab98801587eae442d643b Mon Sep 17 00:00:00 2001 From: j3nsch Date: Mon, 26 Feb 2018 16:01:12 +0100 Subject: [PATCH 001/128] OPUSVIER-3541 - Show notification list as table without duplicates. --- .../View/Partial/multicheckboxtable.phtml | 12 ++ .../admin/controllers/WorkflowController.php | 92 ++--------- modules/admin/forms/Notification.php | 143 ++++++++++++++++++ modules/admin/forms/WorkflowNotification.php | 60 ++++++++ modules/admin/forms/YesNoForm.php | 9 +- modules/default/language/workflow.tmx | 9 ++ .../modules/admin/forms/NotificationTest.php | 45 ++++++ 7 files changed, 285 insertions(+), 85 deletions(-) create mode 100644 library/Application/View/Partial/multicheckboxtable.phtml create mode 100644 modules/admin/forms/Notification.php create mode 100644 modules/admin/forms/WorkflowNotification.php create mode 100644 tests/modules/admin/forms/NotificationTest.php diff --git a/library/Application/View/Partial/multicheckboxtable.phtml b/library/Application/View/Partial/multicheckboxtable.phtml new file mode 100644 index 000000000..ca7133881 --- /dev/null +++ b/library/Application/View/Partial/multicheckboxtable.phtml @@ -0,0 +1,12 @@ + + + element->getRows() as $row) : ?> + + + + + + + + +
/>
diff --git a/modules/admin/controllers/WorkflowController.php b/modules/admin/controllers/WorkflowController.php index 890b3ed0c..28a427fd4 100644 --- a/modules/admin/controllers/WorkflowController.php +++ b/modules/admin/controllers/WorkflowController.php @@ -28,15 +28,18 @@ * @package Module_Admin * @author Jens Schwidder * @author Sascha Szott - * @copyright Copyright (c) 2008-2012, OPUS 4 development team + * @copyright Copyright (c) 2008-2018, OPUS 4 development team * @license http://www.gnu.org/licenses/gpl.html General Public License - * @version $Id$ + * + * TODO fix processing of notification selection + * TODO verify previous checkbox results */ /** * Controller handles transitions of documents between states. */ -class Admin_WorkflowController extends Application_Controller_Action { +class Admin_WorkflowController extends Application_Controller_Action +{ /** * Helper for verifying document IDs. @@ -213,7 +216,7 @@ private function _sendNotification($document, $form = null) { * @return Admin_Form_YesNoForm */ private function _getConfirmationForm($document, $targetState) { - $form = new Admin_Form_YesNoForm(); + $form = new Admin_Form_WorkflowNotification(); $form->setAction( $this->view->url( array('controller' => 'workflow', 'action' => 'changestate', 'targetState' => $targetState) @@ -221,87 +224,16 @@ private function _getConfirmationForm($document, $targetState) { ); $form->setMethod('post'); - $idElement = new Zend_Form_Element_Hidden('id'); - $idElement->setValue($document->getId()); - $form->addElement($idElement); + $form->getElement(Admin_Form_WorkflowNotification::ELEMENT_ID)->setValue($document->getId()); + + $config = $this->getConfig(); - $config = Zend_Registry::get('Zend_Config'); if ($targetState == 'published' && isset($config->notification->document->published->enabled) && $config->notification->document->published->enabled == 1) { - $this->_addPublishNotificationSelection($document, $form); - } - return $form; - } - - /** - * add a checkbox for each PersonSubmitter and PersonAuthor (used to select - * recipients for publish notification email) - * - * @param Opus_Document $document - * @param Zend_Form $form - * - */ - private function _addPublishNotificationSelection($document, $form) { - $form->addElement( - 'hidden', 'plaintext', - array( - 'description' => '

' . $this->view->translate('admin_workflow_notification_headline') - . '

' - . '

' . $this->view->translate('admin_workflow_notification_description') . '

', - 'ignore' => true, - 'decorators' => array(array('Description', array('escape' => false, 'tag' => ''))) - ) - ); - - $submitters = $document->getPersonSubmitter(); - if (!is_null($submitters) && count($submitters) > 0) { - $label = $this->view->translate('admin_workflow_notification_submitter') . ' ' - . trim($submitters[0]->getLastName()) . ", " . trim($submitters[0]->getFirstName()); - $element = null; - if (trim($submitters[0]->getEmail()) == '') { - // email notification is not possible since no email address is specified for submitter - $label .= ' (' . $this->view->translate('admin_workflow_notification_noemail') . ')'; - $element = new Zend_Form_Element_Checkbox( - 'submitter', array('checked' => false, 'disabled' => true, - 'label' => $label) - ); - $element->getDecorator('Label')->setOption('class', 'notification-option option-not-available'); - } - else { - $label .= ' (' . trim($submitters[0]->getEmail()) . ')'; - $element = new Zend_Form_Element_Checkbox('submitter', array('checked' => true, 'label' => $label)); - $element->getDecorator('Label')->setOption('class', 'notification-option'); - } - $form->addElement($element); + $form->addPublishNotificationSelection($document); } - $authors = $document->getPersonAuthor(); - if (!is_null($authors)) { - $index = 1; - foreach ($authors as $author) { - $id = 'author_' . $index; - $label = $index . '. ' . $this->view->translate('admin_workflow_notification_author') . ' ' - . trim($author->getLastName()) . ", " . trim($author->getFirstName()); - $element = null; - if (trim($author->getEmail()) == '') { - // email notification is not possible since no email address is specified for author - $label .= ' (' . $this->view->translate('admin_workflow_notification_noemail') . ')'; - $element = new Zend_Form_Element_Checkbox( - $id, array('checked' => false, 'disabled' => true, 'label' => $label) - ); - $element->getDecorator('Label')->setOption('class', 'notification-option option-not-available'); - } - else { - $label .= ' (' . trim($author->getEmail()) . ')'; - $element = new Zend_Form_Element_Checkbox( - $id, array('checked' => true, 'label' => 'foo', 'label' => $label) - ); - $element->getDecorator('Label')->setOption('class', 'notification-option'); - } - $form->addElement($element); - $index++; - } - } + return $form; } } diff --git a/modules/admin/forms/Notification.php b/modules/admin/forms/Notification.php new file mode 100644 index 000000000..50ec20050 --- /dev/null +++ b/modules/admin/forms/Notification.php @@ -0,0 +1,143 @@ + + * @copyright Copyright (c) 2018, OPUS 4 development team + * @license http://www.gnu.org/licenses/gpl.html General Public License + * + * TODO fix processing of elements in WorkflowController (in subform names get prefix) + * TODO adjust styling of sub form + * TODO unit testing + */ +class Admin_Form_Notification extends Admin_Form_AbstractDocumentSubForm +{ + + private $_document; + + public function init() + { + parent::init(); + + $this->setLegend('admin_workflow_notification_headline'); + + $translator = $this->getTranslator(); + + $this->addElement('note', 'description', array( + 'value' => "

{$translator->translate('admin_workflow_notification_description')}

" + )); + + $this->setDecorators(array( + 'FormElements', + array('ViewScript', array('viewScript' => 'multicheckboxtable.phtml')), + array('Fieldset', array('class' => 'headline')), + )); + } + + /** + * add a checkbox for each PersonSubmitter and PersonAuthor (used to select + * recipients for publish notification email) + * + * @param Opus_Document $document + * @param Zend_Form $form + * + * + * TODO css notification-option, option-not-available + * TODO check if submitter matches author -> change type (labeling) + */ + public function addPublishNotificationSelection($document) + { + $this->_document = $document; + } + + public function getRows() + { + $translator = $this->getTranslator(); + + $document = $this->_document; + + $submitters = $document->getPersonSubmitter(); + + $submitter = null; + + if (!is_null($submitters) && count($submitters) > 0) { + $submitter = $submitters[0]->getModel(); + $option = $this->personToArray($submitters[0]); + $option['value'] = 'submitter'; + $option['type'] = $translator->translate('admin_workflow_notification_submitter'); + $options['submitter'] = $option; + } + + $authors = $document->getPersonAuthor(); + + if (!is_null($authors)) { + foreach ($authors as $index => $author) { + $person = $author->getModel(); + if (!is_null($submitter) + && $submitter->matches($person) + && $submitter->getEmail() == $person->getEmail()) + { + $msg = $translator->translate('admin_workflow_notification_submitter_and_author'); + $options['submitter']['type'] = sprintf($msg, $index + 1); + } + else + { + $option = $this->personToArray($author); + $option['value'] = 'author_' . $index; + $pos = $index + 1; + $option['type'] = "$pos. {$translator->translate('admin_workflow_notification_author')}"; + $options[] = $option; + } + } + } + + return $options; + } + + public function personToArray($person) + { + $translator = $this->getTranslator(); + + $email = trim($person->getEmail()); + + $disabled = false; + + if ($email == '') { + $email = " ({$translator->translate('admin_workflow_notification_noemail')})"; + $disabled = true; + } + + $option = array( + 'name' => $person->getDisplayName(), + 'email' => $email, + 'disabled' => $disabled + ); + + return $option; + } + +} \ No newline at end of file diff --git a/modules/admin/forms/WorkflowNotification.php b/modules/admin/forms/WorkflowNotification.php new file mode 100644 index 000000000..87a5035db --- /dev/null +++ b/modules/admin/forms/WorkflowNotification.php @@ -0,0 +1,60 @@ + + * @copyright Copyright (c) 2018, OPUS 4 development team + * @license http://www.gnu.org/licenses/gpl.html General Public License + */ +class Admin_Form_WorkflowNotification extends Admin_Form_YesNoForm +{ + + const ELEMENT_ID = 'id'; + + public function init() + { + parent::init(); + + $this->addElement('hidden', self::ELEMENT_ID); + } + + /** + * add a checkbox for each PersonSubmitter and PersonAuthor (used to select + * recipients for publish notification email) + * + * @param Opus_Document $document + * @param Zend_Form $form + * + */ + public function addPublishNotificationSelection($document) { + $subform = new Admin_Form_Notification(); + $subform->addPublishNotificationSelection($document); + + $this->addSubForm($subform, 'notification'); + } + +} diff --git a/modules/admin/forms/YesNoForm.php b/modules/admin/forms/YesNoForm.php index 79987abf1..a9aa1ebf2 100644 --- a/modules/admin/forms/YesNoForm.php +++ b/modules/admin/forms/YesNoForm.php @@ -29,12 +29,12 @@ * @author Oliver Marahrens * @copyright Copyright (c) 2009, OPUS 4 development team * @license http://www.gnu.org/licenses/gpl.html General Public License - * @version $Id$ */ +class Admin_Form_YesNoForm extends Zend_Form +{ -class Admin_Form_YesNoForm extends Zend_Form { /** - * Build easy form + * Build easy form for yes/no questions. * * @return void */ @@ -45,8 +45,7 @@ public function init() { $sureno = new Zend_Form_Element_Submit('sureno'); $sureno->setLabel('answer_no'); - #$id = new Zend_Form_Element_Hidden('id'); - $this->addElements(array($sureyes, $sureno)); } + } \ No newline at end of file diff --git a/modules/default/language/workflow.tmx b/modules/default/language/workflow.tmx index a6192fb6a..7658c578e 100644 --- a/modules/default/language/workflow.tmx +++ b/modules/default/language/workflow.tmx @@ -269,6 +269,15 @@ + + + Submitter and %1$s. author + + + Einsteller und %1$s. Autor + + + Author diff --git a/tests/modules/admin/forms/NotificationTest.php b/tests/modules/admin/forms/NotificationTest.php new file mode 100644 index 000000000..c67f0e64a --- /dev/null +++ b/tests/modules/admin/forms/NotificationTest.php @@ -0,0 +1,45 @@ + + * @copyright Copyright (c) 2018, OPUS 4 development team + * @license http://www.gnu.org/licenses/gpl.html General Public License + */ + +class Admin_Form_NotificationTest extends ControllerTestCase { + + public function testGetRows() { + $form = new Admin_Form_Notification(); + + $form->addPublishNotificationSelection(new Opus_Document(146)); + + $rows = $form->getRows(); + + $this->assertCount(2, $rows); + } + +} From 6ed2a8cfe9b8a997724ac97e228bd855050d96d8 Mon Sep 17 00:00:00 2001 From: j3nsch Date: Tue, 19 Jun 2018 15:49:59 +0200 Subject: [PATCH 002/128] OPUSVIER-3896 - Create required enrichments for DOI support during update. --- .../Update/CreateDoiUrnEnrichments.php | 62 +++++++++++++++++++ .../006-Set-status-of-all-existing-DOIs.php | 1 + .../update/007-Create-DOI-URN-Enrichments.php | 43 +++++++++++++ .../Update/CreateDoiUrnEnrichmentsTest.php | 45 ++++++++++++++ 4 files changed, 151 insertions(+) create mode 100644 library/Application/Update/CreateDoiUrnEnrichments.php create mode 100644 scripts/update/007-Create-DOI-URN-Enrichments.php create mode 100644 tests/library/Application/Update/CreateDoiUrnEnrichmentsTest.php diff --git a/library/Application/Update/CreateDoiUrnEnrichments.php b/library/Application/Update/CreateDoiUrnEnrichments.php new file mode 100644 index 000000000..565847585 --- /dev/null +++ b/library/Application/Update/CreateDoiUrnEnrichments.php @@ -0,0 +1,62 @@ + + * @copyright Copyright (c) 2018, OPUS 4 development team + * @license http://www.gnu.org/licenses/gpl.html General Public License + */ + +/** + * Update step creates enrichment key supporting handling of DOI and URN identifiers. + */ +class Application_Update_CreateDoiUrnEnrichments extends Application_Update_PluginAbstract +{ + + private $keyNames = [ + 'opus.doi.autoCreate', + 'opus.urn.autoCreate' + ]; + + + public function run() + { + foreach($this->keyNames as $name) { + $enrichmentKey = Opus_EnrichmentKey::fetchByName($name); + + if (is_null($enrichmentKey)) { + $this->log("Creating enrichment key '$name' ..."); + $enrichmentKey = new Opus_EnrichmentKey(); + $enrichmentKey->setName($name); + $enrichmentKey->store(); + $this->getLogger()->info("Enrichment key '$name' created."); + } else { + $this->getLogger()->info("Enrichment key '$name' already exists!"); + } + } + } +} diff --git a/scripts/update/006-Set-status-of-all-existing-DOIs.php b/scripts/update/006-Set-status-of-all-existing-DOIs.php index 8ce069edc..39b531e0d 100755 --- a/scripts/update/006-Set-status-of-all-existing-DOIs.php +++ b/scripts/update/006-Set-status-of-all-existing-DOIs.php @@ -37,6 +37,7 @@ * Set registration status of all existing DOIs to "registered". * Only documents with server state "published" are considered. * + * TODO move code to class for easier unit testing */ require_once dirname(__FILE__) . '/../common/update.php'; diff --git a/scripts/update/007-Create-DOI-URN-Enrichments.php b/scripts/update/007-Create-DOI-URN-Enrichments.php new file mode 100644 index 000000000..263bee023 --- /dev/null +++ b/scripts/update/007-Create-DOI-URN-Enrichments.php @@ -0,0 +1,43 @@ +#!/usr/bin/env php + + + * @copyright Copyright (c) 2018, OPUS 4 development team + * @license http://www.gnu.org/licenses/gpl.html General Public License + */ + +require_once dirname(__FILE__) . '/../common/update.php'; + +/** + * Create enrichments that are required for the handling of DOI/URN generation. + */ + +$helper = new Application_Update_CreateDoiUrnEnrichments(); +$helper->run(); diff --git a/tests/library/Application/Update/CreateDoiUrnEnrichmentsTest.php b/tests/library/Application/Update/CreateDoiUrnEnrichmentsTest.php new file mode 100644 index 000000000..64ae3be5e --- /dev/null +++ b/tests/library/Application/Update/CreateDoiUrnEnrichmentsTest.php @@ -0,0 +1,45 @@ + + * @copyright Copyright (c) 2018, OPUS 4 development team + * @license http://www.gnu.org/licenses/gpl.html General Public License + */ + +class Application_Update_CreateDoiUrnEnrichmentsTest extends ControllerTestCase +{ + + /** + * TODO The test data might contain values for these enrichments. Deleting them for the test would remove those + * values. Is there a better way? + */ + public function testCreateEnrichments() + { + $this->markTestIncomplete('Deleting existing keys for test removes enrichments values from testdata.'); + } +} From efffb0831026b045c752b87599201528d5e55d81 Mon Sep 17 00:00:00 2001 From: j3nsch Date: Wed, 20 Jun 2018 13:10:38 +0200 Subject: [PATCH 003/128] OPUSVIER-3896 Made script executable. --- scripts/update/007-Create-DOI-URN-Enrichments.php | 0 1 file changed, 0 insertions(+), 0 deletions(-) mode change 100644 => 100755 scripts/update/007-Create-DOI-URN-Enrichments.php diff --git a/scripts/update/007-Create-DOI-URN-Enrichments.php b/scripts/update/007-Create-DOI-URN-Enrichments.php old mode 100644 new mode 100755 From 82c063e7641dfebe2c8f124c24f1ed11edbba307 Mon Sep 17 00:00:00 2001 From: j3nsch Date: Wed, 20 Jun 2018 14:36:05 +0200 Subject: [PATCH 004/128] OPUSVIER-3897 Use development version of framework. --- composer.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/composer.json b/composer.json index b45b642d1..4ca1db7e1 100644 --- a/composer.json +++ b/composer.json @@ -6,7 +6,7 @@ "zendframework/zendframework1": "1.12.*", "jpgraph/jpgraph": "dev-master", "solarium/solarium": "3.4.1", - "opus4-repo/framework": "4.6.3", + "opus4-repo/framework": "dev-master", "opus4-repo/opus4-doi": "4.6.2", "opus4-repo/search": "4.5", "components/jquery": "1.12.4", From 930e359b192317f4413b8b0f9c4045c3fb04a6da Mon Sep 17 00:00:00 2001 From: j3nsch Date: Wed, 20 Jun 2018 14:51:29 +0200 Subject: [PATCH 005/128] OPUSVIER-3897 Coding style. --- .../admin/forms/Document/IdentifierDOI.php | 11 +-- .../forms/Document/IdentifierSpecific.php | 39 ++++++---- .../admin/forms/Document/IdentifierURN.php | 11 +-- modules/admin/forms/Document/Identifiers.php | 11 ++- .../Document/MultiIdentifierOtherSubForm.php | 17 +++-- .../forms/Document/MultiIdentifierSubForm.php | 76 ++++++++++++------- 6 files changed, 102 insertions(+), 63 deletions(-) diff --git a/modules/admin/forms/Document/IdentifierDOI.php b/modules/admin/forms/Document/IdentifierDOI.php index f8b669a7c..76e739e7f 100644 --- a/modules/admin/forms/Document/IdentifierDOI.php +++ b/modules/admin/forms/Document/IdentifierDOI.php @@ -31,14 +31,15 @@ * @license http://www.gnu.org/licenses/gpl.html General Public License */ -class Admin_Form_Document_IdentifierDOI extends Admin_Form_Document_IdentifierSpecific { - +class Admin_Form_Document_IdentifierDOI extends Admin_Form_Document_IdentifierSpecific +{ + protected $type = 'doi'; - public function init() { + public function init() + { parent::init(); $this->getElement(self::ELEMENT_VALUE)->addValidator(new Application_Form_Validate_DOI()); } - -} \ No newline at end of file +} diff --git a/modules/admin/forms/Document/IdentifierSpecific.php b/modules/admin/forms/Document/IdentifierSpecific.php index d93ca8365..4de092a79 100644 --- a/modules/admin/forms/Document/IdentifierSpecific.php +++ b/modules/admin/forms/Document/IdentifierSpecific.php @@ -31,13 +31,14 @@ * @license http://www.gnu.org/licenses/gpl.html General Public License */ -class Admin_Form_Document_IdentifierSpecific extends Admin_Form_AbstractModelSubForm { +class Admin_Form_Document_IdentifierSpecific extends Admin_Form_AbstractModelSubForm +{ /** * Name für Formularelement Input-Field Identifier-Wert */ const ELEMENT_VALUE = 'Value'; - + /** * Name für Formularelement Input-Field Identifier-Id */ @@ -48,12 +49,16 @@ class Admin_Form_Document_IdentifierSpecific extends Admin_Form_AbstractModelSub */ const ELEMENT_DOC_ID = 'DocId'; - protected $type; + /** + * @var string Type of identifier + */ + private $type; /** * Erzeugt Elemente für Identifier Formular. */ - public function init() { + public function init() + { parent::init(); $this->addElement('text', self::ELEMENT_VALUE, @@ -65,19 +70,21 @@ public function init() { $this->addElement('hidden', self::ELEMENT_ID); $this->addElement('hidden', self::ELEMENT_DOC_ID); } - + /** * Befüllt Formularelemente aus Opus_Identifier Instanz. * * @param Opus_Identifier $identifier */ - public function populateFromModel($identifier) { + public function populateFromModel($identifier) + { $this->getElement(self::ELEMENT_VALUE)->setValue($identifier->getValue()); $this->getElement(self::ELEMENT_ID)->setValue($identifier->getId()); $this->getElement(self::ELEMENT_DOC_ID)->setValue($identifier->getParentId()); } - - public function setValue($value) { + + public function setValue($value) + { $this->getElement(self::ELEMENT_VALUE)->setValue($value); } @@ -86,16 +93,18 @@ public function setValue($value) { * * @param Opus_Identifier $identifier */ - public function updateModel($identifier) { + public function updateModel($identifier) + { $value = $this->getElement(self::ELEMENT_VALUE)->getValue(); $identifier->setValue($value); } - public function getModel() { + public function getModel() + { $modelId = $this->getElement(self::ELEMENT_ID)->getValue(); $identifier = null; - + if (strlen(trim($modelId)) > 0) { try { $identifier = new Opus_Identifier($modelId); @@ -109,14 +118,14 @@ public function getModel() { $identifier = new Opus_Identifier(); $identifier->setType($this->type); } - + $this->updateModel($identifier); - + return $identifier; } - public function getType() { + public function getType() + { return $this->type; } - } diff --git a/modules/admin/forms/Document/IdentifierURN.php b/modules/admin/forms/Document/IdentifierURN.php index acfbcd31b..dc2a71fcc 100644 --- a/modules/admin/forms/Document/IdentifierURN.php +++ b/modules/admin/forms/Document/IdentifierURN.php @@ -31,14 +31,15 @@ * @license http://www.gnu.org/licenses/gpl.html General Public License */ -class Admin_Form_Document_IdentifierURN extends Admin_Form_Document_IdentifierSpecific { - +class Admin_Form_Document_IdentifierURN extends Admin_Form_Document_IdentifierSpecific +{ + protected $type = 'urn'; - public function init() { + public function init() + { parent::init(); $this->getElement(self::ELEMENT_VALUE)->addValidator(new Application_Form_Validate_URN()); } - -} \ No newline at end of file +} diff --git a/modules/admin/forms/Document/Identifiers.php b/modules/admin/forms/Document/Identifiers.php index 73825dcdb..bb5e3883a 100644 --- a/modules/admin/forms/Document/Identifiers.php +++ b/modules/admin/forms/Document/Identifiers.php @@ -31,9 +31,11 @@ * @license http://www.gnu.org/licenses/gpl.html General Public License */ -class Admin_Form_Document_Identifiers extends Admin_Form_Document_Section { +class Admin_Form_Document_Identifiers extends Admin_Form_Document_Section +{ - public function init() { + public function init() + { parent::init(); // visueller Balken, der den Anfang des Identifier-Blocks markiert @@ -69,9 +71,6 @@ public function init() { ) ), 'Identifiers' - ); + ); } - - - } diff --git a/modules/admin/forms/Document/MultiIdentifierOtherSubForm.php b/modules/admin/forms/Document/MultiIdentifierOtherSubForm.php index ce99cb92b..f77321a11 100644 --- a/modules/admin/forms/Document/MultiIdentifierOtherSubForm.php +++ b/modules/admin/forms/Document/MultiIdentifierOtherSubForm.php @@ -31,14 +31,17 @@ * @license http://www.gnu.org/licenses/gpl.html General Public License */ -class Admin_Form_Document_MultiIdentifierOtherSubForm extends Admin_Form_Document_MultiSubForm { +class Admin_Form_Document_MultiIdentifierOtherSubForm extends Admin_Form_Document_MultiSubForm +{ - public function init() { + public function init() + { parent::init(); $this->setLegend('admin_document_section_identifier_other'); } - public function getFieldValues($document) { + public function getFieldValues($document) + { $value = parent::getFieldValues($document); if (!is_null($value)) { $value = $this->filterIdentifier($value); @@ -53,7 +56,8 @@ public function getFieldValues($document) { * @param $identifiers * @return array */ - private function filterIdentifier($identifiers) { + private function filterIdentifier($identifiers) + { $result = array(); foreach ($identifiers as $identifier) { if ($identifier->getType() == 'doi' || $identifier->getType() == 'urn') { @@ -71,7 +75,8 @@ private function filterIdentifier($identifiers) { * * @param Opus_Document $document */ - public function updateModel($document) { + public function updateModel($document) + { $values = $this->getSubFormModels($document); $identifiers = $document->getIdentifier(); @@ -85,4 +90,4 @@ public function updateModel($document) { $result = array_merge($result, $values); $document->setIdentifier($result); } -} \ No newline at end of file +} diff --git a/modules/admin/forms/Document/MultiIdentifierSubForm.php b/modules/admin/forms/Document/MultiIdentifierSubForm.php index 31f70d48e..4208be673 100644 --- a/modules/admin/forms/Document/MultiIdentifierSubForm.php +++ b/modules/admin/forms/Document/MultiIdentifierSubForm.php @@ -31,7 +31,8 @@ * @license http://www.gnu.org/licenses/gpl.html General Public License */ -class Admin_Form_Document_MultiIdentifierSubForm extends Admin_Form_Document_MultiSubForm { +class Admin_Form_Document_MultiIdentifierSubForm extends Admin_Form_Document_MultiSubForm +{ /** * Name des Buttons zum Entfernen eines Unterformulars (z.B. Identifier). @@ -65,7 +66,8 @@ class Admin_Form_Document_MultiIdentifierSubForm extends Admin_Form_Document_Mul * * @param string $subFormClass Name der Klasse für Unterformulare */ - public function __construct($subFormClass) { + public function __construct($subFormClass) + { // Typ aus Klassennamen ableiten (Suffix nach dem letzten Unterstrich) $this->_type = substr($subFormClass, strrpos($subFormClass, '_') + 1); $this->_typeShort = strtolower(substr($this->_type, -3)); @@ -77,7 +79,8 @@ public function __construct($subFormClass) { * * init-Methode wird von ZF nach dem Aufruf des Konstruktors aufgerufen */ - public function init() { + public function init() + { parent::init(); // mehrere DOIs / URNs pro Dokument werden nicht unterstützt, so dass der Add-Button obsolet ist @@ -108,7 +111,12 @@ public function init() { $this->setRemoveEmptyCheckbox(false); } - private function addCheckbox() { + /** + * Adds a checkbox for controlling auto generation of identifier. + * @throws Zend_Form_Exception + */ + private function addCheckbox() + { $name = self::ELEMENT_CHK_AUTO . $this->_type; $this->addElement( 'checkbox', @@ -125,7 +133,8 @@ private function addCheckbox() { * * @param Opus_Document $document */ - public function populateFromModel($document) { + public function populateFromModel($document) + { // muss die Checkbox entfernt werden? $removeCheckbox = $this->removeCheckboxForPublishedDocs($document); @@ -166,7 +175,8 @@ public function populateFromModel($document) { * * @return _subFormClass */ - protected function _addSubForm($position, $disableGenerateButton = null) { + protected function _addSubForm($position, $disableGenerateButton = null) + { $subForm = $this->createSubForm(); if (is_null($disableGenerateButton)) { @@ -198,8 +208,8 @@ protected function _addSubForm($position, $disableGenerateButton = null) { * und auch die Anzeige der Checkbox (aktiviert oder nicht aktiviert) * */ - private function addGenerateAtPublishCheckbox($document) { - + private function addGenerateAtPublishCheckbox($document) + { $autoGenerateCheckbox = $this->getElement(self::ELEMENT_CHK_AUTO . $this->_type); if (is_null($autoGenerateCheckbox)) { @@ -226,15 +236,16 @@ private function addGenerateAtPublishCheckbox($document) { break; } } - + /** * bei bereits veröffentlichten Dokumenten soll die Checkbox zum automatischen * Setzen der ID nicht angezeigt werden - * + * * @param Opus_Document $document das zu editierende Dokument * @return liefert true zurück, wenn die Checkbox entfernt wurde */ - private function removeCheckboxForPublishedDocs($document) { + private function removeCheckboxForPublishedDocs($document) + { if ($document->getServerState() == 'published'){ $this->removeElement(self::ELEMENT_CHK_AUTO . $this->_type); return true; @@ -248,7 +259,8 @@ private function removeCheckboxForPublishedDocs($document) { * @param array $identifiers Liste mit Elementen vom Typ Opus_Identifier * @return array mit Elementen vom Typ Opus_Identifier (nach der Filterung auf Basis des Typs) */ - private function filterIdentifier($identifiers) { + private function filterIdentifier($identifiers) + { $result = array(); foreach ($identifiers as $identifier) { $type = $identifier->getType(); @@ -256,7 +268,7 @@ private function filterIdentifier($identifiers) { $result[] = $identifier; } } - return $result; + return $result; } /** @@ -264,7 +276,8 @@ private function filterIdentifier($identifiers) { * * TODO was passiert wenn ein invalides Formular auftaucht beim anschließenden $form->populate()? */ - public function constructFromPost($post, $document = null) { + public function constructFromPost($post, $document = null) + { $keys = array_keys($post); $removeCheckbox = $this->removeCheckboxForPublishedDocs($document); @@ -310,8 +323,8 @@ public function constructFromPost($post, $document = null) { * @param array $context POST Daten für gesamtes Formular * @return string Ergebnis der Verarbeitung */ - public function processPost($data, $context) { - + public function processPost($data, $context) + { foreach ($data as $subFormName => $subdata) { $subform = $this->getSubForm($subFormName); if (!is_null($subform)) { @@ -358,7 +371,8 @@ public function processPost($data, $context) { return null; } - protected function processPostGenerate($subform, $docId) { + protected function processPostGenerate($subform, $docId) + { switch ($this->_subFormClass) { case 'Admin_Form_Document_IdentifierDOI': try { @@ -405,7 +419,8 @@ protected function processPostGenerate($subform, $docId) { * * @param Opus_Document $document */ - public function updateModel($document) { + public function updateModel($document) + { // Array von Opus_Identifier Objekten eines Typs $values = $this->getSubFormModels($document); @@ -458,7 +473,8 @@ public function updateModel($document) { * * @param $document */ - private function handleEnrichment($document) { + private function handleEnrichment($document) + { $autoGenerateCheckbox = $this->getElement(self::ELEMENT_CHK_AUTO . $this->_type); if (!is_null($autoGenerateCheckbox)) { // Null-Check wichtig, da Checkbox nur bei nicht veröffentlichten Dokumenten angezeigt wird @@ -539,7 +555,8 @@ private function addGenerateButton($subform, $enabled = true) { * * @param type $subform */ - protected function prepareSubFormDecorators($subform) { + protected function prepareSubFormDecorators($subform) + { $subform->addDecorator(array('tableRowWrapper' => 'HtmlTag'), array('tag' => 'tr')); $this->applyDecoratorsToElements($subform->getElements()); } @@ -547,7 +564,8 @@ protected function prepareSubFormDecorators($subform) { /** * Erzeugt den Button für das Entfernen des 2. bis n-ten Identifiers des Typs. */ - protected function addRemoveButton($subform) { + protected function addRemoveButton($subform) + { $button = $this->createElement( 'submit', self::ELEMENT_REMOVE, @@ -558,7 +576,11 @@ protected function addRemoveButton($subform) { $subform->addElement($button); } - public function isEmpty() { + /** + * @return bool + */ + public function isEmpty() + { return false; } @@ -571,7 +593,8 @@ public function isEmpty() { * * @param string $name Name des Unterformulars das entfernt werden sollte */ - protected function _removeSubForm($name) { + protected function _removeSubForm($name) + { $order = $this->getSubForm($name)->getOrder(); $this->removeSubForm($name); return $order; @@ -580,7 +603,8 @@ protected function _removeSubForm($name) { /** * Methode wurde überschrieben, da Spezialbehandlung durch die Checkbox erforderlich ist */ - protected function _removeGapsInSubFormOrder() { + protected function _removeGapsInSubFormOrder() + { $subforms = $this->getSubForms(); $renamedSubforms = array(); @@ -599,8 +623,8 @@ protected function _removeGapsInSubFormOrder() { $this->setSubForms($renamedSubforms); } - private function getEnrichmentKeyName() { + private function getEnrichmentKeyName() + { return 'opus.' . $this->_typeShort . '.autoCreate'; } - } From 8f50d1be3c497da0d739ead97b8bca7bdfd62feb Mon Sep 17 00:00:00 2001 From: j3nsch Date: Thu, 12 Jul 2018 16:02:04 +0200 Subject: [PATCH 006/128] OPUSVIER-3907 - Pagination prev-links always on if start lg zero. --- modules/solrsearch/views/scripts/index/pagination.phtml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/modules/solrsearch/views/scripts/index/pagination.phtml b/modules/solrsearch/views/scripts/index/pagination.phtml index 9ae705b5b..eb3802fbf 100644 --- a/modules/solrsearch/views/scripts/index/pagination.phtml +++ b/modules/solrsearch/views/scripts/index/pagination.phtml @@ -37,7 +37,7 @@ - element->getMessage() ?> + element->getMessage() ?>
escape($message) ?>
-
+ -err('Use of partial \'docstatus.phtml\' without document = null.'); ?> +err('Use of partial \'actionbox.phtml\' without document.'); ?> diff --git a/modules/frontdoor/controllers/IndexController.php b/modules/frontdoor/controllers/IndexController.php index d4624205a..b24ddc806 100644 --- a/modules/frontdoor/controllers/IndexController.php +++ b/modules/frontdoor/controllers/IndexController.php @@ -155,7 +155,7 @@ public function indexAction() { $this->incrementStatisticsCounter($docId); - $actionbox = new Admin_Form_ActionBox(); + $actionbox = new Frontdoor_Form_FrontdoorActionBox(); $actionbox->prepareRenderingAsView(); $actionbox->populateFromModel($document); $this->view->adminform = $actionbox; diff --git a/modules/frontdoor/forms/FrontdoorActionBox.php b/modules/frontdoor/forms/FrontdoorActionBox.php new file mode 100644 index 000000000..880a36147 --- /dev/null +++ b/modules/frontdoor/forms/FrontdoorActionBox.php @@ -0,0 +1,55 @@ + + * @copyright Copyright (c) 2018, OPUS 4 development team + * @license http://www.gnu.org/licenses/gpl.html General Public License + */ + +/** + * Modifies ActionBox for frontdoor to replace frontdoor link with link to administration. + */ +class Frontdoor_Form_FrontdoorActionBox extends Admin_Form_ActionBox +{ + + public function getViewActionLinks() + { + $actions = parent::getViewActionLinks(); + + unset($actions['frontdoor']); + + $actions['view'] = array( + 'module' => 'admin', + 'controller' => 'document', + 'action' => 'index', + 'id' => $this->getDocument()->getId() + ); + + return $actions; + } +} diff --git a/modules/frontdoor/views/scripts/actionbox.phtml b/modules/frontdoor/views/scripts/actionbox.phtml deleted file mode 100644 index caaf2cff1..000000000 --- a/modules/frontdoor/views/scripts/actionbox.phtml +++ /dev/null @@ -1,93 +0,0 @@ - - * @copyright Copyright (c) 2008-2012, OPUS 4 development team - * @license http://www.gnu.org/licenses/gpl.html General Public License - * @version $Id$ - */ -?> - -element->getDocument(); - $currentState = $document->getServerState(); - $stateLinks = $this->element->getStateLinks(); - $actionLinks = $this->element->getFrontdoorActionLinks(); -?> - - -
-
-
- element->isViewModeEnabled() || count($stateLinks) == 0) : ?> -
-
translate('ServerState-short')) . ':'?>
-
translate('Opus_Document_ServerState_Value_' - . ucfirst($document->getServerState()))) ?>
-
- - - -
-
-
-
translate('ServerDatePublished-short') . ':'?>
-
formatDate()->formatOpusDate($document->getServerDatePublished(), false) ?>
-
-
-
translate('ServerDateModified-short') . ':'?>
-
formatDate()->formatOpusDate($document->getServerDateModified(), true) ?>
-
-
-
- -
-
-
- -err('Use of partial \'actionbox.phtml\' without document = null.'); ?> - - From 5817c81ddf2c950f805627d32fd044e41d3026bf Mon Sep 17 00:00:00 2001 From: j3nsch Date: Tue, 7 Aug 2018 14:22:01 +0200 Subject: [PATCH 026/128] OPUSVIER-3913 Fixed function name in subclass. --- .../controllers/FormControllerTest.php | 42 +++++++++---------- 1 file changed, 21 insertions(+), 21 deletions(-) diff --git a/tests/modules/publish/controllers/FormControllerTest.php b/tests/modules/publish/controllers/FormControllerTest.php index e944870ba..1bbe3e79e 100644 --- a/tests/modules/publish/controllers/FormControllerTest.php +++ b/tests/modules/publish/controllers/FormControllerTest.php @@ -45,7 +45,7 @@ public function setUp() { parent::setUp(); $this->useGerman(); } - + /** * Test GET on upload action */ @@ -85,7 +85,7 @@ public function testUploadActionWithInvalidDummyPost() { $this->assertResponseCode(200); $this->assertController('form'); $this->assertAction('upload'); - + $body = $this->getResponse()->getBody(); $this->assertContains('Es sind Fehler aufgetreten. Bitte beachten Sie die Fehlermeldungen an den Formularfeldern.', $body); @@ -136,7 +136,7 @@ public function testCheckActionWithValidPostAndAddButton() { $this->assertAction('check'); $body = $this->getResponse()->getBody(); - + $this->assertContains('TitleMain_1', $body); $this->assertContains('TitleMainLanguage_1', $body); $this->assertContains('TitleMain_2', $body); @@ -445,14 +445,14 @@ public function testFormManipulationForBibliography() { } else { $config->form->first->bibliographie = $oldval; } - + $doc = new Opus_Document($session->documentId); $belongsToBibliography = $doc->getBelongsToBibliography(); $doc->deletePermanent(); $this->assertResponseCode(200); $this->assertNotContains("Es sind Fehler aufgetreten.", $this->response->getBody()); - $this->assertFalse((boolean) $belongsToBibliography, 'Expected that document does not belong to bibliography'); + $this->assertFalse((boolean) $belongsToBibliography, 'Expected that document does not belong to bibliography'); } /** @@ -565,7 +565,7 @@ private function fileNoticeOnSecondFormPage($value) { } } - private function addTestDocument($session, $documentType) { + private function addTemporaryTestDocument($session, $documentType) { $doc = $this->createTemporaryDoc(); $session->documentType = $documentType; @@ -578,7 +578,7 @@ private function addTestDocument($session, $documentType) { */ public function testCheckActionWithAddButton() { $session = new Zend_Session_Namespace('Publish'); - $this->addTestDocument($session, 'preprint'); + $this->addTemporaryTestDocument($session, 'preprint'); $data = array( 'PersonSubmitterFirstName_1' => '', 'PersonSubmitterLastName_1' => '', @@ -628,7 +628,7 @@ public function testCheckActionWithAddButton() { */ public function testCheckActionWithDeleteButton() { $session = new Zend_Session_Namespace('Publish'); - $this->addTestDocument($session, 'preprint'); + $this->addTemporaryTestDocument($session, 'preprint'); $session->additionalFields['TitleMain'] = '2'; $data = array( @@ -682,7 +682,7 @@ public function testCheckActionWithDeleteButton() { */ public function testCheckActionWithBrowseDownButton() { $session = new Zend_Session_Namespace('Publish'); - $this->addTestDocument($session, 'preprint'); + $this->addTemporaryTestDocument($session, 'preprint'); $session->additionalFields['Institute'] = '1'; $session->additionalFields['collId0Institute_1'] = '1'; $session->additionalFields['stepInstitute_1'] = '1'; @@ -737,7 +737,7 @@ public function testCheckActionWithBrowseDownButton() { */ public function testCheckActionWithBrowseUpButton() { $session = new Zend_Session_Namespace('Publish'); - $this->addTestDocument($session, 'preprint'); + $this->addTemporaryTestDocument($session, 'preprint'); $session->additionalFields['Institute'] = '1'; $session->additionalFields['collId0Institute_1'] = '1'; $session->additionalFields['collId1Institute_1'] = '15994'; @@ -793,7 +793,7 @@ public function testCheckActionWithBrowseUpButton() { */ public function testCheckActionWithMissingButton() { $session = new Zend_Session_Namespace('Publish'); - $this->addTestDocument($session, 'preprint'); + $this->addTemporaryTestDocument($session, 'preprint'); $session->additionalFields['PersonSubmitter'] = '1'; $session->additionalFields['TitleMain'] = '1'; $session->additionalFields['TitleAbstract'] = '1'; @@ -870,7 +870,7 @@ public function testManipulatePostMissingTitleMainLanguage() { ->setPost(array( 'PersonSubmitterLastName_1' => 'Doe', 'PersonSubmitterEmail_1' => 'doe@example.org', - 'TitleMain_1' => 'Entenhausen', + 'TitleMain_1' => 'Entenhausen', 'PersonAuthorLastName_1' => 'AuthorLastName', 'CompletedDate' => '22.01.2011', 'Language' => 'deu', @@ -918,7 +918,7 @@ public function testManipulatePostMissingTitleAbstractLanguage() { $this->assertController('form'); $this->assertAction('check'); - $this->assertNotContains('Undefined index: TitleAbstractLanguage_1', $this->getResponse()->getBody()); + $this->assertNotContains('Undefined index: TitleAbstractLanguage_1', $this->getResponse()->getBody()); } public function testManipulatePostMissingTitleParentLanguage() { @@ -1021,7 +1021,7 @@ public function testBarfooTemplateIsRenderedForDoctypeFoobar() { $this->dispatch('/publish/form/check'); - $respBody = $this->getResponse()->getBody(); + $respBody = $this->getResponse()->getBody(); $this->assertContains("
- + + Edit Metadata @@ -51,7 +51,7 @@ Zuweisung(en) ändern - + Edit assignment(s) @@ -60,7 +60,7 @@ Zuweisung(en) ändern - + Edit assignment(s) @@ -69,7 +69,7 @@ Zuweisung(en) ändern - + Add New @@ -87,7 +87,7 @@ Neue Zuweisung hinzufügen - + Add new Assignment @@ -96,7 +96,7 @@ Neue Zuweisung hinzufügen - + General @@ -123,7 +123,7 @@ Zusammenfassungen - + Titles @@ -132,7 +132,7 @@ Titel - + Translated Titles @@ -141,7 +141,7 @@ Übersetzte Titel - + Parent Titles @@ -150,7 +150,7 @@ Titel übergeordneter Werke - + Subtitles @@ -159,7 +159,7 @@ Untertitel - + Persons @@ -168,7 +168,7 @@ Personen - + Authors @@ -177,7 +177,7 @@ Autoren - + Editors @@ -195,7 +195,7 @@ Betreuer - + Contributors @@ -213,7 +213,7 @@ Gutachter - + Translators @@ -221,8 +221,8 @@ Übersetzer - - + + Other Persons @@ -231,7 +231,7 @@ Weitere Personen - + Submitter @@ -240,7 +240,7 @@ Einsteller - + Subjects @@ -257,7 +257,7 @@ GND-Schlagwörter - + PSyndex Keywords @@ -266,7 +266,7 @@ PSyndex Schlagwörter - + Tags @@ -284,7 +284,7 @@ Identifikatoren - + Other Identifiers @@ -293,7 +293,7 @@ Andere Identifikatoren - + DOI @@ -340,7 +340,7 @@ - + Thesis statement, DNB @@ -358,7 +358,7 @@ Sammlungen, Klassifikationen - + Abstracts and Subjects @@ -367,7 +367,7 @@ Inhaltliche Erschließung - + Publishing Intitutions @@ -376,7 +376,7 @@ Veröffentlichende Institutionen - + Granting Institutions @@ -385,7 +385,7 @@ Titel verleihende Institutionen - + @@ -431,7 +431,7 @@ Patente - + Bibliographic Information @@ -827,7 +827,7 @@ Die Dokument-ID existiert nicht. - + Document cannot be saved, because some input is not valid. @@ -854,7 +854,7 @@ Ein Titel in der Dokumentensprache '%1$s' ist notwendig. - + Languages can only be used once. @@ -900,14 +900,6 @@ - - - Add metadata - - - Metadaten hinzufügen - - @@ -998,7 +990,7 @@ Fehler beim Entfernen. - + Move @@ -1007,7 +999,7 @@ Verschieben - + Actions @@ -1016,7 +1008,7 @@ Aktionen - + Change role @@ -1025,7 +1017,7 @@ Rolle ändern - + or @@ -1071,6 +1063,15 @@ + + + New document created and opened for editing. + + + Neues Dokument erzeugt und zum Editieren geöffnet. + + + \ No newline at end of file diff --git a/modules/admin/views/scripts/documents/index.phtml b/modules/admin/views/scripts/documents/index.phtml index bd6c54182..ba89132ba 100644 --- a/modules/admin/views/scripts/documents/index.phtml +++ b/modules/admin/views/scripts/documents/index.phtml @@ -86,7 +86,10 @@ - + diff --git a/modules/default/language/admin.tmx b/modules/default/language/admin.tmx index a39695a3b..715c8d4f7 100644 --- a/modules/default/language/admin.tmx +++ b/modules/default/language/admin.tmx @@ -23,7 +23,7 @@ Dateien - + Frontdoor @@ -41,7 +41,7 @@ Administration - + Setup @@ -50,7 +50,7 @@ Oberflächenanpassungen - + Add @@ -59,7 +59,7 @@ Hinzufügen - + Remove @@ -68,7 +68,7 @@ Entfernen - + Edit @@ -77,7 +77,7 @@ Editieren - + Generate now @@ -95,7 +95,7 @@ Erster - + Up @@ -104,7 +104,7 @@ Hoch - + Down @@ -113,7 +113,7 @@ Runter - + Last @@ -122,7 +122,7 @@ Letzter - + Accept Sort Order @@ -168,6 +168,33 @@ - + + + Create + + + Neu + + + + + + Create new document and open it for editing. + + + Neues document erzeugen und zum Editieren öffnen. + + + + + + Duplicate + + + Duplizieren + + + + From 96c8d96612b83f64f58a617a37292d3967728b27 Mon Sep 17 00:00:00 2001 From: BioFreak95 Date: Thu, 9 Aug 2018 16:28:14 +0200 Subject: [PATCH 028/128] OPUSVIER-3925 fixed --- .../modules/admin/controllers/DnbinstituteControllerTest.php | 3 ++- .../admin/controllers/EnrichmentkeyControllerTest.php | 3 ++- tests/modules/admin/controllers/IprangeControllerTest.php | 3 ++- tests/modules/admin/controllers/LanguageControllerTest.php | 3 ++- tests/modules/admin/controllers/LicenceControllerTest.php | 3 ++- tests/modules/admin/controllers/PersonControllerTest.php | 5 +++-- tests/modules/admin/controllers/SeriesControllerTest.php | 3 ++- tests/support/CrudControllerTestCase.php | 2 +- 8 files changed, 16 insertions(+), 9 deletions(-) diff --git a/tests/modules/admin/controllers/DnbinstituteControllerTest.php b/tests/modules/admin/controllers/DnbinstituteControllerTest.php index 93ca9b83b..5924a250d 100644 --- a/tests/modules/admin/controllers/DnbinstituteControllerTest.php +++ b/tests/modules/admin/controllers/DnbinstituteControllerTest.php @@ -26,6 +26,7 @@ * * @category Tests * @author Jens Schwidder + * @author Maximilian Salomon * @copyright Copyright (c) 2008-2018, OPUS 4 development team * @license http://www.gnu.org/licenses/gpl.html General Public License */ @@ -174,7 +175,7 @@ public function testEditActionShowForm() { $this->assertQueryContentContains('div#Name-element', 'Foobar Universität'); $this->assertQuery('li.save-element'); $this->assertQuery('li.cancel-element'); - $this->assertQueryCount(1, 'input#Id'); + $this->assertQueryCount('input#Id', 1); } public function testEditActionSave() { diff --git a/tests/modules/admin/controllers/EnrichmentkeyControllerTest.php b/tests/modules/admin/controllers/EnrichmentkeyControllerTest.php index 07be49c3e..de889080b 100644 --- a/tests/modules/admin/controllers/EnrichmentkeyControllerTest.php +++ b/tests/modules/admin/controllers/EnrichmentkeyControllerTest.php @@ -26,6 +26,7 @@ * * @category Tests * @author Gunar Maiwald + * @author Maximilian Salomon * @copyright Copyright (c) 2008-2018, OPUS 4 development team * @license http://www.gnu.org/licenses/gpl.html General Public License */ @@ -149,7 +150,7 @@ public function testEditActionShowForm() { $this->assertQueryContentContains('div#Name-element', 'Name'); $this->assertQuery('li.save-element'); $this->assertQuery('li.cancel-element'); - $this->assertQueryCount(1, 'input#Id'); + $this->assertQueryCount('input#Id', 1); } public function testEditActionShowFormForProtectedEnrichment() { diff --git a/tests/modules/admin/controllers/IprangeControllerTest.php b/tests/modules/admin/controllers/IprangeControllerTest.php index 4e4a86c8f..4c800f5c1 100644 --- a/tests/modules/admin/controllers/IprangeControllerTest.php +++ b/tests/modules/admin/controllers/IprangeControllerTest.php @@ -27,6 +27,7 @@ * @category Tests * @package Admin * @author Jens Schwidder + * @author Maximilian Salomon * @copyright Copyright (c) 2008-2018, OPUS 4 development team * @license http://www.gnu.org/licenses/gpl.html General Public License */ @@ -164,7 +165,7 @@ public function testEditActionShowForm() $this->assertQueryContentContains('div#Endingip-element', '127.0.0.2'); $this->assertQuery('li.save-element'); $this->assertQuery('li.cancel-element'); - $this->assertQueryCount(1, 'input#Id'); + $this->assertQueryCount('input#Id', 1); } public function testEditActionSave() diff --git a/tests/modules/admin/controllers/LanguageControllerTest.php b/tests/modules/admin/controllers/LanguageControllerTest.php index 9c9df3810..b2e1fcaf4 100644 --- a/tests/modules/admin/controllers/LanguageControllerTest.php +++ b/tests/modules/admin/controllers/LanguageControllerTest.php @@ -26,6 +26,7 @@ * * @category Tests * @author Jens Schwidder + * @author Maximilian Salomon * @copyright Copyright (c) 2008-2018, OPUS 4 development team * @license http://www.gnu.org/licenses/gpl.html General Public License */ @@ -171,7 +172,7 @@ public function testEditActionShowForm() { $this->assertQueryContentContains('div#RefName-element', 'Italian'); $this->assertQuery('li.save-element'); $this->assertQuery('li.cancel-element'); - $this->assertQueryCount(1, 'input#Id'); + $this->assertQueryCount('input#Id', 1); } public function testEditActionSave() { diff --git a/tests/modules/admin/controllers/LicenceControllerTest.php b/tests/modules/admin/controllers/LicenceControllerTest.php index e8e47e71d..1ee01f264 100644 --- a/tests/modules/admin/controllers/LicenceControllerTest.php +++ b/tests/modules/admin/controllers/LicenceControllerTest.php @@ -31,6 +31,7 @@ * @category Tests * @package Admin * @author Jens Schwidder + * @author Maximilian Salomon * @copyright Copyright (c) 2008-2018, OPUS 4 development team * @license http://www.gnu.org/licenses/gpl.html General Public License * @@ -193,7 +194,7 @@ public function testEditActionShowForm() { $this->assertQueryContentContains('div#NameLong-element', 'Creative Commons - CC BY-ND - Namensnennung'); $this->assertQuery('li.save-element'); $this->assertQuery('li.cancel-element'); - $this->assertQueryCount(1, 'input#Id'); + $this->assertQueryCount('input#Id', 1); } public function testEditActionSave() { diff --git a/tests/modules/admin/controllers/PersonControllerTest.php b/tests/modules/admin/controllers/PersonControllerTest.php index ed286e543..580369fd5 100644 --- a/tests/modules/admin/controllers/PersonControllerTest.php +++ b/tests/modules/admin/controllers/PersonControllerTest.php @@ -27,6 +27,7 @@ * @category Tests * @package Admin * @author Jens Schwidder + * @author Maximilian Salomon * @copyright Copyright (c) 2008-2018, OPUS 4 development team * @license http://www.gnu.org/licenses/gpl.html General Public License * @@ -271,7 +272,7 @@ public function testIndexFilter() $this->dispatch('/admin/person/index/filter/Walruss'); $this->assertResponseCode(200); - $this->assertQueryCount(1, 'td.lastname'); + $this->assertQueryCount('td.lastname', 1); $this->assertQueryContentContains('td.lastname', 'Walruss'); $this->assertQueryContentContains('td.firstname', 'Wally'); $this->assertQueryContentContains('td.documents', 8); @@ -282,7 +283,7 @@ public function testIndexFilterCaseInsensitive() $this->dispatch('/admin/person/index/filter/wAlRuSs'); $this->assertResponseCode(200); - $this->assertQueryCount(1, 'td.lastname'); + $this->assertQueryCount('td.lastname', 1); $this->assertNotQueryContentContains('td.lastname', 'wAlRuSs'); $this->assertQueryContentContains('td.lastname', 'Walruss'); $this->assertQueryContentContains('td.firstname', 'Wally'); diff --git a/tests/modules/admin/controllers/SeriesControllerTest.php b/tests/modules/admin/controllers/SeriesControllerTest.php index 19179e20e..a851d8dc6 100644 --- a/tests/modules/admin/controllers/SeriesControllerTest.php +++ b/tests/modules/admin/controllers/SeriesControllerTest.php @@ -28,6 +28,7 @@ * @package Admin * @author Jens Schwidder * @author Michael Lang + * @author Maximilian Salomon * @copyright Copyright (c) 2008-2018, OPUS 4 development team * @license http://www.gnu.org/licenses/gpl.html General Public License */ @@ -154,7 +155,7 @@ public function testEditActionShowForm() { $this->assertQueryContentContains('div#Title-element', 'Visible Series'); $this->assertQuery('li.save-element'); $this->assertQuery('li.cancel-element'); - $this->assertQueryCount(1, 'input#Id'); + $this->assertQueryCount('input#Id', 1); } public function testEditActionSave() { diff --git a/tests/support/CrudControllerTestCase.php b/tests/support/CrudControllerTestCase.php index 1e4c956e7..7e3c96d59 100644 --- a/tests/support/CrudControllerTestCase.php +++ b/tests/support/CrudControllerTestCase.php @@ -142,7 +142,7 @@ public function testNewActionShowForm() { $this->assertQuery('li.save-element'); $this->assertQuery('li.cancel-element'); - $this->assertQueryCount(1, 'input#Id'); + $this->assertQueryCount('input#Id', 1); } public function testEditActionBadId() { From bbc30df61c993841fd8f4d6d7329d63bd6f0757b Mon Sep 17 00:00:00 2001 From: BioFreak95 Date: Fri, 10 Aug 2018 13:17:44 +0200 Subject: [PATCH 029/128] OPUSVIER-3926 fixed --- tests/library/Application/Form/Decorator/FileHashTest.php | 2 ++ tests/library/Application/XsltTest.php | 1 + tests/modules/AppModeTest.php | 1 + tests/modules/admin/controllers/DocumentControllerTest.php | 1 + tests/modules/admin/controllers/EnrichmentkeyControllerTest.php | 1 + tests/modules/admin/controllers/ReportControllerTest.php | 1 + tests/modules/admin/controllers/StatisticControllerTest.php | 1 + tests/modules/admin/forms/FileTest.php | 1 + tests/modules/admin/forms/Person/ChangesTest.php | 1 + tests/modules/solrsearch/controllers/IndexControllerTest.php | 1 + 10 files changed, 11 insertions(+) diff --git a/tests/library/Application/Form/Decorator/FileHashTest.php b/tests/library/Application/Form/Decorator/FileHashTest.php index 187e5060d..70e1ff240 100644 --- a/tests/library/Application/Form/Decorator/FileHashTest.php +++ b/tests/library/Application/Form/Decorator/FileHashTest.php @@ -101,6 +101,7 @@ public function testRenderWithIst() { } public function testRenderWithMissingFile() { + $this->useEnglish(); $element = new Application_Form_Element_FileHash('name'); $file = new Opus_File(123); @@ -127,6 +128,7 @@ public function testRenderWithMissingFile() { } public function testRenderWithFileTooBig() { + $this->useEnglish(); $config = Zend_Registry::get('Zend_Config'); $config->merge(new Zend_Config(array('checksum' => array('maxVerificationSize' => '0')))); diff --git a/tests/library/Application/XsltTest.php b/tests/library/Application/XsltTest.php index aabf6022f..9af438249 100644 --- a/tests/library/Application/XsltTest.php +++ b/tests/library/Application/XsltTest.php @@ -66,6 +66,7 @@ public function testFindHelper() public function testCallStatic() { + $this->useEnglish(); $this->assertEquals('Yes', Application_Xslt::translate('answer_yes')); } diff --git a/tests/modules/AppModeTest.php b/tests/modules/AppModeTest.php index 60d65e8eb..e599c476a 100644 --- a/tests/modules/AppModeTest.php +++ b/tests/modules/AppModeTest.php @@ -45,6 +45,7 @@ public function testProductionMode() { public function testTestingMode() { parent::setUpWithEnv('testing'); + $this->useEnglish(); $this->dispatch('/home'); $this->assertContains('NON PRODUCTION ENVIRONMENT (testing)', $this->getResponse()->getBody()); } diff --git a/tests/modules/admin/controllers/DocumentControllerTest.php b/tests/modules/admin/controllers/DocumentControllerTest.php index aab6dcded..54c8ad3f7 100644 --- a/tests/modules/admin/controllers/DocumentControllerTest.php +++ b/tests/modules/admin/controllers/DocumentControllerTest.php @@ -266,6 +266,7 @@ protected function verifyNavigationLinks($expectedLinks) { } public function testEditActionValidXHTML() { + $this->useEnglish(); $this->dispatch('/admin/document/edit/id/146'); $this->assertResponseCode(200); $this->assertModule('admin'); diff --git a/tests/modules/admin/controllers/EnrichmentkeyControllerTest.php b/tests/modules/admin/controllers/EnrichmentkeyControllerTest.php index 07be49c3e..3b8111ed3 100644 --- a/tests/modules/admin/controllers/EnrichmentkeyControllerTest.php +++ b/tests/modules/admin/controllers/EnrichmentkeyControllerTest.php @@ -123,6 +123,7 @@ public function testNewActionCancel() { } public function testNewActionSaveForExistingEnrichment() { + $this->useEnglish(); $this->createsModels = true; $post = array( diff --git a/tests/modules/admin/controllers/ReportControllerTest.php b/tests/modules/admin/controllers/ReportControllerTest.php index 01348ca9e..bf1bf68e4 100644 --- a/tests/modules/admin/controllers/ReportControllerTest.php +++ b/tests/modules/admin/controllers/ReportControllerTest.php @@ -83,6 +83,7 @@ public function tearDown() { } public function testDoiActionWithEmptyResult() { + $this->useEnglish(); $this->dispatch('/admin/report/doi'); $this->assertResponseCode(200); $this->assertModule('admin'); diff --git a/tests/modules/admin/controllers/StatisticControllerTest.php b/tests/modules/admin/controllers/StatisticControllerTest.php index f6c328bfa..9d2010091 100644 --- a/tests/modules/admin/controllers/StatisticControllerTest.php +++ b/tests/modules/admin/controllers/StatisticControllerTest.php @@ -62,6 +62,7 @@ public function testShowAction() { * Fragt ab, ob bei einem falschen Jahr die Indexseite angezeigt wird */ public function testIndexActionWithWrongYear() { + $this->useEnglish(); $this->request ->setMethod('POST') ->setPost(array('selectedYear' => '1337')); diff --git a/tests/modules/admin/forms/FileTest.php b/tests/modules/admin/forms/FileTest.php index 45649fdd4..7660c734f 100644 --- a/tests/modules/admin/forms/FileTest.php +++ b/tests/modules/admin/forms/FileTest.php @@ -48,6 +48,7 @@ public function testConstructForm() { } public function testPopulateFromModel() { + $this->useEnglish(); $form = new Admin_Form_File(); $file = new Opus_File(126); // hängt an Testdokument 146 diff --git a/tests/modules/admin/forms/Person/ChangesTest.php b/tests/modules/admin/forms/Person/ChangesTest.php index 680b40654..9fd60e1a0 100644 --- a/tests/modules/admin/forms/Person/ChangesTest.php +++ b/tests/modules/admin/forms/Person/ChangesTest.php @@ -197,6 +197,7 @@ public function testGetPreparedChangesMerged() public function testRender() { + $this->useEnglish(); $form = new Admin_Form_Person_Changes(); $form->setOldValues(array( diff --git a/tests/modules/solrsearch/controllers/IndexControllerTest.php b/tests/modules/solrsearch/controllers/IndexControllerTest.php index 2ef08dfb9..6b399d215 100644 --- a/tests/modules/solrsearch/controllers/IndexControllerTest.php +++ b/tests/modules/solrsearch/controllers/IndexControllerTest.php @@ -587,6 +587,7 @@ public function testInvalidSearchQueryReturns500() { } public function testUnavailableSolrServerReturns503() { + $this->useEnglish(); $this->requireSolrConfig(); // manipulate solr configuration From b1d1eeced1e19ee52ca5f4a3ec2cf45b99693ae6 Mon Sep 17 00:00:00 2001 From: BioFreak95 Date: Fri, 10 Aug 2018 13:28:18 +0200 Subject: [PATCH 030/128] OPUSVIER-3926 Some changes in Header --- tests/library/Application/Form/Decorator/FileHashTest.php | 3 ++- tests/library/Application/XsltTest.php | 3 ++- tests/modules/AppModeTest.php | 3 ++- tests/modules/admin/controllers/DocumentControllerTest.php | 1 + .../modules/admin/controllers/EnrichmentkeyControllerTest.php | 1 + tests/modules/admin/controllers/ReportControllerTest.php | 1 + tests/modules/admin/controllers/StatisticControllerTest.php | 1 + tests/modules/admin/forms/FileTest.php | 3 ++- tests/modules/admin/forms/Person/ChangesTest.php | 3 ++- tests/modules/solrsearch/controllers/IndexControllerTest.php | 1 + 10 files changed, 15 insertions(+), 5 deletions(-) diff --git a/tests/library/Application/Form/Decorator/FileHashTest.php b/tests/library/Application/Form/Decorator/FileHashTest.php index 70e1ff240..fdca89ad1 100644 --- a/tests/library/Application/Form/Decorator/FileHashTest.php +++ b/tests/library/Application/Form/Decorator/FileHashTest.php @@ -27,7 +27,8 @@ * @category Application Unit Test * @package Application_Form_Decorator * @author Jens Schwidder - * @copyright Copyright (c) 2008-2013, OPUS 4 development team + * @author Maximilian Salomon + * @copyright Copyright (c) 2008-2018, OPUS 4 development team * @license http://www.gnu.org/licenses/gpl.html General Public License * @version $Id$ */ diff --git a/tests/library/Application/XsltTest.php b/tests/library/Application/XsltTest.php index 9af438249..ead76c6a5 100644 --- a/tests/library/Application/XsltTest.php +++ b/tests/library/Application/XsltTest.php @@ -27,7 +27,8 @@ * @category Application Unit Test * @package Application * @author Jens Schwidder - * @copyright Copyright (c) 2017, OPUS 4 development team + * @author Maximilian Salomon + * @copyright Copyright (c) 2018, OPUS 4 development team * @license http://www.gnu.org/licenses/gpl.html General Public License */ diff --git a/tests/modules/AppModeTest.php b/tests/modules/AppModeTest.php index e599c476a..31ad3fe63 100644 --- a/tests/modules/AppModeTest.php +++ b/tests/modules/AppModeTest.php @@ -26,7 +26,8 @@ * * @category Application Unit Test * @author Sascha Szott - * @copyright Copyright (c) 2008-2013, OPUS 4 development team + * @author Maximilian Salomon + * @copyright Copyright (c) 2008-2018, OPUS 4 development team * @license http://www.gnu.org/licenses/gpl.html General Public License * @version $Id$ */ diff --git a/tests/modules/admin/controllers/DocumentControllerTest.php b/tests/modules/admin/controllers/DocumentControllerTest.php index 54c8ad3f7..7df637279 100644 --- a/tests/modules/admin/controllers/DocumentControllerTest.php +++ b/tests/modules/admin/controllers/DocumentControllerTest.php @@ -27,6 +27,7 @@ * @category Tests * @author Jens Schwidder * @author Michael Lang + * @author Maximilian Salomon * @copyright Copyright (c) 2008-2018, OPUS 4 development team * @license http://www.gnu.org/licenses/gpl.html General Public License */ diff --git a/tests/modules/admin/controllers/EnrichmentkeyControllerTest.php b/tests/modules/admin/controllers/EnrichmentkeyControllerTest.php index 3b8111ed3..3415d7f3c 100644 --- a/tests/modules/admin/controllers/EnrichmentkeyControllerTest.php +++ b/tests/modules/admin/controllers/EnrichmentkeyControllerTest.php @@ -26,6 +26,7 @@ * * @category Tests * @author Gunar Maiwald + * @author Maximilian Salomon * @copyright Copyright (c) 2008-2018, OPUS 4 development team * @license http://www.gnu.org/licenses/gpl.html General Public License */ diff --git a/tests/modules/admin/controllers/ReportControllerTest.php b/tests/modules/admin/controllers/ReportControllerTest.php index bf1bf68e4..b5c3472bb 100644 --- a/tests/modules/admin/controllers/ReportControllerTest.php +++ b/tests/modules/admin/controllers/ReportControllerTest.php @@ -26,6 +26,7 @@ * * @category Unit Tests * @author Sascha Szott + * @author Maximilian Salomon * @copyright Copyright (c) 2018, OPUS 4 development team * @license http://www.gnu.org/licenses/gpl.html General Public License */ diff --git a/tests/modules/admin/controllers/StatisticControllerTest.php b/tests/modules/admin/controllers/StatisticControllerTest.php index 9d2010091..6a4f60fa2 100644 --- a/tests/modules/admin/controllers/StatisticControllerTest.php +++ b/tests/modules/admin/controllers/StatisticControllerTest.php @@ -26,6 +26,7 @@ * * @category Tests * @author Jens Schwidder + * @author Maximilian Salomon * @copyright Copyright (c) 2008-2018, OPUS 4 development team * @license http://www.gnu.org/licenses/gpl.html General Public License */ diff --git a/tests/modules/admin/forms/FileTest.php b/tests/modules/admin/forms/FileTest.php index 7660c734f..010d9f9a4 100644 --- a/tests/modules/admin/forms/FileTest.php +++ b/tests/modules/admin/forms/FileTest.php @@ -27,7 +27,8 @@ * @category Application Unit Test * @package Admin_Form * @author Jens Schwidder - * @copyright Copyright (c) 2008-2017, OPUS 4 development team + * @author Maximilian Salomon + * @copyright Copyright (c) 2008-2018, OPUS 4 development team * @license http://www.gnu.org/licenses/gpl.html General Public License */ class Admin_Form_FileTest extends ControllerTestCase { diff --git a/tests/modules/admin/forms/Person/ChangesTest.php b/tests/modules/admin/forms/Person/ChangesTest.php index 9fd60e1a0..4b34b6432 100644 --- a/tests/modules/admin/forms/Person/ChangesTest.php +++ b/tests/modules/admin/forms/Person/ChangesTest.php @@ -27,7 +27,8 @@ * @category Tests * @package Admin_Form * @author Jens Schwidder - * @copyright Copyright (c) 2017, OPUS 4 development team + * @author Maximilian Salomon + * @copyright Copyright (c) 2018, OPUS 4 development team * @license http://www.gnu.org/licenses/gpl.html General Public License */ diff --git a/tests/modules/solrsearch/controllers/IndexControllerTest.php b/tests/modules/solrsearch/controllers/IndexControllerTest.php index 6b399d215..6cf119ae5 100644 --- a/tests/modules/solrsearch/controllers/IndexControllerTest.php +++ b/tests/modules/solrsearch/controllers/IndexControllerTest.php @@ -29,6 +29,7 @@ * @author Julian Heise * @author Sascha Szott * @author Jens Schwidder + * @author Maximilian Salomon * @copyright Copyright (c) 2008-2018, OPUS 4 development team * @license http://www.gnu.org/licenses/gpl.html General Public License */ From db2a9eaeb53b894cea70d7e20f306c4e71797b33 Mon Sep 17 00:00:00 2001 From: BioFreak95 Date: Tue, 14 Aug 2018 09:34:55 +0200 Subject: [PATCH 031/128] OPUSVIER-3931 add filesize error-message in publish-upload --- modules/publish/language/errors.tmx | 17 ++++++--- .../publish/views/scripts/index/index.phtml | 10 ++++- public/layouts/opus4/js/filetypes.js | 37 ++++++++++++++----- 3 files changed, 49 insertions(+), 15 deletions(-) diff --git a/modules/publish/language/errors.tmx b/modules/publish/language/errors.tmx index e65666b20..16a5c4f77 100644 --- a/modules/publish/language/errors.tmx +++ b/modules/publish/language/errors.tmx @@ -145,23 +145,30 @@ - Your file exceeds the defined size. + Your file '%name%' exceeds the defined size. The allowed size is '%size%' Byte. - Ihre Datei übersteigt die erlaubte Größe. + Ihre Datei '%name%' übersteigt die erlaubte Größe. Die erlaubte Größe liegt bei '%size%' Byte. - File '%value%' has a forbidden extension. Please choose another file. + File '%name%' has a forbidden extension. - Die Datei '%value%' hat eine unerlaubte Dateiendung. Bitte wählen Sie eine andere Datei. + Die Datei '%name%' hat eine unerlaubte Dateiendung. - + + + Please choose another File. + + + Bitte wählen Sie eine andere Datei. + + diff --git a/modules/publish/views/scripts/index/index.phtml b/modules/publish/views/scripts/index/index.phtml index b4e56c351..5ecd04b94 100644 --- a/modules/publish/views/scripts/index/index.phtml +++ b/modules/publish/views/scripts/index/index.phtml @@ -34,12 +34,20 @@ ?> jQueryEnabled() && !empty($this->extensions)) : ?> + 'fileExtensionFalse', + 'invalidFileSizeMessage' => 'fileUploadErrorFormSize', + 'anotherFileMessage' => 'chooseAnotherFile' + ]; + ?> diff --git a/public/layouts/opus4/js/filetypes.js b/public/layouts/opus4/js/filetypes.js index 45ddb71be..7080ce802 100644 --- a/public/layouts/opus4/js/filetypes.js +++ b/public/layouts/opus4/js/filetypes.js @@ -25,24 +25,43 @@ * * @category Application * @author Jens Schwidder - * @copyright Copyright (c) 2008-2016, OPUS 4 development team + * @author Maximilian Salomon + * @copyright Copyright (c) 2008-2018, OPUS 4 development team * @license http://www.gnu.org/licenses/gpl.html General Public License */ -$(function() { +$(function () { var fileElem = $("input:file")[0]; + var maxFileSize = $("input[name=MAX_FILE_SIZE]").val(); - if (! typeof fileElem === "undefined") { + if (typeof fileElem !== "undefined") { fileElem.validFileExtensions = null; // nichts erlaubt, wird auf Publishseite überschrieben - fileElem.invalidFileMessage = 'The extension of file \'%value%\' is not allowed.'; - fileElem.onchange = function() { + fileElem.errorMessages = { + invalidFileTypeMessage: "The extension of file \'%name%\' is not allowed.", + invalidFileSizeMessage: "The size of file \'%name%\' is not allowed. Choose a file with less then \'%size%\' byte.", + anotherFileMessage: "Please choose another file." + }; + + + fileElem.onchange = function () { var filename = this.value; + var fileSize = this.files[0].size; + var errors = []; + var ext = filename.match(/\.([^\.]+)$/); - if (fileElem.validFileExtensions != null && (ext == null || $.inArray(ext[1], this.validFileExtensions) == -1)) { - $message = fileElem.invalidFileMessage; - alert($message.replace('%value%', filename)); + if (fileElem.validFileExtensions != null && (ext == null || $.inArray(ext[1], this.validFileExtensions) === -1)) { + errors.push(fileElem.errorMessages["invalidFileTypeMessage"].replace("%name%", filename)); + } + + if (fileSize > maxFileSize) { + errors.push(fileElem.errorMessages["invalidFileSizeMessage"].replace("%name%", filename).replace("%size%", maxFileSize)); + } + + if (errors.length !== 0) { + errors.push(fileElem.errorMessages["anotherFileMessage"]); + alert(errors.join("\n")); this.value = null; } }; } -}); +}); \ No newline at end of file From 6753738dd0ab5f0779af20cf14b0f0448773d15f Mon Sep 17 00:00:00 2001 From: BioFreak95 Date: Tue, 14 Aug 2018 11:14:15 +0200 Subject: [PATCH 032/128] OPUSVIER-3931 add filesize error-message in publish-upload --- .../publish/controllers/FormController.php | 2 +- modules/publish/language/errors.tmx | 30 +++++++++++++++---- .../publish/views/scripts/index/index.phtml | 3 +- public/layouts/opus4/js/filetypes.js | 10 ++++--- 4 files changed, 33 insertions(+), 12 deletions(-) diff --git a/modules/publish/controllers/FormController.php b/modules/publish/controllers/FormController.php index f2e77b4ef..6c78e74b7 100644 --- a/modules/publish/controllers/FormController.php +++ b/modules/publish/controllers/FormController.php @@ -75,7 +75,7 @@ public function uploadAction() { . ' the expected value in OPUS4 config.ini. Further information can be read in our documentation.' ); return $this->_helper->Redirector->redirectTo( - 'index', $this->view->translate('error_empty_post_array'), 'index' + 'index', array('failure' => $this->view->translate('error_empty_post_array'), 'index') ); } diff --git a/modules/publish/language/errors.tmx b/modules/publish/language/errors.tmx index 16a5c4f77..d557b35c4 100644 --- a/modules/publish/language/errors.tmx +++ b/modules/publish/language/errors.tmx @@ -10,10 +10,10 @@ - Please retry publishing a document using a smaller file. ]]> + - Bitte versuchen Sie erneut ein Dokument mit einer kleineren Datei zu veröffentlichen.]]> + @@ -145,19 +145,28 @@ - Your file '%name%' exceeds the defined size. The allowed size is '%size%' Byte. + Your file exceeds the defined size. - Ihre Datei '%name%' übersteigt die erlaubte Größe. Die erlaubte Größe liegt bei '%size%' Byte. + Ihre Datei übersteigt die erlaubte Größe. + + + + + + Your file exceeds the defined size. The allowed size is '%size%' Byte. + + + Ihre Datei übersteigt die erlaubte Größe. Die erlaubte Größe liegt bei '%size%' Byte. - File '%name%' has a forbidden extension. + File has a forbidden extension. - Die Datei '%name%' hat eine unerlaubte Dateiendung. + Die Datei hat eine unerlaubte Dateiendung. @@ -170,6 +179,15 @@ + + + The file '%name%' has the following errors: + + + Die Datei '%name%' hat folgende Fehler: + + + diff --git a/modules/publish/views/scripts/index/index.phtml b/modules/publish/views/scripts/index/index.phtml index 5ecd04b94..b66f51503 100644 --- a/modules/publish/views/scripts/index/index.phtml +++ b/modules/publish/views/scripts/index/index.phtml @@ -35,8 +35,9 @@ jQueryEnabled() && !empty($this->extensions)) : ?> 'uploadedFileHasErrorMessage', 'invalidFileTypeMessage' => 'fileExtensionFalse', - 'invalidFileSizeMessage' => 'fileUploadErrorFormSize', + 'invalidFileSizeMessage' => 'fileUploadErrorSize', 'anotherFileMessage' => 'chooseAnotherFile' ]; ?> diff --git a/public/layouts/opus4/js/filetypes.js b/public/layouts/opus4/js/filetypes.js index 7080ce802..85f7cb8fe 100644 --- a/public/layouts/opus4/js/filetypes.js +++ b/public/layouts/opus4/js/filetypes.js @@ -37,8 +37,9 @@ $(function () { if (typeof fileElem !== "undefined") { fileElem.validFileExtensions = null; // nichts erlaubt, wird auf Publishseite überschrieben fileElem.errorMessages = { - invalidFileTypeMessage: "The extension of file \'%name%\' is not allowed.", - invalidFileSizeMessage: "The size of file \'%name%\' is not allowed. Choose a file with less then \'%size%\' byte.", + fileNameErrorMessage : "The file \'%name%\' has the following errors:", + invalidFileTypeMessage: "The extension of file is not allowed.", + invalidFileSizeMessage: "The size of file is not allowed. Choose a file with less then \'%size%\' byte.", anotherFileMessage: "Please choose another file." }; @@ -50,14 +51,15 @@ $(function () { var ext = filename.match(/\.([^\.]+)$/); if (fileElem.validFileExtensions != null && (ext == null || $.inArray(ext[1], this.validFileExtensions) === -1)) { - errors.push(fileElem.errorMessages["invalidFileTypeMessage"].replace("%name%", filename)); + errors.push(fileElem.errorMessages["invalidFileTypeMessage"]); } if (fileSize > maxFileSize) { - errors.push(fileElem.errorMessages["invalidFileSizeMessage"].replace("%name%", filename).replace("%size%", maxFileSize)); + errors.push(fileElem.errorMessages["invalidFileSizeMessage"].replace("%size%", maxFileSize)); } if (errors.length !== 0) { + errors.unshift(fileElem.errorMessages["fileNameErrorMessage"].replace("%name%", filename)); errors.push(fileElem.errorMessages["anotherFileMessage"]); alert(errors.join("\n")); this.value = null; From cfd190eda274076d030602089201373283b56bfa Mon Sep 17 00:00:00 2001 From: Maximilian Salomon <32635839+BioFreak95@users.noreply.github.com> Date: Tue, 14 Aug 2018 11:29:04 +0200 Subject: [PATCH 033/128] Update FormController.php Fix small bug --- modules/publish/controllers/FormController.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/publish/controllers/FormController.php b/modules/publish/controllers/FormController.php index 6c78e74b7..f93fa3dc5 100644 --- a/modules/publish/controllers/FormController.php +++ b/modules/publish/controllers/FormController.php @@ -75,7 +75,7 @@ public function uploadAction() { . ' the expected value in OPUS4 config.ini. Further information can be read in our documentation.' ); return $this->_helper->Redirector->redirectTo( - 'index', array('failure' => $this->view->translate('error_empty_post_array'), 'index') + 'index', array('failure' => $this->view->translate('error_empty_post_array')), 'index' ); } From 3fc379df5cbf33d1b53565b95d3d76a7060e0541 Mon Sep 17 00:00:00 2001 From: BioFreak95 Date: Tue, 14 Aug 2018 11:33:55 +0200 Subject: [PATCH 034/128] OPUSVIER-3931 change translate-function --- modules/publish/controllers/FormController.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/publish/controllers/FormController.php b/modules/publish/controllers/FormController.php index 6c78e74b7..e517d57ba 100644 --- a/modules/publish/controllers/FormController.php +++ b/modules/publish/controllers/FormController.php @@ -75,7 +75,7 @@ public function uploadAction() { . ' the expected value in OPUS4 config.ini. Further information can be read in our documentation.' ); return $this->_helper->Redirector->redirectTo( - 'index', array('failure' => $this->view->translate('error_empty_post_array'), 'index') + 'index', ['failure' => 'error_empty_post_array'], 'index' ); } From ac304bc79a1a40a93df25d5a92df35ceedb50494 Mon Sep 17 00:00:00 2001 From: Maximilian Salomon <32635839+BioFreak95@users.noreply.github.com> Date: Tue, 14 Aug 2018 11:35:53 +0200 Subject: [PATCH 035/128] Update FormController.php small changes --- modules/publish/controllers/FormController.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/publish/controllers/FormController.php b/modules/publish/controllers/FormController.php index f93fa3dc5..e517d57ba 100644 --- a/modules/publish/controllers/FormController.php +++ b/modules/publish/controllers/FormController.php @@ -75,7 +75,7 @@ public function uploadAction() { . ' the expected value in OPUS4 config.ini. Further information can be read in our documentation.' ); return $this->_helper->Redirector->redirectTo( - 'index', array('failure' => $this->view->translate('error_empty_post_array')), 'index' + 'index', ['failure' => 'error_empty_post_array'], 'index' ); } From 045e48ae14c08f376dc197935aaa9e4a337bd9eb Mon Sep 17 00:00:00 2001 From: BioFreak95 Date: Thu, 16 Aug 2018 12:10:47 +0200 Subject: [PATCH 036/128] OPUSVIER-3908 Add uploadcheck for publishform Add check for filename (maximal allowed size and allowed characters) Change alert to direct error-message at the website --- application/configs/application.ini | 2 ++ modules/publish/forms/PublishingFirst.php | 5 ++- modules/publish/language/errors.tmx | 19 +++++++++++ .../publish/views/scripts/index/index.phtml | 7 +++- public/layouts/opus4/js/filetypes.js | 33 +++++++++++++++++-- 5 files changed, 62 insertions(+), 4 deletions(-) diff --git a/application/configs/application.ini b/application/configs/application.ini index 9b1f1f035..13ea38340 100644 --- a/application/configs/application.ini +++ b/application/configs/application.ini @@ -110,6 +110,8 @@ errorController.showRequest = 0 ;PUBLICATION SETTINGS publish.maxfilesize = 10240000 +publish.maxFileNameLength = 50 +publish.allowedFilenameCharset = "^[a-zA-Z0-9][a-zA-Z0-9_.-]+$" publish.filetypes.allowed = pdf,txt,html,htm ; filetypes that are accepted in publication form publish.path.documenttypes = APPLICATION_PATH "/application/configs/doctypes" publish.path.documenttemplates = APPLICATION_PATH "/application/configs/doctypes_templates" diff --git a/modules/publish/forms/PublishingFirst.php b/modules/publish/forms/PublishingFirst.php index 59ec05d8a..68e7500a5 100644 --- a/modules/publish/forms/PublishingFirst.php +++ b/modules/publish/forms/PublishingFirst.php @@ -28,7 +28,8 @@ * @category Application * @package Module_Publish * @author Susanne Gottwald - * @copyright Copyright (c) 2008-2010, OPUS 4 development team + * @author Maximilian Salomon + * @copyright Copyright (c) 2008-2018, OPUS 4 development team * @license http://www.gnu.org/licenses/gpl.html General Public License * @version $Id$ */ @@ -261,6 +262,8 @@ public function setViewValues() { $this->view->documentUpload = $group; $this->view->MAX_FILE_SIZE = $this->_config->publish->maxfilesize; + $this->view->maxFileNameLength = $this->_config->publish->maxFileNameLength; + $this->view->allowedFilenameCharset = $this->_config->publish->allowedFilenameCharset; } } diff --git a/modules/publish/language/errors.tmx b/modules/publish/language/errors.tmx index d557b35c4..518a88dc6 100644 --- a/modules/publish/language/errors.tmx +++ b/modules/publish/language/errors.tmx @@ -188,6 +188,25 @@ + + + The length of your filename is too long. Your filename should have less then '%size%' characters. + + + Der Dateiname hat zu viele Zeichen. Die maximal erlaubte Zeichenzahl beträgt '%size%' Zeichen. + + + + + + Your filename has not allowed characters or a wrong form. + + + Der Dateiname enthält nicht zugelassene Zeichen oder hat eine falsche Form. + + + + diff --git a/modules/publish/views/scripts/index/index.phtml b/modules/publish/views/scripts/index/index.phtml index b66f51503..0e1dd37c0 100644 --- a/modules/publish/views/scripts/index/index.phtml +++ b/modules/publish/views/scripts/index/index.phtml @@ -27,7 +27,8 @@ * @category Application * @author Susanne Gottwald * @author Doreen Thiede - * @copyright Copyright (c) 2008-2010, OPUS 4 development team + * @author Maximilian Salomon + * @copyright Copyright (c) 2008-2018, OPUS 4 development team * @license http://www.gnu.org/licenses/gpl.html General Public License * @version $Id$ */ @@ -38,6 +39,8 @@ 'fileNameErrorMessage' => 'uploadedFileHasErrorMessage', 'invalidFileTypeMessage' => 'fileExtensionFalse', 'invalidFileSizeMessage' => 'fileUploadErrorSize', + 'invalidFilenameLengthMessage' => 'filenameLenthError', + 'invalidFilenameCharsetMessage' => 'filenameCharError', 'anotherFileMessage' => 'chooseAnotherFile' ]; ?> @@ -67,6 +70,8 @@ enableUpload) : ?> element($this->MAX_FILE_SIZE, null, 'hidden', 'MAX_FILE_SIZE'); ?> + element($this->maxFileNameLength, null, 'hidden', 'maxFileNameLength'); ?> + element($this->allowedFilenameCharset, null, 'hidden', 'allowedFilenameCharset'); ?> group($this->documentUpload); ?> fileOverview(); ?> diff --git a/public/layouts/opus4/js/filetypes.js b/public/layouts/opus4/js/filetypes.js index 85f7cb8fe..a3fb063e3 100644 --- a/public/layouts/opus4/js/filetypes.js +++ b/public/layouts/opus4/js/filetypes.js @@ -40,13 +40,18 @@ $(function () { fileNameErrorMessage : "The file \'%name%\' has the following errors:", invalidFileTypeMessage: "The extension of file is not allowed.", invalidFileSizeMessage: "The size of file is not allowed. Choose a file with less then \'%size%\' byte.", + invalidFilenameLengthMessage: "The length of your filename is too long. Your filename should have less then \'%size%\' characters.", + invalidFilenameCharsetMessage: "Your filename has wrong characters or a wrong form.", anotherFileMessage: "Please choose another file." }; fileElem.onchange = function () { - var filename = this.value; + var filepath = this.value.split("\\"); + var filename = filepath[filepath.length - 1]; var fileSize = this.files[0].size; + var pattern = new RegExp($("input[name=allowedFilenameCharset]").val()); + var maxFileNameSize = $("input[name=maxFileNameLength]").val(); var errors = []; var ext = filename.match(/\.([^\.]+)$/); @@ -58,10 +63,34 @@ $(function () { errors.push(fileElem.errorMessages["invalidFileSizeMessage"].replace("%size%", maxFileSize)); } + if (fileSize > maxFileSize) { + errors.push(fileElem.errorMessages["invalidFileSizeMessage"].replace("%size%", maxFileSize)); + } + + if (pattern.test(filename) === false) { + errors.push(fileElem.errorMessages["invalidFilenameCharsetMessage"]); + } + + if (filename.length > maxFileNameSize && maxFileNameSize > 0) { + errors.push(fileElem.errorMessages["invalidFilenameLengthMessage"].replace("%size%", maxFileNameSize)); + } + if (errors.length !== 0) { + if (typeof document.getElementsByClassName("form-hint form-errors")[0] !== "undefined") { + document.getElementsByClassName("form-hint form-errors")[0].remove(); + } errors.unshift(fileElem.errorMessages["fileNameErrorMessage"].replace("%name%", filename)); errors.push(fileElem.errorMessages["anotherFileMessage"]); - alert(errors.join("\n")); + + var div = document.createElement("div"); + div.className += "form-hint form-errors"; + var element = document.getElementsByClassName("document-type")[0]; + element.appendChild(div); + var para = document.createElement("p"); + var node = document.createTextNode(errors.join("\n")); + para.appendChild(node); + div.appendChild(para); + this.value = null; } }; From ab98445d670700319598cc68d42cf14e630084cb Mon Sep 17 00:00:00 2001 From: BioFreak95 Date: Thu, 16 Aug 2018 12:13:37 +0200 Subject: [PATCH 037/128] OPUSVIER-3908 Add arguments to config.ini.template --- application/configs/config.ini.template | 2 ++ 1 file changed, 2 insertions(+) diff --git a/application/configs/config.ini.template b/application/configs/config.ini.template index 340fe07fc..500af3a7a 100644 --- a/application/configs/config.ini.template +++ b/application/configs/config.ini.template @@ -134,6 +134,8 @@ gnd.linkAuthor.frontdoor = 1 ;publish.maxfilesize = 10240000 ; publish.filetypes.allowed defines which filetypes can be uploaded. ;publish.filetypes.allowed = pdf,txt,html,htm ; filetypes that are accepted in publication form +;publish.maxFileNameLength = 50 +;publish.allowedFilenameCharset = "^[a-zA-Z0-9][a-zA-Z0-9_.-]+$" ; CHECKSUM SETTINGS ; Maximum filesize in MB (default 50 MB) for calculating MD5 and SHA512 hashes From e36e8107a9b6ad9beb6da01e8a83288eba8b441e Mon Sep 17 00:00:00 2001 From: BioFreak95 Date: Thu, 16 Aug 2018 13:37:41 +0200 Subject: [PATCH 038/128] OPUSVIER-3908

Bugfix --- modules/publish/views/helpers/Fieldset.php | 2 +- public/layouts/opus4/js/filetypes.js | 7 ++----- 2 files changed, 3 insertions(+), 6 deletions(-) diff --git a/modules/publish/views/helpers/Fieldset.php b/modules/publish/views/helpers/Fieldset.php index c051f4172..cf7787f5a 100644 --- a/modules/publish/views/helpers/Fieldset.php +++ b/modules/publish/views/helpers/Fieldset.php @@ -246,7 +246,7 @@ function getRequiredSign() { * @return */ function getFieldsetHint($name) { - return "

" . $this->view->translate('hint_' . $name) . "

"; + return "

" . $this->view->translate('hint_' . $name) . "

"; } function getLabelFor($name, $label, $required) { diff --git a/public/layouts/opus4/js/filetypes.js b/public/layouts/opus4/js/filetypes.js index a3fb063e3..a667cdfc4 100644 --- a/public/layouts/opus4/js/filetypes.js +++ b/public/layouts/opus4/js/filetypes.js @@ -76,16 +76,13 @@ $(function () { } if (errors.length !== 0) { - if (typeof document.getElementsByClassName("form-hint form-errors")[0] !== "undefined") { - document.getElementsByClassName("form-hint form-errors")[0].remove(); - } errors.unshift(fileElem.errorMessages["fileNameErrorMessage"].replace("%name%", filename)); errors.push(fileElem.errorMessages["anotherFileMessage"]); var div = document.createElement("div"); div.className += "form-hint form-errors"; - var element = document.getElementsByClassName("document-type")[0]; - element.appendChild(div); + var element = document.getElementsByClassName("'form-multiple odd'")[0]; + element.insert(div); var para = document.createElement("p"); var node = document.createTextNode(errors.join("\n")); para.appendChild(node); From 6a2785ec7a7676024ddc5f6e52c3cac2b5578124 Mon Sep 17 00:00:00 2001 From: BioFreak95 Date: Thu, 16 Aug 2018 17:42:11 +0200 Subject: [PATCH 039/128] OPUSVIER-3908 Change in JS --- public/layouts/opus4/js/filetypes.js | 14 +------------- 1 file changed, 1 insertion(+), 13 deletions(-) diff --git a/public/layouts/opus4/js/filetypes.js b/public/layouts/opus4/js/filetypes.js index a667cdfc4..8e52ac280 100644 --- a/public/layouts/opus4/js/filetypes.js +++ b/public/layouts/opus4/js/filetypes.js @@ -63,10 +63,6 @@ $(function () { errors.push(fileElem.errorMessages["invalidFileSizeMessage"].replace("%size%", maxFileSize)); } - if (fileSize > maxFileSize) { - errors.push(fileElem.errorMessages["invalidFileSizeMessage"].replace("%size%", maxFileSize)); - } - if (pattern.test(filename) === false) { errors.push(fileElem.errorMessages["invalidFilenameCharsetMessage"]); } @@ -79,15 +75,7 @@ $(function () { errors.unshift(fileElem.errorMessages["fileNameErrorMessage"].replace("%name%", filename)); errors.push(fileElem.errorMessages["anotherFileMessage"]); - var div = document.createElement("div"); - div.className += "form-hint form-errors"; - var element = document.getElementsByClassName("'form-multiple odd'")[0]; - element.insert(div); - var para = document.createElement("p"); - var node = document.createTextNode(errors.join("\n")); - para.appendChild(node); - div.appendChild(para); - + alert(errors.join("\n")); this.value = null; } }; From 39324e533a642f297fd14a6af18d9873b8f61563 Mon Sep 17 00:00:00 2001 From: BioFreak95 Date: Thu, 16 Aug 2018 17:48:35 +0200 Subject: [PATCH 040/128] OPUSVIER-3908 typofixes and review-changes in clientside-validation --- application/configs/application.ini | 6 +++--- application/configs/config.ini.template | 4 ++-- modules/publish/language/errors.tmx | 4 ++-- modules/publish/views/scripts/index/index.phtml | 10 +++++----- public/layouts/opus4/js/filetypes.js | 10 +++++----- 5 files changed, 17 insertions(+), 17 deletions(-) diff --git a/application/configs/application.ini b/application/configs/application.ini index 13ea38340..d24e2ac33 100644 --- a/application/configs/application.ini +++ b/application/configs/application.ini @@ -19,7 +19,7 @@ ; ; LICENCE ; OPUS is free software; you can redistribute it and/or modify it under the -; terms of the GNU General Public License as published by the Free Software +; terms of the GNU General ic License as published by the Free Software ; Foundation; either version 2 of the Licence, or any later version. ; OPUS is distributed in the hope that it will be useful, but WITHOUT ANY ; WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS @@ -110,8 +110,8 @@ errorController.showRequest = 0 ;PUBLICATION SETTINGS publish.maxfilesize = 10240000 -publish.maxFileNameLength = 50 -publish.allowedFilenameCharset = "^[a-zA-Z0-9][a-zA-Z0-9_.-]+$" +publish.filenameMaxLength = 50 +publish.filenameFormat = "^[a-zA-Z0-9][a-zA-Z0-9_.-]+$" publish.filetypes.allowed = pdf,txt,html,htm ; filetypes that are accepted in publication form publish.path.documenttypes = APPLICATION_PATH "/application/configs/doctypes" publish.path.documenttemplates = APPLICATION_PATH "/application/configs/doctypes_templates" diff --git a/application/configs/config.ini.template b/application/configs/config.ini.template index 500af3a7a..a5fe56c94 100644 --- a/application/configs/config.ini.template +++ b/application/configs/config.ini.template @@ -134,8 +134,8 @@ gnd.linkAuthor.frontdoor = 1 ;publish.maxfilesize = 10240000 ; publish.filetypes.allowed defines which filetypes can be uploaded. ;publish.filetypes.allowed = pdf,txt,html,htm ; filetypes that are accepted in publication form -;publish.maxFileNameLength = 50 -;publish.allowedFilenameCharset = "^[a-zA-Z0-9][a-zA-Z0-9_.-]+$" +;publish.filenameMaxLength = 50 +;publish.filenameFormat = "^[a-zA-Z0-9][a-zA-Z0-9_.-]+$" ; CHECKSUM SETTINGS ; Maximum filesize in MB (default 50 MB) for calculating MD5 and SHA512 hashes diff --git a/modules/publish/language/errors.tmx b/modules/publish/language/errors.tmx index 518a88dc6..43cde6e81 100644 --- a/modules/publish/language/errors.tmx +++ b/modules/publish/language/errors.tmx @@ -188,7 +188,7 @@
- + The length of your filename is too long. Your filename should have less then '%size%' characters. @@ -197,7 +197,7 @@ - + Your filename has not allowed characters or a wrong form. diff --git a/modules/publish/views/scripts/index/index.phtml b/modules/publish/views/scripts/index/index.phtml index 0e1dd37c0..db4b44b65 100644 --- a/modules/publish/views/scripts/index/index.phtml +++ b/modules/publish/views/scripts/index/index.phtml @@ -36,11 +36,11 @@ jQueryEnabled() && !empty($this->extensions)) : ?> 'uploadedFileHasErrorMessage', - 'invalidFileTypeMessage' => 'fileExtensionFalse', - 'invalidFileSizeMessage' => 'fileUploadErrorSize', - 'invalidFilenameLengthMessage' => 'filenameLenthError', - 'invalidFilenameCharsetMessage' => 'filenameCharError', + 'fileNameError' => 'uploadedFileHasErrorMessage', + 'invalidFileType' => 'fileExtensionFalse', + 'invalidFileSize' => 'fileUploadErrorSize', + 'invalidFilenameLength' => 'filenameLengthError', + 'invalidFilenameFormat' => 'filenameFormatError', 'anotherFileMessage' => 'chooseAnotherFile' ]; ?> diff --git a/public/layouts/opus4/js/filetypes.js b/public/layouts/opus4/js/filetypes.js index 8e52ac280..a4c2e4e70 100644 --- a/public/layouts/opus4/js/filetypes.js +++ b/public/layouts/opus4/js/filetypes.js @@ -37,11 +37,11 @@ $(function () { if (typeof fileElem !== "undefined") { fileElem.validFileExtensions = null; // nichts erlaubt, wird auf Publishseite überschrieben fileElem.errorMessages = { - fileNameErrorMessage : "The file \'%name%\' has the following errors:", - invalidFileTypeMessage: "The extension of file is not allowed.", - invalidFileSizeMessage: "The size of file is not allowed. Choose a file with less then \'%size%\' byte.", - invalidFilenameLengthMessage: "The length of your filename is too long. Your filename should have less then \'%size%\' characters.", - invalidFilenameCharsetMessage: "Your filename has wrong characters or a wrong form.", + fileNameError : "The file \'%name%\' has the following errors:", + invalidFileType: "The extension of file is not allowed.", + invalidFileSize: "The size of file is not allowed. Choose a file with less then \'%size%\' byte.", + invalidFilenameLength: "The length of your filename is too long. Your filename should have less then \'%size%\' characters.", + invalidFilenameFormat: "Your filename has wrong characters or a wrong form.", anotherFileMessage: "Please choose another file." }; From 499e371fbc4f29772f93bafb7a200eaef34f841d Mon Sep 17 00:00:00 2001 From: BioFreak95 Date: Thu, 16 Aug 2018 19:12:13 +0200 Subject: [PATCH 041/128] OPUSVIER-3908 add Filename-validator --- .../Application/Form/Validate/Filename.php | 112 ++++++++++++++++++ modules/publish/forms/PublishingFirst.php | 8 +- modules/publish/language/errors.tmx | 42 +++---- public/layouts/opus4/js/filetypes.js | 2 +- 4 files changed, 141 insertions(+), 23 deletions(-) create mode 100644 library/Application/Form/Validate/Filename.php diff --git a/library/Application/Form/Validate/Filename.php b/library/Application/Form/Validate/Filename.php new file mode 100644 index 000000000..955a69589 --- /dev/null +++ b/library/Application/Form/Validate/Filename.php @@ -0,0 +1,112 @@ + + * @copyright Copyright (c) 2017-2018, OPUS 4 development team + * @license http://www.gnu.org/licenses/gpl.html General Public License + */ + +/** + * Class Application_Form_Validate_uploadFilenameCheck validates the filename of an fileupload. + */ +class Application_Form_Validate_Filename extends Zend_Validate_Abstract +{ + protected $filenameMaxLength = ''; + protected $filenameFormat = ''; + + /** + * Error message key for invalid filename length + */ + const MSG_NAME_LENGTH = 'namelength'; + + /** + * Error message key for malformed filename + */ + const MSG_NAME_FORMAT = 'format'; + + /** + * Errormessage Templates + * @var array + */ + protected $_messageTemplates = [ + self::MSG_NAME_LENGTH => "filenameLengthError", + self::MSG_NAME_FORMAT => "filenameFormatError" + ]; + + /** + * variables for messageTemplates + * @var array + */ + protected $_messageVariables = array( + 'size' => '_filenameMaxLength', + ); + + /** + * Application_Form_Validate_Filename constructor. + * @param $options + */ + public function __construct($options) + { + $this->_filenameMaxLength = $options[0]; + $this->_filenameFormat = '/' . $options[1] . '/'; + } + + /** + * Check the size and the format of a filename. + * + * @param mixed $value + * @param null $file + * @return bool + */ + public function isValid($value, $file = null) + { + $this->_setValue($value); + if ($file !== null) { + $data['filename'] = $file['name']; + } else { + $data = pathinfo($value); + if (!array_key_exists('filename', $data)) { + + return false; + } + } + + if (strlen($data['filename']) > $this->_filenameMaxLength) { + $this->_error(self::MSG_NAME_LENGTH); + return false; + } + + if (preg_match($this->_filenameFormat, $data['filename']) === 0) { + $this->_error(self::MSG_NAME_FORMAT); + return false; + } + + return true; + } + +} \ No newline at end of file diff --git a/modules/publish/forms/PublishingFirst.php b/modules/publish/forms/PublishingFirst.php index 68e7500a5..8233f0ded 100644 --- a/modules/publish/forms/PublishingFirst.php +++ b/modules/publish/forms/PublishingFirst.php @@ -31,7 +31,6 @@ * @author Maximilian Salomon * @copyright Copyright (c) 2008-2018, OPUS 4 development team * @license http://www.gnu.org/licenses/gpl.html General Public License - * @version $Id$ */ /** @@ -165,6 +164,12 @@ private function _createFileuploadField() { $requireUpload = 0; } + //initialization of filename-validator + $filenameMaxLength = $this->_config->publish->filenameMaxLength; + $filenameFormat = $this->_config->publish->filenameFormat; + $filenameOptions = [$filenameMaxLength, $filenameFormat]; + $filenameValidator = new Application_Form_Validate_Filename($filenameOptions); + //file upload field(s) $fileupload = new Zend_Form_Element_File('fileupload'); $fileupload @@ -175,6 +180,7 @@ private function _createFileuploadField() { ->setMaxFileSize($maxFileSize) ->addValidator('Extension', false, $filetypes) // allowed filetypes by extension ->setValueDisabled(true) + ->addValidator($filenameValidator, false) // filename-format ->setAttrib('enctype', 'multipart/form-data'); if (1 == $requireUpload) { diff --git a/modules/publish/language/errors.tmx b/modules/publish/language/errors.tmx index 43cde6e81..ccf3a224e 100644 --- a/modules/publish/language/errors.tmx +++ b/modules/publish/language/errors.tmx @@ -180,31 +180,31 @@ - - The file '%name%' has the following errors: - - - Die Datei '%name%' hat folgende Fehler: - - + + The file '%name%' has the following errors: + + + Die Datei '%name%' hat folgende Fehler: + + - - The length of your filename is too long. Your filename should have less then '%size%' characters. - - - Der Dateiname hat zu viele Zeichen. Die maximal erlaubte Zeichenzahl beträgt '%size%' Zeichen. - - + + The length of your filename is too long. Your filename should have less then '%size%' characters. + + + Der Dateiname hat zu viele Zeichen. Die maximal erlaubte Zeichenzahl beträgt '%size%' Zeichen. + + - - Your filename has not allowed characters or a wrong form. - - - Der Dateiname enthält nicht zugelassene Zeichen oder hat eine falsche Form. - - + + Your filename has not allowed characters or a wrong form. + + + Der Dateiname enthält nicht zugelassene Zeichen oder hat eine falsche Form. + + diff --git a/public/layouts/opus4/js/filetypes.js b/public/layouts/opus4/js/filetypes.js index a4c2e4e70..6ac27c9ff 100644 --- a/public/layouts/opus4/js/filetypes.js +++ b/public/layouts/opus4/js/filetypes.js @@ -41,7 +41,7 @@ $(function () { invalidFileType: "The extension of file is not allowed.", invalidFileSize: "The size of file is not allowed. Choose a file with less then \'%size%\' byte.", invalidFilenameLength: "The length of your filename is too long. Your filename should have less then \'%size%\' characters.", - invalidFilenameFormat: "Your filename has wrong characters or a wrong form.", + invalidFilenameFormat: "Your filename has not allowed characters or a wrong form.", anotherFileMessage: "Please choose another file." }; From cc9a2c77315e1e443e67fc3493bb84d54f00dac5 Mon Sep 17 00:00:00 2001 From: Maximilian Salomon <32635839+BioFreak95@users.noreply.github.com> Date: Thu, 16 Aug 2018 19:13:30 +0200 Subject: [PATCH 042/128] Update application.ini typo --- application/configs/application.ini | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/application/configs/application.ini b/application/configs/application.ini index d24e2ac33..d3cbc4248 100644 --- a/application/configs/application.ini +++ b/application/configs/application.ini @@ -19,7 +19,7 @@ ; ; LICENCE ; OPUS is free software; you can redistribute it and/or modify it under the -; terms of the GNU General ic License as published by the Free Software +; terms of the GNU General Public License as published by the Free Software ; Foundation; either version 2 of the Licence, or any later version. ; OPUS is distributed in the hope that it will be useful, but WITHOUT ANY ; WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS From 4ee09e67db8f3d67105a3f1b21178fd25f26554c Mon Sep 17 00:00:00 2001 From: BioFreak95 Date: Thu, 16 Aug 2018 19:28:40 +0200 Subject: [PATCH 043/128] OPUSVIER-3908 some style --- library/Application/Form/Validate/Filename.php | 8 ++++---- modules/publish/forms/PublishingFirst.php | 5 ++++- 2 files changed, 8 insertions(+), 5 deletions(-) diff --git a/library/Application/Form/Validate/Filename.php b/library/Application/Form/Validate/Filename.php index 955a69589..b6b75a15e 100644 --- a/library/Application/Form/Validate/Filename.php +++ b/library/Application/Form/Validate/Filename.php @@ -36,8 +36,8 @@ */ class Application_Form_Validate_Filename extends Zend_Validate_Abstract { - protected $filenameMaxLength = ''; - protected $filenameFormat = ''; + protected $_filenameMaxLength = ''; + protected $_filenameFormat = ''; /** * Error message key for invalid filename length @@ -72,8 +72,8 @@ class Application_Form_Validate_Filename extends Zend_Validate_Abstract */ public function __construct($options) { - $this->_filenameMaxLength = $options[0]; - $this->_filenameFormat = '/' . $options[1] . '/'; + $this->_filenameMaxLength = $options['filenameMaxLength']; + $this->_filenameFormat = '/' . $options['filenameFormat'] . '/'; } /** diff --git a/modules/publish/forms/PublishingFirst.php b/modules/publish/forms/PublishingFirst.php index 8233f0ded..18a90502e 100644 --- a/modules/publish/forms/PublishingFirst.php +++ b/modules/publish/forms/PublishingFirst.php @@ -167,7 +167,10 @@ private function _createFileuploadField() { //initialization of filename-validator $filenameMaxLength = $this->_config->publish->filenameMaxLength; $filenameFormat = $this->_config->publish->filenameFormat; - $filenameOptions = [$filenameMaxLength, $filenameFormat]; + $filenameOptions = [ + 'filenameMaxLength' => $filenameMaxLength, + 'filenameFormat' => $filenameFormat + ]; $filenameValidator = new Application_Form_Validate_Filename($filenameOptions); //file upload field(s) From d894c0cb35d0ebb651fdc4a91b6126c4b8497eec Mon Sep 17 00:00:00 2001 From: BioFreak95 Date: Fri, 17 Aug 2018 12:11:17 +0200 Subject: [PATCH 044/128] OPUSVIER-3908 Add FilenameTest --- .../Form/Validate/FilenameTest.php | 121 ++++++++++++++++++ 1 file changed, 121 insertions(+) create mode 100644 tests/library/Application/Form/Validate/FilenameTest.php diff --git a/tests/library/Application/Form/Validate/FilenameTest.php b/tests/library/Application/Form/Validate/FilenameTest.php new file mode 100644 index 000000000..ce28e960d --- /dev/null +++ b/tests/library/Application/Form/Validate/FilenameTest.php @@ -0,0 +1,121 @@ + + * @copyright Copyright (c) 2008-2018, OPUS 4 development team + * @license http://www.gnu.org/licenses/gpl.html General Public License + */ + +//namespace library\Application\Form\Validate; + + +class Application_Form_Validate_FilenameTest extends ControllerTestCase { + + /** + * Data provider for valid arguments. + * + * @return array Array of invalid arguments. + */ + public function validDataProvider() { + return array( + array('Test.txt'), + array('Big_data.pdf'), + array('Python-Code.pdf'), + array('Opus4.txt'), + array('4.7_Handbuch_Opus-4.pdf') + ); + } + + /** + * Data provider for invalid arguments. + * + * @return array Array of invalid arguments and a message. + */ + public function invalidDataProvider() { + return array( + array(null, 'Null value not rejected'), + array('', 'Empty string not rejected'), + array('_test.txt', 'Malformed string not rejected.'), + array(true, 'Boolean not rejected'), + array('-Opus4.pdf', 'Malformed string not rejected.'), + array('testtesttesttesttesttesttesttesttesttesttesttesttesttesttest.pdf', 'String too long') + ); + } + + /** + * Test validation of incorrect arguments. + * + * @param mixed $arg Invalid value to check given by the data provider. + * @param string $msg Error message. + * @return void + * + * @dataProvider invalidDataProvider + */ + public function testInvalidArguments($arg, $msg) { + $config = Application_Configuration::getInstance()->getConfig(); + $filenameMaxLength = $config->publish->filenameMaxLength; + $filenameFormat = $config->publish->filenameFormat; + $filenameOptions = [ + 'filenameMaxLength' => $filenameMaxLength, + 'filenameFormat' => $filenameFormat + ]; + $validator = new Application_Form_Validate_Filename($filenameOptions); + $this->assertFalse($validator->isValid($arg), $msg); + } + + /** + * Test validation of correct arguments. + * + * @param mixed $arg Value to check given by the data provider. + * @return void + * + * @dataProvider validDataProvider + */ + public function testValidArguments($arg) + { + $config = Application_Configuration::getInstance()->getConfig(); + $filenameMaxLength = $config->publish->filenameMaxLength; + $filenameFormat = $config->publish->filenameFormat; + $filenameOptions = [ + 'filenameMaxLength' => $filenameMaxLength, + 'filenameFormat' => $filenameFormat + ]; + $validator = new Application_Form_Validate_Filename($filenameOptions); + + $result = $validator->isValid($arg); + + $codes = $validator->getErrors(); + $msgs = $validator->getMessages(); + $err = ''; + foreach ($codes as $code) { + $err .= '(' . $msgs[$code] . ') '; + } + + $this->assertTrue($result, $arg . ' should pass validation but validator says: ' . $err); + } +} \ No newline at end of file From 6960b545632e63c5a908140f89d64c10b646a711 Mon Sep 17 00:00:00 2001 From: BioFreak95 Date: Fri, 17 Aug 2018 12:20:24 +0200 Subject: [PATCH 045/128] OPUSVIER-3908 Add some Filename-testcases --- tests/library/Application/Form/Validate/FilenameTest.php | 3 +++ 1 file changed, 3 insertions(+) diff --git a/tests/library/Application/Form/Validate/FilenameTest.php b/tests/library/Application/Form/Validate/FilenameTest.php index ce28e960d..5ce144b09 100644 --- a/tests/library/Application/Form/Validate/FilenameTest.php +++ b/tests/library/Application/Form/Validate/FilenameTest.php @@ -63,6 +63,9 @@ public function invalidDataProvider() { array('_test.txt', 'Malformed string not rejected.'), array(true, 'Boolean not rejected'), array('-Opus4.pdf', 'Malformed string not rejected.'), + array('Töst.pdf', 'Malformed string not rejected.'), + array('!Töst.pdf', 'Malformed string not rejected.'), + array('Töst?.pdf', 'Malformed string not rejected.'), array('testtesttesttesttesttesttesttesttesttesttesttesttesttesttest.pdf', 'String too long') ); } From 2e8086bff64666c480f11802f45fa4f573b71ae8 Mon Sep 17 00:00:00 2001 From: BioFreak95 Date: Fri, 17 Aug 2018 12:59:36 +0200 Subject: [PATCH 046/128] OPUSVIER-3908 rename JS-File --- public/layouts/opus4/common.phtml | 2 +- public/layouts/opus4/js/{filetypes.js => upload.js} | 0 2 files changed, 1 insertion(+), 1 deletion(-) rename public/layouts/opus4/js/{filetypes.js => upload.js} (100%) diff --git a/public/layouts/opus4/common.phtml b/public/layouts/opus4/common.phtml index bba4c1c4a..686cb574c 100644 --- a/public/layouts/opus4/common.phtml +++ b/public/layouts/opus4/common.phtml @@ -86,7 +86,7 @@ if (in_array($this->moduleName, array('admin', 'review', 'setup', 'account'))) { $jsFiles[] = 'opus-ui.js'; } else if (in_array($this->moduleName, array('publish'))) { - $jsFiles[] = 'filetypes.js'; + $jsFiles[] = 'upload.js'; } if ($this->jQueryEnabled()) { diff --git a/public/layouts/opus4/js/filetypes.js b/public/layouts/opus4/js/upload.js similarity index 100% rename from public/layouts/opus4/js/filetypes.js rename to public/layouts/opus4/js/upload.js From e71ef2946e0a22d5f5d9fd6220beb91be264e6a3 Mon Sep 17 00:00:00 2001 From: BioFreak95 Date: Fri, 17 Aug 2018 14:04:28 +0200 Subject: [PATCH 047/128] OPUSVIER-3908 reviewchanges codingstyle and variables --- application/configs/config.ini.template | 2 + .../Application/Form/Validate/Filename.php | 41 ++++++++++++++----- modules/publish/forms/PublishingFirst.php | 4 +- .../publish/views/scripts/index/index.phtml | 7 ++-- public/layouts/opus4/js/upload.js | 18 ++++---- .../Form/Validate/FilenameTest.php | 41 ++++++++++--------- 6 files changed, 68 insertions(+), 45 deletions(-) diff --git a/application/configs/config.ini.template b/application/configs/config.ini.template index a5fe56c94..5574715bc 100644 --- a/application/configs/config.ini.template +++ b/application/configs/config.ini.template @@ -135,6 +135,8 @@ gnd.linkAuthor.frontdoor = 1 ; publish.filetypes.allowed defines which filetypes can be uploaded. ;publish.filetypes.allowed = pdf,txt,html,htm ; filetypes that are accepted in publication form ;publish.filenameMaxLength = 50 +;This is an regular expression which allows an alphanumerical filename. It is allowed to use _, - and . but not at beginning. +;Please use an expression without the typical starting and ending backslash, this is automatically added. ;publish.filenameFormat = "^[a-zA-Z0-9][a-zA-Z0-9_.-]+$" ; CHECKSUM SETTINGS diff --git a/library/Application/Form/Validate/Filename.php b/library/Application/Form/Validate/Filename.php index b6b75a15e..00fa4a854 100644 --- a/library/Application/Form/Validate/Filename.php +++ b/library/Application/Form/Validate/Filename.php @@ -36,8 +36,15 @@ */ class Application_Form_Validate_Filename extends Zend_Validate_Abstract { - protected $_filenameMaxLength = ''; - protected $_filenameFormat = ''; + /** + * @var int maximal filename length + */ + protected $filenameMaxLength = 0; + + /** + * @var string the format is a empty string. If this is used as regex, it matches always. + */ + protected $filenameFormat = ''; /** * Error message key for invalid filename length @@ -63,7 +70,7 @@ class Application_Form_Validate_Filename extends Zend_Validate_Abstract * @var array */ protected $_messageVariables = array( - 'size' => '_filenameMaxLength', + 'size' => 'filenameMaxLength', ); /** @@ -72,8 +79,24 @@ class Application_Form_Validate_Filename extends Zend_Validate_Abstract */ public function __construct($options) { - $this->_filenameMaxLength = $options['filenameMaxLength']; - $this->_filenameFormat = '/' . $options['filenameFormat'] . '/'; + self::setFilenameMaxLength($options['filenameMaxLength']); + self::setFilenameFormat('/' . $options['filenameFormat'] . '/'); + } + + public function getFilenameMaxLength(){ + return $this->filenameMaxLength; + } + + public function getFilenameFormat(){ + return $this->filenameFormat; + } + + public function setFilenameMaxLength($value){ + $this->filenameMaxLength = $value; + } + + public function setFilenameFormat($value){ + $this->filenameFormat = $value; } /** @@ -91,22 +114,20 @@ public function isValid($value, $file = null) } else { $data = pathinfo($value); if (!array_key_exists('filename', $data)) { - return false; } } - if (strlen($data['filename']) > $this->_filenameMaxLength) { + if (strlen($data['filename']) > $this->filenameMaxLength) { $this->_error(self::MSG_NAME_LENGTH); return false; } - if (preg_match($this->_filenameFormat, $data['filename']) === 0) { + if (preg_match($this->filenameFormat, $data['filename']) === 0) { $this->_error(self::MSG_NAME_FORMAT); return false; } return true; } - -} \ No newline at end of file +} diff --git a/modules/publish/forms/PublishingFirst.php b/modules/publish/forms/PublishingFirst.php index 18a90502e..5ab5e2899 100644 --- a/modules/publish/forms/PublishingFirst.php +++ b/modules/publish/forms/PublishingFirst.php @@ -271,8 +271,8 @@ public function setViewValues() { $this->view->documentUpload = $group; $this->view->MAX_FILE_SIZE = $this->_config->publish->maxfilesize; - $this->view->maxFileNameLength = $this->_config->publish->maxFileNameLength; - $this->view->allowedFilenameCharset = $this->_config->publish->allowedFilenameCharset; + $this->view->filenameMaxLength = $this->_config->publish->filenameMaxLength; + $this->view->filenameFormat = $this->_config->publish->filenameFormat; } } diff --git a/modules/publish/views/scripts/index/index.phtml b/modules/publish/views/scripts/index/index.phtml index db4b44b65..a3c1c1b8e 100644 --- a/modules/publish/views/scripts/index/index.phtml +++ b/modules/publish/views/scripts/index/index.phtml @@ -30,7 +30,6 @@ * @author Maximilian Salomon * @copyright Copyright (c) 2008-2018, OPUS 4 development team * @license http://www.gnu.org/licenses/gpl.html General Public License - * @version $Id$ */ ?> @@ -41,7 +40,7 @@ 'invalidFileSize' => 'fileUploadErrorSize', 'invalidFilenameLength' => 'filenameLengthError', 'invalidFilenameFormat' => 'filenameFormatError', - 'anotherFileMessage' => 'chooseAnotherFile' + 'anotherFile' => 'chooseAnotherFile' ]; ?> + + + + +
+

Tests of ISSN-validation

+

This test-page tests the ISSN-validation with javascript.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Test-ISSNExpectationActualTest-Result
1050-124XTrue
0001-3218True
0025-5858True
1062-5127True
0317-8471True
12345478False
nullFalse
trueFalse
12456-65478False
123456789False
1050 124XFalse
1050_124XFalse
1050-1242False
+
+ + From 04fc7106dbd80d17ba5e52608d2a181c9d11c33e Mon Sep 17 00:00:00 2001 From: BioFreak95 Date: Fri, 24 Aug 2018 12:22:58 +0200 Subject: [PATCH 064/128] OPUSVIER-3899 Add ISBN-validation with JS and an JS-test-webpage --- public/layouts/opus4/js/validation.js | 104 ++++ tests/javascript/testIsbnValidation.html | 579 +++++++++++++++++++++++ 2 files changed, 683 insertions(+) create mode 100644 tests/javascript/testIsbnValidation.html diff --git a/public/layouts/opus4/js/validation.js b/public/layouts/opus4/js/validation.js index 5fe45bccf..f6d55c66e 100644 --- a/public/layouts/opus4/js/validation.js +++ b/public/layouts/opus4/js/validation.js @@ -72,4 +72,108 @@ function calculateCheckDigitISSN(value) { } return checkdigit; +} + +function validateISBN(value) { + // var messages = { + // invalidCheckdigit: "The check digit of \'%value%\' is not valid", + // invalidFormat: "\'%value%\' is malformed" + // }; + + var isbnDigits = splitISBN(value); + + if (isbnDigits.length === 10) { + return validateISBN10(value); + } + else if (isbnDigits.length === 13) { + return validateISBN13(value); + } + else { + //alert(messages.invalidFormat.replace("%value%", value)); + return false; + } +} + +function validateISBN10(value) { + // var messages = { + // invalidCheckdigit: "The check digit of \'%value%\' is not valid", + // invalidFormat: "\'%value%\' is malformed" + // }; + + if (value.length !== 10 && value.length !== 13) { + return false; + } + + if (value.match(/^[\d]*((-|\s)?[\d]*){2}((-|\s)?[\dX])$/g) === null) { + //alert(messages.invalidFormat.replace("%value%", value)); + return false; + } + + if (value.match(/-/) !== null && value.match(/\s/) !== null) { + //alert(messages.invalidFormat.replace("%value%", value)); + return false; + } + + var isbnDigits = splitISBN(value); + return calculateCheckDigitISBN10(isbnDigits); +} + +function validateISBN13(value) { + // var messages = { + // invalidCheckdigit: "The check digit of \'%value%\' is not valid", + // invalidFormat: "\'%value%\' is malformed" + // }; + + if (value.length !== 13 && value.length !== 17) { + return false; + } + + if (value.match(/^(978|979)((-|\s)?[\d]*){4}$/g) === null) { + //alert(messages.invalidFormat.replace("%value%", value)); + return false; + } + + if (value.match(/-/) !== null && value.match(/\s/) !== null) { + //alert(messages.invalidFormat.replace("%value%", value)); + return false; + } + + var isbnDigits = splitISBN(value); + return calculateCheckDigitISBN13(isbnDigits); +} + +function calculateCheckDigitISBN10(value) { + var z = value; + + if (z[9] === "X") { + z[9] = 10; + } + z = z.map(Number); + var check = 10 * z[0] + 9 * z[1] + 8 * z[2] + 7 * z[3] + 6 * z[4] + 5 * z[5] + 4 * z[6] + 3 * z[7] + 2 * z[8] + 1 * z[9]; + + return (check % 11 === 0); +} + +function calculateCheckDigitISBN13(value) { + var z = value.map(Number); + + var check = (z[0] + z[2] + z[4] + z[6] + z[8] + z[10] + z[12]) + 3 * (z[1] + z[3] + z[5] + z[7] + z[9] + z[11]); + return (check % 10 === 0); +} + + +function splitISBN(value) { + var isbn = value.split(/(-|\s)/); + var digits = []; + isbn.forEach(function (isbn) { + if (isbn.match((/(-|\s)/))) { + return true; + } + var isbn_parts = isbn.split(""); + isbn_parts.forEach(function (isbn_parts) { + digits.push(isbn_parts); + }); + }); + + return digits; } \ No newline at end of file diff --git a/tests/javascript/testIsbnValidation.html b/tests/javascript/testIsbnValidation.html new file mode 100644 index 000000000..dafea1aa6 --- /dev/null +++ b/tests/javascript/testIsbnValidation.html @@ -0,0 +1,579 @@ + + + + + + + + testValidation + + + + + +
+

Tests of ISBN-validation

+

This test-page tests the ISBN-validation with javascript. There are for every function one part. validateISBN10, + validateISBN13 and validateISBN.

+

Tests of ISBN-validation

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Test-ISBNExpectationActualTest-Result
3-935024-10-XTrue
393502410XTrue
3-86680-192-0True
3-937602-69-0True
3 86680 192 0True
3 937602 69 0True
978-3-86680-192-9True
3-937602-69-0True
978-5-7931-8163-1True
978-979-3182-63-6True
978 3 86680 192 9True
978 5 7931 8163 1True
978 979 3182 63 6True
978-3-86680-192-9True
9789793182636True
nullFalse
False
4711False
trueFalse
4711-0815False
980-3-86680-192-9False
978-3-86680-192-5False
978 3 86680-192-9False
nullFalse
False
4711False
trueFalse
4711-0815False
3-86680-192-5False
3 86680 192-0False
3-86680-1902-0False
+ +

Tests of ISBN10-validation

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Test-ISBNExpectationActualTest-Result
3-935024-10-XTrue
393502410XTrue
3-86680-192-0True
3-937602-69-0True
3 86680 192 0True
3 937602 69 0True
39376026940False
nullFalse
False
4711False
trueFalse
4711-0815False
978-3-86680-192-9False
3-86680-192-5False
3 86680 192-0False
3-86680-1902-0False
+ +

Tests of ISBN13-validation

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Test-ISBNExpectationActualTest-Result
978-3-86680-192-9True
978-5-7931-8163-1True
978-979-3182-63-6True
978 3 86680 192 9True
978 5 7931 8163 1True
978 979 3182 63 6True
9789793182636True
nullFalse
False
4711False
trueFalse
4711-0815False
980-3-86680-192-9False
978-3-86680-192-5False
978 3 86680-192-9False
3-937602-69-0False
+
+ + From d327a017be3fe693021452128cef477aae9f9906 Mon Sep 17 00:00:00 2001 From: BioFreak95 Date: Fri, 24 Aug 2018 17:56:38 +0200 Subject: [PATCH 065/128] OPUSVIER-3899 Add identifier-validation to admin-module --- public/layouts/opus4/common.phtml | 5 ++- public/layouts/opus4/js/validation.js | 49 ++++++++++++++++++++++++++- 2 files changed, 52 insertions(+), 2 deletions(-) diff --git a/public/layouts/opus4/common.phtml b/public/layouts/opus4/common.phtml index bba4c1c4a..5cb2ea3e6 100644 --- a/public/layouts/opus4/common.phtml +++ b/public/layouts/opus4/common.phtml @@ -85,7 +85,10 @@ if (in_array($this->moduleName, array('admin', 'review', 'setup', 'account'))) { $jsFiles[] = 'theme_lic.js'; $jsFiles[] = 'opus-ui.js'; } -else if (in_array($this->moduleName, array('publish'))) { + +if (in_array($this->moduleName, array('admin'))) { + $jsFiles[] = 'validation.js'; +} else if (in_array($this->moduleName, array('publish'))) { $jsFiles[] = 'filetypes.js'; } diff --git a/public/layouts/opus4/js/validation.js b/public/layouts/opus4/js/validation.js index f6d55c66e..05c7d9ba3 100644 --- a/public/layouts/opus4/js/validation.js +++ b/public/layouts/opus4/js/validation.js @@ -176,4 +176,51 @@ function splitISBN(value) { }); return digits; -} \ No newline at end of file +} + + +$(document).ready(function () { + var selectors = []; + var result; + + var identifier = $("#fieldset-Identifiers tbody tr td.Value-data"); + var identifierText = $("#fieldset-Identifiers tbody tr :text"); + var identifierSelector = $("#fieldset-Identifiers tbody tr select"); + + $.each(identifier, function (index, value) { + var para = document.createElement("p"); + para.classList.add("datahint"); + para.setAttribute("style", "display : none"); + value.appendChild(para); + }); + + $.each(identifierSelector, function (index, value) { + selectors[index] = value.value; + value.onchange = function () { + selectors[index] = value.value; + }; + }); + + + $.each(identifierText, function (index, value) { + var ident = selectors[index]; + + value.onchange = function () { + if (ident === "isbn") { + result = validateISBN(value.value); + } + else if (ident === "issn") { + + result = validateISSN(value.value); + } + else { + result = true; + } + if (result !== true) { + $(identifier[index]).find("p")[0].innerHTML = result; + $(identifier[index]).find("p").removeAttr("style"); + } + }; + }); + +}); \ No newline at end of file From 900c9b3e5c46460a65431678e7f4be0be632b4cf Mon Sep 17 00:00:00 2001 From: BioFreak95 Date: Fri, 24 Aug 2018 18:12:37 +0200 Subject: [PATCH 066/128] OPUSVIER-3899 Add more detailed messages --- public/layouts/opus4/js/validation.js | 60 ++++++++++++--------------- 1 file changed, 26 insertions(+), 34 deletions(-) diff --git a/public/layouts/opus4/js/validation.js b/public/layouts/opus4/js/validation.js index 05c7d9ba3..befb8298b 100644 --- a/public/layouts/opus4/js/validation.js +++ b/public/layouts/opus4/js/validation.js @@ -31,21 +31,19 @@ function validateISSN(value) { - // var messages = { - // invalidCheckdigit: "The check digit of \'%value%\' is not valid", - // invalidFormat: "\'%value%\' is malformed" - // }; + var messages = { + invalidCheckdigit: "The check digit of \'%value%\' is not valid", + invalidFormat: "\'%value%\' is malformed" + }; // check length if (value.length !== 9) { - //alert(messages.invalidFormat.replace("%value%", value)); - return false; + return messages.invalidFormat.replace("%value%", value); } // check form if (value.match(/^[0-9]{4}[-][0-9]{3}[0-9X]$/g) === null) { - //alert(messages.invalidFormat.replace("%value%", value)); - return false; + return messages.invalidFormat.replace("%value%", value); } // Split ISSN into its parts @@ -54,8 +52,7 @@ function validateISSN(value) { // Calculate and compare check digit var checkdigit = calculateCheckDigitISSN(issn); if (checkdigit != issn[8]) { - //alert(messages.invalidCheckdigit.replace("%value%", value)); - return false; + return messages.invalidCheckdigit.replace("%value%", value); } return true; @@ -75,10 +72,10 @@ function calculateCheckDigitISSN(value) { } function validateISBN(value) { - // var messages = { - // invalidCheckdigit: "The check digit of \'%value%\' is not valid", - // invalidFormat: "\'%value%\' is malformed" - // }; + var messages = { + invalidCheckdigit: "The check digit of \'%value%\' is not valid", + invalidFormat: "\'%value%\' is malformed" + }; var isbnDigits = splitISBN(value); @@ -89,29 +86,26 @@ function validateISBN(value) { return validateISBN13(value); } else { - //alert(messages.invalidFormat.replace("%value%", value)); - return false; + return messages.invalidFormat.replace("%value%", value); } } function validateISBN10(value) { - // var messages = { - // invalidCheckdigit: "The check digit of \'%value%\' is not valid", - // invalidFormat: "\'%value%\' is malformed" - // }; + var messages = { + invalidCheckdigit: "The check digit of \'%value%\' is not valid", + invalidFormat: "\'%value%\' is malformed" + }; if (value.length !== 10 && value.length !== 13) { - return false; + return messages.invalidFormat.replace("%value%", value); } if (value.match(/^[\d]*((-|\s)?[\d]*){2}((-|\s)?[\dX])$/g) === null) { - //alert(messages.invalidFormat.replace("%value%", value)); - return false; + return messages.invalidFormat.replace("%value%", value); } if (value.match(/-/) !== null && value.match(/\s/) !== null) { - //alert(messages.invalidFormat.replace("%value%", value)); - return false; + return messages.invalidFormat.replace("%value%", value); } var isbnDigits = splitISBN(value); @@ -119,23 +113,21 @@ function validateISBN10(value) { } function validateISBN13(value) { - // var messages = { - // invalidCheckdigit: "The check digit of \'%value%\' is not valid", - // invalidFormat: "\'%value%\' is malformed" - // }; + var messages = { + invalidCheckdigit: "The check digit of \'%value%\' is not valid", + invalidFormat: "\'%value%\' is malformed" + }; if (value.length !== 13 && value.length !== 17) { - return false; + return messages.invalidFormat.replace("%value%", value); } if (value.match(/^(978|979)((-|\s)?[\d]*){4}$/g) === null) { - //alert(messages.invalidFormat.replace("%value%", value)); - return false; + return messages.invalidFormat.replace("%value%", value); } if (value.match(/-/) !== null && value.match(/\s/) !== null) { - //alert(messages.invalidFormat.replace("%value%", value)); - return false; + return messages.invalidFormat.replace("%value%", value); } var isbnDigits = splitISBN(value); From 46ed4a49a53e2b939265f1fd0d97f0c1a9b57abd Mon Sep 17 00:00:00 2001 From: BioFreak95 Date: Mon, 10 Sep 2018 16:29:22 +0200 Subject: [PATCH 067/128] OPUSVIER-3899 Bugfix Errormessage hidded after correct identifier Validation no save selectortext after change --- public/layouts/opus4/js/validation.js | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/public/layouts/opus4/js/validation.js b/public/layouts/opus4/js/validation.js index befb8298b..9a5f7cd60 100644 --- a/public/layouts/opus4/js/validation.js +++ b/public/layouts/opus4/js/validation.js @@ -174,6 +174,7 @@ function splitISBN(value) { $(document).ready(function () { var selectors = []; var result; + var ident; var identifier = $("#fieldset-Identifiers tbody tr td.Value-data"); var identifierText = $("#fieldset-Identifiers tbody tr :text"); @@ -190,12 +191,12 @@ $(document).ready(function () { selectors[index] = value.value; value.onchange = function () { selectors[index] = value.value; + ident = selectors[index]; }; }); $.each(identifierText, function (index, value) { - var ident = selectors[index]; value.onchange = function () { if (ident === "isbn") { @@ -212,6 +213,9 @@ $(document).ready(function () { $(identifier[index]).find("p")[0].innerHTML = result; $(identifier[index]).find("p").removeAttr("style"); } + else { + $(identifier[index]).find("p").attr("style", "display : none"); + } }; }); From d91923faa50a2d58c14bb092a5dea5e570c284f5 Mon Sep 17 00:00:00 2001 From: j3nsch Date: Thu, 20 Sep 2018 16:51:57 +0200 Subject: [PATCH 068/128] OPUSVIER-3903 Better default language handling. --- library/Application/Configuration.php | 29 +++++++++++++++---- .../library/Application/ConfigurationTest.php | 12 +++++++- 2 files changed, 35 insertions(+), 6 deletions(-) diff --git a/library/Application/Configuration.php b/library/Application/Configuration.php index 153e75315..b7184aa37 100644 --- a/library/Application/Configuration.php +++ b/library/Application/Configuration.php @@ -66,6 +66,11 @@ class Application_Configuration { */ private $_tempPath = null; + /** + * @var string + */ + private $defaultLanguage = null; + /** * @var Application_Configuration */ @@ -162,13 +167,27 @@ public function isLanguageSupported($language) { * @return string */ public function getDefaultLanguage() { - if ($this->isLanguageSelectionEnabled()) { - return self::DEFAULT_LANGUAGE; - } - else { + if (is_null($this->defaultLanguage)) { $languages = $this->getSupportedLanguages(); - return $languages[0]; + $this->defaultLanguage = $languages[0]; + + if ($this->isLanguageSelectionEnabled()) { + $locale = new Zend_Locale(); + $language = $locale->getDefault(); + if (is_array($language) and count($language) > 0) { + reset($language); + $language = key($language); + } else { + $language = self::DEFAULT_LANGUAGE; + } + + if ($this->isLanguageSupported($language)) { + $this->defaultLanguage = $language; + } + } } + + return $this->defaultLanguage; } /** diff --git a/tests/library/Application/ConfigurationTest.php b/tests/library/Application/ConfigurationTest.php index 996f24195..a39e8ad63 100644 --- a/tests/library/Application/ConfigurationTest.php +++ b/tests/library/Application/ConfigurationTest.php @@ -112,7 +112,7 @@ public function testIsLanguageSelectionEnabledFalse() { } public function testGetDefaultLanguage() { - $this->assertEquals('en', $this->config->getDefaultLanguage()); + $this->assertEquals('de', $this->config->getDefaultLanguage()); } public function testGetDefaultLanguageIfOnlyOneIsSupported() { @@ -120,6 +120,16 @@ public function testGetDefaultLanguageIfOnlyOneIsSupported() { $this->assertEquals('de', $this->config->getDefaultLanguage()); } + public function testGetDefaultLanguageUnsupportedConfigured() { + // because bootstrapping already happened locale needs to be manipulated directly + $locale = new Zend_Locale(); + $locale->setDefault('fr'); + $this->assertEquals('de', $this->config->getDefaultLanguage()); + + $locale->setDefault('de'); + $this->assertEquals('de', $this->config->getDefaultLanguage()); + } + /** * Checks that the path is correct with '/' at the end. */ From 1a5d6975c4f20b1082455684703f3836056a6e18 Mon Sep 17 00:00:00 2001 From: j3nsch Date: Mon, 8 Oct 2018 11:51:28 +0200 Subject: [PATCH 069/128] OPUSVIER-2155 Removed references to DisplayOai field. Code styling. --- modules/admin/language/collections.tmx | 9 - scripts/opus-create-xss-document.php | 5 +- .../snippets/create_all_fields_document.php | 8 +- .../controllers/CollectionControllerTest.php | 157 +++++++++------ .../CollectionrolesControllerTest.php | 81 ++++---- .../admin/models/CollectionRoleTest.php | 42 ++-- .../modules/admin/models/CollectionsTest.php | 20 +- .../modules/publish/models/ValidationTest.php | 181 ++++++++++-------- 8 files changed, 289 insertions(+), 214 deletions(-) diff --git a/modules/admin/language/collections.tmx b/modules/admin/language/collections.tmx index 20d1e470c..2e5d67daa 100644 --- a/modules/admin/language/collections.tmx +++ b/modules/admin/language/collections.tmx @@ -427,15 +427,6 @@ - - - Shown metadata fields in OAI set. - - - Auszugebende Metadaten-Felder im OAI-Set. - - - Your current position: diff --git a/scripts/opus-create-xss-document.php b/scripts/opus-create-xss-document.php index 9fa06481e..a213b0c30 100644 --- a/scripts/opus-create-xss-document.php +++ b/scripts/opus-create-xss-document.php @@ -26,9 +26,9 @@ * * @category Application * @author Thoralf Klein - * @copyright Copyright (c) 2008-2010, OPUS 4 development team + * @author Jens Schwidder + * @copyright Copyright (c) 2008-2018, OPUS 4 development team * @license http://www.gnu.org/licenses/gpl.html General Public License - * @version $Id$ */ // Bootstrapping @@ -158,7 +158,6 @@ function myErrorHandler($errno, $errstr, $errfile, $errline) { ->setVisibleFrontdoor(1) ->setDisplayFrontdoor('Name') ->setVisibleOai('Name') - ->setDisplayOai('Name') ->store(); $instituteName='Institut für empirische Forschung ' . randString($counter++); diff --git a/scripts/snippets/create_all_fields_document.php b/scripts/snippets/create_all_fields_document.php index e1e1cece0..8f74212b0 100644 --- a/scripts/snippets/create_all_fields_document.php +++ b/scripts/snippets/create_all_fields_document.php @@ -26,9 +26,12 @@ * * @category Application * @author Pascal-Nicolas Becker - * @copyright Copyright (c) 2008-2010, OPUS 4 development team + * @author Jens Schwidder + * @copyright Copyright (c) 2008-2018, OPUS 4 development team * @license http://www.gnu.org/licenses/gpl.html General Public License - * @version $Id$ + * + * TODO use fromArray functionality to create document + * TODO create test that verifies completeness (compare with describe function) */ $doc = new Opus_Document(); @@ -93,7 +96,6 @@ ->setVisibleFrontdoor(1) ->setDisplayFrontdoor('Name') ->setVisibleOai('Name') - ->setDisplayOai('Name') ->store(); } $instituteCollections = Opus_Collection::fetchCollectionsByRoleName($institutesRole->getId(), $instituteName); diff --git a/tests/modules/admin/controllers/CollectionControllerTest.php b/tests/modules/admin/controllers/CollectionControllerTest.php index 7888ff4d1..34f8e65a3 100644 --- a/tests/modules/admin/controllers/CollectionControllerTest.php +++ b/tests/modules/admin/controllers/CollectionControllerTest.php @@ -37,7 +37,8 @@ * * @covers Admin_CollectionController */ -class Admin_CollectionControllerTest extends ControllerTestCase { +class Admin_CollectionControllerTest extends ControllerTestCase +{ private $emptyCollectionRole = null; private $nonEmptyCollectionRole = null; @@ -45,7 +46,8 @@ class Admin_CollectionControllerTest extends ControllerTestCase { private $anotherCollection = null; private $rootCollection = null; - public function setUp() { + public function setUp() + { parent::setUp(); $this->emptyCollectionRole = new Opus_CollectionRole(); @@ -53,7 +55,6 @@ public function setUp() { $this->emptyCollectionRole->setOaiName("test1role"); $this->emptyCollectionRole->setDisplayBrowsing("Name"); $this->emptyCollectionRole->setDisplayFrontdoor("Name"); - $this->emptyCollectionRole->setDisplayOai("Name"); $this->emptyCollectionRole->setPosition(100); $this->emptyCollectionRole->store(); @@ -62,7 +63,6 @@ public function setUp() { $this->nonEmptyCollectionRole->setOaiName("test2role"); $this->nonEmptyCollectionRole->setDisplayBrowsing("Name"); $this->nonEmptyCollectionRole->setDisplayFrontdoor("Name"); - $this->nonEmptyCollectionRole->setDisplayOai("Name"); $this->nonEmptyCollectionRole->setPosition(101); $this->nonEmptyCollectionRole->store(); @@ -82,7 +82,8 @@ public function setUp() { $this->anotherCollection->store(); } - public function tearDown() { + public function tearDown() + { if (!is_null($this->nonEmptyCollectionRole) && !is_null($this->nonEmptyCollectionRole->getId())) { $this->nonEmptyCollectionRole->delete(); } @@ -92,7 +93,8 @@ public function tearDown() { parent::tearDown(); } - public function testIndexAction() { + public function testIndexAction() + { $this->dispatch('/admin/collection'); $this->assertRedirect(); $this->assertResponseLocationHeader($this->getResponse(), '/admin/collectionroles'); @@ -101,16 +103,18 @@ public function testIndexAction() { /** * Test show first level of collection. */ - public function testShowAction() { + public function testShowAction() + { $this->dispatch('/admin/collection/show/id/' . $this->collection->getId()); $this->assertResponseCode(200); $this->assertModule('admin'); $this->assertController('collection'); $this->assertAction('show'); - $this->assertContains('123 first collection', $this->getResponse()->getBody()); + $this->assertContains('123 first collection', $this->getResponse()->getBody()); } - public function testShowActionWithEmptyRole() { + public function testShowActionWithEmptyRole() + { $this->dispatch('/admin/collection/show/role/' . $this->emptyCollectionRole->getId()); $this->assertResponseCode(200); $this->assertModule('admin'); @@ -118,7 +122,8 @@ public function testShowActionWithEmptyRole() { $this->assertAction('show'); } - public function testShowActionWithNonEmptyRole() { + public function testShowActionWithNonEmptyRole() + { $this->dispatch('/admin/collection/show/role/' . $this->nonEmptyCollectionRole->getId()); $this->assertResponseCode(200); $this->assertModule('admin'); @@ -128,13 +133,15 @@ public function testShowActionWithNonEmptyRole() { $this->assertContains('987 last collection', $this->getResponse()->getBody()); } - public function testShowActionMissingArg() { + public function testShowActionMissingArg() + { $this->dispatch('/admin/collection/show'); $this->assertRedirect(); $this->assertResponseLocationHeader($this->getResponse(), '/admin/collectionroles'); } - public function testEditAction() { + public function testEditAction() + { $this->dispatch('/admin/collection/edit/id/' . $this->collection->getId()); $this->assertResponseCode(200); $this->assertModule('admin'); @@ -142,20 +149,23 @@ public function testEditAction() { $this->assertAction('edit'); } - public function testDeleteAction() { + public function testDeleteAction() + { $this->dispatch('/admin/collection/delete/id/' . $this->collection->getId()); $this->assertRedirect(); $this->assertResponseLocationHeader($this->getResponse(), '/admin/collection/show/id/' . $this->rootCollection->getId()); } - public function testDeleteActionWithMissingParam() { + public function testDeleteActionWithMissingParam() + { $this->dispatch('/admin/collection/delete'); $this->assertRedirect(); $this->assertResponseLocationHeader($this->getResponse(), '/admin/collectionroles'); } - public function testNewAction() { + public function testNewAction() + { $this->dispatch('/admin/collection/new/type/child/id/' . $this->collection->getId()); $this->assertResponseCode(200); $this->assertModule('admin'); @@ -163,95 +173,110 @@ public function testNewAction() { $this->assertAction('new'); } - public function testNewActionWithMissingParams() { + public function testNewActionWithMissingParams() + { $this->dispatch('/admin/collection/new'); $this->assertRedirect(); $this->assertResponseLocationHeader($this->getResponse(), '/admin/collectionroles'); } - public function testNewActionWithMissingParam() { + public function testNewActionWithMissingParam() + { $this->dispatch('/admin/collection/new/id/' . $this->collection->getId()); $this->assertRedirect(); $this->assertResponseLocationHeader($this->getResponse(), '/admin/collectionroles'); } - public function testHideAction() { + public function testHideAction() + { $this->dispatch('/admin/collection/hide/id/' . $this->collection->getId()); $this->assertRedirect(); $this->assertResponseLocationHeader($this->getResponse(), '/admin/collection/show/id/' . $this->rootCollection->getId()); } - public function testHideActionWithMissingParam() { + public function testHideActionWithMissingParam() + { $this->dispatch('/admin/collection/hide'); $this->assertRedirect(); $this->assertResponseLocationHeader($this->getResponse(), '/admin/collectionroles'); } - public function testUnhideAction() { + public function testUnhideAction() + { $this->dispatch('/admin/collection/unhide/id/' . $this->collection->getId()); $this->assertRedirect(); $this->assertResponseLocationHeader($this->getResponse(), '/admin/collection/show/id/' . $this->rootCollection->getId()); } - public function testUnhideActionWithMissingParam() { + public function testUnhideActionWithMissingParam() + { $this->dispatch('/admin/collection/unhide'); $this->assertRedirect(); $this->assertResponseLocationHeader($this->getResponse(), '/admin/collectionroles'); } - public function testAssignActionWithMissingParam() { + public function testAssignActionWithMissingParam() + { $this->dispatch('/admin/collection/assign'); $this->assertRedirect(); $this->assertResponseLocationHeader($this->getResponse(), '/admin/collectionroles'); } - public function testMoveActionWithMissingParams() { + public function testMoveActionWithMissingParams() + { $this->dispatch('/admin/collection/move'); $this->assertRedirect(); $this->assertResponseLocationHeader($this->getResponse(), '/admin/collectionroles'); } - public function testMoveActionWithMissingPosParam() { + public function testMoveActionWithMissingPosParam() + { $this->dispatch('/admin/collection/move/id/' . $this->collection->getId()); $this->assertRedirect(); $this->assertResponseLocationHeader($this->getResponse(), '/admin/collectionroles'); } - public function testMoveActionWithMissingIdParam() { + public function testMoveActionWithMissingIdParam() + { $this->dispatch('/admin/collection/move/pos/1'); $this->assertRedirect(); $this->assertResponseLocationHeader($this->getResponse(), '/admin/collectionroles'); } - public function testMoveActionWithTooSmallPosParam() { + public function testMoveActionWithTooSmallPosParam() + { $this->dispatch('/admin/collection/move/id/' . $this->collection->getId() . '/pos/0'); $this->assertRedirect(); $this->assertResponseLocationHeader($this->getResponse(), '/admin/collectionroles'); } - public function testMoveActionWithTooLargePosParam() { + public function testMoveActionWithTooLargePosParam() + { $this->dispatch('/admin/collection/move/id/' . $this->collection->getId() . '/pos/3'); $this->assertRedirect(); $this->assertResponseLocationHeader($this->getResponse(), '/admin/collectionroles'); } - public function testMoveActionDownmove() { + public function testMoveActionDownmove() + { $this->dispatch('/admin/collection/move/id/' . $this->collection->getId() . '/pos/2'); $this->assertRedirect(); $this->assertResponseLocationHeader($this->getResponse(), '/admin/collection/show/id/' . $this->rootCollection->getId()); } - public function testMoveActionUpmove() { + public function testMoveActionUpmove() + { $this->dispatch('/admin/collection/move/id/' . $this->anotherCollection->getId() . '/pos/1'); $this->assertRedirect(); $this->assertResponseLocationHeader($this->getResponse(), '/admin/collection/show/id/' . $this->rootCollection->getId()); } - public function testMoveActionWithRootCollection() { + public function testMoveActionWithRootCollection() + { $this->dispatch('/admin/collection/move/id/' . $this->nonEmptyCollectionRole->getRootCollection()->getId() . '/pos/1'); $this->assertRedirect(); @@ -261,7 +286,8 @@ public function testMoveActionWithRootCollection() { /** * Anti-Regression Test for bug ticket OPUSVIER-1823 */ - public function testCollectionRoleGetsTranslatedAsLink() { + public function testCollectionRoleGetsTranslatedAsLink() + { $this->dispatch('/admin/collection/show/id/' . $this->collection->getId()); $this->assertContains('default_collection_role_test2role', $this->getResponse()->getBody()); @@ -270,60 +296,69 @@ public function testCollectionRoleGetsTranslatedAsLink() { /** * Anti-Regression Test for bug ticket OPUSVIER-1823 */ - public function testCollectionRoleGetsTranslatedAsText() { + public function testCollectionRoleGetsTranslatedAsText() + { $this->dispatch('/admin/collection/show/id/' . $this->rootCollection->getId()); - $this->assertQueryContentContains('//div[@class="breadcrumbsContainer"]//a[@href="/admin/collection/show/id/' + $this->assertQueryContentContains( + '//div[@class="breadcrumbsContainer"]//a[@href="/admin/collection/show/id/' . $this->rootCollection->getId() . '"]', - 'default_collection_role_test2role', $this->getResponse()->getBody()); + 'default_collection_role_test2role', $this->getResponse()->getBody() + ); } /** * Anti-Regression Test for bug ticket OPUSVIER-1889. */ - public function testCancelLinkAssignCollection() { + public function testCancelLinkAssignCollection() + { $this->dispatch('/admin/collection/assign/document/40'); $body = $this->getResponse()->getBody(); $this->assertNotContains('/admin/documents/edit/id/40', $body); // old link before fix ("documentS") $this->assertContains('/admin/document/edit/id/40/section/collections', $body); } - - public function testShowDocInfoOnAssignStartPage() { + + public function testShowDocInfoOnAssignStartPage() + { $this->dispatch('/admin/collection/assign/document/146'); $this->assertResponseCode(200); - + // check for docinfo header $this->assertQuery('div#docinfo', 'KOBV'); $this->assertQuery('div#docinfo', '146'); $this->assertQuery('div#docinfo', 'Doe, John'); } - public function testShowDocInfoOnAssignCollectionPage() { + public function testShowDocInfoOnAssignCollectionPage() + { $this->dispatch('/admin/collection/assign/id/2/document/146'); $this->assertResponseCode(200); - + // check for docinfo header $this->assertQuery('div#docinfo', 'KOBV'); $this->assertQuery('div#docinfo', '146'); $this->assertQuery('div#docinfo', 'Doe, John'); } - - public function testShowVisibilityOfRootCollections() { + + public function testShowVisibilityOfRootCollections() + { $this->dispatch('/admin/collection/assign/document/146'); $this->assertResponseCode(200); - + $this->assertQueryContentContains('td.visible', 'default_collection_role_reports'); $this->assertQueryContentContains('td.invisible', 'default_collection_role_invisible-collection'); } - - public function testShowVisibilityOfCollections() { + + public function testShowVisibilityOfCollections() + { $this->dispatch('/admin/collection/assign/id/4/document/146'); $this->assertResponseCode(200); - + $this->assertQueryContentContains('td.visible', '10 Philosophie'); $this->assertQueryContentContains('td.invisible', '11 Metaphysik'); } - public function testTooltipForInsertLinks() { + public function testTooltipForInsertLinks() + { $this->dispatch('/admin/collection/show/id/2485'); $this->assertResponseCode(200); @@ -339,54 +374,58 @@ public function testTooltipForInsertLinks() { } } } - - public function testRegression3054DoNotShowCollectionRoleWithoutRoot() { + + public function testRegression3054DoNotShowCollectionRoleWithoutRoot() + { $this->dispatch('/admin/collection/assign/document/40'); $this->assertNotQueryContentContains('table.collections', 'default_collection_role_no-root-test'); } - public function testCollectionRolesTranslatedOnAssignPage() { + public function testCollectionRolesTranslatedOnAssignPage() + { $this->useEnglish(); $this->dispatch('/admin/collection/assign/document/146'); $this->assertQueryContentContains('//a[@href="/admin/collection/assign/id/2/document/146"]', 'Dewey Decimal Classification'); } - public function testCollectionBreadcrumbTranslatedAndLinked() { + public function testCollectionBreadcrumbTranslatedAndLinked() + { $this->useEnglish(); $this->dispatch('/admin/collection/new/id/2/type/child'); // add entry to DDC $this->assertResponseCode(200); $this->assertQueryContentContains( - '//div[@class="breadcrumbsContainer"]//a[@href="/admin/collection/show/id/2"]', + '//div[@class="breadcrumbsContainer"]//a[@href="/admin/collection/show/id/2"]', 'Dewey Decimal Classification'); } - public function testCreateCollectionCancel() { + public function testCreateCollectionCancel() + { $this->markTestIncomplete('Cancel Buttons hinzufügen und Test erweitern (OPUSVIER-3329)'); - $this->getRequest()->setMethod('POST')->setPost(array( + $this->getRequest()->setMethod('POST')->setPost([ 'Name' => 'TestCollection', 'Visible' => '1', 'Cancel' => 'Abbrechen' - )); + ]); $this->dispatch('/admin/collection/create/id/16216/type/sibling'); } - public function testCreateCollectionRedirect() { + public function testCreateCollectionRedirect() + { $this->markTestIncomplete('TODO implement test'); - $post = array( + $post = [ 'Name' => 'TestCol', 'Number' => 'TestCol', 'Visible' => 1, 'VisiblePublish' => 1, 'Save' => 'Speichern' - ); + ]; $this->dispatch('/admin/collection/create/id/type/child'); $this->assertRedirectTo(''); } - } diff --git a/tests/modules/admin/controllers/CollectionrolesControllerTest.php b/tests/modules/admin/controllers/CollectionrolesControllerTest.php index 519d0e66d..3df02991f 100644 --- a/tests/modules/admin/controllers/CollectionrolesControllerTest.php +++ b/tests/modules/admin/controllers/CollectionrolesControllerTest.php @@ -1,5 +1,4 @@ emptyCollectionRole = new Opus_CollectionRole(); @@ -48,7 +49,6 @@ public function setUp() { $this->emptyCollectionRole->setOaiName("test1role"); $this->emptyCollectionRole->setDisplayBrowsing("Name"); $this->emptyCollectionRole->setDisplayFrontdoor("Name"); - $this->emptyCollectionRole->setDisplayOai("Name"); $this->emptyCollectionRole->setPosition(100); $this->emptyCollectionRole->store(); @@ -57,7 +57,6 @@ public function setUp() { $this->nonEmptyCollectionRole->setOaiName("test2role"); $this->nonEmptyCollectionRole->setDisplayBrowsing("Name"); $this->nonEmptyCollectionRole->setDisplayFrontdoor("Name"); - $this->nonEmptyCollectionRole->setDisplayOai("Name"); $this->nonEmptyCollectionRole->setPosition(101); $this->nonEmptyCollectionRole->store(); @@ -65,7 +64,8 @@ public function setUp() { $rootCollection->store(); } - public function tearDown() { + public function tearDown() + { if (!is_null($this->nonEmptyCollectionRole) && !is_null($this->nonEmptyCollectionRole->getId())) { $this->nonEmptyCollectionRole->delete(); } @@ -75,7 +75,8 @@ public function tearDown() { parent::tearDown(); } - public function testIndexAction() { + public function testIndexAction() + { $this->dispatch('/admin/collectionroles'); $this->assertResponseCode(200); $this->assertModule('admin'); @@ -83,7 +84,8 @@ public function testIndexAction() { $this->assertAction('index'); } - public function testIndexActionInvisibleCssClass() { + public function testIndexActionInvisibleCssClass() + { $this->useEnglish(); $this->dispatch('/admin/collectionroles'); @@ -98,7 +100,8 @@ public function testIndexActionInvisibleCssClass() { $this->assertXpathCount('//th[@class="invisible"]/a', 3); // 3 in Testdaten, +2 in setUp } - public function testEditAction() { + public function testEditAction() + { $this->dispatch('/admin/collectionroles/edit/roleid/' . $this->nonEmptyCollectionRole->getId()); $this->assertResponseCode(200); $this->assertModule('admin'); @@ -106,31 +109,36 @@ public function testEditAction() { $this->assertAction('edit'); } - public function testDeleteAction() { + public function testDeleteAction() + { $this->dispatch('/admin/collectionroles/delete/roleid/' . $this->nonEmptyCollectionRole->getId()); $this->assertRedirect(); $this->assertResponseLocationHeader($this->getResponse(), '/admin/collectionroles'); } - public function testDeleteActionWithMissingParam() { + public function testDeleteActionWithMissingParam() + { $this->dispatch('/admin/collectionroles/delete'); $this->assertRedirect(); $this->assertResponseLocationHeader($this->getResponse(), '/admin/collectionroles'); } - public function testMoveAction() { + public function testMoveAction() + { $this->dispatch('/admin/collectionroles/move/pos/1/roleid/' . $this->emptyCollectionRole->getId()); $this->assertRedirect(); $this->assertResponseLocationHeader($this->getResponse(), '/admin/collectionroles'); } - public function testMoveActionWithMissingParam() { + public function testMoveActionWithMissingParam() + { $this->dispatch('/admin/collectionroles/move'); $this->assertRedirect(); $this->assertResponseLocationHeader($this->getResponse(), '/admin/collectionroles'); } - public function testNewAction() { + public function testNewAction() + { $this->dispatch('/admin/collectionroles/new'); $this->assertResponseCode(200); $this->assertModule('admin'); @@ -138,25 +146,29 @@ public function testNewAction() { $this->assertAction('new'); } - public function testHideAction() { + public function testHideAction() + { $this->dispatch('/admin/collectionroles/hide/roleid/' . $this->nonEmptyCollectionRole->getId()); $this->assertRedirect(); $this->assertResponseLocationHeader($this->getResponse(), '/admin/collectionroles'); } - public function testHideActionWithMissingParam() { + public function testHideActionWithMissingParam() + { $this->dispatch('/admin/collectionroles/hide'); $this->assertRedirect(); $this->assertResponseLocationHeader($this->getResponse(), '/admin/collectionroles'); } - public function testUnhideAction() { + public function testUnhideAction() + { $this->dispatch('/admin/collectionroles/unhide/roleid/' . $this->nonEmptyCollectionRole->getId()); $this->assertRedirect(); $this->assertResponseLocationHeader($this->getResponse(), '/admin/collectionroles'); } - public function testUnhideActionWithMissingParam() { + public function testUnhideActionWithMissingParam() + { $this->dispatch('/admin/collectionroles/unhide'); $this->assertRedirect(); $this->assertResponseLocationHeader($this->getResponse(), '/admin/collectionroles'); @@ -165,7 +177,8 @@ public function testUnhideActionWithMissingParam() { /** * Regression Test for OPUSVIER-2638 */ - public function testOPUSVIER2638() { + public function testOPUSVIER2638() + { $this->dispatch('/admin/collectionroles/edit/roleid/' . $this->nonEmptyCollectionRole->getId()); $this->assertResponseCode(200); $this->assertModule('admin'); @@ -177,7 +190,8 @@ public function testOPUSVIER2638() { $this->assertTrue($containsGermanTitle || $containsEnglishTitle); } - public function testRegression3109CollectionRoleAddBreadcrumb() { + public function testRegression3109CollectionRoleAddBreadcrumb() + { $this->useGerman(); $this->dispatch('/admin/collectionroles/new'); @@ -193,7 +207,8 @@ public function testRegression3109CollectionRoleAddBreadcrumb() { $this->assertQueryContentContains('//div.breadcrumbsContainer', 'Eine neue Sammlung anlegen'); } - public function testRegression3109CollectionRoleEditBreadcrumb() { + public function testRegression3109CollectionRoleEditBreadcrumb() + { $this->useGerman(); $this->dispatch('/admin/collectionroles/edit/roleid/2'); @@ -212,8 +227,8 @@ public function testRegression3109CollectionRoleEditBreadcrumb() { /** * Regression Test for OPUSVIER-3051 */ - public function testDocumentServerDateModifiedNotUpdatedWhenCollectionSortOrderChanged() { - + public function testDocumentServerDateModifiedNotUpdatedWhenCollectionSortOrderChanged() + { // check for expected test data $collectionRole1 = new Opus_CollectionRole(1); @@ -241,25 +256,27 @@ public function testDocumentServerDateModifiedNotUpdatedWhenCollectionSortOrderC $this->assertEquals((string) $docBefore->getServerDateModified(), (string) $docAfter->getServerDateModified()); } - public function testCreateActionGetRequest() { + public function testCreateActionGetRequest() + { $this->dispatch('/admin/collectionroles/create'); $this->assertRedirectTo('/admin/collectionroles'); } - public function testCreateAction() { + public function testCreateAction() + { $this->useEnglish(); $roles = Opus_CollectionRole::fetchAll(); $this->assertEquals(22, count($roles)); - $roleIds = array(); + $roleIds = []; foreach ($roles as $role) { $roleIds[] = $role->getId(); } - $post = array( + $post = [ 'Name' => 'CreateTestColName', 'OaiName' => 'CreateTestColOaiName', 'DisplayBrowsing' => 'Name', @@ -270,7 +287,7 @@ public function testCreateAction() { 'VisibleOai' => '0', 'Position' => '20', 'Save' => 'Speichern' - ); + ]; $this->getRequest()->setMethod('POST')->setPost($post); @@ -306,7 +323,8 @@ public function testCreateAction() { self::MESSAGE_LEVEL_NOTICE); } - public function testCreateActionForEdit() { + public function testCreateActionForEdit() + { $this->useEnglish(); $roles = Opus_CollectionRole::fetchAll(); @@ -324,7 +342,7 @@ public function testCreateActionForEdit() { $roleId = $role->store(); - $post = array( + $post = [ 'oid' => $roleId, 'Name' => 'ModifiedName', 'OaiName' => 'ModifiedOaiName', @@ -336,7 +354,7 @@ public function testCreateActionForEdit() { 'VisibleOai' => '1', 'Position' => '19', 'Save' => 'Speichern' - ); + ]; $this->getRequest()->setMethod('POST')->setPost($post); @@ -362,5 +380,4 @@ public function testCreateActionForEdit() { $this->verifyFlashMessage('Collection role \'ModifiedName\' was edited successfully.', self::MESSAGE_LEVEL_NOTICE); } - } diff --git a/tests/modules/admin/models/CollectionRoleTest.php b/tests/modules/admin/models/CollectionRoleTest.php index 14d4efea0..3020c49fe 100644 --- a/tests/modules/admin/models/CollectionRoleTest.php +++ b/tests/modules/admin/models/CollectionRoleTest.php @@ -26,17 +26,18 @@ * * @category Application Unit Tests * @author Jens Schwidder - * @copyright Copyright (c) 2008-2014, OPUS 4 development team + * @copyright Copyright (c) 2008-2018, OPUS 4 development team * @license http://www.gnu.org/licenses/gpl.html General Public License - * @version $Id$ */ -class Admin_Model_CollectionRoleTest extends ControllerTestCase { +class Admin_Model_CollectionRoleTest extends ControllerTestCase +{ private $collectionRoleId; private $moveTestColId = null; - public function setUp() { + public function setUp() + { parent::setUp(); $collectionRole = new Opus_CollectionRole(); @@ -48,13 +49,13 @@ public function setUp() { $collectionRole->setVisibleOai(1); $collectionRole->setDisplayBrowsing('Number'); $collectionRole->setDisplayFrontdoor('Name'); - $collectionRole->setDisplayOai('NumberName'); $collectionRole->setPosition(99); $this->collectionRoleId = $collectionRole->store(); } - public function tearDown() { + public function tearDown() + { $collectionRole = new Opus_CollectionRole($this->collectionRoleId); $collectionRole->delete(); @@ -66,7 +67,8 @@ public function tearDown() { parent::tearDown(); } - public function testConstructModel() { + public function testConstructModel() + { $model = new Admin_Model_CollectionRole($this->collectionRoleId); $collectionRole = $model->getObject(); @@ -74,7 +76,8 @@ public function testConstructModel() { $this->assertEquals($this->collectionRoleId, $collectionRole->getId()); } - public function testConstructModelWithNull() { + public function testConstructModelWithNull() + { $model = new Admin_Model_CollectionRole(); $collectionRole = $model->getObject(); $this->assertEquals(1, $collectionRole->getVisible()); @@ -87,7 +90,8 @@ public function testConstructModelWithNull() { * @expectedException Admin_Model_Exception * @expectedExceptionMessage missing parameter roleid */ - public function testConstructModelWithEmptyParameter() { + public function testConstructModelWithEmptyParameter() + { $model = new Admin_Model_CollectionRole(''); } @@ -95,7 +99,8 @@ public function testConstructModelWithEmptyParameter() { * @expectedException Admin_Model_Exception * @expectedExceptionMessage roleid parameter value unknown */ - public function testConstructModelWithUnknownId() { + public function testConstructModelWithUnknownId() + { $model = new Admin_Model_CollectionRole(2222); } @@ -103,11 +108,13 @@ public function testConstructModelWithUnknownId() { * @expectedException Admin_Model_Exception * @expectedExceptionMessage roleid parameter value unknown */ - public function testContructModelWithBadParameter() { + public function testContructModelWithBadParameter() + { $model = new Admin_Model_CollectionRole('noId'); } - public function testGetObject() { + public function testGetObject() + { $model = new Admin_Model_CollectionRole($this->collectionRoleId); $collectionRole = $model->getObject(); @@ -115,7 +122,8 @@ public function testGetObject() { $this->assertEquals($this->collectionRoleId, $collectionRole->getId()); } - public function testSetVisibilityTrue() { + public function testSetVisibilityTrue() + { $model = new Admin_Model_CollectionRole($this->collectionRoleId); $collectionRole = $model->getObject(); @@ -130,7 +138,8 @@ public function testSetVisibilityTrue() { $this->assertEquals(1, $collectionRole->getVisible()); } - public function testSetVisibilityFalse() { + public function testSetVisibilityFalse() + { $model = new Admin_Model_CollectionRole($this->collectionRoleId); $collectionRole = $model->getObject(); @@ -144,7 +153,8 @@ public function testSetVisibilityFalse() { $this->assertEquals(0, $collectionRole->getVisible()); } - public function testMove() { + public function testMove() + { $colRole = new Opus_CollectionRole(); $colRole->setName('MoveTestColRole-Name'); $colRole->setOaiName('MoveTestColRole-OaiName'); @@ -172,6 +182,4 @@ public function testMove() { $this->assertEquals($this->collectionRoleId, $colRoles[$colRolesCount - 1]->getId()); $this->assertEquals($this->moveTestColId, $colRoles[$colRolesCount - 2]->getId()); } - } - \ No newline at end of file diff --git a/tests/modules/admin/models/CollectionsTest.php b/tests/modules/admin/models/CollectionsTest.php index 8f0f3b539..f7c02d368 100644 --- a/tests/modules/admin/models/CollectionsTest.php +++ b/tests/modules/admin/models/CollectionsTest.php @@ -27,10 +27,11 @@ * @category Tests * @package Admin_Model * @author Jens Schwidder - * @copyright Copyright (c) 2008-2017, OPUS 4 development team + * @copyright Copyright (c) 2008-2018, OPUS 4 development team * @license http://www.gnu.org/licenses/gpl.html General Public License */ -class Admin_Model_CollectionsTest extends ControllerTestCase { +class Admin_Model_CollectionsTest extends ControllerTestCase +{ private $collectionRoleId; @@ -38,7 +39,8 @@ class Admin_Model_CollectionsTest extends ControllerTestCase { private $_docId; - public function setUp() { + public function setUp() + { parent::setUp(); $collectionRole = new Opus_CollectionRole(); @@ -50,7 +52,6 @@ public function setUp() { $collectionRole->setVisibleOai(1); $collectionRole->setDisplayBrowsing('Number'); $collectionRole->setDisplayFrontdoor('Name'); - $collectionRole->setDisplayOai('NumberName'); $collectionRole->setPosition(99); $root = $collectionRole->addRootCollection(); @@ -64,7 +65,8 @@ public function setUp() { $this->_docId = $document->store(); } - public function tearDown() { + public function tearDown() + { $collectionRole = new Opus_CollectionRole($this->collectionRoleId); $collectionRole->delete(); @@ -74,7 +76,8 @@ public function tearDown() { /** * Checks that visible = 1 for visible collection role. */ - public function testGetCollectionRoleInfo() { + public function testGetCollectionRoleInfo() + { $collections = $this->model->getCollectionRolesInfo(); $this->assertNotNull($collections); @@ -103,7 +106,8 @@ public function testGetCollectionRoleInfo() { /** * Checks that hidden collection role has visible = 0. */ - public function testRoleInvisible() { + public function testRoleInvisible() + { $collectionRole = Opus_CollectionRole::fetchByName('TestCollectionRole-Name'); $collectionRole->setVisible(0); $collectionRole->store(); @@ -179,7 +183,5 @@ public function testCollectionRolesInfoForAssigned() $this->assertFalse($collection['assigned']); } } - } - } diff --git a/tests/modules/publish/models/ValidationTest.php b/tests/modules/publish/models/ValidationTest.php index f429e55da..19544b731 100644 --- a/tests/modules/publish/models/ValidationTest.php +++ b/tests/modules/publish/models/ValidationTest.php @@ -1,5 +1,4 @@ - * @copyright Copyright (c) 2008-2011, OPUS 4 development team + * @copyright Copyright (c) 2008-2018, OPUS 4 development team * @license http://www.gnu.org/licenses/gpl.html General Public License - * @version $Id$ */ -class Publish_Model_ValidationTest extends ControllerTestCase{ +class Publish_Model_ValidationTest extends ControllerTestCase +{ private $session; - public function setUp() { + public function setUp() + { parent::setUp(); $this->session = new Zend_Session_Namespace(); } - public function testValidationWithInvalidDatatype() { + public function testValidationWithInvalidDatatype() + { $val = new Publish_Model_Validation('Irgendwas', $this->session); $val->validate(); $this->assertInternalType('array', $val->validator); } - public function testValidationWithCollectionWithoutCollectionRole() { + public function testValidationWithCollectionWithoutCollectionRole() + { $val = new Publish_Model_Validation('Collection', $this->session); $val->validate(); $validator = $val->validator[0]; $this->assertNull($validator); - } - public function testValidationWithDateDatatype() { + public function testValidationWithDateDatatype() + { $val = new Publish_Model_Validation('Date', $this->session); $val->validate(); $validator = $val->validator[0]; $this->assertInstanceOf('Zend_Validate_Date', $validator); - } - public function testValidationWithEmailDatatype() { + public function testValidationWithEmailDatatype() + { $val = new Publish_Model_Validation('Email', $this->session); $val->validate(); $validator = $val->validator[0]; $this->assertInstanceOf('Zend_Validate_EmailAddress', $validator); - } - public function testValidationWithEnrichmentDatatype() { + /** + * TODO fix unused variable - What is this test doing? + */ + public function testValidationWithEnrichmentDatatype() + { $val = new Publish_Model_Validation('Enrichment', $this->session); $val->validate(); $validator = $val->validator[0]; $this->assertNull($val->validator); - } - public function testValidationWithIntegerDatatype() { + public function testValidationWithIntegerDatatype() + { $val = new Publish_Model_Validation('Integer', $this->session); $val->validate(); $validator = $val->validator[0]; $this->assertInstanceOf('Zend_Validate_Int', $validator); - } - public function testValidationWithLanguageDatatype() { + public function testValidationWithLanguageDatatype() + { $val = new Publish_Model_Validation('Language', $this->session); $val->validate(); $validator = $val->validator[0]; @@ -102,7 +107,8 @@ public function testValidationWithLanguageDatatype() { $this->assertInstanceOf('Zend_Validate_InArray', $validator); } - public function testValidationWithLicenceDatatype() { + public function testValidationWithLicenceDatatype() + { $val = new Publish_Model_Validation('Licence', $this->session); $val->validate(); $validator = $val->validator[0]; @@ -110,8 +116,9 @@ public function testValidationWithLicenceDatatype() { $this->assertInstanceOf('Zend_Validate_InArray', $validator); } - public function testValidationWithListDatatype() { - $options = array(); + public function testValidationWithListDatatype() + { + $options = []; $options['eins'] = 'eins'; $options['zwei'] = 'zwei'; @@ -122,14 +129,16 @@ public function testValidationWithListDatatype() { $this->assertInstanceOf('Zend_Validate_InArray', $validator); } - public function testValidationWithTextDatatype() { + public function testValidationWithTextDatatype() + { $val = new Publish_Model_Validation('Text', $this->session); $val->validate(); $this->assertNull($val->validator); } - public function testValidationWithThesisGrantorDatatype() { + public function testValidationWithThesisGrantorDatatype() + { $val = new Publish_Model_Validation('ThesisGrantor', $this->session); $val->validate(); $validator = $val->validator[0]; @@ -137,7 +146,8 @@ public function testValidationWithThesisGrantorDatatype() { $this->assertInstanceOf('Zend_Validate_InArray', $validator); } - public function testValidationWithThesisPublisherDatatype() { + public function testValidationWithThesisPublisherDatatype() + { $val = new Publish_Model_Validation('ThesisPublisher', $this->session); $val->validate(); $validator = $val->validator[0]; @@ -145,14 +155,16 @@ public function testValidationWithThesisPublisherDatatype() { $this->assertInstanceOf('Zend_Validate_InArray', $validator); } - public function testValidationWithTitleDatatype() { + public function testValidationWithTitleDatatype() + { $val = new Publish_Model_Validation('Title', $this->session); $val->validate(); $this->assertNull($val->validator); } - public function testValidationWithYearDatatype() { + public function testValidationWithYearDatatype() + { $val = new Publish_Model_Validation('Year', $this->session); $val->validate(); $validator = $val->validator[0]; @@ -160,31 +172,32 @@ public function testValidationWithYearDatatype() { $this->assertInstanceOf('Zend_Validate_GreaterThan', $validator); } - public function testSelectOptionsForInvalidDatatype() { + public function testSelectOptionsForInvalidDatatype() + { $val = new Publish_Model_Validation('Irgendwas', $this->session); $children = $val->selectOptions(); $this->assertInternalType('array', $val->validator); - } - public function testSelectOptionsForCollection() { + public function testSelectOptionsForCollection() + { $val = new Publish_Model_Validation('Collection', $this->session, 'jel'); $children = $val->selectOptions('Collection'); $this->assertArrayHasKey('6720', $children); - } - public function testSelectOptionsForLanguage() { + public function testSelectOptionsForLanguage() + { $val = new Publish_Model_Validation('Language', $this->session); $children = $val->selectOptions(); $this->assertArrayHasKey('deu', $children); - } - public function testSelectOptionsForLicence() { + public function testSelectOptionsForLicence() + { $val = new Publish_Model_Validation('Licence', $this->session); $children = $val->selectOptions(); @@ -195,10 +208,11 @@ public function testSelectOptionsForLicence() { * Tests that the sort order of the licences in the publish form matches * the sort order provided from the database. */ - public function testSortOrderOfSelectOptionForLicence() { + public function testSortOrderOfSelectOptionForLicence() + { $licences = Opus_Licence::getAll(); - $activeLicences = array(); + $activeLicences = []; foreach($licences as $licence) { if ($licence->getActive() == '1') { @@ -219,8 +233,9 @@ public function testSortOrderOfSelectOptionForLicence() { } } - public function testSelectOptionsForList() { - $options = array(); + public function testSelectOptionsForList() + { + $options = []; $options['eins'] = 'eins'; $options['zwei'] = 'zwei'; @@ -230,89 +245,94 @@ public function testSelectOptionsForList() { $this->assertArrayHasKey('eins', $children); } - public function testSelectOptionsForThesisGrantor() { + public function testSelectOptionsForThesisGrantor() + { $val = new Publish_Model_Validation('ThesisGrantor', $this->session); $children = $val->selectOptions(); $this->assertArrayHasKey('1', $children); - } - public function testSelectOptionsForThesisPublisher() { + public function testSelectOptionsForThesisPublisher() + { $val = new Publish_Model_Validation('ThesisPublisher', $this->session); $children = $val->selectOptions(); $this->assertArrayHasKey('2', $children); - } - - public function testInvisibleCollectionRoleDDC() { + + public function testInvisibleCollectionRoleDDC() + { $val = new Publish_Model_Validation('Collection', $this->session, 'ddc'); - + $collectionRole = Opus_CollectionRole::fetchByName($val->collectionRole); $visibleFlag = $collectionRole->getVisible(); $collectionRole->setVisible(0); $collectionRole->store(); - - $children = $val->selectOptions('Collection'); + + $children = $val->selectOptions('Collection'); $this->assertNull($children); - + $collectionRole->setVisible($visibleFlag); $collectionRole->store(); - } - - public function testVisibleCollectionRoleDDC() { + + public function testVisibleCollectionRoleDDC() + { $val = new Publish_Model_Validation('Collection', $this->session, 'ddc'); - + $collectionRole = Opus_CollectionRole::fetchByName($val->collectionRole); $visibleFlag = $collectionRole->getVisible(); $collectionRole->setVisible(1); $collectionRole->store(); - - $children = $val->selectOptions('Collection'); - $this->assertInternalType('array', $children); + + $children = $val->selectOptions('Collection'); + $this->assertInternalType('array', $children); $this->assertArrayHasKey('3', $children); - + $collectionRole->setVisible($visibleFlag); $collectionRole->store(); } - + /** - * Regression Test for Ticket https://wiki.kobv.de/jira/browse/OPUSVIER-2209 - */ - public function testNonExistingCollectionRole() { + * Regression Test for Ticket https://wiki.kobv.de/jira/browse/OPUSVIER-2209 + */ + public function testNonExistingCollectionRole() + { $collRole = 'irgendwas'; $val = new Publish_Model_Validation('Collection', $this->session, $collRole); - + $this->assertNull($val->selectOptions()); } - - public function testVisibleSeries() { + + public function testVisibleSeries() + { $val = new Publish_Model_Validation('Series', $this->session); - - $children = $val->selectOptions('Series'); - $this->assertInternalType('array', $children); + + $children = $val->selectOptions('Series'); + $this->assertInternalType('array', $children); $this->assertArrayHasKey('4', $children); - //series with title: Visible Series + //series with title: Visible Series } - - public function testInvisibleSeries() { + + public function testInvisibleSeries() + { $val = new Publish_Model_Validation('Series', $this->session); - - $children = $val->selectOptions('Series'); - $this->assertInternalType('array', $children); + + $children = $val->selectOptions('Series'); + $this->assertInternalType('array', $children); $this->assertArrayNotHasKey('3', $children); - //series with title: Invisible Series + //series with title: Invisible Series } - - public function testSortOrderOfSeries() { + + public function testSortOrderOfSeries() + { $val = new Publish_Model_Validation('Series', $this->session); $values = $val->selectOptions(); - + $series = Opus_Series::getAllSortedBySortKey(); - $visibleSeries = array(); + $visibleSeries = []; foreach($series as $serie) { if ($serie->getVisible() == '1') { @@ -327,19 +347,18 @@ public function testSortOrderOfSeries() { $this->assertEquals($name, $visibleSeries[$index]); $index++; } - } /** * Testet, ob eine Collection, bei der visiblePublish=false gesetzt ist, im Publish-Modul ausgegeben wird. */ - public function testCollectionFieldVisiblePublish() { + public function testCollectionFieldVisiblePublish() + { $collectionRole = new Opus_CollectionRole(); $collectionRole->setName("test"); $collectionRole->setOaiName("test"); $collectionRole->setDisplayBrowsing("Name"); $collectionRole->setDisplayFrontdoor("Name"); - $collectionRole->setDisplayOai("Name"); $collectionRole->setPosition(101); $collectionRole->setVisible(true); $collectionRole->store(); @@ -385,13 +404,13 @@ public function testCollectionFieldVisiblePublish() { * Wenn eine übergeordnete Collection (z.B. die Root-Collection) für das Attribut visiblePublish = false gesetzt ist, * sollen die Kinder auch unsichtbar sein im Publish-Modul. */ - public function testRootCollectionFieldVisiblePublish() { + public function testRootCollectionFieldVisiblePublish() + { $collectionRole = new Opus_CollectionRole(); $collectionRole->setName("test"); $collectionRole->setOaiName("test"); $collectionRole->setDisplayBrowsing("Name"); $collectionRole->setDisplayFrontdoor("Name"); - $collectionRole->setDisplayOai("Name"); $collectionRole->setPosition(101); $collectionRole->setVisible(true); $collectionRole->store(); @@ -434,6 +453,4 @@ public function testRootCollectionFieldVisiblePublish() { $this->assertEquals(0, count($children), "root collection should be invisible in publish"); } - } - From a7abcf995063385e078760b5cd5cb272c942c85d Mon Sep 17 00:00:00 2001 From: j3nsch Date: Fri, 12 Oct 2018 13:55:28 +0200 Subject: [PATCH 070/128] OPUSVIER-3945 Added permission for DOI notifications. --- library/Application/Security/AclProvider.php | 61 ++++++++++++-------- modules/admin/language/resources.tmx | 15 ++++- 2 files changed, 50 insertions(+), 26 deletions(-) diff --git a/library/Application/Security/AclProvider.php b/library/Application/Security/AclProvider.php index daf1001b6..d1e88cc9b 100644 --- a/library/Application/Security/AclProvider.php +++ b/library/Application/Security/AclProvider.php @@ -27,9 +27,8 @@ * @category Application * @package Application_Security * @author Jens Schwidder - * @copyright Copyright (c) 2008-2010, OPUS 4 development team + * @copyright Copyright (c) 2008-2018, OPUS 4 development team * @license http://www.gnu.org/licenses/gpl.html General Public License - * @version $Id$ */ /** @@ -39,7 +38,8 @@ * Konfigurationsdatei gibt. Diese wird gegebenenfalls geladen und für die Konstruktion der ACLs verwendet. * Gibt es keine Datei hat der Nutzer keine Einschränkungen beim Zugriff. */ -class Application_Security_AclProvider { +class Application_Security_AclProvider +{ /** * Name der Role, die für ACL Prüfungen verwendet wird. @@ -55,8 +55,8 @@ class Application_Security_AclProvider { * * TODO resources should be declared in modules and controllers (decentralising) */ - public static $resourceNames = array( - 'admin' => array( + public static $resourceNames = [ + 'admin' => [ 'documents', 'accounts', 'security', @@ -71,16 +71,23 @@ class Application_Security_AclProvider { 'indexmaintenance', 'job', 'options', - 'persons'), - 'review' => array( - 'reviewing'), - 'setup' => array( + 'persons' + ], + 'review' => [ + 'reviewing' + ], + 'setup' => [ 'helppages', 'staticpages', - 'translations') - ); - - public static function init() { + 'translations' + ], + 'doi' => [ + 'doi_notification' + ] + ]; + + public static function init() + { $aclProvider = new Application_Security_AclProvider(); $acl = $aclProvider->getAcls(); @@ -98,7 +105,8 @@ public static function init() { /** Zend_Debug::dump * Liefert ein Zend_Acl Objekt für den aktuellen Nutzer zurück. */ - public function getAcls() { + public function getAcls() + { $logger = $this->getLogger(); $acl = new Zend_Acl(); @@ -130,7 +138,9 @@ public function getAcls() { // create role for user on-the-fly with assigned roles as parents if (Zend_Registry::get('LOG_LEVEL') >= Zend_LOG::DEBUG) { - $logger->debug("ACL: Create role '" . $user . "' with parents " . "(" . implode(", ", $parents) . ")"); + $logger->debug( + "ACL: Create role '" . $user . "' with parents " . "(" . implode(", ", $parents) . ")" + ); } // Add role for current user @@ -142,7 +152,8 @@ public function getAcls() { /** * Erzeugt die notwendigen Zend_Acl_Resource Objekte. */ - public function loadResources($acl) { + public function loadResources($acl) + { $modules = Application_Security_AclProvider::$resourceNames; foreach ($modules as $module => $resources) { @@ -155,7 +166,8 @@ public function loadResources($acl) { $this->loadWorkflowResources($acl); } - public function loadWorkflowResources($acl) { + public function loadWorkflowResources($acl) + { $resources = Application_Controller_Action_Helper_Workflow::getWorkflowResources(); $acl->addResource(new Zend_Acl_Resource('workflow')); @@ -165,10 +177,11 @@ public function loadWorkflowResources($acl) { } } - public function getAllResources() { + public function getAllResources() + { $modules = Application_Security_AclProvider::$resourceNames; - $allResources = array(); + $allResources = []; foreach ($modules as $resources) { $allResources = array_merge($allResources, $resources); @@ -182,7 +195,8 @@ public function getAllResources() { * * TODO load from database and from configuration files */ - public function loadRoles($acl, $roles) { + public function loadRoles($acl, $roles) + { // Feste Rollen, die immer existieren $acl->addRole(new Zend_Acl_Role('guest')); $acl->addRole(new Zend_Acl_Role('administrator')); @@ -200,15 +214,16 @@ public function loadRoles($acl, $roles) { } } - public function getLogger() { + public function getLogger() + { if (is_null($this->_logger)) { $this->_logger = Zend_Registry::get('Zend_Log'); } return $this->_logger; } - public function setLogger($logger) { + public function setLogger($logger) + { $this->_logger = $logger; } - } diff --git a/modules/admin/language/resources.tmx b/modules/admin/language/resources.tmx index 547256a3e..d2edd47f6 100644 --- a/modules/admin/language/resources.tmx +++ b/modules/admin/language/resources.tmx @@ -42,7 +42,7 @@ Sprachen verwalten - + Manage licences @@ -159,7 +159,7 @@ FAQ-Seiten verwalten - + Manage Static Pages @@ -186,7 +186,7 @@ Personenverwaltung - + Settings @@ -196,6 +196,15 @@ + + + DOI Notifications + + + DOI Benachrichtigungen + + + \ No newline at end of file From e37bb679d7770fea3127f401b83f8548b766a3b9 Mon Sep 17 00:00:00 2001 From: j3nsch Date: Fri, 12 Oct 2018 13:59:55 +0200 Subject: [PATCH 071/128] OPUSVIER-3945 Updated presentation of access control page. --- .../views/scripts/access/listmodule.phtml | 21 +++++++------- public/layouts/opus4/css/admin.css | 29 ++++++++++++++++++- 2 files changed, 39 insertions(+), 11 deletions(-) diff --git a/modules/admin/views/scripts/access/listmodule.phtml b/modules/admin/views/scripts/access/listmodule.phtml index 31ac1c187..c80c7f909 100644 --- a/modules/admin/views/scripts/access/listmodule.phtml +++ b/modules/admin/views/scripts/access/listmodule.phtml @@ -34,6 +34,7 @@ */ // TODO move some of the processing into model or controller +// TODO do this as a Zend_Form ?>

translate('access_select_module', $this->roleName) ?>

@@ -52,8 +53,8 @@

translate('access_module_changes') ?>

- -
    + +
      allModules as $module) : ?>
    • @@ -67,11 +68,11 @@
    - +

    translate('access_resource_changes') ?>

    - -
      + +
        allResources as $resource) : ?>
      • @@ -85,22 +86,22 @@
      - +

      translate('access_workflow_changes') ?>

      - -
        + +
          allWorkflow as $resource) : ?>
        • modules) ? ' checked="checked" ' : '' ?> - /> + /> translate('Opus_Document_ServerState_Value_' . ucfirst($states[1]) ); ?> translate('Opus_Document_ServerState_Value_' . ucfirst($states[2])); ?> - translate('acl_resource_workflow_generic', array($state, $targetState)); ?> + translate('acl_resource_workflow_generic', array($state, $targetState)); ?> guestModules) && in_array($resource, $this->guestModules)) : ?> translate('admin_access_checked_in_guest'); ?> diff --git a/public/layouts/opus4/css/admin.css b/public/layouts/opus4/css/admin.css index 5f121ba64..080763ec8 100644 --- a/public/layouts/opus4/css/admin.css +++ b/public/layouts/opus4/css/admin.css @@ -2353,4 +2353,31 @@ form.persons-confirm legend { width: 4%; background-color: transparent; border-bottom: none; -} \ No newline at end of file +} + +ul.permissions-list { + list-style: none; + padding: 0.5em 1em; +} + +ul.permissions-list li { + margin: 0; + padding: 0.2em 0.5em; +} + +ul.permissions-list li:nth-child(even) { + background: #f5f5f5; +} + +.admin_access_listmodule h2 { + color: #26517c; + font-weight: bold; + margin-top: 2em; + margin-bottom: 0.5em; + padding: 0; + border-bottom: 1px solid #26517c; +} + +ul.permissions-list input[type=checkbox] { + margin-right: 1em; +} From de2caac60be332f671d18a5f0d30e3e61852ef7e Mon Sep 17 00:00:00 2001 From: j3nsch Date: Fri, 12 Oct 2018 18:21:23 +0200 Subject: [PATCH 072/128] OPUSVIER-3945 Moved some code out of controller. --- .../admin/controllers/AccessController.php | 84 +++++++------------ modules/admin/models/AccessManager.php | 63 ++++++++++++++ 2 files changed, 93 insertions(+), 54 deletions(-) create mode 100644 modules/admin/models/AccessManager.php diff --git a/modules/admin/controllers/AccessController.php b/modules/admin/controllers/AccessController.php index 6d3b0ded6..c26d231be 100644 --- a/modules/admin/controllers/AccessController.php +++ b/modules/admin/controllers/AccessController.php @@ -29,9 +29,8 @@ * @package Module_Admin * @author Julian Heise * @author Jens Schwidder - * @copyright Copyright (c) 2008-2012, OPUS 4 development team + * @copyright Copyright (c) 2008-2018, OPUS 4 development team * @license http://www.gnu.org/licenses/gpl.html General Public License - * @version $Id$ */ /** @@ -39,12 +38,14 @@ * * */ -class Admin_AccessController extends Application_Controller_Action { +class Admin_AccessController extends Application_Controller_Action +{ /** * */ - public function listroleAction() { + public function listroleAction() + { $id = $this->getRequest()->getParam('docid'); $roles = Opus_UserRole::getAll(); $this->view->docId = $id; @@ -59,8 +60,9 @@ public function listroleAction() { * @param type $roles * @return array */ - private function getCheckedRoles($id, $roles) { - $items = array(); + private function getCheckedRoles($id, $roles) + { + $items = []; foreach ($roles as $role) { $docs = $role->listAccessDocuments(); @@ -71,15 +73,17 @@ private function getCheckedRoles($id, $roles) { return $items; } - /** * Action for showing list of modules and permissions. * * @throws Exception */ - public function listmoduleAction() { + public function listmoduleAction() + { + $security = new Admin_Model_AccessManager(); $id = $this->getRequest()->getParam('roleid'); + if ($id == null) { throw new Exception('Role ID missing'); } @@ -103,43 +107,44 @@ public function listmoduleAction() { } } - $transitions = Application_Controller_Action_Helper_Workflow::getWorkflowResources(); + $transitions = $security->getWorkflowResources(); $this->view->loginNames = $role->getAllAccountNames(); + $this->view->roleId = $role->getId(); $this->view->roleName = $role->getName(); $this->view->modules = $roleModules; + $this->view->allModules = array_keys(Application_Modules::getInstance()->getModules()); - $this->view->allResources = $this->getAllResources(); + $this->view->allResources = $security->getAllResources(); $this->view->allWorkflow = $transitions; } /** * Action for saving selected permissions for role. - * */ - public function storeAction() { + public function storeAction() + { $save = $this->getRequest()->getParam('save_button'); $id = $this->getRequest()->getParam('roleid'); $docId = $this->getRequest()->getParam('docid'); + if (!empty($id)) { $accessMode = $this->getRequest()->getParam('access_mode'); $this->storeModules($this->getRequest()); - $this->view->redirect = array('module'=>'admin','controller'=>'role','action'=>'show','id'=>$id); - } - elseif (!empty($docId)) { + $this->view->redirect = ['module'=>'admin','controller'=>'role','action'=>'show','id'=>$id]; + } elseif (!empty($docId)) { $this->storeRoles($this->getRequest()); - $this->view->redirect = array('module'=>'admin','controller'=>'document','action'=>'index','id'=>$docId); + $this->view->redirect = ['module'=>'admin','controller'=>'document','action'=>'index','id'=>$docId]; } if ($save != null) { $this->view->submit = 'access_submit_save'; $this->view->message = 'access_save_message'; - } - else { + } else { $this->view->submit = 'access_submit_cancel'; $this->view->message = 'access_cancel_message'; } @@ -152,7 +157,8 @@ public function storeAction() { * * TODO secure against missing parameters */ - private function storeModules($request) { + private function storeModules($request) + { $id = $request->getParam('roleid'); $role = new Opus_UserRole($id); @@ -167,7 +173,8 @@ private function storeModules($request) { $params = $request->getParams(); foreach ($params as $name=>$value) { - if ($this->string_begins_with($name, 'set_')) { + $startsWith = 'set_'; + if (substr($name, 0, strlen($startsWith)) === $startsWith) { $module = explode("_", $name, 2); $module = $module[1]; $role->appendAccessModule($module); @@ -184,7 +191,8 @@ private function storeModules($request) { * * TODO Is it a problem if document is append twice? */ - private function storeRoles($request) { + private function storeRoles($request) + { $docId = $request->getParam('docid'); $roles = Opus_UserRole::getAll(); @@ -202,37 +210,5 @@ private function storeRoles($request) { } } } - - /** - * Checks whether a given string has the supplied prefix. - * - * @param $string - * @param $prefix - * @return boolean - */ - private function string_begins_with($string, $prefix) { - return (strncmp($string, $prefix, strlen($prefix)) == 0); - } - - /** - * Liefert Liste mit Ressourcen für die Rechteverwaltung. - * - * Ressourcen für die Rechte vergeben können. Module und Workflow-Übergänge werden separat behandelt. - * - * @return array of strings - */ - private function getAllResources() { - $allResources = array(); - - $aclProvider = new Application_Security_AclProvider(); - - $resources = $aclProvider->getAllResources(); - - foreach ($resources as $resource) { - $allResources[] = 'resource_' . $resource; - } - - return $allResources; - } - } + diff --git a/modules/admin/models/AccessManager.php b/modules/admin/models/AccessManager.php new file mode 100644 index 000000000..8585ffa49 --- /dev/null +++ b/modules/admin/models/AccessManager.php @@ -0,0 +1,63 @@ + + * @copyright Copyright (c) 2018, OPUS 4 development team + * @license http://www.gnu.org/licenses/gpl.html General Public License + */ + +class Admin_Model_AccessManager extends Application_Model_Abstract +{ + + /** + * Liefert Liste mit Ressourcen für die Rechteverwaltung. + * + * Ressourcen für die Rechte vergeben können. Module und Workflow-Übergänge werden separat behandelt. + * + * @return array of strings + */ + public function getAllResources() + { + $allResources = []; + + $aclProvider = new Application_Security_AclProvider(); + + $resources = $aclProvider->getAllResources(); + + foreach ($resources as $resource) { + $allResources[] = 'resource_' . $resource; + } + + return $allResources; + } + + public function getWorkflowResources() + { + return Application_Controller_Action_Helper_Workflow::getWorkflowResources(); + } +} From 27bb847449a88fc730f6145714e599e6527e9fa2 Mon Sep 17 00:00:00 2001 From: j3nsch Date: Fri, 12 Oct 2018 18:21:47 +0200 Subject: [PATCH 073/128] OPUSVIER-3945 Coding style. --- .../Action/Helper/AccessControl.php | 19 +++++++++++-------- .../Application/Security/AccessControl.php | 9 ++++----- modules/admin/controllers/RoleController.php | 7 ++++--- 3 files changed, 19 insertions(+), 16 deletions(-) diff --git a/library/Application/Controller/Action/Helper/AccessControl.php b/library/Application/Controller/Action/Helper/AccessControl.php index 5b5a6eadb..328d23a64 100644 --- a/library/Application/Controller/Action/Helper/AccessControl.php +++ b/library/Application/Controller/Action/Helper/AccessControl.php @@ -27,9 +27,8 @@ * @category Application * @package Controller_Helper * @author Jens Schwidder - * @copyright Copyright (c) 2008-2013, OPUS 4 development team + * @copyright Copyright (c) 2008-2018, OPUS 4 development team * @license http://www.gnu.org/licenses/gpl.html General Public License - * @version $Id$ */ /** @@ -40,11 +39,13 @@ * TODO weiter ausbauen und mit Opus_Security_IRealm konsolidieren (Framework vs. Application Security) */ class Application_Controller_Action_Helper_AccessControl extends Zend_Controller_Action_Helper_Abstract - implements Application_Security_AccessControl { + implements Application_Security_AccessControl +{ private $_acl; - public function direct($resource) { + public function direct($resource) + { return $this->accessAllowed($resource); } @@ -59,7 +60,8 @@ public function direct($resource) { * @param $resource * @return bool */ - public function accessAllowed($resource) { + public function accessAllowed($resource) + { $acl = $this->getAcl(); if (strlen(trim($resource)) == 0) { @@ -78,15 +80,16 @@ public function accessAllowed($resource) { * Returns the Zend_Acl object or null. * @return Zend_Acl */ - protected function getAcl() { + protected function getAcl() + { if (is_null($this->_acl)) { $this->_acl = Zend_Registry::isRegistered('Opus_Acl') ? Zend_Registry::get('Opus_Acl') : null; } return $this->_acl; } - public function setAcl($acl) { + public function setAcl($acl) + { $this->_acl = $acl; } - } diff --git a/library/Application/Security/AccessControl.php b/library/Application/Security/AccessControl.php index f8ef74ee8..4bd06e732 100644 --- a/library/Application/Security/AccessControl.php +++ b/library/Application/Security/AccessControl.php @@ -27,14 +27,13 @@ * @category Application * @package Application_Security * @author Jens Schwidder - * @copyright Copyright (c) 2008-2013, OPUS 4 development team + * @copyright Copyright (c) 2008-2018, OPUS 4 development team * @license http://www.gnu.org/licenses/gpl.html General Public License - * @version $Id$ */ -interface Application_Security_AccessControl { +interface Application_Security_AccessControl +{ public function accessAllowed($resource); - -} \ No newline at end of file +} diff --git a/modules/admin/controllers/RoleController.php b/modules/admin/controllers/RoleController.php index 55d40fdd0..1cfa0f53d 100644 --- a/modules/admin/controllers/RoleController.php +++ b/modules/admin/controllers/RoleController.php @@ -28,12 +28,13 @@ * @category Application * @package Module_Admin * @author Felix Ostrowski - * @copyright Copyright (c) 2008, OPUS 4 development team + * @author Jens Schwidder + * @copyright Copyright (c) 2008-2018, OPUS 4 development team * @license http://www.gnu.org/licenses/gpl.html General Public License - * @version $Id$ */ -class Admin_RoleController extends Application_Controller_Action { +class Admin_RoleController extends Application_Controller_Action +{ private static $_protectedRoles = array('guest', 'administrator'); From a34bb22338e65b1b00e72e3b2b3817063b08c2ff Mon Sep 17 00:00:00 2001 From: j3nsch Date: Mon, 15 Oct 2018 14:07:17 +0200 Subject: [PATCH 074/128] OPUSVIER-3541 Moved state change form code out of controller into class. --- .../admin/controllers/WorkflowController.php | 150 ++++------------- modules/admin/forms/DocumentStateChange.php | 157 ++++++++++++++++++ 2 files changed, 193 insertions(+), 114 deletions(-) create mode 100644 modules/admin/forms/DocumentStateChange.php diff --git a/modules/admin/controllers/WorkflowController.php b/modules/admin/controllers/WorkflowController.php index 890b3ed0c..d812fcfc1 100644 --- a/modules/admin/controllers/WorkflowController.php +++ b/modules/admin/controllers/WorkflowController.php @@ -30,13 +30,13 @@ * @author Sascha Szott * @copyright Copyright (c) 2008-2012, OPUS 4 development team * @license http://www.gnu.org/licenses/gpl.html General Public License - * @version $Id$ */ /** * Controller handles transitions of documents between states. */ -class Admin_WorkflowController extends Application_Controller_Action { +class Admin_WorkflowController extends Application_Controller_Action +{ /** * Helper for verifying document IDs. @@ -55,8 +55,10 @@ class Admin_WorkflowController extends Application_Controller_Action { /** * Initializes controller. */ - public function init() { + public function init() + { parent::init(); + $this->_documentsHelper = $this->_helper->getHelper('Documents'); $this->_workflowHelper = $this->_helper->getHelper('Workflow'); @@ -64,8 +66,7 @@ public function init() { if (isset($config->confirmation->document->statechange->enabled)) { $this->_confirmChanges = ($config->confirmation->document->statechange->enabled == 1) ? true : false; - } - else { + } else { $this->_confirmChanges = true; } } @@ -73,7 +74,8 @@ public function init() { /** * Switches the status of a document to target state. */ - public function changestateAction() { + public function changestateAction() + { $docId = $this->getRequest()->getParam('docId'); $targetState = $this->getRequest()->getParam('targetState'); @@ -82,27 +84,27 @@ public function changestateAction() { // Check if document identifier is valid if (!isset($document)) { return $this->_helper->Redirector->redirectTo( - 'index', array('failure' => $this->view->translate( + 'index', ['failure' => $this->view->translate( 'admin_document_error_novalidid' - )), 'documents', 'admin' + )], 'documents', 'admin' ); } // Check if valid target state if (!$this->_workflowHelper->isValidState($targetState)) { return $this->_helper->Redirector->redirectTo( - 'index', array('failure' => $this->view->translate( + 'index', ['failure' => $this->view->translate( 'admin_workflow_error_invalidstate' - )), 'document', 'admin', array('id' => $docId) + )], 'document', 'admin', ['id' => $docId] ); } // Check if allowed target state if (!$this->_workflowHelper->isTransitionAllowed($document, $targetState)) { return $this->_helper->Redirector->redirectTo( - 'index', array('failure' => $this->view->translate( + 'index', ['failure' => $this->view->translate( 'admin_workflow_error_illegal_transition', $targetState - )), 'document', 'admin', array('id' => $docId) + )], 'document', 'admin', ['id' => $docId] ); } @@ -114,8 +116,8 @@ public function changestateAction() { $key = 'admin_workflow_error_alreadyinstate'; } return $this->_helper->Redirector->redirectTo( - 'index', array('failure' => $this->view->translate($key, $targetState)), - 'document', 'admin', array('id' => $docId) + 'index', ['failure' => $this->view->translate($key, $targetState)], + 'document', 'admin', ['id' => $docId] ); } @@ -127,7 +129,7 @@ public function changestateAction() { return $this->_changeState($document, $targetState, $form); } return $this->_helper->Redirector->redirectTo( - 'index', null, 'document', 'admin', array('id' => $docId) + 'index', null, 'document', 'admin', ['id' => $docId] ); } @@ -136,13 +138,13 @@ public function changestateAction() { $this->view->title = $this->view->translate('admin_workflow_' . $targetState); $this->view->text = $this->view->translate('admin_workflow_' . $targetState . '_sure', $docId); $this->view->form = $this->_getConfirmationForm($document, $targetState); - } - else { + } else { return $this->_changeState($document, $targetState); } } - private function _changeState($document, $targetState, $form = null) { + private function _changeState($document, $targetState, $form = null) + { try { $this->_workflowHelper->changeState($document, $targetState); @@ -152,7 +154,7 @@ private function _changeState($document, $targetState, $form = null) { } catch (Exception $e) { return $this->_helper->Redirector->redirectTo( - 'index', array('failure' => $e->getMessage()), 'documents', 'admin' + 'index', ['failure' => $e->getMessage()], 'documents', 'admin' ); } @@ -166,24 +168,24 @@ private function _changeState($document, $targetState, $form = null) { return $this->_helper->Redirector->redirectTo('index', $message, 'documents', 'admin'); } return $this->_helper->Redirector->redirectTo( - 'index', $message, 'document', 'admin', array('id' => $document->getId()) + 'index', $message, 'document', 'admin', ['id' => $document->getId()] ); } - private function _sendNotification($document, $form = null) { + private function _sendNotification($document, $form = null) + { $notification = new Application_Util_Notification(); - $url = $this->view->url( - array( + $url = $this->view->url([ "module" => "frontdoor", "controller" => "index", "action" => "index", "docId" => $document->getId() - ), + ], null, true ); - $authorsBitmask = array(); + $authorsBitmask = []; $notifySubmitter = true; if (!is_null($form)) { @@ -212,97 +214,17 @@ private function _sendNotification($document, $form = null) { * @param string $action Target action that needs to be confirmed * @return Admin_Form_YesNoForm */ - private function _getConfirmationForm($document, $targetState) { - $form = new Admin_Form_YesNoForm(); - $form->setAction( - $this->view->url( - array('controller' => 'workflow', 'action' => 'changestate', 'targetState' => $targetState) - ) - ); - $form->setMethod('post'); - - $idElement = new Zend_Form_Element_Hidden('id'); - $idElement->setValue($document->getId()); - $form->addElement($idElement); - - $config = Zend_Registry::get('Zend_Config'); - if ($targetState == 'published' && isset($config->notification->document->published->enabled) - && $config->notification->document->published->enabled == 1) { - $this->_addPublishNotificationSelection($document, $form); - } - return $form; - } + private function _getConfirmationForm($document, $targetState) + { + $form = new Admin_Form_DocumentStateChange($targetState); - /** - * add a checkbox for each PersonSubmitter and PersonAuthor (used to select - * recipients for publish notification email) - * - * @param Opus_Document $document - * @param Zend_Form $form - * - */ - private function _addPublishNotificationSelection($document, $form) { - $form->addElement( - 'hidden', 'plaintext', - array( - 'description' => '

          ' . $this->view->translate('admin_workflow_notification_headline') - . '

          ' - . '

          ' . $this->view->translate('admin_workflow_notification_description') . '

          ', - 'ignore' => true, - 'decorators' => array(array('Description', array('escape' => false, 'tag' => ''))) - ) - ); + $form->populateFromModel($document); - $submitters = $document->getPersonSubmitter(); - if (!is_null($submitters) && count($submitters) > 0) { - $label = $this->view->translate('admin_workflow_notification_submitter') . ' ' - . trim($submitters[0]->getLastName()) . ", " . trim($submitters[0]->getFirstName()); - $element = null; - if (trim($submitters[0]->getEmail()) == '') { - // email notification is not possible since no email address is specified for submitter - $label .= ' (' . $this->view->translate('admin_workflow_notification_noemail') . ')'; - $element = new Zend_Form_Element_Checkbox( - 'submitter', array('checked' => false, 'disabled' => true, - 'label' => $label) - ); - $element->getDecorator('Label')->setOption('class', 'notification-option option-not-available'); - } - else { - $label .= ' (' . trim($submitters[0]->getEmail()) . ')'; - $element = new Zend_Form_Element_Checkbox('submitter', array('checked' => true, 'label' => $label)); - $element->getDecorator('Label')->setOption('class', 'notification-option'); - } - $form->addElement($element); - } + $form->setAction($this->view->url([ + 'controller' => 'workflow', 'action' => 'changestate', 'targetState' => $targetState + ])); + $form->setMethod('post'); - $authors = $document->getPersonAuthor(); - if (!is_null($authors)) { - $index = 1; - foreach ($authors as $author) { - $id = 'author_' . $index; - $label = $index . '. ' . $this->view->translate('admin_workflow_notification_author') . ' ' - . trim($author->getLastName()) . ", " . trim($author->getFirstName()); - $element = null; - if (trim($author->getEmail()) == '') { - // email notification is not possible since no email address is specified for author - $label .= ' (' . $this->view->translate('admin_workflow_notification_noemail') . ')'; - $element = new Zend_Form_Element_Checkbox( - $id, array('checked' => false, 'disabled' => true, 'label' => $label) - ); - $element->getDecorator('Label')->setOption('class', 'notification-option option-not-available'); - } - else { - $label .= ' (' . trim($author->getEmail()) . ')'; - $element = new Zend_Form_Element_Checkbox( - $id, array('checked' => true, 'label' => 'foo', 'label' => $label) - ); - $element->getDecorator('Label')->setOption('class', 'notification-option'); - } - $form->addElement($element); - $index++; - } - } + return $form; } - } - diff --git a/modules/admin/forms/DocumentStateChange.php b/modules/admin/forms/DocumentStateChange.php new file mode 100644 index 000000000..2372e2a6e --- /dev/null +++ b/modules/admin/forms/DocumentStateChange.php @@ -0,0 +1,157 @@ + + * @copyright Copyright (c) 2018, OPUS 4 development team + * @license http://www.gnu.org/licenses/gpl.html General Public License + */ + +/** + * Form for confirming state changes for a document and selecting persons for notification messages. + * + * TODO use displaygroup/subform for list of persons (encapsulate for reuse?) + * TODO handle label and description in a better way + */ +class Admin_Form_DocumentStateChange extends Admin_Form_YesNoForm +{ + + const ELEMENT_ID = 'id'; + + private $targetState; + + public function __construct($targetState, $options = null) + { + parent::__construct($options); + $this->setTargetState($targetState); + } + + public function init() + { + parent::init(); + $idElement = new Zend_Form_Element_Hidden(self::ELEMENT_ID); + $this->addElement($idElement); + } + + public function setTargetState($targetState) + { + $this->targetState = $targetState; + } + + public function getTargetState() + { + return $this->targetState; + } + + public function populateFromModel($document) + { + $this->getElement(self::ELEMENT_ID)->setValue($document->getId()); + + $config = Zend_Registry::get('Zend_Config'); + + if ($this->getTargetState() == 'published' && $this->isNotificationEnabled()) { + $this->addPublishNotificationSelection($document); + } + } + + public function isNotificationEnabled() + { + $config = Zend_Registry::get('Zend_Config'); + + return ((isset($config->notification->document->published->enabled) + && $config->notification->document->published->enabled == 1)); + } + + /** + * Add a checkbox for each PersonSubmitter and PersonAuthor (used to select + * recipients for publish notification email) + * + * @param Opus_Document $document + */ + protected function addPublishNotificationSelection($document) + { + $translator = $this->getTranslator(); + + $this->addElement('hidden', 'plaintext', [ + 'description' => '

          ' . $translator->translate('admin_workflow_notification_headline') + . '

          ' + . '

          ' . $translator->translate('admin_workflow_notification_description') . '

          ', + 'ignore' => true, + 'decorators' => [['Description', ['escape' => false, 'tag' => '']]] + ]); + + $submitters = $document->getPersonSubmitter(); + if (!is_null($submitters) && count($submitters) > 0) { + $label = $translator->translate('admin_workflow_notification_submitter') . ' ' + . trim($submitters[0]->getLastName()) . ", " . trim($submitters[0]->getFirstName()); + $element = null; + if (trim($submitters[0]->getEmail()) == '') { + // email notification is not possible since no email address is specified for submitter + $label .= ' (' . $translator->translate('admin_workflow_notification_noemail') . ')'; + $element = new Zend_Form_Element_Checkbox( + 'submitter', ['checked' => false, 'disabled' => true, + 'label' => $label] + ); + $element->getDecorator('Label')->setOption('class', 'notification-option option-not-available'); + } + else { + $label .= ' (' . trim($submitters[0]->getEmail()) . ')'; + $element = new Zend_Form_Element_Checkbox('submitter', ['checked' => true, 'label' => $label]); + $element->getDecorator('Label')->setOption('class', 'notification-option'); + } + $this->addElement($element); + } + + $authors = $document->getPersonAuthor(); + if (!is_null($authors)) { + $index = 1; + foreach ($authors as $author) { + $id = 'author_' . $index; + $label = $index . '. ' . $translator->translate('admin_workflow_notification_author') . ' ' + . trim($author->getLastName()) . ", " . trim($author->getFirstName()); + $element = null; + if (trim($author->getEmail()) == '') { + // email notification is not possible since no email address is specified for author + $label .= ' (' . $translator->translate('admin_workflow_notification_noemail') . ')'; + $element = new Zend_Form_Element_Checkbox( + $id, ['checked' => false, 'disabled' => true, 'label' => $label] + ); + $element->getDecorator('Label')->setOption('class', 'notification-option option-not-available'); + } + else { + $label .= ' (' . trim($author->getEmail()) . ')'; + $element = new Zend_Form_Element_Checkbox( + $id, ['checked' => true, 'label' => 'foo', 'label' => $label] + ); + $element->getDecorator('Label')->setOption('class', 'notification-option'); + } + $this->addElement($element); + $index++; + } + } + } +} From bff7edc456f7b226af0c42173eec0013bc315431 Mon Sep 17 00:00:00 2001 From: j3nsch Date: Mon, 15 Oct 2018 14:07:43 +0200 Subject: [PATCH 075/128] OPUSVIER-3541 Coding style. --- .../Controller/Action/Helper/Workflow.php | 52 +++-- modules/admin/views/scripts/docinfo.phtml | 3 +- .../views/scripts/workflow/changestate.phtml | 6 +- .../controllers/WorkflowControllerTest.php | 215 ++++++++++++------ 4 files changed, 179 insertions(+), 97 deletions(-) diff --git a/library/Application/Controller/Action/Helper/Workflow.php b/library/Application/Controller/Action/Helper/Workflow.php index 8464ce664..a15437d03 100644 --- a/library/Application/Controller/Action/Helper/Workflow.php +++ b/library/Application/Controller/Action/Helper/Workflow.php @@ -27,9 +27,8 @@ * @category Application * @package Controller * @author Jens Schwidder - * @copyright Copyright (c) 2008-2010, OPUS 4 development team + * @copyright Copyright (c) 2008-2018, OPUS 4 development team * @license http://www.gnu.org/licenses/gpl.html General Public License - * @version $Id$ */ /** @@ -37,7 +36,8 @@ * * Implementiert den Workflow ohne Einschränkungen durch Rollen. */ -class Application_Controller_Action_Helper_Workflow extends Zend_Controller_Action_Helper_Abstract { +class Application_Controller_Action_Helper_Workflow extends Zend_Controller_Action_Helper_Abstract +{ /** * Basic workflow configuration. @@ -52,7 +52,8 @@ class Application_Controller_Action_Helper_Workflow extends Zend_Controller_Acti * @param Opus_Document $document * @return array of strings - Allowed target states for document */ - public function direct($document) { + public function direct($document) + { return $this->getAllowedTargetStatesForDocument($document); } @@ -61,7 +62,8 @@ public function direct($document) { * @param string $state * @return boolean TRUE - only if the state string exists */ - public function isValidState($state) { + public function isValidState($state) + { $states = self::getAllStates(); return in_array($state, $states); @@ -73,7 +75,8 @@ public function isValidState($state) { * @param string $targetState * @return boolean - True only if transition is allowed */ - public function isTransitionAllowed($document, $targetState) { + public function isTransitionAllowed($document, $targetState) + { $allowedStates = $this->getAllowedTargetStatesForDocument($document); return in_array($targetState, $allowedStates); @@ -84,7 +87,8 @@ public function isTransitionAllowed($document, $targetState) { * @param Opus_Document $document * @return array of strings - Possible target states for document */ - public function getAllowedTargetStatesForDocument($document) { + public function getAllowedTargetStatesForDocument($document) + { $logger = Zend_Registry::get('Zend_Log'); $currentState = $document->getServerState(); @@ -97,7 +101,7 @@ public function getAllowedTargetStatesForDocument($document) { $logger->debug("ACL: got instance"); if (!is_null($acl)) { - $allowedTargetStates = array(); + $allowedTargetStates = []; foreach ($targetStates as $targetState) { $resource = 'workflow_' . $currentState . '_' . $targetState; @@ -105,8 +109,7 @@ public function getAllowedTargetStatesForDocument($document) { Application_Security_AclProvider::ACTIVE_ROLE, $resource )) { $allowedTargetStates[] = $targetState; - } - else { + } else { $logger->debug("ACL: $resource not allowed"); } } @@ -123,10 +126,11 @@ public function getAllowedTargetStatesForDocument($document) { * @param string $currentState All lowercase name of current state * @return array of strings - Possible target states for document */ - public static function getTargetStates($currentState) { + public static function getTargetStates($currentState) + { // special code to handle 'removed' state if ($currentState === 'removed') { - return array(); + return []; } $workflow = self::getWorkflowConfig(); @@ -135,8 +139,7 @@ public static function getTargetStates($currentState) { if (!empty($targetStates)) { return $targetStates->toArray(); - } - else { + } else { return array(); } } @@ -148,7 +151,8 @@ public static function getTargetStates($currentState) { * * TODO enforcing permissions and throwing exceptions (OPUSVIER-1959) */ - public function changeState($document, $targetState) { + public function changeState($document, $targetState) + { switch ($targetState) { case 'deleted': $document->delete(); @@ -167,7 +171,8 @@ public function changeState($document, $targetState) { * Returns all defined states of workflow model. * @return array of string Names of defined states */ - public static function getAllStates() { + public static function getAllStates() + { $workflow = self::getWorkflowConfig(); return array_keys($workflow->toArray()); @@ -177,8 +182,9 @@ public static function getAllStates() { * Returns an array with resource names for all possible transitions. * @return array of strings */ - public static function getWorkflowResources() { - $transitions = array(); + public static function getWorkflowResources() + { + $transitions = []; $allStates = self::getAllStates(); @@ -197,7 +203,8 @@ public static function getWorkflowResources() { * Returns configuration for basic workflow model. * @return Zend_Config_Ini */ - public static function getWorkflowConfig() { + public static function getWorkflowConfig() + { if (empty(Application_Controller_Action_Helper_Workflow::$_workflowConfig)) { Application_Controller_Action_Helper_Workflow::$_workflowConfig = new Zend_Config_Ini( APPLICATION_PATH . '/modules/admin/models/workflow.ini' @@ -211,15 +218,16 @@ public static function getWorkflowConfig() { * Returns the Zend_Acl object or null. * @return Zend_Acl */ - public function getAcl() { + public function getAcl() + { if (is_null($this->_acl)) { $this->_acl = Zend_Registry::isRegistered('Opus_Acl') ? Zend_Registry::get('Opus_Acl') : null; } return $this->_acl; } - public function setAcl($acl) { + public function setAcl($acl) + { $this->_acl = $acl; } - } diff --git a/modules/admin/views/scripts/docinfo.phtml b/modules/admin/views/scripts/docinfo.phtml index e7dfddfb0..84c31e3d5 100644 --- a/modules/admin/views/scripts/docinfo.phtml +++ b/modules/admin/views/scripts/docinfo.phtml @@ -26,9 +26,8 @@ * * @category Application * @author Jens Schwidder - * @copyright Copyright (c) 2008-2012, OPUS 4 development team + * @copyright Copyright (c) 2008-2018, OPUS 4 development team * @license http://www.gnu.org/licenses/gpl.html General Public License - * @version $Id$ */ ?> diff --git a/modules/admin/views/scripts/workflow/changestate.phtml b/modules/admin/views/scripts/workflow/changestate.phtml index 941a0d0f1..5a9f41d11 100644 --- a/modules/admin/views/scripts/workflow/changestate.phtml +++ b/modules/admin/views/scripts/workflow/changestate.phtml @@ -29,14 +29,14 @@ * @package Module_Admin * @author Oliver Marahrens * @author Sascha Szott - * @copyright Copyright (c) 2008-2012, OPUS 4 development team + * @author Jens Schwidder + * @copyright Copyright (c) 2008-2018, OPUS 4 development team * @license http://www.gnu.org/licenses/gpl.html General Public License - * @version $Id$ */ ?> navigation()->breadcrumbs()->setReplacement($this->title) ?> - + partial('docinfo.phtml', array( 'document' => $this->documentAdapter)) ?>

          diff --git a/tests/modules/admin/controllers/WorkflowControllerTest.php b/tests/modules/admin/controllers/WorkflowControllerTest.php index e9fe88596..223daae3b 100644 --- a/tests/modules/admin/controllers/WorkflowControllerTest.php +++ b/tests/modules/admin/controllers/WorkflowControllerTest.php @@ -37,15 +37,18 @@ * * @covers Admin_WorkflowController */ -class Admin_WorkflowControllerTest extends ControllerTestCase { +class Admin_WorkflowControllerTest extends ControllerTestCase +{ - private function enablePublishNotification() { + private function enablePublishNotification() + { $config = Zend_Registry::get('Zend_Config'); $config->notification->document->published->enabled = 1; $config->notification->document->published->email = "published@localhost"; } - private function createDocWithSubmitterAndAuthor($submitterMail, $authorMail) { + private function createDocWithSubmitterAndAuthor($submitterMail, $authorMail) + { $doc = $this->createTestDocument(); $author = new Opus_Person(); @@ -71,7 +74,8 @@ private function createDocWithSubmitterAndAuthor($submitterMail, $authorMail) { /** * Tests deleting a document. */ - public function testDeleteAction() { + public function testDeleteAction() + { $this->dispatch('/admin/workflow/changestate/docId/24/targetState/deleted'); $this->assertResponseCode(200); $this->assertModule('admin'); @@ -82,12 +86,13 @@ public function testDeleteAction() { /** * Tests user selecting no in delete confirmation form. */ - public function testDeleteActionConfirmNo() { + public function testDeleteActionConfirmNo() + { $this->request ->setMethod('POST') - ->setPost(array( + ->setPost([ 'sureno' => 'sureno' - )); + ]); $this->dispatch('/admin/workflow/changestate/docId/24/targetState/deleted'); $this->assertModule('admin'); $this->assertController('workflow'); @@ -101,12 +106,13 @@ public function testDeleteActionConfirmNo() { /** * Tests user selecting yes in delete confirmation form. */ - public function testDeleteActionConfirmYes() { + public function testDeleteActionConfirmYes() + { $this->request ->setMethod('POST') - ->setPost(array( + ->setPost([ 'sureyes' => 'sureyes' - )); + ]); $this->dispatch('/admin/workflow/changestate/docId/102/targetState/deleted'); $this->assertModule('admin'); $this->assertController('workflow'); @@ -122,7 +128,8 @@ public function testDeleteActionConfirmYes() { /** * Tests showing confirmation for permanently deleting a document. */ - public function testPermanentDeleteAction() { + public function testPermanentDeleteAction() + { $document = $this->createTestDocument(); $document->setServerState('deleted'); $documentId = $document->store(); @@ -138,16 +145,17 @@ public function testPermanentDeleteAction() { /** * Tests user answering no in permanent delete confirmation form. */ - public function testPermanentDeleteActionConfirmNo() { + public function testPermanentDeleteActionConfirmNo() + { $document = $this->createTestDocument(); $document->setServerState('deleted'); $documentId = $document->store(); $this->request ->setMethod('POST') - ->setPost(array( + ->setPost([ 'sureno' => 'sureno' - )); + ]); $this->dispatch('/admin/workflow/changestate/docId/' . $documentId . '/targetState/removed'); $this->assertModule('admin'); $this->assertController('workflow'); @@ -161,12 +169,13 @@ public function testPermanentDeleteActionConfirmNo() { /** * Tests user answering yes in publish confirmation form. */ - public function testPublishActionConfirmYes() { + public function testPublishActionConfirmYes() + { $this->request ->setMethod('POST') - ->setPost(array( + ->setPost([ 'sureyes' => 'sureyes' - )); + ]); $this->dispatch('/admin/workflow/changestate/docId/100/targetState/published'); $this->assertModule('admin'); $this->assertController('workflow'); @@ -186,7 +195,8 @@ public function testPublishActionConfirmYes() { * * @depends testPublishActionConfirmYes */ - public function testUnpublishAction() { + public function testUnpublishAction() + { $this->dispatch('/admin/workflow/changestate/docId/100/targetState/unpublished'); $this->assertEquals(302, $this->getResponse()->getHttpResponseCode()); @@ -203,7 +213,8 @@ public function testUnpublishAction() { * * Test for XSS using docId. */ - public function testXssUsingIdForDeletingDocuments() { + public function testXssUsingIdForDeletingDocuments() + { $this->dispatch('/admin/workflow/changestate/docId/123/targetState/deleted'); $this->assertEquals(302, $this->getResponse()->getHttpResponseCode()); $this->assertResponseLocationHeader($this->getResponse(), '/admin/documents'); @@ -216,7 +227,8 @@ public function testXssUsingIdForDeletingDocuments() { * * Test for failure to redirect for already deleted documents. */ - public function testNoRedirectForAlreadyDeletedDocuments() { + public function testNoRedirectForAlreadyDeletedDocuments() + { $this->dispatch('/admin/workflow/changestate/docId/123/targetState/deleted'); $this->assertEquals(302, $this->getResponse()->getHttpResponseCode()); $this->assertResponseLocationHeader($this->getResponse(), '/admin/document/index/id/123'); @@ -232,7 +244,8 @@ public function testNoRedirectForAlreadyDeletedDocuments() { * * If the document ID is invalid a redirect should happen. */ - public function testNoRedirectForInvalidIdForDeletingDocuments() { + public function testNoRedirectForInvalidIdForDeletingDocuments() + { $this->dispatch('/admin/workflow/changestate/docId/123456789/targetState/deleted'); $this->assertEquals(302, $this->getResponse()->getHttpResponseCode()); $this->assertResponseLocationHeader($this->getResponse(), '/admin/documents'); @@ -248,7 +261,8 @@ public function testNoRedirectForInvalidIdForDeletingDocuments() { * * If the document ID is non-numeric a redirect should happen. */ - public function testNoRedirectForNonNumericIdForDeletingDocuments() { + public function testNoRedirectForNonNumericIdForDeletingDocuments() + { $this->dispatch('/admin/workflow/changestate/docId/foo/targetState/deleted'); $this->assertEquals(302, $this->getResponse()->getHttpResponseCode()); $this->assertResponseLocationHeader($this->getResponse(), '/admin/documents'); @@ -259,61 +273,109 @@ public function testNoRedirectForNonNumericIdForDeletingDocuments() { "Request produced internal error. " . $this->getResponse()->getBody()); } - public function testNotificationIsNotSupported() { - $doc = $this->createDocWithSubmitterAndAuthor('submitter@localhost.de', 'author@localhost.de'); + public function testNotificationIsNotSupported() + { + $doc = $this->createDocWithSubmitterAndAuthor( + 'submitter@localhost.de', 'author@localhost.de' + ); $this->dispatch('/admin/workflow/changestate/docId/' . $doc->getId() . '/targetState/published'); - $this->assertNotContains('submitter@localhost.de', $this->getResponse()->getBody()); - $this->assertNotContains('author@localhost.de', $this->getResponse()->getBody()); - $this->assertNotContains('getResponse()->getBody()); - $this->assertNotContains('getResponse()->getBody()); + $body = $this->getResponse()->getBody(); + + $this->assertNotContains('submitter@localhost.de', $body); + $this->assertNotContains('author@localhost.de', $body); + $this->assertNotContains( + 'assertNotContains( + 'enablePublishNotification(); - $doc = $this->createDocWithSubmitterAndAuthor('submitter@localhost.de', 'author@localhost.de'); + $doc = $this->createDocWithSubmitterAndAuthor( + 'submitter@localhost.de', 'author@localhost.de' + ); $this->dispatch('/admin/workflow/changestate/docId/' . $doc->getId() . '/targetState/published'); - $this->assertContains('submitter@localhost.de', $this->getResponse()->getBody()); - $this->assertContains('author@localhost.de', $this->getResponse()->getBody()); - $this->assertContains('getResponse()->getBody()); + $body = $this->getResponse()->getBody(); + + $this->assertContains('submitter@localhost.de', $body); + $this->assertContains('author@localhost.de', $body); + $this->assertContains( + 'enablePublishNotification(); - $doc = $this->createDocWithSubmitterAndAuthor('submitter@localhost.de', 'author@localhost.de'); + $doc = $this->createDocWithSubmitterAndAuthor( + 'submitter@localhost.de', 'author@localhost.de' + ); $this->dispatch('/admin/workflow/changestate/docId/' . $doc->getId() . '/targetState/published'); - $this->assertContains('submitter@localhost.de', $this->getResponse()->getBody()); - $this->assertContains('author@localhost.de', $this->getResponse()->getBody()); - $this->assertContains('getResponse()->getBody()); + $body = $this->getResponse()->getBody(); + + $this->assertContains('submitter@localhost.de', $body); + $this->assertContains('author@localhost.de', $body); + $this->assertContains( + 'enablePublishNotification(); $doc = $this->createDocWithSubmitterAndAuthor('', 'author@localhost.de'); + $this->dispatch('/admin/workflow/changestate/docId/' . $doc->getId() . '/targetState/published'); - $this->assertNotContains('submitter@localhost.de', $this->getResponse()->getBody()); - $this->assertContains('author@localhost.de', $this->getResponse()->getBody()); - $this->assertContains('getResponse()->getBody()); - $this->assertContains('getResponse()->getBody()); + $body = $this->getResponse()->getBody(); + + $this->assertNotContains('submitter@localhost.de', $body); + $this->assertContains('author@localhost.de', $body); + $this->assertContains( + 'assertContains( + 'enablePublishNotification(); $doc = $this->createDocWithSubmitterAndAuthor('submitter@localhost.de', ''); + $this->dispatch('/admin/workflow/changestate/docId/' . $doc->getId() . '/targetState/published'); - $this->assertContains('submitter@localhost.de', $this->getResponse()->getBody()); - $this->assertNotContains('author@localhost.de', $this->getResponse()->getBody()); - $this->assertContains('getResponse()->getBody()); - $this->assertContains('getResponse()->getBody()); + $body = $this->getResponse()->getBody(); + + $this->assertContains('submitter@localhost.de', $body); + $this->assertNotContains('author@localhost.de', $body); + $this->assertContains( + 'assertContains( + 'enablePublishNotification(); - $doc = $this->createDocWithSubmitterAndAuthor('submitter@localhost.de', 'author@localhost.de'); + $doc = $this->createDocWithSubmitterAndAuthor( + 'submitter@localhost.de', 'author@localhost.de' + ); $author = new Opus_Person(); $author->setFirstName("AFN"); @@ -323,7 +385,7 @@ public function testAuthorNotificationForMultipleAuthors() { $author = new Opus_Person(); $author->setFirstName("BFN"); - $author->setLastName("BLN"); + $author->setLastName("BLN"); $doc->addPersonAuthor($author); $author = new Opus_Person(); @@ -335,35 +397,49 @@ public function testAuthorNotificationForMultipleAuthors() { $doc->store(); $this->dispatch('/admin/workflow/changestate/docId/' . $doc->getId() . '/targetState/published'); - - $this->assertContains('submitter@localhost.de', $this->getResponse()->getBody()); - $this->assertContains('author@localhost.de', $this->getResponse()->getBody()); - $this->assertContains('A@localhost.de', $this->getResponse()->getBody()); - $this->assertContains('C@localhost.de', $this->getResponse()->getBody()); - - $this->assertContains('getResponse()->getBody()); - $this->assertContains('getResponse()->getBody()); - $this->assertContains('getResponse()->getBody()); - $this->assertContains('getResponse()->getBody()); - $this->assertContains('getResponse()->getBody()); + + $body = $this->getResponse()->getBody(); + + $this->assertContains('submitter@localhost.de', $body); + $this->assertContains('author@localhost.de', $body); + $this->assertContains('A@localhost.de', $body); + $this->assertContains('C@localhost.de', $body); + + $this->assertContains( + 'assertContains( + 'assertContains( + 'assertContains( + 'assertContains( + 'dispatch('/admin/workflow/changestate/docId/146/targetState/deleted'); $this->assertResponseCode(200); $this->assertModule('admin'); $this->assertController('workflow'); $this->assertAction('changestate'); - + $this->assertQueryContentContains('div#docinfo', 'KOBV'); $this->assertQueryContentContains('div#docinfo', '146'); $this->assertQueryContentContains('div#docinfo', 'Doe, John'); } - public function testConfirmationDisabled() { - $config = Zend_Registry::get('Zend_Config'); - $config->merge(new Zend_Config(array('confirmation' => array('document' => array('statechange' => array( - 'enabled' => '0')))))); + public function testConfirmationDisabled() + { + Zend_Registry::get('Zend_Config')->merge(new Zend_Config([ + 'confirmation' => ['document' => ['statechange' => ['enabled' => '0']]] + ])); $this->dispatch('/admin/workflow/changestate/docId/102/targetState/deleted'); $this->assertRedirectTo('/admin/document/index/id/102'); // Änderung wird sofort durchgefuehrt @@ -373,5 +449,4 @@ public function testConfirmationDisabled() { $doc->setServerState('unpublished'); $doc->store(); } - } From fc89627d862774d011c274036df1a162ec0bdbd7 Mon Sep 17 00:00:00 2001 From: j3nsch Date: Tue, 16 Oct 2018 13:37:23 +0200 Subject: [PATCH 076/128] OPUSVIER-3541 Coding style. --- library/Application/Form/Element/Text.php | 42 +++++++++++-------- .../Application/Form/Element/TextTest.php | 22 ++++++---- 2 files changed, 37 insertions(+), 27 deletions(-) diff --git a/library/Application/Form/Element/Text.php b/library/Application/Form/Element/Text.php index 12d6ab69b..616866e77 100644 --- a/library/Application/Form/Element/Text.php +++ b/library/Application/Form/Element/Text.php @@ -27,9 +27,8 @@ * @category Application * @package View * @author Jens Schwidder - * @copyright Copyright (c) 2013, OPUS 4 development team + * @copyright Copyright (c) 2013-2018, OPUS 4 development team * @license http://www.gnu.org/licenses/gpl.html General Public License - * @version $Id$ */ /** @@ -37,7 +36,8 @@ * * Zur Zeit nur vom Metadaten-Formular genutzt. */ -class Application_Form_Element_Text extends Zend_Form_Element_Text implements Application_Form_IElement { +class Application_Form_Element_Text extends Zend_Form_Element_Text implements Application_Form_IElement +{ /** * Hinweis, der mit dem Feld angezeigt werden sollte. @@ -59,29 +59,31 @@ class Application_Form_Element_Text extends Zend_Form_Element_Text implements Ap * * Fügt PrefixPath für angepasste OPUS Dekoratoren hinzu. */ - public function init() { + public function init() + { parent::init(); - $this->addPrefixPath('Application_Form_Decorator', 'Application/Form/Decorator', Zend_Form::DECORATOR); + $this->addPrefixPath( + 'Application_Form_Decorator', 'Application/Form/Decorator', Zend_Form::DECORATOR + ); } /** * Lädt die Defaultdekoratoren für ein Textelement. */ - public function loadDefaultDecorators() { + public function loadDefaultDecorators() + { if (!$this->loadDefaultDecoratorsIsDisabled() && count($this->getDecorators()) == 0) { - $this->setDecorators( - array( + $this->setDecorators([ 'ViewHelper', 'Placeholder', 'Description', 'ElementHint', 'Errors', 'ElementHtmlTag', - array('LabelNotEmpty', array('tag' => 'div', 'tagClass' => 'label', 'placement' => 'prepend')), - array(array('dataWrapper' => 'HtmlTagWithId'), array('tag' => 'div', 'class' => 'data-wrapper')) - ) - ); + ['LabelNotEmpty', ['tag' => 'div', 'tagClass' => 'label', 'placement' => 'prepend']], + [['dataWrapper' => 'HtmlTagWithId'], ['tag' => 'div', 'class' => 'data-wrapper']] + ]); } } @@ -89,7 +91,8 @@ public function loadDefaultDecorators() { * Setzt den Hinweis für das Formularelement. * @param $hint Hinweis */ - public function setHint($hint) { + public function setHint($hint) + { $this->_hint = $hint; } @@ -97,14 +100,16 @@ public function setHint($hint) { * Liefert den Hinweis für das Formularelement. * @return string */ - public function getHint() { + public function getHint() + { return $this->_hint; } /** * Sorgt dafür, daß nur der Text ausgeben wird und kein INPUT-Tag. */ - public function prepareRenderingAsView() { + public function prepareRenderingAsView() + { $viewHelper = $this->getDecorator('ViewHelper'); if ($viewHelper instanceof Application_Form_Decorator_ViewHelper) { $viewHelper->setViewOnlyEnabled(true); @@ -112,12 +117,13 @@ public function prepareRenderingAsView() { $this->removeDecorator('Placeholder'); } - public function getStaticViewHelper() { + public function getStaticViewHelper() + { return $this->_staticViewHelper; } - public function setStaticViewHelper($viewHelper) { + public function setStaticViewHelper($viewHelper) + { $this->_staticViewHelper = $viewHelper; } - } diff --git a/tests/library/Application/Form/Element/TextTest.php b/tests/library/Application/Form/Element/TextTest.php index fd60a0c76..3264e965c 100644 --- a/tests/library/Application/Form/Element/TextTest.php +++ b/tests/library/Application/Form/Element/TextTest.php @@ -27,23 +27,27 @@ * @category Application Unit Test * @package Form_Element * @author Jens Schwidder - * @copyright Copyright (c) 2008-2013, OPUS 4 development team + * @copyright Copyright (c) 2008-2018, OPUS 4 development team * @license http://www.gnu.org/licenses/gpl.html General Public License - * @version $Id$ */ -class Application_Form_Element_TextTest extends FormElementTestCase { +class Application_Form_Element_TextTest extends FormElementTestCase +{ - public function setUp() { + public function setUp() + { $this->_formElementClass = 'Application_Form_Element_Text'; $this->_expectedDecoratorCount = 8; - $this->_expectedDecorators = array('ViewHelper', 'Placeholder', 'Description', 'ElementHint', 'Errors', - 'ElementHtmlTag', 'LabelNotEmpty', 'dataWrapper'); + $this->_expectedDecorators = [ + 'ViewHelper', 'Placeholder', 'Description', 'ElementHint', 'Errors', + 'ElementHtmlTag', 'LabelNotEmpty', 'dataWrapper' + ]; $this->_staticViewHelper = 'viewFormDefault'; parent::setUp(); } - public function testSetGetHint() { + public function testSetGetHint() + { $element = new Application_Form_Element_Text('text'); $this->assertNull($element->getHint()); @@ -53,12 +57,12 @@ public function testSetGetHint() { $this->assertEquals('Hinweis', $element->getHint()); } - public function testPrepareRenderingAsViewRemovePlaceholder() { + public function testPrepareRenderingAsViewRemovePlaceholder() + { $element = $this->getElement(); $element->prepareRenderingAsView(); $this->assertFalse($element->getDecorator('Placeholder')); } - } From 950a2ee095693ac8f19001b5a4e31ac721b25e0d Mon Sep 17 00:00:00 2001 From: BioFreak95 Date: Tue, 16 Oct 2018 15:17:45 +0200 Subject: [PATCH 077/128] =?UTF-8?q?OPUSVIER-3947=20=C3=9Cbersetzungsmechan?= =?UTF-8?q?ik=20f=C3=BCr=20Javascript=20Es=20wirde=20eine=20=C3=9Cbersetzu?= =?UTF-8?q?ngsmechanik=20f=C3=BCr=20Javascript=20eingebaut?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../View/Helper/JavascriptTranslation.php | 61 +++++++++++++++++++ .../admin/controllers/DocumentController.php | 4 ++ modules/default/language/error.tmx | 18 ++++++ modules/publish/language/errors.tmx | 2 - public/layouts/opus4/common.phtml | 2 + public/layouts/opus4/js/validation.js | 40 +++++------- 6 files changed, 99 insertions(+), 28 deletions(-) create mode 100644 library/Application/View/Helper/JavascriptTranslation.php diff --git a/library/Application/View/Helper/JavascriptTranslation.php b/library/Application/View/Helper/JavascriptTranslation.php new file mode 100644 index 000000000..c7461b2b2 --- /dev/null +++ b/library/Application/View/Helper/JavascriptTranslation.php @@ -0,0 +1,61 @@ + + * @copyright Copyright (c) 2018, OPUS 4 development team + * @license http://www.gnu.org/licenses/gpl.html General Public License + */ + +class Application_View_Helper_JavascriptTranslation extends Application_View_Helper_Abstract +{ + + protected $messages = ''; + + public function javascriptTranslation() + { + + $output = '"; + + return $output; + } + + public function addJavascriptTranslations($key, $message = null) + { + + if ($message != null) { + $this->messages .= "\t" . "\t" . "\t" . "messages.$key = \"" . htmlspecialchars($message) . "\";" . "\n"; + } else { + $message = $this->view->translate($key); + $this->messages .= "\t" . "\t" . "\t" . "messages.$key = \"" . htmlspecialchars($message) . "\";" . "\n"; + } + + } + +} \ No newline at end of file diff --git a/modules/admin/controllers/DocumentController.php b/modules/admin/controllers/DocumentController.php index dba2bb5ff..0cc5e385f 100644 --- a/modules/admin/controllers/DocumentController.php +++ b/modules/admin/controllers/DocumentController.php @@ -228,6 +228,10 @@ public function editAction() { $this->_helper->breadcrumbs()->setDocumentBreadcrumb($document); $this->renderForm($this->view->form); + + $javascriptTranslations = $this->view->getHelper('javascriptTranslation'); + $javascriptTranslations->addJavascriptTranslations('identifierInvalidFormat'); + $javascriptTranslations->addJavascriptTranslations('identifierInvalidCheckdigit'); } } diff --git a/modules/default/language/error.tmx b/modules/default/language/error.tmx index 1d3dec2ad..72213c4f2 100644 --- a/modules/default/language/error.tmx +++ b/modules/default/language/error.tmx @@ -110,6 +110,24 @@ + + + '%value%' is malformed. + + + '%value%' hat eine unerlaubte Form. + + + + + + The check digit of '%value%' is not valid". + + + Die Prüfziffer '%value%' ist nicht korrekt. + + + diff --git a/modules/publish/language/errors.tmx b/modules/publish/language/errors.tmx index e65666b20..15bb35812 100644 --- a/modules/publish/language/errors.tmx +++ b/modules/publish/language/errors.tmx @@ -161,8 +161,6 @@ - - diff --git a/public/layouts/opus4/common.phtml b/public/layouts/opus4/common.phtml index 5cb2ea3e6..8d17847c7 100644 --- a/public/layouts/opus4/common.phtml +++ b/public/layouts/opus4/common.phtml @@ -142,6 +142,8 @@ if (isset($config->javascript->latex->mathjax)) { + javascriptTranslation() ?> + diff --git a/public/layouts/opus4/js/validation.js b/public/layouts/opus4/js/validation.js index 9a5f7cd60..89dc621bc 100644 --- a/public/layouts/opus4/js/validation.js +++ b/public/layouts/opus4/js/validation.js @@ -29,21 +29,21 @@ * @license http://www.gnu.org/licenses/gpl.html General Public License */ +var messages = { + identifierInvalidCheckdigit: "The check digit of \'%value%\' is not valid", + identifierInvalidFormat: "\'%value%\' is malformed" +}; function validateISSN(value) { - var messages = { - invalidCheckdigit: "The check digit of \'%value%\' is not valid", - invalidFormat: "\'%value%\' is malformed" - }; // check length if (value.length !== 9) { - return messages.invalidFormat.replace("%value%", value); + return messages.identifierInvalidFormat.replace("%value%", value); } // check form if (value.match(/^[0-9]{4}[-][0-9]{3}[0-9X]$/g) === null) { - return messages.invalidFormat.replace("%value%", value); + return messages.identifierInvalidFormat.replace("%value%", value); } // Split ISSN into its parts @@ -52,7 +52,7 @@ function validateISSN(value) { // Calculate and compare check digit var checkdigit = calculateCheckDigitISSN(issn); if (checkdigit != issn[8]) { - return messages.invalidCheckdigit.replace("%value%", value); + return messages.identifierInvalidCheckdigit.replace("%value%", value); } return true; @@ -72,10 +72,6 @@ function calculateCheckDigitISSN(value) { } function validateISBN(value) { - var messages = { - invalidCheckdigit: "The check digit of \'%value%\' is not valid", - invalidFormat: "\'%value%\' is malformed" - }; var isbnDigits = splitISBN(value); @@ -86,26 +82,22 @@ function validateISBN(value) { return validateISBN13(value); } else { - return messages.invalidFormat.replace("%value%", value); + return messages.identifierInvalidFormat.replace("%value%", value); } } function validateISBN10(value) { - var messages = { - invalidCheckdigit: "The check digit of \'%value%\' is not valid", - invalidFormat: "\'%value%\' is malformed" - }; if (value.length !== 10 && value.length !== 13) { - return messages.invalidFormat.replace("%value%", value); + return messages.identifierInvalidFormat.replace("%value%", value); } if (value.match(/^[\d]*((-|\s)?[\d]*){2}((-|\s)?[\dX])$/g) === null) { - return messages.invalidFormat.replace("%value%", value); + return messages.identifierInvalidFormat.replace("%value%", value); } if (value.match(/-/) !== null && value.match(/\s/) !== null) { - return messages.invalidFormat.replace("%value%", value); + return messages.identifierInvalidFormat.replace("%value%", value); } var isbnDigits = splitISBN(value); @@ -113,21 +105,17 @@ function validateISBN10(value) { } function validateISBN13(value) { - var messages = { - invalidCheckdigit: "The check digit of \'%value%\' is not valid", - invalidFormat: "\'%value%\' is malformed" - }; if (value.length !== 13 && value.length !== 17) { - return messages.invalidFormat.replace("%value%", value); + return messages.identifierInvalidFormat.replace("%value%", value); } if (value.match(/^(978|979)((-|\s)?[\d]*){4}$/g) === null) { - return messages.invalidFormat.replace("%value%", value); + return messages.identifierInvalidFormat.replace("%value%", value); } if (value.match(/-/) !== null && value.match(/\s/) !== null) { - return messages.invalidFormat.replace("%value%", value); + return messages.identifierInvalidFormat.replace("%value%", value); } var isbnDigits = splitISBN(value); From c1c13fe5d899c366314bcefe1f21ba4f2bea7c5d Mon Sep 17 00:00:00 2001 From: BioFreak95 Date: Tue, 16 Oct 2018 16:40:25 +0200 Subject: [PATCH 078/128] OPUSVIER-3899 Bugfix in tests and validator-class --- public/layouts/opus4/js/validation.js | 12 ++++++++++-- tests/javascript/testIsbnValidation.html | 18 +++++++++--------- tests/javascript/testIssnValidation.html | 6 +++--- 3 files changed, 22 insertions(+), 14 deletions(-) diff --git a/public/layouts/opus4/js/validation.js b/public/layouts/opus4/js/validation.js index 89dc621bc..5d9d013a3 100644 --- a/public/layouts/opus4/js/validation.js +++ b/public/layouts/opus4/js/validation.js @@ -101,7 +101,11 @@ function validateISBN10(value) { } var isbnDigits = splitISBN(value); - return calculateCheckDigitISBN10(isbnDigits); + if (calculateCheckDigitISBN10(isbnDigits) === false) { + return messages.identifierInvalidCheckdigit.replace("%value%", value); + } + + return true; } function validateISBN13(value) { @@ -119,7 +123,11 @@ function validateISBN13(value) { } var isbnDigits = splitISBN(value); - return calculateCheckDigitISBN13(isbnDigits); + if (calculateCheckDigitISBN13(isbnDigits) === false) { + return messages.identifierInvalidCheckdigit.replace("%value%", value); + } + + return true; } function calculateCheckDigitISBN10(value) { diff --git a/tests/javascript/testIsbnValidation.html b/tests/javascript/testIsbnValidation.html index dafea1aa6..8cb8dc050 100644 --- a/tests/javascript/testIsbnValidation.html +++ b/tests/javascript/testIsbnValidation.html @@ -92,10 +92,10 @@ var expectation = rows[1]; var actual = rows[2]; var result = rows[3]; - if (validateISBN13(ISBN) === false) { - actual.innerHTML = "False"; - } else { + if (validateISBN13(ISBN) === true) { actual.innerHTML = "True"; + } else { + actual.innerHTML = "False"; } if (actual.innerHTML === expectation.innerHTML) { result.innerHTML = 'Passed'; @@ -114,10 +114,10 @@ var expectation = rows[1]; var actual = rows[2]; var result = rows[3]; - if (validateISBN10(ISBN) === false) { - actual.innerHTML = "False"; - } else { + if (validateISBN10(ISBN) === true) { actual.innerHTML = "True"; + } else { + actual.innerHTML = "False"; } if (actual.innerHTML === expectation.innerHTML) { result.innerHTML = 'Passed'; @@ -136,10 +136,10 @@ var expectation = rows[1]; var actual = rows[2]; var result = rows[3]; - if (validateISBN(ISBN) === false) { - actual.innerHTML = "False"; - } else { + if (validateISBN(ISBN) === true) { actual.innerHTML = "True"; + } else { + actual.innerHTML = "False"; } if (actual.innerHTML === expectation.innerHTML) { result.innerHTML = 'Passed'; diff --git a/tests/javascript/testIssnValidation.html b/tests/javascript/testIssnValidation.html index 30057cb40..a550a8593 100644 --- a/tests/javascript/testIssnValidation.html +++ b/tests/javascript/testIssnValidation.html @@ -92,10 +92,10 @@ let expectation = rows[1]; let actual = rows[2]; let result = rows[3]; - if (validateISSN(ISSN) === false) { - actual.innerHTML = "False"; - } else { + if (validateISSN(ISSN) === true) { actual.innerHTML = "True"; + } else { + actual.innerHTML = "False"; } if (actual.innerHTML === expectation.innerHTML) { result.innerHTML = 'Passed'; From f4a482b2211b2f5f1be994a9371b81eddee6e39c Mon Sep 17 00:00:00 2001 From: BioFreak95 Date: Wed, 17 Oct 2018 11:45:08 +0200 Subject: [PATCH 079/128] OPUSVIER-3899 Bugfix in validation --- public/layouts/opus4/js/validation.js | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/public/layouts/opus4/js/validation.js b/public/layouts/opus4/js/validation.js index 5d9d013a3..f259ccb6f 100644 --- a/public/layouts/opus4/js/validation.js +++ b/public/layouts/opus4/js/validation.js @@ -170,7 +170,6 @@ function splitISBN(value) { $(document).ready(function () { var selectors = []; var result; - var ident; var identifier = $("#fieldset-Identifiers tbody tr td.Value-data"); var identifierText = $("#fieldset-Identifiers tbody tr :text"); @@ -187,7 +186,6 @@ $(document).ready(function () { selectors[index] = value.value; value.onchange = function () { selectors[index] = value.value; - ident = selectors[index]; }; }); @@ -195,10 +193,10 @@ $(document).ready(function () { $.each(identifierText, function (index, value) { value.onchange = function () { - if (ident === "isbn") { + if (selectors[index] === "isbn") { result = validateISBN(value.value); } - else if (ident === "issn") { + else if (selectors[index] === "issn") { result = validateISSN(value.value); } From 068595d8715edaadfe90d9d74ce809d2ce4041b1 Mon Sep 17 00:00:00 2001 From: BioFreak95 Date: Wed, 17 Oct 2018 16:00:25 +0200 Subject: [PATCH 080/128] OPUSVIER-3899 view-helper tests and some fixes in view-helper --- .../View/Helper/JavascriptTranslation.php | 27 ++++-- .../admin/controllers/DocumentController.php | 4 +- .../View/Helper/JavascriptTranslationTest.php | 96 +++++++++++++++++++ 3 files changed, 115 insertions(+), 12 deletions(-) create mode 100644 tests/library/Application/View/Helper/JavascriptTranslationTest.php diff --git a/library/Application/View/Helper/JavascriptTranslation.php b/library/Application/View/Helper/JavascriptTranslation.php index c7461b2b2..3ab9d87a0 100644 --- a/library/Application/View/Helper/JavascriptTranslation.php +++ b/library/Application/View/Helper/JavascriptTranslation.php @@ -33,29 +33,36 @@ class Application_View_Helper_JavascriptTranslation extends Application_View_Helper_Abstract { - - protected $messages = ''; + protected $translations = []; public function javascriptTranslation() { - $output = '"; + foreach ($this->translations as $key => $message) { + $output .= " " . "messages.$key = \"" . htmlspecialchars($message) . "\";" . "\n"; + } + $output .= " " . ""; return $output; } - public function addJavascriptTranslations($key, $message = null) + public function addTranslation($key, $message = null) { - if ($message != null) { - $this->messages .= "\t" . "\t" . "\t" . "messages.$key = \"" . htmlspecialchars($message) . "\";" . "\n"; + $this->translations[$key] = $message; } else { $message = $this->view->translate($key); - $this->messages .= "\t" . "\t" . "\t" . "messages.$key = \"" . htmlspecialchars($message) . "\";" . "\n"; + $this->translations[$key] = $message; } + } + public function getTranslations() + { + return $this->translations; } -} \ No newline at end of file + public function setTranslations($value) + { + $this->translations = $value; + } +} diff --git a/modules/admin/controllers/DocumentController.php b/modules/admin/controllers/DocumentController.php index 0cc5e385f..210fffe0a 100644 --- a/modules/admin/controllers/DocumentController.php +++ b/modules/admin/controllers/DocumentController.php @@ -230,8 +230,8 @@ public function editAction() { $this->renderForm($this->view->form); $javascriptTranslations = $this->view->getHelper('javascriptTranslation'); - $javascriptTranslations->addJavascriptTranslations('identifierInvalidFormat'); - $javascriptTranslations->addJavascriptTranslations('identifierInvalidCheckdigit'); + $javascriptTranslations->addTranslation('identifierInvalidFormat'); + $javascriptTranslations->addTranslation('identifierInvalidCheckdigit'); } } diff --git a/tests/library/Application/View/Helper/JavascriptTranslationTest.php b/tests/library/Application/View/Helper/JavascriptTranslationTest.php new file mode 100644 index 000000000..e286854b9 --- /dev/null +++ b/tests/library/Application/View/Helper/JavascriptTranslationTest.php @@ -0,0 +1,96 @@ + + * @copyright Copyright (c) 2018, OPUS 4 development team + * @license http://www.gnu.org/licenses/gpl.html General Public License + */ + +class Application_View_Helper_JavascriptTranslationTest extends ControllerTestCase +{ + + private $_helper; + + public function setUp() + { + parent::setUp(); + + $this->useEnglish(); + + $this->_helper = new Application_View_Helper_JavascriptTranslation(); + + $this->_helper->setView(Zend_Registry::get('Opus_View')); + } + + public function testJavascriptTranslation() + { + $translations = [ + 'key1' => 'message1', + 'key2' => 'message2' + ]; + $this->_helper->setTranslations($translations); + + $expectation = ''; + + $reality = $this->_helper->javascriptTranslation(); + $this->assertEquals($expectation, $reality); + } + + public function testAddTranslation() + { + $this->_helper->addTranslation('key1', 'message1'); + $this->_helper->addTranslation('identifierInvalidFormat'); + $this->_helper->addTranslation('testkey'); + + $translations = [ + 'key1' => 'message1', + 'identifierInvalidFormat' => "'%value%' is malformed.", + 'testkey' => 'testkey' + ]; + + $this->assertEquals($translations, $this->_helper->getTranslations()); + } + + public function testSetTranslations() + { + $translations = [ + 'key1' => 'message1', + 'key2' => 'message2' + ]; + $this->_helper->setTranslations($translations); + $this->assertEquals($translations, $this->_helper->getTranslations()); + } + + public function testGetTranslations() + { + $this->assertEquals([], $this->_helper->getTranslations()); + } +} From 734ef7b2743e6470d3915cc7c70109096a9ab883 Mon Sep 17 00:00:00 2001 From: BioFreak95 Date: Wed, 17 Oct 2018 16:07:44 +0200 Subject: [PATCH 081/128] OPUSVIER-3899 validation.js codingstyle --- public/layouts/opus4/js/validation.js | 10 +--------- 1 file changed, 1 insertion(+), 9 deletions(-) diff --git a/public/layouts/opus4/js/validation.js b/public/layouts/opus4/js/validation.js index f259ccb6f..63f050b45 100644 --- a/public/layouts/opus4/js/validation.js +++ b/public/layouts/opus4/js/validation.js @@ -35,7 +35,6 @@ var messages = { }; function validateISSN(value) { - // check length if (value.length !== 9) { return messages.identifierInvalidFormat.replace("%value%", value); @@ -72,7 +71,6 @@ function calculateCheckDigitISSN(value) { } function validateISBN(value) { - var isbnDigits = splitISBN(value); if (isbnDigits.length === 10) { @@ -87,7 +85,6 @@ function validateISBN(value) { } function validateISBN10(value) { - if (value.length !== 10 && value.length !== 13) { return messages.identifierInvalidFormat.replace("%value%", value); } @@ -109,7 +106,6 @@ function validateISBN10(value) { } function validateISBN13(value) { - if (value.length !== 13 && value.length !== 17) { return messages.identifierInvalidFormat.replace("%value%", value); } @@ -149,7 +145,6 @@ function calculateCheckDigitISBN13(value) { return (check % 10 === 0); } - function splitISBN(value) { var isbn = value.split(/(-|\s)/); var digits = []; @@ -166,7 +161,6 @@ function splitISBN(value) { return digits; } - $(document).ready(function () { var selectors = []; var result; @@ -189,9 +183,7 @@ $(document).ready(function () { }; }); - $.each(identifierText, function (index, value) { - value.onchange = function () { if (selectors[index] === "isbn") { result = validateISBN(value.value); @@ -213,4 +205,4 @@ $(document).ready(function () { }; }); -}); \ No newline at end of file +}); From a4aa85655b421fab7ce0dbff28a1d71cc72cc9e5 Mon Sep 17 00:00:00 2001 From: BioFreak95 Date: Wed, 17 Oct 2018 16:09:32 +0200 Subject: [PATCH 082/128] OPUSVIER-3899 codingstyle --- .../Application/View/Helper/JavascriptTranslationTest.php | 1 - 1 file changed, 1 deletion(-) diff --git a/tests/library/Application/View/Helper/JavascriptTranslationTest.php b/tests/library/Application/View/Helper/JavascriptTranslationTest.php index e286854b9..623585642 100644 --- a/tests/library/Application/View/Helper/JavascriptTranslationTest.php +++ b/tests/library/Application/View/Helper/JavascriptTranslationTest.php @@ -33,7 +33,6 @@ class Application_View_Helper_JavascriptTranslationTest extends ControllerTestCase { - private $_helper; public function setUp() From a7a8d53c23536e2e0377cfd9ee81547b29f1686f Mon Sep 17 00:00:00 2001 From: j3nsch Date: Thu, 18 Oct 2018 15:24:37 +0200 Subject: [PATCH 083/128] OPUSVIER-3541 Allow null for setConfig function parameter. --- library/Application/Export/ExportPlugin.php | 2 +- library/Application/Model/Abstract.php | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/library/Application/Export/ExportPlugin.php b/library/Application/Export/ExportPlugin.php index 2f0a24aae..1f11d9dc9 100644 --- a/library/Application/Export/ExportPlugin.php +++ b/library/Application/Export/ExportPlugin.php @@ -51,7 +51,7 @@ public function getName(); * Sets the plugin configuration. * @param Zend_Config $config */ - public function setConfig(Zend_Config $config); + public function setConfig(Zend_Config $config = null); /** * Sets the HTTP request being processed. diff --git a/library/Application/Model/Abstract.php b/library/Application/Model/Abstract.php index 74362e5d6..3672a1122 100644 --- a/library/Application/Model/Abstract.php +++ b/library/Application/Model/Abstract.php @@ -73,7 +73,7 @@ public function getLogger() { * Sets configuration. * @param $config Zend_Config */ - public function setConfig(Zend_Config $config) { + public function setConfig(Zend_Config $config = null) { $this->_config = $config; } From 100fc67444217c46c517146baa6870507fef57b9 Mon Sep 17 00:00:00 2001 From: j3nsch Date: Thu, 18 Oct 2018 16:28:28 +0200 Subject: [PATCH 084/128] OPUSVIER-3541 Coding style. --- modules/admin/forms/YesNoForm.php | 17 ++++++++++------- 1 file changed, 10 insertions(+), 7 deletions(-) diff --git a/modules/admin/forms/YesNoForm.php b/modules/admin/forms/YesNoForm.php index 79987abf1..0332ee927 100644 --- a/modules/admin/forms/YesNoForm.php +++ b/modules/admin/forms/YesNoForm.php @@ -27,18 +27,21 @@ * @category Application * @package Module_Admin * @author Oliver Marahrens - * @copyright Copyright (c) 2009, OPUS 4 development team + * @author Jens Schwidder + * @copyright Copyright (c) 2009-2018, OPUS 4 development team * @license http://www.gnu.org/licenses/gpl.html General Public License - * @version $Id$ */ -class Admin_Form_YesNoForm extends Zend_Form { +class Admin_Form_YesNoForm extends Zend_Form +{ + /** * Build easy form * * @return void */ - public function init() { + public function init() + { $sureyes = new Zend_Form_Element_Submit('sureyes'); $sureyes->setLabel('answer_yes'); @@ -46,7 +49,7 @@ public function init() { $sureno->setLabel('answer_no'); #$id = new Zend_Form_Element_Hidden('id'); - - $this->addElements(array($sureyes, $sureno)); + + $this->addElements([$sureyes, $sureno]); } -} \ No newline at end of file +} From f82ed450e44fa980eae13cfb4ccc7b1e0000e1e4 Mon Sep 17 00:00:00 2001 From: BioFreak95 Date: Thu, 18 Oct 2018 17:08:14 +0200 Subject: [PATCH 085/128] OPUSVIER-3899 codingstyle and change JS to OOP --- .../View/Helper/JavascriptTranslation.php | 6 +- public/layouts/opus4/common.phtml | 1 - public/layouts/opus4/js/validation.js | 153 +++++++++--------- .../View/Helper/JavascriptTranslationTest.php | 24 +-- 4 files changed, 95 insertions(+), 89 deletions(-) diff --git a/library/Application/View/Helper/JavascriptTranslation.php b/library/Application/View/Helper/JavascriptTranslation.php index 3ab9d87a0..eecd8128f 100644 --- a/library/Application/View/Helper/JavascriptTranslation.php +++ b/library/Application/View/Helper/JavascriptTranslation.php @@ -33,15 +33,15 @@ class Application_View_Helper_JavascriptTranslation extends Application_View_Helper_Abstract { - protected $translations = []; + private $translations = []; public function javascriptTranslation() { $output = '"; + $output .= " " . "" . "\n"; return $output; } diff --git a/public/layouts/opus4/common.phtml b/public/layouts/opus4/common.phtml index 8d17847c7..91d3b3c21 100644 --- a/public/layouts/opus4/common.phtml +++ b/public/layouts/opus4/common.phtml @@ -143,7 +143,6 @@ if (isset($config->javascript->latex->mathjax)) { javascriptTranslation() ?> - diff --git a/public/layouts/opus4/js/validation.js b/public/layouts/opus4/js/validation.js index 63f050b45..4d21e30ae 100644 --- a/public/layouts/opus4/js/validation.js +++ b/public/layouts/opus4/js/validation.js @@ -34,62 +34,29 @@ var messages = { identifierInvalidFormat: "\'%value%\' is malformed" }; -function validateISSN(value) { - // check length - if (value.length !== 9) { - return messages.identifierInvalidFormat.replace("%value%", value); - } - - // check form - if (value.match(/^[0-9]{4}[-][0-9]{3}[0-9X]$/g) === null) { - return messages.identifierInvalidFormat.replace("%value%", value); - } - - // Split ISSN into its parts - var issn = value.split(""); - - // Calculate and compare check digit - var checkdigit = calculateCheckDigitISSN(issn); - if (checkdigit != issn[8]) { - return messages.identifierInvalidCheckdigit.replace("%value%", value); - } - - return true; -} - -function calculateCheckDigitISSN(value) { - var z = value; - var checkdigit = 0; - var check = (8 * z[0] + 7 * z[1] + 6 * z[2] + 5 * z[3] + 4 * z[5] + 3 * z[6] + 2 * z[7]); - if (11 - (check % 11) === 10) { - checkdigit = "X"; - } else { - checkdigit = 11 - (check % 11); - } - - return checkdigit; -} +var IsbnValidation = function () { +}; -function validateISBN(value) { - var isbnDigits = splitISBN(value); +IsbnValidation.prototype.validateISBN = function (value) { + var isbnDigits = this.splitIsbn(value); if (isbnDigits.length === 10) { - return validateISBN10(value); + return this.validateISBN10(value); } else if (isbnDigits.length === 13) { - return validateISBN13(value); + return this.validateISBN13(value); } else { return messages.identifierInvalidFormat.replace("%value%", value); } -} +}; -function validateISBN10(value) { - if (value.length !== 10 && value.length !== 13) { +IsbnValidation.prototype.validateISBN13 = function (value) { + if (value.length !== 13 && value.length !== 17) { return messages.identifierInvalidFormat.replace("%value%", value); } - if (value.match(/^[\d]*((-|\s)?[\d]*){2}((-|\s)?[\dX])$/g) === null) { + if (value.match(/^(978|979)((-|\s)?[\d]*){4}$/g) === null) { return messages.identifierInvalidFormat.replace("%value%", value); } @@ -97,20 +64,20 @@ function validateISBN10(value) { return messages.identifierInvalidFormat.replace("%value%", value); } - var isbnDigits = splitISBN(value); - if (calculateCheckDigitISBN10(isbnDigits) === false) { + var isbnDigits = this.splitIsbn(value); + if (this.calculateCheckDigitISBN13(isbnDigits) === false) { return messages.identifierInvalidCheckdigit.replace("%value%", value); } return true; -} +}; -function validateISBN13(value) { - if (value.length !== 13 && value.length !== 17) { +IsbnValidation.prototype.validateISBN10 = function (value) { + if (value.length !== 10 && value.length !== 13) { return messages.identifierInvalidFormat.replace("%value%", value); } - if (value.match(/^(978|979)((-|\s)?[\d]*){4}$/g) === null) { + if (value.match(/^[\d]*((-|\s)?[\d]*){2}((-|\s)?[\dX])$/g) === null) { return messages.identifierInvalidFormat.replace("%value%", value); } @@ -118,15 +85,31 @@ function validateISBN13(value) { return messages.identifierInvalidFormat.replace("%value%", value); } - var isbnDigits = splitISBN(value); - if (calculateCheckDigitISBN13(isbnDigits) === false) { + var isbnDigits = this.splitIsbn(value); + if (this.calculateCheckDigitISBN10(isbnDigits) === false) { return messages.identifierInvalidCheckdigit.replace("%value%", value); } return true; -} +}; -function calculateCheckDigitISBN10(value) { +IsbnValidation.prototype.splitIsbn = function (value) { + var isbn = value.split(/(-|\s)/); + var digits = []; + isbn.forEach(function (isbn) { + if (isbn.match((/(-|\s)/))) { + return true; + } + var isbn_parts = isbn.split(""); + isbn_parts.forEach(function (isbn_parts) { + digits.push(isbn_parts); + }); + }); + + return digits; +}; + +IsbnValidation.prototype.calculateCheckDigitISBN10 = function (value) { var z = value; if (z[9] === "X") { @@ -136,30 +119,53 @@ function calculateCheckDigitISBN10(value) { var check = 10 * z[0] + 9 * z[1] + 8 * z[2] + 7 * z[3] + 6 * z[4] + 5 * z[5] + 4 * z[6] + 3 * z[7] + 2 * z[8] + 1 * z[9]; return (check % 11 === 0); -} +}; -function calculateCheckDigitISBN13(value) { +IsbnValidation.prototype.calculateCheckDigitISBN13 = function (value) { var z = value.map(Number); var check = (z[0] + z[2] + z[4] + z[6] + z[8] + z[10] + z[12]) + 3 * (z[1] + z[3] + z[5] + z[7] + z[9] + z[11]); return (check % 10 === 0); -} +}; -function splitISBN(value) { - var isbn = value.split(/(-|\s)/); - var digits = []; - isbn.forEach(function (isbn) { - if (isbn.match((/(-|\s)/))) { - return true; - } - var isbn_parts = isbn.split(""); - isbn_parts.forEach(function (isbn_parts) { - digits.push(isbn_parts); - }); - }); +var IssnValidation = function () { +}; - return digits; -} +IssnValidation.prototype.validateISSN = function (value) { + // check length + if (value.length !== 9) { + return messages.identifierInvalidFormat.replace("%value%", value); + } + + // check form + if (value.match(/^[0-9]{4}[-][0-9]{3}[0-9X]$/g) === null) { + return messages.identifierInvalidFormat.replace("%value%", value); + } + + // Split ISSN into its parts + var issn = value.split(""); + + // Calculate and compare check digit + var checkdigit = this.calculateCheckDigitISSN(issn); + if (checkdigit != issn[8]) { + return messages.identifierInvalidCheckdigit.replace("%value%", value); + } + + return true; +}; + +IssnValidation.prototype.calculateCheckDigitISSN = function (value) { + var z = value; + var checkdigit = 0; + var check = (8 * z[0] + 7 * z[1] + 6 * z[2] + 5 * z[3] + 4 * z[5] + 3 * z[6] + 2 * z[7]); + if (11 - (check % 11) === 10) { + checkdigit = "X"; + } else { + checkdigit = 11 - (check % 11); + } + + return checkdigit; +}; $(document).ready(function () { var selectors = []; @@ -186,11 +192,12 @@ $(document).ready(function () { $.each(identifierText, function (index, value) { value.onchange = function () { if (selectors[index] === "isbn") { - result = validateISBN(value.value); + var isbnValidator = new IsbnValidation(); + result = isbnValidator.validateISBN(value.value); } else if (selectors[index] === "issn") { - - result = validateISSN(value.value); + var issnValidator = new IssnValidation(); + result = issnValidator.validateISSN(value.value); } else { result = true; diff --git a/tests/library/Application/View/Helper/JavascriptTranslationTest.php b/tests/library/Application/View/Helper/JavascriptTranslationTest.php index 623585642..efab765c1 100644 --- a/tests/library/Application/View/Helper/JavascriptTranslationTest.php +++ b/tests/library/Application/View/Helper/JavascriptTranslationTest.php @@ -33,7 +33,7 @@ class Application_View_Helper_JavascriptTranslationTest extends ControllerTestCase { - private $_helper; + private $helper; public function setUp() { @@ -41,9 +41,9 @@ public function setUp() $this->useEnglish(); - $this->_helper = new Application_View_Helper_JavascriptTranslation(); + $this->helper = new Application_View_Helper_JavascriptTranslation(); - $this->_helper->setView(Zend_Registry::get('Opus_View')); + $this->helper->setView(Zend_Registry::get('Opus_View')); } public function testJavascriptTranslation() @@ -52,22 +52,22 @@ public function testJavascriptTranslation() 'key1' => 'message1', 'key2' => 'message2' ]; - $this->_helper->setTranslations($translations); + $this->helper->setTranslations($translations); $expectation = ''; - $reality = $this->_helper->javascriptTranslation(); + $reality = $this->helper->javascriptTranslation(); $this->assertEquals($expectation, $reality); } public function testAddTranslation() { - $this->_helper->addTranslation('key1', 'message1'); - $this->_helper->addTranslation('identifierInvalidFormat'); - $this->_helper->addTranslation('testkey'); + $this->helper->addTranslation('key1', 'message1'); + $this->helper->addTranslation('identifierInvalidFormat'); + $this->helper->addTranslation('testkey'); $translations = [ 'key1' => 'message1', @@ -75,7 +75,7 @@ public function testAddTranslation() 'testkey' => 'testkey' ]; - $this->assertEquals($translations, $this->_helper->getTranslations()); + $this->assertEquals($translations, $this->helper->getTranslations()); } public function testSetTranslations() @@ -84,12 +84,12 @@ public function testSetTranslations() 'key1' => 'message1', 'key2' => 'message2' ]; - $this->_helper->setTranslations($translations); - $this->assertEquals($translations, $this->_helper->getTranslations()); + $this->helper->setTranslations($translations); + $this->assertEquals($translations, $this->helper->getTranslations()); } public function testGetTranslations() { - $this->assertEquals([], $this->_helper->getTranslations()); + $this->assertEquals([], $this->helper->getTranslations()); } } From 7b45e71fc8bb72910fca84dbb98dfeed790115f2 Mon Sep 17 00:00:00 2001 From: j3nsch Date: Mon, 22 Oct 2018 14:30:03 +0200 Subject: [PATCH 086/128] OPUSVIER-3541 Coding style. Use constants. --- modules/admin/forms/YesNoForm.php | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/modules/admin/forms/YesNoForm.php b/modules/admin/forms/YesNoForm.php index 89e73cd2f..1a12c51ca 100644 --- a/modules/admin/forms/YesNoForm.php +++ b/modules/admin/forms/YesNoForm.php @@ -35,6 +35,10 @@ class Admin_Form_YesNoForm extends Zend_Form { + const ELEMENT_YES = 'sureyes'; + + const ELEMENT_NO = 'sureno'; + /** * Build easy form for yes/no questions. * @@ -42,14 +46,12 @@ class Admin_Form_YesNoForm extends Zend_Form */ public function init() { - $sureyes = new Zend_Form_Element_Submit('sureyes'); + $sureyes = new Zend_Form_Element_Submit(self::ELEMENT_YES); $sureyes->setLabel('answer_yes'); - $sureno = new Zend_Form_Element_Submit('sureno'); + $sureno = new Zend_Form_Element_Submit(self::ELEMENT_NO); $sureno->setLabel('answer_no'); - #$id = new Zend_Form_Element_Hidden('id'); - $this->addElements([$sureyes, $sureno]); } } From 01a60f2f09fd44ab8ebd84a4ed7d0627af9caae8 Mon Sep 17 00:00:00 2001 From: BioFreak95 Date: Tue, 23 Oct 2018 14:50:22 +0200 Subject: [PATCH 087/128] OPUSVIER-3899 Documentation, codingstyle and change mapping of messages --- .../View/Helper/JavascriptTranslation.php | 12 +++++-- public/layouts/opus4/js/validation.js | 32 +++++++++---------- .../View/Helper/JavascriptTranslationTest.php | 19 +++++++++++ 3 files changed, 45 insertions(+), 18 deletions(-) diff --git a/library/Application/View/Helper/JavascriptTranslation.php b/library/Application/View/Helper/JavascriptTranslation.php index eecd8128f..662f772af 100644 --- a/library/Application/View/Helper/JavascriptTranslation.php +++ b/library/Application/View/Helper/JavascriptTranslation.php @@ -31,6 +31,12 @@ * @license http://www.gnu.org/licenses/gpl.html General Public License */ +/** + * Class Application_View_Helper_JavascriptTranslation + * This view-helper creates a code snippet, what is able to deliver the translations for javascript files. + * With addTranslation, there is an possibility to add an translation-key to the code snippet. + * The key will be translated and the message will be delivered. It is also possible to insert your own key-message pair. + */ class Application_View_Helper_JavascriptTranslation extends Application_View_Helper_Abstract { private $translations = []; @@ -38,8 +44,10 @@ class Application_View_Helper_JavascriptTranslation extends Application_View_Hel public function javascriptTranslation() { $output = '" . "\n"; diff --git a/public/layouts/opus4/js/validation.js b/public/layouts/opus4/js/validation.js index 4d21e30ae..ca4a4c06d 100644 --- a/public/layouts/opus4/js/validation.js +++ b/public/layouts/opus4/js/validation.js @@ -29,10 +29,10 @@ * @license http://www.gnu.org/licenses/gpl.html General Public License */ -var messages = { - identifierInvalidCheckdigit: "The check digit of \'%value%\' is not valid", - identifierInvalidFormat: "\'%value%\' is malformed" -}; +var messages = []; +messages["identifierInvalidCheckdigit"] = "The check digit of \'%value%\' is not valid"; +messages["identifierInvalidFormat"] = "\'%value%\' is malformed"; + var IsbnValidation = function () { }; @@ -47,26 +47,26 @@ IsbnValidation.prototype.validateISBN = function (value) { return this.validateISBN13(value); } else { - return messages.identifierInvalidFormat.replace("%value%", value); + return messages["identifierInvalidFormat"].replace("%value%", value); } }; IsbnValidation.prototype.validateISBN13 = function (value) { if (value.length !== 13 && value.length !== 17) { - return messages.identifierInvalidFormat.replace("%value%", value); + return messages["identifierInvalidFormat"].replace("%value%", value); } if (value.match(/^(978|979)((-|\s)?[\d]*){4}$/g) === null) { - return messages.identifierInvalidFormat.replace("%value%", value); + return messages["identifierInvalidFormat"].replace("%value%", value); } if (value.match(/-/) !== null && value.match(/\s/) !== null) { - return messages.identifierInvalidFormat.replace("%value%", value); + return messages["identifierInvalidFormat"].replace("%value%", value); } var isbnDigits = this.splitIsbn(value); if (this.calculateCheckDigitISBN13(isbnDigits) === false) { - return messages.identifierInvalidCheckdigit.replace("%value%", value); + return messages["identifierInvalidCheckdigit"].replace("%value%", value); } return true; @@ -74,20 +74,20 @@ IsbnValidation.prototype.validateISBN13 = function (value) { IsbnValidation.prototype.validateISBN10 = function (value) { if (value.length !== 10 && value.length !== 13) { - return messages.identifierInvalidFormat.replace("%value%", value); + return messages["identifierInvalidFormat"].replace("%value%", value); } if (value.match(/^[\d]*((-|\s)?[\d]*){2}((-|\s)?[\dX])$/g) === null) { - return messages.identifierInvalidFormat.replace("%value%", value); + return messages["identifierInvalidFormat"].replace("%value%", value); } if (value.match(/-/) !== null && value.match(/\s/) !== null) { - return messages.identifierInvalidFormat.replace("%value%", value); + return messages["identifierInvalidFormat"].replace("%value%", value); } var isbnDigits = this.splitIsbn(value); if (this.calculateCheckDigitISBN10(isbnDigits) === false) { - return messages.identifierInvalidCheckdigit.replace("%value%", value); + return messages["identifierInvalidCheckdigit"].replace("%value%", value); } return true; @@ -134,12 +134,12 @@ var IssnValidation = function () { IssnValidation.prototype.validateISSN = function (value) { // check length if (value.length !== 9) { - return messages.identifierInvalidFormat.replace("%value%", value); + return messages["identifierInvalidFormat"].replace("%value%", value); } // check form if (value.match(/^[0-9]{4}[-][0-9]{3}[0-9X]$/g) === null) { - return messages.identifierInvalidFormat.replace("%value%", value); + return messages["identifierInvalidFormat"].replace("%value%", value); } // Split ISSN into its parts @@ -148,7 +148,7 @@ IssnValidation.prototype.validateISSN = function (value) { // Calculate and compare check digit var checkdigit = this.calculateCheckDigitISSN(issn); if (checkdigit != issn[8]) { - return messages.identifierInvalidCheckdigit.replace("%value%", value); + return messages["identifierInvalidCheckdigit"].replace("%value%", value); } return true; diff --git a/tests/library/Application/View/Helper/JavascriptTranslationTest.php b/tests/library/Application/View/Helper/JavascriptTranslationTest.php index efab765c1..f00ba3a6d 100644 --- a/tests/library/Application/View/Helper/JavascriptTranslationTest.php +++ b/tests/library/Application/View/Helper/JavascriptTranslationTest.php @@ -46,6 +46,9 @@ public function setUp() $this->helper->setView(Zend_Registry::get('Opus_View')); } + /** + * Tests, if the correct code-snippet for the translation will be generated. + */ public function testJavascriptTranslation() { $translations = [ @@ -63,6 +66,9 @@ public function testJavascriptTranslation() $this->assertEquals($expectation, $reality); } + /** + * Tests, if the addTranslation-function translates in the correct way and deliver the correct key-message pairs. + */ public function testAddTranslation() { $this->helper->addTranslation('key1', 'message1'); @@ -88,6 +94,19 @@ public function testSetTranslations() $this->assertEquals($translations, $this->helper->getTranslations()); } + /** + * If the translations are empty or set to null, the code snippet for the translation without any key-message pairs + * should be delivered. This is tested here. + */ + public function testSetNullTranslations() + { + $this->helper->setTranslations(null); + $reality = $this->helper->javascriptTranslation(); + $expectation = '' . "\n"; + $this->assertEquals($expectation, $reality); + } + public function testGetTranslations() { $this->assertEquals([], $this->helper->getTranslations()); From ee66bd0a019832a05583d16874281dd171db6034 Mon Sep 17 00:00:00 2001 From: j3nsch Date: Tue, 23 Oct 2018 15:28:57 +0200 Subject: [PATCH 088/128] OPUSVIER-3541 Coding style. --- modules/admin/forms/Notification.php | 19 +++++++++---------- 1 file changed, 9 insertions(+), 10 deletions(-) diff --git a/modules/admin/forms/Notification.php b/modules/admin/forms/Notification.php index 50ec20050..d0efc7cdc 100644 --- a/modules/admin/forms/Notification.php +++ b/modules/admin/forms/Notification.php @@ -47,15 +47,15 @@ public function init() $translator = $this->getTranslator(); - $this->addElement('note', 'description', array( + $this->addElement('note', 'description', [ 'value' => "

          {$translator->translate('admin_workflow_notification_description')}

          " - )); + ]); - $this->setDecorators(array( + $this->setDecorators([ 'FormElements', - array('ViewScript', array('viewScript' => 'multicheckboxtable.phtml')), - array('Fieldset', array('class' => 'headline')), - )); + ['ViewScript', ['viewScript' => 'multicheckboxtable.phtml']], + ['Fieldset', ['class' => 'headline']], + ]); } /** @@ -131,13 +131,12 @@ public function personToArray($person) $disabled = true; } - $option = array( + $option = [ 'name' => $person->getDisplayName(), 'email' => $email, 'disabled' => $disabled - ); + ]; return $option; } - -} \ No newline at end of file +} From c9d4e4949a109ca14e821eeb0aa26940fd0d8ae7 Mon Sep 17 00:00:00 2001 From: j3nsch Date: Tue, 23 Oct 2018 15:31:30 +0200 Subject: [PATCH 089/128] OPUSVIER-3541 Switch to WorkflowNotification form. Not finished. The form is not working properly yet. The differnet pieces need to be connected. --- library/Application/Util/Notification.php | 239 +++++------ .../Util/PublicationNotification.php | 121 ++++++ .../admin/controllers/WorkflowController.php | 11 +- modules/admin/forms/DocumentStateChange.php | 157 -------- modules/admin/forms/WorkflowNotification.php | 102 ++++- .../Application/Util/NotificationTest.php | 371 ++++-------------- .../Util/PublicationNotificationTest.php | 330 ++++++++++++++++ .../admin/forms/WorkflowNotificationTest.php | 210 ++++++++++ 8 files changed, 939 insertions(+), 602 deletions(-) create mode 100644 library/Application/Util/PublicationNotification.php delete mode 100644 modules/admin/forms/DocumentStateChange.php create mode 100644 tests/library/Application/Util/PublicationNotificationTest.php create mode 100644 tests/modules/admin/forms/WorkflowNotificationTest.php diff --git a/library/Application/Util/Notification.php b/library/Application/Util/Notification.php index 0b588d253..bdda53a74 100644 --- a/library/Application/Util/Notification.php +++ b/library/Application/Util/Notification.php @@ -27,47 +27,36 @@ * @category Application * @package Notification * @author Sascha Szott - * @copyright Copyright (c) 2012, OPUS 4 development team + * @copyright Copyright (c) 2012-2018, OPUS 4 development team * @license http://www.gnu.org/licenses/gpl.html General Public License - * @version $Id$ + * + * TODO remove concept of 'context' - class should not implement different context variations (use OO principles) */ +class Application_Util_Notification extends Application_Model_Abstract +{ -class Application_Util_Notification { - - const SUBMISSION = "submission"; - const PUBLICATION = "publication"; - - private $_logger; - private $_config; - - public function __construct($logger = null, $config = null) { - $this->_logger = is_null($logger) ? Zend_Registry::get('Zend_Log') : $logger; - $this->_config = is_null($config) ? Zend_Registry::get('Zend_Config') : $config; + public function __construct($logger = null, $config = null) + { + $this->setConfig($config); + $this->setLogger($logger); } /** * * @param Opus_Document $document das Dokument auf das sich die Notifizierung bezieht - * @param String $context Notifizierungskontext * @param String $url vollständiger Deeplink, der in der Mail angezeigt werden soll * @param boolean $notifySubmitter Wenn false, wird der Submitter nicht notifiziert * @param array $notifyAuthors Bitmaske, die für jeden Autor (über den Index referenziert) angibt, ob ihm/ihr eine * E-Mail gesendet werden kann (wenn false, dann wird keine Notifizierung versendet) */ - public function prepareMail($document, $context, $url, $notifySubmitter = true, $notifyAuthors = array()) { - if (!$this->validateContext($context)) { - $this->_logger->err( - "context $context is currently not supported or delivery of notification mails is not" - . ' enabled for the current context' - ); - return; - } + public function prepareMail($document, $url, $notifySubmitter = true, $notifyAuthors = []) + { + $logger = $this->getLogger(); - $this->_logger->info("prepare $context notification email for document id " . $document->getId()); + $logger->info("prepare notification email for document id " . $document->getId()); - $authorAddresses = array(); - $authors = array(); - $title = ""; + $authorAddresses = []; + $authors = []; $personAuthors = $document->getPersonAuthor(); if (!empty($personAuthors)) { @@ -76,40 +65,26 @@ public function prepareMail($document, $context, $url, $notifySubmitter = true, // TODO Komma nur wenn FirstName present $name = trim($author->getLastName() . ", " . $author->getFirstName()); array_push($authors, $name); - if ($context == self::PUBLICATION) { - $email = trim($author->getEmail()); - if (!empty($email) && (empty($notifyAuthors) || (isset($notifyAuthors[$index]) - && $notifyAuthors[$index]))) { - array_push($authorAddresses, array( "name" => $name, "address" => $email)); - } - } + $index++; } } - // TODO Funktionalität existiert bereits (Documents Helper oder so) - $titlesMain = $document->getTitleMain(); - if (!empty($titlesMain)) { - // ermittle (den ersten) TitleMain in Dokumentsprache - $language = $document->getLanguage(); - foreach ($titlesMain as $titleMain) { - if ($titleMain->getLanguage() == $language) { - $title = trim($titleMain->getValue()); - break; - } - } - } + $title = $document->getMainTitle(); $this->scheduleNotification( - $this->getMailSubject($context, $document->getId(), $authors, $title), - $this->getMailBody($context, $document->getId(), $authors, $title, $url), - $this->getRecipients($context, $authorAddresses, $document, $notifySubmitter) + $this->getMailSubject($document->getId(), $authors, $title), + $this->getMailBody($document->getId(), $authors, $title, $url), + $this->getRecipients($authorAddresses, $document, $notifySubmitter) ); - $this->_logger->info("$context notification mail creation was completed successfully"); + $logger->info("notification mail creation was completed successfully"); } - private function getMailSubject($context, $docId, $authors, $title) { + private function getMailSubject($docId, $authors, $title) + { + $logger = $this->getLogger(); + $authorString = ""; for ($i = 0; $i < count($authors); $i++) { if ($i > 0) { @@ -123,34 +98,43 @@ private function getMailSubject($context, $docId, $authors, $title) { if ($title == "") { $title = "n/a"; } - if ($context == self::SUBMISSION && isset($this->_config->notification->document->submitted->subject)) { - return sprintf($this->_config->notification->document->submitted->subject, $docId, $authorString, $title); - } - if ($context == self::PUBLICATION && isset($this->_config->notification->document->published->subject)) { - return sprintf($this->_config->notification->document->published->subject, $docId, $authorString, $title); + + $subjectTemplate = $this->getSubjectTemplate(); + + if (strlen(trim($subjectTemplate)) > 0) { + return sprintf($subjectTemplate, $docId, $authorString, $title); + } else { + $logger->err("could not construct mail subject based on application configuration"); + return ''; } - $this->_logger->err("could not construct mail subject based on application configuration"); } - private function getMailBody($context, $docId, $authors, $title, $url) { - if ($context == self::SUBMISSION && isset($this->_config->notification->document->submitted->template)) { - return $this->getTemplate( - $this->_config->notification->document->submitted->template, $docId, $authors, - $title, $url - ); + public function getSubjectTemplate() + { + $config = $this->getConfig(); + + if (isset($config->notification->document->submitted->subject)) { + return $config->notification->document->submitted->subject; } - if ($context == self::PUBLICATION && isset($this->_config->notification->document->published->template)) { + } + + public function getMailBody($docId, $authors, $title, $url) + { + $config = $this->getConfig(); + + if (isset($config->notification->document->submitted->template)) { return $this->getTemplate( - $this->_config->notification->document->published->template, $docId, $authors, + $config->notification->document->submitted->template, $docId, $authors, $title, $url ); } } - private function getTemplate($template, $docId, $authors, $title, $url) { + public function getTemplate($template, $docId, $authors, $title, $url) + { $templateFileName = APPLICATION_PATH . '/application/configs/mail_templates/' . $template; if (!is_file($templateFileName)) { - $this->_logger->err( + $this->getLogger()->err( "could not find mail template based on application configuration: '$templateFileName'" . ' does not exist or is not readable' ); @@ -171,125 +155,100 @@ private function getTemplate($template, $docId, $authors, $title, $url) { return $body; } - private function getRecipients($context, $authorAddresses = null, $document = null, $notifySubmitter = true) { - $addresses = array(); - - switch ($context) { - case self::SUBMISSION: - if (isset($this->_config->notification->document->submitted->email)) { - $addresses = $this->buildAddressesArray( - $context, - $this->_config->notification->document->submitted->email - ); - } - break; - - case self::PUBLICATION: - if (isset($this->_config->notification->document->published->email)) { - $addresses = $this->buildAddressesArray( - $context, - $this->_config->notification->document->published->email - ); - } + public function getRecipients($authorAddresses = null, $document = null, $notifySubmitter = true) + { + $config = $this->getConfig(); - for ($i = 0; $i < count($authorAddresses); $i++) { - $authorAddress = $authorAddresses[$i]; - array_push($addresses, $authorAddress); - $this->_logger->debug( - "send $context notification mail to author " . $authorAddress['address'] - . " (" . $authorAddress['name'] . ")" - ); - } + $addresses = []; - if ($notifySubmitter && !is_null($document)) { - $submitter = $document->getPersonSubmitter(); - if (!empty($submitter)) { - $name = trim($submitter[0]->getLastName() . ", " . $submitter[0]->getFirstName()); - $email = trim($submitter[0]->getEmail()); - if (!empty($email)) { - array_push($addresses, array( "name" => $name , "address" => $email)); - $this->_logger->debug("send $context notification mail to submitter $email ($name)"); - } - } - } - break; - - default: - $addresses = null; - break; + if (isset($config->notification->document->submitted->email)) { + $addresses = $this->buildAddressesArray( + $config->notification->document->submitted->email + ); } return $addresses; } - private function buildAddressesArray($context, $emails) { - $addresses = array(); + public function buildAddressesArray($emails) + { + $addresses = []; if (strlen(trim($emails)) > 0) { foreach (explode(",", $emails) as $address) { $address = trim($address); - $this->_logger->debug("send $context notification mail to $address"); - array_push($addresses, array("name" => $address, "address" => $address)); + $this->getLogger()->debug("send notification mail to $address"); + array_push($addresses, ["name" => $address, "address" => $address]); } } return $addresses; } - private function validateContext($context) { - if ($context == self::SUBMISSION) { - return isset($this->_config->notification->document->submitted->enabled) - && $this->_config->notification->document->submitted->enabled == 1; - } - if ($context == self::PUBLICATION) { - return isset($this->_config->notification->document->published->enabled) - && $this->_config->notification->document->published->enabled == 1;; - } - $this->_logger->err("Email notification mechanism is not supported for context '$context'"); - return false; + /** + * @return bool + * @throws Zend_Exception + * + * TODO should this class be responsible for this decision? + */ + public function isEnabled() + { + $config = $this->getConfig(); + + return isset($config->notification->document->published->enabled) + && $config->notification->document->published->enabled == 1; } - private function scheduleNotification($subject, $message, $recipients) { + /** + * @param $subject + * @param $message + * @param $recipients + * @throws Opus_Model_Exception + * + * TODO the code here should not decide if synchronous or asynchronous - create a job and go (either way) + * TODO the code here should not filter recipients (that should have happened earlier) + */ + private function scheduleNotification($subject, $message, $recipients) + { if (empty($recipients)) { - $this->_logger->warn("No recipients could be determined for email notification: skip operation"); + $this->getLogger()->warn("No recipients could be determined for email notification: skip operation"); return; } - $addressesUsed = array(); + $addressesUsed = []; foreach ($recipients as $recipient) { + // only send if email address has not been used before if (!in_array($recipient['address'], $addressesUsed)) { $job = new Opus_Job(); $job->setLabel(Opus_Job_Worker_MailNotification::LABEL); - $job->setData( - array( + $job->setData([ 'subject' => $subject, 'message' => $message, - 'users' => array($recipient) - ) - ); + 'users' => [$recipient] + ]); + + $config = $this->getConfig(); - if (isset($this->_config->runjobs->asynchronous) && $this->_config->runjobs->asynchronous) { + if (isset($config->runjobs->asynchronous) && $config->runjobs->asynchronous) { // Queue job (execute asynchronously) // skip creating job if equal job already exists if (true === $job->isUniqueInQueue()) { $job->store(); } - } - else { + } else { // Execute job immediately (synchronously) try { - $mail = new Opus_Job_Worker_MailNotification($this->_logger, false); + $mail = new Opus_Job_Worker_MailNotification($this->getLogger(), false); $mail->work($job); } catch (Exception $exc) { - $this->_logger->err("Email notification failed: ".$exc); + $this->getLogger()->err("Email notification failed: " . $exc); } } - array_push($addressesUsed, $recipient['address']); + $addressesUsed[] = $recipient['address']; } } - } } diff --git a/library/Application/Util/PublicationNotification.php b/library/Application/Util/PublicationNotification.php new file mode 100644 index 000000000..852eb06b3 --- /dev/null +++ b/library/Application/Util/PublicationNotification.php @@ -0,0 +1,121 @@ + + * @copyright Copyright (c) 2018, OPUS 4 development team + * @license http://www.gnu.org/licenses/gpl.html General Public License + */ + +/** + * Email notification class for PUBLICATION context. + * + * TODO this is just a first step in refactoring Application_Util_Notification + */ +class Application_Util_PublicationNotification extends Application_Util_Notification +{ + + /* + * TODO old prepareMail code to get author emails in proper format + * + * if ($context == self::PUBLICATION) { + $email = trim($author->getEmail()); + if (!empty($email) && (empty($notifyAuthors) || (isset($notifyAuthors[$index]) + && $notifyAuthors[$index]))) { + array_push($authorAddresses, array( "name" => $name, "address" => $email)); + } + } + */ + + public function getRecipients($authorAddresses = null, $document = null, $notifySubmitter = true) + { + $addresses = []; + + $config = $this->getConfig(); + $logger = $this->getLogger(); + + if (isset($config->notification->document->published->email)) { + $addresses = $this->buildAddressesArray( + $config->notification->document->published->email + ); + } + + for ($i = 0; $i < count($authorAddresses); $i++) { + $authorAddress = $authorAddresses[$i]; + array_push($addresses, $authorAddress); + $logger->debug( + "send publication notification mail to author " . $authorAddress['address'] + . " (" . $authorAddress['name'] . ")" + ); + } + + if ($notifySubmitter && !is_null($document)) { + $submitter = $document->getPersonSubmitter(); + if (!empty($submitter)) { + $name = trim($submitter[0]->getLastName() . ", " . $submitter[0]->getFirstName()); + $email = trim($submitter[0]->getEmail()); + if (!empty($email)) { + array_push($addresses, ["name" => $name , "address" => $email]); + $logger->debug("send publication notification mail to submitter $email ($name)"); + } + } + } + + return $addresses; + } + + public function getMailBody($docId, $authors, $title, $url) + { + $config = $this->getConfig(); + + if (isset($config->notification->document->published->template)) { + return $this->getTemplate( + $config->notification->document->published->template, $docId, $authors, + $title, $url + ); + } + } + + public function isEnabled() + { + $config = $this->getConfig(); + + return isset($config->notification->document->published->enabled) + && $config->notification->document->published->enabled == 1; + } + + public function getSubjectTemplate() + { + $config = $this->getConfig(); + + if (isset($config->notification->document->published->subject)) { + return $config->notification->document->published->subject; + } + } + + +} diff --git a/modules/admin/controllers/WorkflowController.php b/modules/admin/controllers/WorkflowController.php index b8ebb3557..5164cad49 100644 --- a/modules/admin/controllers/WorkflowController.php +++ b/modules/admin/controllers/WorkflowController.php @@ -37,6 +37,8 @@ /** * Controller handles transitions of documents between states. + * + * TODO use id instead of docId like DocumentController */ class Admin_WorkflowController extends Application_Controller_Action { @@ -175,9 +177,13 @@ private function _changeState($document, $targetState, $form = null) ); } + /** + * @param $document + * @param null $form + */ private function _sendNotification($document, $form = null) { - $notification = new Application_Util_Notification(); + $notification = new Application_Util_PublicationNotification(); $url = $this->view->url([ "module" => "frontdoor", "controller" => "index", @@ -203,7 +209,6 @@ private function _sendNotification($document, $form = null) $notification->prepareMail( $document, - Application_Util_Notification::PUBLICATION, $this->view->serverUrl() . $url, $notifySubmitter, $authorsBitmask @@ -219,7 +224,7 @@ private function _sendNotification($document, $form = null) */ private function _getConfirmationForm($document, $targetState) { - $form = new Admin_Form_DocumentStateChange($targetState); + $form = new Admin_Form_WorkflowNotification($targetState); $form->populateFromModel($document); diff --git a/modules/admin/forms/DocumentStateChange.php b/modules/admin/forms/DocumentStateChange.php deleted file mode 100644 index 2372e2a6e..000000000 --- a/modules/admin/forms/DocumentStateChange.php +++ /dev/null @@ -1,157 +0,0 @@ - - * @copyright Copyright (c) 2018, OPUS 4 development team - * @license http://www.gnu.org/licenses/gpl.html General Public License - */ - -/** - * Form for confirming state changes for a document and selecting persons for notification messages. - * - * TODO use displaygroup/subform for list of persons (encapsulate for reuse?) - * TODO handle label and description in a better way - */ -class Admin_Form_DocumentStateChange extends Admin_Form_YesNoForm -{ - - const ELEMENT_ID = 'id'; - - private $targetState; - - public function __construct($targetState, $options = null) - { - parent::__construct($options); - $this->setTargetState($targetState); - } - - public function init() - { - parent::init(); - $idElement = new Zend_Form_Element_Hidden(self::ELEMENT_ID); - $this->addElement($idElement); - } - - public function setTargetState($targetState) - { - $this->targetState = $targetState; - } - - public function getTargetState() - { - return $this->targetState; - } - - public function populateFromModel($document) - { - $this->getElement(self::ELEMENT_ID)->setValue($document->getId()); - - $config = Zend_Registry::get('Zend_Config'); - - if ($this->getTargetState() == 'published' && $this->isNotificationEnabled()) { - $this->addPublishNotificationSelection($document); - } - } - - public function isNotificationEnabled() - { - $config = Zend_Registry::get('Zend_Config'); - - return ((isset($config->notification->document->published->enabled) - && $config->notification->document->published->enabled == 1)); - } - - /** - * Add a checkbox for each PersonSubmitter and PersonAuthor (used to select - * recipients for publish notification email) - * - * @param Opus_Document $document - */ - protected function addPublishNotificationSelection($document) - { - $translator = $this->getTranslator(); - - $this->addElement('hidden', 'plaintext', [ - 'description' => '

          ' . $translator->translate('admin_workflow_notification_headline') - . '

          ' - . '

          ' . $translator->translate('admin_workflow_notification_description') . '

          ', - 'ignore' => true, - 'decorators' => [['Description', ['escape' => false, 'tag' => '']]] - ]); - - $submitters = $document->getPersonSubmitter(); - if (!is_null($submitters) && count($submitters) > 0) { - $label = $translator->translate('admin_workflow_notification_submitter') . ' ' - . trim($submitters[0]->getLastName()) . ", " . trim($submitters[0]->getFirstName()); - $element = null; - if (trim($submitters[0]->getEmail()) == '') { - // email notification is not possible since no email address is specified for submitter - $label .= ' (' . $translator->translate('admin_workflow_notification_noemail') . ')'; - $element = new Zend_Form_Element_Checkbox( - 'submitter', ['checked' => false, 'disabled' => true, - 'label' => $label] - ); - $element->getDecorator('Label')->setOption('class', 'notification-option option-not-available'); - } - else { - $label .= ' (' . trim($submitters[0]->getEmail()) . ')'; - $element = new Zend_Form_Element_Checkbox('submitter', ['checked' => true, 'label' => $label]); - $element->getDecorator('Label')->setOption('class', 'notification-option'); - } - $this->addElement($element); - } - - $authors = $document->getPersonAuthor(); - if (!is_null($authors)) { - $index = 1; - foreach ($authors as $author) { - $id = 'author_' . $index; - $label = $index . '. ' . $translator->translate('admin_workflow_notification_author') . ' ' - . trim($author->getLastName()) . ", " . trim($author->getFirstName()); - $element = null; - if (trim($author->getEmail()) == '') { - // email notification is not possible since no email address is specified for author - $label .= ' (' . $translator->translate('admin_workflow_notification_noemail') . ')'; - $element = new Zend_Form_Element_Checkbox( - $id, ['checked' => false, 'disabled' => true, 'label' => $label] - ); - $element->getDecorator('Label')->setOption('class', 'notification-option option-not-available'); - } - else { - $label .= ' (' . trim($author->getEmail()) . ')'; - $element = new Zend_Form_Element_Checkbox( - $id, ['checked' => true, 'label' => 'foo', 'label' => $label] - ); - $element->getDecorator('Label')->setOption('class', 'notification-option'); - } - $this->addElement($element); - $index++; - } - } - } -} diff --git a/modules/admin/forms/WorkflowNotification.php b/modules/admin/forms/WorkflowNotification.php index 87a5035db..e9864b579 100644 --- a/modules/admin/forms/WorkflowNotification.php +++ b/modules/admin/forms/WorkflowNotification.php @@ -35,6 +35,14 @@ class Admin_Form_WorkflowNotification extends Admin_Form_YesNoForm const ELEMENT_ID = 'id'; + private $targetState; + + public function __construct($targetState, $options = null) + { + parent::__construct($options); + $this->setTargetState($targetState); + } + public function init() { parent::init(); @@ -42,6 +50,24 @@ public function init() $this->addElement('hidden', self::ELEMENT_ID); } + public function setTargetState($targetState) + { + $this->targetState = $targetState; + } + + public function getTargetState() + { + return $this->targetState; + } + + public function isNotificationEnabled() + { + $config = Zend_Registry::get('Zend_Config'); + + return ((isset($config->notification->document->published->enabled) + && $config->notification->document->published->enabled == 1)); + } + /** * add a checkbox for each PersonSubmitter and PersonAuthor (used to select * recipients for publish notification email) @@ -50,11 +76,79 @@ public function init() * @param Zend_Form $form * */ - public function addPublishNotificationSelection($document) { - $subform = new Admin_Form_Notification(); - $subform->addPublishNotificationSelection($document); + public function populateFromModel($document) + { + $this->getElement(self::ELEMENT_ID)->setValue($document->getId()); - $this->addSubForm($subform, 'notification'); + if ($this->getTargetState() == 'published' && $this->isNotificationEnabled()) { + $subform = new Admin_Form_Notification(); + $subform->addPublishNotificationSelection($document); + $this->addSubForm($subform, 'notification'); + } } + /** + * Returns list of recipients for document state change notifications. + * + * For each recipient name, email and role(s) are returned. + * + * Ignore persons without email. + * + * @param $document + * TODO should not be part of the form class (encapsulate in different class) + */ + public function getRecipients($document) { + $recipients = []; + + $authors = $document->getPersonAuthor(); + $this->addPersons($recipients, $authors); + + $submitters = $document->getPersonSubmitter(); + $this->addPersons($recipients, $submitters, 'submitter'); + + return $recipients; + } + + protected function addPersons(&$recipients, $persons, $role = 'author') + { + foreach ($persons as $person) { + $fullname = $person->getDisplayName(); + $email = $person->getEmail(); + if (strlen(trim($email)) > 0) { + if (array_key_exists($email, $recipients)) { + $entry = $recipients[$email]; + $names = $entry['name']; + + if (!is_array($names) && $names !== $fullname || + is_array($names) && !in_array($fullname, $names)) { + if (!is_array($names)) { + $names = [$names]; + } + + $names[] = $fullname; + $entry['name'] = $names; + } + + $roles = $entry['role']; + + if (!is_array($roles) && $roles !== $role || + is_array($roles) && !in_array($role, $roles)) { + if (!is_array($roles)) { + $roles = [$roles]; + + $roles[] = $role; + $entry['role'] = $roles; + } + } + + $recipients[$email] = $entry; + } else { + $recipients[$email] = [ + 'name' => $fullname, + 'role' => $role + ]; + } + } + } + } } diff --git a/tests/library/Application/Util/NotificationTest.php b/tests/library/Application/Util/NotificationTest.php index 2d3e1e279..5244e0dc8 100644 --- a/tests/library/Application/Util/NotificationTest.php +++ b/tests/library/Application/Util/NotificationTest.php @@ -27,20 +27,22 @@ * @category Application * @package Tests * @author Sascha Szott - * @copyright Copyright (c) 2008-2012, OPUS 4 development team + * @author Jens Schwidder + * @copyright Copyright (c) 2008-2018, OPUS 4 development team * @license http://www.gnu.org/licenses/gpl.html General Public License - * @version $Id$ */ -class Application_Util_NotificationTest extends ControllerTestCase { +class Application_Util_NotificationTest extends ControllerTestCase +{ - private $notification; + protected $notification; - private $logger; + protected $logger; - private $config; + protected $config; - public function setUp() { + public function setUp() + { parent::setUp(); $this->notification = new Application_Util_Notification(); $this->logger = Zend_Registry::get('Zend_Log'); @@ -60,7 +62,8 @@ public function setUp() { * Diese Testmethode hat keine Assertions. Sie stellt lediglich sicher, dass alle Codeteile * der Funktion prepareMail durchlaufen werden. */ - public function testPrepareMailForSubmissionContext() { + public function testPrepareMailForSubmissionContext() + { $doc = $this->createTestDocument(); $doc->setLanguage("eng"); @@ -70,120 +73,43 @@ public function testPrepareMailForSubmissionContext() { $doc->addTitleMain($title); $doc->store(); - $this->notification->prepareMail($doc, Application_Util_Notification::SUBMISSION, 'http://localhost/foo/1'); + $this->notification->prepareMail($doc, 'http://localhost/foo/1'); } - /** - * Diese Testmethode hat keine Assertions. Sie stellt lediglich sicher, dass alle Codeteile - * der Funktion prepareMail durchlaufen werden. - */ - public function testPrepareMailForPublicationContext() { - $doc = $this->createTestDocument(); - $doc->setLanguage("eng"); - - $title = new Opus_Title(); - $title->setValue("Test Document"); - $title->setLanguage("eng"); - $doc->addTitleMain($title); - - $author = new Opus_Person(); - $author->setFirstName("John"); - $author->setLastName("Doe"); - $doc->addPersonAuthor($author); - - $author = new Opus_Person(); - $author->setFirstName("John With Address"); - $author->setLastName("Doe"); - $author->setEmail("doe@localhost.de"); - $doc->addPersonAuthor($author); - - $submitter = new Opus_Person(); - $submitter->setFirstName("John"); - $submitter->setLastName("Submitter"); - $submitter->setEmail("sub@localhost.de"); - $doc->addPersonSubmitter($submitter); - - $doc->store(); - $this->notification->prepareMail($doc, Application_Util_Notification::PUBLICATION, 'http://localhost/foo/1'); - } - - public function testValidateContextWithSubmissionContext() { - $method = $this->getMethod('validateContext'); - $this->assertTrue($method->invokeArgs($this->notification, array(Application_Util_Notification::SUBMISSION))); - } - - public function testValidateContextWithSubmissionContextAndDisabledSubmissionNotification() { - $this->config->notification->document->submitted->enabled = 0; - $method = $this->getMethod('validateContext'); - $this->assertFalse($method->invokeArgs($this->notification, array(Application_Util_Notification::SUBMISSION))); - } - - public function testValidateContextWithPublicationContext() { - $method = $this->getMethod('validateContext'); - $this->assertTrue($method->invokeArgs($this->notification, array(Application_Util_Notification::PUBLICATION))); - } - - public function testValidateContextWithPublishedContextAndDisabledPublicationNotification() { - $this->config->notification->document->published->enabled = 0; - $method = $this->getMethod('validateContext'); - $this->assertFalse($method->invokeArgs($this->notification, array(Application_Util_Notification::PUBLICATION))); - } - - public function testValidateContextWithUnknownContext() { - $method = $this->getMethod('validateContext'); - $this->assertFalse($method->invokeArgs($this->notification, array('deleted'))); - } - - public function testValidateContextWithContextNull() { - $method = $this->getMethod('validateContext'); - $this->assertFalse($method->invokeArgs($this->notification, array(null))); - } - - public function testGetSubmissionMailSubjectWithEmptyAuthorsAndEmptyTitle() { + public function testGetSubmissionMailSubjectWithEmptyAuthorsAndEmptyTitle() + { $method = $this->getMethod('getMailSubject'); - $subject = $method->invokeArgs($this->notification, array(Application_Util_Notification::SUBMISSION, "123", array(), "")); + $subject = $method->invokeArgs($this->notification, ["123", [], ""]); $this->assertEquals("Dokument #123 eingestellt: n/a : n/a", $subject); } - public function testGetSubmissionMailSubjectWithOneAuthor() { + public function testGetSubmissionMailSubjectWithOneAuthor() + { $method = $this->getMethod('getMailSubject'); - $subject = $method->invokeArgs($this->notification, array(Application_Util_Notification::SUBMISSION, "123", array("Doe, John"), "Test Document")); + $subject = $method->invokeArgs( + $this->notification, + ["123", ["Doe, John"], "Test Document"] + ); $this->assertEquals("Dokument #123 eingestellt: Doe, John : Test Document", $subject); } - public function testGetSubmissionMailSubjectWithTwoAuthors() { + public function testGetSubmissionMailSubjectWithTwoAuthors() + { $method = $this->getMethod('getMailSubject'); - $subject = $method->invokeArgs($this->notification, array(Application_Util_Notification::SUBMISSION, "123", array("Doe, John", "Doe, Jane"), "Test Document")); + $subject = $method->invokeArgs( + $this->notification, + ["123", ["Doe, John", "Doe, Jane"], "Test Document"] + ); $this->assertEquals("Dokument #123 eingestellt: Doe, John ; Doe, Jane : Test Document", $subject); } - public function testGetPublicationMailSubjectWithEmptyAuthorsAndEmptyTitle() { - $method = $this->getMethod('getMailSubject'); - $subject = $method->invokeArgs($this->notification, array(Application_Util_Notification::PUBLICATION, "123", array(), "")); - $this->assertEquals("Dokument #123 veröffentlicht: n/a : n/a", $subject); - } - - public function testGetPublicationMailSubjectWithOneAuthor() { - $method = $this->getMethod('getMailSubject'); - $subject = $method->invokeArgs($this->notification, array(Application_Util_Notification::PUBLICATION, "123", array("Doe, John"), "Test Document")); - $this->assertEquals("Dokument #123 veröffentlicht: Doe, John : Test Document", $subject); - } - - public function testGetPublicationMailSubjectWithTwoAuthors() { - $method = $this->getMethod('getMailSubject'); - $subject = $method->invokeArgs($this->notification, array(Application_Util_Notification::PUBLICATION, "123", array("Doe, John", "Doe, Jane"), "Test Document")); - $this->assertEquals("Dokument #123 veröffentlicht: Doe, John ; Doe, Jane : Test Document", $subject); - } - - public function testGetMailSubjectWithInvalidContext() { - $method = $this->getMethod('getMailSubject'); - $subject = $method->invokeArgs($this->notification, array("deleted", "123", array("Doe, John", "Doe, Jane"), "Test Document")); - $this->assertNull($subject); - } - - public function testGetSubmissionMailBodyWithEmptyAuthorsAndEmptyTitle() { + public function testGetSubmissionMailBodyWithEmptyAuthorsAndEmptyTitle() + { $method = $this->getMethod('getMailBody'); - $body = $method->invokeArgs($this->notification, array(Application_Util_Notification::SUBMISSION, "123", array(), "", "http://localhost/foo/1")); + $body = $method->invokeArgs( + $this->notification, + ["123", [], "", "http://localhost/foo/1"] + ); $this->assertContains("Autor(en): n/a", $body); $this->assertContains("Titel: n/a", $body); $this->assertContains("Dokument-ID: 123", $body); @@ -191,9 +117,13 @@ public function testGetSubmissionMailBodyWithEmptyAuthorsAndEmptyTitle() { $this->assertContains("Ein neues Dokument wurde auf Ihrem OPUS4-Dokumentenserver hochgeladen", $body); } - public function testGetSubmissionMailBodyWithTwoAuthorsAndNonEmptyTitle() { + public function testGetSubmissionMailBodyWithTwoAuthorsAndNonEmptyTitle() + { $method = $this->getMethod('getMailBody'); - $body = $method->invokeArgs($this->notification, array(Application_Util_Notification::SUBMISSION, "123", array( "Doe, John", "Doe, Jane" ), "Test Title", "http://localhost/foo/1")); + $body = $method->invokeArgs( + $this->notification, + ["123", ["Doe, John", "Doe, Jane"], "Test Title", "http://localhost/foo/1"] + ); $this->assertContains("Autor(en):\nDoe, John\nDoe, Jane", $body); $this->assertContains("Titel: Test Title", $body); $this->assertContains("Dokument-ID: 123", $body); @@ -201,64 +131,39 @@ public function testGetSubmissionMailBodyWithTwoAuthorsAndNonEmptyTitle() { $this->assertContains("Ein neues Dokument wurde auf Ihrem OPUS4-Dokumentenserver hochgeladen", $body); } - public function testGetPublicationMailBodyWithEmptyAuthorsAndEmptyTitle() { - $method = $this->getMethod('getMailBody'); - $body = $method->invokeArgs($this->notification, array(Application_Util_Notification::PUBLICATION, "123", array(), "", "http://localhost/foo/1")); - $this->assertContains("Autor(en): n/a", $body); - $this->assertContains("Titel: n/a", $body); - $this->assertContains("Dokument-ID: 123", $body); - $this->assertContains("http://localhost/foo/1", $body); - $this->assertContains("Folgendes Dokument wurde auf dem OPUS4-Dokumentenserver freigegeben", $body); - } - - public function testGetPublicationMailBodyWithTwoAuthorsAndNonEmptyTitle() { - $method = $this->getMethod('getMailBody'); - $body = $method->invokeArgs($this->notification, array(Application_Util_Notification::PUBLICATION, "123", array( "Doe, John", "Doe, Jane" ), "Test Title", "http://localhost/foo/1")); - $this->assertContains("Autor(en):\nDoe, John\nDoe, Jane", $body); - $this->assertContains("Titel: Test Title", $body); - $this->assertContains("Dokument-ID: 123", $body); - $this->assertContains("http://localhost/foo/1", $body); - $this->assertContains("Folgendes Dokument wurde auf dem OPUS4-Dokumentenserver freigegeben", $body); - } - - public function testGetMailBodyWithInvalidContext() { - $method = $this->getMethod('getMailBody'); - $body = $method->invokeArgs($this->notification, array("deleted", "123", array(), "Test Document", "http://localhost/foo/1")); - $this->assertNull($body); - } - - public function testGetSubmissionMailBodyWithUnknownTemplateFile() { + public function testGetSubmissionMailBodyWithUnknownTemplateFile() + { $this->config->notification->document->submitted->template = 'does-not-exist.phtml'; $method = $this->getMethod('getMailBody'); - $body = $method->invokeArgs($this->notification, array(Application_Util_Notification::SUBMISSION, "123", array(), "Test Document", "http://localhost/foo/1")); + $body = $method->invokeArgs( + $this->notification, + ["123", [], "Test Document", "http://localhost/foo/1"] + ); $this->assertNull($body); } - public function testGetRecipientsWithInvalidContext() { + public function testGetRecipientsForSubmissionContext() + { $method = $this->getMethod('getRecipients'); - $recipients = $method->invokeArgs($this->notification, array("deleted")); - $this->assertNull($recipients); - } - - public function testGetRecipientsForSubmissionContext() { - $method = $this->getMethod('getRecipients'); - $recipients = $method->invokeArgs($this->notification, array(Application_Util_Notification::SUBMISSION)); + $recipients = $method->invoke($this->notification); $this->assertEquals(1, count($recipients)); $this->assertEquals($recipients[0]['name'], "submitted@localhost"); $this->assertEquals($recipients[0]['address'], "submitted@localhost"); } - public function testGetRecipientsForSubmissionContextWithoutSubmittedMailConfig() { + public function testGetRecipientsForSubmissionContextWithoutSubmittedMailConfig() + { $this->config->notification->document->submitted->email = ""; $method = $this->getMethod('getRecipients'); - $recipients = $method->invokeArgs($this->notification, array(Application_Util_Notification::SUBMISSION)); + $recipients = $method->invoke($this->notification); $this->assertEquals(0, count($recipients)); } - public function testGetRecipientsForSubmissionContextAndMultipleAddresses() { + public function testGetRecipientsForSubmissionContextAndMultipleAddresses() + { $this->config->notification->document->submitted->email = "submitted@localhost,sub@host.tld"; $method = $this->getMethod('getRecipients'); - $recipients = $method->invokeArgs($this->notification, array(Application_Util_Notification::SUBMISSION)); + $recipients = $method->invoke($this->notification); $this->assertEquals(2, count($recipients)); $this->assertEquals($recipients[0]['name'], "submitted@localhost"); $this->assertEquals($recipients[0]['address'], "submitted@localhost"); @@ -266,130 +171,12 @@ public function testGetRecipientsForSubmissionContextAndMultipleAddresses() { $this->assertEquals($recipients[1]['address'], "sub@host.tld"); } - public function testGetRecipientsForPublicationContextWithoutAuthorsAsRecipents() { - $doc = $this->createTestDocument(); - $doc->store(); - $method = $this->getMethod('getRecipients'); - $recipients = $method->invokeArgs($this->notification, array(Application_Util_Notification::PUBLICATION, array(), $doc)); - $this->assertEquals(1, count($recipients)); - $this->assertEquals($recipients[0]['name'], "published@localhost"); - $this->assertEquals($recipients[0]['address'], "published@localhost"); - } - - public function testGetRecipientsForPublicationContextWithoutPublishedMailConfig() { - $this->config->notification->document->published->email = ""; - $method = $this->getMethod('getRecipients'); - $recipients = $method->invokeArgs($this->notification, array(Application_Util_Notification::PUBLICATION)); - $this->assertEquals(0, count($recipients)); - } - - public function testGetRecipientsForPublicationContextWithoutPublishedMailConfigButWithAuthors() { - $this->config->notification->document->published->email = ""; - $doc = $this->createTestDocument(); - $doc->store(); - - $authors = array( - array ( "name" => "Doe, John", "address" => "doe@localhost" ), - array ( "name" => "Doe, Jane", "address" => "jane.doe@localhost" ) - ); - - $method = $this->getMethod('getRecipients'); - $recipients = $method->invokeArgs($this->notification, array(Application_Util_Notification::PUBLICATION, $authors, $doc)); - - $this->assertEquals(2, count($recipients)); - $this->assertEquals($recipients[0]['name'], "Doe, John"); - $this->assertEquals($recipients[0]['address'], "doe@localhost"); - $this->assertEquals($recipients[1]['name'], "Doe, Jane"); - $this->assertEquals($recipients[1]['address'], "jane.doe@localhost"); - } - - public function testGetRecipientsForPublicationContextAndMultipleAddressesWithoutAuthorsAsRecipents() { - $this->config->notification->document->published->email = "published@localhost,publ@host.tld"; - $doc = $this->createTestDocument(); - $doc->store(); - $method = $this->getMethod('getRecipients'); - $recipients = $method->invokeArgs($this->notification, array(Application_Util_Notification::PUBLICATION, array(), $doc)); - - $this->assertEquals(2, count($recipients)); - $this->assertEquals($recipients[0]['name'], "published@localhost"); - $this->assertEquals($recipients[0]['address'], "published@localhost"); - $this->assertEquals($recipients[1]['name'], "publ@host.tld"); - $this->assertEquals($recipients[1]['address'], "publ@host.tld"); - } - - public function testGetRecipientsForPublicationContextWithAuthorsAsRecipents() { - $this->config->notification->document->published->email = "published@localhost"; - $doc = $this->createTestDocument(); - $doc->store(); - - $authors = array( - array ( "name" => "Doe, John", "address" => "doe@localhost" ), - array ( "name" => "Doe, Jane", "address" => "jane.doe@localhost" ) - ); - - $method = $this->getMethod('getRecipients'); - $recipients = $method->invokeArgs($this->notification, array(Application_Util_Notification::PUBLICATION, $authors, $doc)); - - $this->assertEquals(3, count($recipients)); - $this->assertEquals($recipients[0]['name'], "published@localhost"); - $this->assertEquals($recipients[0]['address'], "published@localhost"); - $this->assertEquals($recipients[1]['name'], "Doe, John"); - $this->assertEquals($recipients[1]['address'], "doe@localhost"); - $this->assertEquals($recipients[2]['name'], "Doe, Jane"); - $this->assertEquals($recipients[2]['address'], "jane.doe@localhost"); - } - - public function testGetRecipientsForPublicationContextWithSubmitterAsRecipient() { - $this->config->notification->document->published->email = "published@localhost"; - $doc = $this->createTestDocument(); - $submitter = new Opus_Person(); - $submitter->setFirstName('John'); - $submitter->setLastName('Submitter'); - $submitter->setEmail('john.submitter@localhost.de'); - $doc->addPersonSubmitter($submitter); - $doc->store(); - - $authors = array( - array ( "name" => "Doe, John", "address" => "doe@localhost" ), - array ( "name" => "Doe, Jane", "address" => "jane.doe@localhost" ) - ); - - $method = $this->getMethod('getRecipients'); - $recipients = $method->invokeArgs($this->notification, array(Application_Util_Notification::PUBLICATION, $authors, $doc)); - - $this->assertEquals(4, count($recipients)); - $this->assertEquals($recipients[0]['name'], "published@localhost"); - $this->assertEquals($recipients[0]['address'], "published@localhost"); - $this->assertEquals($recipients[1]['name'], "Doe, John"); - $this->assertEquals($recipients[1]['address'], "doe@localhost"); - $this->assertEquals($recipients[2]['name'], "Doe, Jane"); - $this->assertEquals($recipients[2]['address'], "jane.doe@localhost"); - $this->assertEquals($recipients[3]['name'], "Submitter, John"); - $this->assertEquals($recipients[3]['address'], "john.submitter@localhost.de"); - } - - public function testGetRecipientsForPublicationContextWithSubmitterWithoutMailAddressAsRecipient() { - $this->config->notification->document->published->email = "published@localhost"; - $doc = $this->createTestDocument(); - $submitter = new Opus_Person(); - $submitter->setFirstName('John'); - $submitter->setLastName('Submitter'); - $doc->addPersonSubmitter($submitter); - $doc->store(); - - $method = $this->getMethod('getRecipients'); - $recipients = $method->invokeArgs($this->notification, array(Application_Util_Notification::PUBLICATION, array(), $doc)); - - $this->assertEquals(1, count($recipients)); - $this->assertEquals($recipients[0]['name'], "published@localhost"); - $this->assertEquals($recipients[0]['address'], "published@localhost"); - } - /** * Diese Testmethode hat keine Assertions. Sie stellt lediglich sicher, dass alle Codeteile * der Funktion prepareMail durchlaufen werden. */ - public function testPrepareMailWithTwoOptionalArgs() { + public function testPrepareMailWithTwoOptionalArgs() + { $doc = $this->createTestDocument(); $doc->setLanguage("eng"); @@ -417,36 +204,23 @@ public function testPrepareMailWithTwoOptionalArgs() { $doc->addPersonSubmitter($submitter); $doc->store(); - $this->notification->prepareMail($doc, Application_Util_Notification::PUBLICATION, 'http://localhost/foo/1', false, array(false, true)); + $this->notification->prepareMail( + $doc, 'http://localhost/foo/1', false, [false, true] + ); } - public function testGetRecipientsForPublicationContextWithoutSubmitter() { - $doc = $this->createTestDocument(); - $doc->setLanguage("eng"); - - $title = new Opus_Title(); - $title->setValue("Test Document"); - $title->setLanguage("eng"); - $doc->addTitleMain($title); - - $submitter = new Opus_Person(); - $submitter->setFirstName("John"); - $submitter->setLastName("Submitter"); - $submitter->setEmail("sub@localhost.de"); - $doc->addPersonSubmitter($submitter); + public function testCreateWorkerJobIfAsyncEnabled() + { + // TODO use Opus_Job::deleteAll() - requires opus4admin permissions ! + $jobs = Opus_Job::getAll(); - $doc->store(); - $method = $this->getMethod('getRecipients'); - $recipients = $method->invokeArgs($this->notification, array(Application_Util_Notification::PUBLICATION, array(array("name" => "foo", "address" => "foo@localhost")), $doc, false)); - $this->assertEquals(2, count($recipients)); - $this->assertEquals("published@localhost", $recipients[0]["name"]); - $this->assertEquals("published@localhost", $recipients[0]["address"]); - $this->assertEquals("foo", $recipients[1]["name"]); - $this->assertEquals("foo@localhost", $recipients[1]["address"]); - } + if(!empty($jobs)) { + foreach($jobs as $job) { + $job->delete(); + } + } - public function testCreateWorkerJobIfAsyncEnabled() { - $this->config->merge(new Zend_Config(array('runjobs' => array('asynchronous' => 1)))); + $this->config->merge(new Zend_Config(['runjobs' => ['asynchronous' => 1]])); $this->assertEquals(0, Opus_Job::getCount(), 'test data changed.'); $doc = $this->createTestDocument(); @@ -458,9 +232,9 @@ public function testCreateWorkerJobIfAsyncEnabled() { $doc->addTitleMain($title); $doc->store(); - $this->notification->prepareMail($doc, Application_Util_Notification::SUBMISSION, 'http://localhost/foo/1'); + $this->notification->prepareMail($doc, 'http://localhost/foo/1'); - $mailJobs = Opus_Job::getByLabels(array(Opus_Job_Worker_MailNotification::LABEL)); + $mailJobs = Opus_Job::getByLabels([Opus_Job_Worker_MailNotification::LABEL]); $this->assertEquals(1, count($mailJobs), 'Expected 1 mail job'); @@ -473,7 +247,8 @@ public function testCreateWorkerJobIfAsyncEnabled() { } } - private function getMethod($methodName) { + protected function getMethod($methodName) + { $class = new ReflectionClass('Application_Util_Notification'); $method = $class->getMethod($methodName); $method->setAccessible(true); diff --git a/tests/library/Application/Util/PublicationNotificationTest.php b/tests/library/Application/Util/PublicationNotificationTest.php new file mode 100644 index 000000000..563a7d55b --- /dev/null +++ b/tests/library/Application/Util/PublicationNotificationTest.php @@ -0,0 +1,330 @@ + + * @copyright Copyright (c) 2018, OPUS 4 development team + * @license http://www.gnu.org/licenses/gpl.html General Public License + */ + +class Application_Util_PublicationNotificationTest extends ControllerTestCase +{ + + protected $notification; + + protected $logger; + + protected $config; + + public function setUp() + { + parent::setUp(); + $this->notification = new Application_Util_PublicationNotification(); + $this->logger = Zend_Registry::get('Zend_Log'); + // add required config keys + $this->config = Zend_Registry::get('Zend_Config'); + $this->config->notification->document->submitted->enabled = 1; + $this->config->notification->document->published->enabled = 1; + $this->config->notification->document->submitted->subject = 'Dokument #%1$s eingestellt: %2$s : %3$s'; + $this->config->notification->document->published->subject = 'Dokument #%1$s veröffentlicht: %2$s : %3$s'; + $this->config->notification->document->submitted->template = 'submitted.phtml'; + $this->config->notification->document->published->template = 'published.phtml'; + $this->config->notification->document->submitted->email = "submitted@localhost"; + $this->config->notification->document->published->email = "published@localhost"; + } + + public function testGetRecipientsForPublicationContextWithoutAuthorsAsRecipents() + { + $doc = $this->createTestDocument(); + $doc->store(); + $method = $this->getMethod('getRecipients'); + $recipients = $method->invokeArgs($this->notification, [[], $doc]); + $this->assertEquals(1, count($recipients)); + $this->assertEquals('published@localhost', $recipients[0]['name']); + $this->assertEquals('published@localhost', $recipients[0]['address']); + } + + public function testGetRecipientsForPublicationContextWithoutPublishedMailConfig() + { + $this->config->notification->document->published->email = ""; + $method = $this->getMethod('getRecipients'); + $recipients = $method->invokeArgs($this->notification, []); + $this->assertEquals(0, count($recipients)); + } + + public function testGetRecipientsForPublicationContextWithoutPublishedMailConfigButWithAuthors() + { + $this->config->notification->document->published->email = ""; + $doc = $this->createTestDocument(); + $doc->store(); + + $authors = [ + ["name" => "Doe, John", "address" => "doe@localhost"], + ["name" => "Doe, Jane", "address" => "jane.doe@localhost"] + ]; + + $method = $this->getMethod('getRecipients'); + $recipients = $method->invokeArgs( + $this->notification, + [$authors, $doc] + ); + + $this->assertEquals(2, count($recipients)); + $this->assertEquals($recipients[0]['name'], "Doe, John"); + $this->assertEquals($recipients[0]['address'], "doe@localhost"); + $this->assertEquals($recipients[1]['name'], "Doe, Jane"); + $this->assertEquals($recipients[1]['address'], "jane.doe@localhost"); + } + + public function testGetRecipientsForPublicationContextAndMultipleAddressesWithoutAuthorsAsRecipents() + { + $this->config->notification->document->published->email = "published@localhost,publ@host.tld"; + $doc = $this->createTestDocument(); + $doc->store(); + $method = $this->getMethod('getRecipients'); + $recipients = $method->invokeArgs( + $this->notification, + [[], $doc] + ); + + $this->assertEquals(2, count($recipients)); + $this->assertEquals($recipients[0]['name'], "published@localhost"); + $this->assertEquals($recipients[0]['address'], "published@localhost"); + $this->assertEquals($recipients[1]['name'], "publ@host.tld"); + $this->assertEquals($recipients[1]['address'], "publ@host.tld"); + } + + public function testGetRecipientsForPublicationContextWithAuthorsAsRecipents() + { + $this->config->notification->document->published->email = "published@localhost"; + $doc = $this->createTestDocument(); + $doc->store(); + + $authors = [ + ["name" => "Doe, John", "address" => "doe@localhost"], + ["name" => "Doe, Jane", "address" => "jane.doe@localhost"] + ]; + + $method = $this->getMethod('getRecipients'); + $recipients = $method->invokeArgs( + $this->notification, + [$authors, $doc] + ); + + $this->assertEquals(3, count($recipients)); + $this->assertEquals($recipients[0]['name'], "published@localhost"); + $this->assertEquals($recipients[0]['address'], "published@localhost"); + $this->assertEquals($recipients[1]['name'], "Doe, John"); + $this->assertEquals($recipients[1]['address'], "doe@localhost"); + $this->assertEquals($recipients[2]['name'], "Doe, Jane"); + $this->assertEquals($recipients[2]['address'], "jane.doe@localhost"); + } + + public function testGetRecipientsForPublicationContextWithSubmitterAsRecipient() + { + $this->config->notification->document->published->email = "published@localhost"; + $doc = $this->createTestDocument(); + $submitter = new Opus_Person(); + $submitter->setFirstName('John'); + $submitter->setLastName('Submitter'); + $submitter->setEmail('john.submitter@localhost.de'); + $doc->addPersonSubmitter($submitter); + $doc->store(); + + $authors = [ + ["name" => "Doe, John", "address" => "doe@localhost"], + ["name" => "Doe, Jane", "address" => "jane.doe@localhost"] + ]; + + $method = $this->getMethod('getRecipients'); + $recipients = $method->invokeArgs( + $this->notification, + [$authors, $doc] + ); + + $this->assertEquals(4, count($recipients)); + $this->assertEquals($recipients[0]['name'], "published@localhost"); + $this->assertEquals($recipients[0]['address'], "published@localhost"); + $this->assertEquals($recipients[1]['name'], "Doe, John"); + $this->assertEquals($recipients[1]['address'], "doe@localhost"); + $this->assertEquals($recipients[2]['name'], "Doe, Jane"); + $this->assertEquals($recipients[2]['address'], "jane.doe@localhost"); + $this->assertEquals($recipients[3]['name'], "Submitter, John"); + $this->assertEquals($recipients[3]['address'], "john.submitter@localhost.de"); + } + + public function testGetRecipientsForPublicationContextWithSubmitterWithoutMailAddressAsRecipient() + { + $this->config->notification->document->published->email = "published@localhost"; + $doc = $this->createTestDocument(); + $submitter = new Opus_Person(); + $submitter->setFirstName('John'); + $submitter->setLastName('Submitter'); + $doc->addPersonSubmitter($submitter); + $doc->store(); + + $method = $this->getMethod('getRecipients'); + $recipients = $method->invokeArgs( + $this->notification, + [[], $doc] + ); + + $this->assertEquals(1, count($recipients)); + $this->assertEquals($recipients[0]['name'], "published@localhost"); + $this->assertEquals($recipients[0]['address'], "published@localhost"); + } + + public function testGetRecipientsForPublicationContextWithoutSubmitter() + { + $doc = $this->createTestDocument(); + $doc->setLanguage("eng"); + + $title = new Opus_Title(); + $title->setValue("Test Document"); + $title->setLanguage("eng"); + $doc->addTitleMain($title); + + $submitter = new Opus_Person(); + $submitter->setFirstName("John"); + $submitter->setLastName("Submitter"); + $submitter->setEmail("sub@localhost.de"); + $doc->addPersonSubmitter($submitter); + + $doc->store(); + $method = $this->getMethod('getRecipients'); + $recipients = $method->invokeArgs( + $this->notification, + [[["name" => "foo", "address" => "foo@localhost"]], $doc, false] + ); + $this->assertEquals(2, count($recipients)); + $this->assertEquals("published@localhost", $recipients[0]["name"]); + $this->assertEquals("published@localhost", $recipients[0]["address"]); + $this->assertEquals("foo", $recipients[1]["name"]); + $this->assertEquals("foo@localhost", $recipients[1]["address"]); + } + + protected function getMethod($methodName) + { + $class = new ReflectionClass('Application_Util_PublicationNotification'); + $method = $class->getMethod($methodName); + $method->setAccessible(true); + return $method; + } + + public function testGetPublicationMailBodyWithEmptyAuthorsAndEmptyTitle() + { + $method = $this->getMethod('getMailBody'); + $body = $method->invokeArgs( + $this->notification, + ["123", [], "", "http://localhost/foo/1"] + ); + $this->assertContains("Autor(en): n/a", $body); + $this->assertContains("Titel: n/a", $body); + $this->assertContains("Dokument-ID: 123", $body); + $this->assertContains("http://localhost/foo/1", $body); + $this->assertContains("Folgendes Dokument wurde auf dem OPUS4-Dokumentenserver freigegeben", $body); + } + + public function testGetPublicationMailBodyWithTwoAuthorsAndNonEmptyTitle() + { + $method = $this->getMethod('getMailBody'); + $body = $method->invokeArgs( + $this->notification, + ["123", ["Doe, John", "Doe, Jane"], "Test Title", "http://localhost/foo/1"] + ); + $this->assertContains("Autor(en):\nDoe, John\nDoe, Jane", $body); + $this->assertContains("Titel: Test Title", $body); + $this->assertContains("Dokument-ID: 123", $body); + $this->assertContains("http://localhost/foo/1", $body); + $this->assertContains("Folgendes Dokument wurde auf dem OPUS4-Dokumentenserver freigegeben", $body); + } + + /** + * Diese Testmethode hat keine Assertions. Sie stellt lediglich sicher, dass alle Codeteile + * der Funktion prepareMail durchlaufen werden. + */ + public function testPrepareMailForPublicationContext() + { + $doc = $this->createTestDocument(); + $doc->setLanguage("eng"); + + $title = new Opus_Title(); + $title->setValue("Test Document"); + $title->setLanguage("eng"); + $doc->addTitleMain($title); + + $author = new Opus_Person(); + $author->setFirstName("John"); + $author->setLastName("Doe"); + $doc->addPersonAuthor($author); + + $author = new Opus_Person(); + $author->setFirstName("John With Address"); + $author->setLastName("Doe"); + $author->setEmail("doe@localhost.de"); + $doc->addPersonAuthor($author); + + $submitter = new Opus_Person(); + $submitter->setFirstName("John"); + $submitter->setLastName("Submitter"); + $submitter->setEmail("sub@localhost.de"); + $doc->addPersonSubmitter($submitter); + + $doc->store(); + $this->notification->prepareMail($doc, 'http://localhost/foo/1'); + } + + public function testGetPublicationMailSubjectWithEmptyAuthorsAndEmptyTitle() + { + $method = $this->getMethod('getMailSubject'); + $subject = $method->invokeArgs( + $this->notification, + ["123", [], ""] + ); + $this->assertEquals("Dokument #123 veröffentlicht: n/a : n/a", $subject); + } + + public function testGetPublicationMailSubjectWithOneAuthor() + { + $method = $this->getMethod('getMailSubject'); + $subject = $method->invokeArgs( + $this->notification, + ["123", ["Doe, John"], "Test Document"] + ); + $this->assertEquals("Dokument #123 veröffentlicht: Doe, John : Test Document", $subject); + } + + public function testGetPublicationMailSubjectWithTwoAuthors() + { + $method = $this->getMethod('getMailSubject'); + $subject = $method->invokeArgs( + $this->notification, + ["123", ["Doe, John", "Doe, Jane"], "Test Document"] + ); + $this->assertEquals("Dokument #123 veröffentlicht: Doe, John ; Doe, Jane : Test Document", $subject); + } +} diff --git a/tests/modules/admin/forms/WorkflowNotificationTest.php b/tests/modules/admin/forms/WorkflowNotificationTest.php new file mode 100644 index 000000000..cddce1b10 --- /dev/null +++ b/tests/modules/admin/forms/WorkflowNotificationTest.php @@ -0,0 +1,210 @@ + + * @copyright Copyright (c) 2008-2018, OPUS 4 development team + * @license http://www.gnu.org/licenses/gpl.html General Public License + */ + +class Admin_Form_WorkflowNotificationTest extends ControllerTestCase +{ + + private $doc; + + protected function setUpTestDocument() + { + $doc = $this->createTestDocument(); + + $author = new Opus_Person(); + $author->setFirstName('John'); + $author->setLastName('Tester'); + $author->setEmail('john@example.org'); + $doc->addPersonAuthor($author); + + $author = new Opus_Person(); + $author->setFirstName('Jane'); + $author->setLastName('Doe'); + $author->setEmail('jane@example.org'); + $doc->addPersonAuthor($author); + + // This email is used twice for different authors (John & Anton) + $author = new Opus_Person(); + $author->setFirstName('Anton'); + $author->setLastName('Other'); + $author->setEmail('john@example.org'); + $doc->addPersonAuthor($author); + + // Jim doesn't have an email address and won't be a recipient + $author = new Opus_Person(); + $author->setFirstName('Jim'); + $author->setLastName('Busy'); + $doc->addPersonAuthor($author); + + // Jane is author and submitter + $submitter = new Opus_Person(); + $submitter->setFirstName('Jane'); + $submitter->setLastName('Doe'); + $submitter->setEmail('jane@example.org'); + $doc->addPersonSubmitter($submitter); + + // Bob is just submitter + $submitter = new Opus_Person(); + $submitter->setFirstName('Bob'); + $submitter->setLastName('Writer'); + $submitter->setEmail('bob@example.org'); + $doc->addPersonSubmitter($submitter); + + $this->doc = new Opus_Document($doc->store()); + } + + public function testGetRecipients() + { + $this->setUpTestDocument(); + + $form = new Admin_Form_DocumentStateChange('published'); + + $recipients = $form->getRecipients($this->doc); + + $this->assertEquals([ + 'john@example.org' => [ + 'name' => [ + 'Tester, John', + 'Other, Anton' + ], + 'role' => 'author' + ], + 'jane@example.org' => [ + 'name' => 'Doe, Jane', + 'role' => [ + 'author', + 'submitter' + ] + ], + 'bob@example.org' => [ + 'name' => 'Writer, Bob', + 'role' => 'submitter' + ] + ], $recipients); + } + + + /* TODO integrate or delete + * /** + * Add a checkbox for each PersonSubmitter and PersonAuthor (used to select + * recipients for publish notification email) + * + * @param Opus_Document $document + protected function addPublishNotificationSelection($document) + { + $translator = $this->getTranslator(); + + $elements = []; + + $recipients = $this->getRecipients($document); + + foreach ($recipients as $recipient) { + + } + + /** + $submitters = $document->getPersonSubmitter(); + + if (!is_null($submitters) && count($submitters) > 0) { + $label = $translator->translate('admin_workflow_notification_submitter') . ' ' + . trim($submitters[0]->getLastName()) . ", " . trim($submitters[0]->getFirstName()); + $element = null; + if (trim($submitters[0]->getEmail()) == '') { + // email notification is not possible since no email address is specified for submitter + $label .= ' (' . $translator->translate('admin_workflow_notification_noemail') . ')'; + $element = new Zend_Form_Element_Checkbox( + 'submitter', ['checked' => false, 'disabled' => true, + 'label' => $label] + ); + $element->getDecorator('Label')->setOption('class', 'notification-option option-not-available'); + } + else { + $label .= ' (' . trim($submitters[0]->getEmail()) . ')'; + $element = new Zend_Form_Element_Checkbox('submitter', ['checked' => true, 'label' => $label]); + $element->getDecorator('Label')->setOption('class', 'notification-option'); + } + $this->addElement($element); + $elements[] = $element->getName(); + } + + $authors = $document->getPersonAuthor(); + + if (!is_null($authors)) { + $index = 1; + foreach ($authors as $author) { + $id = 'author_' . $index; + $label = $index . '. ' . $translator->translate('admin_workflow_notification_author') . ' ' + . trim($author->getLastName()) . ", " . trim($author->getFirstName()); + $element = null; + if (trim($author->getEmail()) == '') { + // email notification is not possible since no email address is specified for author + $label .= ' (' . $translator->translate('admin_workflow_notification_noemail') . ')'; + $element = new Zend_Form_Element_Checkbox( + $id, ['checked' => false, 'disabled' => true, 'label' => $label] + ); + $element->getDecorator('Label')->setOption('class', 'notification-option option-not-available'); + } + else { + $label .= ' (' . trim($author->getEmail()) . ')'; + $element = new Zend_Form_Element_Checkbox( + $id, ['checked' => true, 'label' => 'foo', 'label' => $label] + ); + $element->getDecorator('Label')->setOption('class', 'notification-option'); + } + $this->addElement($element); + $elements[] = $element->getName(); + $index++; + } + } + + $this->addDisplayGroup($elements, 'notifications', [ + 'legend' => 'admin_workflow_notification_headline', + 'description' => 'admin_workflow_notification_description', + ]); + + $group = $this->getDisplayGroup('notifications'); + + $decorators = $group->getDecorators(); + + // TODO better way? encapsulation? + // TODO description is marked by CSS-class 'hint' + $group->setDecorators([ + $decorators['Zend_Form_Decorator_FormElements'], + $decorators['Zend_Form_Decorator_HtmlTag'], + ['description', ['escape' => false, 'placement' => 'PREPEND']], + $decorators['Zend_Form_Decorator_Fieldset'], + $decorators['Zend_Form_Decorator_DtDdWrapper'], + ]); + } + +*/ +} From 81a1c45d4f410fb6288811e2cff0d4b1625734f2 Mon Sep 17 00:00:00 2001 From: BioFreak95 Date: Thu, 25 Oct 2018 15:13:11 +0200 Subject: [PATCH 090/128] OPUSVIER-3899 Add Documentation to js-testfiles and some style-changes and requirements are implemented. --- tests/javascript/testIsbnValidation.html | 182 +++++------------------ tests/javascript/testIssnValidation.html | 47 ++---- 2 files changed, 52 insertions(+), 177 deletions(-) diff --git a/tests/javascript/testIsbnValidation.html b/tests/javascript/testIsbnValidation.html index 8cb8dc050..f3ec48487 100644 --- a/tests/javascript/testIsbnValidation.html +++ b/tests/javascript/testIsbnValidation.html @@ -27,6 +27,11 @@ * @author Maximilian Salomon * @copyright Copyright (c) 2018, OPUS 4 development team * @license http://www.gnu.org/licenses/gpl.html General Public License +* +* Test of public/layouts/opus4/js/validation.js +* In this file, the ISBN-validation with JS is tested. To see the test-results, you have to open this file in a browser. +* This tests the validateISBN(), validateISBN10 and validateISBN13() functions. +* The results are shown in three different tables. --> @@ -85,14 +90,19 @@ " . "\n"; @@ -54,23 +57,29 @@ public function javascriptTranslation() return $output; } - public function addTranslation($key, $message = null) + /** + * @param $key + * @param null $message contains an optional message + * + * Adds an Message to the viewHelper. If no message is handed, the function tries to translate the handed key. + */ + public function addMessage($key, $message = null) { if ($message != null) { - $this->translations[$key] = $message; + $this->javascriptMessages [$key] = $message; } else { $message = $this->view->translate($key); - $this->translations[$key] = $message; + $this->javascriptMessages [$key] = $message; } } - public function getTranslations() + public function getMessages() { - return $this->translations; + return $this->javascriptMessages; } - public function setTranslations($value) + public function setMessages($value) { - $this->translations = $value; + $this->javascriptMessages = $value; } } diff --git a/modules/admin/controllers/DocumentController.php b/modules/admin/controllers/DocumentController.php index 210fffe0a..57fddf3fb 100644 --- a/modules/admin/controllers/DocumentController.php +++ b/modules/admin/controllers/DocumentController.php @@ -229,9 +229,10 @@ public function editAction() { $this->renderForm($this->view->form); - $javascriptTranslations = $this->view->getHelper('javascriptTranslation'); - $javascriptTranslations->addTranslation('identifierInvalidFormat'); - $javascriptTranslations->addTranslation('identifierInvalidCheckdigit'); + // Adds translated messages for javascript files + $javascriptTranslations = $this->view->getHelper('javascriptMessages'); + $javascriptTranslations->addMessage('identifierInvalidFormat'); + $javascriptTranslations->addMessage('identifierInvalidCheckdigit'); } } diff --git a/public/layouts/opus4/common.phtml b/public/layouts/opus4/common.phtml index 91d3b3c21..24c643c6d 100644 --- a/public/layouts/opus4/common.phtml +++ b/public/layouts/opus4/common.phtml @@ -142,7 +142,7 @@ if (isset($config->javascript->latex->mathjax)) { - javascriptTranslation() ?> + javascriptMessages() ?> diff --git a/public/layouts/opus4/js/validation.js b/public/layouts/opus4/js/validation.js index ca4a4c06d..7a50b332f 100644 --- a/public/layouts/opus4/js/validation.js +++ b/public/layouts/opus4/js/validation.js @@ -29,9 +29,9 @@ * @license http://www.gnu.org/licenses/gpl.html General Public License */ -var messages = []; -messages["identifierInvalidCheckdigit"] = "The check digit of \'%value%\' is not valid"; -messages["identifierInvalidFormat"] = "\'%value%\' is malformed"; +var opus4Messages = []; +opus4Messages["identifierInvalidCheckdigit"] = "The check digit of \'%value%\' is not valid"; +opus4Messages["identifierInvalidFormat"] = "\'%value%\' is malformed"; var IsbnValidation = function () { @@ -47,26 +47,26 @@ IsbnValidation.prototype.validateISBN = function (value) { return this.validateISBN13(value); } else { - return messages["identifierInvalidFormat"].replace("%value%", value); + return opus4Messages["identifierInvalidFormat"].replace("%value%", value); } }; IsbnValidation.prototype.validateISBN13 = function (value) { if (value.length !== 13 && value.length !== 17) { - return messages["identifierInvalidFormat"].replace("%value%", value); + return opus4Messages["identifierInvalidFormat"].replace("%value%", value); } if (value.match(/^(978|979)((-|\s)?[\d]*){4}$/g) === null) { - return messages["identifierInvalidFormat"].replace("%value%", value); + return opus4Messages["identifierInvalidFormat"].replace("%value%", value); } if (value.match(/-/) !== null && value.match(/\s/) !== null) { - return messages["identifierInvalidFormat"].replace("%value%", value); + return opus4Messages["identifierInvalidFormat"].replace("%value%", value); } var isbnDigits = this.splitIsbn(value); if (this.calculateCheckDigitISBN13(isbnDigits) === false) { - return messages["identifierInvalidCheckdigit"].replace("%value%", value); + return opus4Messages["identifierInvalidCheckdigit"].replace("%value%", value); } return true; @@ -74,20 +74,20 @@ IsbnValidation.prototype.validateISBN13 = function (value) { IsbnValidation.prototype.validateISBN10 = function (value) { if (value.length !== 10 && value.length !== 13) { - return messages["identifierInvalidFormat"].replace("%value%", value); + return opus4Messages["identifierInvalidFormat"].replace("%value%", value); } if (value.match(/^[\d]*((-|\s)?[\d]*){2}((-|\s)?[\dX])$/g) === null) { - return messages["identifierInvalidFormat"].replace("%value%", value); + return opus4Messages["identifierInvalidFormat"].replace("%value%", value); } if (value.match(/-/) !== null && value.match(/\s/) !== null) { - return messages["identifierInvalidFormat"].replace("%value%", value); + return opus4Messages["identifierInvalidFormat"].replace("%value%", value); } var isbnDigits = this.splitIsbn(value); if (this.calculateCheckDigitISBN10(isbnDigits) === false) { - return messages["identifierInvalidCheckdigit"].replace("%value%", value); + return opus4Messages["identifierInvalidCheckdigit"].replace("%value%", value); } return true; @@ -134,12 +134,12 @@ var IssnValidation = function () { IssnValidation.prototype.validateISSN = function (value) { // check length if (value.length !== 9) { - return messages["identifierInvalidFormat"].replace("%value%", value); + return opus4Messages["identifierInvalidFormat"].replace("%value%", value); } // check form if (value.match(/^[0-9]{4}[-][0-9]{3}[0-9X]$/g) === null) { - return messages["identifierInvalidFormat"].replace("%value%", value); + return opus4Messages["identifierInvalidFormat"].replace("%value%", value); } // Split ISSN into its parts @@ -148,7 +148,7 @@ IssnValidation.prototype.validateISSN = function (value) { // Calculate and compare check digit var checkdigit = this.calculateCheckDigitISSN(issn); if (checkdigit != issn[8]) { - return messages["identifierInvalidCheckdigit"].replace("%value%", value); + return opus4Messages["identifierInvalidCheckdigit"].replace("%value%", value); } return true; diff --git a/tests/library/Application/View/Helper/JavascriptTranslationTest.php b/tests/library/Application/View/Helper/JavascriptMessagesTest.php similarity index 62% rename from tests/library/Application/View/Helper/JavascriptTranslationTest.php rename to tests/library/Application/View/Helper/JavascriptMessagesTest.php index f00ba3a6d..b0d5d8886 100644 --- a/tests/library/Application/View/Helper/JavascriptTranslationTest.php +++ b/tests/library/Application/View/Helper/JavascriptMessagesTest.php @@ -31,7 +31,7 @@ * @license http://www.gnu.org/licenses/gpl.html General Public License */ -class Application_View_Helper_JavascriptTranslationTest extends ControllerTestCase +class Application_View_Helper_JavascriptMessagesTest extends ControllerTestCase { private $helper; @@ -41,74 +41,74 @@ public function setUp() $this->useEnglish(); - $this->helper = new Application_View_Helper_JavascriptTranslation(); + $this->helper = new Application_View_Helper_JavascriptMessages(); $this->helper->setView(Zend_Registry::get('Opus_View')); } /** - * Tests, if the correct code-snippet for the translation will be generated. + * Tests, if the correct code-snippet for the Messages will be generated. */ - public function testJavascriptTranslation() + public function testJavascriptMessages() { - $translations = [ + $Messages = [ 'key1' => 'message1', 'key2' => 'message2' ]; - $this->helper->setTranslations($translations); + $this->helper->setMessages($Messages); $expectation = ''; + . ' opus4Messages["key1"] = "message1";' . "\n" + . ' opus4Messages["key2"] = "message2";' . "\n" + . ' ' . "\n"; - $reality = $this->helper->javascriptTranslation(); + $reality = $this->helper->javascriptMessages(); $this->assertEquals($expectation, $reality); } /** - * Tests, if the addTranslation-function translates in the correct way and deliver the correct key-message pairs. + * Tests, if the addMessage-function translates in the correct way and deliver the correct key-message pairs. */ - public function testAddTranslation() + public function testAddMessage() { - $this->helper->addTranslation('key1', 'message1'); - $this->helper->addTranslation('identifierInvalidFormat'); - $this->helper->addTranslation('testkey'); + $this->helper->addMessage('key1', 'message1'); + $this->helper->addMessage('identifierInvalidFormat'); + $this->helper->addMessage('testkey'); - $translations = [ + $Messages = [ 'key1' => 'message1', 'identifierInvalidFormat' => "'%value%' is malformed.", 'testkey' => 'testkey' ]; - $this->assertEquals($translations, $this->helper->getTranslations()); + $this->assertEquals($Messages, $this->helper->getMessages()); } - public function testSetTranslations() + public function testSetMessages() { - $translations = [ + $Messages = [ 'key1' => 'message1', 'key2' => 'message2' ]; - $this->helper->setTranslations($translations); - $this->assertEquals($translations, $this->helper->getTranslations()); + $this->helper->setMessages($Messages); + $this->assertEquals($Messages, $this->helper->getMessages()); } /** - * If the translations are empty or set to null, the code snippet for the translation without any key-message pairs + * If the Messages are empty or set to null, the code snippet for the Messages without any key-message pairs * should be delivered. This is tested here. */ - public function testSetNullTranslations() + public function testSetNullMessages() { - $this->helper->setTranslations(null); - $reality = $this->helper->javascriptTranslation(); + $this->helper->setMessages(null); + $reality = $this->helper->javascriptMessages(); $expectation = '' . "\n"; $this->assertEquals($expectation, $reality); } - public function testGetTranslations() + public function testGetMessages() { - $this->assertEquals([], $this->helper->getTranslations()); + $this->assertEquals([], $this->helper->getMessages()); } } From b5a57db1357286cc879ba846f05cfb7cccde522c Mon Sep 17 00:00:00 2001 From: BioFreak95 Date: Thu, 23 Aug 2018 16:25:13 +0200 Subject: [PATCH 092/128] OPUSVIER-3899 Add ISSN-validation with JS and an JS-test-webpage --- public/layouts/opus4/js/validation.js | 75 ++++++++ tests/javascript/testIssnValidation.html | 208 +++++++++++++++++++++++ 2 files changed, 283 insertions(+) create mode 100644 public/layouts/opus4/js/validation.js create mode 100644 tests/javascript/testIssnValidation.html diff --git a/public/layouts/opus4/js/validation.js b/public/layouts/opus4/js/validation.js new file mode 100644 index 000000000..5fe45bccf --- /dev/null +++ b/public/layouts/opus4/js/validation.js @@ -0,0 +1,75 @@ +/** + * This file is part of OPUS. The software OPUS has been originally developed + * at the University of Stuttgart with funding from the German Research Net, + * the Federal Department of Higher Education and Research and the Ministry + * of Science, Research and the Arts of the State of Baden-Wuerttemberg. + * + * OPUS 4 is a complete rewrite of the original OPUS software and was developed + * by the Stuttgart University Library, the Library Service Center + * Baden-Wuerttemberg, the Cooperative Library Network Berlin-Brandenburg, + * the Saarland University and State Library, the Saxon State Library - + * Dresden State and University Library, the Bielefeld University Library and + * the University Library of Hamburg University of Technology with funding from + * the German Research Foundation and the European Regional Development Fund. + * + * LICENCE + * OPUS is free software; you can redistribute it and/or modify it under the + * terms of the GNU General Public License as published by the Free Software + * Foundation; either version 2 of the Licence, or any later version. + * OPUS is distributed in the hope that it will be useful, but WITHOUT ANY + * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more + * details. You should have received a copy of the GNU General Public License + * along with OPUS; if not, write to the Free Software Foundation, Inc., 51 + * Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + * + * @category Application + * @author Maximilian Salomon + * @copyright Copyright (c) 2018, OPUS 4 development team + * @license http://www.gnu.org/licenses/gpl.html General Public License + */ + + +function validateISSN(value) { + // var messages = { + // invalidCheckdigit: "The check digit of \'%value%\' is not valid", + // invalidFormat: "\'%value%\' is malformed" + // }; + + // check length + if (value.length !== 9) { + //alert(messages.invalidFormat.replace("%value%", value)); + return false; + } + + // check form + if (value.match(/^[0-9]{4}[-][0-9]{3}[0-9X]$/g) === null) { + //alert(messages.invalidFormat.replace("%value%", value)); + return false; + } + + // Split ISSN into its parts + var issn = value.split(""); + + // Calculate and compare check digit + var checkdigit = calculateCheckDigitISSN(issn); + if (checkdigit != issn[8]) { + //alert(messages.invalidCheckdigit.replace("%value%", value)); + return false; + } + + return true; +} + +function calculateCheckDigitISSN(value) { + var z = value; + var checkdigit = 0; + var check = (8 * z[0] + 7 * z[1] + 6 * z[2] + 5 * z[3] + 4 * z[5] + 3 * z[6] + 2 * z[7]); + if (11 - (check % 11) === 10) { + checkdigit = "X"; + } else { + checkdigit = 11 - (check % 11); + } + + return checkdigit; +} \ No newline at end of file diff --git a/tests/javascript/testIssnValidation.html b/tests/javascript/testIssnValidation.html new file mode 100644 index 000000000..30057cb40 --- /dev/null +++ b/tests/javascript/testIssnValidation.html @@ -0,0 +1,208 @@ + + + + + + + + testValidation + + + + + +
          +

          Tests of ISSN-validation

          +

          This test-page tests the ISSN-validation with javascript.

          + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
          Test-ISSNExpectationActualTest-Result
          1050-124XTrue
          0001-3218True
          0025-5858True
          1062-5127True
          0317-8471True
          12345478False
          nullFalse
          trueFalse
          12456-65478False
          123456789False
          1050 124XFalse
          1050_124XFalse
          1050-1242False
          +
          + + From eb9f8b8c09ee77954d2a45c396a2b3057a08268d Mon Sep 17 00:00:00 2001 From: BioFreak95 Date: Fri, 24 Aug 2018 12:22:58 +0200 Subject: [PATCH 093/128] OPUSVIER-3899 Add ISBN-validation with JS and an JS-test-webpage --- public/layouts/opus4/js/validation.js | 104 ++++ tests/javascript/testIsbnValidation.html | 579 +++++++++++++++++++++++ 2 files changed, 683 insertions(+) create mode 100644 tests/javascript/testIsbnValidation.html diff --git a/public/layouts/opus4/js/validation.js b/public/layouts/opus4/js/validation.js index 5fe45bccf..f6d55c66e 100644 --- a/public/layouts/opus4/js/validation.js +++ b/public/layouts/opus4/js/validation.js @@ -72,4 +72,108 @@ function calculateCheckDigitISSN(value) { } return checkdigit; +} + +function validateISBN(value) { + // var messages = { + // invalidCheckdigit: "The check digit of \'%value%\' is not valid", + // invalidFormat: "\'%value%\' is malformed" + // }; + + var isbnDigits = splitISBN(value); + + if (isbnDigits.length === 10) { + return validateISBN10(value); + } + else if (isbnDigits.length === 13) { + return validateISBN13(value); + } + else { + //alert(messages.invalidFormat.replace("%value%", value)); + return false; + } +} + +function validateISBN10(value) { + // var messages = { + // invalidCheckdigit: "The check digit of \'%value%\' is not valid", + // invalidFormat: "\'%value%\' is malformed" + // }; + + if (value.length !== 10 && value.length !== 13) { + return false; + } + + if (value.match(/^[\d]*((-|\s)?[\d]*){2}((-|\s)?[\dX])$/g) === null) { + //alert(messages.invalidFormat.replace("%value%", value)); + return false; + } + + if (value.match(/-/) !== null && value.match(/\s/) !== null) { + //alert(messages.invalidFormat.replace("%value%", value)); + return false; + } + + var isbnDigits = splitISBN(value); + return calculateCheckDigitISBN10(isbnDigits); +} + +function validateISBN13(value) { + // var messages = { + // invalidCheckdigit: "The check digit of \'%value%\' is not valid", + // invalidFormat: "\'%value%\' is malformed" + // }; + + if (value.length !== 13 && value.length !== 17) { + return false; + } + + if (value.match(/^(978|979)((-|\s)?[\d]*){4}$/g) === null) { + //alert(messages.invalidFormat.replace("%value%", value)); + return false; + } + + if (value.match(/-/) !== null && value.match(/\s/) !== null) { + //alert(messages.invalidFormat.replace("%value%", value)); + return false; + } + + var isbnDigits = splitISBN(value); + return calculateCheckDigitISBN13(isbnDigits); +} + +function calculateCheckDigitISBN10(value) { + var z = value; + + if (z[9] === "X") { + z[9] = 10; + } + z = z.map(Number); + var check = 10 * z[0] + 9 * z[1] + 8 * z[2] + 7 * z[3] + 6 * z[4] + 5 * z[5] + 4 * z[6] + 3 * z[7] + 2 * z[8] + 1 * z[9]; + + return (check % 11 === 0); +} + +function calculateCheckDigitISBN13(value) { + var z = value.map(Number); + + var check = (z[0] + z[2] + z[4] + z[6] + z[8] + z[10] + z[12]) + 3 * (z[1] + z[3] + z[5] + z[7] + z[9] + z[11]); + return (check % 10 === 0); +} + + +function splitISBN(value) { + var isbn = value.split(/(-|\s)/); + var digits = []; + isbn.forEach(function (isbn) { + if (isbn.match((/(-|\s)/))) { + return true; + } + var isbn_parts = isbn.split(""); + isbn_parts.forEach(function (isbn_parts) { + digits.push(isbn_parts); + }); + }); + + return digits; } \ No newline at end of file diff --git a/tests/javascript/testIsbnValidation.html b/tests/javascript/testIsbnValidation.html new file mode 100644 index 000000000..dafea1aa6 --- /dev/null +++ b/tests/javascript/testIsbnValidation.html @@ -0,0 +1,579 @@ + + + + + + + + testValidation + + + + + +
          +

          Tests of ISBN-validation

          +

          This test-page tests the ISBN-validation with javascript. There are for every function one part. validateISBN10, + validateISBN13 and validateISBN.

          +

          Tests of ISBN-validation

          + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
          Test-ISBNExpectationActualTest-Result
          3-935024-10-XTrue
          393502410XTrue
          3-86680-192-0True
          3-937602-69-0True
          3 86680 192 0True
          3 937602 69 0True
          978-3-86680-192-9True
          3-937602-69-0True
          978-5-7931-8163-1True
          978-979-3182-63-6True
          978 3 86680 192 9True
          978 5 7931 8163 1True
          978 979 3182 63 6True
          978-3-86680-192-9True
          9789793182636True
          nullFalse
          False
          4711False
          trueFalse
          4711-0815False
          980-3-86680-192-9False
          978-3-86680-192-5False
          978 3 86680-192-9False
          nullFalse
          False
          4711False
          trueFalse
          4711-0815False
          3-86680-192-5False
          3 86680 192-0False
          3-86680-1902-0False
          + +

          Tests of ISBN10-validation

          + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
          Test-ISBNExpectationActualTest-Result
          3-935024-10-XTrue
          393502410XTrue
          3-86680-192-0True
          3-937602-69-0True
          3 86680 192 0True
          3 937602 69 0True
          39376026940False
          nullFalse
          False
          4711False
          trueFalse
          4711-0815False
          978-3-86680-192-9False
          3-86680-192-5False
          3 86680 192-0False
          3-86680-1902-0False
          + +

          Tests of ISBN13-validation

          + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
          Test-ISBNExpectationActualTest-Result
          978-3-86680-192-9True
          978-5-7931-8163-1True
          978-979-3182-63-6True
          978 3 86680 192 9True
          978 5 7931 8163 1True
          978 979 3182 63 6True
          9789793182636True
          nullFalse
          False
          4711False
          trueFalse
          4711-0815False
          980-3-86680-192-9False
          978-3-86680-192-5False
          978 3 86680-192-9False
          3-937602-69-0False
          +
          + + From fdb161f6aeac775dadcead099e11853f377fa377 Mon Sep 17 00:00:00 2001 From: BioFreak95 Date: Fri, 24 Aug 2018 17:56:38 +0200 Subject: [PATCH 094/128] OPUSVIER-3899 Add identifier-validation to admin-module --- public/layouts/opus4/common.phtml | 6 ++++ public/layouts/opus4/js/validation.js | 49 ++++++++++++++++++++++++++- 2 files changed, 54 insertions(+), 1 deletion(-) diff --git a/public/layouts/opus4/common.phtml b/public/layouts/opus4/common.phtml index 686cb574c..b62c33eba 100644 --- a/public/layouts/opus4/common.phtml +++ b/public/layouts/opus4/common.phtml @@ -85,8 +85,14 @@ if (in_array($this->moduleName, array('admin', 'review', 'setup', 'account'))) { $jsFiles[] = 'theme_lic.js'; $jsFiles[] = 'opus-ui.js'; } + else if (in_array($this->moduleName, array('publish'))) { $jsFiles[] = 'upload.js'; +if (in_array($this->moduleName, array('admin'))) { + $jsFiles[] = 'validation.js'; +} else if (in_array($this->moduleName, array('publish'))) { + $jsFiles[] = 'filetypes.js'; + } if ($this->jQueryEnabled()) { diff --git a/public/layouts/opus4/js/validation.js b/public/layouts/opus4/js/validation.js index f6d55c66e..05c7d9ba3 100644 --- a/public/layouts/opus4/js/validation.js +++ b/public/layouts/opus4/js/validation.js @@ -176,4 +176,51 @@ function splitISBN(value) { }); return digits; -} \ No newline at end of file +} + + +$(document).ready(function () { + var selectors = []; + var result; + + var identifier = $("#fieldset-Identifiers tbody tr td.Value-data"); + var identifierText = $("#fieldset-Identifiers tbody tr :text"); + var identifierSelector = $("#fieldset-Identifiers tbody tr select"); + + $.each(identifier, function (index, value) { + var para = document.createElement("p"); + para.classList.add("datahint"); + para.setAttribute("style", "display : none"); + value.appendChild(para); + }); + + $.each(identifierSelector, function (index, value) { + selectors[index] = value.value; + value.onchange = function () { + selectors[index] = value.value; + }; + }); + + + $.each(identifierText, function (index, value) { + var ident = selectors[index]; + + value.onchange = function () { + if (ident === "isbn") { + result = validateISBN(value.value); + } + else if (ident === "issn") { + + result = validateISSN(value.value); + } + else { + result = true; + } + if (result !== true) { + $(identifier[index]).find("p")[0].innerHTML = result; + $(identifier[index]).find("p").removeAttr("style"); + } + }; + }); + +}); \ No newline at end of file From 356e106cf97f11dc39349cad6eefe929d0989e9d Mon Sep 17 00:00:00 2001 From: BioFreak95 Date: Fri, 24 Aug 2018 18:12:37 +0200 Subject: [PATCH 095/128] OPUSVIER-3899 Add more detailed messages --- public/layouts/opus4/js/validation.js | 60 ++++++++++++--------------- 1 file changed, 26 insertions(+), 34 deletions(-) diff --git a/public/layouts/opus4/js/validation.js b/public/layouts/opus4/js/validation.js index 05c7d9ba3..befb8298b 100644 --- a/public/layouts/opus4/js/validation.js +++ b/public/layouts/opus4/js/validation.js @@ -31,21 +31,19 @@ function validateISSN(value) { - // var messages = { - // invalidCheckdigit: "The check digit of \'%value%\' is not valid", - // invalidFormat: "\'%value%\' is malformed" - // }; + var messages = { + invalidCheckdigit: "The check digit of \'%value%\' is not valid", + invalidFormat: "\'%value%\' is malformed" + }; // check length if (value.length !== 9) { - //alert(messages.invalidFormat.replace("%value%", value)); - return false; + return messages.invalidFormat.replace("%value%", value); } // check form if (value.match(/^[0-9]{4}[-][0-9]{3}[0-9X]$/g) === null) { - //alert(messages.invalidFormat.replace("%value%", value)); - return false; + return messages.invalidFormat.replace("%value%", value); } // Split ISSN into its parts @@ -54,8 +52,7 @@ function validateISSN(value) { // Calculate and compare check digit var checkdigit = calculateCheckDigitISSN(issn); if (checkdigit != issn[8]) { - //alert(messages.invalidCheckdigit.replace("%value%", value)); - return false; + return messages.invalidCheckdigit.replace("%value%", value); } return true; @@ -75,10 +72,10 @@ function calculateCheckDigitISSN(value) { } function validateISBN(value) { - // var messages = { - // invalidCheckdigit: "The check digit of \'%value%\' is not valid", - // invalidFormat: "\'%value%\' is malformed" - // }; + var messages = { + invalidCheckdigit: "The check digit of \'%value%\' is not valid", + invalidFormat: "\'%value%\' is malformed" + }; var isbnDigits = splitISBN(value); @@ -89,29 +86,26 @@ function validateISBN(value) { return validateISBN13(value); } else { - //alert(messages.invalidFormat.replace("%value%", value)); - return false; + return messages.invalidFormat.replace("%value%", value); } } function validateISBN10(value) { - // var messages = { - // invalidCheckdigit: "The check digit of \'%value%\' is not valid", - // invalidFormat: "\'%value%\' is malformed" - // }; + var messages = { + invalidCheckdigit: "The check digit of \'%value%\' is not valid", + invalidFormat: "\'%value%\' is malformed" + }; if (value.length !== 10 && value.length !== 13) { - return false; + return messages.invalidFormat.replace("%value%", value); } if (value.match(/^[\d]*((-|\s)?[\d]*){2}((-|\s)?[\dX])$/g) === null) { - //alert(messages.invalidFormat.replace("%value%", value)); - return false; + return messages.invalidFormat.replace("%value%", value); } if (value.match(/-/) !== null && value.match(/\s/) !== null) { - //alert(messages.invalidFormat.replace("%value%", value)); - return false; + return messages.invalidFormat.replace("%value%", value); } var isbnDigits = splitISBN(value); @@ -119,23 +113,21 @@ function validateISBN10(value) { } function validateISBN13(value) { - // var messages = { - // invalidCheckdigit: "The check digit of \'%value%\' is not valid", - // invalidFormat: "\'%value%\' is malformed" - // }; + var messages = { + invalidCheckdigit: "The check digit of \'%value%\' is not valid", + invalidFormat: "\'%value%\' is malformed" + }; if (value.length !== 13 && value.length !== 17) { - return false; + return messages.invalidFormat.replace("%value%", value); } if (value.match(/^(978|979)((-|\s)?[\d]*){4}$/g) === null) { - //alert(messages.invalidFormat.replace("%value%", value)); - return false; + return messages.invalidFormat.replace("%value%", value); } if (value.match(/-/) !== null && value.match(/\s/) !== null) { - //alert(messages.invalidFormat.replace("%value%", value)); - return false; + return messages.invalidFormat.replace("%value%", value); } var isbnDigits = splitISBN(value); From 821e1c5232f2ddc0a1561789db024f963dcda78f Mon Sep 17 00:00:00 2001 From: BioFreak95 Date: Mon, 10 Sep 2018 16:29:22 +0200 Subject: [PATCH 096/128] OPUSVIER-3899 Bugfix Errormessage hidded after correct identifier Validation no save selectortext after change --- public/layouts/opus4/js/validation.js | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/public/layouts/opus4/js/validation.js b/public/layouts/opus4/js/validation.js index befb8298b..9a5f7cd60 100644 --- a/public/layouts/opus4/js/validation.js +++ b/public/layouts/opus4/js/validation.js @@ -174,6 +174,7 @@ function splitISBN(value) { $(document).ready(function () { var selectors = []; var result; + var ident; var identifier = $("#fieldset-Identifiers tbody tr td.Value-data"); var identifierText = $("#fieldset-Identifiers tbody tr :text"); @@ -190,12 +191,12 @@ $(document).ready(function () { selectors[index] = value.value; value.onchange = function () { selectors[index] = value.value; + ident = selectors[index]; }; }); $.each(identifierText, function (index, value) { - var ident = selectors[index]; value.onchange = function () { if (ident === "isbn") { @@ -212,6 +213,9 @@ $(document).ready(function () { $(identifier[index]).find("p")[0].innerHTML = result; $(identifier[index]).find("p").removeAttr("style"); } + else { + $(identifier[index]).find("p").attr("style", "display : none"); + } }; }); From c3ca3d2e6f8dc839b8bcace9b43b7bf955a6d92e Mon Sep 17 00:00:00 2001 From: BioFreak95 Date: Tue, 16 Oct 2018 15:17:45 +0200 Subject: [PATCH 097/128] =?UTF-8?q?OPUSVIER-3947=20=C3=9Cbersetzungsmechan?= =?UTF-8?q?ik=20f=C3=BCr=20Javascript=20Es=20wirde=20eine=20=C3=9Cbersetzu?= =?UTF-8?q?ngsmechanik=20f=C3=BCr=20Javascript=20eingebaut?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../View/Helper/JavascriptTranslation.php | 61 +++++++++++++++++++ .../admin/controllers/DocumentController.php | 4 ++ modules/default/language/error.tmx | 18 ++++++ modules/publish/language/errors.tmx | 1 + public/layouts/opus4/common.phtml | 2 + public/layouts/opus4/js/validation.js | 40 +++++------- 6 files changed, 100 insertions(+), 26 deletions(-) create mode 100644 library/Application/View/Helper/JavascriptTranslation.php diff --git a/library/Application/View/Helper/JavascriptTranslation.php b/library/Application/View/Helper/JavascriptTranslation.php new file mode 100644 index 000000000..c7461b2b2 --- /dev/null +++ b/library/Application/View/Helper/JavascriptTranslation.php @@ -0,0 +1,61 @@ + + * @copyright Copyright (c) 2018, OPUS 4 development team + * @license http://www.gnu.org/licenses/gpl.html General Public License + */ + +class Application_View_Helper_JavascriptTranslation extends Application_View_Helper_Abstract +{ + + protected $messages = ''; + + public function javascriptTranslation() + { + + $output = '"; + + return $output; + } + + public function addJavascriptTranslations($key, $message = null) + { + + if ($message != null) { + $this->messages .= "\t" . "\t" . "\t" . "messages.$key = \"" . htmlspecialchars($message) . "\";" . "\n"; + } else { + $message = $this->view->translate($key); + $this->messages .= "\t" . "\t" . "\t" . "messages.$key = \"" . htmlspecialchars($message) . "\";" . "\n"; + } + + } + +} \ No newline at end of file diff --git a/modules/admin/controllers/DocumentController.php b/modules/admin/controllers/DocumentController.php index 1934f7e15..aabcc446a 100644 --- a/modules/admin/controllers/DocumentController.php +++ b/modules/admin/controllers/DocumentController.php @@ -231,6 +231,10 @@ public function editAction() $this->_helper->breadcrumbs()->setDocumentBreadcrumb($document); $this->renderForm($this->view->form); + + $javascriptTranslations = $this->view->getHelper('javascriptTranslation'); + $javascriptTranslations->addJavascriptTranslations('identifierInvalidFormat'); + $javascriptTranslations->addJavascriptTranslations('identifierInvalidCheckdigit'); } /** diff --git a/modules/default/language/error.tmx b/modules/default/language/error.tmx index 1d3dec2ad..72213c4f2 100644 --- a/modules/default/language/error.tmx +++ b/modules/default/language/error.tmx @@ -110,6 +110,24 @@ + + + '%value%' is malformed. + + + '%value%' hat eine unerlaubte Form. + + + + + + The check digit of '%value%' is not valid". + + + Die Prüfziffer '%value%' ist nicht korrekt. + + + diff --git a/modules/publish/language/errors.tmx b/modules/publish/language/errors.tmx index ccf3a224e..1b090089c 100644 --- a/modules/publish/language/errors.tmx +++ b/modules/publish/language/errors.tmx @@ -170,6 +170,7 @@ +<<<<<<< HEAD Please choose another File. diff --git a/public/layouts/opus4/common.phtml b/public/layouts/opus4/common.phtml index b62c33eba..b2a498686 100644 --- a/public/layouts/opus4/common.phtml +++ b/public/layouts/opus4/common.phtml @@ -145,6 +145,8 @@ if (isset($config->javascript->latex->mathjax)) { + javascriptTranslation() ?> + diff --git a/public/layouts/opus4/js/validation.js b/public/layouts/opus4/js/validation.js index 9a5f7cd60..89dc621bc 100644 --- a/public/layouts/opus4/js/validation.js +++ b/public/layouts/opus4/js/validation.js @@ -29,21 +29,21 @@ * @license http://www.gnu.org/licenses/gpl.html General Public License */ +var messages = { + identifierInvalidCheckdigit: "The check digit of \'%value%\' is not valid", + identifierInvalidFormat: "\'%value%\' is malformed" +}; function validateISSN(value) { - var messages = { - invalidCheckdigit: "The check digit of \'%value%\' is not valid", - invalidFormat: "\'%value%\' is malformed" - }; // check length if (value.length !== 9) { - return messages.invalidFormat.replace("%value%", value); + return messages.identifierInvalidFormat.replace("%value%", value); } // check form if (value.match(/^[0-9]{4}[-][0-9]{3}[0-9X]$/g) === null) { - return messages.invalidFormat.replace("%value%", value); + return messages.identifierInvalidFormat.replace("%value%", value); } // Split ISSN into its parts @@ -52,7 +52,7 @@ function validateISSN(value) { // Calculate and compare check digit var checkdigit = calculateCheckDigitISSN(issn); if (checkdigit != issn[8]) { - return messages.invalidCheckdigit.replace("%value%", value); + return messages.identifierInvalidCheckdigit.replace("%value%", value); } return true; @@ -72,10 +72,6 @@ function calculateCheckDigitISSN(value) { } function validateISBN(value) { - var messages = { - invalidCheckdigit: "The check digit of \'%value%\' is not valid", - invalidFormat: "\'%value%\' is malformed" - }; var isbnDigits = splitISBN(value); @@ -86,26 +82,22 @@ function validateISBN(value) { return validateISBN13(value); } else { - return messages.invalidFormat.replace("%value%", value); + return messages.identifierInvalidFormat.replace("%value%", value); } } function validateISBN10(value) { - var messages = { - invalidCheckdigit: "The check digit of \'%value%\' is not valid", - invalidFormat: "\'%value%\' is malformed" - }; if (value.length !== 10 && value.length !== 13) { - return messages.invalidFormat.replace("%value%", value); + return messages.identifierInvalidFormat.replace("%value%", value); } if (value.match(/^[\d]*((-|\s)?[\d]*){2}((-|\s)?[\dX])$/g) === null) { - return messages.invalidFormat.replace("%value%", value); + return messages.identifierInvalidFormat.replace("%value%", value); } if (value.match(/-/) !== null && value.match(/\s/) !== null) { - return messages.invalidFormat.replace("%value%", value); + return messages.identifierInvalidFormat.replace("%value%", value); } var isbnDigits = splitISBN(value); @@ -113,21 +105,17 @@ function validateISBN10(value) { } function validateISBN13(value) { - var messages = { - invalidCheckdigit: "The check digit of \'%value%\' is not valid", - invalidFormat: "\'%value%\' is malformed" - }; if (value.length !== 13 && value.length !== 17) { - return messages.invalidFormat.replace("%value%", value); + return messages.identifierInvalidFormat.replace("%value%", value); } if (value.match(/^(978|979)((-|\s)?[\d]*){4}$/g) === null) { - return messages.invalidFormat.replace("%value%", value); + return messages.identifierInvalidFormat.replace("%value%", value); } if (value.match(/-/) !== null && value.match(/\s/) !== null) { - return messages.invalidFormat.replace("%value%", value); + return messages.identifierInvalidFormat.replace("%value%", value); } var isbnDigits = splitISBN(value); From 3116a6d3cf4e15ceb93a3343bc8582ed616263c8 Mon Sep 17 00:00:00 2001 From: BioFreak95 Date: Tue, 16 Oct 2018 16:40:25 +0200 Subject: [PATCH 098/128] OPUSVIER-3899 Bugfix in tests and validator-class --- public/layouts/opus4/js/validation.js | 12 ++++++++++-- tests/javascript/testIsbnValidation.html | 18 +++++++++--------- tests/javascript/testIssnValidation.html | 6 +++--- 3 files changed, 22 insertions(+), 14 deletions(-) diff --git a/public/layouts/opus4/js/validation.js b/public/layouts/opus4/js/validation.js index 89dc621bc..5d9d013a3 100644 --- a/public/layouts/opus4/js/validation.js +++ b/public/layouts/opus4/js/validation.js @@ -101,7 +101,11 @@ function validateISBN10(value) { } var isbnDigits = splitISBN(value); - return calculateCheckDigitISBN10(isbnDigits); + if (calculateCheckDigitISBN10(isbnDigits) === false) { + return messages.identifierInvalidCheckdigit.replace("%value%", value); + } + + return true; } function validateISBN13(value) { @@ -119,7 +123,11 @@ function validateISBN13(value) { } var isbnDigits = splitISBN(value); - return calculateCheckDigitISBN13(isbnDigits); + if (calculateCheckDigitISBN13(isbnDigits) === false) { + return messages.identifierInvalidCheckdigit.replace("%value%", value); + } + + return true; } function calculateCheckDigitISBN10(value) { diff --git a/tests/javascript/testIsbnValidation.html b/tests/javascript/testIsbnValidation.html index dafea1aa6..8cb8dc050 100644 --- a/tests/javascript/testIsbnValidation.html +++ b/tests/javascript/testIsbnValidation.html @@ -92,10 +92,10 @@ var expectation = rows[1]; var actual = rows[2]; var result = rows[3]; - if (validateISBN13(ISBN) === false) { - actual.innerHTML = "False"; - } else { + if (validateISBN13(ISBN) === true) { actual.innerHTML = "True"; + } else { + actual.innerHTML = "False"; } if (actual.innerHTML === expectation.innerHTML) { result.innerHTML = 'Passed'; @@ -114,10 +114,10 @@ var expectation = rows[1]; var actual = rows[2]; var result = rows[3]; - if (validateISBN10(ISBN) === false) { - actual.innerHTML = "False"; - } else { + if (validateISBN10(ISBN) === true) { actual.innerHTML = "True"; + } else { + actual.innerHTML = "False"; } if (actual.innerHTML === expectation.innerHTML) { result.innerHTML = 'Passed'; @@ -136,10 +136,10 @@ var expectation = rows[1]; var actual = rows[2]; var result = rows[3]; - if (validateISBN(ISBN) === false) { - actual.innerHTML = "False"; - } else { + if (validateISBN(ISBN) === true) { actual.innerHTML = "True"; + } else { + actual.innerHTML = "False"; } if (actual.innerHTML === expectation.innerHTML) { result.innerHTML = 'Passed'; diff --git a/tests/javascript/testIssnValidation.html b/tests/javascript/testIssnValidation.html index 30057cb40..a550a8593 100644 --- a/tests/javascript/testIssnValidation.html +++ b/tests/javascript/testIssnValidation.html @@ -92,10 +92,10 @@ let expectation = rows[1]; let actual = rows[2]; let result = rows[3]; - if (validateISSN(ISSN) === false) { - actual.innerHTML = "False"; - } else { + if (validateISSN(ISSN) === true) { actual.innerHTML = "True"; + } else { + actual.innerHTML = "False"; } if (actual.innerHTML === expectation.innerHTML) { result.innerHTML = 'Passed'; From fcaa2a1ac2d252061170c932c8f01b0923545ca6 Mon Sep 17 00:00:00 2001 From: BioFreak95 Date: Wed, 17 Oct 2018 11:45:08 +0200 Subject: [PATCH 099/128] OPUSVIER-3899 Bugfix in validation --- public/layouts/opus4/js/validation.js | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/public/layouts/opus4/js/validation.js b/public/layouts/opus4/js/validation.js index 5d9d013a3..f259ccb6f 100644 --- a/public/layouts/opus4/js/validation.js +++ b/public/layouts/opus4/js/validation.js @@ -170,7 +170,6 @@ function splitISBN(value) { $(document).ready(function () { var selectors = []; var result; - var ident; var identifier = $("#fieldset-Identifiers tbody tr td.Value-data"); var identifierText = $("#fieldset-Identifiers tbody tr :text"); @@ -187,7 +186,6 @@ $(document).ready(function () { selectors[index] = value.value; value.onchange = function () { selectors[index] = value.value; - ident = selectors[index]; }; }); @@ -195,10 +193,10 @@ $(document).ready(function () { $.each(identifierText, function (index, value) { value.onchange = function () { - if (ident === "isbn") { + if (selectors[index] === "isbn") { result = validateISBN(value.value); } - else if (ident === "issn") { + else if (selectors[index] === "issn") { result = validateISSN(value.value); } From a7b32d1efc2cc732f4f0cf6e1e77b27ba6a3a2fe Mon Sep 17 00:00:00 2001 From: BioFreak95 Date: Wed, 17 Oct 2018 16:00:25 +0200 Subject: [PATCH 100/128] OPUSVIER-3899 view-helper tests and some fixes in view-helper --- .../View/Helper/JavascriptTranslation.php | 27 ++++-- .../admin/controllers/DocumentController.php | 4 +- .../View/Helper/JavascriptTranslationTest.php | 96 +++++++++++++++++++ 3 files changed, 115 insertions(+), 12 deletions(-) create mode 100644 tests/library/Application/View/Helper/JavascriptTranslationTest.php diff --git a/library/Application/View/Helper/JavascriptTranslation.php b/library/Application/View/Helper/JavascriptTranslation.php index c7461b2b2..3ab9d87a0 100644 --- a/library/Application/View/Helper/JavascriptTranslation.php +++ b/library/Application/View/Helper/JavascriptTranslation.php @@ -33,29 +33,36 @@ class Application_View_Helper_JavascriptTranslation extends Application_View_Helper_Abstract { - - protected $messages = ''; + protected $translations = []; public function javascriptTranslation() { - $output = '"; + foreach ($this->translations as $key => $message) { + $output .= " " . "messages.$key = \"" . htmlspecialchars($message) . "\";" . "\n"; + } + $output .= " " . ""; return $output; } - public function addJavascriptTranslations($key, $message = null) + public function addTranslation($key, $message = null) { - if ($message != null) { - $this->messages .= "\t" . "\t" . "\t" . "messages.$key = \"" . htmlspecialchars($message) . "\";" . "\n"; + $this->translations[$key] = $message; } else { $message = $this->view->translate($key); - $this->messages .= "\t" . "\t" . "\t" . "messages.$key = \"" . htmlspecialchars($message) . "\";" . "\n"; + $this->translations[$key] = $message; } + } + public function getTranslations() + { + return $this->translations; } -} \ No newline at end of file + public function setTranslations($value) + { + $this->translations = $value; + } +} diff --git a/modules/admin/controllers/DocumentController.php b/modules/admin/controllers/DocumentController.php index aabcc446a..c961fbe39 100644 --- a/modules/admin/controllers/DocumentController.php +++ b/modules/admin/controllers/DocumentController.php @@ -233,8 +233,8 @@ public function editAction() $this->renderForm($this->view->form); $javascriptTranslations = $this->view->getHelper('javascriptTranslation'); - $javascriptTranslations->addJavascriptTranslations('identifierInvalidFormat'); - $javascriptTranslations->addJavascriptTranslations('identifierInvalidCheckdigit'); + $javascriptTranslations->addTranslation('identifierInvalidFormat'); + $javascriptTranslations->addTranslation('identifierInvalidCheckdigit'); } /** diff --git a/tests/library/Application/View/Helper/JavascriptTranslationTest.php b/tests/library/Application/View/Helper/JavascriptTranslationTest.php new file mode 100644 index 000000000..e286854b9 --- /dev/null +++ b/tests/library/Application/View/Helper/JavascriptTranslationTest.php @@ -0,0 +1,96 @@ + + * @copyright Copyright (c) 2018, OPUS 4 development team + * @license http://www.gnu.org/licenses/gpl.html General Public License + */ + +class Application_View_Helper_JavascriptTranslationTest extends ControllerTestCase +{ + + private $_helper; + + public function setUp() + { + parent::setUp(); + + $this->useEnglish(); + + $this->_helper = new Application_View_Helper_JavascriptTranslation(); + + $this->_helper->setView(Zend_Registry::get('Opus_View')); + } + + public function testJavascriptTranslation() + { + $translations = [ + 'key1' => 'message1', + 'key2' => 'message2' + ]; + $this->_helper->setTranslations($translations); + + $expectation = ''; + + $reality = $this->_helper->javascriptTranslation(); + $this->assertEquals($expectation, $reality); + } + + public function testAddTranslation() + { + $this->_helper->addTranslation('key1', 'message1'); + $this->_helper->addTranslation('identifierInvalidFormat'); + $this->_helper->addTranslation('testkey'); + + $translations = [ + 'key1' => 'message1', + 'identifierInvalidFormat' => "'%value%' is malformed.", + 'testkey' => 'testkey' + ]; + + $this->assertEquals($translations, $this->_helper->getTranslations()); + } + + public function testSetTranslations() + { + $translations = [ + 'key1' => 'message1', + 'key2' => 'message2' + ]; + $this->_helper->setTranslations($translations); + $this->assertEquals($translations, $this->_helper->getTranslations()); + } + + public function testGetTranslations() + { + $this->assertEquals([], $this->_helper->getTranslations()); + } +} From ee83c53345d4fd6aa4c7fabb3a03403c27b12cb3 Mon Sep 17 00:00:00 2001 From: BioFreak95 Date: Wed, 17 Oct 2018 16:07:44 +0200 Subject: [PATCH 101/128] OPUSVIER-3899 validation.js codingstyle --- public/layouts/opus4/js/validation.js | 10 +--------- 1 file changed, 1 insertion(+), 9 deletions(-) diff --git a/public/layouts/opus4/js/validation.js b/public/layouts/opus4/js/validation.js index f259ccb6f..63f050b45 100644 --- a/public/layouts/opus4/js/validation.js +++ b/public/layouts/opus4/js/validation.js @@ -35,7 +35,6 @@ var messages = { }; function validateISSN(value) { - // check length if (value.length !== 9) { return messages.identifierInvalidFormat.replace("%value%", value); @@ -72,7 +71,6 @@ function calculateCheckDigitISSN(value) { } function validateISBN(value) { - var isbnDigits = splitISBN(value); if (isbnDigits.length === 10) { @@ -87,7 +85,6 @@ function validateISBN(value) { } function validateISBN10(value) { - if (value.length !== 10 && value.length !== 13) { return messages.identifierInvalidFormat.replace("%value%", value); } @@ -109,7 +106,6 @@ function validateISBN10(value) { } function validateISBN13(value) { - if (value.length !== 13 && value.length !== 17) { return messages.identifierInvalidFormat.replace("%value%", value); } @@ -149,7 +145,6 @@ function calculateCheckDigitISBN13(value) { return (check % 10 === 0); } - function splitISBN(value) { var isbn = value.split(/(-|\s)/); var digits = []; @@ -166,7 +161,6 @@ function splitISBN(value) { return digits; } - $(document).ready(function () { var selectors = []; var result; @@ -189,9 +183,7 @@ $(document).ready(function () { }; }); - $.each(identifierText, function (index, value) { - value.onchange = function () { if (selectors[index] === "isbn") { result = validateISBN(value.value); @@ -213,4 +205,4 @@ $(document).ready(function () { }; }); -}); \ No newline at end of file +}); From 67ddfb92ad1517fca65f23fdfb53ad37241538c6 Mon Sep 17 00:00:00 2001 From: BioFreak95 Date: Wed, 17 Oct 2018 16:09:32 +0200 Subject: [PATCH 102/128] OPUSVIER-3899 codingstyle --- .../Application/View/Helper/JavascriptTranslationTest.php | 1 - 1 file changed, 1 deletion(-) diff --git a/tests/library/Application/View/Helper/JavascriptTranslationTest.php b/tests/library/Application/View/Helper/JavascriptTranslationTest.php index e286854b9..623585642 100644 --- a/tests/library/Application/View/Helper/JavascriptTranslationTest.php +++ b/tests/library/Application/View/Helper/JavascriptTranslationTest.php @@ -33,7 +33,6 @@ class Application_View_Helper_JavascriptTranslationTest extends ControllerTestCase { - private $_helper; public function setUp() From 6a1721af66ffbce9062976a0077abd9db525c20a Mon Sep 17 00:00:00 2001 From: BioFreak95 Date: Thu, 18 Oct 2018 17:08:14 +0200 Subject: [PATCH 103/128] OPUSVIER-3899 codingstyle and change JS to OOP --- .../View/Helper/JavascriptTranslation.php | 6 +- public/layouts/opus4/common.phtml | 1 - public/layouts/opus4/js/validation.js | 153 +++++++++--------- .../View/Helper/JavascriptTranslationTest.php | 24 +-- 4 files changed, 95 insertions(+), 89 deletions(-) diff --git a/library/Application/View/Helper/JavascriptTranslation.php b/library/Application/View/Helper/JavascriptTranslation.php index 3ab9d87a0..eecd8128f 100644 --- a/library/Application/View/Helper/JavascriptTranslation.php +++ b/library/Application/View/Helper/JavascriptTranslation.php @@ -33,15 +33,15 @@ class Application_View_Helper_JavascriptTranslation extends Application_View_Helper_Abstract { - protected $translations = []; + private $translations = []; public function javascriptTranslation() { $output = '"; + $output .= " " . "" . "\n"; return $output; } diff --git a/public/layouts/opus4/common.phtml b/public/layouts/opus4/common.phtml index b2a498686..c478fdde8 100644 --- a/public/layouts/opus4/common.phtml +++ b/public/layouts/opus4/common.phtml @@ -146,7 +146,6 @@ if (isset($config->javascript->latex->mathjax)) { javascriptTranslation() ?> - diff --git a/public/layouts/opus4/js/validation.js b/public/layouts/opus4/js/validation.js index 63f050b45..4d21e30ae 100644 --- a/public/layouts/opus4/js/validation.js +++ b/public/layouts/opus4/js/validation.js @@ -34,62 +34,29 @@ var messages = { identifierInvalidFormat: "\'%value%\' is malformed" }; -function validateISSN(value) { - // check length - if (value.length !== 9) { - return messages.identifierInvalidFormat.replace("%value%", value); - } - - // check form - if (value.match(/^[0-9]{4}[-][0-9]{3}[0-9X]$/g) === null) { - return messages.identifierInvalidFormat.replace("%value%", value); - } - - // Split ISSN into its parts - var issn = value.split(""); - - // Calculate and compare check digit - var checkdigit = calculateCheckDigitISSN(issn); - if (checkdigit != issn[8]) { - return messages.identifierInvalidCheckdigit.replace("%value%", value); - } - - return true; -} - -function calculateCheckDigitISSN(value) { - var z = value; - var checkdigit = 0; - var check = (8 * z[0] + 7 * z[1] + 6 * z[2] + 5 * z[3] + 4 * z[5] + 3 * z[6] + 2 * z[7]); - if (11 - (check % 11) === 10) { - checkdigit = "X"; - } else { - checkdigit = 11 - (check % 11); - } - - return checkdigit; -} +var IsbnValidation = function () { +}; -function validateISBN(value) { - var isbnDigits = splitISBN(value); +IsbnValidation.prototype.validateISBN = function (value) { + var isbnDigits = this.splitIsbn(value); if (isbnDigits.length === 10) { - return validateISBN10(value); + return this.validateISBN10(value); } else if (isbnDigits.length === 13) { - return validateISBN13(value); + return this.validateISBN13(value); } else { return messages.identifierInvalidFormat.replace("%value%", value); } -} +}; -function validateISBN10(value) { - if (value.length !== 10 && value.length !== 13) { +IsbnValidation.prototype.validateISBN13 = function (value) { + if (value.length !== 13 && value.length !== 17) { return messages.identifierInvalidFormat.replace("%value%", value); } - if (value.match(/^[\d]*((-|\s)?[\d]*){2}((-|\s)?[\dX])$/g) === null) { + if (value.match(/^(978|979)((-|\s)?[\d]*){4}$/g) === null) { return messages.identifierInvalidFormat.replace("%value%", value); } @@ -97,20 +64,20 @@ function validateISBN10(value) { return messages.identifierInvalidFormat.replace("%value%", value); } - var isbnDigits = splitISBN(value); - if (calculateCheckDigitISBN10(isbnDigits) === false) { + var isbnDigits = this.splitIsbn(value); + if (this.calculateCheckDigitISBN13(isbnDigits) === false) { return messages.identifierInvalidCheckdigit.replace("%value%", value); } return true; -} +}; -function validateISBN13(value) { - if (value.length !== 13 && value.length !== 17) { +IsbnValidation.prototype.validateISBN10 = function (value) { + if (value.length !== 10 && value.length !== 13) { return messages.identifierInvalidFormat.replace("%value%", value); } - if (value.match(/^(978|979)((-|\s)?[\d]*){4}$/g) === null) { + if (value.match(/^[\d]*((-|\s)?[\d]*){2}((-|\s)?[\dX])$/g) === null) { return messages.identifierInvalidFormat.replace("%value%", value); } @@ -118,15 +85,31 @@ function validateISBN13(value) { return messages.identifierInvalidFormat.replace("%value%", value); } - var isbnDigits = splitISBN(value); - if (calculateCheckDigitISBN13(isbnDigits) === false) { + var isbnDigits = this.splitIsbn(value); + if (this.calculateCheckDigitISBN10(isbnDigits) === false) { return messages.identifierInvalidCheckdigit.replace("%value%", value); } return true; -} +}; -function calculateCheckDigitISBN10(value) { +IsbnValidation.prototype.splitIsbn = function (value) { + var isbn = value.split(/(-|\s)/); + var digits = []; + isbn.forEach(function (isbn) { + if (isbn.match((/(-|\s)/))) { + return true; + } + var isbn_parts = isbn.split(""); + isbn_parts.forEach(function (isbn_parts) { + digits.push(isbn_parts); + }); + }); + + return digits; +}; + +IsbnValidation.prototype.calculateCheckDigitISBN10 = function (value) { var z = value; if (z[9] === "X") { @@ -136,30 +119,53 @@ function calculateCheckDigitISBN10(value) { var check = 10 * z[0] + 9 * z[1] + 8 * z[2] + 7 * z[3] + 6 * z[4] + 5 * z[5] + 4 * z[6] + 3 * z[7] + 2 * z[8] + 1 * z[9]; return (check % 11 === 0); -} +}; -function calculateCheckDigitISBN13(value) { +IsbnValidation.prototype.calculateCheckDigitISBN13 = function (value) { var z = value.map(Number); var check = (z[0] + z[2] + z[4] + z[6] + z[8] + z[10] + z[12]) + 3 * (z[1] + z[3] + z[5] + z[7] + z[9] + z[11]); return (check % 10 === 0); -} +}; -function splitISBN(value) { - var isbn = value.split(/(-|\s)/); - var digits = []; - isbn.forEach(function (isbn) { - if (isbn.match((/(-|\s)/))) { - return true; - } - var isbn_parts = isbn.split(""); - isbn_parts.forEach(function (isbn_parts) { - digits.push(isbn_parts); - }); - }); +var IssnValidation = function () { +}; - return digits; -} +IssnValidation.prototype.validateISSN = function (value) { + // check length + if (value.length !== 9) { + return messages.identifierInvalidFormat.replace("%value%", value); + } + + // check form + if (value.match(/^[0-9]{4}[-][0-9]{3}[0-9X]$/g) === null) { + return messages.identifierInvalidFormat.replace("%value%", value); + } + + // Split ISSN into its parts + var issn = value.split(""); + + // Calculate and compare check digit + var checkdigit = this.calculateCheckDigitISSN(issn); + if (checkdigit != issn[8]) { + return messages.identifierInvalidCheckdigit.replace("%value%", value); + } + + return true; +}; + +IssnValidation.prototype.calculateCheckDigitISSN = function (value) { + var z = value; + var checkdigit = 0; + var check = (8 * z[0] + 7 * z[1] + 6 * z[2] + 5 * z[3] + 4 * z[5] + 3 * z[6] + 2 * z[7]); + if (11 - (check % 11) === 10) { + checkdigit = "X"; + } else { + checkdigit = 11 - (check % 11); + } + + return checkdigit; +}; $(document).ready(function () { var selectors = []; @@ -186,11 +192,12 @@ $(document).ready(function () { $.each(identifierText, function (index, value) { value.onchange = function () { if (selectors[index] === "isbn") { - result = validateISBN(value.value); + var isbnValidator = new IsbnValidation(); + result = isbnValidator.validateISBN(value.value); } else if (selectors[index] === "issn") { - - result = validateISSN(value.value); + var issnValidator = new IssnValidation(); + result = issnValidator.validateISSN(value.value); } else { result = true; diff --git a/tests/library/Application/View/Helper/JavascriptTranslationTest.php b/tests/library/Application/View/Helper/JavascriptTranslationTest.php index 623585642..efab765c1 100644 --- a/tests/library/Application/View/Helper/JavascriptTranslationTest.php +++ b/tests/library/Application/View/Helper/JavascriptTranslationTest.php @@ -33,7 +33,7 @@ class Application_View_Helper_JavascriptTranslationTest extends ControllerTestCase { - private $_helper; + private $helper; public function setUp() { @@ -41,9 +41,9 @@ public function setUp() $this->useEnglish(); - $this->_helper = new Application_View_Helper_JavascriptTranslation(); + $this->helper = new Application_View_Helper_JavascriptTranslation(); - $this->_helper->setView(Zend_Registry::get('Opus_View')); + $this->helper->setView(Zend_Registry::get('Opus_View')); } public function testJavascriptTranslation() @@ -52,22 +52,22 @@ public function testJavascriptTranslation() 'key1' => 'message1', 'key2' => 'message2' ]; - $this->_helper->setTranslations($translations); + $this->helper->setTranslations($translations); $expectation = ''; - $reality = $this->_helper->javascriptTranslation(); + $reality = $this->helper->javascriptTranslation(); $this->assertEquals($expectation, $reality); } public function testAddTranslation() { - $this->_helper->addTranslation('key1', 'message1'); - $this->_helper->addTranslation('identifierInvalidFormat'); - $this->_helper->addTranslation('testkey'); + $this->helper->addTranslation('key1', 'message1'); + $this->helper->addTranslation('identifierInvalidFormat'); + $this->helper->addTranslation('testkey'); $translations = [ 'key1' => 'message1', @@ -75,7 +75,7 @@ public function testAddTranslation() 'testkey' => 'testkey' ]; - $this->assertEquals($translations, $this->_helper->getTranslations()); + $this->assertEquals($translations, $this->helper->getTranslations()); } public function testSetTranslations() @@ -84,12 +84,12 @@ public function testSetTranslations() 'key1' => 'message1', 'key2' => 'message2' ]; - $this->_helper->setTranslations($translations); - $this->assertEquals($translations, $this->_helper->getTranslations()); + $this->helper->setTranslations($translations); + $this->assertEquals($translations, $this->helper->getTranslations()); } public function testGetTranslations() { - $this->assertEquals([], $this->_helper->getTranslations()); + $this->assertEquals([], $this->helper->getTranslations()); } } From 45e4b87acab5278576f9257f473385f7013eae7a Mon Sep 17 00:00:00 2001 From: BioFreak95 Date: Tue, 23 Oct 2018 14:50:22 +0200 Subject: [PATCH 104/128] OPUSVIER-3899 Documentation, codingstyle and change mapping of messages --- .../View/Helper/JavascriptTranslation.php | 12 +++++-- public/layouts/opus4/js/validation.js | 32 +++++++++---------- .../View/Helper/JavascriptTranslationTest.php | 19 +++++++++++ 3 files changed, 45 insertions(+), 18 deletions(-) diff --git a/library/Application/View/Helper/JavascriptTranslation.php b/library/Application/View/Helper/JavascriptTranslation.php index eecd8128f..662f772af 100644 --- a/library/Application/View/Helper/JavascriptTranslation.php +++ b/library/Application/View/Helper/JavascriptTranslation.php @@ -31,6 +31,12 @@ * @license http://www.gnu.org/licenses/gpl.html General Public License */ +/** + * Class Application_View_Helper_JavascriptTranslation + * This view-helper creates a code snippet, what is able to deliver the translations for javascript files. + * With addTranslation, there is an possibility to add an translation-key to the code snippet. + * The key will be translated and the message will be delivered. It is also possible to insert your own key-message pair. + */ class Application_View_Helper_JavascriptTranslation extends Application_View_Helper_Abstract { private $translations = []; @@ -38,8 +44,10 @@ class Application_View_Helper_JavascriptTranslation extends Application_View_Hel public function javascriptTranslation() { $output = '" . "\n"; diff --git a/public/layouts/opus4/js/validation.js b/public/layouts/opus4/js/validation.js index 4d21e30ae..ca4a4c06d 100644 --- a/public/layouts/opus4/js/validation.js +++ b/public/layouts/opus4/js/validation.js @@ -29,10 +29,10 @@ * @license http://www.gnu.org/licenses/gpl.html General Public License */ -var messages = { - identifierInvalidCheckdigit: "The check digit of \'%value%\' is not valid", - identifierInvalidFormat: "\'%value%\' is malformed" -}; +var messages = []; +messages["identifierInvalidCheckdigit"] = "The check digit of \'%value%\' is not valid"; +messages["identifierInvalidFormat"] = "\'%value%\' is malformed"; + var IsbnValidation = function () { }; @@ -47,26 +47,26 @@ IsbnValidation.prototype.validateISBN = function (value) { return this.validateISBN13(value); } else { - return messages.identifierInvalidFormat.replace("%value%", value); + return messages["identifierInvalidFormat"].replace("%value%", value); } }; IsbnValidation.prototype.validateISBN13 = function (value) { if (value.length !== 13 && value.length !== 17) { - return messages.identifierInvalidFormat.replace("%value%", value); + return messages["identifierInvalidFormat"].replace("%value%", value); } if (value.match(/^(978|979)((-|\s)?[\d]*){4}$/g) === null) { - return messages.identifierInvalidFormat.replace("%value%", value); + return messages["identifierInvalidFormat"].replace("%value%", value); } if (value.match(/-/) !== null && value.match(/\s/) !== null) { - return messages.identifierInvalidFormat.replace("%value%", value); + return messages["identifierInvalidFormat"].replace("%value%", value); } var isbnDigits = this.splitIsbn(value); if (this.calculateCheckDigitISBN13(isbnDigits) === false) { - return messages.identifierInvalidCheckdigit.replace("%value%", value); + return messages["identifierInvalidCheckdigit"].replace("%value%", value); } return true; @@ -74,20 +74,20 @@ IsbnValidation.prototype.validateISBN13 = function (value) { IsbnValidation.prototype.validateISBN10 = function (value) { if (value.length !== 10 && value.length !== 13) { - return messages.identifierInvalidFormat.replace("%value%", value); + return messages["identifierInvalidFormat"].replace("%value%", value); } if (value.match(/^[\d]*((-|\s)?[\d]*){2}((-|\s)?[\dX])$/g) === null) { - return messages.identifierInvalidFormat.replace("%value%", value); + return messages["identifierInvalidFormat"].replace("%value%", value); } if (value.match(/-/) !== null && value.match(/\s/) !== null) { - return messages.identifierInvalidFormat.replace("%value%", value); + return messages["identifierInvalidFormat"].replace("%value%", value); } var isbnDigits = this.splitIsbn(value); if (this.calculateCheckDigitISBN10(isbnDigits) === false) { - return messages.identifierInvalidCheckdigit.replace("%value%", value); + return messages["identifierInvalidCheckdigit"].replace("%value%", value); } return true; @@ -134,12 +134,12 @@ var IssnValidation = function () { IssnValidation.prototype.validateISSN = function (value) { // check length if (value.length !== 9) { - return messages.identifierInvalidFormat.replace("%value%", value); + return messages["identifierInvalidFormat"].replace("%value%", value); } // check form if (value.match(/^[0-9]{4}[-][0-9]{3}[0-9X]$/g) === null) { - return messages.identifierInvalidFormat.replace("%value%", value); + return messages["identifierInvalidFormat"].replace("%value%", value); } // Split ISSN into its parts @@ -148,7 +148,7 @@ IssnValidation.prototype.validateISSN = function (value) { // Calculate and compare check digit var checkdigit = this.calculateCheckDigitISSN(issn); if (checkdigit != issn[8]) { - return messages.identifierInvalidCheckdigit.replace("%value%", value); + return messages["identifierInvalidCheckdigit"].replace("%value%", value); } return true; diff --git a/tests/library/Application/View/Helper/JavascriptTranslationTest.php b/tests/library/Application/View/Helper/JavascriptTranslationTest.php index efab765c1..f00ba3a6d 100644 --- a/tests/library/Application/View/Helper/JavascriptTranslationTest.php +++ b/tests/library/Application/View/Helper/JavascriptTranslationTest.php @@ -46,6 +46,9 @@ public function setUp() $this->helper->setView(Zend_Registry::get('Opus_View')); } + /** + * Tests, if the correct code-snippet for the translation will be generated. + */ public function testJavascriptTranslation() { $translations = [ @@ -63,6 +66,9 @@ public function testJavascriptTranslation() $this->assertEquals($expectation, $reality); } + /** + * Tests, if the addTranslation-function translates in the correct way and deliver the correct key-message pairs. + */ public function testAddTranslation() { $this->helper->addTranslation('key1', 'message1'); @@ -88,6 +94,19 @@ public function testSetTranslations() $this->assertEquals($translations, $this->helper->getTranslations()); } + /** + * If the translations are empty or set to null, the code snippet for the translation without any key-message pairs + * should be delivered. This is tested here. + */ + public function testSetNullTranslations() + { + $this->helper->setTranslations(null); + $reality = $this->helper->javascriptTranslation(); + $expectation = '' . "\n"; + $this->assertEquals($expectation, $reality); + } + public function testGetTranslations() { $this->assertEquals([], $this->helper->getTranslations()); From 63ea64baa653f3f0846855a32e78ce9e3495a127 Mon Sep 17 00:00:00 2001 From: BioFreak95 Date: Thu, 25 Oct 2018 15:13:11 +0200 Subject: [PATCH 105/128] OPUSVIER-3899 Add Documentation to js-testfiles and some style-changes and requirements are implemented. --- tests/javascript/testIsbnValidation.html | 182 +++++------------------ tests/javascript/testIssnValidation.html | 47 ++---- 2 files changed, 52 insertions(+), 177 deletions(-) diff --git a/tests/javascript/testIsbnValidation.html b/tests/javascript/testIsbnValidation.html index 8cb8dc050..f3ec48487 100644 --- a/tests/javascript/testIsbnValidation.html +++ b/tests/javascript/testIsbnValidation.html @@ -27,6 +27,11 @@ * @author Maximilian Salomon * @copyright Copyright (c) 2018, OPUS 4 development team * @license http://www.gnu.org/licenses/gpl.html General Public License +* +* Test of public/layouts/opus4/js/validation.js +* In this file, the ISBN-validation with JS is tested. To see the test-results, you have to open this file in a browser. +* This tests the validateISBN(), validateISBN10 and validateISBN13() functions. +* The results are shown in three different tables. --> @@ -85,14 +90,19 @@ " . "\n"; @@ -54,23 +57,29 @@ public function javascriptTranslation() return $output; } - public function addTranslation($key, $message = null) + /** + * @param $key + * @param null $message contains an optional message + * + * Adds an Message to the viewHelper. If no message is handed, the function tries to translate the handed key. + */ + public function addMessage($key, $message = null) { if ($message != null) { - $this->translations[$key] = $message; + $this->javascriptMessages [$key] = $message; } else { $message = $this->view->translate($key); - $this->translations[$key] = $message; + $this->javascriptMessages [$key] = $message; } } - public function getTranslations() + public function getMessages() { - return $this->translations; + return $this->javascriptMessages; } - public function setTranslations($value) + public function setMessages($value) { - $this->translations = $value; + $this->javascriptMessages = $value; } } diff --git a/modules/admin/controllers/DocumentController.php b/modules/admin/controllers/DocumentController.php index c961fbe39..db07b2e43 100644 --- a/modules/admin/controllers/DocumentController.php +++ b/modules/admin/controllers/DocumentController.php @@ -232,9 +232,10 @@ public function editAction() $this->renderForm($this->view->form); - $javascriptTranslations = $this->view->getHelper('javascriptTranslation'); - $javascriptTranslations->addTranslation('identifierInvalidFormat'); - $javascriptTranslations->addTranslation('identifierInvalidCheckdigit'); + // Adds translated messages for javascript files + $javascriptTranslations = $this->view->getHelper('javascriptMessages'); + $javascriptTranslations->addMessage('identifierInvalidFormat'); + $javascriptTranslations->addMessage('identifierInvalidCheckdigit'); } /** diff --git a/public/layouts/opus4/common.phtml b/public/layouts/opus4/common.phtml index c478fdde8..d1ab60379 100644 --- a/public/layouts/opus4/common.phtml +++ b/public/layouts/opus4/common.phtml @@ -145,7 +145,7 @@ if (isset($config->javascript->latex->mathjax)) { - javascriptTranslation() ?> + javascriptMessages() ?> diff --git a/public/layouts/opus4/js/validation.js b/public/layouts/opus4/js/validation.js index ca4a4c06d..7a50b332f 100644 --- a/public/layouts/opus4/js/validation.js +++ b/public/layouts/opus4/js/validation.js @@ -29,9 +29,9 @@ * @license http://www.gnu.org/licenses/gpl.html General Public License */ -var messages = []; -messages["identifierInvalidCheckdigit"] = "The check digit of \'%value%\' is not valid"; -messages["identifierInvalidFormat"] = "\'%value%\' is malformed"; +var opus4Messages = []; +opus4Messages["identifierInvalidCheckdigit"] = "The check digit of \'%value%\' is not valid"; +opus4Messages["identifierInvalidFormat"] = "\'%value%\' is malformed"; var IsbnValidation = function () { @@ -47,26 +47,26 @@ IsbnValidation.prototype.validateISBN = function (value) { return this.validateISBN13(value); } else { - return messages["identifierInvalidFormat"].replace("%value%", value); + return opus4Messages["identifierInvalidFormat"].replace("%value%", value); } }; IsbnValidation.prototype.validateISBN13 = function (value) { if (value.length !== 13 && value.length !== 17) { - return messages["identifierInvalidFormat"].replace("%value%", value); + return opus4Messages["identifierInvalidFormat"].replace("%value%", value); } if (value.match(/^(978|979)((-|\s)?[\d]*){4}$/g) === null) { - return messages["identifierInvalidFormat"].replace("%value%", value); + return opus4Messages["identifierInvalidFormat"].replace("%value%", value); } if (value.match(/-/) !== null && value.match(/\s/) !== null) { - return messages["identifierInvalidFormat"].replace("%value%", value); + return opus4Messages["identifierInvalidFormat"].replace("%value%", value); } var isbnDigits = this.splitIsbn(value); if (this.calculateCheckDigitISBN13(isbnDigits) === false) { - return messages["identifierInvalidCheckdigit"].replace("%value%", value); + return opus4Messages["identifierInvalidCheckdigit"].replace("%value%", value); } return true; @@ -74,20 +74,20 @@ IsbnValidation.prototype.validateISBN13 = function (value) { IsbnValidation.prototype.validateISBN10 = function (value) { if (value.length !== 10 && value.length !== 13) { - return messages["identifierInvalidFormat"].replace("%value%", value); + return opus4Messages["identifierInvalidFormat"].replace("%value%", value); } if (value.match(/^[\d]*((-|\s)?[\d]*){2}((-|\s)?[\dX])$/g) === null) { - return messages["identifierInvalidFormat"].replace("%value%", value); + return opus4Messages["identifierInvalidFormat"].replace("%value%", value); } if (value.match(/-/) !== null && value.match(/\s/) !== null) { - return messages["identifierInvalidFormat"].replace("%value%", value); + return opus4Messages["identifierInvalidFormat"].replace("%value%", value); } var isbnDigits = this.splitIsbn(value); if (this.calculateCheckDigitISBN10(isbnDigits) === false) { - return messages["identifierInvalidCheckdigit"].replace("%value%", value); + return opus4Messages["identifierInvalidCheckdigit"].replace("%value%", value); } return true; @@ -134,12 +134,12 @@ var IssnValidation = function () { IssnValidation.prototype.validateISSN = function (value) { // check length if (value.length !== 9) { - return messages["identifierInvalidFormat"].replace("%value%", value); + return opus4Messages["identifierInvalidFormat"].replace("%value%", value); } // check form if (value.match(/^[0-9]{4}[-][0-9]{3}[0-9X]$/g) === null) { - return messages["identifierInvalidFormat"].replace("%value%", value); + return opus4Messages["identifierInvalidFormat"].replace("%value%", value); } // Split ISSN into its parts @@ -148,7 +148,7 @@ IssnValidation.prototype.validateISSN = function (value) { // Calculate and compare check digit var checkdigit = this.calculateCheckDigitISSN(issn); if (checkdigit != issn[8]) { - return messages["identifierInvalidCheckdigit"].replace("%value%", value); + return opus4Messages["identifierInvalidCheckdigit"].replace("%value%", value); } return true; diff --git a/tests/library/Application/View/Helper/JavascriptTranslationTest.php b/tests/library/Application/View/Helper/JavascriptMessagesTest.php similarity index 62% rename from tests/library/Application/View/Helper/JavascriptTranslationTest.php rename to tests/library/Application/View/Helper/JavascriptMessagesTest.php index f00ba3a6d..b0d5d8886 100644 --- a/tests/library/Application/View/Helper/JavascriptTranslationTest.php +++ b/tests/library/Application/View/Helper/JavascriptMessagesTest.php @@ -31,7 +31,7 @@ * @license http://www.gnu.org/licenses/gpl.html General Public License */ -class Application_View_Helper_JavascriptTranslationTest extends ControllerTestCase +class Application_View_Helper_JavascriptMessagesTest extends ControllerTestCase { private $helper; @@ -41,74 +41,74 @@ public function setUp() $this->useEnglish(); - $this->helper = new Application_View_Helper_JavascriptTranslation(); + $this->helper = new Application_View_Helper_JavascriptMessages(); $this->helper->setView(Zend_Registry::get('Opus_View')); } /** - * Tests, if the correct code-snippet for the translation will be generated. + * Tests, if the correct code-snippet for the Messages will be generated. */ - public function testJavascriptTranslation() + public function testJavascriptMessages() { - $translations = [ + $Messages = [ 'key1' => 'message1', 'key2' => 'message2' ]; - $this->helper->setTranslations($translations); + $this->helper->setMessages($Messages); $expectation = ''; + . ' opus4Messages["key1"] = "message1";' . "\n" + . ' opus4Messages["key2"] = "message2";' . "\n" + . ' ' . "\n"; - $reality = $this->helper->javascriptTranslation(); + $reality = $this->helper->javascriptMessages(); $this->assertEquals($expectation, $reality); } /** - * Tests, if the addTranslation-function translates in the correct way and deliver the correct key-message pairs. + * Tests, if the addMessage-function translates in the correct way and deliver the correct key-message pairs. */ - public function testAddTranslation() + public function testAddMessage() { - $this->helper->addTranslation('key1', 'message1'); - $this->helper->addTranslation('identifierInvalidFormat'); - $this->helper->addTranslation('testkey'); + $this->helper->addMessage('key1', 'message1'); + $this->helper->addMessage('identifierInvalidFormat'); + $this->helper->addMessage('testkey'); - $translations = [ + $Messages = [ 'key1' => 'message1', 'identifierInvalidFormat' => "'%value%' is malformed.", 'testkey' => 'testkey' ]; - $this->assertEquals($translations, $this->helper->getTranslations()); + $this->assertEquals($Messages, $this->helper->getMessages()); } - public function testSetTranslations() + public function testSetMessages() { - $translations = [ + $Messages = [ 'key1' => 'message1', 'key2' => 'message2' ]; - $this->helper->setTranslations($translations); - $this->assertEquals($translations, $this->helper->getTranslations()); + $this->helper->setMessages($Messages); + $this->assertEquals($Messages, $this->helper->getMessages()); } /** - * If the translations are empty or set to null, the code snippet for the translation without any key-message pairs + * If the Messages are empty or set to null, the code snippet for the Messages without any key-message pairs * should be delivered. This is tested here. */ - public function testSetNullTranslations() + public function testSetNullMessages() { - $this->helper->setTranslations(null); - $reality = $this->helper->javascriptTranslation(); + $this->helper->setMessages(null); + $reality = $this->helper->javascriptMessages(); $expectation = '' . "\n"; $this->assertEquals($expectation, $reality); } - public function testGetTranslations() + public function testGetMessages() { - $this->assertEquals([], $this->helper->getTranslations()); + $this->assertEquals([], $this->helper->getMessages()); } } From adf1a5ec98289f043cd1394a7f594191d477b195 Mon Sep 17 00:00:00 2001 From: BioFreak95 Date: Thu, 25 Oct 2018 16:07:15 +0200 Subject: [PATCH 107/128] OPUSVIER-3899 small conflictfix --- public/layouts/opus4/common.phtml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/public/layouts/opus4/common.phtml b/public/layouts/opus4/common.phtml index d1ab60379..7d06a0a49 100644 --- a/public/layouts/opus4/common.phtml +++ b/public/layouts/opus4/common.phtml @@ -88,7 +88,7 @@ if (in_array($this->moduleName, array('admin', 'review', 'setup', 'account'))) { else if (in_array($this->moduleName, array('publish'))) { $jsFiles[] = 'upload.js'; -if (in_array($this->moduleName, array('admin'))) { +} else if (in_array($this->moduleName, array('admin'))) { $jsFiles[] = 'validation.js'; } else if (in_array($this->moduleName, array('publish'))) { $jsFiles[] = 'filetypes.js'; From f0d1fb889408c15545364b196d00e1f14fc57c2e Mon Sep 17 00:00:00 2001 From: j3nsch Date: Mon, 29 Oct 2018 16:58:57 +0100 Subject: [PATCH 108/128] OPUSVIER-3949 Sorting GND subjects alphabetical optional. --- application/configs/application.ini | 1 + .../frontdoor/views/scripts/index/index.xslt | 15 ++++++++++---- .../controllers/IndexControllerTest.php | 20 +++++++++++++++++++ 3 files changed, 32 insertions(+), 4 deletions(-) diff --git a/application/configs/application.ini b/application/configs/application.ini index d3cbc4248..4ce819ca6 100644 --- a/application/configs/application.ini +++ b/application/configs/application.ini @@ -219,6 +219,7 @@ help.separate = false frontdoor.numOfShortAbstractChars = 0 frontdoor.files.customSorting = 1 +frontdoor.subjects.alphabeticalSorting = 0 ; Visibility of fields in frontdoor (right now just BelongsToBibliography) frontdoor.metadata.BelongsToBibliography = 0 diff --git a/modules/frontdoor/views/scripts/index/index.xslt b/modules/frontdoor/views/scripts/index/index.xslt index d88bd0140..5107421ce 100644 --- a/modules/frontdoor/views/scripts/index/index.xslt +++ b/modules/frontdoor/views/scripts/index/index.xslt @@ -256,10 +256,17 @@ - - - - + + + + + + + + + + + diff --git a/tests/modules/frontdoor/controllers/IndexControllerTest.php b/tests/modules/frontdoor/controllers/IndexControllerTest.php index b0cb358de..4859262c4 100644 --- a/tests/modules/frontdoor/controllers/IndexControllerTest.php +++ b/tests/modules/frontdoor/controllers/IndexControllerTest.php @@ -363,6 +363,26 @@ public function testSeries146() { $this->assertContains('/solrsearch/index/search/searchtype/series/id/1" ', $this->getResponse()->getBody()); } + public function testSubjectSortOrder() + { + $this->dispatch('/frontdoor/index/index/docId/1'); + $this->assertContains('Informationssystem; Geschichte; Ostwald, Wilhelm', $this->getResponse()->getBody()); + } + + public function testSubjectSortOrderAlphabetical() + { + Zend_Registry::get('Zend_Config')->merge(new Zend_Config([ + 'frontdoor' => ['subjects' => ['alphabeticalSorting' => '1']] + ])); + + // frontdoor.subjects.alphabeticalSorting + + $this->dispatch('/frontdoor/index/index/docId/1'); + $this->assertContains( + 'Geschichte; Informations- und Dokumentationswissenschaft; Informationssystem', + $this->getResponse()->getBody() + ); + } /** * Regression test for OPUSVIER-2232 */ From fcc36c865b6793a9ddc68b09d165dd3e7b3e66a1 Mon Sep 17 00:00:00 2001 From: j3nsch Date: Mon, 29 Oct 2018 17:05:27 +0100 Subject: [PATCH 109/128] OPUSVIER-3949 Added new option for subject sorting to release notes. --- RELEASE_NOTES.md | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/RELEASE_NOTES.md b/RELEASE_NOTES.md index 9be9b24cb..784a6a958 100644 --- a/RELEASE_NOTES.md +++ b/RELEASE_NOTES.md @@ -2,6 +2,14 @@ --- +## Release 4.6.3 2018-11 + +Die GND-Schlagwörter werden nicht länger automatisch alphabetisch sortiert. Mit dem +Eintrag `frontdoor.subjects.alphabeticalSorting = 1` in der Datei `config.ini` kann +die Sortierung wieder aktiviert werden. + +--- + ## Release 4.6.2 2018-06-11 Mit diesem Release wird der neue DOI-Support veröffentlicht. From 13a793f32a8adb6346a1a770b13ffbaae08d0246 Mon Sep 17 00:00:00 2001 From: j3nsch Date: Thu, 1 Nov 2018 17:31:02 +0100 Subject: [PATCH 110/128] OPUSVIER-3950 Modified special character handling for BibTex citation. --- .../views/scripts/index/bibtex.xslt | 6 +- .../views/scripts/index/bibtex_article.xslt | 6 +- .../views/scripts/index/bibtex_book.xslt | 14 +- .../views/scripts/index/bibtex_bookpart.xslt | 10 +- .../index/bibtex_conferenceobject.xslt | 10 +- .../scripts/index/bibtex_doctoralthesis.xslt | 6 +- .../scripts/index/bibtex_masterthesis.xslt | 6 +- .../views/scripts/index/bibtex_preprint.xslt | 10 +- .../views/scripts/index/bibtex_report.xslt | 12 +- .../index/utils/bibtex_replace_nonascii.xslt | 119 ++++++ .../index/utils/bibtex_special_characters.xml | 402 ++++++++++++++++++ .../controller/IndexControllerTest.php | 297 +++++++++---- 12 files changed, 765 insertions(+), 133 deletions(-) create mode 100644 modules/citationExport/views/scripts/index/utils/bibtex_replace_nonascii.xslt create mode 100644 modules/citationExport/views/scripts/index/utils/bibtex_special_characters.xml diff --git a/modules/citationExport/views/scripts/index/bibtex.xslt b/modules/citationExport/views/scripts/index/bibtex.xslt index bc4ccf529..4be78b1a1 100644 --- a/modules/citationExport/views/scripts/index/bibtex.xslt +++ b/modules/citationExport/views/scripts/index/bibtex.xslt @@ -30,9 +30,9 @@ * @package Module_CitationExport * @author Oliver Marahrens * @author Gunar Maiwald - * @copyright Copyright (c) 2010, OPUS 4 development team + * @author Jens Schwidder + * @copyright Copyright (c) 2010-2018, OPUS 4 development team * @license http://www.gnu.org/licenses/gpl.html General Public License - * @version $Id$ */ --> @@ -44,7 +44,7 @@ - + diff --git a/modules/citationExport/views/scripts/index/bibtex_article.xslt b/modules/citationExport/views/scripts/index/bibtex_article.xslt index 0d711ae7c..48c63f034 100644 --- a/modules/citationExport/views/scripts/index/bibtex_article.xslt +++ b/modules/citationExport/views/scripts/index/bibtex_article.xslt @@ -30,9 +30,9 @@ * @package Module_CitationExport * @author Oliver Marahrens * @author Gunar Maiwald - * @copyright Copyright (c) 2010, OPUS 4 development team + * @author Jens Schwidder + * @copyright Copyright (c) 2010-2018, OPUS 4 development team * @license http://www.gnu.org/licenses/gpl.html General Public License - * @version $Id$ */ --> @@ -44,7 +44,7 @@ - + diff --git a/modules/citationExport/views/scripts/index/bibtex_book.xslt b/modules/citationExport/views/scripts/index/bibtex_book.xslt index e60d63e75..115782b5e 100644 --- a/modules/citationExport/views/scripts/index/bibtex_book.xslt +++ b/modules/citationExport/views/scripts/index/bibtex_book.xslt @@ -30,9 +30,9 @@ * @package Module_CitationExport * @author Oliver Marahrens * @author Gunar Maiwald - * @copyright Copyright (c) 2010, OPUS 4 development team + * @author Jens Schwidder + * @copyright Copyright (c) 2010-2018, OPUS 4 development team * @license http://www.gnu.org/licenses/gpl.html General Public License - * @version $Id$ */ --> @@ -44,7 +44,7 @@ - + @@ -134,7 +134,7 @@ editor , - + publisher @@ -144,7 +144,7 @@ address , - + volume @@ -176,8 +176,8 @@ , - note - + note + } diff --git a/modules/citationExport/views/scripts/index/bibtex_bookpart.xslt b/modules/citationExport/views/scripts/index/bibtex_bookpart.xslt index 1b9c8ec08..b4ee2dcc8 100644 --- a/modules/citationExport/views/scripts/index/bibtex_bookpart.xslt +++ b/modules/citationExport/views/scripts/index/bibtex_bookpart.xslt @@ -30,9 +30,9 @@ * @package Module_CitationExport * @author Oliver Marahrens * @author Gunar Maiwald - * @copyright Copyright (c) 2010, OPUS 4 development team + * @author Jens Schwidder + * @copyright Copyright (c) 2010-2018, OPUS 4 development team * @license http://www.gnu.org/licenses/gpl.html General Public License - * @version $Id$ */ --> @@ -44,7 +44,7 @@ - + @@ -182,8 +182,8 @@ , - note - + note + } diff --git a/modules/citationExport/views/scripts/index/bibtex_conferenceobject.xslt b/modules/citationExport/views/scripts/index/bibtex_conferenceobject.xslt index 24f2d04b4..689bebf61 100644 --- a/modules/citationExport/views/scripts/index/bibtex_conferenceobject.xslt +++ b/modules/citationExport/views/scripts/index/bibtex_conferenceobject.xslt @@ -30,9 +30,9 @@ * @package Module_CitationExport * @author Oliver Marahrens * @author Gunar Maiwald - * @copyright Copyright (c) 2010, OPUS 4 development team + * @author Jens Schwidder + * @copyright Copyright (c) 2010-2018, OPUS 4 development team * @license http://www.gnu.org/licenses/gpl.html General Public License - * @version $Id$ */ --> @@ -44,7 +44,7 @@ - + @@ -182,8 +182,8 @@ , - note - + note + } diff --git a/modules/citationExport/views/scripts/index/bibtex_doctoralthesis.xslt b/modules/citationExport/views/scripts/index/bibtex_doctoralthesis.xslt index 5d000bc5f..d7f72e277 100644 --- a/modules/citationExport/views/scripts/index/bibtex_doctoralthesis.xslt +++ b/modules/citationExport/views/scripts/index/bibtex_doctoralthesis.xslt @@ -30,9 +30,9 @@ * @package Module_CitationExport * @author Oliver Marahrens * @author Gunar Maiwald - * @copyright Copyright (c) 2010, OPUS 4 development team + * @author Jens Schwidder + * @copyright Copyright (c) 2010-2018, OPUS 4 development team * @license http://www.gnu.org/licenses/gpl.html General Public License - * @version $Id$ */ --> @@ -44,7 +44,7 @@ - + diff --git a/modules/citationExport/views/scripts/index/bibtex_masterthesis.xslt b/modules/citationExport/views/scripts/index/bibtex_masterthesis.xslt index bd46474d9..2e5d03dcb 100644 --- a/modules/citationExport/views/scripts/index/bibtex_masterthesis.xslt +++ b/modules/citationExport/views/scripts/index/bibtex_masterthesis.xslt @@ -30,9 +30,9 @@ * @package Module_CitationExport * @author Oliver Marahrens * @author Gunar Maiwald - * @copyright Copyright (c) 2010, OPUS 4 development team + * @author Jens Schwidder + * @copyright Copyright (c) 2010-2018, OPUS 4 development team * @license http://www.gnu.org/licenses/gpl.html General Public License - * @version $Id$ */ --> @@ -44,7 +44,7 @@ - + diff --git a/modules/citationExport/views/scripts/index/bibtex_preprint.xslt b/modules/citationExport/views/scripts/index/bibtex_preprint.xslt index 004a1dd42..df54079f8 100644 --- a/modules/citationExport/views/scripts/index/bibtex_preprint.xslt +++ b/modules/citationExport/views/scripts/index/bibtex_preprint.xslt @@ -30,9 +30,9 @@ * @package Module_CitationExport * @author Oliver Marahrens * @author Gunar Maiwald - * @copyright Copyright (c) 2010, OPUS 4 development team + * @author Jens Schwidder + * @copyright Copyright (c) 2010-2018, OPUS 4 development team * @license http://www.gnu.org/licenses/gpl.html General Public License - * @version $Id$ */ --> @@ -44,7 +44,7 @@ - + @@ -148,8 +148,8 @@ , - note - + note + } diff --git a/modules/citationExport/views/scripts/index/bibtex_report.xslt b/modules/citationExport/views/scripts/index/bibtex_report.xslt index 5a29a52e9..d21e488fa 100644 --- a/modules/citationExport/views/scripts/index/bibtex_report.xslt +++ b/modules/citationExport/views/scripts/index/bibtex_report.xslt @@ -30,9 +30,9 @@ * @package Module_CitationExport * @author Oliver Marahrens * @author Gunar Maiwald - * @copyright Copyright (c) 2010, OPUS 4 development team + * @author Jens Schwidder + * @copyright Copyright (c) 2010-2018, OPUS 4 development team * @license http://www.gnu.org/licenses/gpl.html General Public License - * @version $Id$ */ --> @@ -44,7 +44,7 @@ - + @@ -75,7 +75,7 @@ - + author @@ -148,8 +148,8 @@ , - note - + note + } diff --git a/modules/citationExport/views/scripts/index/utils/bibtex_replace_nonascii.xslt b/modules/citationExport/views/scripts/index/utils/bibtex_replace_nonascii.xslt new file mode 100644 index 000000000..49f244549 --- /dev/null +++ b/modules/citationExport/views/scripts/index/utils/bibtex_replace_nonascii.xslt @@ -0,0 +1,119 @@ + + + + + + + + + + + + + + + = { + + + } + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/modules/citationExport/views/scripts/index/utils/bibtex_special_characters.xml b/modules/citationExport/views/scripts/index/utils/bibtex_special_characters.xml new file mode 100644 index 000000000..4a16cf5af --- /dev/null +++ b/modules/citationExport/views/scripts/index/utils/bibtex_special_characters.xml @@ -0,0 +1,402 @@ + + + + + + % + \% + + + $ + \$ + + + & + \& + + + # + \# + + + ¡ + !' + + + £ + \pounds + + + ¤ + \i + + + § + \S + + + + \P + + + ¿ + ?' + + + À + {\`A} + + + Á + {\´A} + + + Â + {\^A} + + + Ã + {\~A} + + + Ä + {\"A} + + + Å + {\AA} + + + Æ + {\AE} + + + Ç + {\c{C}} + + + È + {\`E} + + + É + {\´E} + + + Ê + {\^E} + + + Ë + {\"E} + + + Ì + {\`I} + + + Í + {\´I} + + + Î + {\^I} + + + Ï + {\"I} + + + Ð + Ð + + + Ñ + {\~N} + + + Ò + {\`O} + + + Ó + {\´O} + + + Ô + {\^O} + + + Õ + {\~O} + + + Ö + {\"O} + + + × + × + + + Ø + {\O} + + + Ù + {\`U} + + + Ú + {\´U} + + + Û + {\^U} + + + Ü + {\"U} + + + Ý + {\´Y} + + + Þ + Þ + + + à + {\`a} + + + á + {\´a} + + + â + {\^a} + + + ã + {\~a} + + + ä + {\"a} + + + å + {\aa} + + + æ + {\ae} + + + ç + {\c{c}} + + + è + {\`e} + + + é + {\´e} + + + ê + {\^e} + + + ë + {\"e} + + + ì + {\`i} + + + í + {\´i} + + + î + {\^i} + + + ï + {\"i} + + + ð + ð + + + ñ + {\~n} + + + ò + {\`o} + + + ó + {\´o} + + + ô + {\^o} + + + õ + {\~o} + + + ö + {\"o} + + + ÷ + ÷ + + + ø + {\o} + + + ù + {\`u} + + + ú + {\´u} + + + û + {\^u} + + + ü + {\"u} + + + ý + {\´y} + + + þ + þ + + + ÿ + {\"y} + + + + + + ' + + + + ' + + + + {\"u} + + + + - + + + + - + + + + " + + + + " + + + ı + {\i} + + + ş + {\c{s}} + + + ́ + ' + + + + + + + + per mille + + + + - + + + + + + + ź + {\'{z}} + + + + + + + ecp\_ + ecp_ + + + diff --git a/tests/modules/citationExport/controller/IndexControllerTest.php b/tests/modules/citationExport/controller/IndexControllerTest.php index ab1abe051..323491667 100644 --- a/tests/modules/citationExport/controller/IndexControllerTest.php +++ b/tests/modules/citationExport/controller/IndexControllerTest.php @@ -37,11 +37,13 @@ * * @covers CitationExport_IndexController */ -class CitationExport_IndexControllerTest extends ControllerTestCase { +class CitationExport_IndexControllerTest extends ControllerTestCase +{ private $documentId; - public function setUp() { + public function setUp() + { parent::setUp(); $document = $this->createTestDocument(); @@ -52,23 +54,25 @@ public function setUp() { } /* Regression-Test OPUSVIER-2738 */ - public function testMultipleIdentifiersInRis() { - $this->dispatch('/citationExport/index/index/output/ris/docId/153'); - $this->assertResponseCode(200); - $response = $this->getResponse(); - $this->assertContains('SN - 1-2345-678-9', $response->getBody()); - $this->assertContains('SN - 1-5432-876-9', $response->getBody()); - $this->assertContains('SN - 1234-5678', $response->getBody()); - $this->assertContains('SN - 4321-8765', $response->getBody()); - $urnResolverUrl = Zend_Registry::get('Zend_Config')->urn->resolverUrl; - $this->assertContains('UR - ' . $urnResolverUrl . 'urn:nbn:de:foo:123-bar-456', $response->getBody()); - $this->assertContains('UR - ' . $urnResolverUrl . 'urn:nbn:de:foo:123-bar-789', $response->getBody()); - $this->assertContains('UR - http://www.myexampledomain.de/foo', $response->getBody()); - $this->assertContains('UR - http://www.myexampledomain.de/bar', $response->getBody()); + public function testMultipleIdentifiersInRis() + { + $this->dispatch('/citationExport/index/index/output/ris/docId/153'); + $this->assertResponseCode(200); + $response = $this->getResponse(); + $this->assertContains('SN - 1-2345-678-9', $response->getBody()); + $this->assertContains('SN - 1-5432-876-9', $response->getBody()); + $this->assertContains('SN - 1234-5678', $response->getBody()); + $this->assertContains('SN - 4321-8765', $response->getBody()); + $urnResolverUrl = Zend_Registry::get('Zend_Config')->urn->resolverUrl; + $this->assertContains('UR - ' . $urnResolverUrl . 'urn:nbn:de:foo:123-bar-456', $response->getBody()); + $this->assertContains('UR - ' . $urnResolverUrl . 'urn:nbn:de:foo:123-bar-789', $response->getBody()); + $this->assertContains('UR - http://www.myexampledomain.de/foo', $response->getBody()); + $this->assertContains('UR - http://www.myexampledomain.de/bar', $response->getBody()); } /* Regression-Test OPUSVIER-2328 */ - public function testTitleParentInRis() { + public function testTitleParentInRis() + { $this->dispatch('/citationExport/index/index/output/ris/docId/146'); $this->assertResponseCode(200); $response = $this->getResponse(); @@ -76,42 +80,58 @@ public function testTitleParentInRis() { } /* Regression-Test OPUSVIER-2328 */ - public function testPersonEditorInRis() { + public function testPersonEditorInRis() + { $this->dispatch('/citationExport/index/index/output/ris/docId/146'); $this->assertResponseCode(200); $response = $this->getResponse(); $this->assertContains('A2 - Doe, Jane', $response->getBody()); } - /* Regression-Test OPUSVIER-2716 */ - public function testSpecialCharactersInTtitle() { + /** + * Regression-Test OPUSVIER-2716 + * + * TODO use to be 'title = {Dokumenttitel mit Sonderzeichen \%-\"-\#-\&, vgl. OPUSVIER-2716.},' + * There used to be a '\' before '"'. That was removed when fixing OPUSVIER-3950. However it is not clear what + * is correct and why. + */ + public function testSpecialCharactersInTtitle() + { $this->dispatch('/citationExport/index/index/output/bibtex/docId/152'); $this->assertResponseCode(200); $response = $this->getResponse(); - $this->assertContains('title = {Dokumenttitel mit Sonderzeichen \%-\"-\#-\&, vgl. OPUSVIER-2716.},', $response->getBody()); + $this->assertContains( + 'title = {Dokumenttitel mit Sonderzeichen \%-"-\#-\&, vgl. OPUSVIER-2716.},', + $response->getBody() + ); } - public function testIndexActionWithMissingDocIdParam() { + public function testIndexActionWithMissingDocIdParam() + { $this->dispatch('/citationExport/index/index'); $this->assertResponseCode(400); } - public function testIndexActionWithInvalidDocIdParam() { + public function testIndexActionWithInvalidDocIdParam() + { $this->dispatch('/citationExport/index/index/docId/invalidid'); $this->assertResponseCode(400); } - public function testIndexActionWithMissingOutputParam() { + public function testIndexActionWithMissingOutputParam() + { $this->dispatch('/citationExport/index/index/docId/' . $this->documentId); $this->assertResponseCode(400); } - public function testIndexActionWithInvalidOutputParam() { + public function testIndexActionWithInvalidOutputParam() + { $this->dispatch('/citationExport/index/index/output/foo/docId/' . $this->documentId); $this->assertResponseCode(400); } - public function testIndexActionWithUnpublishedDocument() { + public function testIndexActionWithUnpublishedDocument() + { $doc = new Opus_Document($this->documentId); $doc->setServerState('unpublished'); $doc->store(); @@ -119,145 +139,171 @@ public function testIndexActionWithUnpublishedDocument() { $this->assertResponseCode(400); } - public function testIndexActionRis() { + public function testIndexActionRis() + { $this->dispatch('/citationExport/index/index/output/ris/docId/' . $this->documentId); $this->assertResponseCode(200); $response = $this->getResponse(); $this->assertContains('UR - ', $response->getBody()); $this->assertContains('/frontdoor/index/index/docId/' . $this->documentId, $response->getBody()); - $this->assertContains('/citationExport/index/download/output/ris/docId/' . $this->documentId, $response->getBody()); + $this->assertContains( + '/citationExport/index/download/output/ris/docId/' . $this->documentId, + $response->getBody() + ); } /* RIS - TESTS for Document-Types */ - public function testIndexActionRisDoctypeArticle() { + public function testIndexActionRisDoctypeArticle() + { $this->setDocumentType('article'); $this->dispatch('/citationExport/index/index/output/ris/docId/' . $this->documentId); $this->checkRisAssertions('JOUR'); } - public function testIndexActionRisDoctypeBook() { + public function testIndexActionRisDoctypeBook() + { $this->setDocumentType('book'); $this->dispatch('/citationExport/index/index/output/ris/docId/' . $this->documentId); $this->checkRisAssertions('BOOK'); } - public function testIndexActionRisDoctypeBookpart() { + public function testIndexActionRisDoctypeBookpart() + { $this->setDocumentType('bookpart'); $this->dispatch('/citationExport/index/index/output/ris/docId/' . $this->documentId); $this->checkRisAssertions('CHAP'); } - public function testIndexActionRisDoctypeConferenceobject() { + public function testIndexActionRisDoctypeConferenceobject() + { $this->setDocumentType('conferenceobject'); $this->dispatch('/citationExport/index/index/output/ris/docId/' . $this->documentId); $this->checkRisAssertions('CONF'); } - public function testIndexActionRisDoctypeDoctoralthesis() { + public function testIndexActionRisDoctypeDoctoralthesis() + { $this->setDocumentType('doctoralthesis'); $this->dispatch('/citationExport/index/index/output/ris/docId/' . $this->documentId); $this->checkRisAssertions('THES');; } - public function testIndexActionRisDoctypeMasterthesis() { + public function testIndexActionRisDoctypeMasterthesis() + { $this->setDocumentType('masterthesis'); $this->dispatch('/citationExport/index/index/output/ris/docId/' . $this->documentId); $this->checkRisAssertions('THES'); } - public function testIndexActionRisDoctypeBachelorthesis() { + public function testIndexActionRisDoctypeBachelorthesis() + { $this->setDocumentType('bachelorthesis'); $this->dispatch('/citationExport/index/index/output/ris/docId/' . $this->documentId); $this->checkRisAssertions('THES'); } - public function testIndexActionRisDoctypeHabilitation() { + public function testIndexActionRisDoctypeHabilitation() + { $this->setDocumentType('habilitation'); $this->dispatch('/citationExport/index/index/output/ris/docId/' . $this->documentId); $this->checkRisAssertions('THES'); } - public function testIndexActionRisDoctypeReport() { + public function testIndexActionRisDoctypeReport() + { $this->setDocumentType('report'); $this->dispatch('/citationExport/index/index/output/ris/docId/' . $this->documentId); $this->checkRisAssertions('RPRT'); } - public function testIndexActionRisPreprint() { + public function testIndexActionRisPreprint() + { $this->setDocumentType('preprint'); $this->dispatch('/citationExport/index/index/output/ris/docId/' . $this->documentId); $this->checkRisAssertions('INPR'); } - public function testIndexActionRisPeriodical() { + public function testIndexActionRisPeriodical() + { $this->setDocumentType('periodical'); $this->dispatch('/citationExport/index/index/output/ris/docId/' . $this->documentId); $this->checkRisAssertions('JFULL'); } - public function testIndexActionRisContributiontoperiodical() { + public function testIndexActionRisContributiontoperiodical() + { $this->setDocumentType('contributiontoperiodical'); $this->dispatch('/citationExport/index/index/output/ris/docId/' . $this->documentId); $this->checkRisAssertions('NEWS'); } - public function testIndexActionRisReview() { + public function testIndexActionRisReview() + { $this->setDocumentType('review'); $this->dispatch('/citationExport/index/index/output/ris/docId/' . $this->documentId); $this->checkRisAssertions('JOUR'); } - public function testIndexActionRisWorkingpaper() { + public function testIndexActionRisWorkingpaper() + { $this->setDocumentType('workingpaper'); $this->dispatch('/citationExport/index/index/output/ris/docId/' . $this->documentId); $this->checkRisAssertions('UNPD'); } - public function testIndexActionRisMovingimage() { + public function testIndexActionRisMovingimage() + { $this->setDocumentType('movingimage'); $this->dispatch('/citationExport/index/index/output/ris/docId/' . $this->documentId); $this->checkRisAssertions('VIDEO'); } - public function testIndexActionRisCoursematerial() { + public function testIndexActionRisCoursematerial() + { $this->setDocumentType('coursematerial'); $this->dispatch('/citationExport/index/index/output/ris/docId/' . $this->documentId); $this->checkRisAssertions('GEN'); } - public function testIndexActionRisImage() { + public function testIndexActionRisImage() + { $this->setDocumentType('image'); $this->dispatch('/citationExport/index/index/output/ris/docId/' . $this->documentId); $this->checkRisAssertions('GEN'); } - public function testIndexActionRisLecture() { + public function testIndexActionRisLecture() + { $this->setDocumentType('lecture'); $this->dispatch('/citationExport/index/index/output/ris/docId/' . $this->documentId); $this->checkRisAssertions('GEN'); } - public function testIndexActionRisSound() { + public function testIndexActionRisSound() + { $this->setDocumentType('sound'); $this->dispatch('/citationExport/index/index/output/ris/docId/' . $this->documentId); $this->checkRisAssertions('GEN'); } - public function testIndexActionRisStudythesis() { + public function testIndexActionRisStudythesis() + { $this->setDocumentType('studythesis'); $this->dispatch('/citationExport/index/index/output/ris/docId/' . $this->documentId); $this->checkRisAssertions('GEN'); } - public function testIndexActionRisOther() { + public function testIndexActionRisOther() + { $this->setDocumentType('other'); $this->dispatch('/citationExport/index/index/output/ris/docId/' . $this->documentId); $this->checkRisAssertions('GEN'); } - public function testIndexActionRisMisc() { + public function testIndexActionRisMisc() + { $this->setDocumentType('foo'); $this->dispatch('/citationExport/index/index/output/ris/docId/' . $this->documentId); $this->checkRisAssertions('GEN'); @@ -265,7 +311,8 @@ public function testIndexActionRisMisc() { /* RIS - TESTS for Content */ - public function testIndexActionRisSubjectUncontrolled() { + public function testIndexActionRisSubjectUncontrolled() + { $doc = new Opus_Document($this->documentId); $doc->addSubject()->setType('uncontrolled')->setValue('Freies Schlagwort'); $doc->store(); @@ -275,7 +322,8 @@ public function testIndexActionRisSubjectUncontrolled() { $this->assertContains('KW - Freies Schlagwort', $response->getBody()); } - public function testIndexActionRisSubjectSwd() { + public function testIndexActionRisSubjectSwd() + { $doc = new Opus_Document($this->documentId); $doc->addSubject()->setType('swd')->setValue('SWD-Schlagwort'); $doc->store(); @@ -285,7 +333,8 @@ public function testIndexActionRisSubjectSwd() { $this->assertContains('KW - SWD-Schlagwort', $response->getBody()); } - public function testIndexActionRisSeriesVisible() { + public function testIndexActionRisSeriesVisible() + { $s = new Opus_Series(4); $doc = new Opus_Document($this->documentId); $doc->addSeries($s)->setNumber('SeriesNumber'); @@ -297,7 +346,8 @@ public function testIndexActionRisSeriesVisible() { } - public function testIndexActionRisSeriesInvisible() { + public function testIndexActionRisSeriesInvisible() + { $s = new Opus_Series(3); $doc = new Opus_Document($this->documentId); $doc->addSeries($s)->setNumber('SeriesNumber'); @@ -308,7 +358,8 @@ public function testIndexActionRisSeriesInvisible() { $this->assertNotContains('T3 - ' . $s->getTitle() . ' - SeriesNumber', $response->getBody()); } - public function testIndexActionRisPublicNote() { + public function testIndexActionRisPublicNote() + { $doc = new Opus_Document(146); $this->dispatch('/citationExport/index/index/output/ris/docId/' . $doc->getId()); $this->assertResponseCode(200); @@ -316,7 +367,8 @@ public function testIndexActionRisPublicNote() { $this->assertContains('N1 - Für die Öffentlichkeit', $response->getBody()); } - public function testIndexActionRisPrivateNote() { + public function testIndexActionRisPrivateNote() + { $doc = new Opus_Document(146); $this->dispatch('/citationExport/index/index/output/ris/docId/' . $doc->getId()); $this->assertResponseCode(200); @@ -327,19 +379,22 @@ public function testIndexActionRisPrivateNote() { /* BIBTEX - TESTS for Documenttypes */ - public function testIndexActionBibtexDoctypeArticle() { + public function testIndexActionBibtexDoctypeArticle() + { $this->setDocumentType('article'); $this->dispatch('/citationExport/index/index/output/bibtex/docId/' . $this->documentId); $this->checkBibtexAssertions('@article'); } - public function testIndexActionBibtexDoctypeBook() { + public function testIndexActionBibtexDoctypeBook() + { $this->setDocumentType('book'); $this->dispatch('/citationExport/index/index/output/bibtex/docId/' . $this->documentId); $this->checkBibtexAssertions('@book'); } - public function testIndexActionBibtexDoctypeBookpart() { + public function testIndexActionBibtexDoctypeBookpart() + { $this->setDocumentType('bookpart'); $this->dispatch('/citationExport/index/index/output/bibtex/docId/' . $this->documentId); $this->checkBibtexAssertions('@incollection'); @@ -351,25 +406,29 @@ public function testIndexActionBibtexDoctypeConferenceobject() { $this->checkBibtexAssertions('@inproceedings'); } - public function testIndexActionBibtexDoctypeDoctoralthesis() { + public function testIndexActionBibtexDoctypeDoctoralthesis() + { $this->setDocumentType('doctoralthesis'); $this->dispatch('/citationExport/index/index/output/bibtex/docId/' . $this->documentId); $this->checkBibtexAssertions('@phdthesis'); } - public function testIndexActionBibtexDoctypeMasterthesis() { + public function testIndexActionBibtexDoctypeMasterthesis() + { $this->setDocumentType('masterthesis'); $this->dispatch('/citationExport/index/index/output/bibtex/docId/' . $this->documentId); $this->checkBibtexAssertions('@mastersthesis'); } - public function testIndexActionBibtexDoctypePreprint() { + public function testIndexActionBibtexDoctypePreprint() + { $this->setDocumentType('preprint'); $this->dispatch('/citationExport/index/index/output/bibtex/docId/' . $this->documentId); $this->checkBibtexAssertions('@unpublished'); } - public function testIndexActionBibtexDoctypeReport() { + public function testIndexActionBibtexDoctypeReport() + { $this->setDocumentType('report'); $this->dispatch('/citationExport/index/index/output/bibtex/docId/' . $this->documentId); $this->checkBibtexAssertions('@techreport'); @@ -383,7 +442,8 @@ public function testIndexActionBibtexMisc() { /* BIBTEX - TESTS for Content */ - public function testIndexActionBibtexSeriesVisible() { + public function testIndexActionBibtexSeriesVisible() + { $this->setDocumentType('preprint'); $s = new Opus_Series(4); $doc = new Opus_Document($this->documentId); @@ -396,7 +456,8 @@ public function testIndexActionBibtexSeriesVisible() { $this->assertContains('number = {SeriesNumber},', $response->getBody()); } - public function testIndexActionBibtexSeriesInvisible() { + public function testIndexActionBibtexSeriesInvisible() + { $this->setDocumentType('preprint'); $s = new Opus_Series(3); $doc = new Opus_Document($this->documentId); @@ -410,7 +471,8 @@ public function testIndexActionBibtexSeriesInvisible() { } /** Regression Test for OPUSVIER-3251 */ - public function testIndexActionBibtexEnrichmentVisibleAsNote() { + public function testIndexActionBibtexEnrichmentVisibleAsNote() + { $bibtexConfArray = array( 'citationExport' => array('bibtex' => array('enrichment' => 'SourceTitle')) ); @@ -419,32 +481,40 @@ public function testIndexActionBibtexEnrichmentVisibleAsNote() { $this->dispatch('/citationExport/index/index/output/bibtex/docId/146'); $this->assertResponseCode(200); $response = $this->getResponse(); - $this->assertContains('note = {Dieses Dokument ist auch erschienen als ...}', $response->getBody()); + $this->assertContains( + 'note = {Dieses Dokument ist auch erschienen als ...}', + $response->getBody() + ); } /* DOWNLOAD - TESTS */ - public function testDownloadActionWithMissingDocIdParam() { + public function testDownloadActionWithMissingDocIdParam() + { $this->dispatch('/citationExport/index/download'); $this->assertResponseCode(400); } - public function testDownloadActionWithInvalidDocIdParam() { + public function testDownloadActionWithInvalidDocIdParam() + { $this->dispatch('/citationExport/index/download/docId/invalidid'); $this->assertResponseCode(400); } - public function testDownloadActionWithMissingOutputParam() { + public function testDownloadActionWithMissingOutputParam() + { $this->dispatch('/citationExport/index/download/docId/' . $this->documentId); $this->assertResponseCode(400); } - public function testDownloadActionWithInvalidOutputParam() { + public function testDownloadActionWithInvalidOutputParam() + { $this->dispatch('/citationExport/index/download/output/foo/docId/' . $this->documentId); $this->assertResponseCode(400); } - public function testDownloadActionWithUnpublishedDocument() { + public function testDownloadActionWithUnpublishedDocument() + { $doc = new Opus_Document($this->documentId); $doc->setServerState('unpublished'); $doc->store(); @@ -452,7 +522,8 @@ public function testDownloadActionWithUnpublishedDocument() { $this->assertResponseCode(400); } - public function testDownloadActionRis() { + public function testDownloadActionRis() + { $this->dispatch('/citationExport/index/download/output/ris/docId/' . $this->documentId); $this->assertResponseCode(200); $response = $this->getResponse(); @@ -460,55 +531,64 @@ public function testDownloadActionRis() { $this->assertContains('/frontdoor/index/index/docId/' . $this->documentId, $response->getBody()); } - public function testDownloadActionBibtexDoctypeArticle() { + public function testDownloadActionBibtexDoctypeArticle() + { $this->setDocumentType('article'); $this->dispatch('/citationExport/index/download/output/bibtex/docId/' . $this->documentId); $this->checkBibtexAssertions('@article', false); } - public function testDownloadActionBibtexDoctypeBook() { + public function testDownloadActionBibtexDoctypeBook() + { $this->setDocumentType('book'); $this->dispatch('/citationExport/index/download/output/bibtex/docId/' . $this->documentId); $this->checkBibtexAssertions('@book', false); } - public function testDownloadActionBibtexDoctypeBookpart() { + public function testDownloadActionBibtexDoctypeBookpart() + { $this->setDocumentType('bookpart'); $this->dispatch('/citationExport/index/download/output/bibtex/docId/' . $this->documentId); $this->checkBibtexAssertions('@incollection', false); } - public function testDownloadActionBibtexDoctypeConferenceobject() { + public function testDownloadActionBibtexDoctypeConferenceobject() + { $this->setDocumentType('conferenceobject'); $this->dispatch('/citationExport/index/download/output/bibtex/docId/' . $this->documentId); $this->checkBibtexAssertions('@inproceedings', false); } - public function testDownloadActionBibtexDoctypeDoctoralthesis() { + public function testDownloadActionBibtexDoctypeDoctoralthesis() + { $this->setDocumentType('doctoralthesis'); $this->dispatch('/citationExport/index/download/output/bibtex/docId/' . $this->documentId); $this->checkBibtexAssertions('@phdthesis', false); } - public function testDownloadActionBibtexDoctypeMasterthesis() { + public function testDownloadActionBibtexDoctypeMasterthesis() + { $this->setDocumentType('masterthesis'); $this->dispatch('/citationExport/index/download/output/bibtex/docId/' . $this->documentId); $this->checkBibtexAssertions('@mastersthesis', false); } - public function testDownloadActionBibtexDoctypePreprint() { + public function testDownloadActionBibtexDoctypePreprint() + { $this->setDocumentType('preprint'); $this->dispatch('/citationExport/index/download/output/bibtex/docId/' . $this->documentId); $this->checkBibtexAssertions('@unpublished', false); } - public function testDownloadActionBibtexDoctypeReport() { + public function testDownloadActionBibtexDoctypeReport() + { $this->setDocumentType('report'); $this->dispatch('/citationExport/index/download/output/bibtex/docId/' . $this->documentId); $this->checkBibtexAssertions('@techreport', false); } - public function testDownloadActionBibtexMisc() { + public function testDownloadActionBibtexMisc() + { $this->setDocumentType('foo'); $this->dispatch('/citationExport/index/download/output/bibtex/docId/' . $this->documentId); $this->checkBibtexAssertions('@misc', false); @@ -518,7 +598,8 @@ public function testDownloadActionBibtexMisc() { * Regression-Tests für OPUSVIER-3289. * Der Test prüft, ob das Jahr mit ausgegeben wird, wenn NUR das Feld 'publishedYear' gesetzt ist. */ - public function testYearIsNotExportedWhenOnlyPublishedYearIsSet() { + public function testYearIsNotExportedWhenOnlyPublishedYearIsSet() + { $doc = $this->createTestDocument(); $doc->setPublishedYear(2013); $docId = $doc->store(); @@ -531,7 +612,8 @@ public function testYearIsNotExportedWhenOnlyPublishedYearIsSet() { * Regression-Tests für OPUSVIER-3289. * Der Test prüft, ob das Jahr mit ausgegeben wird, wenn NUR das Feld 'publishedDate' gesetzt ist. */ - public function testBibtexYearExportWithOnlyPublishedDateSet() { + public function testBibtexYearExportWithOnlyPublishedDateSet() + { $doc = $this->createTestDocument(); $doc->setPublishedDate('2012-02-01'); $docId = $doc->store(); @@ -544,7 +626,8 @@ public function testBibtexYearExportWithOnlyPublishedDateSet() { * Regression-Tests für OPUSVIER-3289. * Der Test prüft, ob das Jahr mit ausgegeben wird, wenn NUR das Feld 'completedDate' gesetzt ist. */ - public function testBibtexYearExportWithOnlyCompletedDateSet() { + public function testBibtexYearExportWithOnlyCompletedDateSet() + { $doc = $this->createTestDocument(); $doc->setCompletedDate('2012-02-01'); $docId = $doc->store(); @@ -557,7 +640,8 @@ public function testBibtexYearExportWithOnlyCompletedDateSet() { * Regression-Tests für OPUSVIER-3289. * Der Test prüft, ob das Jahr mit ausgegeben wird, wenn NUR das Feld 'completedYear' gesetzt ist. */ - public function testBibtexYearExportWithOnlyCompletedYearSet() { + public function testBibtexYearExportWithOnlyCompletedYearSet() + { $doc = $this->createTestDocument(); $doc->setCompletedYear(2012); $docId = $doc->store(); @@ -569,7 +653,8 @@ public function testBibtexYearExportWithOnlyCompletedYearSet() { /** * Der Test prüft, ob das richtige Jahr ausgegeben wird, wenn alle Felder gesetzt sind. */ - public function testBibtexYearExportWithEveryDate() { + public function testBibtexYearExportWithEveryDate() + { $doc = $this->createTestDocument(); $doc->setCompletedDate('2015-01-01'); $doc->setPublishedYear(2012); @@ -584,7 +669,8 @@ public function testBibtexYearExportWithEveryDate() { /** * Der Test prüft, ob das richtige Jahr ausgegeben wird, wenn alle Felder auf leere Strings gesetzt sind. */ - public function testBibtexYearExportWithEmptyStrings() { + public function testBibtexYearExportWithEmptyStrings() + { $doc = $this->createTestDocument(); $doc->setCompletedDate(''); $doc->setCompletedYear(null); @@ -622,29 +708,54 @@ public function testBibtexNoType() $this->assertNotQueryContentContains('//pre', "type ="); } - private function setDocumentType($documenttype) { + private function setDocumentType($documenttype) + { $doc = new Opus_Document($this->documentId); $doc->setType($documenttype); $doc->store(); } - private function checkBibtexAssertions($bibtexType, $downloadLinkExists = true) { + private function checkBibtexAssertions($bibtexType, $downloadLinkExists = true) + { $this->assertResponseCode(200); $response = $this->getResponse(); $this->assertContains($bibtexType, $response->getBody()); if ($downloadLinkExists) { - $this->assertContains('/citationExport/index/download/output/bibtex/docId/' . $this->documentId, $response->getBody()); + $this->assertContains( + '/citationExport/index/download/output/bibtex/docId/' . $this->documentId, + $response->getBody() + ); } } - private function checkRisAssertions($risType, $downloadLinkExists = true) { + private function checkRisAssertions($risType, $downloadLinkExists = true) + { $this->assertResponseCode(200); $response = $this->getResponse(); $this->assertContains('TY - ' . $risType, $response->getBody()); if ($downloadLinkExists) { - $this->assertContains('/citationExport/index/download/output/ris/docId/' . $this->documentId, $response->getBody()); + $this->assertContains( + '/citationExport/index/download/output/ris/docId/' . $this->documentId, + $response->getBody() + ); } } -} + public function testDoiRendering() + { + $doc = $this->createTestDocument(); + $doc->setType('article'); + + $doi = new Opus_Identifier(); + $doi->setValue('123_345_678'); + $doc->addIdentifierDoi($doi); + $docId = $doc->store(); + + $this->dispatch('/citationExport/index/index/output/bibtex/docId/' . $docId); + + $this->assertQueryContentContains('//pre', "@article{"); + $this->assertQueryContentContains('//pre', '123_345_678'); + $this->assertNotQueryContentContains('//pre', '123\_345\_678'); + } +} From 5cd4738c72d7e2a1f9cee91a2ee7e3e2165128cc Mon Sep 17 00:00:00 2001 From: j3nsch Date: Fri, 2 Nov 2018 14:50:00 +0100 Subject: [PATCH 111/128] OPUSVIER-3899 Provide flexibel indent. Documentation. --- .../View/Helper/JavascriptMessages.php | 83 ++++++++++++++----- .../View/Helper/JavascriptMessagesTest.php | 10 ++- 2 files changed, 69 insertions(+), 24 deletions(-) diff --git a/library/Application/View/Helper/JavascriptMessages.php b/library/Application/View/Helper/JavascriptMessages.php index 6ea357ec8..f05ec670d 100644 --- a/library/Application/View/Helper/JavascriptMessages.php +++ b/library/Application/View/Helper/JavascriptMessages.php @@ -25,51 +25,56 @@ * Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * * @category Application - * @package View_Helper_Document_Helper + * @package Application_View_Helper * @author Maximilian Salomon + * @author Jens Schwidder * @copyright Copyright (c) 2018, OPUS 4 development team * @license http://www.gnu.org/licenses/gpl.html General Public License */ /** - * Class Application_View_Helper_JavascriptMessages - * This view-helper creates a code snippet, what is able to deliver the translations for javascript files. - * With addTranslation, there is an possibility to add an translation-key to the code snippet. - * The key will be translated and the message will be delivered. It is also possible to insert your own key-message pair. + * Helper for generating Javascript providing translated messages. + * + * This view-helper creates a code snippet, that is able to deliver translations for javascript files. This is used + * to provide translated message strings to Javascript code in order to display English or German messages depending + * on the language selected by the user. */ class Application_View_Helper_JavascriptMessages extends Application_View_Helper_Abstract { + /** * @var array contains the messages with translation for javascript-files */ private $javascriptMessages = []; + /** + * Indentation of generated script code. + * @var int Integer + */ + private $indent = 8; + + /** + * TODO can this function be used for more? + */ public function javascriptMessages() { - $output = '" . "\n"; - - return $output; + return $this; } /** - * @param $key - * @param null $message contains an optional message + * Adds a translation. + * + * If no message provided, the function tries to translate the handed key. * - * Adds an Message to the viewHelper. If no message is handed, the function tries to translate the handed key. + * @param string $key Message key + * @param null|string $message contains an optional message */ public function addMessage($key, $message = null) { if ($message != null) { - $this->javascriptMessages [$key] = $message; + $this->javascriptMessages[$key] = $message; } else { - $message = $this->view->translate($key); - $this->javascriptMessages [$key] = $message; + $this->javascriptMessages[$key] = $this->view->translate($key); } } @@ -82,4 +87,42 @@ public function setMessages($value) { $this->javascriptMessages = $value; } + + public function getIndent() + { + return $this->indent; + } + + public function setIndent($indent) + { + if (is_int($indent) && $indent >= 0) { + $this->indent = $indent; + } else { + $this->indent = 0; + } + + return $this; + } + + /** + * Renders Javascript for providing translated messages. + * @return string Javascript snippet + */ + public function toString() { + $indent = str_repeat(' ', $this->getIndent()); + + $output = $indent . '\n"; + + return $output; + } + + public function __toString() { + return $this->toString(); + } } diff --git a/tests/library/Application/View/Helper/JavascriptMessagesTest.php b/tests/library/Application/View/Helper/JavascriptMessagesTest.php index b0d5d8886..0efbf93c7 100644 --- a/tests/library/Application/View/Helper/JavascriptMessagesTest.php +++ b/tests/library/Application/View/Helper/JavascriptMessagesTest.php @@ -24,15 +24,17 @@ * along with OPUS; if not, write to the Free Software Foundation, Inc., 51 * Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * - * @category Application Unit Test - * @package View_Helper + * @category Tests + * @package Application_View_Helper * @author Maximilian Salomon + * @author Jens Schwidder * @copyright Copyright (c) 2018, OPUS 4 development team * @license http://www.gnu.org/licenses/gpl.html General Public License */ class Application_View_Helper_JavascriptMessagesTest extends ControllerTestCase { + private $helper; public function setUp() @@ -57,7 +59,7 @@ public function testJavascriptMessages() ]; $this->helper->setMessages($Messages); - $expectation = '' . "\n"; @@ -102,7 +104,7 @@ public function testSetNullMessages() { $this->helper->setMessages(null); $reality = $this->helper->javascriptMessages(); - $expectation = '' . "\n"; $this->assertEquals($expectation, $reality); } From c858dd2961e66a1c4a468c9c3e780a460a02e4e6 Mon Sep 17 00:00:00 2001 From: j3nsch Date: Fri, 2 Nov 2018 14:50:23 +0100 Subject: [PATCH 112/128] OPUSVIER-3899 Indentation. Coding style. --- modules/default/language/error.tmx | 28 ++++++++++++++-------------- 1 file changed, 14 insertions(+), 14 deletions(-) diff --git a/modules/default/language/error.tmx b/modules/default/language/error.tmx index 72213c4f2..8d220d608 100644 --- a/modules/default/language/error.tmx +++ b/modules/default/language/error.tmx @@ -2,8 +2,8 @@ -
          -
          +
          +
          @@ -111,21 +111,21 @@
          - - '%value%' is malformed. - - - '%value%' hat eine unerlaubte Form. - + + '%value%' is malformed. + + + '%value%' hat eine unerlaubte Form. + - - The check digit of '%value%' is not valid". - - - Die Prüfziffer '%value%' ist nicht korrekt. - + + The check digit of '%value%' is not valid. + + + Die Prüfziffer für '%value%' ist nicht korrekt. + From be8fd17974e073324cbb20af3892631b0b11fb5d Mon Sep 17 00:00:00 2001 From: j3nsch Date: Fri, 2 Nov 2018 14:51:05 +0100 Subject: [PATCH 113/128] OPUSVIER-3899 TODO comments. Labels. --- tests/javascript/testIsbnValidation.html | 134 ++++++++++++----------- tests/javascript/testIssnValidation.html | 86 ++++++++------- 2 files changed, 114 insertions(+), 106 deletions(-) diff --git a/tests/javascript/testIsbnValidation.html b/tests/javascript/testIsbnValidation.html index f3ec48487..939cfd9c4 100644 --- a/tests/javascript/testIsbnValidation.html +++ b/tests/javascript/testIsbnValidation.html @@ -1,37 +1,41 @@ @@ -90,18 +94,18 @@ diff --git a/public/layouts/opus4/js/upload.js b/public/layouts/opus4/js/upload.js index 0d8b1bc87..297e0a108 100644 --- a/public/layouts/opus4/js/upload.js +++ b/public/layouts/opus4/js/upload.js @@ -30,6 +30,10 @@ * @license http://www.gnu.org/licenses/gpl.html General Public License */ +/** + * Array with messages for the client-sided validation. + * @type {Array} + */ var opus4Messages = []; opus4Messages["uploadedFileHasErrorMessage"] = "The file '%name%' has the following errors:"; opus4Messages["fileExtensionFalse"] = "The extension of file is not allowed."; From f9914ba8c21d940dc9729a589ca3a91d638f4416 Mon Sep 17 00:00:00 2001 From: BioFreak95 Date: Mon, 5 Nov 2018 16:46:17 +0100 Subject: [PATCH 124/128] OPUSVIER-3899 - Better understandment --- tests/javascript/testIsbnValidation.html | 142 +++++++++++------------ tests/javascript/testIssnValidation.html | 33 +++--- 2 files changed, 85 insertions(+), 90 deletions(-) diff --git a/tests/javascript/testIsbnValidation.html b/tests/javascript/testIsbnValidation.html index 939cfd9c4..5467b3bfe 100644 --- a/tests/javascript/testIsbnValidation.html +++ b/tests/javascript/testIsbnValidation.html @@ -107,9 +107,9 @@ var actual = cells[2]; var result = cells[3]; if (isbnValidator.validateISBN13(ISBN) === true) { - actual.innerHTML = "True"; + actual.innerHTML = "Valid"; } else { - actual.innerHTML = "False"; + actual.innerHTML = "Invalid"; } if (actual.innerHTML === expectation.innerHTML) { result.innerHTML = 'Passed'; @@ -133,9 +133,9 @@ var actual = cells[2]; var result = cells[3]; if (isbnValidator.validateISBN10(ISBN) === true) { - actual.innerHTML = "True"; + actual.innerHTML = "Valid"; } else { - actual.innerHTML = "False"; + actual.innerHTML = "Invalid"; } if (actual.innerHTML === expectation.innerHTML) { result.innerHTML = 'Passed'; @@ -159,9 +159,9 @@ var actual = cells[2]; var result = cells[3]; if (isbnValidator.validateISBN(ISBN) === true) { - actual.innerHTML = "True"; + actual.innerHTML = "Valid"; } else { - actual.innerHTML = "False"; + actual.innerHTML = "Invalid"; } if (actual.innerHTML === expectation.innerHTML) { result.innerHTML = 'Passed'; @@ -185,7 +185,7 @@

          Tests of ISBN-validation

          ISBN - Valid + Expectation Actual Result @@ -193,127 +193,123 @@

          Tests of ISBN-validation

          3-935024-10-X - True + Valid 393502410X - True + Valid 3-86680-192-0 - True + Valid 3-937602-69-0 - True + Valid 3 86680 192 0 - True + Valid 3 937602 69 0 - True + Valid 978-3-86680-192-9 - True + Valid 3-937602-69-0 - True + Valid 978-5-7931-8163-1 - True + Valid 978-979-3182-63-6 - True + Valid 978 3 86680 192 9 - True + Valid 978 5 7931 8163 1 - True + Valid 978 979 3182 63 6 - True + Valid 978-3-86680-192-9 - True + Valid 9789793182636 - True + Valid null - False + Invalid - False + Invalid 4711 - False + Invalid true - False + Invalid 4711-0815 - False + Invalid 980-3-86680-192-9 - False + Invalid 978-3-86680-192-5 - False + Invalid 978 3 86680-192-9 - False + Invalid null - False + Invalid - False + Invalid 4711 - False - - - true - False + Invalid 4711-0815 - False + Invalid 3-86680-192-5 - False + Invalid 3 86680 192-0 - False + Invalid 3-86680-1902-0 - False + Invalid @@ -330,67 +326,67 @@

          Tests of ISBN10-validation

          3-935024-10-X - True + Valid 393502410X - True + Valid 3-86680-192-0 - True + Valid 3-937602-69-0 - True + Valid 3 86680 192 0 - True + Valid 3 937602 69 0 - True + Valid 39376026940 - False + Invalid null - False + Invalid - False + Invalid 4711 - False + Invalid true - False + Invalid 4711-0815 - False + Invalid 978-3-86680-192-9 - False + Invalid 3-86680-192-5 - False + Invalid 3 86680 192-0 - False + Invalid 3-86680-1902-0 - False + Invalid @@ -407,67 +403,67 @@

          Tests of ISBN13-validation

          978-3-86680-192-9 - True + Valid 978-5-7931-8163-1 - True + Valid 978-979-3182-63-6 - True + Valid 978 3 86680 192 9 - True + Valid 978 5 7931 8163 1 - True + Valid 978 979 3182 63 6 - True + Valid 9789793182636 - True + Valid null - False + Invalid - False + Invalid 4711 - False + Invalid true - False + Invalid 4711-0815 - False + Invalid 980-3-86680-192-9 - False + Invalid 978-3-86680-192-5 - False + Invalid 978 3 86680-192-9 - False + Invalid 3-937602-69-0 - False + Invalid diff --git a/tests/javascript/testIssnValidation.html b/tests/javascript/testIssnValidation.html index a00053361..38e121781 100644 --- a/tests/javascript/testIssnValidation.html +++ b/tests/javascript/testIssnValidation.html @@ -33,7 +33,6 @@ * In this file, the ISBN-validation with JS is tested. To see the test-results, you have to open this file in a browser. * This tests the validateISSN() function. * - * TODO Verständlichere Ausgaben bzw. Hinweis (true = valid, false = invalid) */ --> @@ -106,9 +105,9 @@ var actual = cells[2]; var result = cells[3]; if (issnValidator.validateISSN(ISSN) === true) { - actual.innerHTML = "True"; + actual.innerHTML = "Valid"; } else { - actual.innerHTML = "False"; + actual.innerHTML = "Invalid"; } if (actual.innerHTML === expectation.innerHTML) { result.innerHTML = 'Passed'; @@ -132,61 +131,61 @@

          Tests of ISSN-validation

          Test-ISSN Expectation Actual - Test-Result + Result 1050-124X - True + Valid 0001-3218 - True + Valid 0025-5858 - True + Valid 1062-5127 - True + Valid 0317-8471 - True + Valid 12345478 - False + Invalid null - False + Invalid true - False + Invalid 12456-65478 - False + Invalid 123456789 - False + Invalid 1050 124X - False + Invalid 1050_124X - False + Invalid 1050-1242 - False + Invalid From 21546c747a79957af508f131e506a3ae02b2a09f Mon Sep 17 00:00:00 2001 From: BioFreak95 Date: Mon, 5 Nov 2018 17:02:08 +0100 Subject: [PATCH 125/128] OPUSVIER-3899 - change comment --- public/layouts/opus4/js/validation.js | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/public/layouts/opus4/js/validation.js b/public/layouts/opus4/js/validation.js index 33810474a..8193ca4a6 100644 --- a/public/layouts/opus4/js/validation.js +++ b/public/layouts/opus4/js/validation.js @@ -39,7 +39,7 @@ opus4Messages["identifierInvalidCheckdigit"] = "The check digit of \'%value%\' i opus4Messages["identifierInvalidFormat"] = "\'%value%\' is malformed"; /** - * This function is the main-function for ISBN-validation and uses the specific validation for ISBN10 and ISBN13. + * Class for ISBN validation. * * TODO Validation and message generation are mixed. No function that simply tells me valid or not. */ @@ -47,6 +47,9 @@ opus4Messages["identifierInvalidFormat"] = "\'%value%\' is malformed"; var IsbnValidation = function () { }; +/** + * This function is the main-function for ISBN-validation and uses the specific validation for ISBN10 and ISBN13. + */ IsbnValidation.prototype.validateISBN = function (value) { var isbnDigits = this.splitIsbn(value); From 4a6c20d0d6c43c3d57d40a7e09228ef026411897 Mon Sep 17 00:00:00 2001 From: j3nsch Date: Mon, 5 Nov 2018 18:59:54 +0100 Subject: [PATCH 126/128] OPUSVIER-3951 Release notes and changes. --- CHANGES.md | 55 ++++++++++++++++++++++++++++++++++++++++++++++++ RELEASE_NOTES.md | 30 +++++++++++++++++++++++++- 2 files changed, 84 insertions(+), 1 deletion(-) diff --git a/CHANGES.md b/CHANGES.md index 72dacdab3..0ef83dab1 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -2,6 +2,61 @@ --- +## Release 4.6.3 2018-11-05 + +### Feature Request + +* [OPUSVIER-2940] - Möglichkeit Dokumente direkt in der Administration zu erstellen +* [OPUSVIER-3582] - OAI-Schnittstelle erweitern um Ausgabe von DOI +* [OPUSVIER-3901] - DataCite-XML zum Debugging oder als Backup zwischenspeichern +* [OPUSVIER-3902] - Unterstützung von Microsoft Edge +* [OPUSVIER-3904] - Aufruf von Google Scholar aus der Frontdoor in einem eigenen Browserfenster +* [OPUSVIER-3906] - Datei datacite.xslt für DOI-Registrierung konfigurierbar machen +* [OPUSVIER-3908] - Prüfung von Dateinamen und deren Länge +* [OPUSVIER-3919] - Adressaten von DOI Benachrichtigungen über Accounts konfigurieren +* [OPUSVIER-3949] - GND-Schlagwörter in Frontdoor nicht alphabetisch sortieren + +### Bugs + +* [OPUSVIER-3892] - XML-Dateien werden bei Upload über SWORD ignoriert +* [OPUSVIER-3896] - Neue Enrichments und beim Update anlegen +* [OPUSVIER-3897] - Haken bei Checkbox "URN beim Veröffentlichen generieren" im Metadatenformular funktioniert nicht +* [OPUSVIER-3899] - Speichern von ungültigen Werten, z.B. ISBN, ermöglichen +* [OPUSVIER-3900] - DOIs werden nicht als lokal erkannt +* [OPUSVIER-3903] - Anzeigefehler wenn Englisch nicht als Übersetzungssprache vorhanden ist +* [OPUSVIER-3905] - Landing Page nicht korrekt +* [OPUSVIER-3907] - Bug in der Navigation in der Kurztrefferansicht +* [OPUSVIER-3909] - Enrichments ohne Wert im Import-XML sollten ohne Fehler ignoriert werden +* [OPUSVIER-3910] - Irreführende Fehlermeldung: plugin Opus_Document_Plugin_IdentifierDoi is not applicable for documents with server state ... +* [OPUSVIER-3911] - fehlendes "resumptionToken" +* [OPUSVIER-3912] - Aufruf von Twitter in neuem Browser-Fenster +* [OPUSVIER-3915] - Publish-Formular: Eingabe einer bereits im System vorhandenen DOI muss abgefangen werden +* [OPUSVIER-3916] - E-Mail-Text zum "Statusbericht über DOI-Registrierung" und "Statusbericht über DOI-Prüfung" ändern +* [OPUSVIER-3925] - assertQueryCount - Path und Count Parameter vertauscht +* [OPUSVIER-3931] - Fehler in Publish-Formular-Meldung bei zu großer Datei +* [OPUSVIER-3933] - DataCite Registrierung schlägt fehl bei fehlendem PublishedYear/CompletedYear +* [OPUSVIER-3950] - Ausgabe einer DOI mit "_" ist fehlerhaft im BibTeX CitationExport + +### Aufgaben + +* [OPUSVIER-2155] - CollectionRole-Feld "display_oai" aus Datenbank-Schema und Model entfernen +* [OPUSVIER-2294] - URN-Vergabe für bereits vorhandene Dokumente deaktivieren +* [OPUSVIER-3913] - ZIP und TAR Handhabung in PackageReader auf zwei Klassen aufteilen +* [OPUSVIER-3918] - View Helper für Ausgabe von Nachrichten +* [OPUSVIER-3920] - ActionBox Code vereinheitlichen +* [OPUSVIER-3921] - DOI Support Cron-Jobs lauffähig für OPUS-User (ohne sudo) +* [OPUSVIER-3922] - Aufruf Skript "Änderung der URL von Landing-Pages für lokale DOIs" klären und ggf. Handbuch anpassen +* [OPUSVIER-3923] - Testing OPUS 4 mit Ubuntu 18.04 LTS +* [OPUSVIER-3929] - Opus_Date-Objekte mit updateFromArray initialisieren +* [OPUSVIER-3934] - Vergleichen von Opus_Date und anderen Objekten +* [OPUSVIER-3939] - FromArray-Funktionen für Personen-Objekte +* [OPUSVIER-3945] - Erlaubnis für DOI-Notifikationen zur Zugriffskontrolle hinzufügen +* [OPUSVIER-3946] - Funktion, um alle Nutzer mit Zugriffsrecht zu ermitteln +* [OPUSVIER-3947] - Übersetzungsmechanik für Javascript +* [OPUSVIER-3948] - Funktion, um alle Jobs zu löschen + +--- + ## Release 4.6.2 2018-06-11 ### Feature Request diff --git a/RELEASE_NOTES.md b/RELEASE_NOTES.md index 784a6a958..191eecc52 100644 --- a/RELEASE_NOTES.md +++ b/RELEASE_NOTES.md @@ -2,12 +2,40 @@ --- -## Release 4.6.3 2018-11 +## Release 4.6.3 2018-11-05 + +Mit diesem Release wurden eine Reihe von Fehlern behoben und kleinere Verbesserungen +eingebaut. + +Für ISBN- und ISSN-Identifier werden jetzt im Browser mit Javascript Nachrichten +ausgegeben, wenn die Eingaben ungültig sind. Das Speichern von ungültigen Werten +wird nicht verhindert. Die GND-Schlagwörter werden nicht länger automatisch alphabetisch sortiert. Mit dem Eintrag `frontdoor.subjects.alphabeticalSorting = 1` in der Datei `config.ini` kann die Sortierung wieder aktiviert werden. +Das DataCite-XML für die DOI-Registrierung wird nun unterhalb des "log"-Verzeichnisses +gespeichert, um Probleme besser diagnostizieren zu können. +Die Empfänger von DOI-Benachrichtungen können nun über die Rechteverwaltung in der +Administration festgelegt werden. + +Dateinamen und ihre Länge werden im Publish-Formular nun bereits im Browser geprüft, +bevor die Dateien zum Server hochgeladen werden. Die Regeln für Dateinamen können in +der Konfiguration festgelegt werden. + +Neue, leere Dokumente können nun direkt in der Administration angelegt werden. Das +Duplizieren von Dokumenten in der Administration ist in Arbeit. + +Nach der Aktualisierung der Dateien (`git pull`) sollten die Composer-Abhängigkeiten +aktualisiert werden (`composer update` bzw. `php composer.phar update`). Das Schema +der Datenbank hat sich für diesen Release nicht verändert. Das Update-Skript sollte +ausgeführt werden (`bin/update.sh`), um notwendige Enrichments für den DOI-Support +anzulegen. + +Fragen können Sie gerne über die User-Mailing-Liste an die OPUS 4 Entwicklung richten: + + --- ## Release 4.6.2 2018-06-11 From e71a9b59dacdfe2638b64ba9159888b4ad997af4 Mon Sep 17 00:00:00 2001 From: j3nsch Date: Mon, 5 Nov 2018 19:29:57 +0100 Subject: [PATCH 127/128] OPUSVIER-3899 Fixed unit tests after changes. --- .../Application/Form/Validate/IdentifierTest.php | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/tests/library/Application/Form/Validate/IdentifierTest.php b/tests/library/Application/Form/Validate/IdentifierTest.php index 8f0483f8c..ee37ec626 100644 --- a/tests/library/Application/Form/Validate/IdentifierTest.php +++ b/tests/library/Application/Form/Validate/IdentifierTest.php @@ -54,6 +54,18 @@ class Application_Form_Validate_IdentifierTest extends ControllerTestCase public function setUp() { parent::setUp(); + + Zend_Registry::get('Zend_Config')->merge(new Zend_Config([ + 'identifier' => ['validation' => [ + 'isbn' => [ + 'class' => 'Opus_Validate_Isbn' + ], + 'issn' => [ + 'class' => 'Opus_Validate_Issn' + ] + ]] + ])); + $this->_element = new Application_Form_Element_Identifier('Element'); $this->_element->setValue('ISBN'); $this->_validator = new Application_Form_Validate_Identifier($this->_element); From bd5ebcaea8468b92673459210c6935a745369604 Mon Sep 17 00:00:00 2001 From: j3nsch Date: Mon, 5 Nov 2018 19:32:14 +0100 Subject: [PATCH 128/128] OPUSVIER-3541 Fixed notification form for publication. --- library/Application/Util/Notification.php | 71 +++++++++++++++---- .../View/Partial/multicheckboxtable.phtml | 5 +- .../admin/controllers/WorkflowController.php | 17 +---- modules/admin/forms/Notification.php | 3 + modules/admin/forms/WorkflowNotification.php | 35 ++++++++- .../publish/controllers/DepositController.php | 2 +- .../controllers/WorkflowControllerTest.php | 50 +++---------- .../admin/forms/WorkflowNotificationTest.php | 24 ++++++- 8 files changed, 137 insertions(+), 70 deletions(-) diff --git a/library/Application/Util/Notification.php b/library/Application/Util/Notification.php index bdda53a74..91439f247 100644 --- a/library/Application/Util/Notification.php +++ b/library/Application/Util/Notification.php @@ -48,6 +48,8 @@ public function __construct($logger = null, $config = null) * @param boolean $notifySubmitter Wenn false, wird der Submitter nicht notifiziert * @param array $notifyAuthors Bitmaske, die für jeden Autor (über den Index referenziert) angibt, ob ihm/ihr eine * E-Mail gesendet werden kann (wenn false, dann wird keine Notifizierung versendet) + * + * TODO this class should not collect recipients on its own -> recipients should be provided */ public function prepareMail($document, $url, $notifySubmitter = true, $notifyAuthors = []) { @@ -56,31 +58,76 @@ public function prepareMail($document, $url, $notifySubmitter = true, $notifyAut $logger->info("prepare notification email for document id " . $document->getId()); $authorAddresses = []; - $authors = []; + $authors = $this->getAuthors($document); + $title = $document->getMainTitle(); - $personAuthors = $document->getPersonAuthor(); - if (!empty($personAuthors)) { - $index = 0; - foreach ($personAuthors as $author) { - // TODO Komma nur wenn FirstName present - $name = trim($author->getLastName() . ", " . $author->getFirstName()); - array_push($authors, $name); + $this->scheduleNotification( + $this->getMailSubject($document->getId(), $authors, $title), + $this->getMailBody($document->getId(), $authors, $title, $url), + $this->getRecipients($authorAddresses, $document, $notifySubmitter) + ); - $index++; - } - } + $logger->info("notification mail creation was completed successfully"); + } + + /** + * @param $document + * @param $url + * @param $recipients + * + * TODO this function is only used for PublicatioNotification at the moment - cleanup! + */ + public function prepareMailFor($document, $url, $recipients) + { + $logger = $this->getLogger(); + + $logger->info("prepare notification email for document id " . $document->getId()); + + $authors = $this->getAuthors($document); $title = $document->getMainTitle(); + // TODO currently we need to convert between the old and new array structure + // TODO the components and interfaces involved need to be defined clearly + + $converted = []; + + foreach ($recipients as $address => $recipient) { + $entry = []; + $entry['address'] = $address; + + if (is_array($recipient['name'])) { + $entry['name'] = $recipient['name'][0]; // TODO only use name of first address occurence + } else { + $entry['name'] = $recipient['name']; + } + } + $this->scheduleNotification( $this->getMailSubject($document->getId(), $authors, $title), $this->getMailBody($document->getId(), $authors, $title, $url), - $this->getRecipients($authorAddresses, $document, $notifySubmitter) + $converted ); $logger->info("notification mail creation was completed successfully"); } + public function getAuthors($document) + { + $authors = []; + + $personAuthors = $document->getPersonAuthor(); + if (!empty($personAuthors)) { + foreach ($personAuthors as $author) { + // TODO Komma nur wenn FirstName present + $name = trim($author->getLastName() . ", " . $author->getFirstName()); + array_push($authors, $name); + } + } + + return $authors; + } + private function getMailSubject($docId, $authors, $title) { $logger = $this->getLogger(); diff --git a/library/Application/View/Partial/multicheckboxtable.phtml b/library/Application/View/Partial/multicheckboxtable.phtml index ca7133881..06d769e3b 100644 --- a/library/Application/View/Partial/multicheckboxtable.phtml +++ b/library/Application/View/Partial/multicheckboxtable.phtml @@ -3,7 +3,10 @@ element->getRows() as $row) : ?> - /> + + id="" name="" + /> + diff --git a/modules/admin/controllers/WorkflowController.php b/modules/admin/controllers/WorkflowController.php index 4ce073583..704f07abd 100644 --- a/modules/admin/controllers/WorkflowController.php +++ b/modules/admin/controllers/WorkflowController.php @@ -187,6 +187,7 @@ private function _changeState($document, $targetState, $form = null) private function _sendNotification($document, $form = null) { $notification = new Application_Util_PublicationNotification(); + $url = $this->view->url([ "module" => "frontdoor", "controller" => "index", @@ -197,24 +198,12 @@ private function _sendNotification($document, $form = null) true ); - $authorsBitmask = []; - $notifySubmitter = true; - - if (!is_null($form)) { - foreach ($form->getValues() as $key => $val) { - $pos = strpos($key, 'author_'); - if ($pos !== false && $pos === 0) { - array_push($authorsBitmask, $val == '1'); - } - } - $notifySubmitter = $form->getValue('submitter') == '1'; - } + $recipients = $form->getSelectedRecipients($document, $this->getRequest()->getPost()); $notification->prepareMail( $document, $this->view->serverUrl() . $url, - $notifySubmitter, - $authorsBitmask + $recipients ); } diff --git a/modules/admin/forms/Notification.php b/modules/admin/forms/Notification.php index d0efc7cdc..9881566d5 100644 --- a/modules/admin/forms/Notification.php +++ b/modules/admin/forms/Notification.php @@ -89,7 +89,9 @@ public function getRows() $option = $this->personToArray($submitters[0]); $option['value'] = 'submitter'; $option['type'] = $translator->translate('admin_workflow_notification_submitter'); + $option['checked'] = 1; $options['submitter'] = $option; + } $authors = $document->getPersonAuthor(); @@ -110,6 +112,7 @@ public function getRows() $option['value'] = 'author_' . $index; $pos = $index + 1; $option['type'] = "$pos. {$translator->translate('admin_workflow_notification_author')}"; + $option['checked'] = ($pos = 1) ? '1' : '0'; $options[] = $option; } } diff --git a/modules/admin/forms/WorkflowNotification.php b/modules/admin/forms/WorkflowNotification.php index 7b1c7c867..2d80cd090 100644 --- a/modules/admin/forms/WorkflowNotification.php +++ b/modules/admin/forms/WorkflowNotification.php @@ -88,7 +88,6 @@ public function populateFromModel($document) $this->addSubForm($subform, 'notification'); } } - /** * Returns list of recipients for document state change notifications. * @@ -113,7 +112,7 @@ public function getRecipients($document) { protected function addPersons(&$recipients, $persons, $role = 'author') { - foreach ($persons as $person) { + foreach ($persons as $index => $person) { $fullname = $person->getDisplayName(); $email = $person->getEmail(); if (strlen(trim($email)) > 0) { @@ -153,4 +152,36 @@ protected function addPersons(&$recipients, $persons, $role = 'author') } } } + + /** + * Returns the recipients that have been selected in the form. + * @return + */ + public function getSelectedRecipients($document, $post) + { + $recipients = []; + + $authors = $document->getPersonAuthor(); + + $selected = []; + + // TODO $post = $this->getValues(); + + foreach ($authors as $index => $author) { + $key = "author_$index"; + if (isset($post[$key]) && $post[$key] == '1') { + $selected[] = $authors[$index]; + } + } + + if (count($selected) > 0) { + $this->addPersons($recipients, $selected, 'author'); + } + + if (isset($post['submitter']) && $post['submitter'] == '1') { + $this->addPersons($recipients, [$document->getPersonSubmitter(0)], 'submitter'); + } + + return $recipients; + } } diff --git a/modules/publish/controllers/DepositController.php b/modules/publish/controllers/DepositController.php index 960bc218d..07eda60b0 100644 --- a/modules/publish/controllers/DepositController.php +++ b/modules/publish/controllers/DepositController.php @@ -149,7 +149,7 @@ public function depositAction() { true ); $notification->prepareMail( - $this->document, Application_Util_Notification::SUBMISSION, $this->view->serverUrl() . $url + $this->document, $this->view->serverUrl() . $url ); return $this->_helper->Redirector->redirectToAndExit($targetAction, null, $targetController, $targetModule); diff --git a/tests/modules/admin/controllers/WorkflowControllerTest.php b/tests/modules/admin/controllers/WorkflowControllerTest.php index 223daae3b..cf825ac7d 100644 --- a/tests/modules/admin/controllers/WorkflowControllerTest.php +++ b/tests/modules/admin/controllers/WorkflowControllerTest.php @@ -304,10 +304,7 @@ public function testSubmitterNotificationIsAvailable() $this->assertContains('submitter@localhost.de', $body); $this->assertContains('author@localhost.de', $body); - $this->assertContains( - 'assertXpath('//input[@type="checkbox" and @id="submitter" and @name="submitter" and @value="1" and @checked="checked"]'); } public function testAuthorNotificationIsAvailable() @@ -322,10 +319,7 @@ public function testAuthorNotificationIsAvailable() $this->assertContains('submitter@localhost.de', $body); $this->assertContains('author@localhost.de', $body); - $this->assertContains( - 'assertXpath('//input[@type="checkbox" and @id="author_0" and @name="author_0" and @value="1" and @checked="checked"]'); } public function testSubmitterNotificationIsNotAvailable() @@ -339,14 +333,8 @@ public function testSubmitterNotificationIsNotAvailable() $this->assertNotContains('submitter@localhost.de', $body); $this->assertContains('author@localhost.de', $body); - $this->assertContains( - 'assertContains( - 'assertXpath('//input[@type="checkbox" and @id="submitter" and @name="submitter" and @value="1" and @disabled="disabled"]'); + $this->assertXpath('//input[@type="checkbox" and @id="author_0" and @name="author_0" and @value="1" and @checked="checked"]'); } public function testAuthorNotificationIsNotAvailable() @@ -360,14 +348,8 @@ public function testAuthorNotificationIsNotAvailable() $this->assertContains('submitter@localhost.de', $body); $this->assertNotContains('author@localhost.de', $body); - $this->assertContains( - 'assertContains( - 'assertXpath('//input[@type="checkbox" and @id="submitter" and @name="submitter" and @value="1" and @checked="checked"]'); + $this->assertXpath('//input[@type="checkbox" and @id="author_0" and @name="author_0" and @value="1" and @disabled="disabled"]'); } public function testAuthorNotificationForMultipleAuthors() @@ -405,21 +387,11 @@ public function testAuthorNotificationForMultipleAuthors() $this->assertContains('A@localhost.de', $body); $this->assertContains('C@localhost.de', $body); - $this->assertContains( - 'assertContains( - 'assertContains( - 'assertContains( - 'assertContains( - 'assertXpath('//input[@type="checkbox" and @id="submitter" and @name="submitter" and @value="1" and @checked="checked"]'); + $this->assertXpath('//input[@type="checkbox" and @id="author_0" and @name="author_0" and @value="1" and @checked="checked"]'); + $this->assertXpath('//input[@type="checkbox" and @id="author_1" and @name="author_1" and @value="1" and @checked="checked"]'); + $this->assertXpath('//input[@type="checkbox" and @id="author_2" and @name="author_2" and @value="1" and @disabled="disabled"]'); + $this->assertXpath('//input[@type="checkbox" and @id="author_3" and @name="author_3" and @value="1" and @checked="checked"]'); } public function testShowDocInfoOnConfirmationPage() diff --git a/tests/modules/admin/forms/WorkflowNotificationTest.php b/tests/modules/admin/forms/WorkflowNotificationTest.php index cddce1b10..0533e3d30 100644 --- a/tests/modules/admin/forms/WorkflowNotificationTest.php +++ b/tests/modules/admin/forms/WorkflowNotificationTest.php @@ -86,7 +86,7 @@ public function testGetRecipients() { $this->setUpTestDocument(); - $form = new Admin_Form_DocumentStateChange('published'); + $form = new Admin_Form_WorkflowNotification('published'); $recipients = $form->getRecipients($this->doc); @@ -112,6 +112,28 @@ public function testGetRecipients() ], $recipients); } + public function testGetSelectedRecipients() { + $this->setUpTestDocument(); + + $form = new Admin_Form_WorkflowNotification('published'); + + $post = [ + 'sureyes' => 'Yes', + 'id' => 150, + 'submitter' => '1', + 'author_0' => '1', + 'author_1' => '1', + 'author_2' => '1' + ]; + + $recipients = $form->getSelectedRecipients($this->doc, $post); + + $this->assertCount(2, $recipients); + $this->assertArrayHasKey('john@example.org', $recipients); + $this->assertArrayHasKey('jane@example.org', $recipients); + + // TODO check more expectations (array structure) + } /* TODO integrate or delete * /**