/** * Overloaded so that form error messages are displayed. * * @see OrderFormValidator::php() * @see Form::validate() */ function validate() { if ($this->validator) { $errors = $this->validator->validate(); if ($errors) { if (Director::is_ajax() && $this->validator->getJavascriptValidationHandler() == 'prototype') { 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']))); } } else { $data = $this->getData(); $formError = array(); if ($formMessageType = $this->MessageType()) { $formError['message'] = $this->Message(); $formError['messageType'] = $formMessageType; } // Load errors into session and post back Session::set("FormInfo.{$this->FormName()}", array('errors' => $errors, 'data' => $data, 'formError' => $formError)); } return false; } } return true; }
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; } }
/** * 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; } }
function onAfterSave($record) { if ($record->hasMethod('NormalRelated') && ($record->NormalRelated() || $record->ReverseRelated())) { FormResponse::status_message('Saved, please update related pages.', 'good'); } }
/** * Return a few pieces of information about a change to a page * - Send the new status message * - Update the action buttons * - Update the treenote * - Send a status message */ function tellBrowserAboutPublicationChange($page, $statusMessage) { $JS_title = Convert::raw2js($page->TreeTitle()); $JS_stageURL = $page->DeletedFromStage ? '' : Convert::raw2js($page->AbsoluteLink()); $liveRecord = Versioned::get_one_by_stage('SiteTree', 'Live', "`SiteTree`.ID = {$page->ID}"); $JS_liveURL = $liveRecord ? Convert::raw2js($liveRecord->AbsoluteLink()) : ''; FormResponse::add($this->getActionUpdateJS($page)); FormResponse::update_status($page->Status); if ($JS_stageURL || $JS_liveURL) { FormResponse::add("\$('sitetree').setNodeTitle({$page->ID}, '{$JS_title}')"); } else { FormResponse::add("var node = \$('sitetree').getTreeNodeByIdx('{$page->ID}');"); FormResponse::add("if(node.parentTreeNode)\tnode.parentTreeNode.removeTreeNode(node);"); FormResponse::add("\$('Form_EditForm').reloadIfSetTo({$page->ID});"); } FormResponse::status_message($statusMessage, 'good'); FormResponse::add("\$('Form_EditForm').elements.StageURLSegment.value = '{$JS_stageURL}'"); FormResponse::add("\$('Form_EditForm').elements.LiveURLSegment.value = '{$JS_liveURL}'"); FormResponse::add("\$('Form_EditForm').notify('PagePublished', \$('Form_EditForm').elements.ID.value);"); return FormResponse::respond(); }
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"); } }
/** * Restore a completely deleted page from the SiteTree_versions table. */ function restore($data, $form) { if (($id = $_REQUEST['ID']) && is_numeric($id)) { $restoredPage = Versioned::get_latest_version("SiteTree", $id); if ($restoredPage) { $restoredPage = $restoredPage->doRestoreToStage(); FormResponse::get_page($id); $title = Convert::raw2js($restoredPage->TreeTitle()); FormResponse::add("\$('sitetree').setNodeTitle({$id}, '{$title}');"); FormResponse::status_message(sprintf(_t('CMSMain.RESTORED', "Restored '%s' successfully", PR_MEDIUM, 'Param %s is a title'), $title), 'good'); return FormResponse::respond(); } else { return new SS_HTTPResponse("SiteTree #{$id} not found", 400); } } else { return new SS_HTTPResponse("Please pass an ID in the form content", 400); } }
/** * 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; }
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); } } }
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(); }
/** * Delete a given Dataobjebt by ID * * @param $urlParams Array * @param $form Form * @return String */ function delete($urlParams, $form) { $id = Convert::raw2sql($_REQUEST['ID']); $obj = DataObject::get_by_id($this->stat('data_type'), $id); if ($obj) { $obj->delete(); } // clear session data Session::clear('currentPage'); FormResponse::status_message(_t('GenericDataAdmin.DELETEDSUCCESS', 'Successfully deleted'), 'good'); FormResponse::add("\$('Form_EditForm').deleteEffect();"); return FormResponse::respond(); }
public function save($urlParams, $form) { // Don't save the root folder - there's no database record if ($_REQUEST['ID'] == 'root') { FormResponse::status_message("Saved", "good"); return FormResponse::respond(); } $form->dataFieldByName('Title')->value = $form->dataFieldByName('Name')->value; return parent::save($urlParams, $form); }
function savemember() { $data = $_REQUEST; $className = $this->stat('subitem_class'); $id = $_REQUEST['ID']; if ($id == 'new') { $id = null; } if ($id) { if (defined('DB::USE_ANSI_SQL')) { $record = DataObject::get_one($className, "\"{$className}\".ID = {$id}"); } else { $record = DataObject::get_one($className, "`{$className}`.ID = {$id}"); } } else { // send out an email to notify the user that they have been subscribed $record = new $className(); } $record->update($data); $record->ID = $id; $record->write(); $record->Groups()->add($data['GroupID']); $FirstName = Convert::raw2js($record->FirstName); $Surname = Convert::raw2js($record->Surname); $Email = Convert::raw2js($record->Email); $Password = Convert::raw2js($record->Password); $response = <<<JS \t\t\t\$('MemberList').setRecordDetails({$record->ID}, { \t\t\t\tFirstName : "{$FirstName}", \t\t\t\tSurname : "{$Surname}", \t\t\t\tEmail : "{$Email}" \t\t\t}); \t\t\t\$('MemberList').clearAddForm(); JS; FormResponse::add($response); FormResponse::status_message(_t('NewsletterAdmin.SAVED'), 'good'); return FormResponse::respond(); }
/** * Process a workflow action. * @param string $workflowClass The sub-class of WorkflowRequest that is expected. * @param string $actionName The action method to call on the given WorkflowRequest objec.t * @param int $id The ID# of the page. * @param string $comment The comment to attach. * @param string $successMessage The message to show on success. */ function workflowAction($workflowClass, $actionName, $id, $comment) { if (is_numeric($id)) { // For 2.3 and 2.4 compatibility $bt = defined('DB::USE_ANSI_SQL') ? "\"" : "`"; $page = DataObject::get_by_id("SiteTree", $id); if (!$page) { $page = Versioned::get_one_by_stage("SiteTree", "Live", "{$bt}SiteTree{$bt}.{$bt}ID{$bt} = {$id}"); } if (!$page) { return new HTTPResponse("Can't find Page #{$id}", 400); } } else { return new HTTPResponse("Bad ID", 400); } // If we are creating and approving a workflow in one step, then don't bother emailing $notify = !($actionName == 'action' && !$page->openWorkflowRequest($workflowClass)); if ($request = $page->openOrNewWorkflowRequest($workflowClass, $notify)) { $request->clearMembersEmailed(); if ($successMessage = $request->{$actionName}($comment, null, $notify)) { FormResponse::get_page($id); $title = Convert::raw2js($page->TreeTitle()); FormResponse::add("\$('sitetree').setNodeTitle({$id}, \"{$title}\");"); // gather members for status output if ($notify) { $peeps = $request->getMembersEmailed(); if ($peeps && $peeps->Count()) { $emails = ''; foreach ($peeps as $peep) { if ($peep->Email) { $emails .= $peep->Email . ', '; } } $emails = trim($emails, ', '); } else { $emails = 'no-one'; } } else { $emails = "no-one"; } if ($successMessage) { FormResponse::status_message(sprintf($successMessage, $emails), 'good'); return FormResponse::respond(); } else { return; } } } // Failure FormResponse::status_message(_t('SiteTreeCMSWorkflow.WORKFLOW_ACTION_FAILED', "There was an error when processing your workflow request."), 'bad'); return FormResponse::respond(); }
/** * 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(); }
/** * 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 = self::$data_class; $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(); $record->Groups()->add($groupID); $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(); }
/** * Add existing member to group rather than creating a new member */ function addtogroup() { $data = $_REQUEST; unset($data['ID']); if (!is_numeric($data['ctf']['ID'])) { FormResponse::status_messsage(_t('MemberTableField.ADDINGFIELD', 'Adding failed'), 'bad'); } $className = $this->stat('data_class'); $record = new $className(); $record->update($data); $record->write(); // To Avoid duplication in the Group_Members table if the ComponentSet.php is not modified just uncomment le line below //if( ! $record->isInGroup( $data['ctf']['ID'] ) ) $record->Groups()->add($data['ctf']['ID']); $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'); return FormResponse::respond(); }
/** * Add existing member to group rather than creating a new member */ function addtogroup() { $data = $_REQUEST; unset($data['ID']); $ctfID = isset($data['ctf']) ? $data['ctf']['ID'] : null; if(!is_numeric($ctfID)) { FormResponse::status_messsage(_t('MemberTableField.ADDINGFIELD', 'Adding failed'), 'bad'); } $className = Object::getCustomClass($this->stat('data_class')); $record = new $className(); $record->update($data); $valid = $record->validate(); if($valid->valid()) { $record->write(); $record->Groups()->add($ctfID); $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 { FormResponse::status_message(Convert::raw2xml("I couldn't add that user to this group:\n\n" . $valid->starredlist()), 'bad'); } return FormResponse::respond(); }
/** * Ajax handler for updating the order of a number of tree nodes * $_GET[ID]: An array of node ids in the correct order * $_GET[MovedNodeID]: The node that actually got moved */ public function ajaxupdatesort() { $className = $this->stat('tree_class'); $counter = 0; $js = ''; $_REQUEST['ajax'] = 1; if (!Permission::check('SITETREE_REORGANISE') && !Permission::check('ADMIN')) { FormResponse::status_message(_t('LeftAndMain.CANT_REORGANISE', "You do not have permission to rearange the site tree. Your change was not saved."), "bad"); return FormResponse::respond(); } if (is_array($_REQUEST['ID'])) { if ($_REQUEST['MovedNodeID'] == 0) { //Sorting root $movedNode = DataObject::get($className, "\"ParentID\"=0"); } else { $movedNode = DataObject::get_by_id($className, $_REQUEST['MovedNodeID']); } foreach ($_REQUEST['ID'] as $id) { if ($id == $movedNode->ID) { $movedNode->Sort = ++$counter; $movedNode->Status = "Saved (update)"; $movedNode->write(); $title = Convert::raw2js($movedNode->TreeTitle()); $js .= "\$('sitetree').setNodeTitle({$movedNode->ID}, \"{$title}\");\n"; // Nodes that weren't "actually moved" shouldn't be registered as having been edited; do a direct SQL update instead } else { if (is_numeric($id)) { ++$counter; DB::query("UPDATE \"{$className}\" SET \"Sort\" = {$counter} WHERE \"ID\" = '{$id}'"); } } } FormResponse::status_message(_t('LeftAndMain.SAVED'), 'good'); } else { FormResponse::error(_t('LeftAndMain.REQUESTERROR', "Error in request")); } 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); }
/** * 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(); }
/** * 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(); }
/** * Ajax handler for updating the order of a number of tree nodes * $_GET[ID]: An array of node ids in the correct order * $_GET[MovedNodeID]: The node that actually got moved */ public function ajaxupdatesort() { $className = $this->stat('tree_class'); $counter = 0; $js = ''; $_REQUEST['ajax'] = 1; if(is_array($_REQUEST['ID'])) { if($_REQUEST['MovedNodeID']==0){ //Sorting root $movedNode = DataObject::get($className, "`ParentID`=0"); }else{ $movedNode = DataObject::get_by_id($className, $_REQUEST['MovedNodeID']); } foreach($_REQUEST['ID'] as $id) { if($id == $movedNode->ID) { $movedNode->Sort = ++$counter; $movedNode->Status = "Saved (update)"; $movedNode->write(); $title = Convert::raw2js($movedNode->TreeTitle()); $js .="$('sitetree').setNodeTitle($movedNode->ID, \"$title\");\n"; // Nodes that weren't "actually moved" shouldn't be registered as having been edited; do a direct SQL update instead } else if(is_numeric($id)) { ++$counter; DB::query("UPDATE `$className` SET `Sort` = $counter WHERE `ID` = '$id'"); } } // Virtual pages require selected to be null if the page is the same. FormResponse::add( "if( $('sitetree').selected && $('sitetree').selected[0]){ var idx = $('sitetree').selected[0].getIdx(); if(idx){ $('Form_EditForm').getPageFromServer(idx); } }\n" . $js ); FormResponse::status_message(_t('LeftAndMain.SAVED'), 'good'); } else { FormResponse::error(_t('LeftAndMain.REQUESTERROR',"Error in request")); } return FormResponse::respond(); }