Пример #1
0
	function FeedItems() {
		$output = new DataObjectSet();
		
		include_once(Director::getAbsFile(SAPPHIRE_DIR . '/thirdparty/simplepie/SimplePie.php'));
		
		$t1 = microtime(true);
		$this->feed = new SimplePie($this->AbsoluteRssUrl, TEMP_FOLDER);
		$this->feed->init();
		if($items = $this->feed->get_items(0, $this->NumberToShow)) {
			foreach($items as $item) {
				
				// Cast the Date
				$date = new Date('Date');
				$date->setValue($item->get_date());

				// Cast the Title
				$title = new Text('Title');
				$title->setValue($item->get_title());

				$output->push(new ArrayData(array(
					'Title' => $title,
					'Date' => $date,
					'Link' => $item->get_link()
				)));
			}
			return $output;
		}
	}
 public function getCMSFields()
 {
     $fields = parent::getCMSFields();
     $createdDate = new Date();
     $createdDate->setValue($this->Created);
     $reviewer = $this->Member()->Name;
     $email = $this->Member()->Email;
     $star = "★";
     $emptyStar = "☆";
     $fields->insertBefore(LiteralField::create('reviewer', '<p>Written by <strong>' . $this->getMemberDetails() . '</strong><br />' . $createdDate->Format('l F jS Y h:i:s A') . '</p>'), 'Title');
     $fields->insertBefore(CheckboxField::create('Approved'), 'Title');
     $starRatings = $this->StarRatings();
     foreach ($starRatings as $starRating) {
         $cat = $starRating->StarRatingCategory;
         $stars = str_repeat($star, $starRating->Rating);
         $ratingStars = $stars;
         $maxRating = $starRating->MaxRating - $starRating->Rating;
         $emptyStarRepeat = str_repeat($emptyStar, $maxRating);
         $emptyStars = $emptyStarRepeat;
         /* 4/5 Stars */
         $ratingInfo = $ratingStars . $emptyStars . ' (' . $starRating->Rating . ' of ' . $starRating->MaxRating . ' Stars)';
         $fields->insertBefore(ReadonlyField::create('rating_' . $cat, $cat, html_entity_decode($ratingInfo, ENT_COMPAT, 'UTF-8')), 'Title');
     }
     $fields->removeByName('StarRatings');
     $fields->removeByName('MemberID');
     $fields->removeByName('ProductID');
     return $fields;
 }
 /**
  * Returns a list of months where blog posts are present.
  *
  * @return DataList
  */
 public function getArchive()
 {
     $query = $this->Blog()->getBlogPosts()->dataQuery();
     if ($this->ArchiveType == 'Yearly') {
         $query->groupBy('DATE_FORMAT("PublishDate", \'%Y\')');
     } else {
         $query->groupBy('DATE_FORMAT("PublishDate", \'%Y-%M\')');
     }
     $posts = $this->Blog()->getBlogPosts()->setDataQuery($query);
     if ($this->NumberToDisplay > 0) {
         $posts = $posts->limit($this->NumberToDisplay);
     }
     $archive = new ArrayList();
     if ($posts->count() > 0) {
         foreach ($posts as $post) {
             /**
              * @var BlogPost $post
              */
             $date = new Date();
             $date->setValue($post->PublishDate);
             if ($this->ArchiveType == 'Yearly') {
                 $year = $date->FormatI18N("%Y");
                 $month = null;
                 $title = $year;
             } else {
                 $year = $date->FormatI18N("%Y");
                 $month = $date->FormatI18N("%m");
                 $title = $date->FormatI18N("%B %Y");
             }
             $archive->push(new ArrayData(array('Title' => $title, 'Link' => Controller::join_links($this->Blog()->Link('archive'), $year, $month))));
         }
     }
     return $archive;
 }
 /**
  * Gets a list of all the items in the RSS feed given a user-provided URL, limit, and date format
  *
  * @return ArrayList
  */
 public function RSSItems()
 {
     if (!$this->FeedURL) {
         return false;
     }
     $doc = new DOMDocument();
     @$doc->load($this->FeedURL);
     $items = $doc->getElementsByTagName('item');
     $feeds = array();
     foreach ($items as $node) {
         $itemRSS = array('title' => $node->getElementsByTagName('title')->item(0)->nodeValue, 'desc' => $node->getElementsByTagName('description')->item(0)->nodeValue, 'link' => $node->getElementsByTagName('link')->item(0)->nodeValue, 'date' => $node->getElementsByTagName('pubDate')->item(0)->nodeValue);
         $feeds[] = $itemRSS;
     }
     $output = ArrayList::create(array());
     $count = 0;
     foreach ($feeds as $item) {
         if ($count >= $this->Count) {
             break;
         }
         // Cast the Date
         $date = new Date('Date');
         $date->setValue($item['date']);
         // Cast the Title
         $title = new Text('Title');
         $title->setValue($item['title']);
         $output->push(new ArrayData(array('Title' => $title, 'Date' => $date->Format($this->DateFormat), 'Link' => $item['link'])));
         $count++;
     }
     return $output;
 }
Пример #5
0
 function testLongDate()
 {
     /* "24 May 2006" style formatting of Date::Long() */
     $cases = array('2003-4-3' => '3 April 2003', '3/4/2003' => '3 April 2003');
     foreach ($cases as $original => $expected) {
         $date = new Date();
         $date->setValue($original);
         $this->assertEquals($expected, $date->Long());
     }
 }
 /**
  * @param GridField $grid
  * @return array
  */
 public function getHTMLFragments($grid)
 {
     $cols = new ArrayList();
     foreach ($grid->getColumns() as $name) {
         $meta = $grid->getColumnMetadata($name);
         $cols->push(new ArrayData(array('Name' => $name, 'Title' => $meta['title'])));
     }
     $days = new ArrayList();
     for ($i = 0; $i < 5; $i++) {
         $date = new Date();
         $date->setValue(date('d-m-Y', strtotime('+' . $i . ' days', strtotime($this->startDate))));
         $isHoliday = in_array($date->Format('Y-m-d'), $this->holidays);
         $days->push(new ArrayData(array('Day' => $date->Format('l'), 'IsHoliday' => $isHoliday)));
     }
     return array('header' => $cols->renderWith('RosterGridFieldTitleHeader', array('StartDate' => $this->startDate, 'Days' => $days)));
 }
 private function getNotifications($request)
 {
     $currentUserID = Member::currentUser()->ID;
     $notifications = MemberNotification::get()->innerJoin('MemberNotification_NotificationMembers', '"MemberNotification"."ID"="MemberNotification_NotificationMembers"."MemberNotificationID"')->where("\"MemberNotification_NotificationMembers\".\"MemberID\" = {$currentUserID}")->sort('LastEdited', 'DESC');
     $notificationArray = array();
     if ($notifications) {
         foreach ($notifications as $notification) {
             $notificationReadStatus = DB::query("Select ReadStatus FROM \"MemberNotification_NotificationMembers\"\n\t\t\t\t\tWHERE \"MemberNotificationID\" = {$notification->ID} AND \"MemberID\" = {$currentUserID} LIMIT 1")->value();
             $date = new Date();
             $date->setValue($notification->LastEdited);
             $user = Member::get()->byID($notification->CreatedByMemberID);
             $notificationArray[] = array("id" => $notification->ID, "title" => $notification->MemberNotificationTitle, "message" => $notification->MemberNotificationMessage, "date" => $date->Format('j M Y'), "user" => $user ? $user->FirstName . ' ' . $user->SurName : '', "read" => $notificationReadStatus);
         }
     }
     return $this->jsonPacket($notificationArray);
 }
 /**
  *
  *@return SQLQuery
  **/
 public function apply(DataQuery $query)
 {
     $value = $this->getValue();
     $date = new Date();
     $date->setValue($value);
     $distanceFromToday = time() - strtotime($value);
     $maxDays = round($distanceFromToday / ($this->divider * 2 * 86400)) + 1;
     $formattedDate = $date->format("Y-m-d");
     $db = DB::getConn();
     if ($db instanceof PostgreSQLDatabase) {
         // don't know whether functions should be used, hence the following code using an interval cast to an integer
         $query->where("(\"Order\".\"LastEdited\"::date - '{$formattedDate}'::date)::integer > -" . $maxDays . " AND (\"Order\".\"Created\"::date - '{$formattedDate}'::date)::integer < " . $maxDays);
     } else {
         // default is MySQL DATEDIFF() function - broken for others, each database conn type supported must be checked for!
         $query->where("(DATEDIFF(\"Order\".\"LastEdited\", '{$formattedDate}') > -" . $maxDays . " AND DATEDIFF(\"Order\".\"Created\", '{$formattedDate}') < " . $maxDays . ")");
     }
     return $query;
 }
 public function apply(SQLQuery $query)
 {
     $query = $this->applyRelation($query);
     $value = $this->getValue();
     $date = new Date();
     $date->setValue($value);
     $formattedDate = $date->format("Y-m-d");
     // changed for PostgreSQL compatability
     // NOTE - we may wish to add DATEDIFF function to PostgreSQL schema, it's just that this would be the FIRST function added for SilverStripe
     $db = DB::getConn();
     if ($db instanceof PostgreSQLDatabase) {
         // don't know whether functions should be used, hence the following code using an interval cast to an integer
         return $query->where("(\"Order\".\"Created\"::date - '{$formattedDate}'::date)::integer > -" . self::get_how_many_days_around() . " AND (\"Order\".\"Created\"::date - '{$formattedDate}'::date)::integer < " . self::get_how_many_days_around());
     } else {
         // default is MySQL DATEDIFF() function - broken for others, each database conn type supported must be checked for!
         return $query->where("(DATEDIFF(\"Order\".\"Created\", '{$formattedDate}') > -" . self::get_how_many_days_around() . " AND DATEDIFF(\"Order\".\"Created\", '{$formattedDate}') < " . self::get_how_many_days_around() . ")");
     }
 }
Пример #10
0
	function Dates() {
		Requirements::themedCSS('archivewidget');
		
		$results = new DataObjectSet();
		$blogHolder = $this->getBlogHolder();
		$id = $blogHolder->ID;
		
		$stage = Versioned::current_stage();
		$suffix = (!$stage || $stage == 'Stage') ? "" : "_$stage";

		
		if($this->DisplayMode == 'month') {
			$sqlResults = DB::query("SELECT DISTINCT MONTH(`Date`) AS `Month`, YEAR(`Date`) AS `Year` FROM `SiteTree$suffix` NATURAL JOIN `BlogEntry$suffix` WHERE `ParentID` = $id ORDER BY `Date` DESC");	
		} else {
			$sqlResults = DB::query("SELECT DISTINCT YEAR(`Date`) AS `Year` FROM `SiteTree$suffix` NATURAL JOIN `BlogEntry$suffix` WHERE `ParentID` = $id ORDER BY `Date` DESC");
		}
		
		if(!$sqlResults) return new DataObjectSet();
		
		foreach($sqlResults as $sqlResult) {
			$date = new Date('Date');
			$month = ($this->DisplayMode == 'month') ? (int)$sqlResult['Month'] : 1;
			
			$date->setValue(array(
				'Day' => 1,
				'Month' => $month, 
				'Year' => (int) $sqlResult['Year']
			));
			
			if($this->DisplayMode == 'month') {
				$link = $blogHolder->Link() . $sqlResult['Year']. '/' . sprintf("%'02d", $sqlResult['Month']);
			} else {
				$link = $blogHolder->Link() . $sqlResult['Year'];
			}
			
			$results->push(new ArrayData(array(
				'Date' => $date,
				'Link' => $link
			)));
		}
		
		return $results;
	}
 /**
  *
  *@return SQLQuery
  **/
 public function applyOne(DataQuery $query)
 {
     //$this->model = $query->applyRelation($this->relation);
     $value = $this->getValue();
     $date = new Date();
     $date->setValue($value);
     $distanceFromToday = time() - strtotime($value);
     $maxDays = round($distanceFromToday / ($this->divider * 2 * 86400)) + 1;
     $formattedDate = $date->format("Y-m-d");
     // changed for PostgreSQL compatability
     // NOTE - we may wish to add DATEDIFF function to PostgreSQL schema, it's just that this would be the FIRST function added for SilverStripe
     // default is MySQL DATEDIFF() function - broken for others, each database conn type supported must be checked for!
     $db = DB::getConn();
     if ($db instanceof PostgreSQLDatabase) {
         // don't know whether functions should be used, hence the following code using an interval cast to an integer
         $query->where("(\"EcommercePayment\".\"Created\"::date - '{$formattedDate}'::date)::integer > -" . $maxDays . " AND (\"EcommercePayment\".\"Created\"::date - '{$formattedDate}'::date)::integer < " . $maxDays);
     } else {
         // default is MySQL DATEDIFF() function - broken for others, each database conn type supported must be checked for!
         $query->where("(DATEDIFF(\"EcommercePayment\".\"Created\", '{$formattedDate}') > -" . $maxDays . " AND DATEDIFF(\"EcommercePayment\".\"Created\", '{$formattedDate}') < " . $maxDays . ")");
     }
     return $query;
 }
Пример #12
0
 function FeedItems()
 {
     $output = new DataObjectSet();
     // Protection against infinite loops when an RSS widget pointing to this page is added to this page
     if (stristr($_SERVER['HTTP_USER_AGENT'], 'SimplePie')) {
         return $output;
     }
     include_once Director::getAbsFile(SAPPHIRE_DIR . '/thirdparty/simplepie/simplepie.inc');
     $t1 = microtime(true);
     $feed = new SimplePie($this->AbsoluteRssUrl, TEMP_FOLDER);
     $feed->init();
     if ($items = $feed->get_items(0, $this->NumberToShow)) {
         foreach ($items as $item) {
             // Cast the Date
             $date = new Date('Date');
             $date->setValue($item->get_date());
             // Cast the Title
             $title = new Text('Title');
             $title->setValue($item->get_title());
             $output->push(new ArrayData(array('Title' => $title, 'Date' => $date, 'Link' => $item->get_link())));
         }
         return $output;
     }
 }
Пример #13
0
	/**
	 * returns a date object for use within a template
	 * Usage: $Now.Year - Returns 2006
	 * @return Date The current date
	 */
	function Now() {
		$d = new Date(null);
		$d->setValue(date("Y-m-d h:i:s"));
		return $d;
	}
 function Field()
 {
     if ($this->value) {
         $df = new Date($this->name);
         $df->setValue($this->dataValue());
         $val = Convert::raw2xml($this->value);
     } else {
         $val = '<i>' . _t('Form.NOTSET', '(not set)') . '</i>';
     }
     return "<span class=\"readonly\" id=\"" . $this->id() . "\">{$val}</span>";
 }
Пример #15
0
 function Field($properties = array())
 {
     if ($this->valueObj) {
         if ($this->valueObj->isToday()) {
             $val = Convert::raw2xml($this->valueObj->toString($this->getConfig('dateformat')) . ' (' . _t('DateField.TODAY', 'today') . ')');
         } else {
             $df = new Date($this->name);
             $df->setValue($this->dataValue());
             $val = Convert::raw2xml($this->valueObj->toString($this->getConfig('dateformat')) . ', ' . $df->Ago());
         }
     } else {
         $val = '<i>(' . _t('DateField.NOTSET', 'not set') . ')</i>';
     }
     return "<span class=\"readonly\" id=\"" . $this->id() . "\">{$val}</span>";
 }
 /**
  * A user formatted date
  * @return string
  */
 public function getDate()
 {
     $date = new Date();
     $date->setValue($this->ts);
     return Convert::raw2xml($date->FormatFromSettings());
 }
 /**
  * Returns either 'holiday' or '' for use in Template
  *
  * @param int $i Iteration of days
  * @return string
  */
 private function getIterationHolidayClass($i)
 {
     $date = new Date();
     $thisDateString = date('d-m-Y', strtotime('+' . $i . ' days', strtotime($this->StartDate)));
     $date->setValue($thisDateString);
     return in_array($date->Format('Y-m-d'), $this->getHolidayArray()) ? 'holiday' : '';
 }
 public function check()
 {
     $OdeonCinemaID = (int) $this->request->param("ID");
     if ($OdeonCinemaID) {
         if ($this->OdeonCinema = OdeonCinema::get_by_id("OdeonCinema", $OdeonCinemaID)) {
             $this->OdeonCinema->getCurrentFilms();
             $OdeonFilmID = (int) $this->request->param("OtherID");
             if ($OdeonFilmID) {
                 if ($this->OdeonFilm = OdeonFilm::get_by_id("OdeonFilm", $OdeonFilmID)) {
                     $maxdays = 15;
                     $baseURL = "https://www.odeon.co.uk/";
                     $date = new Date();
                     $RestfulService = new RestfulService($baseURL);
                     $i = 0;
                     do {
                         $date->setValue("+{$i} day");
                         if (!OdeonScreening::get("OdeonScreening", implode(" AND ", array("DATE_FORMAT(ScreeningTime,'%d%m%y') = '{$date->Format("dmy")}'", "FilmID='{$OdeonFilmID}'", "CinemaID='{$OdeonCinemaID}'")))->Count()) {
                             $query = array('date' => $date->Format("Y-m-d"), 'siteId' => $OdeonCinemaID, 'filmMasterId' => $OdeonFilmID, 'type' => 'DAY');
                             $RestfulService->setQueryString($query);
                             $Response = $RestfulService->request("showtimes/day");
                             if (!$Response->isError()) {
                                 $html = HtmlDomParser::str_get_html($Response->getBody());
                                 foreach ($html->find('ul') as $ul) {
                                     foreach ($ul->find('li') as $li) {
                                         $ScreeningTime = new SS_Datetime();
                                         $ScreeningTime->setValue("{$date->Format("Y-m-d")} {$li->find('a', 0)->innertext}:00");
                                         $checkAgainstAPI = true;
                                         if ($OdeonScreening = OdeonScreening::get_one("OdeonScreening", implode(" AND ", array("CinemaID='{$OdeonCinemaID}'", "FilmID='{$OdeonFilmID}'", "ScreeningTime='{$ScreeningTime->Rfc2822()}'")))) {
                                             $checkAgainstAPI = $OdeonScreening->checkAgainstAPI();
                                         } else {
                                             $OdeonScreening = new OdeonScreening();
                                             $OdeonScreening->CinemaID = $OdeonCinemaID;
                                             $OdeonScreening->FilmID = $OdeonFilmID;
                                             $OdeonScreening->ScreeningTime = $ScreeningTime->Rfc2822();
                                         }
                                         if ($checkAgainstAPI) {
                                             $URLSegment = str_replace($baseURL, "", $li->find('a', 0)->href);
                                             $Response_init = $RestfulService->request($URLSegment, "GET", null, null, array(CURLOPT_COOKIESESSION => TRUE));
                                             if (!$Response_init->isError()) {
                                                 $dom = new DOMDocument();
                                                 $dom->strictErrorChecking = FALSE;
                                                 libxml_use_internal_errors(true);
                                                 $dom->loadHTML($Response_init->getBody());
                                                 libxml_clear_errors();
                                                 $nodes = $dom->getElementsByTagName('form');
                                                 $submit_url = false;
                                                 $hidden_inputs = array();
                                                 foreach ($nodes as $node) {
                                                     if (!$submit_url && $node->hasAttributes()) {
                                                         foreach ($node->attributes as $attribute) {
                                                             if (!$submit_url && $attribute->nodeName == 'action') {
                                                                 $submit_url = $attribute->nodeValue;
                                                             }
                                                         }
                                                     }
                                                 }
                                                 unset($node);
                                                 $SubmitURL = ltrim($submit_url, '/');
                                                 $Cookies = $Response_init->getHeader("Set-Cookie");
                                                 if (is_array($Cookies)) {
                                                     $Cookies = implode(';', $Cookies);
                                                 }
                                                 $Response_availability = $RestfulService->request($SubmitURL, "GET", null, null, array(CURLOPT_COOKIE => $Cookies));
                                                 if (!$Response_availability->isError()) {
                                                     $html_availability = HtmlDomParser::str_get_html($Response_availability->getBody());
                                                     $ticketsTable = $html_availability->find('#tickets-table', 0);
                                                     if ($ticketsTable) {
                                                         $ticketsForm = $html_availability->find('#tickets', 0);
                                                         $data = array("submit" => null);
                                                         foreach ($ticketsTable->find('select') as $select) {
                                                             $data[$select->attr["name"]] = "0";
                                                         }
                                                         foreach ($ticketsTable->find('tr') as $tr) {
                                                             foreach ($tr->find('td') as $td) {
                                                                 switch ($td->getAttribute("class")) {
                                                                     case "ticket-col":
                                                                         $OdeonScreening->Title = trim($td->innertext);
                                                                         break;
                                                                     case "price-col":
                                                                         $OdeonScreening->Cost = ltrim(explode(" ", trim($td->plaintext))[0], '£');
                                                                         break;
                                                                     case "quantity-col":
                                                                         $Availability = 1;
                                                                         foreach ($td->find('select') as $select) {
                                                                             foreach ($select->find('option') as $option) {
                                                                                 $Availability = $option->attr["value"];
                                                                             }
                                                                             $data[$select->attr["name"]] = $Availability;
                                                                         }
                                                                         $Response_seats = $RestfulService->request(ltrim(html_entity_decode($ticketsForm->attr['action']), "/"), "POST", $data, null, array(CURLOPT_COOKIE => $Cookies));
                                                                         if (!$Response_seats->isError()) {
                                                                             $html_seats = HtmlDomParser::str_get_html($Response_seats->getBody());
                                                                             if (trim($html_seats->find('.step-headline', 0)->innertext) == "Choose your seats") {
                                                                                 $OdeonScreening->Availability = $Availability;
                                                                                 $OdeonScreening->SessionURL = $URLSegment;
                                                                                 $OdeonScreening->duplicate();
                                                                             }
                                                                         }
                                                                         break;
                                                                 }
                                                             }
                                                         }
                                                     }
                                                 }
                                             }
                                         }
                                     }
                                 }
                             } else {
                                 Debug::show($query);
                                 Debug::show($Response);
                             }
                         }
                         $i++;
                     } while ($i < $maxdays);
                 } else {
                     echo "Not a valid film ID";
                 }
             }
         } else {
             echo "Not a valid cinema ID";
         }
     }
     return $this;
 }
Пример #19
0
 function Field()
 {
     if ($this->value) {
         $df = new Date($this->name);
         $df->setValue($this->dataValue());
         if (date('Y-m-d', time()) == $this->dataValue()) {
             $val = Convert::raw2xml($this->value . ' (' . _t('DateField.TODAY', 'today') . ')');
         } else {
             $val = Convert::raw2xml($this->value . ', ' . $df->Ago());
         }
     } else {
         $val = '<i>(' . _t('DateField.NOTSET', 'not set') . ')</i>';
     }
     return "<span class=\"readonly\" id=\"" . $this->id() . "\">{$val}</span>\n\t\t\t\t<input type=\"hidden\" value=\"{$this->value}\" name=\"{$this->name}\" />";
 }
Пример #20
0
    public function testDateProperty()
    {

        $property = new Date('AProperty');
        $time = time();

        //check it stores the value correctly
        $property->setValue($time);
        $this->assertEquals($time, $property->getValue());

        //check the output type is correct
        $this->assertInstanceOf('\MongoDate', $property->__getRawValue());

        //check the MorphDate objects content is correct
        $this->assertEquals($time, $property->__getRawValue()->sec);
    }