public function render(array $data, ContextInterface $context) { // debug($data); // debug($this->_templates); $date_data = ['type' => 'text', 'name' => $data['name'] . '__date__', 'id' => $this->get_dom_id($data['name'] . '-date'), 'language' => $data['language'], 'datepicker_format' => $data['datepicker_format'], 'upper_datepicker_id' => isset($data['upper_datepicker_name']) ? $this->get_dom_id($data['upper_datepicker_name'] . '-date') : null, 'upper_datepicker_name' => isset($data['upper_datepicker_name']) ? $data['upper_datepicker_name'] : null, 'format_on_blur' => $data['format_on_blur'], 'alaxos_js_format' => $data['alaxos_js_format'], 'class' => 'form-control inputDate']; // debug($date_data); $time_data = ['type' => 'text', 'name' => $data['name'] . '__time__', 'id' => $this->get_dom_id($data['name'] . '-time'), 'class' => 'form-control inputTime']; $hidden_data = ['type' => 'hidden', 'name' => $data['name'], 'id' => $this->get_dom_id($data['name'] . '-hidden')]; $display_timezone = null; if (Configure::check('display_timezone')) { $display_timezone = Configure::read('display_timezone'); } elseif (Configure::check('default_display_timezone')) { $display_timezone = Configure::read('default_display_timezone'); } /* * Case of posted data */ if (isset($data['val']) && !empty($data['val']) && is_string($data['val'])) { $data['val'] = Time::parse($data['val'], $display_timezone); } if (isset($data['val']) && (is_a($data['val'], 'Cake\\I18n\\Time') || is_a($data['val'], 'Cake\\I18n\\FrozenTime'))) { if (isset($display_timezone)) { $data['val']->setTimezone($display_timezone); //it doesn't change the timezone internally, but it changes the tz used for display } $datetime = $data['val']; $date_data['value'] = $datetime->format($data['php_date_format']); $time_data['value'] = $datetime->format('H:i'); $hidden_data['value'] = $date_data['value'] . ' ' . $time_data['value']; } $input = $this->get_html_code($date_data, $time_data, $hidden_data); $input .= $this->get_js_code($date_data, $time_data, $hidden_data); return $input; }
public function navbar() { $this->loadModel('Events'); $ongoing_events = $this->Events->find()->select(['id', 'eventname'])->where(['enddate <=' => Time::parse('now'), 'startdate >=' => Time::parse('now')])->order(['startdate' => 'DESC'])->toArray(); $coming_events = $this->Events->find()->select(['id', 'eventname'])->where(['enddate >' => Time::parse('now')])->order(['startdate' => 'DESC'])->toArray(); $past_events = $this->Events->find()->select(['id', 'eventname'])->where(['enddate <' => Time::parse('now')])->order(['startdate' => 'DESC'])->toArray(); $this->set(['ongoing_events' => $ongoing_events, 'coming_events' => $coming_events, 'past_events' => $past_events]); }
public function findUnresolved() { $this->currentTime = Time::parse('now'); $query = $this->find()->contain(['Submissions.Users' => function ($q) { return $q->select(['id']); }])->where(['winner_id IS' => null]); $query->matching('Hunts', function ($q) { return $q->where(['Hunts.voting_end_date <=' => $this->currentTime]); }); return $query; }
public function next_run($original, $last, $period) { date_default_timezone_set(Configure::read('ServerTimeZoneFix')); $real_offset = date('Z'); date_default_timezone_set('UTC'); $now = Time::parse($real_offset . " seconds"); if ($last->lt($original)) { return $original->i18nFormat(null, 'UTC'); } $breaker = true; while ($breaker) { $counter = $original; $counter->modify('+' . $period . "days"); if ($counter->gte($now)) { $breaker = false; } } return $counter->i18nFormat(null, 'UTC'); }
/** * main() method. * * @return void */ public function main() { $this->loadModel('Users'); $timeAgo = '-' . Configure::read('Authentication.login_lock_duration'); $timeLock = Time::parse($timeAgo); $lockedUsers = $this->Users->find()->where(['Users.failed_login_count >=' => Configure::read('Authentication.max_login_retries'), 'Users.failed_login_timestamp <' => $timeLock])->toArray(); if (!empty($lockedUsers)) { $this->out('found ' . count($lockedUsers) . ' locked user to unlock'); $i = 0; foreach ($lockedUsers as $user) { $user->login_retries = 0; $user->failed_login_timestamp = null; if ($this->Users->save($user)) { $i++; } } $this->out('Unlocked ' . $i . ' user'); } else { $this->out('found no locked user to unlock'); } }
public function getStatus($id) { // Only called on a single entity, rather than a map/reduce on a whole table. // Can't tell which one is more 'useful', in the context of this app, though... $now = Time::parse('now'); $query = $this->find()->where(['Hunts.id' => $id])->first(); if ($query['start_date'] <= $now && $query['end_date'] >= $now) { $status['subs'] = "open"; } else { $status['subs'] = "closed"; } if ($query['voting_start_date'] <= $now && $query['voting_end_date'] >= $now) { $status['vote'] = "open"; } else { $status['vote'] = "closed"; } return $status; }
public function testGetBatch() { $identifier = 'test_email_notification_custom'; $this->_createNotificationContent($identifier); $data = ['locale' => 'eng', 'recipient_user_id' => 'f9df9eab-a6a3-4c89-9579-3eaeeb47e25f', 'transport' => 'email', 'config' => ['placeholder1' => 'PL1', 'placeholder2' => 'PL2']]; $notification1 = $this->NotificationQueue->createNotification($identifier, $data); $res1 = $this->NotificationQueue->enqueue($notification1); $notification2 = $this->NotificationQueue->createNotification($identifier, $data); $notification2->created = Time::createFromTimestamp(strtotime('+5hour')); // this is critical, as we're ordering by created when getting a batch $res2 = $this->NotificationQueue->enqueue($notification2); $batch = $this->NotificationQueue->getBatch(1); $this->assertTrue(is_array($batch)); $this->assertEquals(count($batch), 1); $firstNotification = $this->NotificationQueue->get($notification1->id); $secondNotification = $this->NotificationQueue->get($notification2->id); $this->assertTrue($firstNotification->locked); $this->assertFalse($secondNotification->locked); $this->assertEquals($batch[0]->id, $firstNotification->id); // notification1 must not be in the batch, as it is locked by the first batch $batch2 = $this->NotificationQueue->getBatch(); $this->assertTrue(is_array($batch2)); $this->assertEquals(count($batch2), 1); $this->assertEquals($batch2[0]->id, $secondNotification->id); $this->NotificationQueue->clearLocks(); // make sure sent notifications are not added to the batch $this->NotificationQueue->success($notification1->id); $batch2 = $this->NotificationQueue->getBatch(); $this->assertTrue(is_array($batch2)); $this->assertEquals(count($batch2), 1); $this->assertEquals($batch2[0]->id, $secondNotification->id); $this->NotificationQueue->clearLocks(); $notification1->sent = false; $this->NotificationQueue->save($notification1); // make sure notifications which have reached the max send tries are not in the batch $notification2->send_tries = $this->NotificationQueue->getMaxSendTries(); $this->NotificationQueue->save($notification2); $batch3 = $this->NotificationQueue->getBatch(); $this->assertTrue(is_array($batch3)); $this->assertEquals(count($batch3), 1); $this->assertEquals($batch3[0]->id, $firstNotification->id); // notification to be sent in the future shouldn't be in the batch $data['send_after'] = Time::parse('+2 hours'); $notification3 = $this->NotificationQueue->createNotification($identifier, $data); $this->NotificationQueue->save($notification3); $batch4 = $this->NotificationQueue->getBatch(); $this->assertTrue(is_array($batch4)); $this->assertEmpty(count($batch4)); }
protected function _chartjs_statistics() { $wld_template = ['labels' => ['Win', 'Loss', 'Draw'], 'datasets' => [['label' => 'result', 'data' => [0, 0, 0]]]]; $games = $this->Games->find('all'); $games = $this->_restrictToCurrentUser($games); // $games->groupBy('') $unique_pairs = []; $games = $games->toArray(); $loc = ['1' => 0, '-1' => 1, '0' => 2]; foreach ($games as $key => $game) { $game->format($this->Auth->user('id')); $array_key = $game->opponent_id . '-' . $game->game_type_id; if (!array_key_exists(strval($game->result), $loc)) { continue; } if (!array_key_exists($array_key, $unique_pairs)) { $unique_pairs[$array_key]['chart'] = $wld_template; $unique_pairs[$array_key]['key'] = $array_key; $unique_pairs[$array_key]['opponent_id'] = $game->opponent_id; $unique_pairs[$array_key]['opponent_type'] = $game->opponent_type; $unique_pairs[$array_key]['opponent_image'] = $game->opponent_image; $unique_pairs[$array_key]['game_count'] = 0; $unique_pairs[$array_key]['game_type_id'] = $game->game_type_id; $unique_pairs[$array_key]['title'] = $game->opponent_display . ' in ' . $game->game_type_name; $unique_pairs[$array_key]['date'] = ''; } if ($game->result == 0 and !isset($unique_pairs[$array_key]['chart']['datasets'][0][2])) { $unique_pairs[$array_key]['chart']['datasets'][0]['data'][2] = 0; $unique_pairs[$array_key]['chart']['labels'][2] = 'Draw'; } $unique_pairs[$array_key]['chart']['datasets'][0]['data'][$loc[$game->result]]++; if (strtotime($game->created) > strtotime($unique_pairs[$array_key]['date'])) { $unique_pairs[$array_key]['date'] = $game->created; $unique_pairs[$array_key]['date_display'] = 'Last Game: ' . Time::parse($game->created)->nice('America/New_York'); } } usort($unique_pairs, function ($a, $b) { return strtotime($b['date']) - strtotime($a['date']); }); //$stats['chart_data']['datasets'][0]['data'] = $unique_pairs; $this->set(['_serialize' => true, 'success' => true, 'data' => ['chart_data' => $unique_pairs]]); }
public function findByDate() { $currentTime = Time::parse('now'); $now = $currentTime->i18nFormat('YYYY-MM-dd HH:mm:ss'); $query = $this->find()->contain(['Marks.Hunts', 'PictureComments.Users'])->where(['Hunts.voting_end_date <=' => $now])->order(['Pictures.timestamp' => 'DESC']); return $query; }
/** * Returns hash with lines found in /var/log/cakephp/cakebox.cli.log * * @return string Array Containing all log entries */ public function getCakeboxCliLog() { $lines = file($this->cakeboxMeta['cli_log']); $result = []; // extract timestamp, level and message from Monolog logstash format foreach ($lines as $line) { preg_match('/\\"@timestamp\\":\\"(.+)\\",\\"@source.+\\"level\\":(\\d{3}).+\\"@message\\":\\"(.+)\\",\\"@tags".+/', $line, $matches); // parse timestamp so we can split into human readable date and time $time = Time::parse($matches[1]); // add Monolog/RFC 5424 level names // // Should ideally be moved into testable logic or... ask Monolog lib. $level = $matches[2]; switch ($level) { case 100: $levelName = 'debug'; break; case 200: $levelName = 'info'; break; case 250: $levelName = 'notice'; break; case 300: $levelName = 'warning'; break; case 400: $levelName = 'error'; break; case 500: $levelName = 'critical'; break; case 550: $levelName = 'alert'; break; case 600: $levelName = 'emergency'; break; default: $levelName = $level; } // store as rich formatted hash entry $result[] = ['date' => $time->i18nFormat('YYYY-MM-dd'), 'time' => $time->i18nFormat('HH:mm:ss'), 'level' => $level, 'level_name' => $levelName, 'message' => $matches[3]]; } return $result; }
public function cron() { $this->loadModel('Schedules'); $all = $this->Schedules->find('all'); date_default_timezone_set(Configure::read('ServerTimeZoneFix')); $real_offset = date('Z'); date_default_timezone_set('UTC'); $now = Time::parse($real_offset . " seconds"); $this->verbose("Runtime: " . $now); foreach ($all as $task) { $this->verbose("Task #" . $task->id . " Period: " . $task->period . " Original: " . $task->start_time . " Last: " . $task->last_run); $do_this_task = false; if ($task->last_run->lt($task->start_time)) { $this->verbose(' Has never run'); if ($task->start_time->lte($now)) { $do_this_task = true; $this->verbose(' Should run now, overdue'); } else { $this->verbose(' SKIPPING'); } } else { $this->verbose(' Has run'); $counter = $task->start_time; $breaker = true; while ($breaker) { $counter->modify("+" . $task->period . "days"); if ($counter->gt($task->last_run)) { $breaker = false; $this->verbose(' Found next run: ' . $counter); } } if ($counter->lte($now)) { $this->verbose(' Should run now!'); $do_this_task = true; } else { $this->verbose(' SKIPPING'); } } if ($do_this_task) { $this->verbose(' Running task type: ' . $task->jobtype); switch ($task->jobtype) { case "unpaid": $this->sendunpaid($task->sendto); break; case "remind": $this->sendremind(); break; case "tasks": $this->sendtask($task->sendto, $task->show_id); break; case "budget": $this->sendbudget($task->sendto, $task->show_id); break; case "today": $this->sendcal($task->sendto, $task->show_id); break; } $task->last_run = $now; $this->Schedules->save($task); $this->verbose(' Updated last run'); } } }
public function _getModifiedDate() { $modified = Time::parse($this->modified); return $modified->nice('Europe/Paris', 'fr-FR'); }
protected function _addDatetimeCondition(Query $query, $fieldName, $value, array $options = array()) { $default_timezone = date_default_timezone_get(); $display_timezone = $default_timezone; if (isset($this->_config['display_timezone'])) { $display_timezone = $this->_config['display_timezone']; } elseif (Configure::check('display_timezone')) { $display_timezone = Configure::read('display_timezone'); } elseif (Configure::check('default_display_timezone')) { $display_timezone = Configure::read('default_display_timezone'); } // $default_timezone = date_default_timezone_get(); // $display_timezone = !empty($display_timezone) ? $display_timezone : $default_timezone; $date1 = null; $date2 = null; if (is_array($value)) { /* * FROM - TO filter */ if (isset($value['__start__']) && !empty($value['__start__'])) { try { $date1 = Time::parse($value['__start__'], $display_timezone); $date1->setTimezone($default_timezone); } catch (\Exception $ex) { } } if (isset($value['__end__']) && !empty($value['__end__'])) { try { $date2 = Time::parse($value['__end__'], $display_timezone); $date2->setTimezone($default_timezone); } catch (\Exception $ex) { } } } elseif (is_string($value) && !empty($value)) { /* * ONE field filter */ try { $date1 = Time::parse($value, $display_timezone); $date1->setTimezone($default_timezone); } catch (\Exception $ex) { } } /****/ if (isset($date2)) { if (stripos($value['__end__'], ' ') === false) { /* * No time is given -> we should search *including* the end date * -> add one day to searched value */ $date2->addDay(); } } /****/ if (isset($date1) && isset($date2)) { /* * search BETWEEN both dates */ $query->where(function ($exp) use($fieldName, $date1, $date2) { return $exp->gte($fieldName, $date1->toDateTimeString())->lte($fieldName, $date2->toDateTimeString()); }); } elseif (isset($date1)) { /* * search AT first date */ if (stripos($value['__start__'], ' ') === false) { /* * Not time is given -> the search is made on the whole day, from midnight to midnight */ $fake_date2 = $date1->copy(); $fake_date2->addDay(); $query->where(function ($exp) use($fieldName, $date1, $fake_date2) { return $exp->gte($fieldName, $date1->toDateTimeString())->lt($fieldName, $fake_date2->toDateTimeString()); }); } else { $query->where([$fieldName => $date1->toDateTimeString()]); } } elseif (isset($date2)) { /* * search UNTIL second date */ $query->where(function ($exp) use($fieldName, $date2) { return $exp->lte($fieldName, $date2->toDateTimeString()); }); } }
public function term() { $settings = TableRegistry::get('Settings'); $users = TableRegistry::get('Users'); $session = $this->request->session(); $user = $users->get($this->Auth->user('id')); $now = Time::now(); $apiId = $settings->get('10')->text; $apiToken = $settings->get('11')->text; $apiBase = $settings->get('12')->text; if (is_null($user->osm_secret) || !$session->check('OSM.Secret')) { $this->Flash->error(__('Please link your account first')); return $this->redirect(['action' => 'link']); } elseif (is_null($user->osm_section_id)) { $this->Flash->error(__('Please set your section first')); return $this->redirect(['action' => 'section']); } else { $userOsmId = $user->osm_user_id; $userOsmSecret = $user->osm_secret . $session->read('OSM.Secret'); $userOsmSection = $user->osm_section_id; } $http = new Client(['host' => $apiBase, 'scheme' => 'https']); $url = '/api.php?action=getTerms'; $response = $http->post($url, ['userid' => $userOsmId, 'secret' => $userOsmSecret, 'token' => $apiToken, 'apiid' => $apiId]); if ($response->isOk()) { $preBody = $response->json; // Debugger::dump($preBody); $body = Hash::get($preBody, $user->osm_section_id); // Debugger::dump($body); $terms = Hash::combine($body, '{n}.termid', '{n}', '{n}.past'); // Debugger::dump($terms); $term = Hash::get($terms, 1); //Debugger::dump($term); //$term_end = $term->enddate; foreach ($term as $term) { $startdate = Hash::get($term, 'startdate'); $start = Time::parse($startdate); $enddate = Hash::get($term, 'enddate'); $end = Time::parse($enddate); $count = 0; if ($start < $now && $end > $now) { $count = $count + 1; $termSel = $term; } } if ($count == 1) { $termId = Hash::get($termSel, 'termid'); $termEndDate = Hash::get($termSel, 'enddate'); $termEnd = Time::parse($termEndDate); $usrData = ['osm_current_term' => $termId, 'osm_term_end' => $termEnd, 'osm_linked' => 3]; $users->patchEntity($user, $usrData); if ($users->save($user)) { $this->Flash->success(__('Your OSM Term has been set.')); return $this->redirect(['action' => 'home']); } else { $this->Flash->error(__('The user could not be saved. Please, try again.')); return $this->redirect(['action' => 'home']); } } else { $this->Flash->error(__('More than 1 Term Applies.')); } } else { $this->Flash->error(__('There was a request error, please try again.')); return $this->redirect(['action' => 'home']); } }
public function getValues() { return [['2017-07-06 14:20:00', '2017-07-06 14:20:00', 'Date time string'], ['2017-07-06', '2017-07-06', 'Date string'], ['14:20:00', '14:20:00', 'Time string'], ['foobar', 'foobar', 'Non-date string'], [15, 15, 'Non-date integer'], [Time::parse('2017-07-06 14:20:00'), '14:20', 'Time from object']]; }
/** * Operate over workers by sending a PCNTL signal. * * Note: The workers status is conveniently stored by ResqueStatus. * * @param string $title Action title * @param array $workers List of workers * @param string $noWorkersMessage Message when there is not workers * @param string $listTitle Title of the list of workers * @param string $allActionMessage Message for executing the action on all workers * @param string $promptMessage Prompt message * @param string $schedulerWorkerActionMessage Message for executing the action on the scheduler worker * @param string $workerActionMessage Mesage for executing the action on a regular worker * @param function $formatListItem Function used to format each list item * @param function $successCallback Action executed on success * @param string $signal Signal to send to the worker process * @param function $schedulerWorkerAction Action to execute on the scheduled worker * @return void * @see ResqueStatus\ResqueStatus::isSchedulerWorker() */ protected function _sendSignal($title, $workers, $noWorkersMessage, $listTitle, $allActionMessage, $promptMessage, $schedulerWorkerActionMessage, $workerActionMessage, $formatListItem, $successCallback, $signal, $schedulerWorkerAction = null) { if (!function_exists('pcntl_signal')) { return $this->out('<error>' . __d('cake_resque', "This function requires the PCNTL extension") . '</error>'); } $ResqueStatus = $this->ResqueStatus; if ($formatListItem === null) { $formatListItem = function ($worker, $i) use($ResqueStatus) { $now = Time::parse(CakeResque::getWorkerStartDate($worker)); return sprintf(" [%3d] - %s, started %s", $i, $ResqueStatus->isSchedulerWorker($worker) ? '<comment>**Scheduler Worker**</comment>' : $worker, $now->timeAgoInWords()); }; } $this->out('<info>' . $title . '</info>'); if (empty($workers)) { $this->out(' ' . $noWorkersMessage); } else { $workerIndex = []; if (!$this->params['all'] && count($workers) > 1) { $this->out($listTitle . ':'); $i = 1; foreach ($workers as $worker) { $this->out($formatListItem($worker, $i++)); } $options = range(1, $i - 1); if ($i > 2) { $this->out(' [all] - ' . $allActionMessage); $options[] = 'all'; } $in = $this->in($promptMessage . ': ', $options); if ($in == 'all') { $workerIndex = range(1, count($workers)); } else { $workerIndex[] = $in; } } else { $workerIndex = range(1, count($workers)); } foreach ($workerIndex as $index) { $worker = $workers[$index - 1]; list($hostname, $pid, $queue) = explode(':', (string) $worker); if (Configure::read('CakeResque.Scheduler.enabled') === true && $ResqueStatus->isSchedulerWorker($worker)) { if ($schedulerWorkerAction !== null) { $schedulerWorkerAction($worker); } $this->out($schedulerWorkerActionMessage, 0); } else { $this->out($workerActionMessage($pid), 0); } $killResponse = $this->_kill($signal, $pid); $successCallback($worker); if ($killResponse['code'] === 0) { $this->out('<success>' . __d('cake_resque', 'Done') . '</success>'); } else { $this->out('<error>' . $killResponse['message'] . '</error>'); } } } $this->out(''); }
/** * This function is the post request handler for exam registration/retake/defer. DO NOT TOUCH THIS METHOD.... * @param string $iemail * @return void|Ambigous <void, \Cake\Network\Response> */ private function examRegistrationPostRequestHandler($iemail = null) { // If the user hit the cancel button take him back to the dashboard if (isset($this->request->data['cancel'])) { $this->Auth->session->delete('selectedExamId'); $this->_clearSession(); return $this->redirect(array('action' => 'dashboard')); } // write these keys into the session so re-entrancy is maintained $this->Auth->session->delete('paymentMethod'); // payment code should be selectively deleted since it is not mandatory the user will always select paycode as an option if ($this->Auth->session->check('paymentCode')) { $this->Auth->session->delete('paymentCode'); } $this->Auth->session->write('disabled', 'No'); $this->Auth->session->write('satadmission', 'No'); $this->Auth->session->write('releaseInfo', 'No'); $this->Auth->session->delete('date'); $this->Auth->session->delete('level'); // Looks like the candidate is trying to register for the exam $selectedExamLocation = $_POST['locations']; $selectedExamId = $_POST['exam']; $examRegOptions = $_POST['examregoptions' . $selectedExamId]; // this holds the option that was selected for payment $paymentMethod = $_POST['payment']; // will hold the payment code if paycode was the option selected $paymentCode = $_POST['paycodeinput' . $selectedExamId]; if (strcmp($paymentMethod, 'paycode') == 0) { if (empty($paymentCode)) { $this->Flash->error('Payment Code is a mandatory field'); return; } else { // payment code has been entered and payment option chosen is paycode $this->Auth->session->write('paymentCode', $paymentCode); } } $this->Auth->session->write('paymentMethod', $paymentMethod); // switch over the exam registration option keys and set options as selected if (!empty($examRegOptions)) { for ($i = 0; $i < count($examRegOptions); $i++) { switch ($examRegOptions[$i]) { case 'disabled': $this->Auth->session->write('disabled', 'Yes'); break; case 'satadmission': $this->Auth->session->write('satadmission', 'Yes'); break; case 'releaseInfo': $this->Auth->session->write('releaseInfo', 'Yes'); break; } } } $examModel = $this->ExaminationT; $dbConn = $this->getDBConnector(); $fee = $examModel->getExamFee($dbConn, $selectedExamId, $selectedExamLocation, $this->Auth->session->read('retest'), $this->Auth->session->read('deferexam'), $this->Auth->user('Individual_ID')); $examDateNLvl = $examModel->getExamDate($dbConn, $selectedExamId); $this->Auth->session->write('date', Time::parse($examDateNLvl[0]->Exam_Date)->format('m/d/Y')); $this->Auth->session->write('level', $examDateNLvl[0]->Exam_Level); // This action will be called only for fresh registrations. $this->Auth->session->write("fee", $fee); $this->Auth->session->write("selectedExamLocation", $selectedExamLocation); $this->Auth->session->write("selectedExamId", $selectedExamId); $this->Auth->session->write('randomhash', md5($selectedExamId)); return $this->redirect(array('action' => 'selectmailaddress')); }