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;
 }
 public function transformCollectionAsArrayList($collection)
 {
     $result = $this->transformCollection($collection);
     $list = new \ArrayList();
     $list->addAll($result);
     return $list;
 }
 /**
  * @param ManyManyList $products
  */
 public function updateRelatedProducts(&$products, $limit, $random)
 {
     $curCount = $products->count();
     if ($curCount < $limit) {
         $cfg = Config::inst()->forClass(get_class($this->owner));
         $class = $cfg->get('related_products_class');
         // look up the fields
         $fields = $cfg->get('related_products_fields');
         if (empty($fields)) {
             return;
         }
         if (!is_array($fields)) {
             $fields = array($fields);
         }
         // create a filter from the fields
         $filter = array();
         foreach ($fields as $f) {
             $filter[$f] = $this->owner->getField($f);
         }
         // Convert to an array list so we can add to it
         $products = new ArrayList($products->toArray());
         // Look up products that match the filter
         $generated = DataObject::get($class)->filterAny($filter)->exclude('ID', $this->owner->ID)->sort('RAND()')->limit($limit - $curCount);
         foreach ($generated as $prod) {
             $products->push($prod);
         }
     }
 }
 /**
  * Export core
  *
  * Replaces definition in GridFieldPrintButton
  * same as original except sources data from $gridField->getList() instead of $gridField->getManipulatedList()
  *
  * @param GridField
  */
 public function generatePrintData(GridField $gridField)
 {
     $printColumns = $this->getPrintColumnsForGridField($gridField);
     $header = null;
     if ($this->printHasHeader) {
         $header = new ArrayList();
         foreach ($printColumns as $field => $label) {
             $header->push(new ArrayData(array("CellString" => $label)));
         }
     }
     // The is the only variation from the parent class, using getList() instead of getManipulatedList()
     $items = $gridField->getList();
     $itemRows = new ArrayList();
     foreach ($items as $item) {
         $itemRow = new ArrayList();
         foreach ($printColumns as $field => $label) {
             $value = $gridField->getDataFieldValue($item, $field);
             $itemRow->push(new ArrayData(array("CellString" => $value)));
         }
         $itemRows->push(new ArrayData(array("ItemRow" => $itemRow)));
         $item->destroy();
     }
     $ret = new ArrayData(array("Title" => $this->getTitle($gridField), "Header" => $header, "ItemRows" => $itemRows, "Datetime" => SS_Datetime::now(), "Member" => Member::currentUser()));
     return $ret;
 }
 /**
  * @param string $keywords
  * @param array $filters [optional]
  * @param array $facetSpec [optional]
  * @param int $start [optional]
  * @param int $limit [optional]
  * @param string $sort [optional]
  * @return ArrayData
  */
 function searchFromVars($keywords, array $filters = array(), array $facetSpec = array(), $start = -1, $limit = -1, $sort = '')
 {
     $searchable = ShopSearch::get_searchable_classes();
     $matches = new ArrayList();
     foreach ($searchable as $className) {
         $list = DataObject::get($className);
         // get searchable fields
         $keywordFields = $this->getSearchFields($className);
         // build the filter
         $filter = array();
         // Use parametrized query if SilverStripe >= 3.2
         if (SHOP_SEARCH_IS_SS32) {
             foreach ($keywordFields as $indexFields) {
                 $filter[] = array("MATCH ({$indexFields}) AGAINST (?)" => $keywords);
             }
             $list = $list->whereAny($filter);
         } else {
             foreach ($keywordFields as $indexFields) {
                 $filter[] = sprintf("MATCH ({$indexFields}) AGAINST ('%s')", Convert::raw2sql($keywords));
             }
             // join all the filters with an "OR" statement
             $list = $list->where(implode(' OR ', $filter));
         }
         // add in any other filters
         $list = FacetHelper::inst()->addFiltersToDataList($list, $filters);
         // add any matches to the big list
         $matches->merge($list);
     }
     return new ArrayData(array('Matches' => $matches, 'Facets' => FacetHelper::inst()->buildFacets($matches, $facetSpec, (bool) Config::inst()->get('ShopSearch', 'auto_facet_attributes'))));
 }
 public function notifyObservers()
 {
     for ($i = 0; $i < $this->observers->size(); $i++) {
         $observer = $this->observers->get($i);
         $observer->update($this->temperature, $this->humidity, $this->pressure);
     }
 }
예제 #7
0
	/**
	 * Return this field's linked items
	 */
	function getItems() {
		// If the value has been set, use that
		if($this->value != 'unchanged' && is_array($this->sourceObject)) {
			$items = array();
			$values = is_array($this->value) ? $this->value : preg_split('/ *, */', trim($this->value));
			foreach($values as $value) {
				$item = new stdClass;
				$item->ID = $value;
				$item->Title = $this->sourceObject[$value];
				$items[] = $item;
			}
			return $items;
			
		// Otherwise, look data up from the linked relation
		} if($this->value != 'unchanged' && is_string($this->value)) {
			$items = new ArrayList();
			$ids = explode(',', $this->value);
			foreach($ids as $id) {
				if(!is_numeric($id)) continue;
				$item = DataObject::get_by_id($this->sourceObject, $id);
				if($item) $items->push($item);
			}
			return $items;
		} else if($this->form) {
			$fieldName = $this->name;
			$record = $this->form->getRecord();
			if(is_object($record) && $record->hasMethod($fieldName)) 
				return $record->$fieldName();
		}	
	}
 /**
  * Get a filtered list of discussions by can view rights.
  *
  * This method is basically the meat and potates of this module and does most
  * of the crunch work of finding the relevant discussion list and ensuring
  * the current user is allowed to view it.
  *
  * @return DataList
  */
 public function ViewableDiscussions()
 {
     $tag = $this->getTag();
     $category = $this->getCategory();
     $member = Member::currentUser();
     $discussions_to_view = new ArrayList();
     if ($tag) {
         $SQL_tag = Convert::raw2sql($tag);
         $discussions = Discussion::get()->filter("ParentID", $this->ID)->where("\"Discussion\".\"Tags\" LIKE '%{$SQL_tag}%'");
     } elseif ($category) {
         $discussions = Discussion::get()->filter(array("ParentID" => $this->ID, "Categories.ID:ExactMatch" => $category->ID));
     } elseif ($this->request->param('Action') == 'liked') {
         $discussions = $member->LikedDiscussions();
     } elseif ($this->request->param('Action') == 'my') {
         $discussions = Discussion::get()->filter(array("ParentID" => $this->ID, "AuthorID" => $member->ID));
     } else {
         $discussions = $this->Discussions();
     }
     foreach ($discussions as $discussion) {
         if ($discussion->canView($member)) {
             $discussions_to_view->add($discussion);
         }
     }
     $this->extend("updateViewableDiscussions", $discussions_to_view);
     return new PaginatedList($discussions_to_view, $this->request);
 }
 /**
  * @param GridField $gridField
  *
  * @return array
  */
 public function getHTMLFragments($gridField)
 {
     Requirements::css(CMC_BULKUPDATER_MODULE_DIR . '/css/CmcGridFieldBulkUpdater.css');
     Requirements::javascript(CMC_BULKUPDATER_MODULE_DIR . '/javascript/CmcGridFieldBulkUpdater.js');
     Requirements::add_i18n_javascript(CMC_BULKUPDATER_MODULE_DIR . '/lang/js');
     //initialize column data
     $cols = new ArrayList();
     $fields = $gridField->getConfig()->getComponentByType('GridFieldEditableColumns')->getDisplayFields($gridField);
     foreach ($gridField->getColumns() as $col) {
         $fieldName = $col;
         $fieldType = '';
         $fieldLabel = '';
         if (isset($fields[$fieldName])) {
             $fieldData = $fields[$fieldName];
             if (isset($fieldData['field'])) {
                 $fieldType = $fieldData['field'];
             }
             if (isset($fieldData['title'])) {
                 $fieldLabel = $fieldData['title'];
             }
         }
         //Debug::show($fieldType);
         if (class_exists($fieldType) && $fieldType != 'ReadonlyField') {
             $field = new $fieldType($fieldName, $fieldLabel);
             if ($fieldType == 'DatetimeField' || $fieldType == 'DateField' || $fieldType == 'TimeField') {
                 $field->setValue(date('Y-m-d H:i:s'));
                 $field->setConfig('showcalendar', true);
             }
             $cols->push(new ArrayData(array('UpdateField' => $field, 'Name' => $fieldName, 'Title' => $fieldLabel)));
         } else {
             $meta = $gridField->getColumnMetadata($col);
             $cols->push(new ArrayData(array('Name' => $col, 'Title' => $meta['title'])));
         }
     }
     $templateData = array();
     if (!count($this->config['actions'])) {
         user_error('Trying to use GridFieldBulkManager without any bulk action.', E_USER_ERROR);
     }
     //set up actions
     $actionsListSource = array();
     $actionsConfig = array();
     foreach ($this->config['actions'] as $action => $actionData) {
         $actionsListSource[$action] = $actionData['label'];
         $actionsConfig[$action] = $actionData['config'];
     }
     reset($this->config['actions']);
     $firstAction = key($this->config['actions']);
     $dropDownActionsList = DropdownField::create('bulkActionName', '')->setSource($actionsListSource)->setAttribute('class', 'bulkActionName no-change-track')->setAttribute('id', '');
     //initialize buttonLabel
     $buttonLabel = _t('CMC_GRIDFIELD_BULK_UPDATER.ACTION1_BTN_LABEL', $this->config['actions'][$firstAction]['label']);
     //add menu if more than one action
     if (count($this->config['actions']) > 1) {
         $templateData = array('Menu' => $dropDownActionsList->FieldHolder());
         $buttonLabel = _t('CMC_GRIDFIELD_BULK_UPDATER.ACTION_BTN_LABEL', 'Go');
     }
     //Debug::show($buttonLabel);
     $templateData = array_merge($templateData, array('Button' => array('Label' => $buttonLabel, 'Icon' => $this->config['actions'][$firstAction]['config']['icon']), 'Select' => array('Label' => _t('CMC_GRIDFIELD_BULK_UPDATER.SELECT_ALL_LABEL', 'Select all')), 'Colspan' => count($gridField->getColumns()) - 1, 'Cols' => $cols));
     $templateData = new ArrayData($templateData);
     return array('header' => $templateData->renderWith('CmcBulkUpdaterButtons'));
 }
 /**
  * normally returns TRUE, but returns FALSE when it, or its parent is in the list.
  * todo: add products in other product categories
  * @param SiteTree $page
  * @return Boolean
  */
 function canBeDiscounted(SiteTree $page)
 {
     if ($this->owner->PageIDs) {
         $allowedPageIDs = explode(',', $this->owner->PageIDs);
         $checkPages = new ArrayList(array($page));
         $alreadyCheckedPageIDs = array();
         while ($checkPages->Count()) {
             $page = $checkPages->First();
             if (array_search($page->ID, $allowedPageIDs) !== false) {
                 return true;
             }
             $alreadyCheckedPageIDs[] = $page->ID;
             $checkPages->remove($page);
             // Parents list update
             if ($page->hasMethod('AllParentGroups')) {
                 $parents = new ArrayList($page->AllParentGroups()->toArray());
             } else {
                 $parents = new ArrayList();
             }
             $parent = $page->Parent();
             if ($parent && $parent->exists()) {
                 $parents->unshift($parent);
             }
             foreach ($parents as $parent) {
                 if (array_search($parent->ID, $alreadyCheckedPageIDs) === false) {
                     $checkPages->push($parent);
                 }
             }
             $checkPages->removeDuplicates();
         }
         return false;
     }
     return true;
 }
 /**
  * If this is attached to an object with the hierarchy extension, it returns
  * a set of a schema objects attached to any ancestors (which should be
  * present on this object).
  *
  * @return ArrayList
  */
 public function getInheritedSchemas()
 {
     $result = new ArrayList();
     if (!$this->owner->hasExtension('Hierarchy')) {
         return new ArrayList();
     }
     $ids = array();
     $parents = $this->owner->getAncestors();
     foreach ($parents as $parent) {
         $ids[] = $parent->ID;
     }
     if (count($ids)) {
         $filter = sprintf('"MetadataSchema"."ID" = "MetadataSchemaLink"."SchemaID"' . ' AND "MetadataSchemaLink"."ParentClass" = \'%s\'' . ' AND "MetadataSchemaLink"."ParentID" IN (%s)', ClassInfo::baseDataClass($this->owner->class), implode(', ', $ids));
         $result = MetadataSchema::get()->innerJoin('MetadataSchemaLink', $filter);
         if ($result) {
             $result = new ArrayList($result->toArray());
         } else {
             $result = new ArrayList();
         }
     }
     if ($this->owner instanceof SiteTree) {
         // Check SiteConfig too
         $config = SiteConfig::current_site_config();
         if ($config->hasExtension('MetadataExtension')) {
             $schemas = $config->getAttachedSchemas();
             if ($schemas && $schemas->count()) {
                 $result->merge($schemas);
             }
         }
     }
     return $result;
 }
예제 #12
0
파일: Int.php 프로젝트: redema/sapphire
	function Times() {
		$output = new ArrayList();
		for( $i = 0; $i < $this->value; $i++ )
			$output->push( new ArrayData( array( 'Number' => $i + 1 ) ) );

		return $output;
	}
 /**
  * If HideUnmatchedFilters is on then remove all filters which are not found in the items by their 'AssociatedFilters' relationship.
  *
  * @param \DataList $filters list of GridListFilter models
  * @param array     $parameters
  * @return \ArrayList
  */
 public function constrainGridListFilters(&$filters, &$parameters = [])
 {
     $out = new \ArrayList();
     if ($this()->{self::SingleFieldName}) {
         $ids = $filters->column('ID');
         if (count($ids)) {
             $items = $this()->GridListItems();
             // this is where we keep track of GridListFilters which have been found on items where ID is the key
             $foundFilters = array_combine($ids, array_fill(0, count($ids), false));
             foreach ($foundFilters as $filterID => &$found) {
                 /** @var \Page|Model $item */
                 foreach ($items as $item) {
                     if ($item->hasExtension(HasGridListFilters::class_name())) {
                         if ($itemFilters = $item->{HasGridListFilters::relationship_name()}()->column('ID')) {
                             if (in_array($filterID, $itemFilters)) {
                                 $found = true;
                                 break;
                             }
                         }
                     }
                 }
             }
             foreach ($filters as $filter) {
                 if (isset($foundFilters[$filter->ID])) {
                     $out->push($filter);
                 }
             }
             $filters = $out;
         }
     }
 }
 /**
  *
  * @return ArrayList
  */
 public function AvailableWidgets()
 {
     $widgets = new ArrayList();
     foreach ($this->widgetClasses as $widgetClass) {
         $classes = ClassInfo::subclassesFor($widgetClass);
         if (isset($classes['Widget'])) {
             unset($classes['Widget']);
         } else {
             if (isset($classes[0]) && $classes[0] == 'Widget') {
                 unset($classes[0]);
             }
         }
         foreach ($classes as $class) {
             $available = Config::inst()->get($class, 'only_available_in');
             if (!empty($available) && is_array($available)) {
                 if (in_array($this->Name, $available)) {
                     $widgets->push(singleton($class));
                 }
             } else {
                 $widgets->push(singleton($class));
             }
         }
     }
     return $widgets;
 }
예제 #15
0
 function testRSSFeed()
 {
     $list = new ArrayList();
     $list->push(new RSSFeedTest_ItemA());
     $list->push(new RSSFeedTest_ItemB());
     $list->push(new RSSFeedTest_ItemC());
     $rssFeed = new RSSFeed($list, "http://www.example.com", "Test RSS Feed", "Test RSS Feed Description");
     $content = $rssFeed->feedContent();
     //Debug::message($content);
     $this->assertContains('<link>http://www.example.org/item-a/</link>', $content);
     $this->assertContains('<link>http://www.example.com/item-b.html</link>', $content);
     $this->assertContains('<link>http://www.example.com/item-c.html</link>', $content);
     $this->assertContains('<title>ItemA</title>', $content);
     $this->assertContains('<title>ItemB</title>', $content);
     $this->assertContains('<title>ItemC</title>', $content);
     $this->assertContains('<description>ItemA Content</description>', $content);
     $this->assertContains('<description>ItemB Content</description>', $content);
     $this->assertContains('<description>ItemC Content</description>', $content);
     // Feed #2 - put Content() into <title> and AltContent() into <description>
     $rssFeed = new RSSFeed($list, "http://www.example.com", "Test RSS Feed", "Test RSS Feed Description", "Content", "AltContent");
     $content = $rssFeed->feedContent();
     $this->assertContains('<title>ItemA Content</title>', $content);
     $this->assertContains('<title>ItemB Content</title>', $content);
     $this->assertContains('<title>ItemC Content</title>', $content);
     $this->assertContains('<description>ItemA AltContent</description>', $content);
     $this->assertContains('<description>ItemB AltContent</description>', $content);
     $this->assertContains('<description>ItemC AltContent</description>', $content);
 }
예제 #16
0
 public function index()
 {
     $featured_news = new ArrayList($this->news_repository->getFeaturedNews(true, 3));
     $recent_news = new ArrayList($this->news_repository->getRecentNews());
     $slide_news = new ArrayList($this->news_repository->getSlideNews());
     return $this->renderWith(array('NewsPage', 'Page'), array('FeaturedNews' => $featured_news, 'RecentNews' => $recent_news, 'SlideNews' => $slide_news, 'SlideNewsCount' => $slide_news->count()));
 }
 public function doAllChildrenIncludingDeleted($context = null)
 {
     if (!$this->owner) {
         user_error('Hierarchy::doAllChildrenIncludingDeleted() called without $this->owner');
     }
     $baseClass = ClassInfo::baseDataClass($this->owner->class);
     if ($baseClass) {
         $stageChildren = $this->owner->stageChildren(true);
         $stageChildren = $this->RemoveNewsPostsFromSiteTree($stageChildren);
         // Add live site content that doesn't exist on the stage site, if required.
         if ($this->owner->hasExtension('Versioned')) {
             // Next, go through the live children.  Only some of these will be listed
             $liveChildren = $this->owner->liveChildren(true, true);
             if ($liveChildren) {
                 $liveChildren = $this->RemoveNewsPostsFromSiteTree($liveChildren);
                 $merged = new ArrayList();
                 $merged->merge($stageChildren);
                 $merged->merge($liveChildren);
                 $stageChildren = $merged;
             }
         }
         $this->owner->extend("augmentAllChildrenIncludingDeleted", $stageChildren, $context);
     } else {
         user_error("Hierarchy::AllChildren() Couldn't determine base class for '{$this->owner->class}'", E_USER_ERROR);
     }
     return $stageChildren;
 }
예제 #18
0
 function testAddSameElementTwice()
 {
     $list = new ArrayList("string");
     $list->add("Hello there");
     $list->add("Hello there");
     $this->assertEqual(2, $list->size());
 }
 public function updateFilteredEmailRecipients(ArrayList $recipients, $data, $form)
 {
     foreach ($recipients as $recipient) {
         // check if condition set
         if (($field = $recipient->ConditionField()) && $field->ID) {
             // get field name
             $fieldName = $field->Name;
             // get condition value
             $conditionValue = $recipient->ConditionFieldValue;
             // get field value
             $fieldValue = "";
             if ($field->hasMethod('getValueFromData')) {
                 $fieldValue = $field->getValueFromData($data);
             } else {
                 if (isset($data[$fieldName])) {
                     $fieldValue = $data[$fieldName];
                 }
             }
             // remove recipient if values don't match
             if (trim($fieldValue) != trim($conditionValue)) {
                 $recipients->remove($recipient);
             }
         }
     }
 }
예제 #20
0
 public function listProducts()
 {
     $idlist = $this->getProductIdsForPage();
     if (is_array($idlist)) {
         $prods = Product::get()->byIDs($idlist)->sort('SortKey, Brand, Sold asc');
         #Nollst�ll
         $oldpostBrand = "";
         $oldpostSold = "";
         $outdata = new ArrayList();
         foreach ($prods as $prod) {
             if ($oldpostBrand != $prod->Brand || $oldpostSold != $prod->Sold) {
                 //                Rubrik ska skrivas ut  s�  den stoppas in i en egen ArrayData
                 $headerRow = new ArrayData(array('isHeaderRow' => true, 'HeaderBrand' => $prod->Brand, 'HeaderSold' => $prod->Sold));
                 $outdata->push($headerRow);
             }
             #Vanlig row
             $thisrow = $prod;
             $outdata->push($thisrow);
             #spara undan f�r att j�mf�ra
             $oldpostBrand = $prod->Brand;
             $oldpostSold = $prod->Sold;
         }
         return $outdata;
     }
 }
예제 #21
0
 function testNormalList()
 {
     $list = new ArrayList("string");
     $list->add("a");
     $list->add("b");
     $this->assertEqual("[a,b]", $list->__toString());
 }
 function Downloads()
 {
     $dos = new ArrayList();
     $folders = $this->getFolderList();
     //get details
     foreach ($folders as $folder) {
         $svnLink = "https://silverstripe-ecommerce.googlecode.com/svn/modules/{$folder}/trunk/";
         if ($folder == "ecommerce") {
             $svnLink = "https://silverstripe-ecommerce.googlecode.com/svn/trunk/";
         }
         $gitLink = "https://github.com/sunnysideup/silverstripe-{$folder}";
         $downloadLink = "assets/downloads/" . trim($folder) . ".zip";
         if (!isset($this->defaultDownloadArray[$folder])) {
             $this->defaultDownloadArray[$folder] = array("Title" => $folder, "FolderPadded" => $folder, "SVNLink" => $svnLink, "GITLink" => $gitLink);
         }
         $downloadFile = Director::baseFolder() . "/" . $downloadLink;
         if (file_exists($downloadFile)) {
             $this->defaultDownloadArray[$folder]["DownloadLink"] = $downloadLink;
         }
     }
     //sort
     ksort($this->defaultDownloadArray);
     //pad folder for svn externals and add to dos...
     foreach ($this->defaultDownloadArray as $folder => $folderArray) {
         $folderArray["Folder"] = $folder;
         if (isset($folderArray["FolderPadded"])) {
             $folderArray["FolderPadded"] = str_pad(trim($folderArray["FolderPadded"]), 45, " ", STR_PAD_RIGHT);
         }
         if (isset($folderArray["GITLink"])) {
             $folderArray["GITLinkGIT"] = str_pad(str_replace("https://", "git://", $folderArray["GITLink"]), 85, " ", STR_PAD_RIGHT);
         }
         $dos->push(new ArrayData($folderArray));
     }
     return $dos;
 }
 /**
  * @param string $keywords
  * @param array $filters [optional]
  * @param array $facetSpec [optional]
  * @param int $start [optional]
  * @param int $limit [optional]
  * @param string $sort [optional]
  * @return ArrayData
  */
 function searchFromVars($keywords, array $filters = array(), array $facetSpec = array(), $start = -1, $limit = -1, $sort = '')
 {
     $searchable = ShopSearch::get_searchable_classes();
     $matches = new ArrayList();
     foreach ($searchable as $className) {
         $list = DataObject::get($className);
         // get searchable fields
         $keywordFields = $this->scaffoldSearchFields($className);
         // convert that list into something we can pass to Datalist::filter
         $keywordFilter = array();
         if (!empty($keywords)) {
             foreach ($keywordFields as $searchField) {
                 $name = strpos($searchField, ':') !== FALSE ? $searchField : "{$searchField}:PartialMatch";
                 $keywordFilter[$name] = $keywords;
             }
         }
         if (count($keywordFilter) > 0) {
             $list = $list->filterAny($keywordFilter);
         }
         // add in any other filters
         $list = FacetHelper::inst()->addFiltersToDataList($list, $filters);
         // add any matches to the big list
         $matches->merge($list);
     }
     return new ArrayData(array('Matches' => $matches, 'Facets' => FacetHelper::inst()->buildFacets($matches, $facetSpec, (bool) Config::inst()->get('ShopSearch', 'auto_facet_attributes'))));
 }
 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;
 }
 /**
  * We need to disable Translatable before retreiving the DataObjects or 
  * Pages for the sitemap, because otherwise only pages in the default 
  * language are found.
  * 
  * Next we need to add the alternatives for each Translatable Object 
  * included in the sitemap: basically these are the Translations plus 
  * the current object itself
  * 
  * @return Array
  */
 public function sitemap()
 {
     Translatable::disable_locale_filter();
     $sitemap = parent::sitemap();
     Translatable::enable_locale_filter();
     $updatedItems = new ArrayList();
     foreach ($sitemap as $items) {
         foreach ($items as $item) {
             if ($item->hasExtension('Translatable')) {
                 $translations = $item->getTranslations();
                 if ($translations) {
                     $alternatives = new ArrayList();
                     foreach ($translations as $translation) {
                         $translation->GoogleLocale = $this->getGoogleLocale($translation->Locale);
                         $alternatives->push($translation);
                     }
                     $item->GoogleLocale = $this->getGoogleLocale($item->Locale);
                     $alternatives->push($item);
                     $item->Alternatives = $alternatives;
                 }
                 $updatedItems->push($item);
             }
         }
     }
     if (!empty($updatedItems)) {
         return array('Items' => $updatedItems);
     } else {
         return $sitemap;
     }
 }
예제 #26
0
 public function BillingHistory()
 {
     $billingHistory = new ArrayList();
     $orders = Order::get()->filter(array('MemberID' => Member::currentUserID(), 'OrderStatus' => 'c'))->sort('Created');
     foreach ($orders as $order) {
         $productId = $order->ProductID;
         if (($productId == 1 || $productId == 2 || $productId == 3) && $order->IsTrial == 1) {
             $productDesc = 'First Month Trial';
         } else {
             $product = Product::get()->byID($productId);
             $productDesc = $product->Name;
         }
         $creditCard = $order->CreditCard();
         $ccNumber = 'XXXX-XXXX-XXXX-' . substr($creditCard->CreditCardNumber, -4);
         $orderDetails = array('Date' => $order->Created, 'Description' => $productDesc, 'CCType' => strtoupper($creditCard->CreditCardType), 'CCNumber' => $ccNumber, 'Amount' => $order->Amount);
         $billingHistory->push(new ArrayData($orderDetails));
     }
     $memBillHistory = MemberBillingHistory::get()->filter('MemberID', Member::currentUserID())->sort('Created');
     foreach ($memBillHistory as $history) {
         $creditCard = $history->CreditCard();
         $ccNumber = 'XXXX-XXXX-XXXX-' . substr($creditCard->CreditCardNumber, -4);
         $details = array('Date' => $history->Created, 'Description' => $history->Product()->Name, 'CCType' => strtoupper($creditCard->CreditCardType), 'CCNumber' => $ccNumber, 'Amount' => $history->Product()->RecurringPrice);
         $billingHistory->push(new ArrayData($details));
     }
     $sortedBillingHistory = $billingHistory->sort('Date');
     return $sortedBillingHistory;
 }
 /**
  *@returns DataObjectSet
  **/
 function fetchFBFeed($url, $maxnumber = 1, $timeFormat = 'F jS Y, H:i')
 {
     /* The following line is absolutely necessary to read Facebook feeds. Facebook will not recognize PHP as a browser and therefore won't fetch anything. So we define a browser here */
     ini_set('user_agent', 'Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.5; en-US; rv:1.9.1.3) Gecko/20090824 Firefox/3.5.3');
     $updates = simplexml_load_file($url);
     //Load feed with simplexml
     $arrayList = new ArrayList();
     //Initialize empty array to store statuses
     foreach ($updates->channel->item as $fbUpdate) {
         if ($maxnumber == 0) {
             break;
         } else {
             $desc = $fbUpdate->description;
             //Add www.facebook.com to hyperlinks
             $desc = str_replace('href="', 'href="http://www.facebook.com', $desc);
             //Converts UTF-8 into ISO-8859-1 to solve special symbols issues
             $desc = iconv("UTF-8", "ISO-8859-1//TRANSLIT", $desc);
             //Get status update time
             $pubdate = strtotime($fbUpdate->pubDate);
             $propertime = gmdate($timeFormat, $pubdate);
             //Customize this to your liking
             //Get link to update
             $linkback = $fbUpdate->link;
             //Store values in array
             $fbItem = array('Description' => $desc, 'Date' => $propertime, 'Link' => $linkback);
             $arrayList->push(new ArrayData($fbItem));
             $maxnumber--;
         }
     }
     return $arrayList;
 }
 /**
  * Generate an list of items that will be loaded into the custom menu
  *
  * @param $menu template slug for retriving a menu
  * @return ArrayList
  */
 public function CustomMenu($menu = "")
 {
     $menu_items = new ArrayList();
     if (isset($menu)) {
         // Ensure argument is safe for database
         $menu = Convert::raw2sql($menu);
         $filter = array('Slug' => $menu);
         if ($menu = CustomMenuHolder::get()->filter($filter)->first()) {
             // If a custom order is set, use it
             if ($menu->Order) {
                 $order = explode(',', $menu->Order);
             }
             if (isset($order) && is_array($order) && count($order) > 0) {
                 foreach ($order as $item) {
                     $menu_items->push($menu->Pages()->find('ID', $item));
                 }
             } else {
                 foreach ($menu->Pages() as $item) {
                     $menu_items->push($item);
                 }
             }
         }
     }
     return $menu_items;
 }
 public function getCurrentFilms()
 {
     $r = new ArrayList();
     //$RestfulService = new RestfulService("http://www.odeon.co.uk/api/uk/v2/cinemas/cinema/{$this->ID}/filmswithdetails.json");
     $RestfulService = new RestfulService("http://www.odeon.co.uk/api/uk/v2/cinemas/cinema/{$this->ID}/", 259200);
     $Response = $RestfulService->request("filmswithdetails.json");
     if (!$Response->isError()) {
         $films = Convert::json2array($Response->getBody());
         foreach ($films as $film) {
             $OdeonFilm = OdeonFilm::get_by_id('OdeonFilm', (int) $film['masterId']);
             if (!$OdeonFilm) {
                 $OdeonFilm = new OdeonFilm();
                 $OdeonFilm->ID = (int) $film['masterId'];
                 $OdeonFilm->Title = Convert::raw2sql($film['title']);
                 if (isset($film['media']['imageUrl400'])) {
                     $OdeonFilm->imageUrlSmall = Convert::raw2sql($film['media']['imageUrl400']);
                 }
                 if (isset($film['casts'])) {
                     $OdeonFilm->Content = Convert::raw2sql($film['casts']);
                 }
                 $OdeonFilm->write();
             }
             $r->push($OdeonFilm);
         }
     }
     return $r->sort("Title DESC");
 }
예제 #30
-1
 public function getHTMLFragments($gridField)
 {
     $fields = new ArrayList();
     $state = $gridField->State->UserFormsGridField;
     $selectedField = $state->filter;
     $selectedValue = $state->value;
     // show dropdown of all the fields available from the submitted form fields
     // that have been saved. Takes the titles from the currently live form.
     $columnField = new DropdownField('FieldNameFilter', '');
     $columnField->setSource($this->columns);
     $columnField->setEmptyString(_t('UserFormsGridFieldFilterHeader.FILTERSUBMISSIONS', 'Filter Submissions..'));
     $columnField->setHasEmptyDefault(true);
     $columnField->setValue($selectedField);
     $valueField = new TextField('FieldValue', '', $selectedValue);
     $columnField->addExtraClass('ss-gridfield-sort');
     $columnField->addExtraClass('no-change-track');
     $valueField->addExtraClass('ss-gridfield-sort');
     $valueField->addExtraClass('no-change-track');
     $valueField->setAttribute('placeholder', _t('UserFormsGridFieldFilterHeader.WHEREVALUEIS', 'where value is..'));
     $fields->push(new FieldGroup(new CompositeField($columnField, $valueField)));
     $fields->push(new FieldGroup(new CompositeField($start = new DateField('StartFilter', 'From'), $end = new DateField('EndFilter', 'Till'))));
     foreach (array($start, $end) as $date) {
         $date->setConfig('showcalendar', true);
         $date->setConfig('dateformat', 'y-mm-dd');
         $date->setConfig('datavalueformat', 'y-mm-dd');
         $date->addExtraClass('no-change-track');
     }
     $end->setValue($state->end);
     $start->setValue($state->start);
     $fields->push($actions = new FieldGroup(GridField_FormAction::create($gridField, 'filter', false, 'filter', null)->addExtraClass('ss-gridfield-button-filter')->setAttribute('title', _t('GridField.Filter', "Filter"))->setAttribute('id', 'action_filter_' . $gridField->getModelClass() . '_' . $columnField), GridField_FormAction::create($gridField, 'reset', false, 'reset', null)->addExtraClass('ss-gridfield-button-close')->setAttribute('title', _t('GridField.ResetFilter', "Reset"))->setAttribute('id', 'action_reset_' . $gridField->getModelClass() . '_' . $columnField)));
     $actions->addExtraClass('filter-buttons');
     $actions->addExtraClass('no-change-track');
     $forTemplate = new ArrayData(array('Fields' => $fields));
     return array('header' => $forTemplate->renderWith('GridFieldFilterHeader_Row'));
 }