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(); }
/** * @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))); } } }
/** * 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(); }
/** * 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 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'; }
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; }
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'); }
/** * 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; }
/** * 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 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"; } }
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()) . "'"); } }
/** * 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; }
function getCurrentSprint() { $now = SS_Datetime::now()->URLDate(); $currentSprints = $this->Sprints("StartDate <= '{$now}' && EndDate >= '{$now}'"); if ($currentSprints) { return $currentSprints->first(); } }
/** * Marks the subbmission for the exam as finished * * @return \SS_HTTPResponse */ public function finishexam() { if ($submission = ExamSubmission::get()->byID($this->getRequest()->postVar('SubmissionID'))) { $submission->FinishTime = \SS_Datetime::now()->getValue(); $submission->write(); return $this->respond(['Finished' => true]); } }
public function start() { // Ensure started date is set if (!$this->Started) { $this->Started = SS_Datetime::now()->Rfc2822(); $this->write(); } }
/** * {@inheritdoc} */ public function liveChildren($showAll = false, $onlyDeletedFromStage = false) { $staged = parent::liveChildren($showAll, $onlyDeletedFromStage); if (!$this->shouldFilter() && $this->isBlog() && !Permission::check('VIEW_DRAFT_CONTENT')) { $dataQuery = $staged->dataQuery()->innerJoin('BlogPost', '"BlogPost_Live"."ID" = "SiteTree_Live"."ID"')->where(sprintf('"PublishDate" < \'%s\'', Convert::raw2sql(SS_Datetime::now()))); $staged = $staged->setDataQuery($dataQuery); } return $staged; }
public function onQueue(TransitionEvent $e) { /** @var DNDeployment $deployment */ $deployment = $e->getStateMachine()->getObject(); $token = $deployment->enqueueDeployment(); $deployment->setResqueToken($token); $deployment->DeployStarted = SS_Datetime::now()->Rfc2822(); $deployment->write(); $deployment->log()->write(sprintf('Deploy queued as job %s (sigFile is %s)', $token, $deployment->getSigFile())); }
/** * Augment queries so that we don't fetch unpublished articles. * * @param SQLQuery $query */ public function augmentSQL(SQLQuery &$query) { $stage = Versioned::current_stage(); if (Controller::curr() instanceof LeftAndMain) { return; } if ($stage == 'Live' || !Permission::check('VIEW_DRAFT_CONTENT')) { $query->addWhere(sprintf('"PublishDate" < \'%s\'', Convert::raw2sql(SS_Datetime::now()))); } }
/** * Augments (@link Hierarchy::liveChildren()} * * @param $staged DataList * @param $showAll boolean **/ public function liveChildren($showAll = false, $onlyDeletedFromStage = false) { $staged = parent::liveChildren($showAll, $onlyDeletedFromStage); if (!$this->shouldFilter() && in_array(get_class($this->owner), ClassInfo::subClassesFor("Blog")) && !Permission::check("VIEW_DRAFT_CONTENT")) { // Filter publish posts $dataQuery = $staged->dataQuery()->innerJoin("BlogPost", '"BlogPost_Live"."ID" = "SiteTree"_"Live"."ID"')->where('"PublishDate" < \'' . Convert::raw2sql(SS_Datetime::now()) . '\''); $staged = $staged->setDataQuery($dataQuery); } return $staged; }
/** * Clear out stale jobs based on the cleanup values */ public function process() { $statusList = implode('\', \'', $this->config()->cleanup_statuses); switch ($this->config()->cleanup_method) { // If Age, we need to get jobs that are at least n days old case "age": $cutOff = date("Y-m-d H:i:s", strtotime(SS_Datetime::now() . " - " . $this->config()->cleanup_value . " days")); $stale = DB::query('SELECT "ID" FROM "QueuedJobDescriptor" WHERE "JobStatus" IN (\'' . $statusList . '\') AND "LastEdited" < \'' . $cutOff . '\''); $staleJobs = $stale->column("ID"); break; // If Number, we need to save n records, then delete from the rest // If Number, we need to save n records, then delete from the rest case "number": $fresh = DB::query('SELECT "ID" FROM "QueuedJobDescriptor" ORDER BY "LastEdited" ASC LIMIT ' . $this->config()->cleanup_value); $freshJobIDs = implode('\', \'', $fresh->column("ID")); $stale = DB::query('SELECT "ID" FROM "QueuedJobDescriptor" WHERE "ID" NOT IN (\'' . $freshJobIDs . '\') AND "JobStatus" IN (\'' . $statusList . '\')'); $staleJobs = $stale->column("ID"); break; default: $this->addMessage("Incorrect configuration values set. Cleanup ignored"); $this->isComplete = true; return; } if (empty($staleJobs)) { $this->addMessage("No jobs to clean up."); $this->isComplete = true; return; } $numJobs = count($staleJobs); $staleJobs = implode('\', \'', $staleJobs); DB::query('DELETE FROM "QueuedJobDescriptor" WHERE "ID" IN (\'' . $staleJobs . '\')'); $this->addMessage($numJobs . " jobs cleaned up."); // let's make sure there is a cleanupJob in the queue if (Config::inst()->get('CleanupJob', 'is_enabled')) { $this->addMessage("Queueing the next Cleanup Job."); $cleanup = new CleanupJob(); singleton('QueuedJobService')->queueJob($cleanup, date('Y-m-d H:i:s', time() + 86400)); } $this->isComplete = true; return; }
/** * @param string $callerClass */ public static function get($callerClass = null, $filter = "", $sort = "", $join = "", $limit = null, $containerClass = 'DataList') { $get = parent::get($callerClass, $filter, $sort, $join, $limit, $containerClass); $now = SS_Datetime::now()->getValue(); foreach ($get as $x) { if ($x->ScreeningTime < $now) { $get->removeByID($x->ID); $x->delete(); } } return $get; }
public function addSignature($member = null) { if (!$member) { $member = Member::currentUser(); } $sig = new UserAgreementSignature(); $sig->MemberID = $member->ID; $sig->DateAgreed = SS_Datetime::now(); $sig->SessionID = session_id(); $sig->AgreementContent = $this->Content; $this->Signatures()->add($sig); }
public function testDeploy() { SS_Datetime::set_mock_now(date('Y-m-d H:i:s')); $step = $this->getDummyConfirmationStep(); $step->start(); $step->deploy(); // Assert not error at startup $this->assertEquals('Finished', $step->Status); // Assert that 'now' is used for the deployment date $this->assertEquals(SS_Datetime::now()->Format('Y-m-d H:i:s'), $step->Deployed); $this->assertHasLog('RequestDeploymentStep is being deployed'); }
protected function onBeforeWrite() { parent::onBeforeWrite(); if (empty($this->PostDate)) { $this->PostDate = SS_Datetime::now()->Rfc2822(); } if (empty($this->ExpirationDate)) { $expiration_date = new DateTime(); $expiration_date->add(new DateInterval('P2M')); $this->ExpirationDate = $expiration_date->format('Y-m-d'); } }
public function testRollback() { SS_Datetime::set_mock_now(date('Y-m-d H:i:s')); $step = $this->getDummyConfirmationStep(); $step->start(); $step->rollback(); // Assert not error at startup $this->assertEquals('Started', $step->Status); // Assert that 'now' is used for the deployment date $this->assertEquals(SS_Datetime::now()->Format('Y-m-d H:i:s'), $step->RolledBack); $this->assertHasLog('RollbackWindowStep is being rolled back'); }
/** * @param array $params * * @return SS_List */ public function sourceRecords($params = array()) { Versioned::reading_stage("Stage"); $records = SiteTree::get(); $compatibility = ContentReviewCompatability::start(); if (empty($params["ReviewDateBefore"]) && empty($params["ReviewDateAfter"])) { // If there's no review dates set, default to all pages due for review now $reviewDate = new Zend_Date(SS_Datetime::now()->Format("U")); $reviewDate->add(1, Zend_Date::DAY); $records = $records->where(sprintf('"NextReviewDate" < \'%s\'', $reviewDate->toString("YYYY-MM-dd"))); } else { // Review date before if (!empty($params['ReviewDateBefore'])) { // TODO Get value from DateField->dataValue() once we have access to form elements here $reviewDate = new Zend_Date($params["ReviewDateBefore"], Config::inst()->get("i18n", "date_format")); $reviewDate->add(1, Zend_Date::DAY); $records = $records->where(sprintf("\"NextReviewDate\" < '%s'", $reviewDate->toString("YYYY-MM-dd"))); } // Review date after if (!empty($params["ReviewDateAfter"])) { // TODO Get value from DateField->dataValue() once we have access to form elements here $reviewDate = new Zend_Date($params["ReviewDateAfter"], Config::inst()->get("i18n", "date_format")); $records = $records->where(sprintf("\"NextReviewDate\" >= '%s'", $reviewDate->toString("YYYY-MM-dd"))); } } // Show virtual pages? if (empty($params["ShowVirtualPages"])) { $virtualPageClasses = ClassInfo::subclassesFor("VirtualPage"); $records = $records->where(sprintf("\"SiteTree\".\"ClassName\" NOT IN ('%s')", implode("','", array_values($virtualPageClasses)))); } // Owner dropdown if (!empty($params["ContentReviewOwner"])) { $ownerNames = Convert::raw2sql($params["ContentReviewOwner"]); $records = $records->filter("OwnerNames:PartialMatch", $ownerNames); } // Only show pages assigned to the current user? // This come last because it transforms $records to an ArrayList. if (!empty($params["OnlyMyPages"])) { $currentUser = Member::currentUser(); $records = $records->filterByCallback(function ($page) use($currentUser) { $options = $page->getOptions(); foreach ($options->ContentReviewOwners() as $owner) { if ($currentUser->ID == $owner->ID) { return true; } } return false; }); } ContentReviewCompatability::done($compatibility); return $records; }
/** * @param string $token * @return bool * @throws InvalidHashSpeakerRegistrationRequestException * @throws SpeakerRegistrationRequestAlreadyConfirmedException */ public function confirm($token) { $original_hash = $this->getField('ConfirmationHash'); if ($this->IsConfirmed) { throw new SpeakerRegistrationRequestAlreadyConfirmedException(); } if (self::HashConfirmationToken($token) === $original_hash) { $this->IsConfirmed = true; $this->ConfirmationDate = SS_Datetime::now()->Rfc2822(); return true; } throw new InvalidHashSpeakerRegistrationRequestException(); }
public function postRequest(\SS_HTTPRequest $request, \SS_HTTPResponse $response, \DataModel $model) { $actions = $this->microBlogService->getUserActions(); if ($actions && count($actions)) { $members = Member::get()->filter('ID', array_keys($actions)); foreach ($members as $member) { if ($member->exists()) { $member->LastPostView = SS_Datetime::now()->getValue(); $member->write(); } } } }