function generatePDF() { // tempfolder $tmpBaseFolder = TEMP_FOLDER . '/shopsystem'; $tmpFolder = project() ? "{$tmpBaseFolder}/" . project() : "{$tmpBaseFolder}/site"; if (is_dir($tmpFolder)) { Filesystem::removeFolder($tmpFolder); } if (!file_exists($tmpFolder)) { Filesystem::makeFolder($tmpFolder); } $baseFolderName = basename($tmpFolder); //Get site Requirements::clear(); $link = Director::absoluteURL($this->pdfLink() . "/?view=1"); $response = Director::test($link); $content = $response->getBody(); $content = utf8_decode($content); $contentfile = "{$tmpFolder}/" . $this->PublicURL . ".html"; if (!file_exists($contentfile)) { // Write to file if ($fh = fopen($contentfile, 'w')) { fwrite($fh, $content); fclose($fh); } } return $contentfile; }
/** * Ajax call from browser * @param SS_HTTPRequest $request sent by browser * @return string json response to send to back to the browser */ public function analyse(SS_HTTPRequest $request) { // Set the tenon options $tenon_options = $this->buildOptions($request); // Origin check if (strpos($request->postVar('tURL'), Director::absoluteURL(Director::baseURL())) === 0) { // Only proceed if the key is set if (strlen(trim($tenon_options["key"])) > 28 && ctype_xdigit(trim($tenon_options["key"]))) { // Store the page and create a hash of its contents $this->tenon_page = $request->postVar('tURL'); $this->tenon_hash = $this->createHash($request); $this->log("TenonAjax.requestTenon", "url=" . $this->tenon_url . ", options=" . print_r($tenon_options, true)); // If the page/hash combination has not already been checked, do it now if (!$this->existingPageHash()) { if ($this->requestSend($tenon_options) && $this->responseSave() && $this->savePageHash()) { $out = $this->jsonResponse(true); $this->log("TenonAjax.analyse", "out={$out}"); return $out; } } } } else { $this->log('Invalid request received by ' . Director::absoluteURL(Director::baseURL()) . ' from ' . $request->postVar('tURL')); } return $this->jsonResponse(false); }
public static function forceNonWWW() { if (!Director::isDev() && !Director::isTest() && strpos($_SERVER['HTTP_HOST'], 'www') === 0) { $destURL = str_replace(Director::protocol() . 'www.', Director::protocol(), Director::absoluteURL($_SERVER['REQUEST_URI'])); self::force_redirect($destURL); } }
/** * will ask the target server to return the file list and the data object list * @param type $request */ public function run($request) { if (!$this->config()->target) { throw new Exception('Target not found in yml file. See readme.md for installation instructions.'); } if (!$this->config()->key) { throw new Exception('Key not found in yml file. See readme.md for installation instructions.'); } $myurl = Director::absoluteURL('/remoteassetdiff') . '/' . urlencode($this->config()->key); $downloadurl = Director::absoluteURL('/remoteassetdownload') . '/' . urlencode($this->config()->key) . '?m=' . time(); // download without javascript if (Director::is_cli()) { ini_set('memory_limit', '1024M'); set_time_limit(0); echo "Creating list of files to download" . PHP_EOL; $listoffiles = RemoteAssetTask::DownloadFile($myurl); $fullist = json_decode($listoffiles); if (!is_array($fullist->download)) { throw new Exception('Failure to download list of files'); } foreach ($fullist->download as $file) { echo "Downloading {$file} ... "; try { RemoteAssetTask::DownloadFile($downloadurl . '&download=' . $file); echo "Success" . PHP_EOL; } catch (Exception $e) { echo "Failure" . PHP_EOL; } } echo "Done" . PHP_EOL; return; } echo ArrayData::create(array('FetchURL' => $myurl, 'DownloadURL' => $downloadurl, 'Target' => $this->config()->target, 'ToMachine' => Director::absoluteURL('/')))->renderWith('RemoteAssetTask'); }
/** * Login form handler method * * This method is called when the user clicks on "Log in" * * @param array $data Submitted data */ public function dologin($data) { if ($this->performLogin($data)) { $this->logInUserAndRedirect($data); } else { if (array_key_exists('Email', $data)) { Session::set('SessionForms.MemberLoginForm.Email', $data['Email']); Session::set('SessionForms.MemberLoginForm.Remember', isset($data['Remember'])); } if (isset($_REQUEST['BackURL'])) { $backURL = $_REQUEST['BackURL']; } else { $backURL = null; } if ($backURL) { Session::set('BackURL', $backURL); } // Show the right tab on failed login $loginLink = Director::absoluteURL($this->controller->Link()); if ($backURL) { $loginLink .= '?BackURL=' . urlencode($backURL); } $this->controller->redirect($loginLink . '#' . $this->FormName() . '_tab'); } }
/** * constructor * * @param Controller $controller the controller object * @param array $params additional parameters * @param array $preferences array with preferences * @param bool $barebone is the form initialized completely? * * @return void * * @author Sebastian Diel <*****@*****.**>, * Sascha Koehler <*****@*****.**> * @since 15.11.2014 */ public function __construct($controller, $params = null, $preferences = null, $barebone = false) { $member = SilvercartCustomer::currentUser(); $checkoutData = $controller->getCombinedStepData(); if (!$this->payment && $member) { if (array_key_exists('PaymentMethod', $checkoutData)) { $this->paymentMethodObj = DataObject::get_by_id('SilvercartPaymentMethod', $checkoutData['PaymentMethod']); if ($this->paymentMethodObj) { $this->paymentMethodObj->setController($controller); $this->paymentMethodObj->setCancelLink(Director::absoluteURL($controller->Link()) . 'GotoStep/2'); $this->paymentMethodObj->setReturnLink(Director::absoluteURL($controller->Link())); $this->paymentMethodObj->setCustomerDetailsByCheckoutData($checkoutData); $this->paymentMethodObj->setInvoiceAddressByCheckoutData($checkoutData); $this->paymentMethodObj->setShippingAddressByCheckoutData($checkoutData); $this->paymentMethodObj->setShoppingCart($member->getCart()); } } } parent::__construct($controller, $params, $preferences, $barebone); if (!$barebone) { /* * redirect a user if his cart is empty and no order exists */ $checkoutData = $this->controller->getCombinedStepData(); if (!SilvercartCustomer::currentUser() || !SilvercartCustomer::currentUser()->getCart()->isFilled() && !array_key_exists('orderId', $checkoutData)) { $frontPage = SilvercartPage_Controller::PageByIdentifierCode(); $this->getController()->redirect($frontPage->RelativeLink()); } } }
function run() { $batch_size = 15; if (isset($_GET['batch_size'])) { $batch_size = intval(trim(Convert::raw2sql($_GET['batch_size']))); } $surveys = DeploymentSurvey::getNotDigestSent($batch_size); $deployments = Deployment::getNotDigestSent($batch_size); if ($surveys) { foreach ($surveys as $survey) { $survey->SendDigest = 1; $survey->write(); } } if ($deployments) { foreach ($deployments as $dep) { $dep->SendDigest = 1; $dep->write(); } } if ((!is_null($surveys) && count($surveys)) > 0 || !is_null($deployments) && count($deployments)) { global $email_new_deployment; $email = EmailFactory::getInstance()->buildEmail($email_new_deployment, $email_new_deployment, $subject = 'New Deployments and Surveys'); $email->setTemplate('NewDeploymentsSurveysEmail'); $email->populateTemplate(array('SurveysUrl' => Director::absoluteURL('admin/deployments/DeploymentSurvey/EditForm/field/DeploymentSurvey/item'), 'DeploymentsUrl' => Director::absoluteURL('admin/deployments/Deployment/EditForm/field/Deployment/item'), 'SangriaDeploymentsUrl' => Director::absoluteURL('sangria/ViewDeploymentDetails'), 'Surveys' => $surveys, 'Deployments' => $deployments)); $email->send(); } }
/** * @return Form */ public function getEditForm($id = null, $fields = null) { $config = CodeBankConfig::CurrentConfig(); $fields = $config->getCMSFields(); $actions = new FieldList(FormAction::create('doSave', _t('CodeBank.SAVE', '_Save'))->addExtraClass('ss-ui-action-constructive')->setAttribute('data-icon', 'accept'), FormAction::create('doExportToClient', _t('CodeBank.EXPORT_TO_CLIENT', '_Export To Desktop Client'))->setAttribute('data-exporturl', Director::absoluteURL('code-bank-api/export-to-client'))->setAttribute('data-icon', 'export')); if (Permission::check('ADMIN')) { $actions->push(FormAction::create('doImportFromClient', _t('CodeBank.IMPORT_FROM_CLIENT', '_Import From Desktop Client'))->setAttribute('data-icon', 'import')->setAttribute('data-importurl', $this->Link('import-from-client'))); } $form = CMSForm::create($this, 'EditForm', $fields, $actions)->setHTMLID('Form_EditForm'); $form->addExtraClass('root-form'); $form->addExtraClass('cms-edit-form center'); // don't add data-pjax-fragment=CurrentForm, its added in the content template instead $form->setHTMLID('Form_EditForm'); $form->loadDataFrom($config); $form->setTemplate($this->getTemplatesWithSuffix('_EditForm')); // Use <button> to allow full jQuery UI styling $actions = $actions->dataFields(); if ($actions) { foreach ($actions as $action) { $action->setUseButtonTag(true); } } $this->extend('updateEditForm', $form); //Display message telling user to run dev/build because the version numbers are out of sync if (CB_VERSION != '@@VERSION@@' && CodeBankConfig::CurrentConfig()->Version != CB_VERSION . ' ' . CB_BUILD_DATE) { $form->setMessage(_t('CodeBank.UPDATE_NEEDED', '_A database upgrade is required please run {startlink}dev/build{endlink}.', array('startlink' => '<a href="dev/build?flush=all">', 'endlink' => '</a>')), 'error'); } else { if ($this->hasOldTables()) { $form->setMessage(_t('CodeBank.MIGRATION_AVAILABLE', '_It appears you are upgrading from Code Bank 2.2.x, your old data can be migrated {startlink}click here to begin{endlink}, though it is recommended you backup your database first.', array('startlink' => '<a href="dev/tasks/CodeBankLegacyMigrate">', 'endlink' => '</a>')), 'warning'); } } $form->Actions()->push(new LiteralField('CodeBankVersion', '<p class="codeBankVersion">Code Bank: ' . $this->getVersion() . '</p>')); return $form; }
/** * This does not actually perform any validation, but just creates the * initial registration object. */ public function validateStep($data, $form) { $form = $this->getForm(); $datetime = $form->getController()->getDateTime(); $confirmation = $datetime->Event()->RegEmailConfirm; $registration = $this->getForm()->getSession()->getRegistration(); // If we require email validation for free registrations, then send // out the email and mark the registration. Otherwise immediately // mark it as valid. if ($confirmation) { $email = new Email(); $config = SiteConfig::current_site_config(); $registration->TimeID = $datetime->ID; $registration->Status = 'Unconfirmed'; $registration->write(); if (Member::currentUserID()) { $details = array('Name' => Member::currentUser()->getName(), 'Email' => Member::currentUser()->Email); } else { $details = $form->getSavedStepByClass('EventRegisterTicketsStep'); $details = $details->loadData(); } $link = Controller::join_links($this->getForm()->getController()->Link(), 'confirm', $registration->ID, '?token=' . $registration->Token); $regLink = Controller::join_links($datetime->Event()->Link(), 'registration', $registration->ID, '?token=' . $registration->Token); $email->setTo($details['Email']); $email->setSubject(sprintf('Confirm Registration For %s (%s)', $datetime->getTitle(), $config->Title)); $email->setTemplate('EventRegistrationConfirmationEmail'); $email->populateTemplate(array('Name' => $details['Name'], 'Registration' => $registration, 'RegLink' => $regLink, 'Title' => $datetime->getTitle(), 'SiteConfig' => $config, 'ConfirmLink' => Director::absoluteURL($link))); $email->send(); Session::set("EventRegistration.{$registration->ID}.message", $datetime->Event()->EmailConfirmMessage); } else { $registration->Status = 'Valid'; $registration->write(); } return true; }
/** * Create the new notification email. * * @param Member $customer * @param Order $order * @param String $from * @param String $to * @param String $subject * @param String $body * @param String $bounceHandlerURL * @param String $cc * @param String $bcc */ public function __construct(Member $customer, Order $order, $from = null, $to = null, $subject = null, $body = null, $bounceHandlerURL = null, $cc = null, $bcc = null) { $siteConfig = ShopConfig::get()->first(); if ($siteConfig->NotificationTo) { $this->to = $siteConfig->NotificationTo; } if ($siteConfig->NotificationSubject) { $this->subject = $siteConfig->NotificationSubject . ' - Order #' . $order->ID; } if ($siteConfig->NotificationBody) { $this->body = $siteConfig->NotificationBody; } if ($customer->Email) { $this->from = $customer->Email; } elseif (Email::getAdminEmail()) { $this->from = Email::getAdminEmail(); } else { $this->from = 'no-reply@' . $_SERVER['HTTP_HOST']; } $this->signature = ''; $adminLink = Director::absoluteURL('/admin/shop/'); //Get css for Email by reading css file and put css inline for emogrification $this->setTemplate('Order_NotificationEmail'); if (file_exists(Director::getAbsFile($this->ThemeDir() . '/css/ShopEmail.css'))) { $css = file_get_contents(Director::getAbsFile($this->ThemeDir() . '/css/ShopEmail.css')); } else { $css = file_get_contents(Director::getAbsFile('swipestripe/css/ShopEmail.css')); } $this->populateTemplate(array('Message' => $this->Body(), 'Order' => $order, 'Customer' => $customer, 'InlineCSS' => "<style>{$css}</style>", 'Signature' => $this->signature, 'AdminLink' => $adminLink)); parent::__construct($from, null, $subject, $body, $bounceHandlerURL, $cc, $bcc); }
/** * Send verification email to member. */ public function sendVerificationEmail() { $validation_link = Controller::join_links(Director::absoluteURL('Security/validate-email'), $this->owner->VerificationString); $site_config = SiteConfig::current_site_config(); $site_title = $site_config->Title; $admin_email = Config::inst()->get('Email', 'admin_email'); $email_template_data = array('Member' => $this->owner, 'ValidationLink' => $validation_link, 'SiteConfig' => $site_config); $email_subject = _t('MemberEmailVerification.VERIFICATIONEMAILSUBJECT', "{site_title} Email Verification", array('site_title' => $site_title)); if (!$admin_email) { // Fallback to a placeholder admin email if Email.admin_email is not set $admin_email = '*****@*****.**'; } $sender_email = self::get_formatted_email($site_title, $admin_email); $recipient_email = $this->owner->Email; $email_to_recipient = Email::create($sender_email, $recipient_email, $email_subject); $email_to_recipient->setTemplate('VerificationEmail'); $email_to_recipient->populateTemplate($email_template_data); $email_status = $email_to_recipient->send(); // Return true if the email was successfully sent // Mailer::email will return `true` or an array if the email was successfully sent if ($email_status === true || is_array($email_status)) { return true; } return false; }
function testHandleURLRedirectionWithQueryString() { $response = $this->get('query-test-with-query-string?foo=bar'); $expected = $this->objFromFixture('RedirectedURL', 'redirect-with-query'); $this->assertEquals(301, $response->getStatusCode()); $this->assertEquals(Director::absoluteURL($expected->To), $response->getHeader('Location')); }
/** * @return String - title for project * * */ function SiteTitle() { $sc = SiteConfig::current_site_config(); if ($sc && $sc->Title) { return $sc->Title; } return Director::absoluteURL(); }
public function __construct($page, $member, $offers) { $from = $page->EmailFrom; $to = $member->Email; $subject = $page->NewOffersNewsletterSubject; parent::__construct($from, $to, $subject); $this->populateTemplate(new ArrayData(array('Member' => $member, 'TaskPage' => $page, 'Offers' => $offers, '$SiteName' => SiteConfig::current_site_config()->Title, '$LoginLink' => Director::absoluteURL(singleton('Security')->Link('login'))))); }
/** * Get the absolute URL for this page, including protocol and host. * * @param string $action See {@link Link()} * @return string */ public function AbsoluteLink($action = null) { if ($this->hasMethod('alternateAbsoluteLink')) { return $this->alternateAbsoluteLink($action); } else { return Director::absoluteURL($this->Link($action)); } }
public function Image($url, $alt = '') { $altattr = Convert::raw2att($alt); $imageSRC = Convert::raw2att(Director::absoluteURL($url)); $width = $this->getWidth($url); $height = $this->getHeight($url); return "<img\n\t\t\t\tborder=\"0\"\n\t\t\t\tsrc=\"{$imageSRC}\"\n\t\t\t\twidth=\"{$width}\"\n\t\t\t\theight=\"{$height}\"\n\t\t\t\talt=\"{$altattr}\"\n\t\t\t/>"; }
/** * Replaces variables inside an email template according to {@link TEMPLATE_NOTE}. * * @param string $string * @param Member $member * @return string */ public static function get_parsed_string($string, $member, $page) { $variables = array('$SiteName' => SiteConfig::current_site_config()->Title, '$LoginLink' => Director::absoluteURL(singleton('Security')->Link('login')), '$ConfirmLink' => Director::absoluteURL(Controller::join_links($page->Link('confirm'), $member->ID, "?key={$member->ValidationKey}")), '$LostPasswordLink' => Director::absoluteURL(singleton('Security')->Link('lostpassword')), '$Member.Created' => $member->obj('Created')->Nice()); foreach (array('Name', 'FirstName', 'Surname', 'Email') as $field) { $variables["\$Member.{$field}"] = $member->{$field}; } return str_replace(array_keys($variables), array_values($variables), $string); }
public static function redirectToSSL($url) { $dest = str_replace('http:', 'https:', Director::absoluteURL($url)); // This coupling to SapphireTest is necessary to test the destination URL and to not interfere with tests if (!headers_sent()) { header("Location: {$dest}"); } die("<h1>Your browser is not accepting header redirects</h1><p>Please <a href=\"{$dest}\">click here</a>"); }
/** * Retrieves the nececary data and returns it as rendered html * * @return HTMLText */ public function PlacePinterestButton() { $baseURL = Director::absoluteBaseURL(); $currentURL = Director::absoluteURL(''); $filename = $this->owner->Filename; $completPath = $baseURL . $filename; $imagTitle = $this->owner->Title; $sendData = new ArrayData(array("AbsoluteLink" => $completPath, "Description" => $imagTitle, "AbsoluteSiteLink" => $currentURL)); return $sendData->renderWith('PinterestButton'); }
public function updateCMSFields(FieldList $fields) { parent::updateCMSFields($fields); // Fix URLSegment field issue for root pages if (!SiteTree::config()->nested_urls || empty($this->owner->ParentID)) { $baseLink = Director::absoluteURL(Controller::join_links(Director::baseURL(), Fluent::alias(Fluent::current_locale()), '/')); $urlsegment = $fields->dataFieldByName('URLSegment'); $urlsegment->setURLPrefix($baseLink); } }
/** * Generate an absolute url for gateways to return to, or send requests to. * @param GatewayMessage $message message that redirect applies to. * @param string $status the intended status / action of the gateway * @param string $returnurl the application url to re-redirect to * @return string the resulting redirect url */ public static function get_return_url(GatewayMessage $message, $status = 'complete') { $returnurl = Controller::join_links('paymentendpoint', $message->Identifier, $status); // We only want to return the fake URL if it's to the processor directly, not the end user if ($status == 'notify' && defined('OMNIPAY_RETURN_URL')) { return OMNIPAY_RETURN_URL . $returnurl; } else { return Director::absoluteURL($returnurl); } }
protected function getUploadFields() { if (isset($_REQUEST['album'])) { SWFUploadConfig::addPostParam('AlbumID', $_REQUEST['album']); $album_name = DataObject::get_by_id("ImageGalleryAlbum", $_REQUEST['album'])->AlbumName; } else { $album_name = ""; } return new FieldSet(new HeaderField($title = sprintf(_t('ImageGalleryManager.UPLOADIMAGESTO', 'Upload Images to "%s"'), $album_name), $headingLevel = 2), new HeaderField($title = _t('ImageGalleryManager.UPLOADFROMPC', 'Upload from my computer'), $headingLevel = 3), new SWFUploadField("UploadForm", "Upload", "", array('file_upload_limit' => $this->getUploadLimit(), 'file_queue_limit' => $this->getUploadLimit(), 'browse_button_text' => _t('ImageGalleryManager.UPLOADIMAGES', 'Upload Images') . '...', 'upload_url' => Director::absoluteURL('ImageGalleryManager_Controller/handleswfupload'), 'required' => 'true'))); }
public function ReadyVideo() { $PATH = Director::absoluteURL('digomePlayer', true); $script = <<<EOD \$GP.url.flash = '{$PATH}/digomePlayerHTTP.swf'; DigomePlayer.registerSkin('{$PATH}/skin/'); DigomePlayer.load('a.digome-player'); EOD; Requirements::customScript($script, 'digomePlayer'); }
public function __construct($object = null, $urls = null) { if ($object) { if (singleton('SimpleCachePublisher')->dontCache($object)) { $this->totalSteps = 1; return; } $collection = null; if ($object instanceof DataList) { $collection = $object; $object = $object->First(); } else { $collection = new ArrayList(); $collection->push($object); } $this->setObject($object); if (!$urls) { // swap over to a proper base URL if needed if ($object->SiteID && class_exists('Multisites')) { // let's set the base directly $base = $object->Site()->getUrl(); if (substr($base, -1) !== '/') { // ensures base URL has a trailing slash $base .= '/'; } Config::inst()->update('Director', 'alternate_base_url', $base); } $stage = Versioned::current_stage(); Versioned::reading_stage('Live'); $urls = array(); // loop over the collection so we only add URLs once foreach ($collection as $object) { if ($object->NeverCache) { continue; } if ($object->hasMethod('pagesAffectedByChanges')) { $affected = $object->pagesAffectedByChanges(null); foreach ($affected as $newUrl) { $newUrl = Director::absoluteURL($newUrl); $urls[$newUrl] = true; } } else { $urls[$object->AbsoluteLink()] = true; } } if (count($urls)) { $urls = array_keys($urls); } Versioned::reading_stage($stage); $object->extend('updateAffectedPages', $urls); } $this->urls = array_unique($urls); $this->totalSteps = count($this->urls); } }
/** * Turn all relative URLs in the content to absolute URLs */ public static function absoluteURLs($html) { $html = str_replace('$CurrentPageURL', $_SERVER['REQUEST_URI'], $html); return HTTP::urlRewriter($html, function ($url) { //no need to rewrite, if uri has a protocol (determined here by existence of reserved URI character ":") if (preg_match('/^\\w+:/', $url)) { return $url; } return Director::absoluteURL($url, true); }); }
public function expand($url) { $base = Director::absoluteURL(Controller::join_links(Director::baseURL(), self::$url_path, "/")); if (substr($url, 0, strlen($base)) == $base) { $hash_SQL = Convert::raw2sql(substr($url, strlen($base))); $obj = DataObject::get_one('SSURLShortenerObject', "Hash = '{$hash_SQL}'"); if ($obj) { return $obj->LongURL; } } return ""; }
public function alternateAbsoluteLink($action = null) { $link = Director::absoluteURL($this->owner->Link($action)); if ($this->owner->hasExtension('Translatable')) { $targetLoc = $this->owner->Locale; $currLoc = Translatable::get_current_locale(); if ($targetLoc != $currLoc) { $link = Controller::join_links(Director::protocol() . LocaleDomains::getHostFromLocale($targetLoc), $this->owner->RelativeLink($action)); } } return $link; }
function getCMSFields() { $fields = parent::getCMSFields(); $exampleLink = Director::absoluteURL($this->Link("setamount")) . "/123.45"; $exampleLinkExplanation = sprintf(_t("AnyPriceProductPage.EXPLANATION", '<br /><br /><h5>How to preset the amount?</h5><p>The link <a href="%1$s">%1$s</a> will pre-set the amount to 123.45. You can use this link (and vary the amount as needed) to cutomers to receive payments.</p>.'), $exampleLink); $fields->addFieldsToTab("Root.AddAmountForm", array(new TextField("AmountFieldLabel", "Amount Field Label (what amount would you like to pay?)"), new TextField("ActionFieldLabel", "Action Field Label (e.g. pay entered amount now)"), new NumericField("MinimumAmount", "Minimum Amount"), new NumericField("MaximumAmount", "Maximum Amount"), new TextField("RecommendedAmounts", "Hinted amounts, separated by commas (e.g. <i>5,10,100</i>)"), new LiteralField("ExampleLinkExplanation", $exampleLinkExplanation))); // Standard product detail fields $fields->removeFieldsFromTab('Root.Details', array('Weight', 'Price', 'Model')); // Flags for this product which affect it's behaviour on the site $fields->removeFieldsFromTab('Root.Details', array('FeaturedProduct')); return $fields; }
/** * @param SS_HTTPRequest $request * @throws SS_HTTPResponse_Exception */ public function onBeforeHTTPError404($request) { $url = strtolower($this->getUrl($request)); $oldPage = OldURLRedirect::get_from_url($url); // If there's a match, direct! if ($oldPage) { $response = new SS_HTTPResponse(); $dest = $oldPage->getRedirectionLink(); $response->redirect(Director::absoluteURL($dest), $oldPage->getRedirectCode()); throw new SS_HTTPResponse_Exception($response); } }
/** * * @param SS_HTTPRequest $request * @return SS_HTTPResponse */ public function listProjects(SS_HTTPRequest $request) { $response = array('href' => Director::absoluteURL($this->Link()), 'projects' => array()); if ($request->httpMethod() != 'GET') { return $this->message('API not found', 404); } foreach (DNProject::get() as $item) { if ($item->canView($this->getMember())) { $response['projects'][] = array("name" => $item->Name, "href" => Director::absoluteURL($item->APILink(""))); } } return $this->getAPIResponse($response); }