/**
  * Out of the box, the handler "CurrentForm" value, which will return the rendered form.  
  * Non-Ajax calls will redirect back.
  * 
  * @param SS_HTTPRequest $request 
  * @param array $extraCallbacks List of anonymous functions or callables returning either a string
  * or SS_HTTPResponse, keyed by their fragment identifier. The 'default' key can
  * be used as a fallback for non-ajax responses.
  * @param array $fragmentOverride Change the response fragments.
  * @return SS_HTTPResponse
  */
 public function respond(SS_HTTPRequest $request, $extraCallbacks = array())
 {
     // Prepare the default options and combine with the others
     $callbacks = array_merge($this->callbacks, $extraCallbacks);
     $response = $this->getResponse();
     $responseParts = array();
     if (isset($this->fragmentOverride)) {
         $fragments = $this->fragmentOverride;
     } elseif ($fragmentStr = $request->getHeader('X-Pjax')) {
         $fragments = explode(',', $fragmentStr);
     } else {
         if ($request->isAjax()) {
             throw new SS_HTTPResponse_Exception("Ajax requests to this URL require an X-Pjax header.", 400);
         }
         $response->setBody(call_user_func($callbacks['default']));
         return $response;
     }
     // Execute the fragment callbacks and build the response.
     foreach ($fragments as $fragment) {
         if (isset($callbacks[$fragment])) {
             $res = call_user_func($callbacks[$fragment]);
             $responseParts[$fragment] = $res ? (string) $res : $res;
         } else {
             throw new SS_HTTPResponse_Exception("X-Pjax = '{$fragment}' not supported for this URL.", 400);
         }
     }
     $response->setBody(Convert::raw2json($responseParts));
     $response->addHeader('Content-Type', 'text/json');
     return $response;
 }
 public function testIsAjax()
 {
     $req = new SS_HTTPRequest('GET', '/', array('ajax' => 0));
     $this->assertFalse($req->isAjax());
     $req = new SS_HTTPRequest('GET', '/', array('ajax' => 1));
     $this->assertTrue($req->isAjax());
     $req = new SS_HTTPRequest('GET', '/');
     $req->addHeader('X-Requested-With', 'XMLHttpRequest');
     $this->assertTrue($req->isAjax());
 }
 /**
  * @param SS_HTTPRequest $request
  * @param AjaxHTTPResponse $response
  * @param GroupedProduct $groupedProduct
  * @param array $data
  * @param GroupedCartForm $form [optional]
  */
 public function updateErrorResponse(&$request, &$response, $groupedProduct, $data, $form)
 {
     if ($request->isAjax() && $this->owner->getController()->hasExtension('AjaxControllerExtension')) {
         if (!$response) {
             $response = $this->owner->getController()->getAjaxResponse();
         }
         $response->triggerEvent('statusmessage', array('content' => $form->Message(), 'type' => $form->MessageType()));
         $form->clearMessage();
     }
 }
 /**
  * @param SS_HTTPRequest $request
  * @param SS_HTTPResponse $response
  * @param ArrayData $results
  * @param array $data
  */
 public function updateSearchResultsResponse(&$request, &$response, $results, $data)
 {
     if ($request->isAjax() && $this->owner->hasExtension('AjaxControllerExtension')) {
         if (!$response) {
             $response = $this->owner->getAjaxResponse();
         }
         $response->addRenderContext('RESULTS', $results);
         $response->pushRegion('SearchResults', $results);
         $response->pushRegion('SearchHeader', $results);
         $response->triggerEvent('searchresults');
     }
 }
 /**
  * Filter executed AFTER a request
  *
  * @param SS_HTTPRequest $request Request container object
  * @param SS_HTTPResponse $response Response output object
  * @param DataModel $model Current DataModel
  * @return boolean Whether to continue processing other filters. Null or true will continue processing (optional)
  */
 public function postRequest(SS_HTTPRequest $request, SS_HTTPResponse $response, DataModel $model)
 {
     $code = $response->getStatusCode();
     $error_page_path = Director::baseFolder() . "/errors_pages/ui/{$code}/index.html";
     if (!$request->isAjax() && file_exists($error_page_path)) {
         //clean buffer
         ob_clean();
         $page_file = fopen($error_page_path, "r") or die("Unable to open file!");
         $body = fread($page_file, filesize($error_page_path));
         fclose($page_file);
         // set content type
         $response->addHeader('Content-Type', 'text/html');
         $response->setBody($body);
         $response->setStatusCode(200);
         return true;
     }
     return true;
 }
	/**
	 * Out of the box, the handler "CurrentForm" value, which will return the rendered form.  
	 * Non-Ajax calls will redirect back.
	 * 
	 * @param SS_HTTPRequest $request 
	 * @param array $extraCallbacks List of anonymous functions or callables returning either a string
	 * or SS_HTTPResponse, keyed by their fragment identifier. The 'default' key can
	 * be used as a fallback for non-ajax responses.
	 * @return SS_HTTPResponse
	 */
	public function respond(SS_HTTPRequest $request, $extraCallbacks = array()) {
		// Prepare the default options and combine with the others
		$callbacks = array_merge(
			array_change_key_case($this->callbacks, CASE_LOWER),
			array_change_key_case($extraCallbacks, CASE_LOWER)
		);
		
		if($fragment = $request->getHeader('X-Pjax')) {
			$fragment = strtolower($fragment);
			if(isset($callbacks[$fragment])) {
				return call_user_func($callbacks[$fragment]);
			} else {
				throw new SS_HTTPResponse_Exception("X-Pjax = '$fragment' not supported for this URL.", 400);
			}
		} else {
			if($request->isAjax()) throw new SS_HTTPResponse_Exception("Ajax requests to this URL require an X-Pjax header.", 400);
			return call_user_func($callbacks['default']);
		}
		
	}
 /**
  * Invoke a batch action
  *
  * @param SS_HTTPRequest $request
  * @return SS_HTTPResponse
  */
 public function handleBatchAction($request)
 {
     // This method can't be called without ajax.
     if (!$request->isAjax()) {
         return $this->parentController->redirectBack();
     }
     // Protect against CSRF on destructive action
     if (!SecurityToken::inst()->checkRequest($request)) {
         return $this->httpError(400);
     }
     // Find the action handler
     $action = $request->param('BatchAction');
     $actionHandler = $this->actionByName($action);
     // Sanitise ID list and query the database for apges
     $csvIDs = $request->requestVar('csvIDs');
     $ids = $this->cleanIDs($csvIDs);
     // Filter ids by those which are applicable to this action
     // Enforces front end filter in LeftAndMain.BatchActions.js:refreshSelected
     $ids = $actionHandler->applicablePages($ids);
     // Query ids and pass to action to process
     $pages = $this->getPages($ids);
     return $actionHandler->run($pages);
 }
 public function ghost(SS_HTTPRequest $r)
 {
     if (!$r->param('ID')) {
         return $this->httpError(400);
     }
     if (!$this->canModerate()) {
         return $this->httpError(403);
     }
     $member = Member::get()->byID($r->param('ID'));
     if (!$member || !$member->exists()) {
         return $this->httpError(404);
     }
     $member->ForumStatus = 'Ghost';
     $member->write();
     // Log event
     $currentUser = Member::currentUser();
     SS_Log::log(sprintf('Ghosted member %s (#%d), by moderator %s (#%d)', $member->Email, $member->ID, $currentUser->Email, $currentUser->ID), SS_Log::NOTICE);
     return $r->isAjax() ? true : $this->redirectBack();
 }
 /**
  * test the ajax response
  * for developers only
  * @return output to buffer
  */
 function ajaxtest(SS_HTTPRequest $request)
 {
     if (Director::isDev() || Permission::check("ADMIN")) {
         header('Content-Type', 'text/plain');
         echo "<pre>";
         $_REQUEST["ajax"] = 1;
         $v = $this->cart->setMessageAndReturn("test only");
         $v = str_replace(",", ",\r\n\t\t", $v);
         $v = str_replace("}", "\r\n\t}", $v);
         $v = str_replace("{", "\t{\r\n\t\t", $v);
         $v = str_replace("]", "\r\n]", $v);
         echo $v;
         echo "</pre>";
     } else {
         echo "please <a href=\"Security/login/?BackURL=" . urlencode($this->config()->get("url_segment") . "/ajaxtest/") . "\">log in</a> first.";
     }
     if (!$request->isAjax()) {
         die("---- make sure to add ?ajax=1 to the URL ---");
     }
 }
 /**
  * @param SS_HTTPRequest $request
  * @return $this|HTMLText
  */
 public function index(SS_HTTPRequest $request)
 {
     if ($request->isAjax()) {
         $data = $this->data();
         return $this->customise($data)->renderWith('BlogPage_Item');
     }
     return array();
 }
Exemple #11
0
 /**
  * This action will star / unstar a project for the current member
  *
  * @param \SS_HTTPRequest $request
  *
  * @return SS_HTTPResponse
  */
 public function toggleprojectstar(\SS_HTTPRequest $request)
 {
     $project = $this->getCurrentProject();
     if (!$project) {
         return $this->project404Response();
     }
     $member = Member::currentUser();
     if ($member === null) {
         return $this->project404Response();
     }
     $favProject = $member->StarredProjects()->filter('DNProjectID', $project->ID)->first();
     if ($favProject) {
         $member->StarredProjects()->remove($favProject);
     } else {
         $member->StarredProjects()->add($project);
     }
     if (!$request->isAjax()) {
         return $this->redirectBack();
     }
 }
 /**
  * Add one of an item to a cart (Product Page)
  *
  * @see the addtocart function within AddProductForm class
  * @param SS_HTTPRequest $request
  * @param AjaxHTTPResponse $response
  * @param Buyable $buyable [optional]
  * @param int $quantity [optional]
  * @param AddProductForm $form [optional]
  */
 public function updateAddProductFormResponse(&$request, &$response, $buyable, $quantity, $form)
 {
     if ($request->isAjax()) {
         if (!$response) {
             $response = $this->owner->getController()->getResponse();
         }
         $response->removeHeader('Content-Type');
         $response->addHeader('Content-Type', 'application/json; charset=utf-8');
         $shoppingcart = ShoppingCart::curr();
         $shoppingcart->calculate();
         // recalculate the shopping cart
         $data = array('id' => (string) $buyable->ID, 'internalItemID' => $buyable->InternalItemID, 'title' => $buyable->Title, 'url' => $buyable->URLSegment, 'categories' => $buyable->getCategories()->column('Title'), 'addLink' => $buyable->addLink(), 'removeLink' => $buyable->removeLink(), 'removeallLink' => $buyable->removeallLink(), 'setquantityLink' => $buyable->Item()->setquantityLink(), 'message' => array('content' => $form->Message(), 'type' => $form->MessageType()));
         $form->clearMessage();
         // include totals if required
         if ($shoppingcart) {
             $data['subTotal'] = $shoppingcart->SubTotal();
             $data['grandTotal'] = $shoppingcart->GrandTotal();
         }
         $this->owner->extend('updateAddProductFormResponseShopJsonResponse', $data, $request, $response, $buyable, $quantity, $form);
         $response->setBody(json_encode($data));
     }
 }
 /**
  * @param SS_HTTPRequest $request
  * @param AjaxHTTPResponse $response
  * @param AddProductForm $form [optional]
  */
 public function updateCartFormResponse(&$request, &$response, $form = null)
 {
     if ($request->isAjax()) {
         if (!$response) {
             $response = $this->owner->getAjaxResponse();
         }
         // Because ShoppingCart::current() calculates the order once and
         // then remembers the total, and that was called BEFORE the product
         // was added, we need to recalculate again here. Under non-ajax
         // requests the redirect eliminates the need for this but under
         // ajax the total lags behind the subtotal without this.
         ShoppingCart::curr()->calculate();
         $this->setupRenderContexts($response);
         $this->triggerStatusMessage($response, $form);
         $response->pushRegion('CartFormAjax', $this->owner, array('Editable' => true));
         $response->pushRegion('SideCart', $this->owner);
     }
 }
 /**
  * Get's the previous URL that lead up to the current request.
  *
  * NOTE: Honestly, this should be built into SS_HTTPRequest, but we can't depend on that right now... so instead,
  * this is being copied verbatim from Controller (in the framework).
  *
  * @param SS_HTTPRequest $request
  * @return string
  */
 protected function getBackURL(SS_HTTPRequest $request)
 {
     // Initialize a sane default (basically redirects to root admin URL).
     $controller = $this->getToplevelController();
     $url = method_exists($this->requestHandler, "Link") ? $this->requestHandler->Link() : $controller->Link();
     // Try to parse out a back URL using standard framework technique.
     if ($request->requestVar('BackURL')) {
         $url = $request->requestVar('BackURL');
     } else {
         if ($request->isAjax() && $request->getHeader('X-Backurl')) {
             $url = $request->getHeader('X-Backurl');
         } else {
             if ($request->getHeader('Referer')) {
                 $url = $request->getHeader('Referer');
             }
         }
     }
     return $url;
 }
 /**
  *
  * @param  SS_HTTPRequest   $request [description]
  * @return string
  */
 public function import($request)
 {
     $obj = $this->owner->customise(array('EditForm' => $this->owner->ImportForm()));
     if ($request->isAjax()) {
         // Rendering is handled by template, which will call EditForm() eventually
         $content = $obj->renderWith($this->owner->getTemplatesWithSuffix('_Content'));
     } else {
         $content = $obj->renderWith($this->owner->getViewer('show'));
     }
     return $content;
 }
Exemple #16
0
	/**
	 * @deprecated 3.0 Use SS_HTTPRequest->isAjax() instead (through Controller->getRequest())
	 */
	function isAjax() {
		Deprecation::notice('3.0', 'Use SS_HTTPRequest->isAjax() instead (through Controller->getRequest())');
		return $this->request->isAjax();
	}
 public function translate(SS_HTTPRequest $request)
 {
     $locales = "";
     if (SiteTree::has_extension("Translatable")) {
         $locales = Translatable::get_allowed_locales();
     } else {
         $locales = array("it_IT");
     }
     $locales_list = new ArrayList();
     foreach ($locales as $key => $value) {
         $obj = new ViewableData();
         $obj->__set("Locale", $value);
         $obj->__set("LocaleName", i18n::get_locale_name($value));
         $obj->__set("Lang", i18n::get_lang_from_locale($value));
         $locales_list->push($obj);
     }
     if ($request->isAjax()) {
         if (isset($_POST["collect"])) {
             foreach ($locales as $value) {
                 $c = new TextCollector($value);
                 $c->run(LanguageAdmin::$modules, true);
             }
             die(_t("SUCCESSFULL_COLLECT", "The text was collected."));
         }
         if (isset($_POST["save"])) {
             $lang_array[$_POST["locale"]] = $_POST[$_POST["locale"]];
             $file = $_POST["file"];
             $yml_file = sfYaml::dump($lang_array);
             if ($fh = fopen($file, "w")) {
                 fwrite($fh, $yml_file);
                 fclose($fh);
                 file_get_contents("http://{$_SERVER['HTTP_HOST']}?flush");
             } else {
                 throw new LogicException("Cannot write language file! Please check permissions of {$langFile}");
             }
             die;
         }
         $files = $this->getFiles();
         if (isset($_POST["loadfiles"])) {
             //  die($this->getYaml($_POST["loadfiles"]));
             $this->customise(array("Translations" => $this->getYaml($_POST["loadfiles"]), "Modules" => $files, "Locales" => $locales_list));
             $content = $this->renderWith('LanguageAdmin_Content');
             return $content;
         } else {
             $this->customise(array("Modules" => $files, "Translations" => $this->getYaml($files->filter(array('Locale' => $locales_list->first()->Locale))->first()->Path), "Locales" => $locales_list, "CurrentLocale" => $locales_list->first()->LocaleName));
             $content = $this->renderWith('LanguageAdmin_Content');
             return $content;
         }
     } else {
         $files = $this->getFiles();
         $this->customise(array("Modules" => $files, "Translations" => $this->getYaml($files->filter(array('Locale' => $locales_list->first()->Locale))->first()->Path), "Locales" => $locales_list, "CurrentLocale" => $locales_list->first()->LocaleName));
         $content = $this->renderWith($this->getViewer('translate'));
         return $content;
     }
 }
 /**
  * @param SS_HTTPRequest $request
  * @param AjaxHttpResponse $response
  * @param WishList $list
  */
 public function updateSetCurrentListResponse($request, &$response, $list)
 {
     if ($request->isAjax() && $this->owner->hasExtension('AjaxControllerExtension')) {
         if (!$response) {
             $response = $this->owner->getAjaxResponse();
         }
         $response->pushRegion('WishListPageHeader', $this->owner);
         $response->pushRegion('WishListItems', $this->owner);
         $response->pushRegion('WishListPageActions', $this->owner);
         $response->pushRegion('OtherWishLists', $this->owner);
         $response->triggerEvent('wishlistchanged');
     }
 }
 /**
  * Return a ArrayList of all blog children of this page.
  *
  * @param SS_HTTPRequest $request
  * @return array|HTMLText
  * @throws Exception
  */
 public function index(SS_HTTPRequest $request)
 {
     /** @var PaginatedList $pagination */
     $pagination = PaginatedList::create($this->liveChildren(true), Controller::curr()->request);
     $items = $this->Items > 0 ? $this->Items : 10;
     $pagination->setPageLength($items);
     $data = array('PaginatedPages' => $pagination);
     if ($request->isAjax()) {
         return $this->customise($data)->renderWith('PortfolioHolder_Item');
     }
     return $data;
 }
 /**
  * @param SS_HTTPRequest $request
  * @return array|HTMLText
  */
 public function index(SS_HTTPRequest $request)
 {
     /**
      * Return a ArrayList of all BlogPage children of this page.
      *
      * @return PaginatedList
      */
     $pagination = PaginatedList::create($this->liveChildren(true), Controller::curr()->request);
     $items = $this->Items > 0 ? $this->Items : 10;
     /** @var PaginatedList $pagination */
     $pagination->setPageLength($items);
     $data = array('PaginatedPages' => $pagination);
     /** If the request is AJAX */
     if ($request->isAjax()) {
         return $this->customise($data)->renderWith('BlogHolder_Item');
     }
     return $data;
 }