/**
  * This may need to be optimised. We'll just have to see how it performs.
  *
  * @param SS_HTTPRequest $req
  * @return array
  */
 public function downloads(SS_HTTPRequest $req)
 {
     $downloads = new ArrayList();
     $member = Member::currentUser();
     if (!$member || !$member->exists()) {
         $this->httpError(401);
     }
     // create a dropdown for sorting
     $sortOptions = Config::inst()->get('DownloadableAccountPageController', 'sort_options');
     if ($sortOptions) {
         $sort = $req->requestVar('sort');
         if (empty($sort)) {
             reset($sortOptions);
             $sort = key($sortOptions);
         }
         $sortControl = new DropdownField('download-sort', 'Sort By:', $sortOptions, $sort);
     } else {
         $sort = 'PurchaseDate';
         $sortControl = '';
     }
     // create a list of downloads
     $orders = $member->getPastOrders();
     if (!empty($orders)) {
         foreach ($orders as $order) {
             if ($order->DownloadsAvailable()) {
                 $downloads->merge($order->getDownloads());
             }
         }
     }
     Requirements::javascript(SHOP_DOWNLOADABLE_FOLDER . '/javascript/AccountPage_downloads.js');
     return array('Title' => 'Digital Purchases', 'Content' => '', 'SortControl' => $sortControl, 'HasDownloads' => $downloads->count() > 0, 'Downloads' => $downloads->sort($sort));
 }
 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");
 }
    public function BlogTags()
    {
        if ($newsIndex = $this->NewsIndex()) {
            $alRet = new ArrayList();
            $arrTags = array();
            $strTable = Versioned::current_stage() == 'Stage' ? 'NewsPost' : 'NewsPost_Live';
            $results = DB::query('SELECT `Tags` AS Tags, COUNT(1) AS Items
				FROM ' . $strTable . '
				WHERE `Tags` IS NOT NULL
				GROUP BY Tags');
            while ($row = $results->nextRecord()) {
                $arrCurrentItems = explode(',', $row['Tags']);
                foreach ($arrCurrentItems as $strItem) {
                    $strItem = trim($strItem);
                    $strLower = strtolower($strItem);
                    if (!array_key_exists($strLower, $arrTags)) {
                        $arrTags[$strLower] = new ArrayData(array('Tag' => $strItem, 'Count' => $row['Items'], 'Link' => $newsIndex->Link('tag/' . urlencode($strItem))));
                    } else {
                        $arrayData = $arrTags[$strLower];
                        $arrayData->Count += $row['Items'];
                    }
                }
            }
            foreach ($arrTags as $arrTag) {
                $alRet->push($arrTag);
            }
            return $alRet->sort('Count')->limit(SiteConfig::current_site_config()->NumberOfTags ?: PHP_INT_MAX);
        }
    }
 /**
  * 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;
 }
Example #5
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;
 }
 /**
  * takes a DataList of Rateable DataObjects and sorts them by their average score 
  * @param DataList $list
  * @return ArrayList
  **/
 public function sortByRating(DataList $list, $dir = 'DESC')
 {
     $items = new ArrayList($list->toArray());
     foreach ($items as $item) {
         $score = $item->getAverageScore();
         $item->Score = $score ? $score : 0;
         $item->Title = $item->Title;
     }
     return $items->sort('Score', $dir);
 }
Example #7
0
 function testSortObjectsComparator()
 {
     $oList = new ArrayList("SampleSortableObject");
     $oList->add(new SampleSortableObject(new String("b")));
     $oList->add(new SampleSortableObject(new String("a")));
     $oList->add(new SampleSortableObject(new String("c")));
     $oList->sort(new SampleSortableObjectComparator());
     $this->assertEqual(new String("c"), $oList->get(0)->getField());
     $this->assertEqual(new String("b"), $oList->get(1)->getField());
     $this->assertEqual(new String("a"), $oList->get(2)->getField());
 }
Example #8
0
 public function sortedOptions()
 {
     $options = $this->Options();
     $newList = new ArrayList();
     // Add to new list
     foreach ($options as $option) {
         //$option->Position = $option->getPos();
         $newList->add($option);
         $newList->byID($option->ID)->Position = $option->getPos();
     }
     return $newList->sort('Position DESC');
 }
 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 getDockedBlocks()
 {
     $blocks = Block::get()->filter(array('showBlockbyClass' => true));
     $blocks_map = $blocks->map('ID', 'shownInClass');
     foreach ($blocks_map as $blockID => $Classes) {
         $Classes = explode(',', $Classes);
         if (!in_array($this->owner->ClassName, $Classes)) {
             $blocks = $blocks->exclude('ID', $blockID);
         }
     }
     $published_blocks = new ArrayList();
     foreach ($blocks as $block) {
         if ($block->isPublished()) {
             $published_blocks->push($block);
         }
     }
     return $published_blocks->sort('SortOrder', 'ASC');
 }
 function FutureEvents($num, $filter = '')
 {
     if ($this->event_manager == null) {
         $this->buildEventManager();
     }
     $filterLowerCase = strtolower($filter);
     $events_array = new ArrayList();
     if ($filterLowerCase != 'other') {
         $filter_array = array('EventEndDate:GreaterThanOrEqual' => date('Y-m-d'));
         if (strtolower($filter) != 'all' && $filter != '') {
             $filter_array['EventCategory'] = $filter;
         }
         $pulled_events = EventPage::get()->filter($filter_array)->sort('EventStartDate', 'ASC')->limit($num)->toArray();
     } else {
         $pulled_events = EventPage::get()->where("EventCategory is null and EventEndDate >= CURDATE()")->sort('EventStartDate', 'ASC')->limit($num)->toArray();
     }
     $events_array->merge($pulled_events);
     return $events_array->sort('EventStartDate', 'ASC')->limit($num, 0)->toArray();
 }
 function getEstimates()
 {
     if ($this->calculated) {
         return $this->estimates;
     }
     $output = new ArrayList();
     if ($options = $this->getShippingMethods()) {
         foreach ($options as $option) {
             $rate = $option->getCalculator($this->order)->calculate($this->address);
             if ($rate !== null) {
                 $option->CalculatedRate = $rate;
                 $output->push($option);
             }
         }
     }
     $output->sort("CalculatedRate", "ASC");
     //sort by rate, lowest to highest
     // cache estimates
     $this->estimates = $output;
     $this->calculated = true;
     return $output;
 }
	function sourceRecords($params, $sort, $limit) {
		$join = '';
		$sortBrokenReason = false;
		if($sort) {
			$parts = explode(' ', $sort);
			$field = $parts[0];
			$direction = $parts[1];
			
			if($field == 'AbsoluteLink') {
				$sort = 'URLSegment ' . $direction;
			} elseif($field == 'Subsite.Title') {
				$join = 'LEFT JOIN "Subsite" ON "Subsite"."ID" = "SiteTree"."SubsiteID"';
			} elseif($field == 'BrokenReason') {
				$sortBrokenReason = true;
				$sort = '';
			}
		}
		$q = DB::USE_ANSI_SQL ? '"' : '`';
		if (!isset($_REQUEST['CheckSite']) || $params['CheckSite'] == 'Published') $ret = Versioned::get_by_stage('SiteTree', 'Live', "({$q}SiteTree{$q}.{$q}HasBrokenLink{$q} = 1 OR {$q}SiteTree{$q}.{$q}HasBrokenFile{$q} = 1)", $sort, $join, $limit);
		else $ret = DataObject::get('SiteTree', "({$q}SiteTree{$q}.{$q}HasBrokenFile{$q} = 1 OR {$q}HasBrokenLink{$q} = 1)", $sort, $join, $limit);
		
		$returnSet = new ArrayList();
		if ($ret) foreach($ret as $record) {
			$reason = false;
			$isRedirectorPage = in_array($record->ClassName, ClassInfo::subclassesFor('RedirectorPage'));
			$isVirtualPage = in_array($record->ClassName, ClassInfo::subclassesFor('VirtualPage'));
			
			if ($isVirtualPage) {
				if ($record->HasBrokenLink) {
					$reason = _t('BrokenLinksReport.VirtualPageNonExistent', "virtual page pointing to non-existent page");
					$reasonCodes = array("VPBROKENLINK");
				}
			} else if ($isRedirectorPage) {
				if ($record->HasBrokenLink) {
					$reason = _t('BrokenLinksReport.RedirectorNonExistent', "redirector page pointing to non-existent page");
					$reasonCodes = array("RPBROKENLINK");
				}
			} else {
				if ($record->HasBrokenLink && $record->HasBrokenFile) {
					$reason = _t('BrokenLinksReport.HasBrokenLinkAndFile', "has broken link and file");
					$reasonCodes = array("BROKENFILE", "BROKENLINK");
				} else if ($record->HasBrokenLink && !$record->HasBrokenFile) {
					$reason = _t('BrokenLinksReport.HasBrokenLink', "has broken link");
					$reasonCodes = array("BROKENLINK");
				} else if (!$record->HasBrokenLink && $record->HasBrokenFile) {
					$reason = _t('BrokenLinksReport.HasBrokenFile', "has broken file");
					$reasonCodes = array("BROKENFILE");
				}
			}
			
			if ($reason) {
				if (isset($params['Reason']) && $params['Reason'] && !in_array($params['Reason'], $reasonCodes)) continue;
				$record->BrokenReason = $reason;
				$returnSet->push($record);
			}
		}
		
		if($sortBrokenReason) $returnSet->sort('BrokenReason', $direction);
		
		return $returnSet;
	}
 public function ExportFullSchedule()
 {
     $sort = $this->getRequest()->getVar('sort') ? $this->getRequest()->getVar('sort') : 'day';
     $show_desc = $this->getRequest()->getVar('show_desc') ? $this->getRequest()->getVar('show_desc') : false;
     $base = Director::protocolAndHost();
     if (is_null($this->Summit())) {
         return $this->httpError(404, 'Sorry, summit not found');
     }
     $schedule = $this->Summit()->getSchedule();
     $events = new ArrayList();
     $sort_list = false;
     foreach ($schedule as $event) {
         switch ($sort) {
             case 'day':
                 $group_label = $event->getDayLabel();
                 break;
             case 'track':
                 if (!$event->isPresentation() || !$event->Category() || !$event->Category()->Title) {
                     continue 2;
                 }
                 $group_label = $event->Category()->Title;
                 $sort_list = true;
                 break;
             case 'event_type':
                 $group_label = $event->Type->Type;
                 $sort_list = true;
                 break;
         }
         if ($group_array = $events->find('Group', $group_label)) {
             $group_array->Events->push($event);
         } else {
             $group_array = new ArrayData(array('Group' => $group_label, 'Events' => new ArrayList()));
             $group_array->Events->push($event);
             $events->push($group_array);
         }
     }
     if ($sort_list) {
         $events->sort('Group');
     }
     $html_inner = $this->renderWith(array('SummitAppMySchedulePage_pdf'), array('Schedule' => $events, 'Summit' => $this->Summit(), 'ShowDescription' => $show_desc, 'Heading' => 'Full Schedule by ' . $sort));
     $css = @file_get_contents($base . "/summit/css/summitapp-myschedule-pdf.css");
     //create pdf
     $file = FileUtils::convertToFileName('full-schedule') . '.pdf';
     $html_outer = sprintf("<html><head><style>%s</style></head><body><div class='container'>%s</div></body></html>", $css, $html_inner);
     try {
         $html2pdf = new HTML2PDF('P', 'A4', 'en', true, 'UTF-8', array(15, 5, 15, 5));
         $html2pdf->setTestIsImage(false);
         $html2pdf->WriteHTML($html_outer);
         //clean output buffer
         ob_end_clean();
         $html2pdf->Output($file, "D");
     } catch (HTML2PDF_exception $e) {
         $message = array('errno' => '', 'errstr' => $e->__toString(), 'errfile' => 'SummitAppSchedPage.php', 'errline' => '', 'errcontext' => '');
         SS_Log::log($message, SS_Log::ERR);
         $this->httpError(404, 'There was an error on PDF generation!');
     }
 }
 /**
  * Generate a list of all the pages in the documentation grouped by the first letter of the page.
  * @return {GroupedList}
  */
 public function AllPages()
 {
     $pages = $this->getManifest()->getPages();
     $output = new ArrayList();
     $baseLink = Config::inst()->get('DocumentationViewer', 'link_base');
     foreach ($pages as $url => $page) {
         $first = strtoupper(trim(substr($page['title'], 0, 1)));
         if ($first) {
             $output->push(new ArrayData(array('Link' => Controller::join_links($baseLink, $url), 'Title' => $page['title'], 'FirstLetter' => $first)));
         }
     }
     return GroupedList::create($output->sort('Title', 'ASC'));
 }
 /**
  * @param array $params
  *
  * @return SS_List
  */
 public function sourceRecords($params = array())
 {
     Versioned::reading_stage("Stage");
     $records = SiteTree::get();
     $compatibility = ContentReviewCompatability::start();
     if (empty($params["ReviewDateBefore"]) && empty($params["ReviewDateAfter"])) {
         // If there's no review dates set, default to all pages due for review now
         $reviewDate = new Zend_Date(SS_Datetime::now()->Format("U"));
         $reviewDate->add(1, Zend_Date::DAY);
         $records = $records->where(sprintf('"NextReviewDate" < \'%s\'', $reviewDate->toString("YYYY-MM-dd")));
     } else {
         // Review date before
         if (!empty($params['ReviewDateBefore'])) {
             // TODO Get value from DateField->dataValue() once we have access to form elements here
             $reviewDate = new Zend_Date($params["ReviewDateBefore"], Config::inst()->get("i18n", "date_format"));
             $reviewDate->add(1, Zend_Date::DAY);
             $records = $records->where(sprintf("\"NextReviewDate\" < '%s'", $reviewDate->toString("YYYY-MM-dd")));
         }
         // Review date after
         if (!empty($params["ReviewDateAfter"])) {
             // TODO Get value from DateField->dataValue() once we have access to form elements here
             $reviewDate = new Zend_Date($params["ReviewDateAfter"], Config::inst()->get("i18n", "date_format"));
             $records = $records->where(sprintf("\"NextReviewDate\" >= '%s'", $reviewDate->toString("YYYY-MM-dd")));
         }
     }
     // Show virtual pages?
     if (empty($params["ShowVirtualPages"])) {
         $virtualPageClasses = ClassInfo::subclassesFor("VirtualPage");
         $records = $records->where(sprintf("\"SiteTree\".\"ClassName\" NOT IN ('%s')", implode("','", array_values($virtualPageClasses))));
     }
     // Owner dropdown
     if (!empty($params["ContentReviewOwner"])) {
         $ownerNames = Convert::raw2sql($params["ContentReviewOwner"]);
         $records = $records->filter("OwnerNames:PartialMatch", $ownerNames);
     }
     $records = new ArrayList($records->sort("NextReviewDate", "DESC")->toArray());
     ContentReviewCompatability::done($compatibility);
     return $records;
 }
 /**
  * Generate a list of all the pages in the documentation grouped by the
  * first letter of the page.
  *
  * @return GroupedList
  */
 public function AllPages()
 {
     $pages = $this->getManifest()->getPages();
     $output = new ArrayList();
     foreach ($pages as $url => $page) {
         $first = strtoupper(trim(substr($page['title'], 0, 1)));
         if ($first) {
             $output->push(new ArrayData(array('Link' => $url, 'Title' => $page['title'], 'FirstLetter' => $first)));
         }
     }
     return GroupedList::create($output->sort('Title', 'ASC'));
 }
 public function testSortSimpleDESCOrder()
 {
     $list = new ArrayList(array(array('Name' => 'Steve'), (object) array('Name' => 'Bob'), array('Name' => 'John')));
     // Sort two arguments
     $list1 = $list->sort('Name', 'DESC');
     $this->assertEquals($list1->toArray(), array(array('Name' => 'Steve'), array('Name' => 'John'), (object) array('Name' => 'Bob')));
     // Sort single string
     $list2 = $list->sort('Name desc');
     $this->assertEquals($list2->toArray(), array(array('Name' => 'Steve'), array('Name' => 'John'), (object) array('Name' => 'Bob')));
     // Sort quoted string
     $list3 = $list->sort('"Name" DESCENDING');
     $this->assertEquals($list3->toArray(), array(array('Name' => 'Steve'), array('Name' => 'John'), (object) array('Name' => 'Bob')));
     // Sort array specifier
     $list4 = $list->sort(array('Name' => 'descending'));
     $this->assertEquals($list4->toArray(), array(array('Name' => 'Steve'), array('Name' => 'John'), (object) array('Name' => 'Bob')));
     // Check original list isn't altered
     $this->assertEquals($list->toArray(), array(array('Name' => 'Steve'), (object) array('Name' => 'Bob'), array('Name' => 'John')));
 }
Example #19
0
	/**
	 * Populates an array of classes in the CMS
	 * which allows the user to change the page type.
	 *
	 * @return SS_List
	 */
	public function PageTypes() {
		$classes = SiteTree::page_type_classes();

		$result = new ArrayList();

		foreach($classes as $class) {
			$instance = singleton($class);

			if($instance instanceof HiddenClass) continue;

			if(!$instance->canCreate()) continue;

			// skip this type if it is restricted
			if($instance->stat('need_permission') && !$this->can(singleton($class)->stat('need_permission'))) continue;

			$addAction = $instance->i18n_singular_name();
			
			// Get description
			$description = _t($class . 'DESCRIPTION');
			if(!$description) $description = $instance->uninherited('description');
			if($class == 'Page' && !$description) $description = singleton('SiteTree')->uninherited('description');
			
			$result->push(new ArrayData(array(
				'ClassName' => $class,
				'AddAction' => $addAction,
				'Description' => $description,
				// TODO Sprite support
				'IconURL' => $instance->stat('icon')
			)));
		}
		
		$result->sort('AddAction');
		return $result;
	}
 /**
  * @param int $limit
  * @return DataList
  */
 function getNewsItemsFromSource($limit = 20)
 {
     $rss_news = null;
     $return_array = new ArrayList();
     $outsourced_limit = 10;
     $rss_news = $this->getRssItems($outsourced_limit)->toArray();
     foreach ($rss_news as $item) {
         $pubDate = DateTime::createFromFormat("D, j M Y H:i:s O", $item->pubDate)->setTimezone(new DateTimeZone("UTC"));
         $ss_pubDate = new SS_Datetime();
         $ss_pubDate->setValue($pubDate->format("Y-m-d H:i:s"));
         $rss_news = new RssNews();
         $rss_news->Date = $ss_pubDate;
         $rss_news->Headline = $item->title;
         $rss_news->Link = $item->link;
         $rss_news->Category = 'Planet';
         $return_array->push($rss_news);
     }
     $blog_news = $this->getBlogItems($outsourced_limit)->toArray();
     foreach ($blog_news as $item) {
         $pubDate = DateTime::createFromFormat("D, j M Y H:i:s O", $item->pubDate)->setTimezone(new DateTimeZone("UTC"));
         $ss_pubDate = new SS_Datetime();
         $ss_pubDate->setValue($pubDate->format("Y-m-d H:i:s"));
         $rss_news = new RssNews();
         $rss_news->Date = $ss_pubDate;
         $rss_news->Headline = $item->title;
         $rss_news->Link = $item->link;
         $rss_news->Category = 'Blog';
         $return_array->push($rss_news);
     }
     $superuser_news = $this->getSuperUserItems($outsourced_limit)->toArray();
     foreach ($superuser_news as $item) {
         $pubDate = DateTime::createFromFormat("Y-m-j\\TH:i:sO", $item->pubDate)->setTimezone(new DateTimeZone("UTC"));
         $ss_pubDate = new SS_Datetime();
         $ss_pubDate->setValue($pubDate->format("Y-m-d H:i:s"));
         $rss_news = new RssNews();
         $rss_news->Date = $ss_pubDate;
         $rss_news->Headline = $item->title;
         $rss_news->Link = $item->link;
         $rss_news->Category = 'Superuser';
         $return_array->push($rss_news);
     }
     return $return_array->sort('Date', 'DESC')->limit($limit, 0);
 }
Example #21
0
 function NewsItems($limit = 20)
 {
     $repository = new SapphireRssNewsRepository();
     $tx_manager = SapphireTransactionManager::getInstance();
     $rss_news_manager = new RssNewsManager($repository, $tx_manager);
     $return_array = new ArrayList();
     $group_array = $rss_news_manager->getNewsItemsFromDatabaseGroupedByCategory();
     for ($i = 0; $i < 7 && $i < count($group_array[RssNews::SuperUser]); $i++) {
         $item = $group_array[RssNews::SuperUser][$i];
         $return_array->push(array('type' => $item->Category, 'link' => $item->Link, 'title' => $item->Headline, 'pubdate' => date('D, M jS Y', strtotime($item->Date)), 'rawpubdate' => $item->Date));
     }
     for ($i = 0; $i < 3 && $i < count($group_array[RssNews::Planet]); $i++) {
         $item = $group_array[RssNews::Planet][$i];
         $return_array->push(array('type' => $item->Category, 'link' => $item->Link, 'title' => $item->Headline, 'pubdate' => date('D, M jS Y', strtotime($item->Date)), 'rawpubdate' => $item->Date));
     }
     /*for ($i = 0; $i < 3 && $i < count($group_array[RssNews::Blog]); $i++ ) {
                 $item = $group_array[RssNews::Blog][$i];
     
                 $return_array->push(array('type' => $item->Category, 'link' => $item->Link, 'title' => $item->Headline,
                     'pubdate' => date('D, M jS Y', strtotime($item->Date)), 'rawpubdate' => $item->Date));
             }*/
     $rss_count = $return_array->count();
     $openstack_news = DataObject::get('News', "Approved = 1", "Date DESC", "", $limit - $rss_count)->toArray();
     foreach ($openstack_news as $item) {
         $art_link = 'news/view/' . $item->ID . '/' . $item->HeadlineForUrl;
         $return_array->push(array('type' => 'News', 'link' => $art_link, 'title' => $item->Headline, 'pubdate' => date('D, M jS Y', strtotime($item->Date)), 'rawpubdate' => $item->Date));
     }
     return $return_array->sort('rawpubdate', 'DESC')->limit($limit, 0);
 }
Example #22
0
 /**
  * Check that we don't cause recursion errors with array_multisort() and circular dependencies
  */
 public function testSortWithCircularDependencies()
 {
     $itemA = new stdClass();
     $childA = new stdClass();
     $itemA->child = $childA;
     $childA->parent = $itemA;
     $itemA->Sort = 1;
     $itemB = new stdClass();
     $childB = new stdClass();
     $itemB->child = $childB;
     $childB->parent = $itemB;
     $itemB->Sort = 1;
     $items = new ArrayList();
     $items->add($itemA);
     $items->add($itemB);
     // This call will trigger a fatal error if there are issues with circular dependencies
     $items->sort('Sort');
 }
Example #23
0
 public function testMultiSort()
 {
     $list = new ArrayList(array((object) array('Name' => 'Object1', 'F1' => 1, 'F2' => 2, 'F3' => 3), (object) array('Name' => 'Object2', 'F1' => 2, 'F2' => 1, 'F3' => 4), (object) array('Name' => 'Object3', 'F1' => 5, 'F2' => 2, 'F3' => 2)));
     $list->sort('F3', 'ASC');
     $this->assertEquals($list->first()->Name, 'Object3', 'Object3 should be first in the list');
     $list->sort('F3', 'DESC');
     $this->assertEquals($list->first()->Name, 'Object2', 'Object2 should be first in the list');
     $list->sort(array('F2' => 'ASC', 'F1' => 'ASC'));
     $this->assertEquals($list->last()->Name, 'Object3', 'Object3 should be last in the list');
     $list->sort(array('F2' => 'ASC', 'F1' => 'DESC'));
     $this->assertEquals($list->last()->Name, 'Object1', 'Object1 should be last in the list');
 }
Example #24
0
	public function testMultiSort() {
		$list = new ArrayList(array(
			(object) array('ID'=>3, 'Name'=>'Bert', 'Importance'=>1),
			(object) array('ID'=>1, 'Name'=>'Aron', 'Importance'=>2),
			(object) array('ID'=>2, 'Name'=>'Aron', 'Importance'=>1),
		));
		
		$list->sort(array('Name'=>'ASC', 'Importance'=>'ASC'));
		$this->assertEquals($list->first()->ID, 2, 'Aron.2 should be first in the list');
		$this->assertEquals($list->last()->ID, 3, 'Bert.3 should be last in the list');
		
		$list->sort(array('Name'=>'ASC', 'Importance'=>'DESC'));
		$this->assertEquals($list->first()->ID, 1, 'Aron.2 should be first in the list');
		$this->assertEquals($list->last()->ID, 3, 'Bert.3 should be last in the list');
	}
Example #25
0
 /**
  * Resolves static and dynamic authors linked to this post.
  *
  * @return ArrayList
  */
 public function getCredits()
 {
     $list = new ArrayList();
     $list->merge($this->getDynamicCredits());
     $list->merge($this->getStaticCredits());
     return $list->sort('Name');
 }
 public function getGroupedPlayerGames()
 {
     $reg = $this->getCurrentRegistration();
     if (!$reg) {
         return false;
     }
     $playergames = $reg->PlayerGames();
     $games = new ArrayList();
     foreach ($playergames as $playergame) {
         $games->push(new ArrayData(array("Game" => $playergame->Game(), "Preference" => $playergame->Preference, "Favourite" => $playergame->Favourite, "Status" => $playergame->Status, "Session" => $playergame->Game()->Session)));
     }
     $result = $games->sort(array('Session' => 'ASC', 'Preference' => 'ASC'));
     return GroupedList::create($result);
 }
Example #27
0
 /**
  * @return PaginatedList The list of "pending" data archives which are waiting for a file
  * to be delivered offline by post, and manually uploaded into the system.
  */
 public function PendingDataArchives()
 {
     $project = $this->getCurrentProject();
     $archives = new ArrayList();
     foreach ($project->DNEnvironmentList() as $env) {
         foreach ($env->DataArchives() as $archive) {
             if ($archive->canView() && $archive->isPending()) {
                 $archives->push($archive);
             }
         }
     }
     return new PaginatedList($archives->sort("Created", "DESC"), $this->request);
 }
 /**
  * Adds the CMS fields for the ColorScheme setting.
  * 
  * @param FieldList $fields Fields to update
  * 
  * @return void
  *
  * @author Sebastian Diel <*****@*****.**>
  * @since 26.09.2014
  */
 public function getCMSFieldsForColorScheme(FieldList $fields)
 {
     $colorSchemePath = Director::baseFolder() . '/silvercart/css';
     if (is_dir($colorSchemePath)) {
         if ($handle = opendir($colorSchemePath)) {
             $colorSchemes = new ArrayList();
             while (false !== ($entry = readdir($handle))) {
                 if (substr($entry, -4) != '.css') {
                     continue;
                 }
                 if (substr($entry, 0, 6) != 'color_') {
                     continue;
                 }
                 $colorSchemeName = substr($entry, 6, -4);
                 $colorSchemeFile = $colorSchemePath . '/' . $entry;
                 $lines = file($colorSchemeFile);
                 $backgroundColors = array();
                 $fontColors = array();
                 foreach ($lines as $line) {
                     if (strpos(strtolower($line), 'background-color') !== false && preg_match('/#[a-z|A-Z|0-9]{3,6}/', $line, $matches)) {
                         $backgroundColors[$matches[0]] = new ArrayData(array('Color' => $matches[0]));
                     } elseif (strpos(strtolower(trim($line)), 'color') === 0 && preg_match('/#[a-z|A-Z|0-9]{3,6}/', $line, $matches)) {
                         $fontColors[$matches[0]] = new ArrayData(array('Color' => $matches[0]));
                     }
                 }
                 $colorSchemes->push(new ArrayData(array('Name' => $colorSchemeName, 'Title' => _t('SilvercartConfig.ColorScheme_' . $colorSchemeName, ucfirst($colorSchemeName)), 'BackgroundColors' => new ArrayList($backgroundColors), 'FontColors' => new ArrayList($fontColors), 'IsActive' => $this->owner->ColorScheme == $colorSchemeName)));
             }
             closedir($handle);
         }
         $colorSchemes->sort('Title');
         $fields->removeByName('ColorScheme');
         $logoField = new UploadField('SilvercartLogo', $this->owner->fieldLabel('SilvercartLogo'));
         $logoField->setDescription($this->owner->fieldLabel('SilvercartLogoDesc'));
         // Build color scheme toggle group
         $colorSchemeConfigurationField = ToggleCompositeField::create('ColorSchemeConfiguration', $this->owner->fieldLabel('ColorSchemeConfiguration'), array($fields->dataFieldByName('Title'), $fields->dataFieldByName('Tagline'), $fields->dataFieldByName('Theme'), $logoField, new LiteralField('ColorScheme', $this->owner->customise(array('ColorSchemes' => $colorSchemes))->renderWith('ColorSchemeField'))))->setHeadingLevel(4)->setStartClosed(true);
         $fields->removeByName('Title');
         $fields->removeByName('Tagline');
         $fields->removeByName('Theme');
         $fields->addFieldToTab('Root.Main', $colorSchemeConfigurationField);
     } else {
         $fields->removeByName('ColorScheme');
     }
 }