Exemplo n.º 1
1
 /**
  * Handles the action when subscribe is being done
  * 
  * @param  Array  $data
  * @param  Form   $form
  */
 public function subscribe(array $data, Form $form)
 {
     $settings = SiteConfig::current_site_config();
     $MailChimp = new \Drewm\MailChimp($settings->APIKey);
     $apiData = array('id' => $settings->MailChimpList()->filter(array('Code' => 'NEWSLETTER'))->First()->ListID, 'email' => array('email' => $data['Email']), 'double_optin' => false, 'update_existing' => false, 'replace_interests' => false, 'send_welcome' => false);
     $this->extend('updateAPIData', $apiData);
     $result = $MailChimp->call('lists/subscribe', $apiData);
     if (Director::is_ajax()) {
         if (isset($result['status']) && $result['status'] == 'error') {
             if ($result['code'] == 214) {
                 return json_encode(array('success' => false, 'message' => $data['Email'] . ' is already subscribed'));
             } else {
                 return json_encode(array('success' => false, 'message' => $result['error']));
             }
         } else {
             return json_encode(array('success' => true, 'message' => 'Thank you for subscribing to our newsletter'));
         }
     } else {
         if (isset($result['status']) && $result['status'] == 'error') {
             if ($result['code'] == 214) {
                 $this->sessionMessage($data['Email'] . ' is already subscribed.', 'bad');
             } else {
                 $this->sessionMessage($result['error'], 'bad');
             }
         } else {
             $this->sessionMessage('Thank you for subscribing to our newsletter', 'good');
         }
         Controller::curr()->redirectBack();
     }
 }
 public function transition($request)
 {
     if (!Member::currentUserID()) {
         return Security::permissionFailure($this, _t('AdvancedWorkflowActionController.ACTION_ERROR', "You must be logged in"));
     }
     $id = $this->request->requestVar('id');
     $transition = $this->request->requestVar('transition');
     $instance = DataObject::get_by_id('WorkflowInstance', (int) $id);
     if ($instance && $instance->canEdit()) {
         $transition = DataObject::get_by_id('WorkflowTransition', (int) $transition);
         if ($transition) {
             if ($this->request->requestVar('comments')) {
                 $action = $instance->CurrentAction();
                 $action->Comment = $this->request->requestVar('comments');
                 $action->write();
             }
             singleton('WorkflowService')->executeTransition($instance->getTarget(), $transition->ID);
             $result = array('success' => true, 'link' => $instance->getTarget()->AbsoluteLink());
             if (Director::is_ajax()) {
                 return Convert::raw2json($result);
             } else {
                 return $this->redirect($instance->getTarget()->Link());
             }
         }
     }
     if (Director::is_ajax()) {
         $result = array('success' => false);
         return Convert::raw2json($result);
     } else {
         $this->redirect($instance->getTarget()->Link());
     }
 }
 /**
  * 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;
 }
 public static function include_code()
 {
     if (Director::is_ajax()) {
         self::block();
     } else {
         Requirements::javascript(THIRDPARTY_DIR . "/jquery/jquery.js");
         Requirements::javascript('prettyphoto/javascript/jquery.prettyPhoto.js');
         Requirements::css('prettyphoto/css/prettyPhoto.css');
         $config = '';
         $theme = Config::inst()->get("PrettyPhoto", "theme");
         $moreConfigArray = Config::inst()->get("PrettyPhoto", "more_config");
         foreach ($moreConfigArray as $key => $value) {
             if ($value === false) {
                 $value = "false";
             } elseif ($value === true) {
                 $value = "true";
             } elseif ($value === intval($value)) {
                 //$value = $value;
             } else {
                 $value = " '{$value}' ";
             }
             $moreConfigArray[$key] = "{$key}: {$value}";
         }
         if ($theme) {
             $config .= "theme: '" . $theme . "'";
         }
         if ($config && count($moreConfigArray)) {
             $config .= ", ";
         }
         if ($config) {
             $config .= implode(",", $moreConfigArray);
         }
         Requirements::customScript('PrettyPhotoInitConfigs = {' . $config . '}; jQuery(document).ready(function(){PrettyPhotoLoader.load("' . Config::inst()->get("PrettyPhoto", "selector") . '")});', "prettyPhotoCustomScript");
     }
 }
 function submit($data, $form)
 {
     $member = Member::currentUser();
     if (!$member || !$member->inGroup("ADMIN")) {
         $form->setMessage("You need to be logged as an admin to send this email.", "bad");
         return Controller::curr()->redirectBack();
     }
     $data = Convert::raw2sql($data);
     $page = null;
     if (isset($data["ModuleProductID"])) {
         $page = ModuleProduct::get()->byID(intval($data["ModuleProductID"]));
     }
     if (!$page) {
         $form->setMessage("Can not find the right page for saving this email.", "bad");
         return Controller::curr()->redirectBack();
     }
     $email = new ModuleProductEmail();
     $form->saveInto($email);
     $email->write();
     if (Director::is_ajax()) {
         return "mail sent!";
     } else {
         return Controller::curr()->redirect($page->Link());
     }
 }
 public function output()
 {
     // TODO: Refactor into a content-type option
     if (\Director::is_ajax()) {
         return $this->friendlyErrorMessage;
     } else {
         // TODO: Refactor this into CMS
         if (class_exists('ErrorPage')) {
             $errorFilePath = \ErrorPage::get_filepath_for_errorcode($this->statusCode, class_exists('Translatable') ? \Translatable::get_current_locale() : null);
             if (file_exists($errorFilePath)) {
                 $content = file_get_contents($errorFilePath);
                 if (!headers_sent()) {
                     header('Content-Type: text/html');
                 }
                 // $BaseURL is left dynamic in error-###.html, so that multi-domain sites don't get broken
                 return str_replace('$BaseURL', \Director::absoluteBaseURL(), $content);
             }
         }
         $renderer = \Debug::create_debug_view();
         $output = $renderer->renderHeader();
         $output .= $renderer->renderInfo("Website Error", $this->friendlyErrorMessage, $this->friendlyErrorDetail);
         if (\Email::config()->admin_email) {
             $mailto = \Email::obfuscate(\Email::config()->admin_email);
             $output .= $renderer->renderParagraph('Contact an administrator: ' . $mailto . '');
         }
         $output .= $renderer->renderFooter();
         return $output;
     }
 }
 /**
  * Handles the submission of the contact form. Checks spam and builds and sends the email
  *
  * @param array The form data
  * @param Form The Form object	
  */
 public function doContactFormSubmit($data, $form)
 {
     Session::set("FormData.{$form->FormName()}", $data);
     $proxy = $form->proxy;
     foreach ($proxy->getSpamProtection() as $spam) {
         if ($spam->isSpam($data, $form)) {
             $form->sessionMessage($spam->getMessage(), "bad");
             $spam->logSpamAttempt($this->owner->request);
             return $this->owner->redirectBack();
         }
     }
     if ($func = $proxy->getOnBeforeSend()) {
         $result = $func($data, $form, $proxy);
         if ($result === false) {
             return $this->owner->redirectBack();
         }
     }
     $this->sendEmail($data, $form);
     Session::clear("FormData.{$form->FormName()}");
     if ($func = $proxy->getOnAfterSend()) {
         $func($data, $form, $proxy);
     }
     if ($proxy->getSuccessURL()) {
         return $this->owner->redirect($proxy->getSuccessURL());
     } else {
         if (Director::is_ajax()) {
             return new SS_HTTPResponse($proxy->getSuccessMessage());
         }
         $form->sessionMessage(strip_tags($proxy->getSuccessMessage()), 'good');
         return $this->owner->redirectBack();
     }
 }
 /**
  * Skip the question via AJAX.
  */
 public function otherquestion()
 {
     if (Director::is_ajax()) {
         Session::clear('QACaptchaField.Retry');
         return $this->renderWith('QACaptchaField');
     }
 }
 /**
  * Load an article by ajax, fallback to default rendering if not an ajax request
  *
  * @return string
  */
 public function index()
 {
     if (Director::is_ajax()) {
         return json_encode(array('html' => $this->renderWith("NewsItem_Content")->value));
     } else {
         return parent::index();
     }
 }
 /**
  * Injects some custom javascript to provide instant loading of DataObject
  * tables.
  *
  * @return void
  *
  * @author Sebastian Diel <*****@*****.**>
  * @since 13.01.2011
  */
 public function onAfterInit()
 {
     Translatable::set_current_locale(i18n::get_locale());
     if (Director::is_ajax()) {
         return true;
     }
     Requirements::css('silvercart/admin/css/SilvercartMain.css');
 }
 function index(SS_HTTPRequest $request)
 {
     if (Director::is_ajax()) {
         return $this->delegate($request);
     } else {
         return $this;
     }
 }
 function redirect($status = "success", $message = "")
 {
     if (Director::is_ajax()) {
         return $status;
         //TODO: allow for custom return types, eg json - similar to ShoppingCart::return_data()
     }
     Director::redirect(CheckoutPage::find_link());
 }
 public function postRequest(SS_HTTPRequest $request, SS_HTTPResponse $response, DataModel $model)
 {
     if (!$response->isError() && !Director::is_ajax()) {
         // Find or create the visitor record
         $visitor = Visitor::initVisitor();
         // Log the arrival of this visitor to this page
         $visitor->logPageArrival();
     }
 }
 public function AccountPaymentFields($request)
 {
     if (Director::is_ajax()) {
         $customer = Member::currentUser();
         $fields = CompositeField::create(TextField::create('AccountPaymentNumber', 'Account Number', $customer ? $customer->AccountNumber : '')->setAttribute('required', 'required'))->setName('AccountPaymentFields');
         return $fields->FieldHolder();
     }
     return false;
 }
 /**
  *
  */
 function init()
 {
     RSSFeed::linkToFeed(Director::baseURL() . $this->URLSegment . "/episodesRSS");
     if (Director::is_ajax()) {
         $this->isAjax = true;
     } else {
         $this->isAjax = false;
     }
     parent::init();
 }
	 function init(){
	  //add a javascript library for easy interaction with the server
	  Requirements::javascript('mysite/javascript/jQuery.js');
	  if(Director::is_ajax() || $_GET["ajaxDebug"]) {
	   $this->isAjax = true;
	  } else {
	   $this->isAjax = false;
	  } 
	  parent::init();
	 }
 public function Delete($data, $item)
 {
     if (!$item->canDelete()) {
         $this->httpError(403);
     }
     $this->parent->{$this->name . 'ID'} = null;
     $this->parent->write();
     $item->delete();
     return Director::is_ajax() ? $this->FieldHolder() : Director::redirectBack();
 }
 /**
  * Render or return a backtrace from the given scope.
  *
  * @param unknown_type $returnVal
  * @param unknown_type $ignoreAjax
  * @return unknown
  */
 static function backtrace($returnVal = false, $ignoreAjax = false, $ignoredFunctions = null)
 {
     $plainText = Director::is_cli() || Director::is_ajax() && !$ignoreAjax;
     $result = self::get_rendered_backtrace(debug_backtrace(), $plainText, $ignoredFunctions);
     if ($returnVal) {
         return $result;
     } else {
         echo $result;
     }
 }
 public function __construct($controller, $name, FieldList $fields, FieldList $actions, $validator = null)
 {
     parent::__construct($controller, $name, $fields, $actions, $validator);
     if (!Director::is_ajax()) {
         Requirements::javascript(FRAMEWORK_DIR . '/thirdparty/jquery/jquery.min.js');
         Requirements::javascript('bootstrap_extra_fields/javascript/tooltip.js');
         $this->setTemplate('BootstrapHorizontalAjaxForm')->addExtraClass('form-horizontal');
     } else {
         $this->setTemplate('BootstrapHorizontalForm')->addExtraClass('form-horizontal');
     }
 }
 /**
  * Injects some custom javascript to provide instant loading of DataObject
  * tables.
  *
  * @return void
  *
  * @author Sebastian Diel <*****@*****.**>
  * @since 04.04.2013
  */
 public function onAfterInit()
 {
     if (Director::is_ajax()) {
         return true;
     }
     Requirements::javascript('silvercart/admin/javascript/SilvercartLeftAndMain.js');
     Requirements::css('silvercart/admin/css/SilvercartMain.css');
     foreach (self::$additional_css_files as $css_file) {
         Requirements::css($css_file);
     }
 }
 static function include_code()
 {
     if (Director::is_ajax()) {
         self::block();
     } else {
         Requirements::javascript(THIRDPARTY_DIR . "/jquery/jquery.js");
         Requirements::javascript('superfish/javascript/hoverIntent.js');
         Requirements::javascript('superfish/javascript/superfish.js');
         Requirements::ThemedCSS('superfish');
         Requirements::customScript(self::get_config(), 'superfishconfig');
     }
 }
 public function reindex($data, Form $form)
 {
     $task = singleton('SolrReindexTask');
     if ($task) {
         $task->run($this->request);
     }
     if (Director::is_ajax()) {
         return $this->getResponseNegotiator()->respond($this->request);
     } else {
         $this->redirectBack();
     }
 }
Exemplo n.º 23
0
 public function checkOwnAjaxRequest($request)
 {
     $referer = @$_SERVER['HTTP_REFERER'];
     if (empty($referer)) {
         return false;
     }
     //validate
     if (!Director::is_ajax()) {
         return false;
     }
     return Director::is_site_url($referer);
 }
 protected function fontAction($change)
 {
     $currentSize = $this->currentFontSize();
     $currentSize = floatval($currentSize) + $change;
     Session::set("fontsize", $currentSize);
     if (Director::is_ajax()) {
         return $this->CurrentFontSizeInPercentages($currentSize);
     } else {
         Director::redirectBack();
     }
     return array();
 }
 function doMyForm(array $data, Form $form)
 {
     //return $this->render();
     if ($form->validate()) {
         if (Director::is_ajax()) {
             return "Nice!";
         } else {
             $this->customise(array("MyForm" => "Nice!"));
         }
     }
     return;
 }
 public function show($params)
 {
     if ($params['ID']) {
         $this->setCurrentPageID($params['ID']);
     }
     if (isset($params['OtherID'])) {
         Session::set('currentMember', $params['OtherID']);
     }
     if (Director::is_ajax()) {
         SSViewer::setOption('rewriteHashlinks', false);
         return $this->EditForm() ? $this->EditForm()->formHtmlContent() : false;
     }
     return array();
 }
 public function output($statusCode)
 {
     // Ajax content is plain-text only
     if (\Director::is_ajax()) {
         return $this->getTitle();
     }
     // Determine if cached ErrorPage content is available
     $content = ErrorPage::get_content_for_errorcode($statusCode);
     if ($content) {
         return $content;
     }
     // Fallback to default output
     return parent::output($statusCode);
 }
 /**
  * Start an enquiry.
  */
 public function startenquiry($data, $form)
 {
     $quantity = isset($data['Quantity']) ? (int) $data['Quantity'] : 1;
     if ($buyable = $form->getBuyable($data)) {
         $item = $buyable->createItem($quantity, $data);
         $enquiry = Enquiry::find_or_make();
         $enquiry->Items()->add($item);
     }
     if (Director::is_ajax()) {
         return $this->EnquiryForm()->forAjaxTemplate();
     }
     $this->owner->redirect(Controller::join_links($this->owner->Link(), "enquire"));
     return;
 }
 /**
  * Determine if the cache should be enabled for the current request
  *
  * @param string $url
  * @return boolean
  */
 protected function enabled($url)
 {
     // Master override
     if (!self::config()->enabled) {
         return false;
     }
     // No GET params other than cache relevant config is passed (e.g. "?stage=Stage"),
     // which would mean that we have to bypass the cache
     if (count(array_diff(array_keys($_GET), array('url')))) {
         return false;
     }
     // Request is not POST (which would have to be handled dynamically)
     if ($_POST) {
         return false;
     }
     // Check url doesn't hit opt out filter
     $optOutURL = self::config()->optOutURL;
     if (!empty($optOutURL) && preg_match($optOutURL, $url)) {
         return false;
     }
     // Check url hits the opt in filter
     $optInURL = self::config()->optInURL;
     if (!empty($optInURL) && !preg_match($optInURL, $url)) {
         return false;
     }
     // Check ajax filter
     if (!self::config()->enableAjax && Director::is_ajax()) {
         return false;
     }
     // If displaying form errors then don't display cached result
     if (!isset($_SESSION)) {
         Session::start();
     }
     Session::clear_all();
     // Forces the session to be regenerated from $_SESSION
     foreach (Session::get_all() as $field => $data) {
         // Check for session details in the form FormInfo.{$FormName}.errors
         if ($field === 'FormInfo' && $data != null) {
             foreach ($data as $formData) {
                 if (isset($formData['errors'])) {
                     return false;
                 }
             }
         }
     }
     // OK!
     return true;
 }
Exemplo n.º 30
0
 protected function showWithEditForm($params, $editForm)
 {
     if (isset($params['ID'])) {
         Session::set('currentPage', $params['ID']);
     }
     if (isset($params['OtherID'])) {
         Session::set('currentOtherID', $params['OtherID']);
     }
     if (Director::is_ajax()) {
         SSViewer::setOption('rewriteHashlinks', false);
         $result = $this->customise(array('EditForm' => $editForm))->renderWith($this->getTemplatesWithSuffix("_right"));
         return $this->getLastFormIn($result);
     } else {
         return array();
     }
 }