/**
  * Method that turns this object into a field type, to be loaded into a form
  *
  * @return FormField
  */
 public function Field()
 {
     if ($this->Title && $this->DisplayAs) {
         $name = "customise_{$this->ID}_" . Convert::raw2url($this->Title);
         $title = $this->Required ? $this->Title . ' *' : $this->Title;
         $options = $this->Options()->map('Title', 'ItemSummary');
         $defaults = $this->DefaultOptions();
         $default = $defaults->exists() ? $defaults->first()->Title : null;
         switch ($this->DisplayAs) {
             case 'Dropdown':
                 $field = DropdownField::create($name, $title, $options, $default)->setEmptyString(_t('Commerce.PleaseSelect', 'Please Select'))->setAttribute("class", "dropdown btn");
                 break;
             case 'Radio':
                 $field = OptionSetField::create($name, $title, $options, $default);
                 break;
             case 'Checkboxes':
                 $field = CheckboxSetField::create($name, $title, $options, $defaults->column('ID'));
                 break;
             case 'TextEntry':
                 $field = TextField::create($name, $title);
                 if ($this->MaxLength) {
                     $field->setMaxLength($this->MaxLength);
                 }
                 break;
         }
         $this->extend('updateField', $field);
         return $field;
     } else {
         return false;
     }
 }
 public function processRecord($record, $columnMap, &$results, $preview = false)
 {
     $objID = parent::processRecord($record, $columnMap, $results, $preview);
     $_cache_groupByCode = array();
     // Add to predefined groups
     $member = DataObject::get_by_id($this->objectClass, $objID);
     foreach ($this->groups as $group) {
         // TODO This isnt the most memory effective way to add members to a group
         $member->Groups()->add($group);
     }
     // Add to groups defined in CSV
     if (isset($record['Groups']) && $record['Groups']) {
         $groupCodes = explode(',', $record['Groups']);
         foreach ($groupCodes as $groupCode) {
             $groupCode = Convert::raw2url($groupCode);
             if (!isset($_cache_groupByCode[$groupCode])) {
                 $group = Group::get()->filter('Code', $groupCode)->first();
                 if (!$group) {
                     $group = new Group();
                     $group->Code = $groupCode;
                     $group->Title = $groupCode;
                     $group->write();
                 }
                 $member->Groups()->add($group);
                 $_cache_groupByCode[$groupCode] = $group;
             }
         }
     }
     $member->destroy();
     unset($member);
     return $objID;
 }
 public function onBeforeWrite()
 {
     parent::onBeforeWrite();
     // If subsites enabled
     if (class_exists('Subsite') && ($subsite = Subsite::currentSubsite())) {
         $this->SubsiteID = $subsite->ID;
     }
     // Ensure the slug is URL safe
     $this->Slug = $this->Slug ? Convert::raw2url($this->Slug) : Convert::raw2url($this->Title);
 }
 public function onBeforeWrite()
 {
     parent::onBeforeWrite();
     $this->CallBackSlug = !$this->CallBackSlug ? 'sagepay' : Convert::raw2url($this->CallBackSlug);
     if (!$this->Summary) {
         $this->Summary = "Pay with credit/debit card securely via SagePay";
     }
     if (!$this->GatewayMessage) {
         $this->GatewayMessage = "Thank you for your order from: " . SiteConfig::current_site_config()->Title;
     }
 }
 public function onBeforeWrite()
 {
     parent::onBeforeWrite();
     // Set our URL segment
     if (!$this->URLSegment) {
         $url = Convert::raw2url($this->Title);
         $url = str_replace(":", "", $url);
         $url = str_replace(";", "", $url);
         $this->URLSegment = $url;
     }
 }
 public function onBeforeWrite()
 {
     if ($this->owner->ProductGroupID) {
         $group = $this->owner->ProductGroup();
         // Set the URL for this product to include the parent URL
         $this->owner->URLSegment = $group->URLSegment . "-" . Convert::raw2url($this->owner->Title);
         // Set the base price
         if (!$this->owner->BasePrice) {
             $this->owner->BasePrice = $group->BasePrice;
         }
     }
 }
 /**
  * Returns the tags added to this discussion
  */
 public function TagsCollection()
 {
     $output = new ArrayList();
     if ($this->Tags) {
         $tags = preg_split(" *, *", trim($this->Tags));
         $link = $this->Parent() ? $this->Parent()->Link('tag') : '';
         foreach ($tags as $tag) {
             $output->push(new ArrayData(array('Tag' => Convert::raw2xml($tag), 'Link' => Controller::join_links($link, Convert::raw2url($tag)), 'URLTag' => Convert::raw2url($tag))));
         }
     }
     return $output;
 }
 public function getTagsCollection()
 {
     $allTags = new ArrayList();
     $max = 0;
     $member = Member::currentUser();
     // Find if we need to filter tags by current discussion page
     $controller = Controller::curr();
     if (method_exists($controller, "data")) {
         $page = $controller->data();
     } else {
         $page = null;
     }
     if ($page != null && $page instanceof DiscussionPage) {
         $discussions = $page->Discussions();
     } else {
         $discussions = Discussion::get();
     }
     if ($discussions) {
         foreach ($discussions as $discussion) {
             if ($discussion->canView($member)) {
                 $theseTags = preg_split(" *, *", trim($discussion->Tags));
                 foreach ($theseTags as $tag) {
                     if ($tag) {
                         if ($allTags->find("Tag", $tag)) {
                             $allTags->find("Tag", $tag)->Count++;
                         } else {
                             $allTags->push(new ArrayData(array("Tag" => $tag, "Count" => 1, "Link" => Controller::join_links($discussion->Parent()->Link("tag"), Convert::raw2url($tag)))));
                         }
                         $tag_count = $allTags->find("Tag", $tag)->Count;
                         $max = $tag_count > $max ? $tag_count : $max;
                     }
                 }
             }
         }
         if ($allTags->exists()) {
             // First sort our tags
             $allTags->sort($this->SortParam, $this->SortOrder);
             // Now if a limit has been set, limit the list
             if ($this->Limit) {
                 $allTags = $allTags->limit($this->Limit);
             }
         }
         return $allTags;
     }
     return;
 }
 public function searchTweets($query, $count)
 {
     // Init caching
     $cacheKey = "searchTweets_" . str_replace("-", "_", Convert::raw2url($query)) . "_{$count}";
     $cache = SS_Cache::factory('CachedTwitterService');
     // Return cached value, if available
     if ($rawResult = $cache->load($cacheKey)) {
         return unserialize($rawResult);
     }
     // Save and return
     $result = $this->cachedService->searchTweets($query, $count);
     $cache->save(serialize($result), $cacheKey, array(), Config::inst()->get('CachedTwitterService', 'lifetime'));
     // Refresh the 'TimeAgo' field, as the cached value would now be outdated, or the locale could have changed.
     if ($result) {
         foreach ($result as $index => $item) {
             $result[$index]['TimeAgo'] = TwitterService::determine_time_ago($item['Date']);
         }
     }
     return $result;
 }
 function bulkimport($data, $form)
 {
     $fh = fopen($data['SourceFile']['tmp_name'], 'r');
     Versioned::reading_stage('Stage');
     if (isset($data['DeleteExisting']) && $data['DeleteExisting']) {
         foreach (Page::get() as $page) {
             $page->deleteFromStage('Stage');
             $page->deleteFromStage('Live');
         }
     }
     $parentRefs = array();
     while ($line = fgets($fh, 10000)) {
         // Skip comments
         if (preg_match('/^#/', $line)) {
             continue;
         }
         // Split up indentation, title and optional JSON
         if (preg_match("/^(\t*)([^{]*)({.*})?/", $line, $matches)) {
             $numTabs = strlen($matches[1]);
             $title = trim($matches[2]);
             $json = isset($matches[3]) && trim($matches[3]) ? json_decode(trim($matches[3]), true) : array();
             // Either extract the URL from provided meta data, or generate it
             $url = array_key_exists('URLSegment', $json) ? $json['URLSegment'] : $title;
             $url = Convert::raw2url($url);
             // Allow custom classes based on meta data
             $className = array_key_exists('ClassName', $json) ? $json['ClassName'] : 'Page';
             // If we've got too many tabs, then outdent until we find a page to attach to.
             while (!isset($parentRefs[$numTabs - 1]) && $numTabs > 0) {
                 $numTabs--;
             }
             $parentID = $numTabs > 0 ? $parentRefs[$numTabs - 1] : 0;
             // Try to find an existing page, or create a new one
             $page = Page::get()->filter(array('URLSegment' => $url, 'ParentID' => $parentID))->First();
             if (!$page) {
                 $page = new $className();
             }
             // Apply any meta data properties to the page
             $page->ParentID = $parentID;
             $page->Title = $title;
             $page->URLSegment = $url;
             if ($json) {
                 $page->update($json);
             }
             $page->write();
             // Optionall publish
             if (isset($data['PublishAll']) && $data['PublishAll']) {
                 $page->publish('Stage', 'Live');
             }
             if (!SapphireTest::is_running_test()) {
                 echo "<li>Written ID# {$page->ID}: {$page->Title}";
                 if ($page->ParentID) {
                     echo " (ParentID# {$page->ParentID})";
                 }
                 echo "</li>";
             }
             // Populate parentRefs with the most recent page at every level.   Necessary to build tree
             // Children of home should be placed at the top level
             if (strtolower($title) == 'home') {
                 $parentRefs[$numTabs] = 0;
             } else {
                 $parentRefs[$numTabs] = $page->ID;
             }
             // Remove no-longer-relevant children from the parentRefs.  Allows more graceful acceptance of files
             // with errors
             for ($i = sizeof($parentRefs) - 1; $i > $numTabs; $i--) {
                 unset($parentRefs[$i]);
             }
             // Memory cleanup
             $page->destroy();
             unset($page);
         }
     }
     if (!SapphireTest::is_running_test()) {
         $complete = $this->complete();
         echo $complete['Content'];
     } else {
         $this->redirect($this->Link() . 'complete');
     }
 }
 public function onBeforeWrite()
 {
     parent::onBeforeWrite();
     $this->URLSegment = $this->URLSegment ? $this->URLSegment : Convert::raw2url($this->Title);
 }
 /**
  * Tests {@link Convert::testRaw2URL()}
  * @todo test toASCII()
  */
 public function testRaw2URL()
 {
     $orig = Config::inst()->get('URLSegmentFilter', 'default_allow_multibyte');
     Config::inst()->update('URLSegmentFilter', 'default_allow_multibyte', false);
     $this->assertEquals('foo', Convert::raw2url('foo'));
     $this->assertEquals('foo-and-bar', Convert::raw2url('foo & bar'));
     $this->assertEquals('foo-and-bar', Convert::raw2url('foo &amp; bar!'));
     $this->assertEquals('foos-bar-2', Convert::raw2url('foo\'s [bar] (2)'));
     Config::inst()->update('URLSegmentFilter', 'default_allow_multibyte', $orig);
 }
Пример #13
0
 /**
  * Overloaded to ensure the code is always descent.
  *
  * @param string
  */
 public function setCode($val)
 {
     $this->setField("Code", Convert::raw2url($val));
 }
 /**
  * Parse the tweet object into a HTML block
  * 
  * @param stdObject $tweet Tweet object
  * @return string HTML text
  */
 protected function parseText($tweet)
 {
     $rawText = $tweet->text;
     // tokenise into words for parsing (multibyte safe)
     $tokens = preg_split('/(?<!^)(?!$)/u', $rawText);
     // Inject links
     foreach ($tweet->entities->urls as $url) {
         $this->injectLink($tokens, $url, $url->url, $url->expanded_url);
     }
     // Inject hashtags
     foreach ($tweet->entities->hashtags as $hashtag) {
         $link = 'https://twitter.com/search?src=hash&q=' . Convert::raw2url('#' . $hashtag->text);
         $text = "#" . $hashtag->text;
         $this->injectLink($tokens, $hashtag, $link, $text);
     }
     // Inject mentions
     foreach ($tweet->entities->user_mentions as $mention) {
         $link = 'https://twitter.com/' . Convert::raw2url($mention->screen_name);
         $this->injectLink($tokens, $mention, $link, $mention->name);
     }
     // Re-combine tokens
     return implode('', $tokens);
 }
Пример #15
0
	/**
	 * @todo test toASCII()
	 */
	function testRaw2URL() {
		$this->assertEquals('foo', Convert::raw2url('foo'));
		$this->assertEquals('foo-and-bar', Convert::raw2url('foo & bar'));
		$this->assertEquals('foo-and-bar', Convert::raw2url('foo &amp; bar!'));
		$this->assertEquals('foos-bar-2', Convert::raw2url('foo\'s [bar] (2)'));
	}
 /**
  * Single calendar
  * Can be public or private
  * For public calendars either the calendar id or the calendar url can be supplied
  * For private calendars user email and hash need to be supplied - like this.
  * The private calendar hash is created in {@see PrivateCalendarMemberExtension}
  */
 function cal()
 {
     //echo 'test';
     $call = null;
     $request = $this->getRequest();
     $ics = null;
     $idOrURL = $request->param('ID');
     //echo $idOrURL;
     //Public calendar via id
     if (is_numeric($idOrURL)) {
         //calendar id is requested
         //echo 'request is numeric';
         $cal = Calendar::get()->ByID((int) $request->param('ID'));
         //echo $cal->getLink();
         //Public calendar via url
     } else {
         //calendar url is requested
         //echo 'request is a string';
         $url = Convert::raw2url($idOrURL);
         $cal = Calendar::get()->filter('URLSegment', $url)->First();
     }
     //If not public calendar is found we check for a private calendar
     if (!$cal) {
         echo $idOrURL;
         $member = Member::get()->filter('Email', $idOrURL)->filter('PrivateCalendarKey', $request->param('OtherID'))->First();
         if ($member && $member->exists()) {
             return $this->memberCalendar($member);
         }
     }
     if ($cal && $cal->exists()) {
         //everybody can access public calendars
         if ($cal->ClassName == 'PublicCalendar') {
             $ics = ICSExport::ics_from_sscal($cal);
             $calName = $cal->Title;
         }
         return $this->output($ics, $calName);
     } else {
         echo "calendar can't be found";
     }
 }
 public function getConvertedService()
 {
     return Convert::raw2url($this->Service);
 }
 public function onBeforeWrite()
 {
     parent::onBeforeWrite();
     // Ensure that the code is URL safe
     $this->Code = Convert::raw2url($this->Code);
 }
Пример #19
0
 /**
  * @todo test toASCII()
  */
 public function testRaw2URL()
 {
     $orig = URLSegmentFilter::$default_allow_multibyte;
     URLSegmentFilter::$default_allow_multibyte = false;
     $this->assertEquals('foo', Convert::raw2url('foo'));
     $this->assertEquals('foo-and-bar', Convert::raw2url('foo & bar'));
     $this->assertEquals('foo-and-bar', Convert::raw2url('foo &amp; bar!'));
     $this->assertEquals('foos-bar-2', Convert::raw2url('foo\'s [bar] (2)'));
     URLSegmentFilter::$default_allow_multibyte = $orig;
 }
 /**
  * Renders the current calendar, if a calenar link has been supplied via the url
  */
 public function CurrentCalendar()
 {
     $url = Convert::raw2url($this->request->param('ID'));
     $cal = PublicCalendar::get()->filter('URLSegment', $url)->First();
     return $cal;
 }
 public function getFooterHeadingAnchor()
 {
     if ($this->FooterHeading) {
         return Convert::raw2url($this->FooterHeading);
     }
 }
Пример #22
0
 /**
  * Generate a URL segment based on the title provided.
  * 
  * If {@link Extension}s wish to alter URL segment generation, they can do so by defining
  * updateURLSegment(&$url, $title).  $url will be passed by reference and should be modified.
  * $title will contain the title that was originally used as the source of this generated URL.
  * This lets extensions either start from scratch, or incrementally modify the generated URL.
  * 
  * @param string $title Page title.
  * @return string Generated url segment
  */
 function generateURLSegment($title)
 {
     $t = Convert::raw2url($title);
     if (!$t || $t == '-' || $t == '-1') {
         $t = "page-{$this->ID}";
     }
     // Hook for extensions
     $this->extend('updateURLSegment', $t, $title);
     return $t;
 }
 /**
  * Gets the overview data from new relic
  */
 public function overview_data()
 {
     //Purge Requirements
     Requirements::clear();
     //If we're not configured properly return an error
     if (!$this->getIsConfigured()) {
         $msg = _t('NewRelicPerformanceReport.API_APP_CONFIG_ERROR', '_New Relic API Key or Application ID is missing, check configuration');
         $e = new SS_HTTPResponse_Exception($msg, 400);
         $e->getResponse()->addHeader('Content-Type', 'text/plain');
         $e->getResponse()->addHeader('X-Status', rawurlencode($msg));
         throw $e;
         return;
     }
     //Build the base restful service object
     $service = new RestfulService('https://api.newrelic.com/v2/applications/' . Convert::raw2url($this->config()->application_id) . '/metrics/data.json', $this->config()->refresh_rate);
     $service->httpHeader('X-Api-Key:' . Convert::raw2url($this->config()->api_key));
     //Perform the request
     $response = $service->request('', 'POST', 'names[]=HttpDispatcher&names[]=Apdex&names[]=EndUser/Apdex&names[]=Errors/all&names[]=EndUser&period=60');
     //Retrieve the body
     $body = $response->getBody();
     if (!empty($body)) {
         $this->response->addHeader('Content-Type', 'application/json; charset=utf-8');
         return $body;
     }
     //Data failed to load
     $msg = _t('NewRelicPerformanceReport.DATA_LOAD_FAIL', '_Failed to retrieve data from New Relic');
     $e = new SS_HTTPResponse_Exception($msg, 400);
     $e->getResponse()->addHeader('Content-Type', 'text/plain');
     $e->getResponse()->addHeader('X-Status', rawurlencode($msg));
     throw $e;
 }
 public static function GetContinentSuffixes()
 {
     $arrRet = array();
     foreach (Config::inst()->get('ContinentalContent', 'continents') as $key => $continent) {
         if (is_array($continent)) {
             $arrRet[Convert::raw2url($key)] = self::UpdateContinentExtensionName($key);
         } else {
             $arrRet[Convert::raw2url($continent)] = self::UpdateContinentExtensionName($continent);
         }
     }
     return $arrRet;
 }