Example #1
1
 public function xSaveAction()
 {
     $this->request->defineParams(array('category' => array('type' => 'string'), 'name' => array('type' => 'string'), 'value' => array('type' => 'json')));
     $governance = new Scalr_Governance($this->getEnvironmentId());
     $category = $this->getParam('category');
     $name = $this->getParam('name');
     $value = $this->getParam('value');
     if ($category == Scalr_Governance::CATEGORY_GENERAL && $name == Scalr_Governance::GENERAL_LEASE) {
         $enabled = (bool) $value['limits']['enableDefaultLeaseDuration'];
         unset($value['limits']['enableDefaultLeaseDuration']);
         if (!$governance->isEnabled(Scalr_Governance::CATEGORY_GENERAL, Scalr_Governance::GENERAL_LEASE) && $value['enabled'] == 1 && $enabled) {
             $dt = new DateTime();
             $dt->add(new DateInterval('P' . $value['limits']['defaultLifePeriod'] . 'D'));
             $farms = $this->db->GetCol('SELECT id FROM farms WHERE env_id = ? AND status = ?', array($this->getEnvironmentId(), FARM_STATUS::RUNNING));
             foreach ($farms as $farmId) {
                 $farm = DBFarm::LoadByID($farmId);
                 $farm->SetSetting(DBFarm::SETTING_LEASE_STATUS, 'Active');
                 $farm->SetSetting(DBFarm::SETTING_LEASE_TERMINATE_DATE, $dt->format('Y-m-d H:i:s'));
                 $farm->SetSetting(DBFarm::SETTING_LEASE_NOTIFICATION_SEND, '');
                 $farm->SetSetting(DBFarm::SETTING_LEASE_EXTEND_CNT, 0);
             }
         }
     }
     $governance->setValue($category, $name, $value);
     $this->response->success('Successfully saved');
 }
Example #2
0
 function approve($id, $data = null)
 {
     $training = new Training();
     $course_obj = new Course();
     $request = $this->get(array('id' => $id));
     $course = $course_obj->get(array('id' => $request['course_id']));
     $data['course_id'] = $request['course_id'];
     $data['start'] = $request['planned_date'];
     $date = new DateTime($data['start']);
     if ($course['duration'] > 8) {
         $date->add(new DateInterval('P' . ceil($course['duration'] / 8) . 'DT' . $course['duration'] % 8 . 'H'));
     } else {
         $date->add(new DateInterval('PT' . $course['duration'] . 'H'));
     }
     $data['finish'] = $date->format('Y-m-d H:i');
     $data['user_id'] = $request['user_id'];
     $data['status_id'] = Training::CREATED;
     if ($course['format_id'] == Course::ONLINE || $course['format_id'] == Course::WEBCAST) {
         $data['course_hash'] = md5($data['user_id'] . $data['course_id'] . $data['start']);
     }
     $data['tries'] = 0;
     if ($course['exam'] == 't') {
         $data['exam_hash'] = md5($data['user_id'] . $data['course_id'] . $data['start'] . $data['tries']);
     }
     $data['request_id'] = $id;
     $data['active'] = 'true';
     $training->add($data);
     $this->disable($id);
 }
 /**
  * This just setsup some events in the db for running certain tests that query getting events back.
  * @since 4.6.x
  */
 protected function _setup_events()
 {
     //setup some dates we'll use for testing with.
     $timezone = new DateTimeZone('America/Toronto');
     $upcoming_start_date = new DateTime("now +2hours", $timezone);
     $past_start_date = new DateTime("now -2days", $timezone);
     $current_end_date = new DateTime("now +2days", $timezone);
     $current = new DateTime("now", $timezone);
     $formats = array('Y-d-m', 'h:i a');
     $full_format = implode(' ', $formats);
     //setup some datetimes to attach to events.
     $datetimes = array('expired_datetime' => $this->factory->datetime->create(array('DTT_EVT_start' => $past_start_date->format($full_format), 'DTT_EVT_end' => $past_start_date->format($full_format), 'timezone' => 'America/Toronto', 'formats' => $formats)), 'upcoming_datetime' => $this->factory->datetime->create(array('DTT_EVT_start' => $upcoming_start_date->format($full_format), 'DTT_EVT_end' => $upcoming_start_date->format($full_format), 'timezone' => 'America/Toronto', 'formats' => $formats)), 'active_datetime' => $this->factory->datetime->create(array('DTT_EVT_start' => $current->sub(new DateInterval("PT2H"))->format($full_format), 'DTT_EVT_end' => $current_end_date->add(new DateInterval("PT2H"))->format($full_format), 'timezone' => 'America/Toronto', 'formats' => $formats)), 'sold_out_datetime' => $this->factory->datetime->create(array('DTT_EVT_start' => $upcoming_start_date->format($full_format), 'DTT_EVT_end' => $upcoming_start_date->format($full_format), 'DTT_reg_limit' => 10, 'DTT_sold' => 10, 'timezone' => 'America/Toronto', 'formats' => $formats)), 'inactive_datetime' => $this->factory->datetime->create(array('DTT_EVT_start' => $current->sub(new DateInterval("PT2H"))->format($full_format), 'DTT_EVT_end' => $current_end_date->add(new DateInterval("PT2H"))->format($full_format), 'timezone' => 'America/Toronto', 'formats' => $formats)));
     //setup some events
     $events = $this->factory->event->create_many('4');
     //add datetimes to the events.
     $events[0]->_add_relation_to($datetimes['expired_datetime'], 'Datetime');
     $events[0]->save();
     $events[1]->_add_relation_to($datetimes['upcoming_datetime'], 'Datetime');
     $events[1]->save();
     $events[2]->_add_relation_to($datetimes['active_datetime'], 'Datetime');
     $events[2]->save();
     $events[3]->_add_relation_to($datetimes['sold_out_datetime'], 'Datetime');
     $events[3]->save();
     foreach ($events as $event) {
         $event->set('status', 'publish');
         $event->save();
     }
     //one more event that is just going to be inactive
     $final_event = $this->factory->event->create();
     $final_event->_add_relation_to($datetimes['inactive_datetime'], 'Datetime');
     $final_event->save();
 }
Example #4
0
 public function testScheduled()
 {
     $start = new \DateTime('now', new \DateTimeZone('UTC'));
     $start->add(new \DateInterval('P1D'));
     $end = clone $start;
     $end->add(new \DateInterval('PT2H'));
     $scheduledTimes = [['start' => $start, 'end' => $end]];
     $start = new \DateTime('now', new \DateTimeZone('UTC'));
     $start->add(new \DateInterval('PT2H'));
     $end = clone $start;
     $end->add(new \DateInterval('PT1H'));
     array_unshift($scheduledTimes, ['start' => $start, 'end' => $end]);
     $start = new \DateTime('now', new \DateTimeZone('UTC'));
     $start->add(new \DateInterval('P1D'));
     $start->add(new \DateInterval('PT1H'));
     $end = clone $start;
     $end->add(new \DateInterval('PT3H'));
     $scheduledTimes[] = ['start' => $start, 'end' => $end];
     $scheduledTimes[] = ['start' => $start, 'end' => $end];
     foreach ($scheduledTimes as $times) {
         $watcher = $this->getMockBuilder(ScheduledWatcherInterface::class)->disableOriginalConstructor()->getMock();
         $watcher->expects(self::any())->method('isActive')->will(self::returnValue(true));
         $watcher->expects(self::any())->method('isScheduled')->will(self::returnValue(true));
         $watcher->expects(self::any())->method('getScheduledTimes')->will(self::returnValue([$times]));
         /* @var WatcherInterface $watcher */
         $this->janitor->addWatcher($watcher);
     }
     self::assertEquals($scheduledTimes, $this->janitor->getScheduledTimes());
 }
Example #5
0
 function generaLiga($equipos)
 {
     $this->equipos = $equipos;
     foreach ($equipos as $equipo) {
         $equipo = new Equipo($equipo);
         $equipo->persist();
     }
     //Intervalo entre jornadas y fecha 1ª jornada
     $intervalo = new DateInterval("P7D");
     $fecha = new DateTime("2014-11-2");
     //Por si hay equipos impares
     if (count($equipos) % 2 != 0) {
         array_push($equipos, "extra!!");
     }
     //Genera las jornadas de la 1ª vuelta
     for ($i = 0; $i < count($equipos) - 1; $i++) {
         //Formato fecha
         $fechaPartido = $fecha->format("Y-m-d");
         //Una jornada por cada vuelta del for
         $jornadaActual = new Jornada($fechaPartido);
         //Suma intervalo jornadas
         $fecha->add($intervalo);
         $jornadaActual->persist();
         //Coge del 1º a la mitad
         $locales = array_slice($equipos, 0, count($equipos) / 2);
         //De la mitad a los que haya
         $visitantes = array_reverse(array_slice($equipos, count($equipos) / 2));
         for ($j = 0; $j < count($visitantes); $j++) {
             $partidoActual = new Partido($jornadaActual->getId(), $locales[$j], $visitantes[$j]);
             $partidoActual->persist();
             //En la jornada i, el partido j, el local es j
             $liga[$i][$j]['local'] = $locales[$j];
             $liga[$i][$j]['visitante'] = $visitantes[$j];
         }
         //El 1er equipo
         $equipoBase = array_shift($equipos);
         array_unshift($equipos, array_pop($equipos));
         array_unshift($equipos, $equipoBase);
     }
     //Genera las jornadas de vuelta
     foreach ($liga as $jornada) {
         $fechaPartido = $fecha->format("Y-m-d");
         //Una jornada por cada vuelta del for
         $jornadaActual = new Jornada($fechaPartido);
         //Suma intervalo jornadas
         $fecha->add($intervalo);
         $jornadaActual->persist();
         $jornadaVuelta = [];
         foreach ($jornada as $partido) {
             $partidoActual = new Partido($jornadaActual->getId(), $partido["visitante"], $partido['local']);
             $partidoActual->persist();
             $partidoVuelta['local'] = $partido['visitante'];
             $partidoVuelta['visitante'] = $partido['local'];
             $jornadaVuelta[] = $partidoVuelta;
         }
         array_push($liga, $jornadaVuelta);
     }
     return $liga;
 }
 /**
  * Move forward to next element
  * @link http://php.net/manual/en/iterator.next.php
  * @return void Any returned value is ignored.
  * @since 5.0.0
  */
 public function next()
 {
     if ($this->_current === null) {
         $this->_current = clone $this->_startDate;
     } else {
         $this->_current = clone $this->_current;
         $this->_current->add($this->_dateInterval);
     }
 }
 public function getTasksProvider()
 {
     $createdDate = new \DateTime();
     $updatedDate = $createdDate->add(new \DateInterval('PT10S'));
     $startDate = $createdDate->add(new \DateInterval('PT1H'));
     $end = clone $startDate;
     $endDate = $end->add(new \DateInterval('PT30M'));
     return [['tasks' => [['id' => 1, 'subject' => 'test_subject', 'description' => 'test_description', 'dueDate' => $startDate, 'createdAt' => $createdDate, 'updatedAt' => $updatedDate]], 'expected' => [['calendar' => 123, 'id' => 1, 'title' => 'test_subject', 'description' => 'test_description', 'start' => $startDate->format('c'), 'end' => $endDate->format('c'), 'allDay' => false, 'createdAt' => $createdDate->format('c'), 'updatedAt' => $updatedDate->format('c'), 'editable' => false, 'removable' => false]]]];
 }
 /**
  * Run the database seeds.
  *
  * @return void
  */
 public function run()
 {
     $datetime = new DateTime('today');
     DB::table('events')->insert(['name' => 'Pisyek', 'title' => 'SI Finance', 'start_time' => strtotime($datetime->setTime(10, 00)->format('Y-m-d H:i:s')), 'end_time' => strtotime($datetime->add(new DateInterval('PT1H'))->format('Y-m-d H:i:s'))]);
     $datetime = new DateTime('tomorrow');
     DB::table('events')->insert(['name' => 'Aron Kumar', 'title' => 'Meeting HR & You', 'start_time' => strtotime($datetime->format('Y-m-d H:i:s')), 'end_time' => strtotime($datetime->add(new DateInterval('PT2H'))->format('Y-m-d H:i:s'))]);
     $datetime = new DateTime('yesterday');
     DB::table('events')->insert(['name' => 'Jericho', 'title' => 'HYPE', 'start_time' => strtotime($datetime->setTime(11, 00)->format('Y-m-d H:i:s')), 'end_time' => strtotime($datetime->add(new DateInterval('PT1H'))->format('Y-m-d H:i:s'))]);
     DB::table('events')->insert(['name' => 'Remy', 'title' => 'HC PDC', 'start_time' => strtotime($datetime->setTime(14, 00)->format('Y-m-d H:i:s')), 'end_time' => strtotime($datetime->add(new DateInterval('PT2H'))->format('Y-m-d H:i:s'))]);
 }
 /**
  * Run the database seeds.
  *
  * @return void
  */
 public function run()
 {
     $datetime = new DateTime('today');
     DB::table('events')->insert(['name' => 'Pisyek', 'title' => 'Meeting with VC from UAE', 'start_time' => $datetime->setTime(10, 00)->format('Y-m-d H:i:s'), 'end_time' => $datetime->add(new DateInterval('PT1H'))->format('Y-m-d H:i:s')]);
     $datetime = new DateTime('tomorrow');
     DB::table('events')->insert(['name' => 'Ali Baba', 'title' => 'Meeting Para Penyamun', 'start_time' => $datetime->format('Y-m-d H:i:s'), 'end_time' => $datetime->add(new DateInterval('PT2H'))->format('Y-m-d H:i:s')]);
     $datetime = new DateTime('yesterday');
     DB::table('events')->insert(['name' => 'Vince', 'title' => 'Zumba with Zin Hamka', 'start_time' => $datetime->setTime(11, 00)->format('Y-m-d H:i:s'), 'end_time' => $datetime->add(new DateInterval('PT1H'))->format('Y-m-d H:i:s')]);
     DB::table('events')->insert(['name' => 'Lili', 'title' => 'Lunch', 'start_time' => $datetime->setTime(14, 00)->format('Y-m-d H:i:s'), 'end_time' => $datetime->add(new DateInterval('PT2H'))->format('Y-m-d H:i:s')]);
 }
Example #10
0
 /**
  * @param \DateTime        $begin
  * @param FactoryInterface $factory
  *
  * @throws \CalendR\Exception
  */
 public function __construct(\DateTime $begin, FactoryInterface $factory)
 {
     $this->factory = $factory;
     if (!static::isValid($begin)) {
         throw $this->createInvalidException();
     }
     $this->begin = clone $begin;
     $this->end = clone $begin;
     $this->end->add($this->getDateInterval());
 }
 function setStartAndEndDate(&$scheduler)
 {
     $start = new \DateTime('now', new \DateTimeZone('UTC'));
     $start->add(new \DateInterval('P1M'));
     $scheduler['start_date'] = $start->format('Y-m-d');
     if (!empty($scheduler['end_date'])) {
         $end = $start->add(new \DateInterval('P2Y6M'));
         $scheduler['end_date'] = $end->format('Y-m-d');
     }
 }
Example #12
0
 public function __construct($accessToken, $expiresIn, $tokenType, $scope = null, $refreshToken = null)
 {
     $this->accessToken = trim($accessToken);
     $this->expiresIn = (int) $expiresIn;
     $this->tokenType = trim($tokenType);
     $this->scope = true === empty(trim($scope)) ? null : trim($scope);
     $this->refreshToken = true === empty(trim($refreshToken)) ? null : trim($refreshToken);
     $this->expiresAt = new \DateTime();
     $this->expiresAt->add(new \DateInterval(sprintf('PT%sS', $this->expiresIn)));
     $this->validate();
 }
Example #13
0
 /**
  * Extend the expiration datetime by the set TTL.
  *
  * If there is no expiration datetime initialized, it will be.
  *
  * @throws \DomainException If there is no TTL set.
  */
 public function extendExpiration()
 {
     if (null === $this->ttl) {
         throw new DomainException('There is no TTL set for this Lock.');
     }
     if (!$this->expiresAt) {
         $this->expiresAt = new \DateTime();
         $this->expiresAt->setTimestamp(time());
     }
     $this->expiresAt->add($this->ttl);
 }
Example #14
0
 /**
  * {@inheritDoc}
  */
 public function expiresAfter($time)
 {
     if ($time === null) {
         $this->expirationDate = null;
     } elseif ($time instanceof \DateInterval) {
         $this->expirationDate = new \DateTime();
         $this->expirationDate->add($time);
     } else {
         $this->expirationDate = new \DateTime();
         $this->expirationDate->add(new \DateInterval('P' . $time . 'S'));
     }
     return $this;
 }
Example #15
0
 /**
  * Constructor.
  */
 public function __construct()
 {
     $this->minDate = new \DateTime();
     $this->startingDate = new \DateTime();
     $this->endingDate = new \DateTime();
     $this->endingDate->add(new \DateInterval("P1D"));
     $this->rooms = array();
     $this->rooms[] = new RoomData();
     $this->rooms[] = new RoomData();
     $this->rooms[] = new RoomData();
     $this->rooms[] = new RoomData();
     $this->rooms[] = new RoomData();
 }
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $now = new \DateTime();
     $output->writeln("<comment>Create reminder scheduler started on {$now->format('Y-m-d H:i:s')}</comment>");
     $esCourses = $this->getContainer()->get('es_courses');
     $em = $this->getContainer()->get('doctrine')->getManager();
     $scheduler = $this->getContainer()->get('scheduler');
     // Parse the input arguments
     $type = $input->getArgument('type');
     $date = $input->getArgument('date');
     // The date at which the job is to be run
     if ($type != CourseStartReminderJob::JOB_TYPE_1_DAY_BEFORE && $type != CourseStartReminderJob::JOB_TYPE_2_WEEKS_BEFORE) {
         // Invalid job type
         $output->writeln("<error>Invalid job type. Valid types are email_reminder_course_start_2weeks/email_reminder_course_start_1day</error>");
         return;
     }
     $dateParts = explode('-', $date);
     if (!checkdate($dateParts[1], $dateParts[2], $dateParts[0])) {
         $output->writeLn("<error>Invalid date or format. Correct format is Y-m-d</error>");
         return;
     }
     $dt = new \DateTime($date);
     if ($type == CourseStartReminderJob::JOB_TYPE_2_WEEKS_BEFORE) {
         // Find courses starting 2 weeks (14 days after the current date)
         $dt->add(new \DateInterval('P14D'));
     } elseif ($type == CourseStartReminderJob::JOB_TYPE_1_DAY_BEFORE) {
         // Find courses starting 1 day later
         $dt->add(new \DateInterval('P1D'));
     }
     $output->writeln("<comment>{$type} - {$dt->format('Y-m-d')}</comment>");
     $results = $esCourses->findByNextSessionStartDate($dt, $dt);
     $output->writeln("<comment>" . $results['results']['hits']['total'] . ' courses starting on ' . $dt->format('Y-m-d') . " <comment>");
     if ($results['results']['hits']['total'] == 0) {
         $output->writeln("<info>No courses starting on {$dt->format('Y-m-d')}</info>");
         return;
     }
     $courseIds = array();
     foreach ($results['results']['hits']['hits'] as $course) {
         $courseIds[] = $course['_id'];
     }
     $users = MTHelper::getUsersToCoursesMap($em, $courseIds);
     $output->writeln("<comment>" . count($users) . ' users found </comment>');
     $scheduled = 0;
     foreach ($users as $uid => $courses) {
         $id = $scheduler->schedule(new \DateTime($date), $type, 'ClassCentral\\MOOCTrackerBundle\\Job\\CourseStartReminderJob', $courses, $uid);
         if ($id) {
             $scheduled++;
         }
     }
     $output->writeln("<info>{$scheduled} jobs scheduled</info>");
 }
Example #17
0
function checkNotification($date, $extension)
{
    try {
        $dbh = new PDO('mysql:host=mysql488.db.sakura.ne.jp;dbname=meganeshibu_db;charset=utf8', 'meganeshibu', 'DBmaster777', array(PDO::ATTR_EMULATE_PREPARES => false));
    } catch (PDOException $e) {
        exit('データベース接続失敗。' . $e->getMessage());
    }
    $notificationList = array();
    $datetime = new DateTime($date);
    $datetime->add(DateInterval::createFromDateString($extension));
    $interval = DateInterval::createFromDateString('+59 second');
    $dateStart = $datetime->format('Y-m-d H:i:s');
    $dateEnd = $datetime->add($interval)->format('Y-m-d H:i:s');
    $sql = <<<EOT
(select
    'スケジュール' as Type,
    ScheduleTable.ScheduleID as ID,
    ScheduleTable.ScheduleName as Name,
    ScheduleTable.ScheduleInfo as Info,
    UserTable.UserID,
    UserTable.NotificationID
from
    ScheduleTable,
    UserTable
where
    UserTable.UserID = ScheduleTable.UserID
    and (ScheduleTable.ScheduleStart between '{$dateStart}' and '{$dateEnd}')
)
union
(select
    'タスク' as Type,
    TaskTable.TaskID as ID,
    TaskTable.TaskName as Name,
    TaskTable.TaskInfo as Info,
    UserTable.UserID,
    UserTable.NotificationID
from
    TaskTable,
    UserTable
where
    UserTable.UserID = TaskTable.UserID
    and (TaskTable.TaskEnd between '{$dateStart}' and '{$dateEnd}')
)
EOT;
    $stmt = $dbh->query($sql);
    while ($row = $stmt->fetchObject()) {
        $notificationList[] = array('type' => $row->Type, 'id' => $row->ID, 'name' => $row->Name, 'info' => $row->Info, 'user_id' => $row->UserID, 'notificationID' => $row->NotificationID);
    }
    $dbh = null;
    return $notificationList;
}
 public function getNextOccurrence(\DateTime $dateTime)
 {
     $currentYearOccurrence = \DateTime::createFromFormat('Y-m-d', $dateTime->format('Y'), $dateTime->format('m'), $dateTime->format('d'));
     $nextYearOccurrence = \DateTime::createFromFormat('Y-m-d', $dateTime->format('Y') + 1, $dateTime->format('m'), $dateTime->format('d'));
     if ($dateTime < $currentYearOccurrence) {
         return $currentYearOccurrence;
     } else {
         if ($dateTime > $currentYearOccurrence && $this->contains($dateTime->add('1 days'))) {
             return $dateTime->add('1 days');
         } else {
             return $nextYearOccurrence;
         }
     }
 }
Example #19
0
 public static function getDatesArrayForStationReports($quickReportType, $fromDateStr, $toDateStr)
 {
     $dateArr = null;
     $fromDate = new DateTime($toDateStr);
     $toDate = new DateTime($toDateStr);
     if ($quickReportType != "null") {
         $fromDate = new DateTime();
         $toDate = new DateTime();
     }
     //$fromDate->setTimezone($timezone);
     //$toDate ->setTimezone($timezone);
     $fromDate->setTime(0, 0, 0);
     if ($quickReportType == "today") {
         //$toDate = $toDate->setTime(23,59,59);
     } else {
         if ($quickReportType == "last7days") {
             $fromDate->add(DateInterval::createFromDateString('-7 days'));
             $fromDate->setTime(0, 0, 0);
         } else {
             if ($quickReportType == "last30days") {
                 $fromDate->add(DateInterval::createFromDateString('-1 month'));
                 $fromDate = $fromDate->setTime(0, 0, 0);
             } else {
                 if ($quickReportType == "last6months") {
                     $fromDate->add(DateInterval::createFromDateString('-6 months'));
                     $fromDate = $fromDate->setTime(0, 0, 0);
                 } else {
                     if ($quickReportType == "thisyear") {
                         $d = $fromDate->format('d');
                         $m = $fromDate->format('m');
                         $Y = $fromDate->format('Y');
                         $fromDate = $fromDate->setDate($Y, 1, 1);
                         // set the wanted day for the month
                         $fromDate = $fromDate->setTime(0, 0, 0);
                     } else {
                         if ($quickReportType == "null") {
                             $fromDate = new DateTime($fromDateStr);
                             $toDate = new DateTime($toDateStr);
                         }
                     }
                 }
             }
         }
     }
     $fromDateAStr = $fromDate->format("Y/m/d  H:i:s");
     $toDateAStr = $toDate->format("Y/m/d  H:i:s");
     $dateArr = array('fromDate' => $fromDateAStr, 'toDate' => $toDateAStr);
     return $dateArr;
 }
Example #20
0
 public static function geraParcelas($id_cliente, $delay, $valor, $parcelas)
 {
     $date = new DateTime(date('Y-m-d'));
     $date->add(new DateInterval('P' . $delay . 'D'));
     for ($n = 1; $n <= $parcelas; $n++) {
         $conta = new self();
         $conta->id_cliente = $id_cliente;
         $conta->dt_emissao = date('Y-m-d');
         $conta->dt_vencimento = $date->format('Y-m-d');
         $conta->valor = $valor / $parcelas;
         $conta->paga = 'N';
         $conta->store();
         $date->add(new DateInterval('P1M'));
     }
 }
Example #21
0
 public function actionToken($state)
 {
     // only poeple on the list should be generating new tokens
     if (!$this->context->token->checkAccess($_SERVER['REMOTE_ADDR'])) {
         echo "Oh sorry man, this is a private party!";
         mail($this->context->token->getEmail(), 'Notice', 'The token is maybe invalid!');
         $this->terminate();
     }
     // facebook example code...
     $stoken = $this->session->getSection('token');
     if (!isset($_GET['code'])) {
         $stoken->state = md5(uniqid(rand(), TRUE));
         //CSRF protection
         $dialog_url = "https://www.facebook.com/dialog/oauth?client_id=" . $this->context->token->getAppId() . "&redirect_uri=" . urlencode($this->link('//Crawler:token')) . "&scope=" . $this->context->token->getAppPermissions() . "&state=" . $stoken->state;
         echo "<script> top.location.href='" . $dialog_url . "'</script>";
         $this->terminate();
     }
     if (isset($stoken->state) && $stoken->state === $_GET['state']) {
         $token_url = "https://graph.facebook.com/oauth/access_token?" . "client_id=" . $this->context->token->getAppId() . "&redirect_uri=" . urlencode($this->link('//Crawler:token')) . "&client_secret=" . $this->context->token->getAppSecret() . "&code=" . $_GET['code'];
         $response = file_get_contents($token_url);
         $params = null;
         parse_str($response, $params);
         $date = new DateTime();
         $date->add(new DateInterval('PT' . $params["expires"] . 'S'));
         $this->context->token->saveToken($params['access_token'], $date);
         echo "Thanks for your token :)";
     } else {
         echo "The state does not match. You may be a victim of CSRF.";
     }
     $this->terminate();
 }
 /**
  * @param string $token
  * @param string $type The token type (from OAuth2 key 'token_type').
  * @param array  $data Other token data.
  */
 public function __construct($token, $type, array $data = [])
 {
     $this->token = $token;
     $this->type = $type;
     $this->data = $data;
     if (isset($data['expires'])) {
         $this->expires = new \DateTime();
         $this->expires->setTimestamp($data['expires']);
     } elseif (isset($data['expires_in'])) {
         $this->expires = new \DateTime();
         $this->expires->add(new \DateInterval(sprintf('PT%sS', $data['expires_in'])));
     }
     if (isset($data['refresh_token'])) {
         $this->refreshToken = new self($data['refresh_token'], 'refresh_token');
     }
 }
Example #23
0
 public function listAction()
 {
     $repository = $this->getDoctrine()->getRepository('ProdekoIlmoBundle:Event');
     $now = new \DateTime();
     //Listaa tapahtumat, joiden ilmo on tulevaisuudessa
     $query = $repository->createQueryBuilder('e')->where('e.registrationStarts > :now')->setParameter('now', $now)->orderBy('e.registrationStarts', 'ASC')->getQuery();
     $upcomingEvents = $query->getResult();
     //Listaa tapahtumat, joiden ilmo on käynnissä
     $query = $repository->createQueryBuilder('e')->where('e.registrationStarts < :now')->andWhere('e.registrationEnds > :now')->setParameter('now', $now)->orderBy('e.takesPlace', 'ASC')->getQuery();
     $activeEvents = $query->getResult();
     //Listaa tapahtumia, joiden ilmo on jo sulkeutunut
     $pastEventTreshold = new \DateTime();
     $pastEventTreshold->sub(new \DateInterval('P2W'));
     //TODO: make configurable
     $query = $repository->createQueryBuilder('e')->where('e.registrationEnds < :now')->orderBy('e.takesPlace', 'DESC');
     $isAdmin = $this->get('security.context')->isGranted('ROLE_ADMIN');
     if (!$isAdmin) {
         $query = $query->andWhere('e.takesPlace > :treshold')->setParameters(array('treshold' => $pastEventTreshold, 'now' => $now));
     } else {
         $query = $query->setParameter('now', $now);
     }
     $query = $query->getQuery();
     $pastEvents = $query->getResult();
     //Hae tapahtumat, joissa on kiltisilmo paraikaa meneillään
     $kiltisNow = new \DateTime();
     $kiltisNow->add(new \DateInterval('PT3H'));
     $query = $repository->createQueryBuilder('e')->where('e.kiltisilmo = true')->andWhere('e.registrationStarts < :kiltisNow')->andWhere('e.registrationStarts > :now')->setParameters(array('now' => $now, 'kiltisNow' => $kiltisNow))->getQuery();
     $kiltisEvents = $query->getResult();
     return $this->render('ProdekoIlmoBundle:Ilmo:eventlist.html.twig', array('activeEvents' => $activeEvents, 'upcomingEvents' => $upcomingEvents, 'pastEvents' => $pastEvents, 'kiltisEvents' => $kiltisEvents));
 }
Example #24
0
 public static function minutesToString($minutes = "")
 {
     $dtF = new DateTime("@0");
     $dtT = new DateTime("@0");
     $dtT->add(new DateInterval('PT' . $minutes . 'M'));
     return $dtF->diff($dtT)->format('%a jour, %h heures, %i minutes');
 }
Example #25
0
 /**
  * {@inheritdoc}
  */
 public function incrementExpiresAt()
 {
     $expiresAt = new \DateTime();
     $expiresAt->add(new \DateInterval('PT3H'));
     $this->expiresAt = $expiresAt;
     return $this;
 }
 public function getEndDate(int $months, string $dateFormat = 'Y-m-d') : string
 {
     $date = new DateTime($this->format('Y-m-d'));
     $date->add(new DateInterval("P" . $months . "M"));
     $date->sub(new DateInterval("P1D"));
     return $date->format($dateFormat);
 }
Example #27
0
 /**
  * stringifyPayments 
  * Takes an array of payments and generates a legal phrasing of those payments
  * 
  * @param mixed $payments 
  * @access public
  * @return void
  */
 public function stringifyPayments($payments)
 {
     if (!count($payments)) {
         return null;
     }
     rsort($payments);
     $uniquePayments = array_unique($payments);
     $seen = array_combine(array_values($uniquePayments), array_fill(0, count($uniquePayments), 0));
     foreach ($payments as $payment) {
         $seen[$payment]++;
     }
     $count = 0;
     $numTotal = 0;
     foreach ($seen as $paymentAmount => $num) {
         $today = $myToday = new \DateTime();
         $myToday = new \DateTime();
         $commenceDate = !empty($dueDate) ? $dueDate->add(new \DateInterval('P1M'))->format('Y-m-d') : $myToday->add(new \DateInterval('P1M'))->format('Y-m-d');
         $dueDate = $today->add(new \DateInterval('P' . $numTotal . 'M'));
         $numTotal += $num;
         $dueDateStr = $dueDate->format('m/d/y');
         $dueString = $num > 1 ? 'due on the ' . $today->format('jS') . ' day of the month, commencing on' : 'due';
         $str = sprintf('%s %s of $%5.2f %s %s', $num, $num < 2 ? 'installment' : 'monthly installments', $paymentAmount, $dueString, $dueDateStr);
         $clauses[] = $str;
     }
     $joinStr = count($clauses) == 2 ? '; thereafter ' : '; ';
     return join('; ', $clauses);
 }
Example #28
0
function CheckDateDiff($date, $interval = CONFIRMATION_TERM)
{
    $time = new DateTime($date);
    $time->add(new DateInterval(CONFIRMATION_TERM));
    $curDate = new DateTime();
    return $curDate < $time;
}
Example #29
0
 public function generateCSVData($filterFields, $accountNum, $connect)
 {
     $db = new db_config();
     $data = '';
     $sql = $db->mquery("EXEC dbo.getCalls @caller_tag = '" . $filterFields . "', @account_number = '" . $accountNum . "'", $connect);
     $num = $db->numrows($sql);
     $HeadingsArray = array('Caller tag', 'Date', 'Time', 'Contact Name', 'Phone number', 'Duration', 'Estimated cost', 'Actual cost', 'Bill issued');
     $csvContent = implode(",", $HeadingsArray) . "\n";
     while ($row = $db->fetchobject($sql)) {
         $valuesArray['caller_tag'] = $db->strip($row->caller_tag);
         $call_date = $db->strip($row->call_date);
         $valuesArray['call_date_format'] = date('d M', strtotime($call_date));
         $valuesArray['time'] = $db->strip($row->time);
         $valuesArray['contact_name'] = $db->strip($row->contact_name);
         $valuesArray['phone_number'] = $db->strip($row->phone_number);
         $date = new DateTime('2000-01-01');
         $date->add(new DateInterval('P0Y0M0DT0H0M' . $row->duration . 'S'));
         $valuesArray['duration'] = $date->format('i\\m s\\s');
         $valuesArray['estimated_cost'] = $db->strip($row->estimated_cost);
         $valuesArray['actual_cost'] = $db->strip($row->actual_cost);
         $valuesArray['bill_issued'] = $db->strip($row->bill_issued);
         $csvContent .= implode(",", $valuesArray) . "\r\n";
         unset($valuesArray);
     }
     $fileName = date("Y-m-d") . "_export.csv";
     header('Content-Type: text/csv');
     header("Content-length: " . filesize($fileName));
     header('Content-Disposition: inline; filename="' . $fileName . '"');
     echo $csvContent;
 }
Example #30
0
 function it_has_time_after_setting_it()
 {
     $time = new \DateTime();
     $time->add(new \DateInterval('P1D'));
     $this->setTime($time);
     $this->getTime()->shouldReturn($time->getTimestamp());
 }