/** * Update the information whether user messages should be * displayed or not. * @param $args array * @param $request PKPRequest * @return string a JSON message */ function updateUserMessageState($args, &$request) { // Exit with a fatal error if request parameters are missing. if (!isset($args['setting-name']) && isset($args['setting-value'])) { fatalError('Required request parameter "setting-name" or "setting-value" missing!'); } // Retrieve the user from the session. $user =& $request->getUser(); assert(is_a($user, 'User')); // Validate the setting. // FIXME: We don't have to retrieve the setting type (which is always bool // for user messages) but only whether the setting name is valid and the // value is boolean. $settingName = $args['setting-name']; $settingValue = $args['setting-value']; $settingType = $this->_settingType($settingName); switch ($settingType) { case 'bool': if (!($settingValue === 'false' || $settingValue === 'true')) { // Exit with a fatal error when the setting value is invalid. fatalError('Invalid setting value! Must be "true" or "false".'); } $settingValue = $settingValue === 'true' ? true : false; break; default: // Exit with a fatal error when an unknown setting is found. fatalError('Unknown setting!'); } // Persist the validated setting. $userSettingsDao =& DAORegistry::getDAO('UserSettingsDAO'); $userSettingsDao->updateSetting($user->getId(), $settingName, $settingValue, $settingType); // Return a success message. $json = new JSONMessage(true); return $json->getString(); }
/** * Display series admin page. * @param $args array * @param $request PKPRequest */ function series($args, $request) { $this->setupTemplate($request); $templateMgr = TemplateManager::getManager($request); $jsonMessage = new JSONMessage(true, $templateMgr->fetch('management/series.tpl')); return $jsonMessage->getString(); }
/** * Show the form to allow the user to select review files * (bring in/take out files from submission stage to review stage) * * FIXME: Move to its own handler so that it can be re-used among grids. * * @param $args array * @param $request PKPRequest * @return string Serialized JSON object */ function selectFiles($args, $request) { $submission = $this->getSubmission(); import('lib.pkp.controllers.grid.files.review.form.ManageReviewFilesForm'); $manageReviewFilesForm = new ManageReviewFilesForm($submission->getId(), $this->getRequestArg('stageId'), $this->getRequestArg('reviewRoundId')); $manageReviewFilesForm->initData($args, $request); $json = new JSONMessage(true, $manageReviewFilesForm->fetch($request)); return $json->getString(); }
/** * Show the form to allow the user to select review files * (bring in/take out files from submission stage to review stage) * * FIXME: Move to it's own handler so that it can be re-used among grids. * * @param $args array * @param $request PKPRequest * @return string Serialized JSON object */ function selectFiles($args, $request) { $submission = $this->getSubmission(); import('lib.pkp.controllers.grid.files.final.form.ManageFinalDraftFilesForm'); $manageFinalDraftFilesForm = new ManageFinalDraftFilesForm($submission->getId()); $manageFinalDraftFilesForm->initData($args, $request); $json = new JSONMessage(true, $manageFinalDraftFilesForm->fetch($request)); return $json->getString(); }
/** * Persist the status for a user's preference to see inline help. * @param $args array * @param $request PKPRequest * @return string Serialized JSON object */ function toggleHelp($args, $request) { $user = $request->getUser(); $user->setInlineHelp($user->getInlineHelp() ? 0 : 1); $userDao = DAORegistry::getDAO('UserDAO'); $userDao->updateObject($user); import('lib.pkp.classes.core.JSONMessage'); $json = new JSONMessage(true); return $json->getString(); }
/** * Show the publication metadata form. * @param $request Request * @param $args array * @return string JSON message */ function publicationMetadata($args, $request) { import('controllers.tab.issueEntry.form.IssueEntryPublicationMetadataForm'); $submission = $this->getSubmission(); $stageId = $this->getStageId(); $user = $request->getUser(); $issueEntryPublicationMetadataForm = new IssueEntryPublicationMetadataForm($submission->getId(), $user->getId(), $stageId, array('displayedInContainer' => true)); $issueEntryPublicationMetadataForm->initData($args, $request); $json = new JSONMessage(true, $issueEntryPublicationMetadataForm->fetch($request)); return $json->getString(); }
/** * @covers JSONMessage */ public function testGetString() { // Create a test object. $testObject = new stdClass(); $testObject->someInt = 5; $testObject->someFloat = 5.5; $json = new JSONMessage($status = true, $content = 'test content', $elementId = '0', $additionalAttributes = array('testObj' => $testObject)); $json->setEvent('someEvent', array('eventDataKey' => array('item1', 'item2'))); // Render the JSON message. $expectedString = '{"status":true,"content":"test content",' . '"elementId":"0","testObj":{"someInt":5,"someFloat":5.5},' . '"event":{"name":"someEvent","data":{"eventDataKey":["item1","item2"]}}}'; self::assertEquals($expectedString, $json->getString()); }
/** * Get a list of submission options for new catalog entries. * @param $args array * @param $request PKPRequest */ function getSubmissions($args, $request) { $press = $request->getPress(); $monographDao = DAORegistry::getDAO('MonographDAO'); $submissionsIterator = $monographDao->getUnpublishedMonographsByPressId($press->getId()); $submissions = array(); while ($monograph = $submissionsIterator->next()) { $submissions[$monograph->getId()] = $monograph->getLocalizedTitle(); } $jsonMessage = new JSONMessage(true, $submissions); return $jsonMessage->getString(); }
/** * @see LinkActionRequest::getLocalizedOptions() */ function getLocalizedOptions() { $parentLocalizedOptions = parent::getLocalizedOptions(); // override the modalHandler option. $parentLocalizedOptions['modalHandler'] = '$.pkp.controllers.modal.JsEventConfirmationModalHandler'; $parentLocalizedOptions['jsEvent'] = $this->getEvent(); if (is_array($this->getExtraArguments())) { $json = new JSONMessage(); $json->setContent($this->getExtraArguments()); $parentLocalizedOptions['extraArguments'] = $json->getString(); } return $parentLocalizedOptions; }
/** * Fetches an email template's message body and returns it via AJAX. * @param $args array * @param $request PKPRequest */ function fetchTemplateBody($args, $request) { $templateId = $request->getUserVar('template'); import('lib.pkp.classes.mail.SubmissionMailTemplate'); $template = new SubmissionMailTemplate($this->getSubmission(), $templateId); if ($template) { $user = $request->getUser(); $dispatcher = $request->getDispatcher(); $context = $request->getContext(); $template->assignParams(array('editorialContactSignature' => $user->getContactSignature(), 'signatureFullName' => $user->getFullname())); $json = new JSONMessage(true, $template->getBody() . "\n" . $context->getSetting('emailSignature')); return $json->getString(); } }
/** * Returns a JSON response containing information regarding the galley formats enabled * for this submission. * @param $args array * @param $request Request */ function fetchFormatInfo($args, $request) { $submission = $this->getSubmission(); $json = new JSONMessage(); $galleyDao = DAORegistry::getDAO('ArticleGalleyDAO'); $galleys = $galleyDao->getBySubmissionId($submission->getId()); $formats = array(); while ($galley = $galleys->next()) { $formats[$galley->getId()] = $galley->getLocalizedName(); } $json->setStatus(true); $json->setContent(true); $json->setAdditionalAttributes(array('formats' => $formats)); return $json->getString(); }
/** * Display the grid's containing page. * @param $args array * @param $request PKPRequest */ function save($args, $request) { $filename = $this->_getFilename($request); $notificationManager = new NotificationManager(); $user = $request->getUser(); $contents = $this->correctCr($request->getUserVar('fileContents')); if (file_put_contents($filename, $contents)) { $notificationManager->createTrivialNotification($user->getId()); } else { // Could not write the file $notificationManager->createTrivialNotification($user->getId(), NOTIFICATION_TYPE_ERROR, array('contents' => __('plugins.generic.translator.couldNotWriteFile', array('filename' => $filename)))); } $message = new JSONMessage(true); return $message->getString(); }
/** * Handle file uploads for cover/image art for things like Series and Categories. * @param $args array * @param $request PKPRequest */ function uploadImage($args, $request) { $router = $request->getRouter(); $context = $request->getContext(); $user = $request->getUser(); import('lib.pkp.classes.file.TemporaryFileManager'); $temporaryFileManager = new TemporaryFileManager(); $temporaryFile = $temporaryFileManager->handleUpload('uploadedFile', $user->getId()); if ($temporaryFile) { $json = new JSONMessage(true); $json->setAdditionalAttributes(array('temporaryFileId' => $temporaryFile->getId())); } else { $json = new JSONMessage(false, __('common.uploadFailed')); } return $json->getString(); }
/** * Save 'manage final draft files' form * @param $args array * @param $request PKPRequest * @return string Serialized JSON object */ function updateFinalDraftFiles($args, $request) { $submission = $this->getSubmission(); import('lib.pkp.controllers.grid.files.final.form.ManageFinalDraftFilesForm'); $manageFinalDraftFilesForm = new ManageFinalDraftFilesForm($submission->getId()); $manageFinalDraftFilesForm->readInputData(); if ($manageFinalDraftFilesForm->validate()) { $dataProvider = $this->getDataProvider(); $manageFinalDraftFilesForm->execute($args, $request, $dataProvider->getCategoryData($this->getStageId())); // Let the calling grid reload itself return DAO::getDataChangedEvent(); } else { $json = new JSONMessage(false); return $json->getString(); } }
/** * Render a category with all the rows inside of it. * @param $args array * @param $request Request * @return string the serialized row JSON message or a flag * that indicates that the row has not been found. */ function fetchCategory(&$args, &$request) { // Instantiate the requested row (includes a // validity check on the row id). $row =& $this->getRequestedCategoryRow($request, $args); $json = new JSONMessage(true); if (is_null($row)) { // Inform the client that the category does no longer exist. $json->setAdditionalAttributes(array('elementNotFound' => (int) $args['rowId'])); } else { // Render the requested category $this->setFirstDataColumn(); $json->setContent($this->_renderCategoryInternally($request, $row)); } // Render and return the JSON message. return $json->getString(); }
/** * Save 'manage review files' form. * @param $args array * @param $request PKPRequest * @return string Serialized JSON object */ function updateReviewFiles($args, $request) { $submission = $this->getSubmission(); import('lib.pkp.controllers.grid.files.review.form.ManageReviewFilesForm'); $manageReviewFilesForm = new ManageReviewFilesForm($submission->getId(), $this->getRequestArg('stageId'), $this->getRequestArg('reviewRoundId')); $manageReviewFilesForm->readInputData(); if ($manageReviewFilesForm->validate()) { $dataProvider = $this->getDataProvider(); $manageReviewFilesForm->execute($args, $request, $dataProvider->getCategoryData($this->getStageId())); $this->setupTemplate($request); $user = $request->getUser(); NotificationManager::createTrivialNotification($user->getId(), NOTIFICATION_TYPE_SUCCESS, array('contents' => __('notification.updatedReviewFiles'))); // Let the calling grid reload itself return DAO::getDataChangedEvent(); } else { $json = new JSONMessage(false); return $json->getString(); } }
/** * Save the metadata tab. * @param $args array * @param $request PKPRequest */ function saveForm($args, $request) { $this->setupTemplate($request); import('controllers.modals.submissionMetadata.form.SubmissionMetadataViewForm'); $submissionMetadataViewForm = new SubmissionMetadataViewForm($this->_submission->getId()); $json = new JSONMessage(); // Try to save the form data. $submissionMetadataViewForm->readInputData(); if ($submissionMetadataViewForm->validate()) { $submissionMetadataViewForm->execute($request); // Create trivial notification. $notificationManager = new NotificationManager(); $user = $request->getUser(); $notificationManager->createTrivialNotification($user->getId(), NOTIFICATION_TYPE_SUCCESS, array('contents' => __('notification.savedSubmissionMetadata'))); } else { $json->setStatus(false); } return $json->getString(); }
/** * Get the form contents for the given payment method. * @param $args array * @param $request PKPRequest */ function getPaymentFormContents($args, $request) { $paymentPluginName = $request->getUserVar('paymentPluginName'); $plugins =& PluginRegistry::loadCategory('paymethod'); if (!isset($plugins[$paymentPluginName])) { // Invalid plugin name $jsonMessage = new JSONMessage(false); } else { // Fetch and return the JSON-encoded form contents $plugin =& $plugins[$paymentPluginName]; $params = array(); // Blank -- OJS compatibility. Need to supply by reference. $templateMgr = TemplateManager::getManager($request); // Expose current settings to the template $context = $request->getContext(); foreach ($plugin->getSettingsFormFieldNames() as $fieldName) { $templateMgr->assign($fieldName, $plugin->getSetting($context->getId(), $fieldName)); } $jsonMessage = new JSONMessage(true, $plugin->displayPaymentSettingsForm($params, $templateMgr)); } return $jsonMessage->getString(); }
/** * AJAX request for search query auto-completion. * @param $args array * @param $request Request * @return JSON string */ function queryAutocomplete($args, $request) { $this->validate(null, $request); // Check whether auto-suggest is enabled. $suggestionList = array(); $lucenePlugin = $this->_getLucenePlugin(); $enabled = (bool) $lucenePlugin->getSetting(0, 'autosuggest'); if ($enabled) { // Retrieve search criteria from the user input. $articleSearch = new ArticleSearch(); $searchFilters = $articleSearch->getSearchFilters($request); // Get the autosuggest input and remove it from // the filter array. $autosuggestField = $request->getUserVar('searchField'); $userInput = $searchFilters[$autosuggestField]; if (isset($searchFilters[$autosuggestField])) { unset($searchFilters[$autosuggestField]); } // Instantiate a search request. $searchRequest = new SolrSearchRequest(); $searchRequest->setJournal($searchFilters['searchJournal']); $searchRequest->setFromDate($searchFilters['fromDate']); $searchRequest->setToDate($searchFilters['toDate']); $keywords = $articleSearch->getKeywordsFromSearchFilters($searchFilters); $searchRequest->addQueryFromKeywords($keywords); // Get the web service. $solrWebService = $lucenePlugin->getSolrWebService(); /* @var $solrWebService SolrWebService */ $suggestions = $solrWebService->getAutosuggestions($searchRequest, $autosuggestField, $userInput, (int) $lucenePlugin->getSetting(0, 'autosuggestType')); // Prepare a suggestion list as understood by the // autocomplete JS handler. foreach ($suggestions as $suggestion) { $suggestionList[] = array('label' => $suggestion, 'value' => $suggestion); } } // Return the suggestions as JSON message. $json = new JSONMessage(true, $suggestionList); return $json->getString(); }
/** * Delete a note. * @param $args array * @param $request PKPRequest */ function deleteNote($args, $request) { $this->setupTemplate($request); $noteId = (int) $request->getUserVar('noteId'); $noteDao = DAORegistry::getDAO('NoteDAO'); $note = $noteDao->getById($noteId); if (!$note || $note->getAssocType() != $this->_getAssocType() || $note->getAssocId() != $this->_getAssocId()) { fatalError('Invalid note!'); } $noteDao->deleteById($noteId); $user = $request->getUser(); NotificationManager::createTrivialNotification($user->getId(), NOTIFICATION_TYPE_SUCCESS, array('contents' => __('notification.removedNote'))); $json = new JSONMessage(true); return $json->getString(); }
/** * Save a submission step. * @param $args array first parameter is the step being saved * @param $request Request */ function saveStep($args, $request) { $step = isset($args[0]) ? (int) $args[0] : 1; $router = $request->getRouter(); $context = $router->getContext($request); $submission = $this->getAuthorizedContextObject(ASSOC_TYPE_SUBMISSION); $this->setupTemplate($request); $formClass = "SubmissionSubmitStep{$step}Form"; import("classes.submission.form.{$formClass}"); $submitForm = new $formClass($context, $submission); $submitForm->readInputData(); if (!HookRegistry::call('SubmissionHandler::saveSubmit', array($step, &$submission, &$submitForm))) { if ($submitForm->validate()) { $submissionId = $submitForm->execute($args, $request); if (!$submission) { return $request->redirectUrlJson($router->url($request, null, null, 'wizard', $step + 1, array('submissionId' => $submissionId), 'step-2')); } $json = new JSONMessage(true); $json->setEvent('setStep', max($step + 1, $submission->getSubmissionProgress())); } else { $json = new JSONMessage(true, $submitForm->fetch($request)); } return $json->getString(); } }
/** * Update a category * @param $args array * @param $request PKPRequest * @return string Serialized JSON object */ function updateItem($args, $request) { // -> categoryId must be present and valid // -> htmlId must be present and valid import('controllers.grid.admin.categories.form.AdminCategoryForm'); $categoryId = isset($args['rowId']) ? $args['rowId'] : null; $categoryForm = new AdminCategoryForm($categoryId); $categoryForm->readInputData(); if ($categoryForm->validate()) { $categoryForm->execute($args, $request); return DAO::getDataChangedEvent($categoryForm->categoryId); } else { $json = new JSONMessage(false); return $json->getString(); } }
/** * Displays the issue galleys page. * @param $args array * @param $request PKPRequest */ function issueGalleys($args, $request) { $issue = $this->getAuthorizedContextObject(ASSOC_TYPE_ISSUE); $issueId = $issue->getId(); $templateMgr = TemplateManager::getManager($request); import('classes.issue.IssueAction'); $templateMgr->assign('issueId', $issueId); $templateMgr->assign('unpublished', !$issue->getPublished()); $templateMgr->assign('issue', $issue); $issueGalleyDao = DAORegistry::getDAO('IssueGalleyDAO'); $templateMgr->assign('issueGalleys', $issueGalleyDao->getByIssueId($issue->getId())); $json = new JSONMessage(true, $templateMgr->fetch('controllers/grid/issues/issueGalleys.tpl')); return $json->getString(); }
/** * @see PKPRouter::handleAuthorizationFailure() */ function handleAuthorizationFailure($request, $authorizationMessage) { // Translate the authorization error message. if (defined('LOCALE_COMPONENT_APPLICATION_COMMON')) { AppLocale::requireComponents(LOCALE_COMPONENT_APPLICATION_COMMON); } AppLocale::requireComponents(LOCALE_COMPONENT_PKP_USER); $translatedAuthorizationMessage = __($authorizationMessage); // Add the router name and operation if show_stacktrace is enabled. if (Config::getVar('debug', 'show_stacktrace')) { $url = $request->getRequestUrl(); $queryString = $request->getQueryString(); if ($queryString) { $queryString = '?' . $queryString; } $translatedAuthorizationMessage .= ' [' . $url . $queryString . ']'; } // Return a JSON error message. import('lib.pkp.classes.core.JSONMessage'); $json = new JSONMessage(false, $translatedAuthorizationMessage); return $json->getString(); }
/** * Generate a JSON message with an event that can be sent * to the client to refresh itself according to changes * in the DB. * * @param $elementId string (Optional) To refresh a single element * give the element ID here. Otherwise all elements will * be refreshed. * @param $parentElementId string (Optional) To refresh a single * element that is associated with another one give the parent * element ID here. * @param $content mixed (Optional) Additional content to pass back * to the handler of the JSON message. * @return string A rendered JSON message. */ static function getDataChangedEvent($elementId = null, $parentElementId = null, $content = '') { // Create the event data. $eventData = null; if ($elementId) { $eventData = array($elementId); if ($parentElementId) { $eventData['parentElementId'] = $parentElementId; } } // Create and render the JSON message with the // event to be triggered on the client side. import('lib.pkp.classes.core.JSONMessage'); $json = new JSONMessage(true, $content); $json->setEvent('dataChanged', $eventData); return $json->getString(); }
/** * Reload the default localized settings for the journal * @param $args array * @param $request object */ function reloadLocalizedDefaultSettings($args, $request) { // make sure the locale is valid $locale = $request->getUserVar('localeToLoad'); if (!AppLocale::isLocaleValid($locale)) { $json = new JSONMessage(false); return $json->getString(); } $journal = $request->getJournal(); $journalSettingsDao = DAORegistry::getDAO('JournalSettingsDAO'); $journalSettingsDao->reloadLocalizedDefaultSettings($journal->getId(), 'registry/journalSettings.xml', array('indexUrl' => $request->getIndexUrl(), 'journalPath' => $journal->getData('path'), 'primaryLocale' => $journal->getPrimaryLocale(), 'journalName' => $journal->getName($journal->getPrimaryLocale())), $locale); // also reload the user group localizable data $userGroupDao = DAORegistry::getDAO('UserGroupDAO'); $userGroupDao->installLocale($locale, $journal->getId()); return DAO::getDataChangedEvent(); }
/** * Returns the template results as a JSON message. * @param $template string * @param $status boolean * @return string JSON message with the template rendered */ function fetchJson($template, $status = true) { import('lib.pkp.classes.core.JSONMessage'); $json = new JSONMessage($status, $this->fetch($template)); return $json->getString(); }
/** * Fetch a file that have been uploaded. * * @param $args array * @param $request Request * @return string */ function fetchFile($args, $request) { // Get the setting name. $settingName = $args['settingName']; // Try to fetch the file. $tabForm = $this->getTabForm(); $tabForm->initData($request); $renderedElement = $tabForm->renderFileView($settingName, $request); $json = new JSONMessage(); if ($renderedElement == false) { $json->setAdditionalAttributes(array('noData' => $settingName)); } else { $json->setElementId($settingName); $json->setContent($renderedElement); } return $json->getString(); }
/** * Save statistics settings. * @ */ function saveStatisticsSettings($args, $request) { $router = $request->getRouter(); $context = $router->getContext($request); $defaultMetricType = $request->getUserVar('defaultMetricType'); $context->updateSetting('defaultMetricType', $defaultMetricType); $notificationManager = new NotificationManager(); $user = $request->getUser(); $notificationManager->createTrivialNotification($user->getId()); 'classes.core.JSONMessage'; $json = new JSONMessage(); return $json->getString(); }
/** * Display the grid's containing page. * @param $args array * @param $request PKPRequest */ function save($args, $request) { $filename = $this->_getFilename($request); $notificationManager = new NotificationManager(); $user = $request->getUser(); if (!file_exists($filename)) { $dir = dirname($filename); if (!file_exists($dir)) { mkdir($dir); } $localeList = PKPLocale::getAllLocales(); file_put_contents($filename, strtr(file_get_contents(self::$plugin->getRegistryPath() . '/locale.xml'), array('{$locale}' => $this->locale, '{$localeName}' => $localeList[$this->locale]))); } // Use the EditableLocaleFile class to handle changes. import('lib.pkp.classes.file.EditableLocaleFile'); $this->file = new EditableLocaleFile($this->locale, $filename); // Delegate processing to the listbuilder handler. This will invoke the callbacks below. self::$plugin->import('controllers.listbuilder.LocaleFileListbuilderHandler'); if (LocaleFileListbuilderHandler::unpack($request, $request->getUserVar('localeKeys'))) { if ($this->file->write()) { $notificationManager->createTrivialNotification($user->getId()); } else { // Could not write the file $notificationManager->createTrivialNotification($user->getId(), NOTIFICATION_TYPE_ERROR, array('contents' => __('plugins.generic.translator.couldNotWriteFile', array('filename' => $filename)))); } } else { // Some kind of error occurred (probably garbled formatting) $notificationManager->createTrivialNotification($user->getId(), NOTIFICATION_TYPE_ERROR, array('contents' => __('plugins.generic.translator.errorEditingFile', array('filename' => $filename)))); } $message = new JSONMessage(true); return $message->getString(); }