/**
  * This method is copied 2015-11-24 from  theplumpss/twitter module (https://github.com/plumpss/twitter/blob/master/code/PlumpTwitterFeed.php)
  * Also some other parts of this module has used theplumpss/twitter as an example, but tweet_to_array() is the
  * only direct copy - although it has some modifications too, regarding to format of the return value.
  * @param $tweet
  * @return mixed
  */
 private static function tweet_to_array($tweet)
 {
     $date = new SS_Datetime();
     $date->setValue(strtotime($tweet->created_at));
     $html = $tweet->text;
     if ($tweet->entities) {
         //url links
         if ($tweet->entities->urls) {
             foreach ($tweet->entities->urls as $url) {
                 $html = str_replace($url->url, '<a href="' . $url->url . '" target="_blank">' . $url->url . '</a>', $html);
             }
         }
         //hashtag links
         if ($tweet->entities->hashtags) {
             foreach ($tweet->entities->hashtags as $hashtag) {
                 $html = str_replace('#' . $hashtag->text, '<a target="_blank" href="https://twitter.com/search?q=%23' . $hashtag->text . '">#' . $hashtag->text . '</a>', $html);
             }
         }
         //user links
         if ($tweet->entities->user_mentions) {
             foreach ($tweet->entities->user_mentions as $mention) {
                 $html = str_replace('@' . $mention->screen_name, '<a target="_blank" href="https://twitter.com/' . $mention->screen_name . '">@' . $mention->screen_name . '</a>', $html);
             }
         }
     }
     $title = new Text();
     $title->setValue($tweet->text);
     return array('LastEdited' => (string) $date, 'Created' => (string) $date, 'Fetched' => SS_Datetime::now(), 'SoMeAuthor' => $tweet->user->screen_name, 'SoMeUsername' => self::config()->username, 'Avatar' => $tweet->user->profile_image_url, 'Content' => $html, 'Title' => preg_replace('/\\.$/', '', $title->Summary(self::config()->title_length)), 'TwitterID' => $tweet->id, 'Locale' => $tweet->lang, 'Source' => 'Twitter');
 }
 public function parameterFields()
 {
     $fields = new FieldList();
     // Check if any order exist
     if (Order::get()->exists()) {
         $first_order = Order::get()->sort('Created ASC')->first();
         $months = array('All');
         $statuses = Order::config()->statuses;
         array_unshift($statuses, 'All');
         for ($i = 1; $i <= 12; $i++) {
             $months[] = date("F", mktime(0, 0, 0, $i + 1, 0, 0));
         }
         // Get the first order, then count down from current year to that
         $firstyear = new SS_Datetime('FirstDate');
         $firstyear->setValue($first_order->Created);
         $years = array();
         for ($i = date('Y'); $i >= $firstyear->Year(); $i--) {
             $years[$i] = $i;
         }
         //Result Limit
         $result_limit_options = array(0 => 'All', 50 => 50, 100 => 100, 200 => 200, 500 => 500);
         $fields->push(DropdownField::create('Filter_Month', 'Filter by month', $months));
         $fields->push(DropdownField::create('Filter_Year', 'Filter by year', $years));
         $fields->push(DropdownField::create('Filter_Status', 'Filter By Status', $statuses));
         $fields->push(DropdownField::create("ResultsLimit", "Limit results to", $result_limit_options));
     }
     return $fields;
 }
 private static function create_tweet($tweet)
 {
     $date = new SS_Datetime();
     $date->setValue(strtotime($tweet->created_at));
     $html = $tweet->text;
     if ($tweet->entities) {
         //url links
         if ($tweet->entities->urls) {
             foreach ($tweet->entities->urls as $url) {
                 $html = str_replace($url->url, '<a href="' . $url->url . '" target="_blank">' . $url->url . '</a>', $html);
             }
         }
         //hashtag links
         if ($tweet->entities->hashtags) {
             foreach ($tweet->entities->hashtags as $hashtag) {
                 $html = str_replace('#' . $hashtag->text, '<a target="_blank" href="https://twitter.com/search?q=%23' . $hashtag->text . '">#' . $hashtag->text . '</a>', $html);
             }
         }
         //user links
         if ($tweet->entities->user_mentions) {
             foreach ($tweet->entities->user_mentions as $mention) {
                 $html = str_replace('@' . $mention->screen_name, '<a target="_blank" href="https://twitter.com/' . $mention->screen_name . '">@' . $mention->screen_name . '</a>', $html);
             }
         }
     }
     return new ArrayData(array('Date' => $date, 'Username' => $tweet->user->screen_name, 'Avatar' => $tweet->user->profile_image_url, 'Text' => $tweet->text, 'Html' => $html));
 }
 public function LastUpdated()
 {
     $elements = new DataList($this->dataClass);
     $lastUpdated = new SS_Datetime('LastUpdated');
     $lastUpdated->setValue($elements->max('LastEdited'));
     return $lastUpdated;
 }
Beispiel #5
0
 /**
  * @return SS_Datetime
  */
 public function Created()
 {
     $created = $this->tag->getCommit()->getCommitterDate();
     // gitonomy sets the time to UTC, so now we set the timezone to
     // whatever PHP is set to (date.timezone). This will change in the future if each
     // deploynaut user has their own timezone
     $created->setTimezone(new DateTimeZone(date_default_timezone_get()));
     $d = new SS_Datetime();
     $d->setValue($created->format('Y-m-d H:i:s'));
     return $d;
 }
 /**
  * @param mixed $data
  * @param string $field
  * @param array $options
  * @return string
  * @throws \ValidationException
  */
 public static function validate_datetime($data, $field, $options = [])
 {
     $options = array_merge(['required' => true], $options);
     $required = $options['required'];
     if (isset($data[$field]) && is_string($data[$field])) {
         $date = $data[$field];
         $dateTime = new \SS_Datetime();
         $dateTime->setValue($date);
         if (!$dateTime->getValue()) {
             throw new \ValidationException("No valid datetime given.");
         }
         return $dateTime->Format('Y-m-d H:i:s');
     } else {
         if ($required) {
             throw new \ValidationException("No {$field} given, but {$field} is required");
         }
     }
 }
 /**
  * @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);
 }
 /**
  * Pull down latest tweets using the twitter API
  *
  * @return ArrayList
  */
 public function LatestTweets($limit = 3)
 {
     $config = SiteConfig::current_site_config();
     $output = new ArrayList();
     if ($config->TwitterConsumerKey) {
         $tmhOAuth = new tmhOAuth(array('consumer_key' => $config->TwitterConsumerKey, 'consumer_secret' => $config->TwitterConsumerSecret, 'user_token' => $config->TwitterAccessToken, 'user_secret' => $config->TwitterAccessTokenSecret, 'curl_ssl_verifypeer' => false));
         $code = $tmhOAuth->request('GET', $tmhOAuth->url('1.1/statuses/user_timeline'), array('screen_name' => $config->TwitterUsername, 'count' => $limit));
         $response = $tmhOAuth->response['response'];
         $tweets = json_decode($response, true);
         if (!$tweets) {
             return false;
         }
         if ($this->errorCheck($tweets)) {
             return false;
         }
         foreach ($tweets as &$tweet) {
             $date = new SS_Datetime();
             $date->setValue($tweet['created_at']);
             $output->push(new ArrayData(array('ID' => $tweet['id'], 'Date' => $date, 'Content' => $this->tweetConvert($tweet['text']), 'User' => new ArrayData(array('ID' => $tweet['user']['id'], 'Name' => $tweet['user']['name'], 'ProfileImg' => $tweet['user']['profile_image_url'], 'ScreenName' => $tweet['user']['screen_name'])))));
         }
     }
     return $output;
 }
 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;
 }
 public function addVersionViewer(FieldList $fields)
 {
     if ($this->owner->hasExtension('Versioned') || $this->owner->hasExtension('VersionedDataObject')) {
         // Get the object where this function was called for reference purposes
         $object = $this->owner;
         // Get all tabs in the current model admin and prepart to put within a tabset called "Current"
         $current_tabs = $fields->find('Name', 'Root')->Tabs();
         $fields = FieldList::create(TabSet::create("Root", $currenttab = TabSet::create("Current"), $historytab = TabSet::create("History")->addExtraClass("vertical-tabs")));
         // Add all existing tabs to "Current" tabset
         $first = true;
         foreach ($current_tabs as $tab) {
             // If we have the getVersionedState function,
             // add a notice regarding the versioned state to the first tab
             // TODO incorporate VersionedDataObjectState extension into this module
             if ($first && $object->hasMethod('getVersionedState')) {
                 $fields->addFieldToTab("Root.Current." . $tab->title, LiteralField::create('VersionedState', '<div class="message notice"><p>' . $object->getVersionedState() . '</p></div>'));
                 $first = false;
             }
             $fields->addFieldsToTab("Root.Current." . $tab->title, $tab->Fields());
         }
         // Remove any fields that have VersionViewerVisibility turned off
         foreach ($current_tabs as &$tab) {
             foreach ($tab->Fields() as $field) {
                 // echo '<pre>'.$field->Name.' Viewable? '; print_r($field->versionViewerVisibility);
                 if (!$field->versionViewerVisibility && $tab->fieldByName($field->Name)) {
                     $tab->removeByName($field->Name);
                 }
             }
         }
         // die();
         // Also, as of now, Versioned does not track has_many or many_many relationships
         // So find fields relating to those relationships, remove them,
         // and add a message regarding this
         $untracked_msg = "";
         foreach ($current_tabs as &$tab) {
             foreach ($tab->Fields() as $field) {
                 $rel_class = $object->getRelationClass($field->Name);
                 if ($rel_class) {
                     if (in_array($rel_class, $object->has_many()) || in_array($rel_class, $object->many_many())) {
                         if ($tab->fieldByName($field->Name)) {
                             $tab->removeByName($field->Name);
                             if (!$untracked_msg) {
                                 // $untracked_msg = '<div class="message notice"><p>Note: the following relationships are not tracked by versioning because they involve multiple records:<br />';
                                 $untracked_msg = '<p>' . $field->Title();
                             } else {
                                 $untracked_msg .= "<br />" . $field->Title();
                             }
                         }
                     }
                 }
             }
         }
         if ($untracked_msg) {
             $untracked_msg .= '</p>';
         }
         // Get all past versions of this data object and put the relevant data in a set of tabs
         // within a tabset called "History"
         $versions = $object->allVersions();
         foreach ($versions as $version) {
             // Get a record of this version of the object
             $record = Versioned::get_version($object->ClassName, $object->ID, $version->Version);
             // Make a set of read-only fields for use in assembling the History tabs
             $read_fields = $current_tabs->makeReadonly();
             // Make a form using the relevant fields and load it with data from this record
             $form = new Form($object, "old_version", $read_fields, $object->getCMSActions());
             $form->loadDataFrom($record);
             // Add the version number to each field name so we don't have duplicate field names
             if ($form->fields->dataFields()) {
                 foreach ($form->fields->dataFields() as $field) {
                     $field->Name = $field->Name . "version" . $version->Version;
                 }
             }
             // Generate some heading strings describing this version
             $was_published = $version->WasPublished ? "P" : "D";
             $was_published_full = $version->WasPublished ? "Published" : "Saved as draft";
             $publishedby = Member::get()->byId($version->PublisherID);
             $authoredby = Member::get()->byId($version->AuthorID);
             $publisher_heading = "";
             $author_heading = "";
             if ($publishedby) {
                 $publisher_heading = " by " . $publishedby->getName();
             }
             if ($authoredby) {
                 $author_heading = " (Authored by " . $authoredby->getName() . ")";
             }
             $up_date = new SS_Datetime('update');
             $up_date->setValue($version->LastEdited);
             $nice_date = $up_date->FormatFromSettings();
             $tab_title = $version->Version . " - " . $nice_date . " (" . $was_published . ")";
             $latest_version_notice = "";
             if ($version->isLatestVersion()) {
                 $latest_version_notice = " (latest version)";
             }
             $tab_heading = "<div class='message notice'><p><strong>Viewing version " . $version->Version . $latest_version_notice . ".</strong><br>" . $was_published_full . $publisher_heading . " on " . $nice_date . $author_heading . "</p></div>";
             // Add fields to a tab headed with a description of this version
             $fields->addFieldsToTab('Root.History.' . $tab_title, LiteralField::create('versionHeader' . $version->Version, $tab_heading));
             $fields->addFieldsToTab('Root.History.' . $tab_title, $form->fields);
             // Add notice regarding untracked relationships
             if ($untracked_msg) {
                 $fields->addFieldsToTab('Root.History.' . $tab_title, HeaderField::create('untrackedMessageHeader' . $version->Version, 'Note: the relationships listed below are not tracked by versioning because they involve multiple records', 4));
                 $fields->addFieldsToTab('Root.History.' . $tab_title, LiteralField::create('untrackedMessage' . $version->Version, $untracked_msg));
                 // $fields->addFieldsToTab('Root.History.' . $tab_title, LiteralField::create('untrackedMessage'.$version->Version, $untracked_msg));
             }
         }
     }
     return $fields;
 }
 public function parameterFields()
 {
     $fields = new FieldList();
     if (class_exists("Subsite")) {
         $first_order = Subsite::get_from_all_subsites("Order")->sort('Created', 'ASC')->first();
     } else {
         $first_order = Order::get()->sort('Created', 'ASC')->first();
     }
     // Check if any order exist
     if ($first_order) {
         // List all months
         $months = array('All');
         for ($i = 1; $i <= 12; $i++) {
             $months[] = date("F", mktime(0, 0, 0, $i + 1, 0, 0));
         }
         // Get the first order, then count down from current year to that
         $firstyear = new SS_Datetime('FirstDate');
         $firstyear->setValue($first_order->Created);
         $years = array();
         for ($i = date('Y'); $i >= $firstyear->Year(); $i--) {
             $years[$i] = $i;
         }
         // Order Status
         $statuses = Order::config()->statuses;
         array_unshift($statuses, 'All');
         $fields->push(TextField::create('Filter_FirstName', 'Customer First Name'));
         $fields->push(TextField::create('Filter_Surname', 'Customer Surname'));
         $fields->push(TextField::create('Filter_StockID', 'Stock ID'));
         $fields->push(TextField::create('Filter_ProductName', 'Product Name'));
         $fields->push(DropdownField::create('Filter_Month', 'Month', $months));
         $fields->push(DropdownField::create('Filter_Year', 'Year', $years));
         $fields->push(DropdownField::create('Filter_Status', 'Order Status', $statuses));
     }
     return $fields;
 }
 /**
  * Determines if a fetched date is outdated.
  *
  * @param mixed $fetched Date to evaluate.
  * @return boolean
  */
 public static function isOutdated($fetched)
 {
     if ($fetched) {
         // Check if $fetched is an object
         if (!is_object($fetched)) {
             $dateime = new SS_Datetime();
             $dateime->setValue($fetched);
             $fetched = $dateime;
         }
         if ($fetched->TimeDiff() > HailApi::getRefreshRate()) {
             return true;
         }
         return false;
     }
     return true;
 }
 /**
  * 
  * @return string
  */
 public function getExpireHTML()
 {
     if (!$this->owner->Secured) {
         return;
     }
     if ($this->owner instanceof Folder) {
         $ret = "N/A";
     } else {
         switch ($this->owner->ExpiryType) {
             case 'AtAFixedDate':
                 if ($expireDate = $this->owner->ExpireAtDate) {
                     $datetime = new SS_Datetime();
                     $datetime->setValue($expireDate);
                     $now = $today = date('Y-m-d H:i:s');
                     if ($expireDate > $now) {
                         $expire = _t("FileSecured.EmbargoedNotExpired", "Not expired, will expire ");
                     } else {
                         $expire = _t("FileSecured.EmbargoedExpired", "Expired ");
                     }
                     $time = Time::create();
                     $time->setValue($datetime->Time());
                     $date = Date::create();
                     $date->setValue($datetime->Date());
                     $ret = $expire . " at " . $time->Nice() . ", " . $date->Long();
                 } else {
                     $ret = _t("FileSecured.EmbargoedNoDateSetNotExpired", "No embargoing date/time is set, so treated as not expired");
                 }
                 break;
             default:
                 //case 'None':
                 $ret = "Not expired";
         }
     }
     return $ret;
 }
 /**
  * @return SS_Datetime
  */
 public function LastUpdated()
 {
     if ($this->_lastUpdatedCache) {
         return $this->_lastUpdatedCache;
     }
     try {
         $created = $this->branch->getCommit()->getCommitterDate();
     } catch (Exception $e) {
         //occasionally parsing will fail this is a fallback to make it still work
         return new SS_Datetime();
     }
     // gitonomy sets the time to UTC, so now we set the timezone to
     // whatever PHP is set to (date.timezone). This will change in the future if each
     // deploynaut user has their own timezone
     $created->setTimezone(new DateTimeZone(date_default_timezone_get()));
     $date = new SS_Datetime();
     $date->setValue($created->format('Y-m-d H:i:s'));
     $this->_lastUpdatedCache = $date;
     return $date;
 }
 private function syncToDB($events)
 {
     $events = $events->Items;
     // Archive all the events that we have but not Arlo
     $eventsInDb = ArloEvent::get();
     if ($eventsInDb) {
         foreach ($eventsInDb as $eventdb) {
             if (!$this->checkEventInAPI($events, $eventdb->EventID)) {
                 $eventdb->Archive = true;
                 $eventdb->write();
             }
         }
     }
     foreach ($events as $event) {
         //identify the event by its ID which is to be unique
         $arloevent = ArloEvent::get()->filter(array('EventID' => $event->EventID))->First();
         // if it doesnt exist in DB make a new one!
         if (!$arloevent) {
             $arloevent = new ArloEvent();
         }
         $name = isset($event->Name) ? $event->Name : '';
         $summary = isset($event->Summary) ? $event->Summary : '';
         $description = isset($event->Description->Text) ? $event->Description->Text : '';
         $link = isset($event->ViewUri) ? $event->ViewUri : '';
         $location = isset($event->Location) ? $event->Location->Name : '';
         $start = isset($event->StartDateTime) ? $event->StartDateTime : '';
         $end = isset($event->EndDateTime) ? $event->EndDateTime : '';
         $code = isset($event->Code) ? $event->Code : '';
         $templatecode = isset($event->TemplateCode) ? $event->TemplateCode : '';
         $provider = isset($event->Provider) ? $event->Provider : '';
         $private = isset($event->IsPrivate) ? $event->IsPrivate : false;
         $private = $private == 'false' ? false : true;
         $startdatetime = new SS_Datetime();
         $startdatetime->setValue($event->StartDateTime);
         $enddatetime = new SS_Datetime();
         $enddatetime->setValue($event->EndDateTime);
         $arloevent->EventID = $event->EventID;
         $arloevent->Name = $name;
         $arloevent->ViewUri = $link;
         $arloevent->Code = $code;
         $arloevent->Summary = $summary;
         $arloevent->Description = $description;
         $arloevent->StartDateTime = $startdatetime;
         $arloevent->EndDateTime = $enddatetime;
         $arloevent->Location = $location;
         $arloevent->TemplateCode = $templatecode;
         $arloevent->Provider = $provider;
         $arloevent->IsPrivate = $private;
         $arloevent->write();
     }
 }
 /**
  * Load feed xml and return items
  * 
  * @param boolean $refresh
  * @return ArrayList or boolean false
  */
 function Items($refresh = false)
 {
     if (!$this->FeedURL) {
         return false;
     }
     if (!($xml = $this->loadXml())) {
         return false;
     }
     $result = new ArrayList();
     $counter = (int) $this->Results;
     if (!$counter) {
         $counter = -1;
     }
     // Return all posts
     foreach ($xml->channel->item as $item) {
         // Date
         $date = new SS_Datetime('Date');
         $date->setValue((string) $item->pubDate);
         // Title
         $itemTitle = (string) $item->title;
         $itemTitle = html_entity_decode($itemTitle);
         $title = new Text('Title');
         $title->setValue($itemTitle);
         // Description
         $itemDescription = (string) $item->description;
         $itemDescription = html_entity_decode($itemDescription);
         $description = new Text('Description');
         if ($this->Striptags) {
             $itemDescription = strip_tags($itemDescription);
         }
         $description->setValue($itemDescription);
         // Link
         $link = (string) $item->link;
         // Summary
         $summary = $itemDescription;
         $summary = strip_tags($summary);
         $summary = trim($summary);
         // Get first paragraph
         $summary = explode("\n", $summary);
         $summary = array_shift($summary);
         // Truncate summary if necessary
         $maxLength = (int) $this->SummaryMaxLength;
         if ($maxLength && strlen($summary) > $maxLength) {
             $summary = substr($summary, 0, $maxLength) . '...';
         }
         // Add to result list
         $result->push(new ArrayData(array('Title' => $title, 'Date' => $date, 'Link' => $link, 'Description' => $description, 'Summary' => $summary)));
         if ($counter) {
             $counter--;
             if (!$counter) {
                 break;
             }
         }
     }
     // Apply custom modifier function to each entry
     if (count($result) && !empty($this->Modifier) && $this->ClassName != __CLASS__ && method_exists($this->ClassName, $this->Modifier)) {
         try {
             $m = $this->Modifier;
             foreach ($result as $item) {
                 $this->{$m}($item);
             }
         } catch (Exception $e) {
             // Ignore
         }
     }
     // Return items
     return $result;
 }
 /**
  * Extracts and populates an array structure with the video information returned from Vimeo for a single video object.
  * @param Object
  * @return array
  */
 private function _extractVideoInfo($data)
 {
     $video = array();
     $video['ID'] = intval($data->id);
     $video['Title'] = new Text(null);
     $video['Title']->setValue(trim($data->title));
     /*
      * need to clean up the text returned from Vimeo and paragraph format it so we can use
      * all the nifty SilverStripe text functionality. :)
      */
     $desc = nl2br(trim($data->description));
     $desc = str_replace("<br />\n<br />", '<br />', $desc);
     $desc = '<p>' . str_replace('<br />', '</p><p>', $desc) . '</p>';
     $video['Description'] = new HTMLText();
     $video['Description']->setValue($desc);
     // video url info
     foreach ($data->urls->url as $url) {
         switch ($url->type) {
             case 'video':
                 $video['Url'] = new Text();
                 $video['Url']->setValue(trim($url->_content));
                 break;
             case 'mobile':
                 $video['MobileUrl'] = new Text();
                 $video['MobileUrl']->setValue(trim($url->_content));
                 break;
             default:
                 // do nothing.
                 break;
         }
     }
     // video date info
     $upload_date = trim($data->upload_date);
     // create a SS_Datetime object so we can use familiar functionality.
     $ud = new SS_Datetime();
     $ud->setValue($upload_date);
     $video['UploadDate'] = $ud;
     $modified_date = trim($data->modified_date);
     // create a SS_Datetime object so we can use familiar functionality.
     $md = new SS_Datetime();
     $md->setValue($modified_date);
     $video['ModifiedDate'] = $md;
     // video thumbnail info
     foreach ($data->thumbnails->thumbnail as $tn) {
         if (strpos($tn->_content, '_100.jpg') !== false) {
             $video['ThumbSmall'] = new Text();
             $video['ThumbSmall']->setValue(trim($tn->_content));
         } elseif (strpos($tn->_content, '_200.jpg') !== false) {
             $video['ThumbMedium'] = new Text();
             $video['ThumbMedium']->setValue(trim($tn->_content));
         } elseif (strpos($tn->_content, '_640.jpg') !== false) {
             $video['ThumbLarge'] = new Text();
             $video['ThumbLarge']->setValue(trim($tn->_content));
         }
     }
     // User information
     $video['UserName'] = new Varchar(null, 255);
     $video['UserName']->setValue(trim($data->owner->username));
     $video['UserDisplayName'] = new Varchar(null, 255);
     $video['UserDisplayName']->setValue(trim($data->owner->display_name));
     $video['UserRealName'] = new Varchar(null, 255);
     $video['UserRealName']->setValue(trim($data->owner->realname));
     $video['UserID'] = (int) trim($data->owner->id);
     $video['UserUrl'] = new Text();
     $video['UserUrl']->setValue(trim($data->owner->profileurl));
     // User photos
     for ($i = 0; $i < count($data->owner->portraits->portrait); $i++) {
         $tn = $data->owner->portraits->portrait[$i];
         switch ($i) {
             case 0:
                 $video['UserPortraitSmall'] = new Text();
                 $video['UserPortraitSmall']->setValue(trim($tn->_content));
                 break;
             case 1:
                 $video['UserPortraitMedium'] = new Text();
                 $video['UserPortraitMedium']->setValue(trim($tn->_content));
                 break;
             case 2:
                 $video['UserPortraitLarge'] = new Text();
                 $video['UserPortraitLarge']->setValue(trim($tn->_content));
                 break;
             case 3:
                 $video['UserPortraitXLarge'] = new Text();
                 $video['UserPortraitXLarge']->setValue(trim($tn->_content));
                 break;
             default:
                 // do nothing.
                 break;
         }
     }
     $video['NumberLikes'] = intval(trim($data->number_of_likes));
     $video['NumberPlays'] = intval(trim($data->number_of_plays));
     $video['NumberComments'] = intval(trim($data->number_of_comments));
     $video['Duration'] = intval(trim($data->duration));
     $video['Width'] = intval(trim($data->width));
     $video['Height'] = intval(trim($data->height));
     $video['IsHD'] = new Boolean(null);
     $video['IsHD']->setValue(intval($data->is_hd));
     $video['EmbedPrivacy'] = new Text();
     $video['EmbedPrivacy']->setValue(trim($data->embed_privacy));
     return $video;
 }
 /**
  * retries latest tweets from Twitter
  *
  * @param String $username (e.g. mytwitterhandle)
  * @param Int $count - number of tweets to retrieve at any one time
  * @return DataObjectSet | Null
  */
 public function TwitterFeed($username, $count = 5)
 {
     if (!$username) {
         user_error("No username provided");
     }
     Config::inst()->update("MyTwitterData", "username", $username);
     //check settings are available
     $requiredSettings = array("twitter_consumer_key", "twitter_consumer_secret", "titter_oauth_token", "titter_oauth_token");
     foreach ($requiredSettings as $setting) {
         if (!Config::inst()->get("MyTwitter", $setting)) {
             user_error(" you must set MyTwitter::{$setting}", E_USER_NOTICE);
             return null;
         }
     }
     require_once Director::baseFolder() . '/' . SS_SHARETHIS_DIR . '/third_party/twitter_oauth/TwitterOAuthConsumer.php';
     $connection = new TwitterOAuth(Config::inst()->get("MyTwitter", "twitter_consumer_key"), Config::inst()->get("MyTwitter", "twitter_consumer_secret"), Config::inst()->get("MyTwitter", "titter_oauth_token"), Config::inst()->get("MyTwitter", "titter_oauth_token_secret"));
     $config = Config::inst()->get("MyTwitter", "twitter_config");
     $config['screen_name'] = $username;
     $tweets = $connection->get('statuses/user_timeline', $config);
     $tweetList = new ArrayList();
     if (count($tweets) > 0 && !isset($tweets->error)) {
         $i = 0;
         foreach ($tweets as $tweet) {
             if (Config::inst()->get("MyTwitter", "favourites_only") && $tweet->favorite_count == 0) {
                 break;
             }
             if (Config::inst()->get("MyTwitter", "non_replies_only") && $tweet->in_reply_to_status_id) {
                 break;
             }
             if (Config::inst()->get("MyTwitter", "debug")) {
                 print_r($tweet);
             }
             if (++$i > $count) {
                 break;
             }
             $date = new SS_Datetime();
             $date->setValue(strtotime($tweet->created_at));
             $text = htmlentities($tweet->text, ENT_NOQUOTES, $encoding = "UTF-8", $doubleEncode = false);
             if (!empty($tweet->entities) && !empty($tweet->entities->urls)) {
                 foreach ($tweet->entities->urls as $url) {
                     if (!empty($url->url) && !empty($url->display_url)) {
                         $text = str_replace($url->url, '<a href="' . $url->url . '" class="external">' . $url->display_url . '</a>', $text);
                     }
                 }
             }
             $tweetList->push(new ArrayData(array('ID' => $tweet->id_str, 'Title' => $text, 'Date' => $date)));
         }
     }
     return $tweetList;
 }
 /**
  * Parse URL parameters and set the filters
  *
  * @param boolean $produceErrorMessages Set to false to omit session messages.
  * @return array
  */
 public function parseParams($produceErrorMessages = true)
 {
     $tag = $this->request->getVar('tag');
     $from = $this->request->getVar('from');
     $to = $this->request->getVar('to');
     $year = $this->request->getVar('year');
     $month = $this->request->getVar('month');
     if ($tag == '') {
         $tag = null;
     }
     if ($from == '') {
         $from = null;
     }
     if ($to == '') {
         $to = null;
     }
     if ($year == '') {
         $year = null;
     }
     if ($month == '') {
         $month = null;
     }
     if (isset($tag)) {
         $tag = (int) $tag;
     }
     if (isset($from)) {
         $from = urldecode($from);
         $parser = new SS_Datetime();
         $parser->setValue($from);
         $from = $parser->Format('Y-m-d');
     }
     if (isset($to)) {
         $to = urldecode($to);
         $parser = new SS_Datetime();
         $parser->setValue($to);
         $to = $parser->Format('Y-m-d');
     }
     if (isset($year)) {
         $year = (int) $year;
     }
     if (isset($month)) {
         $month = (int) $month;
     }
     // If only "To" has been provided filter by single date. Normalise by swapping with "From".
     if (isset($to) && !isset($from)) {
         list($to, $from) = array($from, $to);
     }
     // Flip the dates if the order is wrong.
     if (isset($to) && isset($from) && strtotime($from) > strtotime($to)) {
         list($to, $from) = array($from, $to);
         if ($produceErrorMessages) {
             Session::setFormMessage('Form_DateRangeForm', _t('DateUpdateHolder.FilterAppliedMessage', 'Filter has been applied with the dates reversed.'), 'warning');
         }
     }
     // Notify the user that filtering by single date is taking place.
     if (isset($from) && !isset($to)) {
         if ($produceErrorMessages) {
             Session::setFormMessage('Form_DateRangeForm', _t('DateUpdateHolder.DateRangeFilterMessage', 'Filtered by a single date.'), 'warning');
         }
     }
     return array('tag' => $tag, 'from' => $from, 'to' => $to, 'year' => $year, 'month' => $month);
 }
 /**
  * Get an SSDatetime object representing the converted
  * time. Used to access the helper methods that SSDatetime
  * provides
  */
 function SSDatetime()
 {
     $datetime = new SS_Datetime($this->name);
     $datetime->setValue($this->value);
     return $datetime;
 }
 /**
  * Helper method to convert weather data in JSON format to a SilverStripe DataObject
  * It appears several times in the API
  * @param  [type] $weather [description]
  * @return [type]          [description]
  */
 private function json_weather_to_data_object($weather)
 {
     $do = new DataObject();
     //$do->Latitude = $weather->coord->lat;
     //$do->Longitude = $weather->coord->lat;
     //$do->Name = $weather->name;
     //$do->Country = $weather->sys->country;
     //$do->Sunrise = $weather->sys->sunrise;
     //$do->Sunset = $weather->sys->sunset;
     $do->WeatherDescription = $weather->weather[0]->description;
     $do->WeatherMain = $weather->weather[0]->main;
     $do->WeatherIconURL = 'http://openweathermap.org/img/w/' . $weather->weather[0]->icon . '.png';
     if (isset($weather->wind)) {
         $do->WindSpeed = $weather->wind->speed;
         $do->WindDirection = $weather->wind->deg;
     }
     // 5 day forecast
     if (isset($weather->main)) {
         $do->TemperatureCurrent = $weather->main->temp;
         $do->TemperatureMin = $weather->main->temp_min;
         $do->TemperatureMax = $weather->main->temp_max;
         $do->Pressure = $weather->main->pressure;
         $do->PressureSeaLevel = $weather->main->sea_level;
         $do->PressureGroundLevel = $weather->main->grnd_level;
         $do->Humidity = $weather->main->humidity;
     } else {
         // 10 day forecast is a different format
         $do->TemperatureMin = $weather->temp->min;
         $do->TemperatureMax = $weather->temp->max;
         $do->Pressure = $weather->pressure;
         $do->Humidity = $weather->humidity;
         $do->WindSpeed = $weather->speed;
         $do->WindDirection = $weather->deg;
     }
     $ssdt = new SS_Datetime();
     $ssdt->setValue($weather->dt);
     $do->DateTime = $ssdt;
     if (isset($weather->clouds)) {
         // variation in data output here :(
         if (isset($weather->clouds->all)) {
             $do->CloudCoverPercentage = $weather->clouds->all;
         } else {
             $do->CloudCoverPercentage = $weather->clouds;
         }
     }
     return $do;
 }