public function getChangeFrequency()
 {
     $date = date('Y-m-d H:i:s');
     $created = new SS_Datetime();
     $created->value = $this->owner->Created ? $this->owner->Created : $date;
     $now = new SS_Datetime();
     $now->value = $date;
     $versions = $this->owner->Version ? $this->owner->Version : 1;
     $timediff = $now->format('U') - $created->format('U');
     // Check how many revisions have been made over the lifetime of the
     // Page for a rough estimate of it's changing frequency.
     $period = $timediff / ($versions + 1);
     if ($period > 60 * 60 * 24 * 365) {
         $freq = GoogleSiteMapGenerator::CHANGE_FREQ_YEARLY;
     } elseif ($period > 60 * 60 * 24 * 30) {
         $freq = GoogleSiteMapGenerator::CHANGE_FREQ_MONTHLY;
     } elseif ($period > 60 * 60 * 24 * 7) {
         $freq = GoogleSiteMapGenerator::CHANGE_FREQ_WEEKLY;
     } elseif ($period > 60 * 60 * 24) {
         $freq = GoogleSiteMapGenerator::CHANGE_FREQ_DAILY;
     } elseif ($period > 60 * 60) {
         $freq = GoogleSiteMapGenerator::CHANGE_FREQ_HOURLY;
     } else {
         $freq = GoogleSiteMapGenerator::CHANGE_FREQ_ALWAYS;
     }
     return $freq;
 }
 /**
  * Formatted Dates
  * Returns either the event's date or both start and end date if the event spans more than
  * one date
  *
  * Format:
  * Jun 7th - Jun 10th
  *
  * @param SS_Datetime $startObj
  * @param SS_Datetime $endObj
  * @return string
  */
 public static function formatted_dates($startObj, $endObj)
 {
     //Checking if end date is set
     $endDateIsset = true;
     if (isset($endObj->value)) {
         $endDateIsset = false;
     }
     $startTime = strtotime($startObj->value);
     $endTime = strtotime($endObj->value);
     $startMonth = date('M', $startTime);
     $startDayOfMonth = $startObj->DayOfMonth(true);
     $str = $startMonth . ' ' . $startDayOfMonth;
     if (date('Y-m-d', $startTime) == date('Y-m-d', $endTime)) {
         //one date - str. has already been written
     } else {
         //two dates
         if ($endDateIsset) {
             $endMonth = date('M', $endTime);
             $endDayOfMonth = $endObj->DayOfMonth(true);
             if ($startMonth == $endMonth) {
                 $str .= ' - ' . $endDayOfMonth;
             } else {
                 $str .= ' - ' . $endMonth . ' ' . $endDayOfMonth;
             }
         }
     }
     return $str;
 }
 /**
  * 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 LastUpdated()
 {
     $elements = new DataList($this->dataClass);
     $lastUpdated = new SS_Datetime('LastUpdated');
     $lastUpdated->setValue($elements->max('LastEdited'));
     return $lastUpdated;
 }
 /**
  * Returns a pages change frequency calculated by pages age and number of 
  * versions. Google expects always, hourly, daily, weekly, monthly, yearly 
  * or never as values.
  * 
  * @see http://support.google.com/webmasters/bin/answer.py?hl=en&answer=183668&topic=8476&ctx=topic
  *
  * @return SS_Datetime
  */
 public function getChangeFrequency()
 {
     if ($freq = GoogleSitemap::get_frequency_for_class($this->owner->class)) {
         return $freq;
     }
     $date = date('Y-m-d H:i:s');
     $created = new SS_Datetime();
     $created->value = $this->owner->Created ? $this->owner->Created : $date;
     $now = new SS_Datetime();
     $now->value = $date;
     $versions = $this->owner->Version ? $this->owner->Version : 1;
     $timediff = $now->format('U') - $created->format('U');
     // Check how many revisions have been made over the lifetime of the
     // Page for a rough estimate of it's changing frequency.
     $period = $timediff / ($versions + 1);
     if ($period > 60 * 60 * 24 * 365) {
         $freq = 'yearly';
     } elseif ($period > 60 * 60 * 24 * 30) {
         $freq = 'monthly';
     } elseif ($period > 60 * 60 * 24 * 7) {
         $freq = 'weekly';
     } elseif ($period > 60 * 60 * 24) {
         $freq = 'daily';
     } elseif ($period > 60 * 60) {
         $freq = 'hourly';
     } else {
         $freq = 'always';
     }
     return $freq;
 }
 private static function generate_data_for_day(SS_Datetime $date)
 {
     $data = array('timestamp' => time(), 'searchDate' => $date->Format("Y-m-d"), 'collections' => array('events' => array(), 'galleries' => array(), 'locations' => array()));
     $galleryIDs = array();
     $locationIDs = array();
     // Get events
     $where = sprintf("DATE(`StartDate`) = '%s'", $date->Format('Y-m-d'));
     $events = Event::get()->where($where)->exclude(array("GalleryID" => 0, "Gallery.LocationID" => 0));
     foreach ($events as $event) {
         $galleryIDs[] = $event->GalleryID;
         $data['collections']['events'][] = $event->forAPI();
     }
     // Get galleries
     $galleries = Gallery::get()->byIDs(array_unique($galleryIDs));
     foreach ($galleries as $gallery) {
         $locationIDs[] = $gallery->LocationID;
         $data['collections']['galleries'][] = $gallery->forAPI();
     }
     // Get locations
     $locations = Location::get()->byIDs(array_unique($locationIDs));
     foreach ($locations as $location) {
         $data['collections']['locations'][] = $location->forAPI();
     }
     return $data;
 }
 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 Items()
 {
     $filter = '';
     $bt = defined('DB::USE_ANSI_SQL') ? "\"" : "`";
     if (self::$use_show_in_search) {
         $filter = "{$bt}ShowInSearch{$bt} = 1";
     }
     $this->Pages = Versioned::get_by_stage('SiteTree', 'Live', $filter);
     $newPages = new DataObjectSet();
     if ($this->Pages) {
         foreach ($this->Pages as $page) {
             // Only include pages from this host and pages which are not an instance of ErrorPage
             // We prefix $_SERVER['HTTP_HOST'] with 'http://' so that parse_url to help parse_url identify the host name component; we could use another protocol (like
             // 'ftp://' as the prefix and the code would work the same.
             if (parse_url($page->AbsoluteLink(), PHP_URL_HOST) == parse_url('http://' . $_SERVER['HTTP_HOST'], PHP_URL_HOST) && !$page instanceof ErrorPage) {
                 // If the page has been set to 0 priority, we set a flag so it won't be included
                 if ($page->canView() && (!isset($page->Priority) || $page->Priority > 0)) {
                     // The one field that isn't easy to deal with in the template is
                     // Change frequency, so we set that here.
                     $properties = $page->toMap();
                     $created = new SS_Datetime();
                     $created->value = $properties['Created'];
                     $now = new SS_Datetime();
                     $now->value = date('Y-m-d H:i:s');
                     $versions = $properties['Version'];
                     $timediff = $now->format('U') - $created->format('U');
                     // Check how many revisions have been made over the lifetime of the
                     // Page for a rough estimate of it's changing frequency.
                     $period = $timediff / ($versions + 1);
                     if ($period > 60 * 60 * 24 * 365) {
                         // > 1 year
                         $page->ChangeFreq = 'yearly';
                     } elseif ($period > 60 * 60 * 24 * 30) {
                         // > ~1 month
                         $page->ChangeFreq = 'monthly';
                     } elseif ($period > 60 * 60 * 24 * 7) {
                         // > 1 week
                         $page->ChangeFreq = 'weekly';
                     } elseif ($period > 60 * 60 * 24) {
                         // > 1 day
                         $page->ChangeFreq = 'daily';
                     } elseif ($period > 60 * 60) {
                         // > 1 hour
                         $page->ChangeFreq = 'hourly';
                     } else {
                         // < 1 hour
                         $page->ChangeFreq = 'always';
                     }
                     $newPages->push($page);
                 }
             }
         }
         return $newPages;
     }
 }
Example #10
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;
 }
 /**
  * Test CronTaskController::runTask
  */
 public function testRunTask()
 {
     $runner = CronTaskController::create();
     $runner->setQuiet(true);
     $task = new CronTaskTest_TestCron();
     // Assuming first run, match the exact time (seconds are ignored)
     $this->assertEquals(0, CronTaskTest_TestCron::$times_run);
     SS_Datetime::set_mock_now('2010-06-20 13:00:10');
     $runner->runTask($task);
     $this->assertEquals(1, CronTaskTest_TestCron::$times_run);
     // Test that re-requsting the task in the same minute do not retrigger another run
     SS_Datetime::set_mock_now('2010-06-20 13:00:40');
     $runner->runTask($task);
     $this->assertEquals(1, CronTaskTest_TestCron::$times_run);
     // Job prior to next hour mark should not run
     SS_Datetime::set_mock_now('2010-06-20 13:40:00');
     $runner->runTask($task);
     $this->assertEquals(1, CronTaskTest_TestCron::$times_run);
     // Jobs just after the next hour mark should run
     SS_Datetime::set_mock_now('2010-06-20 14:10:00');
     $runner->runTask($task);
     $this->assertEquals(2, CronTaskTest_TestCron::$times_run);
     // Jobs run on the exact next expected date should run
     SS_Datetime::set_mock_now('2010-06-20 15:00:00');
     $runner->runTask($task);
     $this->assertEquals(3, CronTaskTest_TestCron::$times_run);
     // Jobs somehow delayed a whole day should be run
     SS_Datetime::set_mock_now('2010-06-21 13:40:00');
     $runner->runTask($task);
     $this->assertEquals(4, CronTaskTest_TestCron::$times_run);
 }
 /**
  * Return the form field
  *
  */
 public function getFormField()
 {
     $defaultValue = $this->DefaultToToday ? SS_Datetime::now()->Format('Y-m-d') : $this->Default;
     $field = EditableDateField_FormField::create($this->Name, $this->EscapedTitle, $defaultValue)->setConfig('showcalendar', true)->setFieldHolderTemplate('UserFormsField_holder')->setTemplate('UserFormsField');
     $this->doUpdateFormField($field);
     return $field;
 }
 public function LatestTweetsList($limit = '5')
 {
     $conf = SiteConfig::current_site_config();
     if (empty($conf->TwitterName) || empty($conf->TwitterConsumerKey) || empty($conf->TwitterConsumerSecret) || empty($conf->TwitterAccessToken) || empty($conf->TwitterAccessTokenSecret)) {
         return new ArrayList();
     }
     $cache = SS_Cache::factory('LatestTweets_cache');
     if (!($results = unserialize($cache->load(__FUNCTION__)))) {
         $results = new ArrayList();
         require_once dirname(__FILE__) . '/tmhOAuth/tmhOAuth.php';
         require_once dirname(__FILE__) . '/tmhOAuth/tmhUtilities.php';
         $tmhOAuth = new tmhOAuth(array('consumer_key' => $conf->TwitterConsumerKey, 'consumer_secret' => $conf->TwitterConsumerSecret, 'user_token' => $conf->TwitterAccessToken, 'user_secret' => $conf->TwitterAccessTokenSecret, 'curl_ssl_verifypeer' => false));
         $code = $tmhOAuth->request('GET', $tmhOAuth->url('1.1/statuses/user_timeline'), array('screen_name' => $conf->TwitterName, 'count' => $limit));
         $tweets = $tmhOAuth->response['response'];
         $json = new JSONDataFormatter();
         if (($arr = $json->convertStringToArray($tweets)) && is_array($arr) && isset($arr[0]['text'])) {
             foreach ($arr as $tweet) {
                 try {
                     $here = new DateTime(SS_Datetime::now()->getValue());
                     $there = new DateTime($tweet['created_at']);
                     $there->setTimezone($here->getTimezone());
                     $date = $there->Format('Y-m-d H:i:s');
                 } catch (Exception $e) {
                     $date = 0;
                 }
                 $results->push(new ArrayData(array('Text' => nl2br(tmhUtilities::entify_with_options($tweet, array('target' => '_blank'))), 'Date' => SS_Datetime::create_field('SS_Datetime', $date))));
             }
         }
         $cache->save(serialize($results), __FUNCTION__);
     }
     return $results;
 }
 /**
  * Export core
  *
  * Replaces definition in GridFieldPrintButton
  * same as original except sources data from $gridField->getList() instead of $gridField->getManipulatedList()
  *
  * @param GridField
  */
 public function generatePrintData(GridField $gridField)
 {
     $printColumns = $this->getPrintColumnsForGridField($gridField);
     $header = null;
     if ($this->printHasHeader) {
         $header = new ArrayList();
         foreach ($printColumns as $field => $label) {
             $header->push(new ArrayData(array("CellString" => $label)));
         }
     }
     // The is the only variation from the parent class, using getList() instead of getManipulatedList()
     $items = $gridField->getList();
     $itemRows = new ArrayList();
     foreach ($items as $item) {
         $itemRow = new ArrayList();
         foreach ($printColumns as $field => $label) {
             $value = $gridField->getDataFieldValue($item, $field);
             $itemRow->push(new ArrayData(array("CellString" => $value)));
         }
         $itemRows->push(new ArrayData(array("ItemRow" => $itemRow)));
         $item->destroy();
     }
     $ret = new ArrayData(array("Title" => $this->getTitle($gridField), "Header" => $header, "ItemRows" => $itemRows, "Datetime" => SS_Datetime::now(), "Member" => Member::currentUser()));
     return $ret;
 }
 public function getEventsAction(SS_HTTPRequest $request)
 {
     // Search date
     $date = DBField::create_field("SS_Datetime", $request->param("SearchDate"));
     if (!$date->getValue()) {
         $date = SS_Datetime::now();
     }
     // Get event data
     $cache = SS_Cache::factory(self::EVENTS_CACHE_NAME);
     $cacheKey = $date->Format('Y_m_d');
     if ($result = $cache->load($cacheKey)) {
         $data = unserialize($result);
     } else {
         $data = EventsDataUtil::get_events_data_for_day($date);
         $cache->save(serialize($data), $cacheKey);
     }
     // Get init data
     if ($request->param("GetAppConfig")) {
         $cache = SS_Cache::factory(self::CONFIG_CACHE_NAME);
         $cacheKey = 'APP_CONFIG';
         if ($result = $cache->load($cacheKey)) {
             $configData = unserialize($result);
         } else {
             $configData = AppConfigDataUtil::get_config_data();
             $cache->save(serialize($configData), $cacheKey);
         }
         $data['appConfig'] = $configData;
     }
     return $this->sendResponse($data);
 }
 /**
  * Augment queries so that we don't fetch unpublished articles.
  **/
 public function augmentSQL(SQLQuery &$query)
 {
     $stage = Versioned::current_stage();
     if ($stage == 'Live' || !Permission::check("VIEW_DRAFT_CONTENT")) {
         $query->addWhere("PublishDate < '" . Convert::raw2sql(SS_Datetime::now()) . "'");
     }
 }
 public function prepValueForDB($value)
 {
     $value = parent::prepValueForDB($value);
     $ciphertext = $this->service->encrypt($value);
     $this->value = $ciphertext;
     return $ciphertext;
 }
 public function approve()
 {
     $this->Moderated = true;
     $this->IsApproved = true;
     $this->write();
     $parent = $this->getParent();
     //debug::show($parent->ClassName);
     if ($parent->GuestBookID) {
         $GuestBookPage = $parent->GuestBook();
         $oBlogParent = $GuestBookPage->Level(1);
         //$GuestBookPageChildClass = $this->getGuestBookPageChildClass($GuestBook);
         $GuestBook = new BlogPost();
         $GuestBook->Title = $this->Title;
         $GuestBook->AuthorNames = $this->Author;
         $GuestBook->Content = $this->Content;
         $GuestBook->PublishDate = SS_Datetime::now()->getValue();
         $GuestBook->ParentID = $oBlogParent->ID;
         $GuestBook->FeaturedImageID = $this->ImageID;
         $GuestBook->doPublish();
         $GuestBook->write();
         $GuestBook->doRestoreToStage();
         //$GuestBook->writeToStage("Stage", "Live");
         $this->GuestBookLinkingID = $GuestBook->ID;
         $GuestBook->ShowInMenus = true;
         $GuestBook->doPublish();
         $GuestBook->write();
         $GuestBook->doRestoreToStage();
     }
     $this->write();
     return 'Submission published';
 }
 /**
  * Send customer an order receipt email.
  * Precondition: The order payment has been successful
  */
 public function sendReceipt()
 {
     $subject = sprintf(_t("OrderNotifier.RECEIPTSUBJECT", "Order #%d Receipt"), $this->order->Reference);
     $this->sendEmail('Order_ReceiptEmail', $subject, self::config()->bcc_receipt_to_admin);
     $this->order->ReceiptSent = SS_Datetime::now()->Rfc2822();
     $this->order->write();
 }
 public function process()
 {
     $nextTask = DevTaskRun::get_next_task();
     if ($nextTask) {
         //create task instance
         $task = Injector::inst()->create($nextTask->Task);
         //get params
         $params = explode(' ', $nextTask->Params);
         $paramList = array();
         if ($params) {
             foreach ($params as $param) {
                 $parts = explode('=', $param);
                 if (count($parts) === 2) {
                     $paramList[$parts[0]] = $parts[1];
                 }
             }
         }
         echo 'Starting task ' . $task->getTitle() . "\n";
         //remove so it doesn't get rerun
         $nextTask->Status = 'Running';
         $nextTask->write();
         $request = new SS_HTTPRequest('GET', 'dev/tasks/' . $nextTask->Task, $paramList);
         $task->run($request);
         $nextTask->Status = 'Finished';
         $nextTask->FinishDate = SS_Datetime::now()->getValue();
         $nextTask->write();
         echo 'Finished task ' . $task->getTitle() . "\n";
     }
 }
 /**
  * Add the default for the Date being the current day.
  */
 public function populateDefaults()
 {
     parent::populateDefaults();
     if (!isset($this->Date) || $this->Date === null) {
         $this->Date = SS_Datetime::now()->Format('Y-m-d H:i:s');
     }
 }
 /**
  * Prepares this combined report
  *
  * Functions the same as the parent class, but we need to
  * clone the Related reports too
  *
  * @return CombinedReport
  */
 public function prepareAndGenerate()
 {
     $report = $this->duplicate(false);
     $report->ReportID = $this->ID;
     $report->Created = SS_Datetime::now();
     $report->LastEdited = SS_Datetime::now();
     $report->Title = $this->GeneratedReportTitle;
     $report->write();
     $toClone = $this->ChildReports();
     if ($toClone) {
         foreach ($toClone as $child) {
             $clonedChild = $child->duplicate(false);
             $clonedChild->Created = SS_Datetime::now();
             $clonedChild->LastEdited = SS_Datetime::now();
             $clonedChild->CombinedReportID = $report->ID;
             $clonedChild->write();
         }
     }
     $report->generateReport('html');
     $report->generateReport('csv');
     if (class_exists('PdfRenditionService')) {
         $report->generateReport('pdf');
     }
     return $report;
 }
 /**
  * @dataProvider canViewProvider
  */
 public function testCanView($date, $user, $page, $canView)
 {
     $userRecord = $this->objFromFixture('Member', $user);
     $pageRecord = $this->objFromFixture('BlogPost', $page);
     SS_Datetime::set_mock_now($date);
     $this->assertEquals($canView, $pageRecord->canView($userRecord));
 }
 /**
  * Determine selected BlogEntry items to show on this page
  * 
  * @param int $limit
  * @return PaginatedList
  */
 public function FilteredBlogEntries($limit = null)
 {
     require_once 'Zend/Date.php';
     if ($limit === null) {
         $limit = BlogTree::$default_entries_limit;
     }
     // only use freshness if no action is present (might be displaying tags or rss)
     if ($this->owner->LandingPageFreshness && !$this->owner->request->param('Action')) {
         $d = new Zend_Date(SS_Datetime::now()->getValue());
         $d->sub($this->owner->LandingPageFreshness, Zend_Date::MONTH);
         $date = $d->toString('YYYY-MM-dd');
         $filter = "\"BlogEntry\".\"Date\" > '{$date}'";
     } else {
         $filter = '';
     }
     // allow filtering by author field and some blogs have an authorID field which
     // may allow filtering by id
     if (isset($_GET['author']) && isset($_GET['authorID'])) {
         $author = Convert::raw2sql($_GET['author']);
         $id = Convert::raw2sql($_GET['authorID']);
         $filter .= " \"BlogEntry\".\"Author\" LIKE '" . $author . "' OR \"BlogEntry\".\"AuthorID\" = '" . $id . "'";
     } else {
         if (isset($_GET['author'])) {
             $filter .= " \"BlogEntry\".\"Author\" LIKE '" . Convert::raw2sql($_GET['author']) . "'";
         } else {
             if (isset($_GET['authorID'])) {
                 $filter .= " \"BlogEntry\".\"AuthorID\" = '" . Convert::raw2sql($_GET['authorID']) . "'";
             }
         }
     }
     $date = $this->owner->SelectedDate();
     return $this->owner->Entries($limit, $this->owner->SelectedTag(), $date ? $date : '', array(get_class($this), 'FilterByDate'), $filter);
 }
 public function preRequest(SS_HTTPRequest $request, Session $session, DataModel $model)
 {
     if (!$this->testSessionEnvironment->isRunningTests()) {
         return;
     }
     $testState = $this->testSessionEnvironment->getState();
     // Date and time
     if (isset($testState->datetime)) {
         SS_Datetime::set_mock_now($testState->datetime);
     }
     // Register mailer
     if (isset($testState->mailer)) {
         $mailer = $testState->mailer;
         Email::set_mailer(new $mailer());
         Config::inst()->update("Email", "send_all_emails_to", null);
     }
     // Allows inclusion of a PHP file, usually with procedural commands
     // to set up required test state. The file can be generated
     // through {@link TestSessionStubCodeWriter}, and the session state
     // set through {@link TestSessionController->set()} and the
     // 'testsession.stubfile' state parameter.
     if (isset($testState->stubfile)) {
         $file = $testState->stubfile;
         if (!Director::isLive() && $file && file_exists($file)) {
             // Connect to the database so the included code can interact with it
             global $databaseConfig;
             if ($databaseConfig) {
                 DB::connect($databaseConfig);
             }
             include_once $file;
         }
     }
 }
 function SaveDeployment($data, $form)
 {
     $id = convert::raw2sql($data['DeploymentID']);
     // Only loaded if it belongs to current user
     $Deployment = $form->controller->LoadDeployment($id);
     // If a deployment wasn't returned, we'll create a new one
     if (!$Deployment) {
         $Deployment = new Deployment();
         $Deployment->OrgID = Member::currentUser()->getCurrentOrganization()->ID;
         $newDeploy = true;
     }
     $form->saveInto($Deployment);
     $survey = $form->controller->GetCurrentSurvey();
     $Deployment->DeploymentSurveyID = $survey->ID;
     $Deployment->UpdateDate = SS_Datetime::now()->Rfc2822();
     $Deployment->OrgID = $survey->OrgID;
     $Deployment->write();
     /**/
     $survey->CurrentStep = 'MoreDeploymentDetails';
     $survey->HighestStepAllowed = 'MoreDeploymentDetails';
     $survey->UpdateDate = SS_Datetime::now()->Rfc2822();
     $survey->write();
     // If it is a new deployment and it is public, we send an email...
     if (isset($newDeploy) && $Deployment->IsPublic === 1) {
         global $email_new_deployment;
         global $email_from;
         $email = EmailFactory::getInstance()->buildEmail($email_from, $email_new_deployment, 'New Deployment');
         $email->setTemplate('NewDeploymentEmail');
         $email->populateTemplate(array('Deployment' => $Deployment));
         $email->send();
     }
     Session::set('CurrentDeploymentID', $Deployment->ID);
     Controller::curr()->redirect($form->controller->Link() . 'MoreDeploymentDetails');
 }
 function index()
 {
     $posts = $this->request->postVars();
     $filename = $posts['filename'];
     $surveyID = intval($posts['surveyID']);
     if (!$filename || !Member::currentUser() || !$surveyID || !($Survey = Survey::get()->filter('ID', $surveyID)->first())) {
         return false;
     }
     $folder = Folder::find_or_make('jsonFormFiles');
     $fullFileName = Director::baseFolder() . '/' . $folder->getRelativePath() . $filename . '.json';
     $jsonString = '{"name":"' . $Survey->Name . '","startDate": "' . $Survey->StartDate . '", "endDate": "' . $Survey->EndDate . '","sections": [';
     foreach ($Survey->Sections() as $Section) {
         $jsonString .= '{"Title": "' . $Section->Title . '","Descripton": "' . $Section->Description . '","sectionQuestions": [';
         foreach ($Section->SurveyQuestions() as $SQ) {
             $jsonString .= '{"number": "' . $SQ->Number . '","title": "' . $SQ->Title . '","description":"' . $SQ->Description . '","helpText": "' . $SQ->HelpText . '","questions": [';
             foreach ($SQ->Questions() as $Question) {
                 $jsonString .= $Question->renderJson();
             }
             $jsonString = rtrim($jsonString, ",");
             $jsonString .= ']},';
         }
         $jsonString = rtrim($jsonString, ",");
         $jsonString .= ']},';
     }
     $jsonString = rtrim($jsonString, ",");
     $jsonString .= ']}';
     file_put_contents($fullFileName, $jsonString);
     $Survey->LastJsonGenerated = SS_Datetime::now()->getValue();
     $Survey->write();
 }
 public function testGetNextDateTimeDuring()
 {
     $sched = $this->objFromFixture('ScheduleRangeDay', 'schedDay1');
     //During
     SS_Datetime::set_mock_now('2015-10-03 12:30:00');
     $this->assertEquals('2015-10-03 13:00:00', $sched->getNextDateTime()->Format('Y-m-d H:i:s'));
 }
 /**
  * @inheritdoc
  *
  * @return array
  */
 function check()
 {
     $cutoffTime = strtotime($this->relativeAge, SS_Datetime::now()->Format('U'));
     $files = $this->getFiles();
     $invalidFiles = array();
     $validFiles = array();
     $checkFn = $this->checkFn;
     $allValid = true;
     if ($files) {
         foreach ($files as $file) {
             $fileTime = $checkFn($file);
             $valid = $this->compareOperand == '>' ? $fileTime >= $cutoffTime : $fileTime <= $cutoffTime;
             if ($valid) {
                 $validFiles[] = $file;
             } else {
                 $invalidFiles[] = $file;
                 if ($this->checkType == self::CHECK_ALL) {
                     return array(EnvironmentCheck::ERROR, sprintf('File "%s" doesn\'t match age check (compare %s: %s, actual: %s)', $file, $this->compareOperand, date('c', $cutoffTime), date('c', $fileTime)));
                 }
             }
         }
     }
     // If at least one file was valid, count as passed
     if ($this->checkType == self::CHECK_SINGLE && count($invalidFiles) < count($files)) {
         return array(EnvironmentCheck::OK, '');
     } else {
         if (count($invalidFiles) == 0) {
             return array(EnvironmentCheck::OK, '');
         } else {
             return array(EnvironmentCheck::ERROR, sprintf('No files matched criteria (%s %s)', $this->compareOperand, date('c', $cutoffTime)));
         }
     }
 }
 public function start()
 {
     // Ensure started date is set
     if (!$this->Started) {
         $this->Started = SS_Datetime::now()->Rfc2822();
         $this->write();
     }
 }