/**
  * 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;
 }
Exemple #2
0
 /**
  * Load the given javascript template with the page.
  * @param file The template file to load.
  * @param vars The array of variables to load.  These variables are loaded via string search & replace.
  */
 static function javascriptTemplate($file, $vars, $uniquenessID = null)
 {
     $script = file_get_contents(Director::getAbsFile($file));
     foreach ($vars as $k => $v) {
         $search[] = '$' . $k;
         $replace[] = str_replace("\\'", "'", Convert::raw2js($v));
     }
     $script = str_replace($search, $replace, $script);
     Requirements::customScript($script, $uniquenessID);
 }
 /**
  * Send the preview/test email
  * @param SS_HTTPRequest $request
  */
 public function emailpreview(SS_HTTPRequest $request = null)
 {
     $emailVar = $request->getVar('email');
     $recipient = new Recipient(Recipient::$test_data);
     if ($request && !empty($emailVar)) {
         $recipient->Email = Convert::raw2js($emailVar);
     } else {
         $recipient->Email = Member::currentUser()->Email;
     }
     $newsletter = $this->record;
     $email = new NewsletterEmail($newsletter, $recipient, true);
     $email->send();
     return Controller::curr()->redirectBack();
 }
 function Field($options = array())
 {
     //GENERAL
     Requirements::javascript(THIRDPARTY_DIR . '/jquery/jquery.js');
     Requirements::javascript("datefield_simplified/javascript/SimpleDateField.js");
     $this->addExtraClass("simpledatefield");
     $this->setAttribute("placeholder", $this->Config()->get("placeholder_value"));
     $html = parent::Field($options);
     $fieldID = $this->id();
     $url = Convert::raw2js(Director::absoluteBaseURL() . Config::inst()->get("SimpleDateField_Controller", "url") . "/ajaxvalidation/");
     $objectID = $fieldID . "_OBJECT";
     Requirements::customScript("\r\n\t\t\tvar {$objectID} = new SimpleDateFieldAjaxValidationAPI('" . $fieldID . "');\r\n\t\t\t{$objectID}.init();\r\n\t\t\t{$objectID}.setVar('url', '{$url}');\r\n\t\t\t", 'func_SimpleDateField' . $fieldID);
     return $html;
 }
    /**
     * Redirects the user to the external login page
     *
     * @return SS_HTTPResponse
     */
    protected function redirectToExternalLogin()
    {
        $loginURL = Security::create()->Link('login');
        $loginURLATT = Convert::raw2att($loginURL);
        $loginURLJS = Convert::raw2js($loginURL);
        $message = _t('CMSSecurity.INVALIDUSER', '<p>Invalid user. <a target="_top" href="{link}">Please re-authenticate here</a> to continue.</p>', 'Message displayed to user if their session cannot be restored', array('link' => $loginURLATT));
        $this->response->setStatusCode(200);
        $this->response->setBody(<<<PHP
<!DOCTYPE html>
<html><body>
{$message}
<script type="text/javascript">
setTimeout(function(){top.location.href = "{$loginURLJS}";}, 0);
</script>
</body></html>
PHP
);
        return $this->response;
    }
 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();
 }
Exemple #7
0
 function forTemplate()
 {
     $page = $this->CurrentPage();
     if ($page) {
         $description = str_replace(array("\n", "\r"), "", $page->MetaDescription);
         $title = Convert::raw2js($page->Title);
         $level1 = $page->Level(1);
         $level2 = $page->Level(2);
         if ($level1->URLSegment == 'modes') {
             $level1 = $level2;
             $level2 = $page->Level(3);
         }
         if ($level2 && $level1->URLSegment == 'home') {
             $level1 = $level2;
             $level2 = $page->Level(3);
         }
         $section = $level1->Title;
         $service = $level2 ? $level2->Title : $section;
         $fullURL = $page->Link();
         $imprintID = ImprintStats::$imprintID;
         return "<!-- Start: Nexsys Imprint Code (Copyright Nexsys Development Ltd 2002-2005) -->\n\t\t<script src=\"cms/javascript/ImprintStats.js\" type=\"text/javascript\"></script>\n\t\t<script type=\"text/javascript\">\n\t\t//<![CDATA[\t\n\t\tvar NI_DESCRIPTION = \"{$description}\";\n\t\tvar NI_SECTION = \"{$section}\";\n\t\tvar NI_SERVICE = \"{$service}\";\n\t\tvar NI_TRIGGER = \"{$trigger}\";\n\t\tvar NI_AMOUNT = \"0\";\n\t\tvar NI_ADCAMPAIGN = \"\";\n\t\tvar NI_TITLE = \"{$title}\";\n\t\tvar NI_URL = \"{$fullURL}\";\n\t\tvar NI_BASKET_ADD = \"\";\n\t\tvar NI_BASKET_REMOVE = \"\";\n\t\tvar NI_PARAMETERS = \"\";\n\t\t\n\t\tif (typeof(NI_IW) != \"undefined\") ni_TrackHit(\"imprint1.nexsysdev.net\", {$imprintID}, NI_DESCRIPTION, NI_SECTION, NI_SERVICE, NI_TRIGGER, NI_AMOUNT, NI_ADCAMPAIGN, NI_TITLE, NI_URL, 1, NI_BASKET_ADD, NI_BASKET_REMOVE, NI_PARAMETERS);\n\t\telse document.write('<div style=\"position:absolute;width:1px;height:1px;overflow:hidden\"><img src=\"http://imprint1.nexsysdev.net/Hit.aspx?tv=1&sc={$imprintID}&js=1\" width=\"1\" height=\"1\" style=\"border:0\" alt=\"Nexsys Imprint\"/></div>');\n\t\t//]]>\n\t\t</script>\n\t\t\n\t\t<noscript>\n\t\t<div style=\"position:absolute;width:1px;height:1px;overflow:hidden\"><a href=\"http://www.nexsysdev.com\"><img src=\"http://imprint1.nexsysdev.net/Hit.aspx?tv=1&sc=55075&lo=&st=&sv=&tr=&ac=&js=0\" width=\"1\" height=\"1\" alt=\"Nexsys Imprint\" /></a></div>\n\t\t</noscript>\n\t\t<!-- End: Nexsys Imprint Code -->";
     }
 }
    /**
     * Send this HTTPReponse to the browser
     */
    public function output()
    {
        // Attach appropriate X-Include-JavaScript and X-Include-CSS headers
        if (Director::is_ajax()) {
            Requirements::include_in_response($this);
        }
        if (in_array($this->statusCode, self::$redirect_codes) && headers_sent($file, $line)) {
            $url = Director::absoluteURL($this->headers['Location'], true);
            $urlATT = Convert::raw2htmlatt($url);
            $urlJS = Convert::raw2js($url);
            $title = Director::isDev() ? "{$urlATT}... (output started on {$file}, line {$line})" : "{$urlATT}...";
            echo <<<EOT
<p>Redirecting to <a href="{$urlATT}" title="Click this link if your browser does not redirect you">{$title}</a></p>
<meta http-equiv="refresh" content="1; url={$urlATT}" />
<script type="text/javascript">setTimeout(function(){
\twindow.location.href = "{$urlJS}";
}, 50);</script>";
EOT;
        } else {
            $line = $file = null;
            if (!headers_sent($file, $line)) {
                header($_SERVER['SERVER_PROTOCOL'] . " {$this->statusCode} " . $this->getStatusDescription());
                foreach ($this->headers as $header => $value) {
                    header("{$header}: {$value}", true, $this->statusCode);
                }
            } else {
                // It's critical that these status codes are sent; we need to report a failure if not.
                if ($this->statusCode >= 300) {
                    user_error("Couldn't set response type to {$this->statusCode} because " . "of output on line {$line} of {$file}", E_USER_WARNING);
                }
            }
            // Only show error pages or generic "friendly" errors if the status code signifies
            // an error, and the response doesn't have any body yet that might contain
            // a more specific error description.
            if (Director::isLive() && $this->isError() && !$this->body) {
                Debug::friendlyError($this->statusCode, $this->getStatusDescription());
            } else {
                echo $this->body;
            }
        }
    }
 /**
  * Sets the popup-title by javascript. Make sure to use FormResponse in ajax-requests,
  * otherwise the title-change will only take effect on items existing during page-load.
  *
  * @param $caption String
  */
 function setPopupCaption($caption)
 {
     $this->popupCaption = Convert::raw2js($caption);
 }
 /**
  * Replace a given DOM-element with the given content.
  * It automatically prefills {$non_ajax_content} with the passed content (as a fallback).
  * 
  * @param $domID string The DOM-ID of an HTML-element that should be replaced
  * @param $domContent string The new HTML-content
  * @param $reapplyBehaviour boolean Applies behaviour to the given domID after refreshing it
  * @param $replaceMethod string Method for replacing - either 'replace' (=outerHTML) or 'update' (=innerHTML)
  *   (Caution: "outerHTML" might cause problems on the client-side, e.g. on table-tags)
  * 
  * @todo More fancy replacing with loading-wheel etc.
  */
 static function update_dom_id($domID, $domContent, $reapplyBehaviour = true, $replaceMethod = 'replace', $uniquenessID = null)
 {
     //self::$non_ajax_content = $domContent;
     $JS_domID = Convert::raw2js($domID);
     $JS_domContent = Convert::raw2js($domContent);
     $JS_replaceMethod = Convert::raw2js($replaceMethod);
     if (isset($uniquenessID)) {
         self::$rules[$uniquenessID] = "Element.{$JS_replaceMethod}('{$JS_domID}','{$JS_domContent}');";
     } else {
         self::$rules[] = "Element.{$JS_replaceMethod}('{$JS_domID}','{$JS_domContent}');";
     }
     if ($reapplyBehaviour) {
         if (isset($uniquenessID)) {
             self::$behaviour_apply_rules[$uniquenessID] .= "Behaviour.apply('{$JS_domID}', true);";
         } else {
             self::$behaviour_apply_rules[] = "Behaviour.apply('{$JS_domID}', true);";
         }
     }
 }
 /**
  * retuns the customised Javascript for the form field.
  * @return String
  */
 protected function getJavascript()
 {
     return "\n\t\t\tvar GoogleAddressField" . $this->id() . " = new GoogleAddressField( '" . Convert::raw2js($this->getName()) . "')\n\t\t\t\t.setVar('errorMessageMoreSpecific', '" . Convert::raw2js(_t("GoogleAddressField.ERROR_MESSAGE_MORE_SPECIFIC", "Error: please enter a more specific location.")) . "')\n\t\t\t\t.setVar('errorMessageAddressNotFound', '" . Convert::raw2js(_t("GoogleAddressField.ERROR_MESSAGE_ADDRESS_NOT_FOUND", "Error: sorry, address could not be found.")) . "')\n\t\t\t\t.setVar('findNewAddressText', '" . Convert::raw2js(_t("GoogleAddressField.FIND_NEW_ADDRESS", "Find Alternative Address")) . "')\n\t\t\t\t.setVar('useSensor', " . Convert::raw2js($this->userSensor ? "true" : "false") . ")\n\t\t\t\t.setVar('relatedFields', " . Convert::raw2json($this->getFieldMap()) . ")\n\t\t\t\t.setVar('googleStaticMapLink', '" . Convert::raw2js($this->googleStaticMapLink) . "')\n\t\t\t\t.setVar('linkLabelToViewMap', '" . Convert::raw2js(_t("GoogleAddressField.LINK_LABEL_TO_VIEW_MAP", "view map")) . "')\n\t\t\t\t.init();";
 }
    /**
     * Redirect the user to the change password form.
     *
     * @return SS_HTTPResponse
     */
    protected function redirectToChangePassword()
    {
        // Since this form is loaded via an iframe, this redirect must be performed via javascript
        $changePasswordForm = new ChangePasswordForm($this->controller, 'ChangePasswordForm');
        $changePasswordForm->sessionMessage(_t('Member.PASSWORDEXPIRED', 'Your password has expired. Please choose a new one.'), 'good');
        // Get redirect url
        $changePasswordURL = $this->getExternalLink('changepassword');
        if ($backURL = $this->controller->getRequest()->requestVar('BackURL')) {
            Session::set('BackURL', $backURL);
            $changePasswordURL = Controller::join_links($changePasswordURL, '?BackURL=' . urlencode($backURL));
        }
        $changePasswordURLATT = Convert::raw2att($changePasswordURL);
        $changePasswordURLJS = Convert::raw2js($changePasswordURL);
        $message = _t('CMSMemberLoginForm.PASSWORDEXPIRED', '<p>Your password has expired. <a target="_top" href="{link}">Please choose a new one.</a></p>', 'Message displayed to user if their session cannot be restored', array('link' => $changePasswordURLATT));
        // Redirect to change password page
        $this->controller->getResponse()->setStatusCode(200);
        $this->controller->getResponse()->setBody(<<<PHP
<!DOCTYPE html>
<html><body>
{$message}
<script type="application/javascript">
setTimeout(function(){top.location.href = "{$changePasswordURLJS}";}, 0);
</script>
</body></html>
PHP
);
        return $this->controller->getResponse();
    }
    /**
     * Action handler for the save button on the file subform.
     * Saves the file
     */
    public function savefile($data, $form)
    {
        $record = DataObject::get_by_id("File", $data['ID']);
        if (!$record) {
            return $this->httpError(400);
        }
        $form->saveInto($record);
        $record->write();
        $title = Convert::raw2js($record->Title);
        $name = Convert::raw2js($record->Name);
        $saved = sprintf(_t('AssetAdmin.SAVEDFILE', 'Saved file %s'), "#{$data['ID']}");
        echo <<<JS
\t\t\tstatusMessage('{$saved}');
\t\t\t\$('record-{$data['ID']}').getElementsByTagName('td')[1].innerHTML = "{$title}";
\t\t\t\$('record-{$data['ID']}').getElementsByTagName('td')[2].innerHTML = "{$name}";
JS;
    }
 protected function cleanJS($s)
 {
     $s = Convert::raw2js($s);
     $s = str_replace("\r\n", " ", $s);
     $s = str_replace("\n", " ", $s);
     $s = str_replace('/', '\\/', $s);
     return $s;
 }
 /**
  * Include the content of the given JavaScript file in the list of requirements. Dollar-sign
  * variables will be interpolated with values from $vars similar to a .ss template.
  *
  * @param string         $file         The template file to load, relative to docroot
  * @param string[] $vars The array of variables to interpolate.
  * @param string $uniquenessID A unique ID that ensures a piece of code is only added once
  */
 public function javascriptTemplate($file, $vars, $uniquenessID = null)
 {
     $script = file_get_contents(Director::getAbsFile($file));
     $search = array();
     $replace = array();
     if ($vars) {
         foreach ($vars as $k => $v) {
             $search[] = '$' . $k;
             $replace[] = str_replace("\\'", "'", Convert::raw2js($v));
         }
     }
     $script = str_replace($search, $replace, $script);
     $this->customScript($script, $uniquenessID);
 }
Exemple #16
0
 /**
  * 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;
 }
	/**
	 * 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();
	}
Exemple #18
0
 public function JS()
 {
     return Convert::raw2js($this->RAW());
 }
 public function setAddress($v)
 {
     $this->Address = Convert::raw2js($v);
 }
Exemple #20
0
 /**
  * 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();
 }
    protected function getJavascript()
    {
        return '
		EcomBuyableSelectField.set_nothingFound("' . _t('BuyableSelectField.NOTHINGFOUND', 'no products found - please try again') . '");
		EcomBuyableSelectField.set_fieldName("' . Convert::raw2js($this->name()) . '");
		EcomBuyableSelectField.set_formName("' . Convert::raw2js($this->form->Name()) . '");
		EcomBuyableSelectField.set_countOfSuggestions(' . $this->countOfSuggestions . ');
		EcomBuyableSelectField.set_selectedBuyableFieldName("' . Convert::raw2js($this->fieldSelectedBuyable->name()) . '");
		EcomBuyableSelectField.set_selectedBuyableFieldID("' . Convert::raw2js($this->fieldSelectedBuyable->id()) . '");
		';
    }
Exemple #22
0
    /**
     * 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();
    }
 /**
  * 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);
     }
 }
    public function CreateFlashObject($Title = '', $FlashFileDivID = '', $FlashFilename = '', $AlternativeContent = '', $Width = 0, $Height = 0, $FlashVersion = '', $ParamArray = array(), $javascriptAlreadyAdded = false)
    {
        if (!$Title) {
            $Title = self::$title;
        }
        $Title = Convert::raw2js($Title);
        if (!$FlashFileDivID) {
            $FlashFileDivID = self::$flash_file_div_id;
        }
        $FlashFileID = Convert::raw2js($FlashFileDivID);
        if (!$AlternativeContent) {
            $AlternativeContent = self::$alternative_content;
        }
        if (!$Width) {
            $Width = self::$width;
        }
        $Width = intval($Width);
        if (!$Height) {
            $Height = self::$height;
        }
        $Height = intval($Height);
        if (!$FlashVersion) {
            $FlashVersion = self::$flash_version;
        }
        if (!$ParamArray) {
            $ParamArray = self::$param_array;
        }
        if (!$FlashFilename) {
            $FlashFilename = self::$filename;
        }
        $FlashFilename = Convert::raw2js($FlashFilename);
        $doSet = new DataObjectSet();
        if ($FlashFilename) {
            $params = '';
            $paramsJS = '';
            foreach ($ParamArray as $key => $value) {
                $params .= '<param name="' . $key . '" value="' . Convert::Raw2ATT($value) . '" />';
                $paramsJS .= '
					params.' . $key . ' = "' . $value . '";';
            }
            $record = array('ID' => $FlashFileID, 'FileName' => $FlashFilename, 'Title' => $Title, 'Width' => intval($Width), 'Height' => intval($Height), 'FlashVersion' => $FlashVersion, 'AlternativeContent' => $AlternativeContent, 'Parameters' => $params, 'UseDynamicInsert' => self::$use_dynamic_insert);
            $doSet->push(new ArrayData($record));
            if (!$javascriptAlreadyAdded) {
                if (self::$use_dynamic_insert) {
                    $js = '
						jQuery(document).ready(
							function () {
								jQuery(".FlashAlternativeContent").hide();
								var flashvars = {};
								var params = {};
								' . $paramsJS . '
								var attributes = {};
								attributes.id = "' . $FlashFileDivID . '";
								swfobject.embedSWF("' . $FlashFilename . '", "' . $FlashFileDivID . '", "' . $Width . '", "' . $Height . '", "' . $FlashVersion . '","flash/swfobject/expressInstall.swf", flashvars, params, attributes);
								jQuery(".FlashAlternativeContent").fadeIn(3000);
							}
						);';
                } else {
                    $js = '
						jQuery(document).ready(
							function () {
								swfobject.registerObject("' . $FlashFileDivID . '", "' . $FlashVersion . '", "flash/swfobject/expressInstall.swf");
							}
						);';
                }
                Requirements::javascript(THIRDPARTY_DIR . "/jquery/jquery.js");
                Requirements::javascript("flash/javascript/swfobject.js");
                Requirements::customScript($js);
            }
        }
        return $doSet;
    }
 public function JS()
 {
     return Convert::raw2js($this->value);
 }
 public function publish($comment, $member, $notify)
 {
     if (!$member) {
         $member = Member::currentUser();
     }
     // We have to mark as completed now, or we'll get
     // recursion from SiteTreeCMSWorkflow::onAfterPublish.
     $page = $this->Page();
     $page->LatestCompletedWorkflowRequestID = $this->ID;
     $page->writeWithoutVersion();
     // Embargo means we go Approved -> Scheduled
     if ($this->EmbargoDate) {
         $this->setSchedule();
         $this->PublisherID = $member->ID;
         $this->write();
         // Otherwise we go Approved -> Published
     } else {
         $this->Status = 'Completed';
         $this->PublisherID = $member->ID;
         $this->write();
         // Only publish the page if it hasn't already been published elsewhere.  This occurs when
         // SiteTree::doPublish() 'auto-closes' an open workflow
         //if($page->getIsModifiedOnStage()) {
         $page->doPublish();
         //}
         if ($notify) {
             $this->notifyPublished($comment);
         }
     }
     $this->addNewChange($comment, $this->Status, DataObject::get_by_id('Member', $this->PublisherID));
     // @todo Coupling to UI :-(
     $title = Convert::raw2js($page->TreeTitle());
     FormResponse::add("\$('sitetree').setNodeTitle({$page->ID}, \"{$title}\");");
     return _t('SiteTreeCMSWorkflow.PUBLISHMESSAGE', 'Published changes to live version. Emailed %s.');
 }
 /**
  * Tests {@link Convert::raw2js()}
  */
 public function testRaw2JS()
 {
     // Test attempt to break out of string
     $this->assertEquals('\\"; window.location=\\"http://www.google.com', Convert::raw2js('"; window.location="http://www.google.com'));
     $this->assertEquals('\\\'; window.location=\\\'http://www.google.com', Convert::raw2js('\'; window.location=\'http://www.google.com'));
     // Test attempt to close script tag
     $this->assertEquals('\\"; \\x3c/script\\x3e\\x3ch1\\x3eHa \\x26amp; Ha\\x3c/h1\\x3e\\x3cscript\\x3e', Convert::raw2js('"; </script><h1>Ha &amp; Ha</h1><script>'));
     // Test newlines are properly escaped
     $this->assertEquals('New\\nLine\\rReturn', Convert::raw2js("New\nLine\rReturn"));
     // Check escape of slashes
     $this->assertEquals('\\\\\\"\\x3eClick here', Convert::raw2js('\\">Click here'));
 }
 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 Field($properties = array())
 {
     Requirements::javascript('pixlr/javascript/pixlr.js');
     Requirements::javascript('pixlr/javascript/pixlr.jquery.js');
     Requirements::javascript('pixlr/javascript/pixlr-image-field.js');
     $fieldAttributes = array('id' => $this->id(), 'class' => 'pixlrTrigger', 'value' => Convert::raw2att($this->label), 'type' => 'button');
     $targetUrl = strlen($this->targetUrl) ? $this->targetUrl : Director::absoluteURL('pixlr/saveimage');
     $exitUrl = strlen($this->exitUrl) ? $this->exitUrl : Director::absoluteURL('pixlr/closepixlr');
     // now add any additional parameters onto the end of the target string
     $sep = strpos($targetUrl, '?') ? '&amp;' : '?';
     foreach ($this->returnParams as $param => $v) {
         $targetUrl .= $sep . $param . '=' . $v;
         $sep = '&';
     }
     $loc = ($m = Member::currentUser()) ? i18n::get_lang_from_locale($m->Locale) : 'en';
     $title = isset($this->returnParams['title']) ? $this->returnParams['title'] : 'New Image';
     $opts = array('referrer' => Convert::raw2js('SilverStripe CMS'), 'loc' => $loc, 'title' => $this->value && is_object($this->value) ? Convert::raw2js($this->value->Name) : $title, 'locktarget' => 'true', 'exit' => $exitUrl, 'target' => $targetUrl, 'method' => 'get', 'copy' => false);
     // where should we open the editor? as in, which window is it rooted in?
     $openin = 'window';
     if ($this->value) {
         if ($this->config()->use_credentials) {
             $opts['credentials'] = 'true';
             $opts['image'] = Convert::raw2js(Director::absoluteBaseURL() . $this->value->Filename);
         } else {
             // need to post the image to their server first, so we'll stick the image ID into the
             // page, and let the jquery plugin handle uploading it to pixlr first
             if (is_object($this->value)) {
                 $opts['id'] = $this->value->ID;
             } else {
                 $opts['id'] = $this->value;
             }
             $opts['preload'] = Director::absoluteURL('pixlr/sendimage');
             // In silverstripe, when editing an image it actually occurs in an iframe popup contained within
             // another iframe. Because we want the editor to appear mounted in the top level window,
             // we have to explicitly add it to the correct location
             //				$openin = 'window.parent.parent';
         }
         $opts['locktitle'] = 'true';
         $opts['mode'] = 'popup';
     }
     $opts['service'] = $this->editorMode;
     //		$opts = Convert::raw2json($opts);
     $opts['openobjname'] = $openin;
     $fieldAttributes['data-pixlr-editor'] = json_encode($opts);
     //		$script = <<<JSCRIPT
     //jQuery().ready(function () {
     //var opts = $opts;
     //opts.openin = $openin;
     //jQuery('#{$this->id()}').pixlrize(opts);
     //});
     //JSCRIPT;
     //		Requirements::customScript($script, 'pixlr-'.$this->id());
     return $this->createTag('input', $fieldAttributes);
 }
 /**
  * Return the value of a field in a JavaScript-save format.
  */
 public function JS_val($field, $arguments = null, $cache = true)
 {
     return Convert::raw2js($this->RAW_val($field, $arguments, $cache));
 }