/**
  *
  * @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;
 }
예제 #2
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;
 }
 /**
  * @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'));
 }
 /**
  * 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 SplitSetIntoGridRows($itemsInGridMethod, $numberOfCols)
 {
     error_log("GRID ROWS");
     $itemsInGrid = $this->owner->{$itemsInGridMethod}();
     $position = 1;
     $columns = new ArrayList();
     $result = new ArrayList();
     foreach ($itemsInGrid as $key => $item) {
         $columns->push($item);
         error_log("Comparing position {$position} > number of cols {$numberOfCols}");
         if ($position >= $numberOfCols) {
             error_log("NEW ROW");
             $position = 1;
             $row = new ArrayList();
             $row->Columns = $columns;
             $result->push($row);
             $columns = new ArrayList();
         } else {
             $position = $position + 1;
         }
     }
     if ($columns->Count() > 0) {
         $row = new ArrayList();
         $row->Columns = $columns;
         $result->push($row);
     }
     // FIXME add padding?
     return $result;
     //$result = new DataObjectSet();
 }
 /**
  * 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;
     }
 }
 /**
  * Setup the list of records to show.
  * @param array $params array of filter-rules.
  * @param array $sort
  * @param integer $limit
  * @return ArrayList with the records.
  */
 public function sourceRecords($params, $sort, $limit)
 {
     if ($sort) {
         $parts = explode(' ', $sort);
         $field = $parts[0];
         $direction = $parts[1];
     }
     $filter = array('Comments.ID:GreaterThan' => 0);
     if (count($params) > 0 && isset($params['Title'])) {
         $filter['News.Title:PartialMatch'] = $params['Title'];
     }
     $ret = News::get()->filter($filter);
     $returnSet = new ArrayList();
     if ($ret) {
         foreach ($ret as $record) {
             $record->Commentcount = $record->Comments()->count();
             $record->Spamcount = $record->Comments()->filter(array('AkismetMarked' => 1))->count();
             $record->Hiddencount = $record->Comments()->filter(array('AkismetMarked' => 0, 'Visible' => 0))->count();
             if (isset($params['Comment']) && $params['Comment'] == 'SPAMCOUNT' && $record->Spamcount > 0) {
                 $returnSet->push($record);
             } elseif (isset($params['Comment']) && $params['Comment'] == 'HIDDENCOUNT' && $record->Hiddencount > 0) {
                 $returnSet->push($record);
             } elseif (isset($params['Comment']) && $params['Comment'] == '' || !isset($params['Comment'])) {
                 $returnSet->push($record);
             }
         }
     }
     return $returnSet;
 }
 /**
  * returns sorted User Agreements to be signed
  * @return ArrayList UserAgreement's required
  **/
 public function unsignedAgreements()
 {
     // are there any required agreements for this users groups?
     $groupIDs = $this->owner->Groups()->getIdList();
     $agreementsRemaining = new ArrayList();
     $requiredAgreements = $groupIDs ? UserAgreement::get()->filter('Archived', false)->filterAny('GroupID', $groupIDs) : null;
     $this->owner->extend('updateRequiredAgreements', $requiredAgreements);
     // collect agreements to be signed - checking agreement type (one off vs session)
     if ($requiredAgreements) {
         //Flush the component cache - which causes the First Agreement for each Member to be shown twice on the first occurrence
         $this->owner->flushCache();
         $signedAgreements = $this->owner->SignedAgreements();
         foreach ($requiredAgreements as $required) {
             if (!$signedAgreements->find('UserAgreementID', $required->ID)) {
                 $agreementsRemaining->push($required);
             } else {
                 if ($required->Type == 'Every Login') {
                     $signings = $this->owner->SignedAgreements("UserAgreementID='" . $required->ID . "'");
                     if (!$signings->find('SessionID', session_id())) {
                         $agreementsRemaining->push($required);
                     }
                 }
             }
         }
         $agreementsRemaining->sort('Sort', 'ASC');
     }
     return $agreementsRemaining;
 }
 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;
     }
 }
 /**
  *
  * @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]);
             }
         }
         $record = $this->form->getRecord();
         $availableWidgets = null;
         $restrictedWidgets = null;
         if ($record) {
             $availableWidgets = $record->config()->available_widgets;
             $restrictedWidgets = $record->config()->restricted_widgets;
         }
         foreach ($classes as $class) {
             if (!empty($availableWidgets) && is_array($availableWidgets) && !in_array($class, $availableWidgets) || !empty($restrictedWidgets) && is_array($restrictedWidgets) && in_array($class, $restrictedWidgets)) {
                 continue;
             }
             $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;
 }
예제 #11
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);
 }
 public function testConvertDataObjectSet()
 {
     $do = $this->getDataObjectStub(array('getAllowedFields', 'DynamicField'), array('Title' => 'This is a test title', 'Something' => 'Not allowed'));
     $do->expects($this->any())->method('getAllowedFields')->will($this->returnValue(array('Title', 'DynamicField')));
     $do->expects($this->any())->method('DynamicField')->will($this->returnValue('Test'));
     $formatter = $this->getFormatterStub();
     $dos = new ArrayList();
     $dos->push(clone $do);
     $dos->push(clone $do);
     $this->assertEquals(array(array('Title' => 'This is a test title', 'DynamicField' => 'Test'), array('Title' => 'This is a test title', 'DynamicField' => 'Test')), $formatter->convertDataObjectSet($dos));
 }
 /**
  * Inserts manually added blocks at front of list.
  *
  * @param \ArrayList|\DataList $items
  * @param                      $filters
  * @param array                $parameters
  */
 public function sequenceGridListItems(&$items, $filters, &$parameters = [])
 {
     $out = new \ArrayList();
     $blocks = $this->related()->Sort('Sort desc');
     foreach ($blocks as $block) {
         $out->push($block);
     }
     foreach ($items as $item) {
         $out->push($item);
     }
     $items = $out;
 }
예제 #14
0
 public function getEventsContainer($number)
 {
     $events = $this->getEvents()->limit($number)->toArray();
     $eventsAll = new ArrayList();
     for ($i = 0; $i < $number; $i++) {
         if (array_key_exists($i, $events)) {
             $eventsAll->push($events[$i]);
         } else {
             $eventsAll->push(null);
         }
     }
     return $eventsAll;
 }
 public function InlineGalleries()
 {
     $result = new ArrayList();
     // find child galleries
     foreach ($this->owner->AllChildren() as $child) {
         if ($child->ClassName == 'GalleryPage') {
             $result->push($child);
         }
     }
     if ($this->owner->AttachedGalleryID != 0) {
         $result->push($this->owner->AttachedGallery());
     }
     return $result;
 }
 public function GetItems(ArrayList $photoset)
 {
     $photos = PhotoItem::get()->filter("PhotoAlbumID", $this->owner->ID);
     if ($photos) {
         foreach ($photos as $photo) {
             if ($photo->getComponent("Photo")->exists()) {
                 $photoset->push($photo);
             } elseif ($photo->getComponent("VideoItem")->exists()) {
                 $photoset->push($photo);
             }
         }
     }
     return $photoset;
 }
 /**
  * Get all discounts that have been applied to an order.
  *
  * @return ArrayList
  */
 public function Discounts()
 {
     $discounts = Discount::get()->leftJoin("OrderDiscountModifier_Discounts", "\"Discount\".\"ID\" = \"OrderDiscountModifier_Discounts\".\"DiscountID\"")->innerJoin("OrderAttribute", "(\"OrderDiscountModifier_Discounts\".\"OrderDiscountModifierID\" = \"OrderAttribute\".\"ID\")")->filter("OrderAttribute.OrderID", $this->owner->ID);
     $finalDiscounts = new ArrayList();
     foreach ($discounts as $discount) {
         $finalDiscounts->push($discount);
     }
     foreach ($this->owner->Items() as $item) {
         foreach ($item->Discounts() as $discount) {
             $finalDiscounts->push($discount);
         }
     }
     $finalDiscounts->removeDuplicates();
     return $finalDiscounts;
 }
 /**
  * @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);
         }
     }
 }
 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;
 }
 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;
 }
 /**
  *@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;
 }
예제 #22
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;
	}
 /**
  * Adds a registered nested form
  *
  * @param CustomHtmlForm $registeredNestedForm Registered newsted form
  * 
  * @return void
  * 
  * @author Sebastian Diel <*****@*****.**>
  * @since 15.07.2011
  */
 public function addRegisteredNestedForm(CustomHtmlForm $registeredNestedForm)
 {
     if (empty($this->registeredNestedForms)) {
         $this->registeredNestedForms = new ArrayList();
     }
     $this->registeredNestedForms->push($registeredNestedForm);
 }
 /**
  * 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;
 }
 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");
 }
예제 #26
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();
		}	
	}
 /**
  * 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;
         }
     }
 }
 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;
 }
 /**
  * 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;
 }
예제 #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'));
 }