This is shamlessley copy > pasted from CMS. Though have removed permissions stuff as this is more intrinsically linked to the CMS.
Author: Tom Rix
Inheritance: extends DataObject, implements PermissionProvider
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 update($title, $subtitle, $siteAuthor, $siteContactEmail,
	                       $friendlyURL, $UUID, $sitePath, $defaultLanguage,
	                       $databaseConnection, $databaseUser, $databasePassword)
	{
		$config = new SiteConfig;
		$config->title = $title;
		$config->subtitle = $subtitle;
		$config->siteAuthor = $siteAuthor;
		$config->siteContactEmail = $siteContactEmail;
		$config->friendlyURL = $friendlyURL;
		$config->UUID = $UUID;
		$config->sitePath = $sitePath;
		$config->databaseConnection = $databaseConnection;
		$config->databaseUser = $databaseUser;
		$config->defaultLanguage = $defaultLanguage;
		
		try
		{
			$config->save();
			
			$this->notice(t('Saved site configuration'));
			$this->redirect('admin/system');
		}
		catch (ValidationException $e)
		{
			$this->config = $config;
			$this->languages = $this->getLanguages();
			$this->error(t('Failed saving configuration'));
			$this->render('config');
		}
	}
 protected function upgradeConfig(SiteConfig $config)
 {
     $this->log("Upgrading site config ID = " . $config->ID);
     if ($config->GoogleAnalyticsUseUniversalAnalytics) {
         $config->GoogleAnalyticsType = 'Universal Analytics';
     } else {
         $config->GoogleAnalyticsType = 'Old Asynchronous Analytics';
     }
     $config->GoogleAnalyticsUpgradedV2 = true;
     $config->write();
 }
 /**
  * @param SiteConfig $config
  * @param SiteTree $owner
  * @param string $metadata
  *
  * @return void
  *
  */
 public function updateMetadata(SiteConfig $config, SiteTree $owner, &$metadata)
 {
     // Facebook App ID
     if ($config->FacebookAppID) {
         $metadata .= $owner->MarkupComment('Facebook Insights');
         $metadata .= $owner->MarkupFacebook('fb:app_id', $config->FacebookAppID, false);
         // Admins (if App ID)
         foreach ($config->FacebookAdmins() as $admin) {
             if ($admin->FacebookProfileID) {
                 $metadata .= $owner->MarkupFacebook('fb:admins', $admin->FacebookProfileID, false);
             }
         }
     }
 }
 public function alternateSiteConfig()
 {
     if (!$this->owner->SubsiteID) {
         return false;
     }
     $sc = DataObject::get_one('SiteConfig', '"SubsiteID" = ' . $this->owner->SubsiteID);
     if (!$sc) {
         $sc = new SiteConfig();
         $sc->SubsiteID = $this->owner->SubsiteID;
         $sc->Title = _t('Subsite.SiteConfigTitle', 'Your Site Name');
         $sc->Tagline = _t('Subsite.SiteConfigSubtitle', 'Your tagline here');
         $sc->write();
     }
     return $sc;
 }
 public function getCMSFields()
 {
     $conf = SiteConfig::current_site_config();
     $themes = $conf->getAvailableThemes();
     $theme = new DropdownField('Theme', _t('Multisites.THEME', 'Theme'), $themes);
     $theme->setEmptyString(_t('Multisites.DEFAULTTHEME', '(Default theme)'));
     $fields = new FieldList(new TabSet('Root', new Tab('Main', new HeaderField('SiteConfHeader', _t('Multisites.SITECONF', 'Site Configuration')), new TextField('Title', _t('Multisites.TITLE', 'Title')), new TextField('Tagline', _t('Multisites.TAGLINE', 'Tagline/Slogan')), $theme, new HeaderField('SiteURLHeader', _t('Multisites.SITEURL', 'Site URL')), new OptionsetField('Scheme', _t('Multisites.SCHEME', 'Scheme'), array('any' => _t('Multisites.ANY', 'Any'), 'http' => _t('Multisites.HTTP', 'HTTP'), 'https' => _t('Multisites.HTTPS', 'HTTPS (HTTP Secure)'))), new TextField('Host', _t('Multisites.HOST', 'Host')), new MultiValueTextField('HostAliases', _t('Multisites.HOSTALIASES', 'Host Aliases')), new CheckboxField('IsDefault', _t('Multisites.ISDEFAULT', 'Is this the default site?')), new HeaderField('SiteAdvancedHeader', _t('Multisites.SiteAdvancedHeader', 'Advanced Settings')), TextareaField::create('RobotsTxt', _t('Multisites.ROBOTSTXT', 'Robots.txt'))->setDescription(_t('Multisites.ROBOTSTXTUSAGE', '<p>Please consult <a href="http://www.robotstxt.org/robotstxt.html" target="_blank">http://www.robotstxt.org/robotstxt.html</a> for usage of the robots.txt file.</p>')))));
     $devIDs = Config::inst()->get('Multisites', 'developer_identifiers');
     if (is_array($devIDs)) {
         if (!ArrayLib::is_associative($devIDs)) {
             $devIDs = ArrayLib::valuekey($devIDs);
         }
         $fields->addFieldToTab('Root.Main', DropdownField::create('DevID', _t('Multisites.DeveloperIdentifier', 'Developer Identifier'), $devIDs));
     }
     if (Multisites::inst()->assetsSubfolderPerSite()) {
         $fields->addFieldToTab('Root.Main', new TreeDropdownField('FolderID', _t('Multisites.ASSETSFOLDER', 'Assets Folder'), 'Folder'), 'SiteURLHeader');
     }
     if (!Permission::check('SITE_EDIT_CONFIGURATION')) {
         foreach ($fields->dataFields() as $field) {
             $fields->makeFieldReadonly($field);
         }
     }
     $this->extend('updateSiteCMSFields', $fields);
     return $fields;
 }
 function updateEditForm(&$form)
 {
     if ($form->getName() == 'RootForm' && SiteConfig::has_extension("Translatable")) {
         $siteConfig = SiteConfig::current_site_config();
         $form->Fields()->push(new HiddenField('Locale', '', $siteConfig->Locale));
     }
 }
 /**
  * @name OpenGraphMetadata
  */
 public function OpenGraphMetadata()
 {
     $self = $this->owner;
     if ($self->OpenGraphType != 'off') {
         // variables
         $config = SiteConfig::current_site_config();
         $metadata = $self->MarkupHeader('Open Graph');
         //// Type
         $metadata .= $self->MarkupFacebook('og:type', $self->OpenGraphType, false);
         //// Site Name
         $metadata .= $self->MarkupFacebook('og:site_name', $config->Title, true, $config->Charset);
         //// URL
         $metadata .= $self->MarkupFacebook('og:url', $self->AbsoluteLink(), false);
         //// Title
         $title = $self->OpenGraphTitle ? $self->OpenGraphTitle : $self->Title;
         $metadata .= $self->MarkupFacebook('og:title', $title, true, $config->Charset);
         //// Description
         $description = $self->OpenGraphDescription ? $self->OpenGraphDescription : $self->GenerateDescription();
         $metadata .= $self->MarkupFacebook('og:description', $description, true, $config->Charset);
         //// Image
         if ($self->OpenGraphImage()->exists()) {
             $metadata .= $self->MarkupFacebook('og:image', $self->OpenGraphImage()->getAbsoluteURL(), false);
         }
         //// og:locale
         //// article:author
         // in Core
         //// article:publisher
         // in Core
         // return
         return $metadata;
     } else {
         return false;
     }
 }
 public function updateSettingsFields(FieldList $fields)
 {
     $systemThemes = SiteConfig::current_site_config()->getAvailableThemes();
     $partials = $themes = array('' => '', 'none' => '(none)');
     foreach ($systemThemes as $key => $themeName) {
         if (file_exists(Director::baseFolder() . '/themes/' . $themeName . '/templates/Page.ss')) {
             $themes[$key] = $themeName;
         } else {
             $partials[$key] = $themeName;
         }
     }
     $themeDropdownField = new DropdownField("AppliedTheme", 'Applied Theme', $themes);
     $fields->addFieldToTab('Root.Theme', $themeDropdownField);
     $current = $this->appliedTheme();
     if ($current) {
         $themeDropdownField->setRightTitle('Current effective theme: ' . $current);
     } else {
         $themeDropdownField->setRightTitle('Using default site theme');
     }
     $themeDropdownField = new DropdownField("PartialTheme", 'Partial Theme', $partials);
     $fields->addFieldToTab('Root.Theme', $themeDropdownField);
     $current = $this->appliedPartialTheme();
     if ($current) {
         $themeDropdownField->setRightTitle('Current effective partial theme: ' . $current);
     } else {
         $themeDropdownField->setRightTitle('Please only use a specific applied theme OR a partial theme, not both!');
     }
 }
 /**
  * @param	SS_HTTPRequest $request
  */
 public function run($request)
 {
     // Only allow execution from the command line (for simplicity).
     if (!Director::is_cli()) {
         echo "<p>Sorry, but this can only be run from the command line.</p>";
         return;
     }
     try {
         // Get and validate desired maintenance mode setting.
         $get = $request->getVars();
         if (empty($get["args"])) {
             throw new Exception("Please provide an argument (e.g. 'on' or 'off').", 1);
         }
         $arg = strtolower(current($get["args"]));
         if ($arg != "on" && $arg != "off") {
             throw new Exception("Invalid argument: '{$arg}' (expected 'on' or 'off')", 2);
         }
         // Get and write site configuration now.
         $config = SiteConfig::current_site_config();
         $previous = !empty($config->MaintenanceMode) ? "on" : "off";
         $config->MaintenanceMode = $arg == "on";
         $config->write();
         // Output status and exit.
         if ($arg != $previous) {
             $this->output("Maintenance mode is now '{$arg}'.");
         } else {
             $this->output("NOTE: Maintenance mode was already '{$arg}' (nothing has changed).");
         }
     } catch (Exception $e) {
         $this->output("ERROR: " . $e->getMessage());
         if ($e->getCode() <= 2) {
             $this->output("Usage:  sake dev/tasks/MaintenanceMode [on|off]");
         }
     }
 }
 /**
  * Completes the job by zipping up the generated export and creating an
  * export record for it.
  */
 protected function complete()
 {
     $siteTitle = SiteConfig::current_site_config()->Title;
     $filename = preg_replace('/[^a-zA-Z0-9-.+]/', '-', sprintf('%s-%s.zip', $siteTitle, date('c')));
     $dir = Folder::findOrMake(SiteExportExtension::EXPORTS_DIR);
     $dirname = ASSETS_PATH . '/' . SiteExportExtension::EXPORTS_DIR;
     $pathname = "{$dirname}/{$filename}";
     SiteExportUtils::zip_directory($this->tempDir, "{$dirname}/{$filename}");
     Filesystem::removeFolder($this->tempDir);
     $file = new File();
     $file->ParentID = $dir->ID;
     $file->Title = $siteTitle . ' ' . date('c');
     $file->Filename = $dir->Filename . $filename;
     $file->write();
     $export = new SiteExport();
     $export->ParentClass = $this->rootClass;
     $export->ParentID = $this->rootId;
     $export->Theme = $this->theme;
     $export->BaseUrlType = ucfirst($this->baseUrlType);
     $export->BaseUrl = $this->baseUrl;
     $export->ArchiveID = $file->ID;
     $export->write();
     if ($this->email) {
         $email = new Email();
         $email->setTo($this->email);
         $email->setTemplate('SiteExportCompleteEmail');
         $email->setSubject(sprintf('Site Export For "%s" Complete', $siteTitle));
         $email->populateTemplate(array('SiteTitle' => $siteTitle, 'Link' => $file->getAbsoluteURL()));
         $email->send();
     }
 }
 public function updateCMSFields(FieldList $fields)
 {
     // vars
     $config = SiteConfig::current_site_config();
     $owner = $this->owner;
     // decode data into array
     $data = json_decode($owner->OpenGraphData, true);
     // @todo Add repair method if data is missing / corrupt ~ for fringe cases
     // tab
     $tab = new Tab('OpenGraph');
     // add disabled/error state if `off`
     if ($data['og:type'] === 'off') {
         $tab->addExtraClass('error');
     }
     // add the tab
     $fields->addFieldToTab('Root.Metadata', $tab, 'FullOutput');
     // new identity
     $tab = 'Root.Metadata.OpenGraph';
     // add description
     // type always visible
     $fields->addFieldsToTab($tab, array(LabelField::create('OpenGraphHeader', '@todo Information</a>')->addExtraClass('information'), DropdownField::create('OpenGraphType', '<a href="http://ogp.me/#types">og:type</a>', self::$types, $data['og:type'])));
     if ($data['og:type'] !== 'off') {
         $fields->addFieldsToTab($tab, array(ReadonlyField::create('OpenGraphURL', 'Canonical URL', $owner->AbsoluteLink()), TextField::create('OpenGraphSiteName', 'Site Name', $data['og:site_name'])->setAttribute('placeholder', $config->Title), TextField::create('OpenGraphTitle', 'Page Title', $data['og:title'])->setAttribute('placeholder', $owner->Title), TextareaField::create('OpenGraphDescription', 'Description', $data['og:description'])->setAttribute('placeholder', $owner->GenerateDescription()), UploadField::create('OpenGraphImage', 'Image<pre>type: png/jpg/gif</pre><pre>size: variable *</pre>', $owner->OpenGraphImage)->setAllowedExtensions(array('png', 'jpg', 'jpeg', 'gif'))->setFolderName(self::$SEOOpenGraphUpload . $owner->Title)->setDescription('* <a href="https://developers.facebook.com/docs/sharing/best-practices#images" target="_blank">Facebook image best practices</a>, or use any preferred Open Graph guide.')));
     }
 }
 public function processComment()
 {
     if ($comment = $this->getComment()) {
         $config = SiteConfig::current_site_config();
         if (isset($_GET['token'])) {
             $realtoken = md5($config->SiteTitle . $comment->ID);
             if ($_GET['token'] == $realtoken) {
                 if (isset($_GET['delete'])) {
                     echo "Comment Deleted.";
                     $parent = $comment->getParent();
                     $comment->delete();
                     $this->redirect($parent->Link());
                 } else {
                     $comment->Moderated = true;
                     $comment->write();
                     echo "Comment Approved.";
                     $this->redirect($comment->Link());
                 }
             } else {
                 die("Oh dear: Error 1A");
             }
         } else {
             die("Oh dear: Error 1B");
         }
     } else {
         die("Comment not found. Already deleted?");
     }
 }
 public function getConf()
 {
     if (!static::$conf_instance) {
         static::$conf_instance = SiteConfig::current_site_config();
     }
     return static::$conf_instance;
 }
 /**
  * Submit the form
  *
  * @param $data
  * @param $form
  * @return bool|SS_HTTPResponse
  */
 public function Subscribe($data, $form)
 {
     /** @var Form $form */
     $data = $form->getData();
     /** Set the form state */
     Session::set('FormInfo.Form_' . $this->name . '.data', $data);
     $siteConfig = SiteConfig::current_site_config();
     /** Check if the API key, and List ID have been set. */
     if ($siteConfig->MailChimpAPI && $siteConfig->MailChimpListID) {
         $mailChimp = new \Drewm\MailChimp($siteConfig->MailChimpAPI);
         $result = $mailChimp->call('lists/subscribe', array('id' => $siteConfig->MailChimpListID, 'email' => array('email' => $data['Email'])));
     } else {
         /** If not, redirect back and display a flash error. */
         $this->controller->setFlash('Missing API key, or List ID', 'danger');
         return $this->controller->redirectBack();
     }
     /**
      * If the status of the request returns an error,
      * display the error
      */
     if (isset($result['status'])) {
         if ($result['status'] == 'error') {
             $this->controller->setFlash($result['error'], 'danger');
             return $this->controller->redirectBack();
         }
     }
     /** Clear the form state */
     Session::clear('FormInfo.Form_' . $this->name . '.data');
     if ($siteConfig->MailChimpSuccessMessage) {
         $this->controller->setFlash($siteConfig->MailChimpSuccessMessage, 'success');
     } else {
         $this->controller->setFlash('Your subscription has been received, you will be sent a confirmation email shortly.', 'success');
     }
     return $this->controller->redirect($this->controller->data()->Link());
 }
 public function LatestTweetsList($limit = '5')
 {
     $conf = SiteConfig::current_site_config();
     if (empty($conf->TwitterName) || empty($conf->TwitterConsumerKey) || empty($conf->TwitterConsumerSecret) || empty($conf->TwitterAccessToken) || empty($conf->TwitterAccessTokenSecret)) {
         return new ArrayList();
     }
     $cache = SS_Cache::factory('LatestTweets_cache');
     if (!($results = unserialize($cache->load(__FUNCTION__)))) {
         $results = new ArrayList();
         require_once dirname(__FILE__) . '/tmhOAuth/tmhOAuth.php';
         require_once dirname(__FILE__) . '/tmhOAuth/tmhUtilities.php';
         $tmhOAuth = new tmhOAuth(array('consumer_key' => $conf->TwitterConsumerKey, 'consumer_secret' => $conf->TwitterConsumerSecret, 'user_token' => $conf->TwitterAccessToken, 'user_secret' => $conf->TwitterAccessTokenSecret, 'curl_ssl_verifypeer' => false));
         $code = $tmhOAuth->request('GET', $tmhOAuth->url('1.1/statuses/user_timeline'), array('screen_name' => $conf->TwitterName, 'count' => $limit));
         $tweets = $tmhOAuth->response['response'];
         $json = new JSONDataFormatter();
         if (($arr = $json->convertStringToArray($tweets)) && is_array($arr) && isset($arr[0]['text'])) {
             foreach ($arr as $tweet) {
                 try {
                     $here = new DateTime(SS_Datetime::now()->getValue());
                     $there = new DateTime($tweet['created_at']);
                     $there->setTimezone($here->getTimezone());
                     $date = $there->Format('Y-m-d H:i:s');
                 } catch (Exception $e) {
                     $date = 0;
                 }
                 $results->push(new ArrayData(array('Text' => nl2br(tmhUtilities::entify_with_options($tweet, array('target' => '_blank'))), 'Date' => SS_Datetime::create_field('SS_Datetime', $date))));
             }
         }
         $cache->save(serialize($results), __FUNCTION__);
     }
     return $results;
 }
 /**
  * @name TwitterCardsMetadata
  * outputs Twitter metadata
  */
 public function TwitterCardsMetadata()
 {
     $self = $this->owner;
     if ($self->TwitterCardsType != 'off') {
         // variables
         $config = SiteConfig::current_site_config();
         $metadata = $self->MarkupHeader('Twitter Cards');
         //// Type
         $metadata .= $self->MarkupTwitter('twitter:card', $self->TwitterCardsType, false);
         //// Site Name
         $metadata .= $self->MarkupTwitter('twitter:site', $config->Title, true, $config->Charset);
         //// URL
         $metadata .= $self->MarkupTwitter('twitter:url', $self->AbsoluteLink(), false);
         //// Title
         // default to SiteTree::$Title
         $title = $self->TwitterCardsTitle ? $self->TwitterCardsTitle : $self->Title;
         $metadata .= $self->MarkupTwitter('twitter:title', $title, true, $config->Charset);
         //// Description
         // default to SiteTree::$Description
         $description = $self->TwitterCardsDescription ? $self->TwitterCardsDescription : $self->GenerateDescription();
         $metadata .= $self->MarkupTwitter('twitter:description', $description, true, $config->Charset);
         //// Image
         if ($self->TwitterCardsImage()->exists()) {
             $metadata .= $self->MarkupTwitter('twitter:image', $self->TwitterCardsImage()->getAbsoluteURL(), false);
         }
         // return
         return $metadata;
     } else {
         return false;
     }
 }
 public function index()
 {
     $site = SiteConfig::current_site_config();
     $order = $this->order;
     // Setup the paypal gateway URL
     if (Director::isDev()) {
         $gateway_url = "https://www.sandbox.paypal.com/cgi-bin/webscr";
     } else {
         $gateway_url = "https://www.paypal.com/cgi-bin/webscr";
     }
     $callback_url = Controller::join_links(Director::absoluteBaseURL(), Payment_Controller::config()->url_segment, "callback", $this->payment_gateway->ID);
     $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');
     $back_url = Controller::join_links(Director::absoluteBaseURL(), Checkout_Controller::config()->url_segment, "finish");
     $fields = new FieldList(HiddenField::create('business', null, $this->payment_gateway->BusinessID), HiddenField::create('item_name', null, $site->Title), HiddenField::create('cmd', null, "_cart"), HiddenField::create('paymentaction', null, "sale"), HiddenField::create('invoice', null, $order->OrderNumber), HiddenField::create('custom', null, $order->OrderNumber), HiddenField::create('upload', null, 1), HiddenField::create('discount_amount_cart', null, $order->DiscountAmount), HiddenField::create('amount', null, $order->Total), HiddenField::create('currency_code', null, $site->Currency()->GatewayCode), HiddenField::create('first_name', null, $order->FirstName), HiddenField::create('last_name', null, $order->Surname), HiddenField::create('address1', null, $order->Address1), HiddenField::create('address2', null, $order->Address2), HiddenField::create('city', null, $order->City), HiddenField::create('zip', null, $order->PostCode), HiddenField::create('country', null, $order->Country), HiddenField::create('email', null, $order->Email), HiddenField::create('return', null, $success_url), HiddenField::create('notify_url', null, $callback_url), HiddenField::create('cancel_return', null, $error_url));
     $i = 1;
     foreach ($order->Items() as $item) {
         $fields->add(HiddenField::create('item_name_' . $i, null, $item->Title));
         $fields->add(HiddenField::create('amount_' . $i, null, number_format($item->Price + $item->Tax, 2)));
         $fields->add(HiddenField::create('quantity_' . $i, null, $item->Quantity));
         $i++;
     }
     // Add shipping as an extra product
     $fields->add(HiddenField::create('item_name_' . $i, null, _t("Commerce.Postage", "Postage")));
     $fields->add(HiddenField::create('amount_' . $i, null, number_format($order->PostageCost + $order->PostageTax, 2)));
     $fields->add(HiddenField::create('quantity_' . $i, null, "1"));
     $actions = FieldList::create(LiteralField::create('BackButton', '<a href="' . $back_url . '" class="btn btn-red commerce-action-back">' . _t('Commerce.Back', 'Back') . '</a>'), FormAction::create('Submit', _t('Commerce.ConfirmPay', 'Confirm and Pay'))->addExtraClass('btn')->addExtraClass('btn-green'));
     $form = Form::create($this, 'Form', $fields, $actions)->addExtraClass('forms')->setFormMethod('POST')->setFormAction($gateway_url);
     $this->extend('updateForm', $form);
     return array("Title" => _t('Commerce.CheckoutSummary', "Summary"), "MetaTitle" => _t('Commerce.CheckoutSummary', "Summary"), "Form" => $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;
 }
 /**
  * @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;
 }
Exemplo n.º 21
0
    public function init()
    {
        parent::init();
        // Concatenate CSS
        Requirements::combine_files('style.css', array('mysite/css/layout.css', 'mysite/css/userstyles.css'));
        // Concatenate JavaScript
        Requirements::combine_files('scripts.js', array('mysite/javascript/lib/top-nav.js', 'mysite/javascript/vanilla.js'));
        // Google Analytics
        $config = SiteConfig::current_site_config();
        $google = $config->GACode;
        $gaJS = <<<JS
            (function(i, s, o, g, r, a, m) {
                i['GoogleAnalyticsObject'] = r;
                i[r] = i[r] || function() {
                    (i[r].q = i[r].q || []).push(arguments)
                }, i[r].l = 1 * new Date();
                a = s.createElement(o), m = s.getElementsByTagName(o)[0];
                a.async = 1;
                a.src = g;
                m.parentNode.insertBefore(a, m)
            })(window, document, 'script', '//www.google-analytics.com/analytics.js', 'ga');
            ga('create', '{$google}', 'auto');
            ga('send', 'pageview');
JS;
        Requirements::customScript($gaJS);
    }
 public function testAddressBookWithReadonlyFieldForCountry()
 {
     $member = $this->objFromFixture("Member", "joebloggs");
     $this->logInAs($member);
     $this->controller->init();
     //reinit to connect up member
     // setup a single-country site
     $siteconfig = DataObject::get_one('SiteConfig');
     $siteconfig->AllowedCountries = "NZ";
     $siteconfig->write();
     $singlecountry = SiteConfig::current_site_config();
     $this->assertEquals("NZ", $singlecountry->getSingleCountry(), "Confirm that the website is setup as a single country site");
     // Open the Address Book page to test form submission with a readonly field
     $page = $this->get("account/addressbook/");
     // goto address book page
     $this->assertEquals(200, $page->getStatusCode(), "a page should load");
     $this->assertContains("Form_CreateAddressForm_Country_readonly", $page->getBody(), "The Country field is readonly");
     $this->assertNotContains("<option value=\"NZ\">New Zealand</option>", $page->getBody(), "Dropdown field is not shown");
     // Create an address
     $data = array("Address" => "234 Hereford Street", "City" => "Christchurch", "State" => "Canterbury", "PostalCode" => "8011");
     $this->submitForm("Form_CreateAddressForm", "action_saveaddress", $data);
     $this->assertEquals(200, $page->getStatusCode(), "a page should load");
     $nz_address = Address::get()->filter('PostalCode', '8011')->sort('ID')->last();
     $this->assertEquals("NZ", $nz_address->Country, "New address successfully saved; even with a Country readonly field in the form");
     $this->assertEquals("234 Hereford Street", $nz_address->Address, "Ensure that the Address is 234 Hereford Street");
 }
 public function Tweets()
 {
     $twitterApp = TwitterApp::get()->first();
     if (!$twitterApp) {
         return null;
     }
     $siteConfig = SiteConfig::current_site_config();
     $twitter = $twitterApp->getTwitter();
     $twitter->setAccess(new OAuthToken($twitterApp->TwitterAccessToken, $twitterApp->TwitterAccessSecret));
     if ($twitter->hasAccess()) {
         $result = $twitter->api("1.1/statuses/user_timeline.json", "GET", array("screen_name" => $this->TwitterHandle, "count" => $this->NumberOfTweets));
         if ($result->statusCode() == 200) {
             $rawTweets = json_decode($result->body(), true);
             if (count($rawTweets) > 0) {
                 $tweets = new ArrayList();
                 foreach ($rawTweets as $tweet) {
                     // Parse tweet links, users and hashtags.
                     $parsed = preg_replace("#(^|[\n ])([\\w]+?://[\\w]+[^ \"\n\r\t<]*)#ise", "'\\1<a href=\"\\2\" target=\"_blank\">\\2</a>'", $tweet['text']);
                     $parsed = preg_replace("#(^|[\n ])@([A-Za-z0-9\\_]*)#ise", "'\\1<a href=\"http://www.twitter.com/\\2\" target=\"_blank\">@\\2</a>'", $parsed);
                     $parsed = preg_replace("#(^|[\n ])\\#([A-Za-z0-9]*)#ise", "'\\1<a href=\"http://www.twitter.com/search?q=\\2\" target=\"_blank\">#\\2</a>'", $parsed);
                     $t = new ArrayData(array());
                     $t->Tweet = DBField::create_field("HTMLText", $parsed, "Tweet");
                     $t->TweetDate = DBField::create_field("SS_Datetime", strtotime($tweet['created_at']));
                     $t->TweetLink = DBField::create_field("Varchar", "http://www.twitter.com/" . rawurlencode($tweet['user']['screen_name']) . "/status/" . rawurlencode($tweet['id_str']));
                     $tweets->push($t);
                 }
                 return $tweets;
             }
         }
     }
     return null;
 }
 function testEachSubsiteHasAUniqueSiteConfig()
 {
     $subsite1 = $this->objFromFixture('Subsite', 'domaintest1');
     $subsite2 = $this->objFromFixture('Subsite', 'domaintest2');
     $this->assertTrue(is_array(singleton('SiteConfigSubsites')->extraStatics()));
     Subsite::changeSubsite(0);
     $sc = SiteConfig::current_site_config();
     $sc->Title = 'RootSite';
     $sc->write();
     Subsite::changeSubsite($subsite1->ID);
     $sc = SiteConfig::current_site_config();
     $sc->Title = 'Subsite1';
     $sc->write();
     Subsite::changeSubsite($subsite2->ID);
     $sc = SiteConfig::current_site_config();
     $sc->Title = 'Subsite2';
     $sc->write();
     Subsite::changeSubsite(0);
     $this->assertEquals(SiteConfig::current_site_config()->Title, 'RootSite');
     Subsite::changeSubsite($subsite1->ID);
     $this->assertEquals(SiteConfig::current_site_config()->Title, 'Subsite1');
     Subsite::changeSubsite($subsite2->ID);
     $this->assertEquals(SiteConfig::current_site_config()->Title, 'Subsite2');
     $keys = SiteConfig::current_site_config()->extend('cacheKeyComponent');
     $this->assertContains('subsite-' . $subsite2->ID, $keys);
 }
    public function fix_fluent_menu()
    {
        if (!class_exists('Fluent')) {
            return;
        }
        $conf = SiteConfig::current_site_config();
        $localesNames = Fluent::locale_names();
        if ($conf->hasExtension('ActiveLocalesExtension') && $conf->ActiveLocales) {
            $localesNames = $conf->ActiveLocalesNames();
        }
        $locales = json_encode($localesNames);
        $locale = json_encode(Fluent::current_locale());
        // If we have only one locale, set this one as default
        if (count($localesNames) === 1) {
            $locale = json_encode(key($localesNames));
        }
        $param = json_encode(Fluent::config()->query_param);
        $buttonTitle = json_encode(_t('Fluent.ChangeLocale', 'Change Locale'));
        Requirements::block('FluentHeadScript');
        Requirements::insertHeadTags(<<<EOT
<script type="text/javascript">
//<![CDATA[
\tvar fluentLocales = {$locales};
\tvar fluentLocale = {$locale};
\tvar fluentParam = {$param};
\tvar fluentButtonTitle = {$buttonTitle};
//]]>
</script>
EOT
, 'FluentHeadScriptSubsite');
    }
 /**
  * Create the new receipt 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 = SiteConfig::current_site_config();
     if ($customer->Email) {
         $this->to = $customer->Email;
     }
     if ($siteConfig->ReceiptSubject) {
         $this->subject = $siteConfig->ReceiptSubject . ' - Order #' . $order->ID;
     }
     if ($siteConfig->ReceiptBody) {
         $this->body = $siteConfig->ReceiptBody;
     }
     if ($siteConfig->ReceiptFrom) {
         $this->from = $siteConfig->ReceiptFrom;
     } elseif (Email::getAdminEmail()) {
         $this->from = Email::getAdminEmail();
     } else {
         $this->from = 'no-reply@' . $_SERVER['HTTP_HOST'];
     }
     if ($siteConfig->EmailSignature) {
         $this->signature = $siteConfig->EmailSignature;
     }
     //Get css for Email by reading css file and put css inline for emogrification
     $this->setTemplate('Order_ReceiptEmail');
     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));
     parent::__construct($from, null, $subject, $body, $bounceHandlerURL, $cc, $bcc);
 }
Exemplo n.º 27
0
 public function updateCMSFields(FieldList $fields)
 {
     $fields->removeByName('Country');
     $fields->removeByName("DefaultShippingAddressID");
     $fields->removeByName("DefaultBillingAddressID");
     $fields->addFieldToTab('Root.Main', DropdownField::create('Country', _t('Address.db_Country', 'Country'), SiteConfig::current_site_config()->getCountriesList()));
 }
 public function process()
 {
     $config = SiteConfig::current_site_config();
     $datetime = $this->getDatetime();
     $emails = $this->emails;
     if (!count($emails)) {
         $this->isComplete = true;
         return;
     }
     $email = new Email();
     $email->setSubject(sprintf(_t('EventManagement.EVENTREMINDERSUBJECT', 'Event Reminder For %s (%s)'), $datetime->EventTitle(), $config->Title));
     $email->setTemplate('EventReminderEmail');
     $email->populateTemplate(array('SiteConfig' => $config, 'Datetime' => $datetime));
     foreach ($emails as $addr => $name) {
         $_email = clone $email;
         $_email->setTo($addr);
         $_email->populateTemplate(array('Name' => $name));
         $_email->send();
         unset($emails[$addr]);
         $this->emails = $emails;
         ++$this->currentStep;
     }
     if (!count($emails)) {
         $this->isComplete = true;
     }
 }
Exemplo n.º 29
0
 public function run($request)
 {
     // update block/set titles
     // Name field has been reverted back to Title
     // DB::query("update Block set Name = Title");
     // DB::query("update BlockSet set Name = Title");
     // update block areas
     DB::query("\n\t\t\tupdate SiteTree_Blocks\n\t\t\tleft join Block on SiteTree_Blocks.BlockID = Block.ID\n\t\t\tset BlockArea = Block.Area\n\t\t\twhere BlockID = Block.ID\n\t\t");
     // update block sort
     DB::query("\n\t\t\tupdate SiteTree_Blocks\n\t\t\tleft join Block on SiteTree_Blocks.BlockID = Block.ID\n\t\t\tset Sort = Block.Weight\n\t\t\twhere BlockID = Block.ID\n\t\t");
     echo "BlockAreas, Sort updated<br />";
     // migrate global blocks
     $sc = SiteConfig::current_site_config();
     if ($sc->Blocks()->Count()) {
         $set = BlockSet::get()->filter('Title', 'Global')->first();
         if (!$set) {
             $set = BlockSet::create(array('Title' => 'Global'));
             $set->write();
         }
         foreach ($sc->Blocks() as $block) {
             if (!$set->Blocks()->find('ID', $block->ID)) {
                 $set->Blocks()->add($block, array('Sort' => $block->Weight, 'BlockArea' => $block->Area));
                 echo "Block #{$block->ID} added to Global block set<br />";
             }
         }
     }
     // publish blocks
     $blocks = Block::get()->filter('Published', 1);
     foreach ($blocks as $block) {
         $block->publish('Stage', 'Live');
         echo "Published Block #{$block->ID}<br />";
     }
 }
Exemplo n.º 30
0
 /**
  * @param int $amount
  * @return array
  */
 function getGoogleFonts($amount = 30)
 {
     $fontFile = Director::baseFolder() . '/boilerplate/fonts/google-web-fonts.txt';
     //Total time the file will be cached in seconds, set to a week
     $cacheTime = 86400 * 7;
     if (file_exists($fontFile) && $cacheTime < filemtime($fontFile)) {
         $content = json_decode(file_get_contents($fontFile));
     } else {
         $url = 'https://www.googleapis.com/webfonts/v1/webfonts?key=' . SiteConfig::current_site_config()->FontAPI;
         $ch = curl_init();
         curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
         curl_setopt($ch, CURLOPT_HEADER, false);
         curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
         curl_setopt($ch, CURLOPT_URL, $url);
         curl_setopt($ch, CURLOPT_REFERER, $url);
         curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
         $fontContent = curl_exec($ch);
         curl_close($ch);
         $fp = fopen($fontFile, 'w');
         fwrite($fp, $fontContent);
         fclose($fp);
         $content = json_decode($fontContent);
     }
     if ($amount == 'all') {
         return $content->items;
     } else {
         return array_slice($content->items, 0, $amount);
     }
 }