public function register(SS_HTTPRequest $request)
 {
     if ($request->isPOST()) {
         try {
             if (Customer::get()->filter('Email', $request->postVar('Email'))->count()) {
                 throw new ValidationException("Sorry a member with that email address already exists");
             }
             $password = Customer::create_new_password();
             /** @var Customer $member */
             $member = Injector::inst()->create('ProfiledMemberClass');
             $member->changePassword($password);
             // update member with cleansed posted variables
             $updateData = array_merge(ProfiledMemberForm::update_models('register', array_merge($request->postVars(), ['Password' => $password]), $member));
             /** @var CryptofierImplementation $crypto */
             $crypto = Injector::inst()->get('CryptofierService');
             $token = $crypto->friendly($crypto->encrypt($member->Email));
             $member->{ProfiledMemberExtension::VerificationFieldName} = $token;
             $member->write();
             $member->addToGroupByCode(self::CustomerGroupCode);
             // add verification link and HasRegisteredFlag
             $updateData = array_merge(['Password' => $password, 'VerificationLink' => Controller::join_links(Director::absoluteBaseURL(), $this()->ActionLink("verify/{$token}"))], $updateData);
             $this->sendEmail('Register', $member, $updateData);
             Session::set(self::SessionEmailKey, $member->Email);
             $url = CrackerjackModule::get_config_setting(__CLASS__, 'post_register_url') ?: $this()->ActionLink('thanks');
             return $this()->redirect($url);
         } catch (ValidationException $e) {
             ProfiledMemberForm::set_form_message($e->getMessage(), CrackerjackForm::Bad);
             return $this()->redirectBack();
         }
     } else {
         return array();
     }
 }
 public function getCMSFields()
 {
     $datetimeField = DatetimeField::create("Date")->setTitle($this->fieldLabel("Date"));
     $datetimeField->getDateField()->setConfig("dmyfields", true);
     // Check if NewsImage should be saved in a seperate folder
     if (self::config()->save_image_in_seperate_folder == false) {
         $UploadField = UploadField::create("NewsImage")->setTitle($this->fieldLabel("NewsImage"))->setFolderName("news");
     } else {
         if ($this->ID == "0") {
             $UploadField = FieldGroup::create(LiteralField::create("Save", $this->fieldLabel("SaveHelp")))->setTitle($this->fieldLabel("NewsImage"));
         } else {
             $UploadField = UploadField::create("NewsImage")->setTitle($this->fieldLabel("NewsImage"))->setFolderName("news/" . $this->URLSegment);
         }
     }
     // Create direct link to NewsArticle
     if ($this->ID == "0") {
         // Little hack to hide $urlsegment when article isn't saved yet.
         $urlsegment = LiteralField::create("NoURLSegmentYet", "");
     } else {
         if ($NewsHolder = $this->NewsHolder()) {
             $baseLink = Controller::join_links(Director::absoluteBaseURL(), $NewsHolder->Link(), $this->URLSegment);
         }
         $urlsegment = Fieldgroup::create(LiteralField::create("URLSegment", "URLSegment")->setContent('<a href="' . $baseLink . '" target="_blank">' . $baseLink . '</a>'))->setTitle("URLSegment");
     }
     $fields = FieldList::create(new TabSet("Root", new Tab("Main", $urlsegment, TextField::create("Title")->setTitle($this->fieldLabel("Title")), $datetimeField, HTMLEditorField::create("Content")->setTitle($this->fieldLabel("Content")), $UploadField)));
     $this->extend("updateCMSFields", $fields);
     return $fields;
 }
 public function generateSiteMap($sitemap = 'sitemap.xml', $siteURL = null)
 {
     $siteData = singleton('SiteDataService');
     $pages = $siteData->getItems();
     $xml = new SimpleXMLElement('<urlset></urlset>');
     $xml->addAttribute('xmlns', 'http://www.sitemaps.org/schemas/sitemap/0.9');
     $xml->addAttribute('xmlns:xsi', 'http://www.w3.org/2001/XMLSchema-instance');
     $xml->addAttribute('xsi:schemaLocation', 'http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd');
     if (!$siteURL) {
         $siteURL = self::config()->get('base_url');
         if (!$siteURL) {
             $siteURL = Director::absoluteBaseURL();
         }
     }
     $siteURL = rtrim($siteURL, '/') . '/';
     if (!strpos($siteURL, ':/')) {
         $siteURL = $this->config()->protocol . '://' . $siteURL;
     }
     foreach ($pages as $page) {
         $url = $xml->addChild('url');
         $url->addChild('loc', $siteURL . $page->Link);
         $url->addChild('changefreq', $page->ChangeFreq);
         $url->addChild('priority', $page->Priority);
     }
     file_put_contents($sitemap, $xml->asXML());
 }
 public function subscribeRealtime()
 {
     $subID = $_GET['subscription'];
     $sub = InstagramSubscription::get()->byID($subID);
     $callback = Director::absoluteBaseURL() . Config::inst()->get('Instagram', 'subscribeCallback');
     $type = $sub->Type;
     if ($type !== 'tag' && $type !== 'user') {
         throw new Exception('Subscription type is invalid');
     }
     $url = 'v1/subscriptions';
     if ($type == 'tag') {
         $key = $sub->Hashtag;
         $data = array("client_id" => $this->clientID, 'client_secret' => $this->clientSecret, 'object' => 'tag', 'object_id' => $key, 'aspect' => 'media', 'callback_url' => $callback);
     } else {
         if ($type == 'user') {
             $data = array("client_id" => $this->clientID, 'client_secret' => $this->clientSecret, 'object' => 'user', 'aspect' => 'media', 'verify_token' => $sub->AccessToken, 'callback_url' => $callback);
         }
     }
     $res = $this->json_request($url, 'POST', $data);
     if ($res->meta->code == 200) {
         $sub->SubscriptionID = $res->data->id;
         $sub->write();
         return true;
     } else {
         throw new Exception('Error Subscribing to Instagram');
     }
 }
 public function ConvertURL($url, $filename, $useCacheIfAvailable = false)
 {
     $folderFilename = '';
     if (isset($_GET["flush"])) {
         $useCacheIfAvailable = false;
     }
     $folderFilename = $this->file2FolderFilename($filename);
     if ($folderFilename && $useCacheIfAvailable) {
         if (file_exists($folderFilename)) {
             $url = Director::absoluteBaseURL() . $this->file2FolderFilename($filename, true);
             header("Location: {$url}");
             exit;
         }
     }
     try {
         $pdf = $this->pdf->convertURI($url);
     } catch (PdfcrowdException $e) {
         return "Pdfcrowd Error: " . $e->getMessage();
     }
     if ($folderFilename = $this->file2FolderFilename($filename)) {
         if (!$pdf) {
             $pdf = "error occured";
         }
         $this->removeCachedPDF($filename);
         $fh = fopen($folderFilename, 'w');
         fwrite($fh, $pdf);
         fclose($fh);
     }
     return $this->outputPDF($pdf, $filename);
 }
Esempio n. 6
0
	function testExternalBackUrlRedirectionDisallowed() {
		$page = new SiteTree();
		$page->URLSegment = 'testpage';
		$page->Title = 'Testpage';
		$page->write();
		$page->publish('Stage','Live');
		
		// Test internal relative redirect
		$response = $this->doTestLoginForm('*****@*****.**', '1nitialPassword', 'testpage');
		$this->assertEquals(302, $response->getStatusCode());
		$this->assertRegExp('/testpage/', $response->getHeader('Location'),
			"Internal relative BackURLs work when passed through to login form"
		);
		// Log the user out
		$this->session()->inst_set('loggedInAs', null);
		
		// Test internal absolute redirect
		$response = $this->doTestLoginForm('*****@*****.**', '1nitialPassword', Director::absoluteBaseURL() . 'testpage');
		// for some reason the redirect happens to a relative URL
		$this->assertRegExp('/^' . preg_quote(Director::absoluteBaseURL(), '/') . 'testpage/', $response->getHeader('Location'),
			"Internal absolute BackURLs work when passed through to login form"
		);
		// Log the user out
		$this->session()->inst_set('loggedInAs', null);
		
		// Test external redirect
		$response = $this->doTestLoginForm('*****@*****.**', '1nitialPassword', 'http://myspoofedhost.com');
		$this->assertNotRegExp('/^' . preg_quote('http://myspoofedhost.com', '/') . '/', $response->getHeader('Location'),
			"Redirection to external links in login form BackURL gets prevented as a measure against spoofing attacks"
		);
		// Log the user out
		$this->session()->inst_set('loggedInAs', null);
	}
Esempio n. 7
0
 function index()
 {
     Session::clear("loggedInAs");
     Requirements::themedCSS("form");
     // if the email address is given
     $emailAddress = Convert::raw2sql($this->urlParams['Email']);
     $mailingListID = (int) $this->urlParams['MailingList'];
     if ($mailingListID) {
         $mailingList = DataObject::get_by_id("NewsletterType", $mailingListID);
     }
     // try to find the member with the email specified
     if ($emailAddress) {
         $member = DataObject::get_one('Member', "`Email` = '{$emailAddress}'");
     } else {
         $member = false;
     }
     // if the email address and mailing list is given in the URL and both are valid,
     // then unsubscribe the user
     if ($member && $mailingList && $member->inGroup($mailingList->GroupID)) {
         $this->unsubscribeFromList($member, $mailingList);
         $url = '/done/' . $member->Email . '/' . $mailingList->Title;
         Director::redirect(Director::absoluteBaseURL() . $this->RelativeLink() . $url);
         return;
     } elseif ($member) {
         $listForm = $this->MailingListForm($member);
     } else {
         $listForm = $this->EmailAddressForm();
     }
     if ($this->urlParams['Email'] == "done") {
         $listForm->sessionMessage(_t('Unsubscribe.SUCCESS', 'Thank you. You have been removed from the selected groups'), "good");
     }
     return $this->customise(array('Content' => $listForm->forTemplate()))->renderWith('Page');
 }
 /**
  * Convenience method to return links to cart related page.
  * 
  * @param String $type The type of cart page a link is needed for
  * @return String The URL to the particular page
  */
 function CartLink($type = 'Cart')
 {
     switch ($type) {
         case 'Account':
             if ($page = DataObject::get_one('AccountPage')) {
                 return $page->Link();
             } else {
                 break;
             }
         case 'Checkout':
             if ($page = DataObject::get_one('CheckoutPage')) {
                 return $page->Link();
             } else {
                 break;
             }
         case 'Login':
             return Director::absoluteBaseURL() . 'Security/login';
             break;
         case 'Logout':
             if ($page = DataObject::get_one('AccountPage')) {
                 return $page->Link() . 'logout';
             } else {
                 break;
             }
         case 'Cart':
         default:
             if ($page = DataObject::get_one('CartPage')) {
                 return $page->Link();
             } else {
                 break;
             }
     }
 }
 /**
  * Retrieve and process order data from the request
  */
 public function callback($request)
 {
     $this->extend('onBeforeCallback');
     $data = $this->request->postVars();
     $status = "error";
     $order_id = 0;
     $payment_id = 0;
     $success_url = Controller::join_links(Director::absoluteBaseURL(), Payment_Controller::config()->url_segment, 'complete');
     $error_url = Controller::join_links(Director::absoluteBaseURL(), Payment_Controller::config()->url_segment, 'complete', 'error');
     $vars = array("SiteConfig" => SiteConfig::current_site_config(), "RedirectURL" => $error_url);
     // Check if CallBack data exists and install id matches the saved ID
     if (isset($data) && (isset($data['instId']) && isset($data['cartId']) && isset($data['transStatus']) && isset($data["callbackPW"])) && $this->payment_gateway->InstallID == $data['instId'] && $this->payment_gateway->ResponsePassword == $data["callbackPW"]) {
         $order_id = $data['cartId'];
         $payment_id = $data['transId'];
         $status = $data['transStatus'];
         if ($data['transStatus'] == 'Y') {
             $status = 'paid';
             $vars["RedirectURL"] = $success_url;
         } else {
             $status = 'failed';
         }
     } else {
         return $this->httpError(500);
     }
     $payment_data = ArrayData::array_to_object(array("OrderID" => $order_id, "PaymentProvider" => "WorldPay", "PaymentID" => $payment_id, "Status" => $status, "GatewayData" => $data));
     $this->setPaymentData($payment_data)->customise($vars);
     $this->extend('onAfterCallback');
     return $this->renderWith(array("Worldpay_callback"));
 }
 /**
  * @return Form|SS_HTTPResponse
  */
 public function EditProfileForm()
 {
     if (!Member::currentUser()) {
         $this->setFlash(_t('EditProfilePage.LoginWarning', 'Please login to edit your profile'), 'warning');
         return $this->redirect(Director::absoluteBaseURL());
     }
     $firstName = new TextField('FirstName');
     $firstName->setAttribute('placeholder', _t('EditProfilePage.FirstNamePlaceholder', 'Enter your first name'))->setAttribute('required', 'required')->addExtraClass('form-control');
     $surname = new TextField('Surname');
     $surname->setAttribute('placeholder', _t('EditProfilePage.SurnamePlaceholder', 'Enter your surname'))->setAttribute('required', 'required')->addExtraClass('form-control');
     $email = new EmailField('Email');
     $email->setAttribute('placeholder', _t('EditProfilePage.EmailPlaceholder', 'Enter your email address'))->setAttribute('required', 'required')->addExtraClass('form-control');
     $jobTitle = new TextField('JobTitle');
     $jobTitle->setAttribute('placeholder', _t('EditProfilePage.JobTitlePlaceholder', 'Enter your job title'))->addExtraClass('form-control');
     $website = new TextField('Website');
     $website->setAttribute('placeholder', _t('EditProfilePage.WebsitePlaceholder', 'Enter your website'))->addExtraClass('form-control');
     $blurb = new TextareaField('Blurb');
     $blurb->setAttribute('placeholder', _t('EditProfilePage.BlurbPlaceholder', 'Enter your blurb'))->addExtraClass('form-control');
     $confirmPassword = new ConfirmedPasswordField('Password', _t('EditProfilePage.PasswordLabel', 'New Password'));
     $confirmPassword->canBeEmpty = true;
     $confirmPassword->setAttribute('placeholder', _t('EditProfilePage.PasswordPlaceholder', 'Enter your password'))->addExtraClass('form-control');
     $fields = new FieldList($firstName, $surname, $email, $jobTitle, $website, $blurb, $confirmPassword);
     $action = new FormAction('SaveProfile', _t('EditProfilePage.SaveProfileText', 'Update Profile'));
     $action->addExtraClass('btn btn-primary btn-lg');
     $actions = new FieldList($action);
     // Create action
     $validator = new RequiredFields('FirstName', 'Email');
     //Create form
     $form = new Form($this, 'EditProfileForm', $fields, $actions, $validator);
     //Populate the form with the current members data
     $Member = Member::currentUser();
     $form->loadDataFrom($Member->data());
     //Return the form
     return $form;
 }
 public function onBeforeInit()
 {
     $host = GlobalNavSiteTreeExtension::get_toolbar_hostname();
     if (isset($_REQUEST['flush']) && $host == Director::absoluteBaseURL()) {
         GlobalNavSiteTreeExtension::create_nav();
     }
 }
 /**
  * @inheritdoc
  */
 public function run($request)
 {
     /* Get the protocol and host */
     list($protocol, $host) = explode('://', Director::absoluteBaseURL());
     $host = trim($host, '/\\');
     try {
         /* Flush via SSViewer, this is a clean flush */
         echo 'Flushing SSViewer caches<br />';
         SSViewer::flush_template_cache();
         /* Remove the entire cache directory forcefully. Hard, unclean flush */
         echo 'Removing temp folder ' . TEMP_FOLDER . '<br />';
         exec('rm -rf ' . TEMP_FOLDER);
         if (!file_exists(TEMP_FOLDER)) {
             /* Show a success-message if the TEMP_FOLDER is gone */
             echo 'Succesfully purged the temporary folder. A rebuild of caches is necessary now.<br />';
         }
         /* Flush Varnish. If it isn't available, this _might_ crash. Previous statements have been executed though */
         echo "Flushing Varnish cache for host {$host}<br />";
         exec('flushvarnish -h ' . $host);
         /* Be friendly to the user */
         echo 'Done clearing caches, please reload your site: <a href="' . Director::absoluteBaseURL() . '">here</a><br />';
         echo 'Please note, all protocols have the same cache, so not only ' . $protocol . 'is cleared';
     } catch (Exception $e) {
         /* When boom, error out */
         echo 'Error while clearing caches: ' . $e->getMessage();
     }
 }
Esempio n. 13
0
 public function init()
 {
     // Check permissions
     // if(!Member::currentUser() || !Member::currentUser()->isAdmin()) Security::permissionFailure($this);
     parent::init();
     /*
     		if(!$this->can('AdminCMS')) {
     			$messageSet = array(
     				'default' => "Please choose an authentication method and enter your credentials to access the CMS.",
     				'alreadyLoggedIn' => "I'm sorry, but you can't access that part of the CMS.  If you want to log in as someone else, do so below",
     				'logInAgain' => "You have been logged out of the CMS.  If you would like to log in again, enter a username and password below.",
     			);
     
     			Security::permissionFailure($this, $messageSet);
     			return;
     		}*/
     Requirements::javascript(MCE_ROOT . "tiny_mce_src.js");
     Requirements::javascript("jsparty/tiny_mce_improvements.js");
     Requirements::javascript("jsparty/hover.js");
     Requirements::javascript("jsparty/scriptaculous/controls.js");
     Requirements::javascript("cms/javascript/SecurityAdmin.js");
     Requirements::javascript("cms/javascript/LeftAndMain_left.js");
     Requirements::javascript("cms/javascript/LeftAndMain_right.js");
     Requirements::javascript("cms/javascript/CMSMain_left.js");
     Requirements::javascript("cms/javascript/NewsletterAdmin_left.js");
     Requirements::javascript("cms/javascript/NewsletterAdmin_right.js");
     Requirements::javascript("sapphire/javascript/ProgressBar.js");
     // We don't want this showing up in every ajax-response, it should always be present in a CMS-environment
     if (!Director::is_ajax()) {
         Requirements::javascriptTemplate("cms/javascript/tinymce.template.js", array("ContentCSS" => project() . "/css/editor.css", "BaseURL" => Director::absoluteBaseURL(), "Lang" => i18n::get_tinymce_lang()));
     }
     // needed for MemberTableField (Requirements not determined before Ajax-Call)
     Requirements::javascript("cms/javascript/MemberTableField.js");
     Requirements::css("cms/css/NewsletterAdmin.css");
 }
Esempio n. 14
0
	function index() {
		$tasks = $this->getTasks();

		// Web mode
		if(!Director::is_cli()) {
			$renderer = new DebugView();
			$renderer->writeHeader();
			$renderer->writeInfo("Sapphire Development Tools: Tasks", Director::absoluteBaseURL());
			$base = Director::baseURL();
			if(strpos($base,-1) != '/') $base .= '/';
			
			echo "<ul>";
			foreach($tasks as $task) {
				echo "<li>";
				echo "<a href=\"{$base}dev/tasks/" . $task['class'] . "\">" . $task['title'] . "</a><br />";
				echo "<span class=\"description\">" . $task['description'] . "</span>";
				echo "</li>\n";
			}
			echo "</ul>";

			$renderer->writeFooter();
		// CLI mode
		} else {
			echo "SAPPHIRE DEVELOPMENT TOOLS: Tasks\n--------------------------\n\n";
			foreach($tasks as $task) {
				echo " * $task: sake dev/tasks/" . $task['class'] . "\n";
			}
		}
	}
 public function placeOrder(SS_HTTPRequest $request)
 {
     $eventbrite_event_header = $request->getHeader('X-Eventbrite-Event');
     if (!$eventbrite_event_header) {
         return $this->httpError(403);
     }
     if ($eventbrite_event_header !== 'order.placed') {
         return $this->httpError(403);
     }
     if (!$this->isJson()) {
         return $this->httpError(403);
     }
     $json_request = $this->getJsonRequest();
     if (!isset($json_request['config']) || !isset($json_request['api_url'])) {
         return $this->httpError(403);
     }
     $config = $json_request['config'];
     if (!isset($config['action']) || $config['action'] !== 'order.placed') {
         return $this->httpError(403);
     }
     $current_local_url = Controller::join_links(Director::absoluteBaseURL(), $request->getURL());
     if (!isset($config['endpoint_url']) || $config['endpoint_url'] !== $current_local_url) {
         return $this->httpError(403);
     }
     try {
         $this->manager->registerEvent('ORDER_PLACED', $json_request['api_url']);
     } catch (Exception $ex) {
         SS_Log::log($ex->getMessage(), SS_Log::ERR);
         return $this->httpError(500);
     }
     return true;
 }
 public function MaxStripeLoginLink()
 {
     if ($o = Config::inst()->get('MaxLoginFormPageExtension', 'MaxStripeLoginLink')) {
         return $o;
     }
     return Director::absoluteBaseURL();
 }
 public function init()
 {
     $ageMonth = Cookie::get('bmonth');
     $ageDay = Cookie::get('bday');
     $ageYear = Cookie::get('byear');
     $age = Cookie::get('age');
     $allowed_urls = array('/age-gate/');
     if ($age == NULL) {
         if (!$this->isSearchEngine()) {
             if (!in_array($_SERVER['REQUEST_URI'], $allowed_urls)) {
                 Session::set('AgeGateBackURL', urlencode($_SERVER['REQUEST_URI']));
                 $this->redirect(Director::absoluteBaseURL() . "age-gate/");
             }
         }
     } else {
         if (!in_array($_SERVER['REQUEST_URI'], $allowed_urls)) {
             if ($ageMonth == NULL || $ageDay == NULL || $ageYear == NULL) {
                 if (!in_array($_SERVER['REQUEST_URI'], $allowed_urls)) {
                     Session::set('AgeGateBackURL', urlencode($_SERVER['REQUEST_URI']));
                 }
                 $this->redirect(Director::absoluteBaseURL() . "age-gate/");
             }
         }
     }
     parent::init();
 }
 /**
  * @uses ModelAsController::getNestedController()
  * @param SS_HTTPRequest $request
  * @param DataModel $model
  * @return SS_HTTPResponse
  */
 public function handleRequest(SS_HTTPRequest $request, DataModel $model)
 {
     $this->setRequest($request);
     $this->setDataModel($model);
     $this->pushCurrent();
     // Create a response just in case init() decides to redirect
     $this->response = new SS_HTTPResponse();
     $this->init();
     // If we had a redirection or something, halt processing.
     if ($this->response->isFinished()) {
         $this->popCurrent();
         return $this->response;
     }
     // If the database has not yet been created, redirect to the build page.
     if (!DB::is_active() || !ClassInfo::hasTable('SiteTree')) {
         $this->response->redirect(Director::absoluteBaseURL() . 'dev/build?returnURL=' . (isset($_GET['url']) ? urlencode($_GET['url']) : null));
         $this->popCurrent();
         return $this->response;
     }
     try {
         $result = $this->getNestedController();
         if ($result instanceof RequestHandler) {
             $result = $result->handleRequest($this->getRequest(), $model);
         } else {
             if (!$result instanceof SS_HTTPResponse) {
                 user_error("ModelAsController::getNestedController() returned bad object type '" . get_class($result) . "'", E_USER_WARNING);
             }
         }
     } catch (SS_HTTPResponse_Exception $responseException) {
         $result = $responseException->getResponse();
     }
     $this->popCurrent();
     return $result;
 }
 /**
  * @return array
  */
 public function EmailBodyVariables()
 {
     $editPageLink = singleton('CMSPageEditController')->Link('show');
     $editPageLink .= '/' . $this->FormID;
     $absoluteEditPageLink = Controller::join_links(Director::absoluteBaseURL(), $editPageLink);
     return array('$LinkTag' => '<a href="' . $absoluteEditPageLink . '">' . $absoluteEditPageLink . '</a>', '$Link' => $absoluteEditPageLink);
 }
Esempio n. 20
0
 public function init()
 {
     parent::init();
     Requirements::javascript(MCE_ROOT . "tiny_mce_src.js");
     Requirements::javascript("jsparty/tiny_mce_improvements.js");
     Requirements::javascript("jsparty/hover.js");
     Requirements::javascript("jsparty/scriptaculous/controls.js");
     Requirements::javascript("cms/javascript/SecurityAdmin.js");
     Requirements::javascript("cms/javascript/LeftAndMain_left.js");
     Requirements::javascript("cms/javascript/LeftAndMain_right.js");
     Requirements::javascript("cms/javascript/CMSMain_left.js");
     Requirements::javascript("cms/javascript/ReportAdmin_left.js");
     Requirements::javascript("cms/javascript/ReportAdmin_right.js");
     Requirements::css("cms/css/ReportAdmin.css");
     // TODO Find a better solution to integrate optional Requirements in a specific order
     if (Director::fileExists("ecommerce/css/DataReportCMSMain.css")) {
         Requirements::css("ecommerce/css/DataReportCMSMain.css");
     }
     if (Director::fileExists("ecommerce/css/DataReportCMSMain.css")) {
         Requirements::javascript("ecommerce/javascript/DataReport.js");
     }
     if (Director::fileExists(project() . "/css/DataReportCMSMain.css")) {
         Requirements::css(project() . "/css/DataReportCMSMain.css");
     }
     if (Director::fileExists(project() . "/css/DataReportCMSMain.css")) {
         Requirements::javascript(project() . "/javascript/DataReport.js");
     }
     // We don't want this showing up in every ajax-response, it should always be present in a CMS-environment
     if (!Director::is_ajax()) {
         Requirements::javascriptTemplate("cms/javascript/tinymce.template.js", array("ContentCSS" => project() . "/css/editor.css", "BaseURL" => Director::absoluteBaseURL(), "Lang" => i18n::get_tinymce_lang()));
     }
 }
Esempio n. 21
0
 public function index()
 {
     $tasks = $this->getTasks();
     // Web mode
     if (!Director::is_cli()) {
         $renderer = new DebugView();
         $renderer->writeHeader();
         $renderer->writeInfo("SilverStripe Development Tools: Tasks", Director::absoluteBaseURL());
         $base = Director::absoluteBaseURL();
         echo "<div class=\"options\">";
         echo "<ul>";
         foreach ($tasks as $task) {
             echo "<li><p>";
             echo "<a href=\"{$base}dev/tasks/" . $task['segment'] . "\">" . $task['title'] . "</a><br />";
             echo "<span class=\"description\">" . $task['description'] . "</span>";
             echo "</p></li>\n";
         }
         echo "</ul></div>";
         $renderer->writeFooter();
         // CLI mode
     } else {
         echo "SILVERSTRIPE DEVELOPMENT TOOLS: Tasks\n--------------------------\n\n";
         foreach ($tasks as $task) {
             echo " * {$task['title']}: sake dev/tasks/" . $task['segment'] . "\n";
         }
     }
 }
 /**
  * @todo fix this BIG mess.
  */
 public static function postFacebook($message, $link = null, $impression = null)
 {
     $member = Member::currentUser();
     $postresult = false;
     $SiteConfig = SiteConfig::current_site_config();
     if ($member && $SiteConfig->FBAppID && $SiteConfig->FBSecret) {
         if ($link == null) {
             $link = Director::absoluteBaseURL();
         }
         $page = '/' . $SiteConfig->FBPageID . '/feed';
         $facebook = new Facebook(array('appId' => $SiteConfig->FBAppID, 'secret' => $SiteConfig->FBSecret));
         $token = $facebook->api('/me/accounts');
         foreach ($token['data'] as $pages) {
             if ($pages['id'] == $SiteConfig->FBPageID) {
                 $facebook->setAccessToken($pages['access_token']);
                 $verified = true;
                 break;
             }
         }
         if ($verified) {
             $data = array('message' => $message, 'link' => $link, 'picture' => $impression);
             $postresult = $facebook->api($page, 'post', $data);
         }
     }
     return $postresult;
 }
 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;
     }
 }
 /**
  * @param $data
  * @param $form
  * @return bool|SS_HTTPResponse
  */
 function Register($data, $form)
 {
     // Set session array individually as setting the password breaks the form.
     $sessionArray = array('Email' => $data['Email']);
     // Check for existing member email address
     if ($existingUser = DataObject::get_one('Member', "Email = '" . Convert::raw2sql($data['Email']) . "'")) {
         $form->AddErrorMessage('Email', _t('RegistrationPage.EmailValidationText', 'Sorry, that email address already exists. Please choose another.'), 'validation');
         Session::set('FormInfo.Form_RegistrationForm.data', $sessionArray);
         return $this->redirectBack();
     }
     // Otherwise create new member and log them in
     $Member = new Member();
     $form->saveInto($Member);
     $Member->write();
     $Member->login();
     // Find or create the 'user' group
     if (!($userGroup = DataObject::get_one('Group', "Code = 'users'"))) {
         $userGroup = new Group();
         $userGroup->Code = 'users';
         $userGroup->Title = 'Users';
         $userGroup->Write();
         $userGroup->Members()->add($Member);
     }
     // Add member to user group
     $userGroup->Members()->add($Member);
     // Get profile page otherwise display warning.
     if ($ProfilePage = DataObject::get_one('EditProfilePage')) {
         $name = $data['FirstName'] ?: ($name = $data['Email']);
         $this->setFlash(_t('RegistrationPage.RegisteredSuccessText', 'Welcome ' . $name . ', your account has been created!'), 'success');
         return $this->redirect($ProfilePage->Link());
     } else {
         $this->setFlash(_t('RegistrationPage.RegisteredWarningText', 'Please add a "Edit Profile Page" in your SiteTree to enable profile editing'), 'warning');
         return $this->redirect(Director::absoluteBaseURL());
     }
 }
 public static function service()
 {
     $service = new RestfulService(Director::absoluteBaseURL() . 'api/v1', 0);
     $service->httpHeader('Accept: application/json');
     $service->httpHeader('Content-Type: application/json');
     return $service;
 }
 public function updateCMSFields(FieldList $fields)
 {
     $fields->removeFieldFromTab("Root.Main", "MenuTitle");
     $fields->addFieldToTab('Root.Main', new LiteralField("manage", "<a style='margin-bottom:15px' class='backlink ss-ui-button cms-panel-link ui-button ui-widget ui-state-default ui-corner-all ui-button-text-icon-primary ui-state-hover ui-state-active' data-icon='back' href='" . Director::absoluteBaseURL() . "admin/pages/edit/show/" . $this->owner->Parent()->ID . "' role='button' aria-disabled='false'><span class='ui-button-icon-primary ui-icon btn-icon-back'></span><span style='padding-left:5px' >\n\t\t\tManage Posts\n\t\t</span></a>"), 'Title');
     $image = $fields->dataFieldByName("FeaturedImage");
     if ($image) {
         $image->setFolderName('Managed/BlogPosts/Featured');
         $image->setCanPreviewFolder(false);
     }
     // Get config options for using tags / categories
     $use_categories = Config::inst()->get("Blog", 'use_categories');
     $use_tags = Config::inst()->get("Blog", 'use_tags');
     $use_featured_image = Config::inst()->get("Blog", 'use_featured_image');
     // Adds message below tags/categories fields if none exist telling user where to create them
     if (!$this->owner->Parent()->Categories()->count() && $use_categories) {
         $cats = $fields->dataFieldByName("Categories");
         $cats->setRightTitle("You must first add categories via the <strong>Blog Options</strong> tab on the <a href='admin/pages/edit/show/" . $this->owner->Parent()->ID . "'>main Blog page</a>.");
     }
     if (!$this->owner->Parent()->Tags()->count() && $use_tags) {
         $cats = $fields->dataFieldByName("Tags");
         $cats->setRightTitle("You must first add tags via the <strong>Blog Options</strong> tab on the <a href='admin/pages/edit/show/" . $this->owner->Parent()->ID . "'>main Blog page</a>.");
     }
     // Hide tags/categories fields if turned off in config
     if (!$use_categories) {
         $fields->removeByName("Categories");
     }
     if (!$use_tags) {
         $fields->removeByName("Tags");
     }
     if (!$use_featured_image && !$this->owner->FeaturedImage()->exists()) {
         $fields->removeFieldFromTab("Root.Main", "FeaturedImage");
     }
     // Need to add proper support for this, removing for now, needs to play nicely with my "Disply Full Posts" option:
     $fields->removeFieldFromTab("Root.Main", "CustomSummary");
 }
 public function init()
 {
     parent::init();
     $renderer = new DebugView();
     $renderer->writeHeader();
     $renderer->writeInfo("SilverStripe Development Tools: Logs", Director::absoluteBaseURL());
 }
 /**
  * @param null $id Not used.
  * @param null $fields Not used.
  *
  * @return Form
  */
 public function getEditForm($id = null, $fields = null)
 {
     $siteConfig = SiteConfig::current_site_config();
     $fields = $siteConfig->getCMSFields();
     // Tell the CMS what URL the preview should show
     $home = Director::absoluteBaseURL();
     $fields->push(new HiddenField('PreviewURL', 'Preview URL', $home));
     // Added in-line to the form, but plucked into different view by LeftAndMain.Preview.js upon load
     $fields->push($navField = new LiteralField('SilverStripeNavigator', $this->getSilverStripeNavigator()));
     $navField->setAllowHTML(true);
     $actions = $siteConfig->getCMSActions();
     $form = CMSForm::create($this, 'EditForm', $fields, $actions)->setHTMLID('Form_EditForm');
     $form->setResponseNegotiator($this->getResponseNegotiator());
     $form->addExtraClass('cms-content center cms-edit-form');
     // don't add data-pjax-fragment=CurrentForm, its added in the content template instead
     if ($form->Fields()->hasTabset()) {
         $form->Fields()->findOrMakeTab('Root')->setTemplate('CMSTabSet');
     }
     $form->setHTMLID('Form_EditForm');
     $form->loadDataFrom($siteConfig);
     $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);
     return $form;
 }
 public function getCMSFields()
 {
     $this->beforeUpdateCMSFields(function ($fields) {
         $fields->addFieldsToTab('Root.Main', array(Textfield::create('ContactName', 'Name'), TextField::create('Phone', 'Phone'), TextField::create('Mobile', 'Mobile'), TextField::create('Fax', 'Fax'), EmailField::create('Email', 'Email'), $website = TextField::create('Website', 'Website')));
         $website->setRightTitle('e.g ' . Director::absoluteBaseURL());
     });
     return parent::getCMSFields();
 }
 public function getRequestHeaders($site = null)
 {
     if (!$site) {
         $site = Director::absoluteBaseURL();
     }
     $host = parse_url($site, PHP_URL_HOST);
     return array('Accept' => 'application/json, text/javascript, */*; q=0.01', 'Accept-Encoding' => 'gzip,deflate,sdch', 'Accept-Language' => 'en-GB,fr;q=0.8,en-US;q=0.6,en;q=0.4', 'Cache-Control' => 'no-cache', 'Connection' => 'keep-alive', 'Host' => $host, 'Origin' => 'http://' . $host, 'Pragma' => 'no-cache', 'Referer' => 'http://' . $host . '/', 'User-Agent' => 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.63 Safari/537.36', 'X-Silverstripe-Apitoken' => 'secret key');
 }