function run(DataObjectSet $pages) { $pageIDs = $pages->column('ID'); foreach ($pageIDs as $pageID) { FormResponse::add("\$('Form_EditForm').reloadIfSetTo({$pageID});"); } $this->batchaction($pages, 'batchApprove', _t('BatchApprovePages.APPROVED_PAGES', 'Approved %d pages, %d failures')); return FormResponse::respond(); }
function run(DataObjectSet $pages) { $pageIDs = $pages->column('ID'); foreach ($pageIDs as $pageID) { FormResponse::add("\$('Form_EditForm').reloadIfSetTo({$pageID});"); } $count = array(); $count['PUBLISH_SUCCESS'] = $count['DELETE_SUCCESS'] = 0; $count['PUBLISH_FAILURE'] = $count['DELETE_FAILURE'] = 0; $arbitraryPage = $pages->First(); $arbitraryPage->invokeWithExtensions('onBeforeBatchPublish', $pages); foreach ($pages as $page) { $type = $page->openWorkflowRequest() instanceof WorkflowDeletionRequest ? 'DELETE' : 'PUBLISH'; if ($page->batchPublish()) { $count[$type . '_SUCCESS']++; // Now make sure the tree title is appropriately updated $publishedRecord = DataObject::get_by_id('SiteTree', $page->ID); if ($publishedRecord) { $JS_title = Convert::raw2js($publishedRecord->TreeTitle()); FormResponse::add("\$('sitetree').setNodeTitle({$page->ID}, '{$JS_title}');"); } } else { $count[$type . '_FAILURE']++; FormResponse::add("\$('sitetree').addNodeClassByIdx('{$page->ID}', 'failed');"); } $page->destroy(); unset($page); } $arbitraryPage->invokeWithExtensions('onAfterBatchPublish', $pages); $messages = array('PUBLISH_SUCCESS' => _t('BatchPublishPages.PUBLISH_SUCCESS', 'Published %d pages.'), 'PUBLISH_FAILURE' => _t('BatchPublishPages.PUBLISH_FAILURE', 'Failed to publish %d pages.'), 'DELETE_SUCCESS' => _t('BatchPublishPages.DELETE_SUCCESS', 'Deleted %d pages from the published site.'), 'DELETE_FAILURE' => _t('BatchPublishPages.DELETE_FAILURE', 'Failed to delete %d pages from the published site.'), 'PUBLISH_SUCCESS_ONE' => _t('BatchPublishPages.PUBLISH_SUCCESS_ONE', 'Published %d page.'), 'PUBLISH_FAILURE_ONE' => _t('BatchPublishPages.PUBLISH_FAILURE_ONE', 'Failed to publish %d page.'), 'DELETE_SUCCESS_ONE' => _t('BatchPublishPages.DELETE_SUCCESS_ONE', 'Deleted %d page from the published site.'), 'DELETE_FAILURE_ONE' => _t('BatchPublishPages.DELETE_FAILURE_ONE', 'Failed to delete %d page from the published site.')); $displayedMessages = array(); foreach ($count as $type => $count) { if ($count) { $message = $count == 1 ? $messages[$type . '_ONE'] : $messages[$type]; $displayedMessages[] = sprintf($message, $count); } } $displayedMessage = implode(" ", $displayedMessages); FormResponse::add('statusMessage("' . $displayedMessage . '","good");'); return FormResponse::respond(); }
function moderate() { $id = (int) $this->urlParams['ID']; $className = Convert::raw2sql($this->urlParams['ClassName']); $state = Convert::raw2sql($this->urlParams['State']); $methods = array("delete" => "moderatorDelete", "isspam" => "markSpam", "isham" => "markHam", "approve" => "markApproved", "unapprove" => "markUnapproved"); ModeratableState::push_state($state); $method = $methods[$this->urlParams['Command']]; if (!$method) { FormResponse::clear(); FormResponse::status_message("Command invalid", 'bad'); } else { if ($error = DataObject::get_by_id($className, $id)->{$method}()) { FormResponse::status_message($error, 'bad'); } else { FormResponse::add('$("moderation").elementMoved(' . $id . ');'); } } ModeratableState::pop_state(); return FormResponse::respond(); }
/** * When an error page is published, create a static HTML page with its * content, so the page can be shown even when SilverStripe is not * functioning correctly before publishing this page normally. * @param string|int $fromStage Place to copy from. Can be either a stage name or a version number. * @param string $toStage Place to copy to. Must be a stage name. * @param boolean $createNewVersion Set this to true to create a new version number. By default, the existing version number will be copied over. */ function doPublish() { parent::doPublish(); // Run the page $response = Director::test(Director::makeRelative($this->Link())); $errorContent = $response->getBody(); // Check we have an assets base directory, creating if it we don't if (!file_exists(ASSETS_PATH)) { mkdir(ASSETS_PATH, 02775); } // if the page is published in a language other than default language, // write a specific language version of the HTML page $filePath = self::get_filepath_for_errorcode($this->ErrorCode, $this->Locale); if ($fh = fopen($filePath, "w")) { fwrite($fh, $errorContent); fclose($fh); } else { $fileErrorText = sprintf(_t("ErrorPage.ERRORFILEPROBLEM", "Error opening file \"%s\" for writing. Please check file permissions."), $errorFile); FormResponse::status_message($fileErrorText, 'bad'); FormResponse::respond(); return; } }
public function startrun() { $task = new LinkCheckTask(); $result = $task->process(); $script = ''; if (class_exists('SapphireTest', false) && SapphireTest::is_running_test()) { return; } if (!$result) { FormResponse::status_message('There is already a link check running at the moment. Please wait for it to complete before starting a new one.', 'bad'); return FormResponse::respond(); } if (!empty($result['LinkCheckRunID'])) { $run = DataObject::get_by_id('LinkCheckRun', (int) $result['LinkCheckRunID']); if ($run) { echo $this->addTreeNodeJS($run, true); } } }
/** * When an error page is published, create a static HTML page with its * content, so the page can be shown even when SilverStripe is not * functioning correctly before publishing this page normally. * @param string|int $fromStage Place to copy from. Can be either a stage name or a version number. * @param string $toStage Place to copy to. Must be a stage name. * @param boolean $createNewVersion Set this to true to create a new version number. By default, the existing version number will be copied over. */ function doPublish() { parent::doPublish(); // Run the page (reset the theme, it might've been disabled by LeftAndMain::init()) $oldTheme = SSViewer::current_theme(); SSViewer::set_theme(SSViewer::current_custom_theme()); $response = Director::test(Director::makeRelative($this->Link())); SSViewer::set_theme($oldTheme); $errorContent = $response->getBody(); // Make the base tag dynamic. // $errorContent = preg_replace('/<base[^>]+href="' . str_replace('/','\\/', Director::absoluteBaseURL()) . '"[^>]*>/i', '<base href="$BaseURL" />', $errorContent); // Check we have an assets base directory, creating if it we don't if (!file_exists(ASSETS_PATH)) { mkdir(ASSETS_PATH, 02775); } // if the page is published in a language other than default language, // write a specific language version of the HTML page $filePath = self::get_filepath_for_errorcode($this->ErrorCode, $this->Locale); if ($fh = fopen($filePath, "w")) { fwrite($fh, $errorContent); fclose($fh); } else { $fileErrorText = sprintf(_t("ErrorPage.ERRORFILEPROBLEM", "Error opening file \"%s\" for writing. Please check file permissions."), $errorFile); FormResponse::status_message($fileErrorText, 'bad'); FormResponse::respond(); return; } }
public function exportastarball() { $template = $this->getCurrentDynamicTemplate(); if (!$template) { FormResponse::status_message("No template selected, Please select template"); FormResponse::load_form($this->getitem(), 'Form_EditForm'); return FormResponse::respond(); } else { $fileData = $template->exportAs("tar.gz"); $fileName = $template->Name . ".tar.gz"; return SS_HTTPRequest::send_file($fileData, $fileName, "application/x-tar"); } }
/** * Create a new translation from an existing item, switch to this language and reload the tree. */ function createtranslation($request) { // Protect against CSRF on destructive action if (!SecurityToken::inst()->checkRequest($request)) { return $this->httpError(400); } $langCode = Convert::raw2sql($_REQUEST['newlang']); $originalLangID = (int) $_REQUEST['ID']; $record = $this->getRecord($originalLangID); $this->Locale = $langCode; Translatable::set_current_locale($langCode); // Create a new record in the database - this is different // to the usual "create page" pattern of storing the record // in-memory until a "save" is performed by the user, mainly // to simplify things a bit. // @todo Allow in-memory creation of translations that don't persist in the database before the user requests it $translatedRecord = $record->createTranslation($langCode); $url = sprintf("%s/%d/?locale=%s", $this->Link('show'), $translatedRecord->ID, $langCode); FormResponse::add(sprintf('window.location.href = "%s";', $url)); return FormResponse::respond(); }
/** * When an error page is published, create a static HTML page with its * content, so the page can be shown even when SilverStripe is not * functioning correctly before publishing this page normally. * @param string|int $fromStage Place to copy from. Can be either a stage name or a version number. * @param string $toStage Place to copy to. Must be a stage name. * @param boolean $createNewVersion Set this to true to create a new version number. By default, the existing version number will be copied over. */ function publish($fromStage, $toStage, $createNewVersion = false) { $oldStage = Versioned::current_stage(); // Run the page $response = Director::test(Director::makeRelative($this->Link())); $errorContent = $response->getBody(); // Check we have an assets base directory, creating if it we don't if(!file_exists(ASSETS_PATH)) { mkdir(ASSETS_PATH, 02775); } // Path to the error file in the file store $errorFile = ASSETS_PATH . "/error-$this->ErrorCode.html"; // Attempt to open the file, writing it if it doesn't exist $fh = @fopen($errorFile, "w"); if($fh) { fwrite($fh, $errorContent); fclose($fh); } else { $fileErrorText = sprintf( _t( "ErrorPage.ERRORFILEPROBLEM", "Error opening file \"%s\" for writing. Please check file permissions." ), $errorFile ); FormResponse::status_message($fileErrorText, 'bad'); FormResponse::respond(); return; } // Restore the version we're currently connected to. Versioned::reading_stage($oldStage); return $this->extension_instances['Versioned']->publish($fromStage, $toStage, $createNewVersion); }
/** * Handle a form submission. GET and POST requests behave identically. * Populates the form with {@link loadDataFrom()}, calls {@link validate()}, * and only triggers the requested form action/method * if the form is valid. */ function httpSubmission($request) { $vars = $request->requestVars(); if(isset($funcName)) { Form::set_current_action($funcName); } // Populate the form $this->loadDataFrom($vars, true); // Validate the form if(!$this->validate()) { if(Director::is_ajax()) { return FormResponse::respond(); } else { Director::redirectBack(); return; } } // Protection against CSRF attacks if($this->securityTokenEnabled()) { $securityID = Session::get('SecurityID'); if(!$securityID || !isset($vars['SecurityID']) || $securityID != $vars['SecurityID']) { $this->httpError(400, "SecurityID doesn't match, possible CRSF attack."); } } // Determine the action button clicked $funcName = null; foreach($vars as $paramName => $paramVal) { if(substr($paramName,0,7) == 'action_') { // Break off querystring arguments included in the action if(strpos($paramName,'?') !== false) { list($paramName, $paramVars) = explode('?', $paramName, 2); $newRequestParams = array(); parse_str($paramVars, $newRequestParams); $vars = array_merge((array)$vars, (array)$newRequestParams); } // Cleanup action_, _x and _y from image fields $funcName = preg_replace(array('/^action_/','/_x$|_y$/'),'',$paramName); break; } } // If the action wasnt' set, choose the default on the form. if(!isset($funcName) && $defaultAction = $this->defaultAction()){ $funcName = $defaultAction->actionName(); } if(isset($funcName)) { $this->setButtonClicked($funcName); } // First, try a handler method on the controller if($this->controller->hasMethod($funcName)) { return $this->controller->$funcName($vars, $this, $request); // Otherwise, try a handler method on the form object } else { return $this->$funcName($vars, $this, $request); } }
/** * Processing that occurs before a form is executed. * This includes form validation, if it fails, we redirect back * to the form with appropriate error messages */ function beforeProcessing() { if ($this->validator) { $errors = $this->validator->validate(); if ($errors) { if (Director::is_ajax()) { // Send validation errors back as JSON with a flag at the start //echo "VALIDATIONERROR:" . Convert::array2json($errors); FormResponse::status_message(_t('Form.VALIDATIONFAILED', 'Validation failed'), 'bad'); foreach ($errors as $error) { FormResponse::add(sprintf("validationError('%s', '%s', '%s');\n", Convert::raw2js($error['fieldName']), Convert::raw2js($error['message']), Convert::raw2js($error['messageType']))); } echo FormResponse::respond(); return false; } else { $data = $this->getData(); // People will get worried if you leave credit card information in session.. if (isset($data['CreditCardNumber'])) { unset($data['CreditCardNumber']); } if (isset($data['DateExpiry'])) { unset($data['Expiry']); } // Load errors into session and post back Session::set("FormInfo.{$this->FormName()}", array('errors' => $errors, 'data' => $data)); Director::redirectBack(); } return false; } } return true; }
function httpSubmission($request) { $vars = $request->requestVars(); if (isset($funcName)) { Form::set_current_action($funcName); } // Populate the form $this->loadDataFrom($vars, true); // Protection against CSRF attacks $token = $this->getSecurityToken(); if (!$token->checkRequest($request)) { $this->httpError(400, _t('AdvancedWorkflowFrontendForm.SECURITYTOKENCHECK', "Security token doesn't match, possible CSRF attack.")); } // Determine the action button clicked $funcName = null; foreach ($vars as $paramName => $paramVal) { if (substr($paramName, 0, 7) == 'action_') { // Added for frontend workflow form - get / set transitionID on controller, // unset action and replace with doFrontEndAction action if (substr($paramName, 0, 18) == 'action_transition_') { $this->controller->transitionID = substr($paramName, strrpos($paramName, '_') + 1); unset($vars['action_transition_' . $this->controller->transitionID]); $vars['action_doFrontEndAction'] = 'doFrontEndAction'; $paramName = 'action_doFrontEndAction'; $paramVal = 'doFrontEndAction'; } // Break off querystring arguments included in the action if (strpos($paramName, '?') !== false) { list($paramName, $paramVars) = explode('?', $paramName, 2); $newRequestParams = array(); parse_str($paramVars, $newRequestParams); $vars = array_merge((array) $vars, (array) $newRequestParams); } // Cleanup action_, _x and _y from image fields $funcName = preg_replace(array('/^action_/', '/_x$|_y$/'), '', $paramName); break; } } // If the action wasnt' set, choose the default on the form. if (!isset($funcName) && ($defaultAction = $this->defaultAction())) { $funcName = $defaultAction->actionName(); } if (isset($funcName)) { $this->setButtonClicked($funcName); } // Permission checks (first on controller, then falling back to form) if ($this->controller->hasMethod($funcName) && !$this->controller->checkAccessAction($funcName) && !$this->Actions()->fieldByName('action_' . $funcName)) { return $this->httpError(403, sprintf(_t('AdvancedWorkflowFrontendForm.ACTIONCONTROLLERCHECK', 'Action "%s" not allowed on controller (Class: %s)'), $funcName, get_class($this->controller))); } elseif ($this->hasMethod($funcName) && !$this->checkAccessAction($funcName)) { return $this->httpError(403, sprintf(_t('AdvancedWorkflowFrontendForm.ACTIONFORMCHECK', 'Action "%s" not allowed on form (Name: "%s")'), $funcName, $this->Name())); } if ($wfTransition = $this->controller->getCurrentTransition()) { $wfTransType = $wfTransition->Type; } else { $wfTransType = null; //ie. when a custom Form Action is defined in WorkflowAction } // Validate the form if (!$this->validate() && $wfTransType == 'Active') { if (Director::is_ajax()) { // Special case for legacy Validator.js implementation (assumes eval'ed javascript collected through FormResponse) if ($this->validator->getJavascriptValidationHandler() == 'prototype') { return FormResponse::respond(); } else { $acceptType = $request->getHeader('Accept'); if (strpos($acceptType, 'application/json') !== FALSE) { // Send validation errors back as JSON with a flag at the start $response = new SS_HTTPResponse(Convert::array2json($this->validator->getErrors())); $response->addHeader('Content-Type', 'application/json'); } else { $this->setupFormErrors(); // Send the newly rendered form tag as HTML $response = new SS_HTTPResponse($this->forTemplate()); $response->addHeader('Content-Type', 'text/html'); } return $response; } } else { if ($this->getRedirectToFormOnValidationError()) { if ($pageURL = $request->getHeader('Referer')) { if (Director::is_site_url($pageURL)) { // Remove existing pragmas $pageURL = preg_replace('/(#.*)/', '', $pageURL); return Director::redirect($pageURL . '#' . $this->FormName()); } } } return Director::redirectBack(); } } // First, try a handler method on the controller (has been checked for allowed_actions above already) if ($this->controller->hasMethod($funcName)) { return $this->controller->{$funcName}($vars, $this, $request); // Otherwise, try a handler method on the form object. } elseif ($this->hasMethod($funcName)) { return $this->{$funcName}($vars, $this, $request); } return $this->httpError(404); }
/** * Removes all unused thumbnails from the file store * and returns the status of the process to the user. */ public function deleteunusedthumbnails() { $count = 0; $thumbnails = $this->getUnusedThumbnails(); if ($thumbnails) { foreach ($thumbnails as $thumbnail) { unlink(ASSETS_PATH . "/" . $thumbnail); $count++; } } $message = sprintf(_t('AssetAdmin.THUMBSDELETED', '%s unused thumbnails have been deleted'), $count); FormResponse::status_message($message, 'good'); echo FormResponse::respond(); }
protected function javascriptRefresh($message = 'Please wait...') { FormResponse::add("\$('Form_EditForm').resetElements();"); FormResponse::add('$$("#sitetree li.current")[0].selectTreeNode();'); FormResponse::status_message($message, "good"); return FormResponse::respond(); }
protected function getRelatedData() { $relatedName = $_REQUEST['RelatedClass']; $id = $_REQUEST[$relatedName]['ID']; $baseClass = $this->stat('data_type'); $relatedClasses = singleton($baseClass)->stat('has_one'); if ($id) { $relatedObject = DataObject::get_by_id($relatedClasses[$relatedName], $id); $response .= <<<JS \t\t\t\$('{$relatedName}').unsetNewRelatedKey(); JS; } elseif ($id !== '0') { //in case of null; $relatedObject = new $relatedClasses[$relatedName](); if ($parentID = $_REQUEST[$relatedName]['ParentID']) { $relatedObject->ParentID = $parentID; } $id = $relatedObject->write(); $response .= <<<JS \t\t\t\$('{$relatedName}').setNewRelatedKey({$id}); JS; } else { // in case of 0 $relatedObject = new $relatedClasses[$relatedName](); if ($parentID = $_REQUEST[$relatedName]['ParentID']) { $relatedObject->ParentID = $parentID; } $response .= <<<JS \t\t\t\$('{$relatedName}').unsetNewRelatedKey(); JS; } if (Director::is_ajax()) { $fields = $_REQUEST[$relatedName]; $response .= <<<JS var dataArray = new Array(); JS; foreach ($fields as $k => $v) { $JS_newKey = Convert::raw2js($relatedName . '[' . $k . ']'); $JS_newValue = Convert::raw2js($relatedObject->{$k}); $response .= <<<JS dataArray['{$JS_newKey}'] = '{$JS_newValue}'; JS; } $response .= <<<JS \$('{$relatedName}').updateChildren(dataArray, true); JS; FormResponse::add($response); } return FormResponse::respond(); }
/** * Add existing member to group rather than creating a new member */ function addtogroup() { // Protect against CSRF on destructive action $token = $this->getForm()->getSecurityToken(); if (!$token->checkRequest($this->controller->getRequest())) { return $this->httpError(400); } $data = $_REQUEST; $groupID = isset($data['ctf']['ID']) ? $data['ctf']['ID'] : null; if (!is_numeric($groupID)) { FormResponse::status_messsage(_t('MemberTableField.ADDINGFIELD', 'Adding failed'), 'bad'); return; } // Get existing record either by ID or unique identifier. $identifierField = Member::get_unique_identifier_field(); $className = 'Member'; $record = null; if (isset($data[$identifierField])) { $record = DataObject::get_one($className, sprintf('"%s" = \'%s\'', $identifierField, $data[$identifierField])); if ($record && !$record->canEdit()) { return $this->httpError('401'); } } // Fall back to creating a new record if (!$record) { $record = new $className(); } // Update an existing record, or populate a new one. // If values on an existing (autocompleted) record have been changed, // they will overwrite current data. We need to unset 'ID' // record as it points to the group rather than the member record, and would // cause the member to be written to a potentially existing record. unset($data['ID']); $record->update($data); // Validate record, mainly password restrictions. // Note: Doesn't use Member_Validator $valid = $record->validate(); if ($valid->valid()) { $record->write(); $this->getDataList()->add($record); $this->sourceItems(); // TODO add javascript to highlight added row (problem: might not show up due to sorting/filtering) FormResponse::update_dom_id($this->id(), $this->renderWith($this->template), true); FormResponse::status_message(_t('MemberTableField.ADDEDTOGROUP', 'Added member to group'), 'good'); } else { $message = sprintf(_t('MemberTableField.ERRORADDINGUSER', 'There was an error adding the user to the group: %s'), Convert::raw2xml($valid->starredList())); FormResponse::status_message($message, 'bad'); } return FormResponse::respond(); }
function run(DataObjectSet $pages) { foreach ($pages as $page) { $id = $page->ID; // Perform the action if ($page->canDelete()) { $page->doDeleteFromLive(); } // check to see if the record exists on the live site, if it doesn't remove the tree node $stageRecord = Versioned::get_one_by_stage('SiteTree', 'Stage', "`SiteTree`.`ID`={$id}"); if ($stageRecord) { $stageRecord->IsAddedToStage = true; $title = Convert::raw2js($stageRecord->TreeTitle()); FormResponse::add("\$('sitetree').setNodeTitle({$id}, '{$title}');"); FormResponse::add("\$('Form_EditForm').reloadIfSetTo({$id});"); } else { FormResponse::add("var node = \$('sitetree').getTreeNodeByIdx('{$id}');"); FormResponse::add("if(node && node.parentTreeNode)\tnode.parentTreeNode.removeTreeNode(node);"); FormResponse::add("\$('Form_EditForm').reloadIfSetTo({$id});"); } $page->destroy(); unset($page); } $message = sprintf(_t('CMSBatchActions.DELETED_PAGES', 'Deleted %d pages from the published site'), $pages->Count()); FormResponse::add('statusMessage("' . $message . '","good");'); return FormResponse::respond(); }
/** * Delete a number of items */ public function deleteitems($request) { // Protect against CSRF on destructive action if (!SecurityToken::inst()->checkRequest($request)) { return $this->httpError(400); } $ids = split(' *, *', $_REQUEST['csvIDs']); $script = "st = \$('sitetree'); \n"; foreach ($ids as $id) { if (is_numeric($id)) { $record = DataObject::get_by_id($this->stat('tree_class'), $id); if ($record && !$record->canDelete()) { return Security::permissionFailure($this); } DataObject::delete_by_id($this->stat('tree_class'), $id); $script .= "node = st.getTreeNodeByIdx({$id}); if(node) node.parentTreeNode.removeTreeNode(node); \$('Form_EditForm').closeIfSetTo({$id}); \n"; } } FormResponse::add($script); return FormResponse::respond(); }
public function removememberfromgroup() { $groupID = $this->urlParams['ID']; $memberID = $this->urlParams['OtherID']; if (is_numeric($groupID) && is_numeric($memberID)) { $member = DataObject::get_by_id('Member', (int) $memberID); if (!$member->canDelete()) { return Security::permissionFailure($this); } $member->Groups()->remove((int) $groupID); FormResponse::add("reloadMemberTableField();"); } else { user_error("SecurityAdmin::removememberfromgroup: Bad parameters: Group={$groupID}, Member={$memberID}", E_USER_ERROR); } return FormResponse::respond(); }
/** * Receives the form submission which tells the index rebuild process to * begin. * * @access public * @return String The AJAX response to send to the CMS. */ public function rebuildZendSearchLuceneIndex() { ZendSearchLuceneWrapper::rebuildIndex(); FormResponse::status_message(_t('ZendSearchLucene.SuccessMessage', 'A Lucene search index rebuild job has been added to the Jobs queue.'), 'good'); return FormResponse::respond(); }
/** * Custom delete implementation: * Remove member from group rather than from the database */ function delete() { // Protect against CSRF on destructive action $token = $this->getForm()->getSecurityToken(); // TODO Not sure how this is called, using $_REQUEST to be on the safe side if (!$token->check($_REQUEST['SecurityID'])) { return $this->httpError(400); } $groupID = Convert::raw2sql($_REQUEST['ctf']['ID']); $memberID = Convert::raw2sql($_REQUEST['ctf']['childID']); if (is_numeric($groupID) && is_numeric($memberID)) { $member = DataObject::get_by_id('Member', $memberID); $member->Groups()->remove($groupID); } else { user_error("MemberTableField::delete: Bad parameters: Group={$groupID}, Member={$memberID}", E_USER_ERROR); } return FormResponse::respond(); }
/** * Delete a number of items */ public function deleteitems() { $ids = split(' *, *', $_REQUEST['csvIDs']); $script = "st = \$('sitetree'); \n"; foreach($ids as $id) { if(is_numeric($id)) { $record = DataObject::get_by_id($this->stat('tree_class'), $id); if($record && !$record->canDelete()) return Security::permissionFailure($this); DataObject::delete_by_id($this->stat('tree_class'), $id); $script .= "node = st.getTreeNodeByIdx($id); if(node) node.parentTreeNode.removeTreeNode(node); $('Form_EditForm').closeIfSetTo($id); \n"; } } FormResponse::add($script); return FormResponse::respond(); }
/** * Custom delete implementation: * Remove member from group rather than from the database */ function delete() { $groupID = Convert::raw2sql($_REQUEST['ctf']['ID']); $memberID = Convert::raw2sql($_REQUEST['ctf']['childID']); if(is_numeric($groupID) && is_numeric($memberID)) { $member = DataObject::get_by_id('Member', $memberID); $member->Groups()->remove($groupID); } else { user_error("MemberTableField::delete: Bad parameters: Group=$groupID, Member=$memberID", E_USER_ERROR); } return FormResponse::respond(); }
/** * Switch the cms language and reload the site tree * */ function switchlanguage($lang, $donotcreate = null) { //is it's a clean switch (to an existing language deselect the current page) if (is_string($lang)) { $dontunloadPage = true; } $lang = is_string($lang) ? $lang : urldecode($this->urlParams['ID']); if ($lang != Translatable::default_lang()) { Translatable::set_reading_lang(Translatable::default_lang()); $tree_class = $this->stat('tree_class'); $obj = new $tree_class(); $allIDs = $obj->getDescendantIDList(); $allChildren = $obj->AllChildren(); $classesMap = $allChildren->map('ID', 'ClassName'); $titlesMap = $allChildren->map(); Translatable::set_reading_lang($lang); $obj = new $tree_class(); $languageIDs = $obj->getDescendantIDList(); $notcreatedlist = array_diff($allIDs, $languageIDs); FormResponse::add("\$('addpage').getElementsByTagName('button')[0].disabled=true;"); FormResponse::add("\$('Form_AddPageOptionsForm').getElementsByTagName('div')[1].getElementsByTagName('input')[0].disabled=true;"); FormResponse::add("\$('Translating_Message').innerHTML = 'Translating mode - " . i18n::get_language_name($lang) . "';"); FormResponse::add("Element.removeClassName('Translating_Message','nonTranslating');"); } else { Translatable::set_reading_lang($lang); FormResponse::add("\$('addpage').getElementsByTagName('button')[0].disabled=false;"); FormResponse::add("\$('Form_AddPageOptionsForm').getElementsByTagName('div')[1].getElementsByTagName('input')[0].disabled=false;"); FormResponse::add("Element.addClassName('Translating_Message','nonTranslating');"); } $obj = singleton($this->stat('tree_class')); $obj->markPartialTree(); $siteTree = $obj->getChildrenAsUL("", ' "<li id=\\"record-$child->ID\\" class=\\"" . $child->CMSTreeClasses($extraArg) . "\\">" . "<a href=\\"" . Director::link(substr($extraArg->Link(),0,-1), "show", $child->ID) . "\\" " . (($child->canEdit() || $child->canAddChildren()) ? "" : "class=\\"disabled\\"") . " title=\\"' . _t('LeftAndMain.PAGETYPE') . '".$child->class."\\" >" . (Convert::raw2js($child->TreeTitle())) . "</a>" ', $this, true); $rootLink = $this->Link() . '0'; $siteTree = "<li id=\"record-0\" class=\"Root nodelete\"><a href=\"{$rootLink}\">" . _t('LeftAndMain.SITECONTENT') . "</a>" . $siteTree . "</li></ul>"; FormResponse::add("\$('sitetree').innerHTML ='" . ereg_replace("[\n]", "\\\n", $siteTree) . "';"); FormResponse::add("SiteTree.applyTo('#sitetree');"); if (isset($notcreatedlist)) { foreach ($notcreatedlist as $notcreated) { if ($notcreated == $donotcreate) { continue; } $id = "new-{$classesMap[$notcreated]}-0-{$notcreated}"; Session::set($id . '_originalLangID', $notcreated); $treeTitle = Convert::raw2js($titlesMap[$notcreated]); $response = <<<JS \t\t\t\t\tvar tree = \$('sitetree'); \t\t\t\t\tvar newNode = tree.createTreeNode("{$id}", "{$treeTitle}", "{$classesMap[$notcreated]} (untranslated)"); \t\t\t\t\taddClass(newNode, 'untranslated'); \t\t\t\t\tnode = tree.getTreeNodeByIdx(0); \t\t\t\t\tnode.open(); \t\t\t\t\tnode.appendTreeNode(newNode); JS; FormResponse::add($response); } } if (!isset($dontunloadPage)) { FormResponse::add("node = \$('sitetree').getTreeNodeByIdx(0); node.selectTreeNode();"); } return FormResponse::respond(); }
/** * Returns the content of the TableListField as a piece of FormResponse javascript * @deprecated Please use the standard URL through Link() which gives you the FieldHolder as an HTML fragment. */ function ajax_refresh() { // compute sourceItems here instead of Items() to ensure that // pagination and filters are respected on template accessors //$this->sourceItems(); $response = $this->renderWith($this->template); FormResponse::update_dom_id($this->id(), $response, 1); FormResponse::set_non_ajax_content($response); return FormResponse::respond(); }
function run(DataObjectSet $pages) { $ids = $pages->column('ID'); $this->batchaction($pages, 'doUnpublish', _t('CMSBatchActions.DELETED_PAGES', 'Deleted %d pages from the published site, %d failures')); foreach ($ids as $pageID) { $id = $pageID; // check to see if the record exists on the stage site, if it doesn't remove the tree node $stageRecord = Versioned::get_one_by_stage('SiteTree', 'Stage', "\"SiteTree\".\"ID\"={$id}"); if ($stageRecord) { $stageRecord->IsAddedToStage = true; $title = Convert::raw2js($stageRecord->TreeTitle()); FormResponse::add("\$('sitetree').setNodeTitle({$id}, '{$title}');"); FormResponse::add("\$('Form_EditForm').reloadIfSetTo({$id});"); } else { FormResponse::add("var node = \$('sitetree').getTreeNodeByIdx('{$id}');"); FormResponse::add("if(node && node.parentTreeNode)\tnode.parentTreeNode.removeTreeNode(node);"); FormResponse::add("\$('Form_EditForm').reloadIfSetTo({$id});"); } } return FormResponse::respond(); }
public function updatereport() { FormResponse::load_form($this->EditForm()->forTemplate()); return FormResponse::respond(); }
/** * Handle a form submission. GET and POST requests behave identically. * Populates the form with {@link loadDataFrom()}, calls {@link validate()}, * and only triggers the requested form action/method * if the form is valid. */ function httpSubmission($request) { $vars = $request->requestVars(); if (isset($funcName)) { Form::set_current_action($funcName); } // Populate the form $this->loadDataFrom($vars, true); // Protection against CSRF attacks if ($this->securityTokenEnabled()) { $securityID = Session::get('SecurityID'); if (!$securityID || !isset($vars['SecurityID']) || $securityID != $vars['SecurityID']) { $this->httpError(400, "SecurityID doesn't match, possible CSRF attack."); } } // Determine the action button clicked $funcName = null; foreach ($vars as $paramName => $paramVal) { if (substr($paramName, 0, 7) == 'action_') { // Break off querystring arguments included in the action if (strpos($paramName, '?') !== false) { list($paramName, $paramVars) = explode('?', $paramName, 2); $newRequestParams = array(); parse_str($paramVars, $newRequestParams); $vars = array_merge((array) $vars, (array) $newRequestParams); } // Cleanup action_, _x and _y from image fields $funcName = preg_replace(array('/^action_/', '/_x$|_y$/'), '', $paramName); break; } } // If the action wasnt' set, choose the default on the form. if (!isset($funcName) && ($defaultAction = $this->defaultAction())) { $funcName = $defaultAction->actionName(); } if (isset($funcName)) { $this->setButtonClicked($funcName); } // Validate the form if (!$this->validate()) { if (Director::is_ajax()) { // Special case for legacy Validator.js implementation (assumes eval'ed javascript collected through FormResponse) if ($this->validator->getJavascriptValidationHandler() == 'prototype') { return FormResponse::respond(); } else { $acceptType = $request->getHeader('Accept'); if (strpos($acceptType, 'application/json') !== FALSE) { // Send validation errors back as JSON with a flag at the start $response = new SS_HTTPResponse(Convert::array2json($this->validator->getErrors())); $response->addHeader('Content-Type', 'application/json'); } else { $this->setupFormErrors(); // Send the newly rendered form tag as HTML $response = new SS_HTTPResponse($this->forTemplate()); $response->addHeader('Content-Type', 'text/html'); } return $response; } } else { if ($this->getRedirectToFormOnValidationError()) { if ($pageURL = $request->getHeader('Referer')) { if (Director::is_site_url($pageURL)) { // Remove existing pragmas $pageURL = preg_replace('/(#.*)/', '', $pageURL); return Director::redirect($pageURL . '#' . $this->FormName()); } } } return Director::redirectBack(); } } // First, try a handler method on the controller if ($this->controller->hasMethod($funcName)) { return $this->controller->{$funcName}($vars, $this, $request); // Otherwise, try a handler method on the form object } else { if ($this->hasMethod($funcName)) { return $this->{$funcName}($vars, $this, $request); } } }
/** * Removes all unused thumbnails from the file store * and returns the status of the process to the user. */ public function deleteunusedthumbnails($request) { // Protect against CSRF on destructive action if (!SecurityToken::inst()->checkRequest($request)) { return $this->httpError(400); } $count = 0; $thumbnails = $this->getUnusedThumbnails(); if ($thumbnails) { foreach ($thumbnails as $thumbnail) { unlink(ASSETS_PATH . "/" . $thumbnail); $count++; } } $message = sprintf(_t('AssetAdmin.THUMBSDELETED', '%s unused thumbnails have been deleted'), $count); FormResponse::status_message($message, 'good'); echo FormResponse::respond(); }
/** * Use the URL-Parameter "action_saveComplexTableField" * to provide a clue to the main controller if the main form has to be rendered, * even if there is no action relevant for the main controller (to provide the instance of ComplexTableField * which in turn saves the record. * * @see {Form::ReferencedField}). */ function saveComplexTableField() { if (isset($_REQUEST['ctf']['childID']) && is_numeric($_REQUEST['ctf']['childID'])) { $childObject = DataObject::get_by_id($this->sourceClass, $_REQUEST['ctf']['childID']); } else { $childObject = new $this->sourceClass(); $this->fields->removeByName('ID'); } $this->saveInto($childObject); $funcName = $this->controller->itemWriteMethod; if (!$funcName) { $funcName = "write"; } $childObject->{$funcName}(); // if ajax-call in an iframe, update window if (Director::is_ajax()) { // Newly saved objects need their ID reflected in the reloaded form to avoid double saving $form = $this->controller->DetailForm($childObject->ID); $form->loadDataFrom($childObject); FormResponse::update_dom_id($form->FormName(), $form->formHtmlContent(), true, 'update'); return FormResponse::respond(); } else { Director::redirectBack(); } }