/**
 * Valida un intervalo de fechas en formato DD-MM-AAAA. Lanza una excepción en caso de error.
 */
function validarIntervaloFechasFuturo($fechaInicio, $fechaFin)
{
    // Fecha actual a las 00:00:00
    $fechaActual = new DateTime();
    $fechaActual->setTime(0, 0, 0);
    $fechaInicio = trim($fechaInicio);
    $fechaInicio = substr($fechaInicio, 0, 10);
    $fechaInicio = DateTime::createFromFormat('!d-m-Y', $fechaInicio);
    $fechaFin = trim($fechaFin);
    $fechaFin = substr($fechaFin, 0, 10);
    $fechaFin = DateTime::createFromFormat('!d-m-Y', $fechaFin);
    // Fechas bien formadas ?
    if (!empty($fechaInicio) && !empty($fechaFin)) {
        // La fecha de fin es mayor o igual a la de inicio ?
        if ($fechaInicio->getTimeStamp() <= $fechaFin->getTimeStamp()) {
            // Fecha de inicio mayor o igual a la actual ?
            if ($fechaInicio->getTimeStamp() >= $fechaActual->getTimeStamp()) {
                return;
            } else {
                throw new Exception('La fecha de inicio debe ser la actual o una futura');
            }
        } else {
            throw new Exception('La fecha de inicio es mayor a la de fin');
        }
    } else {
        throw new Exception('Intervalo de fechas incorrecto');
    }
}
Example #2
0
 /**
  * @param $employeeID
  * @param $managerID
  * @param \DateTime $startTime
  * @param \DateTime $endTime
  * @param float $break
  * @return array
  */
 public function createShift($employeeID, $managerID, $startTime, $endTime, $break = 0.25)
 {
     $date = new MongoDate();
     $shift = ['break' => $break, 'manager_id' => $managerID, 'created_at' => $date, 'employee_id' => $employeeID, 'updated_at' => $date, 'id' => uniqid(), '_id' => null, 'start_time' => new MongoDate($startTime->getTimeStamp()), 'end_time' => new MongoDate($endTime->getTimeStamp())];
     $this->collection->insert($shift);
     return $shift;
 }
Example #3
0
 /**
  * @dataProvider parserTestProvider
  */
 public function testParser($expression, $valid = false, $dtime = 'now', $matching = false)
 {
     $ct = new Cron($expression, new DateTimeZone('Europe/Berlin'));
     $dt = new DateTime($dtime, new DateTimeZone('Europe/Berlin'));
     $this->assertEquals($valid, $ct->isValid());
     $this->assertEquals($matching, $ct->isMatching($dt->getTimeStamp()));
 }
Example #4
0
function print_news($symbol = "EURUSD", $time = 0)
{
    $date = new DateTimeZone('Europe/London');
    $date2 = new DateTime('now', $date);
    $timestamp = $date2->getTimeStamp();
    if ($time == 0) {
        $time = $timestamp;
    }
    $result = find_news_by_symbol($symbol, $time);
    $var = "";
    if ($result == NULL) {
        echo "null";
    } else {
        $var .= "symbol:" . $result->symbol . ";";
        $var .= "actualTrend:" . $result->actualTrend . ";";
        $var .= "weekTrend:" . $result->weekTrend . ";";
        $var .= "monthTrend:" . $result->monthTrend . ";";
        $var .= "target1:" . $result->t1 . ";";
        $var .= "target2:" . $result->t2 . ";";
        $var .= "pivot:" . $result->pivot . ";";
        $var .= "resistance1:" . $result->r1 . ";";
        $var .= "time:" . $result->time . ";";
    }
    return $var;
}
 function shouldHaveLeftAt(DateTime $atTime)
 {
     if ($atTime->getTimeStamp() > $this->date->getTimeStamp()) {
         return true;
     } else {
         return false;
     }
 }
Example #6
0
 public function testWarpTravel()
 {
     $dateTime = new \DateTime();
     $record = array('datetime' => clone $dateTime);
     $lolifiedRecord = $this->warp->lolify($record);
     $this->assertInstanceOf('DateTime', $lolifiedRecord['datetime']);
     $this->assertGreaterThan($dateTime->getTimeStamp(), $lolifiedRecord['datetime']->getTimeStamp());
 }
 /**
  * @dataProvider provider
  */
 public function testNextCheckMoreThan30(IAmberChecker $checker)
 {
     $now = new DateTime();
     $result = $checker->next_check_date(FALSE, 1000, 100 + 45 * 24 * 60 * 60, FALSE);
     $this->assertSame($now->getTimeStamp() + 24 * 60 * 60 * 30, $result);
     $now = new DateTime();
     $result = $checker->next_check_date(TRUE, 1000, 100 + 45 * 24 * 60 * 60, TRUE);
     $this->assertSame($now->getTimeStamp() + 24 * 60 * 60 * 30, $result);
 }
Example #8
0
 private function loginIntervalLimit($lastAttempt)
 {
     $unixDay = 86401;
     $timeObject = new DateTime();
     $currentAttempt = $timeObject->getTimeStamp();
     $difference = $currentAttempt - $lastAttempt;
     if ($difference < $unixDay) {
         return false;
     }
 }
Example #9
0
 /**
  * Checks if our event starts earlier than the date supplied
  * @param \DateTime $date
  * @return bool
  */
 public function startsEarlier(\DateTime $date)
 {
     $earlier = FALSE;
     $t1 = $this->start_date->getTimeStamp();
     $t3 = $date->getTimestamp();
     if ($t1 < $t3) {
         $earlier = TRUE;
     }
     return $earlier;
 }
 /**
  * @param null $timeOffset
  * @param  int|null $storeId
  * return timeobject depending on store time zone
  * @return DateTime
  */
 public function getTimeObject($timeOffset = null, $storeId = null)
 {
     if (!empty($timeOffset)) {
         $date = new DateTime('now', $this->getTimeZone($storeId));
         $timeStamp = $date->getTimeStamp();
         $timeStamp += $timeOffset;
         $date->setTimestamp($timeStamp);
         return $date;
     }
     return new DateTime('now', $this->getTimeZone());
 }
Example #11
0
 public static function dateTimeFormat($date, $timezone = 'GMT')
 {
     $context = Context::getInstance();
     $lang = Language::getLanguageById($context->session->lang);
     $fromTimezone = new \DateTimeZone($timezone);
     $datetime = new \DateTime($date, $fromTimezone);
     $toTimezone = new \DateTimeZone($lang->timezone);
     $datetime->setTimezone($toTimezone);
     $strings = $lang->getStrings();
     $stamp = $datetime->getTimeStamp();
     return static::format($stamp, $strings->DATETIME_FORMAT);
 }
Example #12
0
function write_file_cache($type, $service_key, $lang_code)
{
    if ($type == 'notice') {
        $current_page = 1;
        $keyword = '';
        $page_block = 10;
        // 한 화면에 보여지는 페이지 수
        $limit = 20;
        // 한 화면에 보여지는 리스트 수
        $offset = ($current_page - 1) * $limit;
        // 각 페이지의 한 화면의 리스트의 첫번째 인덱스
        // DB에서 DATA 얻기
        $db_result = get_instance()->notice_db_model->get_notice_list(0, $lang_code, $keyword, $offset, $limit);
        $notice_list = array();
        if (isset($db_result['list'])) {
            $notice_list = $db_result['list'];
            foreach ($notice_list as $key => $row) {
                $date = new DateTime($row['regist_date'], new DateTimeZone('Asia/Seoul'));
                $notice_list[$key]['regist_date'] = (string) $date->getTimeStamp();
            }
        }
        // file write
        $string_data = json_encode($notice_list);
        file_put_contents(get_instance()->config->item('file_full_path') . $service_key . '_' . $lang_code . '.' . $type, $string_data);
    } else {
        if ($type == 'faq') {
            $current_page = 1;
            $keyword = '';
            $page_block = 10;
            // 한 화면에 보여지는 페이지 수
            $limit = 20;
            // 한 화면에 보여지는 리스트 수
            $offset = ($current_page - 1) * $limit;
            // 각 페이지의 한 화면의 리스트의 첫번째 인덱스
            // DB에서 DATA 얻기
            $db_result = get_instance()->faq_db_model->get_faq_list(0, $lang_code, $keyword, $offset, $limit);
            $faq_list = array();
            if (isset($db_result['list'])) {
                $faq_list = $db_result['list'];
                foreach ($faq_list as $key => $row) {
                    $date = new DateTime($row['regist_date'], new DateTimeZone('Asia/Seoul'));
                    $faq_list[$key]['regist_date'] = (string) $date->getTimeStamp();
                }
            }
            // file write
            $string_data = json_encode($faq_list);
            file_put_contents(get_instance()->config->item('file_full_path') . $service_key . '_' . $lang_code . '.' . $type, $string_data);
        } else {
        }
    }
}
Example #13
0
 public function doubleClick()
 {
     $now = new \DateTime('now');
     if (!$this->session->has('lastClick')) {
         $this->session->set('lastClick', $now->getTimestamp());
         return false;
     }
     $value = intval($this->session->get('lastClick'));
     $lastClick = new \DateTime();
     $lastClick->setTimestamp($value);
     $diff = $now->diff($lastClick);
     $this->session->set('lastClick', $now->getTimeStamp());
     return $diff->s < 3;
 }
Example #14
0
 public static function getNearestEntities($entityID, $currentDate, $startDate = '', $responsibleID = 0, $intervalInDays = 7, $checkPermissions = true, $limit = 5)
 {
     if (!is_string($startDate) || $startDate === '') {
         $startDate = $currentDate;
     }
     $site = new \CSite();
     $dateFormat = $site->GetDateFormat('SHORT');
     $curretTime = $currentDate !== '' ? MakeTimeStamp($currentDate, $dateFormat) : false;
     $startTime = $startDate !== '' ? MakeTimeStamp($startDate, $dateFormat) : false;
     if ($startTime === false) {
         return array();
     }
     $dt = new \DateTime();
     $dt->setTimestamp($startTime);
     $dt->add(new \DateInterval("P{$intervalInDays}D"));
     $endTime = $dt->getTimeStamp();
     $currentSorting = self::internalPrepareSorting($curretTime);
     $startSorting = self::internalPrepareSorting($startTime);
     $endSorting = self::internalPrepareSorting($endTime);
     $result = array();
     if ($entityID === \CCrmOwnerType::Lead) {
         $filter = array('>=BIRTHDAY_SORT' => $startSorting, '<=BIRTHDAY_SORT' => $endSorting, 'CHECK_PERMISSIONS' => $checkPermissions ? 'Y' : 'N');
         if ($responsibleID > 0) {
             $filter['=ASSIGNED_BY_ID'] = $responsibleID;
         }
         $dbResult = \CCrmLead::GetListEx(array(), $filter, false, array('nTopCount' => $limit), array('ID', 'BIRTHDATE', 'BIRTHDAY_SORT', 'HONORIFIC', 'NAME', 'SECOND_NAME', 'LAST_NAME'));
         while ($fields = $dbResult->Fetch()) {
             $fields['ENTITY_TYPE_ID'] = \CCrmOwnerType::Lead;
             $fields['IMAGE_ID'] = 0;
             $sorting = isset($fields['BIRTHDAY_SORT']) ? (int) $fields['BIRTHDAY_SORT'] : 512;
             $fields['IS_BIRTHDAY'] = $sorting === $currentSorting;
             $result[] = $fields;
         }
     } elseif ($entityID === \CCrmOwnerType::Contact) {
         $filter = array('>=BIRTHDAY_SORT' => $startSorting, '<=BIRTHDAY_SORT' => $endSorting, 'CHECK_PERMISSIONS' => $checkPermissions ? 'Y' : 'N');
         if ($responsibleID > 0) {
             $filter['=ASSIGNED_BY_ID'] = $responsibleID;
         }
         $dbResult = \CCrmContact::GetListEx(array(), $filter, false, array('nTopCount' => $limit), array('ID', 'BIRTHDATE', 'BIRTHDAY_SORT', 'HONORIFIC', 'NAME', 'SECOND_NAME', 'LAST_NAME', 'PHOTO'));
         while ($fields = $dbResult->Fetch()) {
             $fields['ENTITY_TYPE_ID'] = \CCrmOwnerType::Contact;
             $fields['IMAGE_ID'] = isset($fields['PHOTO']) ? (int) $fields['PHOTO'] : 0;
             $sorting = isset($fields['BIRTHDAY_SORT']) ? (int) $fields['BIRTHDAY_SORT'] : 512;
             $fields['IS_BIRTHDAY'] = $sorting === $currentSorting;
             $result[] = $fields;
         }
     }
     return $result;
 }
Example #15
0
 public function vote(TokenInterface $token, $object, array $attributes)
 {
     if ($object instanceof Workspace) {
         //check the expiration date first
         $now = new \DateTime();
         if ($object->getEndDate()) {
             if ($now->getTimeStamp() > $object->getEndDate()->getTimeStamp()) {
                 return VoterInterface::ACCESS_DENIED;
             }
         }
         //then we do all the rest
         $toolName = isset($attributes[0]) && $attributes[0] !== 'OPEN' ? $attributes[0] : null;
         $action = isset($attributes[1]) ? strtolower($attributes[1]) : 'open';
         $accesses = $this->wm->getAccesses($token, array($object), $toolName, $action);
         return isset($accesses[$object->getId()]) && $accesses[$object->getId()] === true ? VoterInterface::ACCESS_GRANTED : VoterInterface::ACCESS_DENIED;
     }
     return VoterInterface::ACCESS_ABSTAIN;
 }
 public function testCalculateNew()
 {
     //Test Today.
     $todayDateStamp = DateTimeCalculatorUtil::calculateNew(DateTimeCalculatorUtil::TODAY, new DateTime(null, new DateTimeZone(Yii::app()->timeZoneHelper->getForCurrentUser())));
     $todayDateTime = new DateTime(null, new DateTimeZone(Yii::app()->timeZoneHelper->getForCurrentUser()));
     $today = Yii::app()->dateFormatter->format(DatabaseCompatibilityUtil::getDateFormat(), $todayDateTime->getTimeStamp());
     $this->assertEquals($today, $todayDateStamp);
     //Test Tomorrow.
     $tomorrowDateStamp = DateTimeCalculatorUtil::calculateNew(DateTimeCalculatorUtil::TOMORROW, new DateTime(null, new DateTimeZone(Yii::app()->timeZoneHelper->getForCurrentUser())));
     $tomorrowDateTime = new DateTime(null, new DateTimeZone(Yii::app()->timeZoneHelper->getForCurrentUser()));
     $tomorrow = Yii::app()->dateFormatter->format(DatabaseCompatibilityUtil::getDateFormat(), $tomorrowDateTime->getTimeStamp() + 60 * 60 * 24);
     $this->assertEquals($tomorrow, $tomorrowDateStamp);
     //Test Yesterday.
     $yesterdayDateStamp = DateTimeCalculatorUtil::calculateNew(DateTimeCalculatorUtil::YESTERDAY, new DateTime(null, new DateTimeZone(Yii::app()->timeZoneHelper->getForCurrentUser())));
     $yesterdayDateTime = new DateTime(null, new DateTimeZone(Yii::app()->timeZoneHelper->getForCurrentUser()));
     $yesterday = Yii::app()->dateFormatter->format(DatabaseCompatibilityUtil::getDateFormat(), $yesterdayDateTime->getTimeStamp() - 60 * 60 * 24);
     $this->assertEquals($yesterday, $yesterdayDateStamp);
     //Test Now.
     $nowDateTimeStamp = DateTimeCalculatorUtil::calculateNew(DateTimeCalculatorUtil::NOW, new DateTime(null, new DateTimeZone(Yii::app()->timeZoneHelper->getForCurrentUser())));
     $nowDateTime = new DateTime(null, new DateTimeZone(Yii::app()->timeZoneHelper->getForCurrentUser()));
     $this->assertWithinTolerance($nowDateTime->getTimeStamp(), DateTimeUtil::convertDbFormatDateTimeToTimestamp($nowDateTimeStamp), 1);
     //Now test all calculations using a different time zone.
     $this->assertNotEquals('Europe/Malta', Yii::app()->timeZoneHelper->getForCurrentUser());
     //Test Today.
     $todayDateStamp = DateTimeCalculatorUtil::calculateNew(DateTimeCalculatorUtil::TODAY, new DateTime(null, new DateTimeZone('Europe/Malta')));
     $todayDateTime = new DateTime(null, new DateTimeZone('Europe/Malta'));
     $today = Yii::app()->dateFormatter->format(DatabaseCompatibilityUtil::getDateFormat(), $todayDateTime->getTimeStamp());
     $this->assertEquals($today, $todayDateStamp);
     //Test Tomorrow.
     $tomorrowDateStamp = DateTimeCalculatorUtil::calculateNew(DateTimeCalculatorUtil::TOMORROW, new DateTime(null, new DateTimeZone('Europe/Malta')));
     $tomorrowDateTime = new DateTime(null, new DateTimeZone('Europe/Malta'));
     $tomorrow = Yii::app()->dateFormatter->format(DatabaseCompatibilityUtil::getDateFormat(), $tomorrowDateTime->getTimeStamp() + 60 * 60 * 24);
     $this->assertEquals($tomorrow, $tomorrowDateStamp);
     //Test Yesterday.
     $yesterdayDateStamp = DateTimeCalculatorUtil::calculateNew(DateTimeCalculatorUtil::YESTERDAY, new DateTime(null, new DateTimeZone('Europe/Malta')));
     $yesterdayDateTime = new DateTime(null, new DateTimeZone('Europe/Malta'));
     $yesterday = Yii::app()->dateFormatter->format(DatabaseCompatibilityUtil::getDateFormat(), $yesterdayDateTime->getTimeStamp() - 60 * 60 * 24);
     $this->assertEquals($yesterday, $yesterdayDateStamp);
     //Test Now.
     $nowDateTimeStamp = DateTimeCalculatorUtil::calculateNew(DateTimeCalculatorUtil::NOW, new DateTime(null, new DateTimeZone('Europe/Malta')));
     $nowDateTime = new DateTime(null, new DateTimeZone('Europe/Malta'));
     $this->assertWithinTolerance($nowDateTime->getTimeStamp(), DateTimeUtil::convertDbFormatDateTimeToTimestamp($nowDateTimeStamp), 1);
 }
 protected function setImportedEventFromMeetupData(ImportedEventModel $importedEvent, $meetupData)
 {
     $changesToSave = false;
     if (property_exists($meetupData, 'description')) {
         $description = $meetupData->description;
         var_dump($description);
         if ($importedEvent->getDescription() != $description) {
             $importedEvent->setDescription($description);
             $changesToSave = true;
         }
     }
     $start = new \DateTime('', new \DateTimeZone('UTC'));
     $start->setTimestamp($meetupData->time / 1000);
     if (property_exists($meetupData, 'duration') && $meetupData->duration) {
         $end = new \DateTime('', new \DateTimeZone('UTC'));
         $end->setTimestamp($meetupData->time / 1000);
         $end->add(new \DateInterval("PT" . $meetupData->duration / 1000 . "S"));
     } else {
         $end = clone $start;
         $end->add(new \DateInterval("PT3H"));
     }
     if (!$importedEvent->getStartAt() || $importedEvent->getStartAt()->getTimeStamp() != $start->getTimeStamp()) {
         $importedEvent->setStartAt($start);
         $changesToSave = true;
     }
     if (!$importedEvent->getEndAt() || $importedEvent->getEndAt()->getTimeStamp() != $end->getTimeStamp()) {
         $importedEvent->setEndAt($end);
         $changesToSave = true;
     }
     if ($importedEvent->getTitle() != $meetupData->name) {
         $importedEvent->setTitle($meetupData->name);
         $changesToSave = true;
     }
     if ($importedEvent->getUrl() != $meetupData->event_url) {
         $importedEvent->setUrl($meetupData->event_url);
         $changesToSave = true;
     }
     if ($importedEvent->getTimezone() != $meetupData->timezone) {
         $importedEvent->setTimezone($meetupData->timezone);
         $changesToSave = true;
     }
     if ($importedEvent->getTicketUrl() != $meetupData->event_url) {
         $importedEvent->setTicketUrl($meetupData->event_url);
         $changesToSave = true;
     }
     return $changesToSave;
 }
 public function testSearchFormDynamicAttributes()
 {
     $super = User::getByUsername('super');
     Yii::app()->user->userModel = $super;
     $searchAttributes = array('aaaMember' => 'Vomitorio Corp', 'bbb' => array('relatedData' => true, 'ccc' => array('relatedData' => true, 'date__Date' => array('type' => MixedDateTypesSearchFormAttributeMappingRules::TYPE_AFTER, 'firstDate' => '1991-03-04'), 'dateTime__DateTime' => array('type' => MixedDateTypesSearchFormAttributeMappingRules::TYPE_TODAY), 'dateTime2__DateTime' => array('value' => null), 'eee' => array('relatedData' => true, 'eeeMember' => 'eeeMemberValue'), 'iii' => array('relatedData' => true, 'date__Date' => array('type' => MixedDateTypesSearchFormAttributeMappingRules::TYPE_AFTER, 'firstDate' => '1991-03-04'), 'dateTime__DateTime' => array('type' => MixedDateTypesSearchFormAttributeMappingRules::TYPE_TODAY), 'dateTime2__DateTime' => array('value' => null)))));
     $metadataAdapter = new SearchDataProviderMetadataAdapter(new AAA(false), 1, $searchAttributes);
     $todayDateTime = new DateTime(null, new DateTimeZone(Yii::app()->timeZoneHelper->getForCurrentUser()));
     $today = Yii::app()->dateFormatter->format(DatabaseCompatibilityUtil::getDateFormat(), $todayDateTime->getTimeStamp());
     $todayPlus7Days = MixedDateTypesSearchFormAttributeMappingRules::calculateNewDateByDaysFromNow(7);
     $metadata = $metadataAdapter->getAdaptedMetadata();
     $compareClauses = array(1 => array('attributeName' => 'aaaMember', 'operatorType' => 'startsWith', 'value' => 'Vomitorio Corp'), 2 => array('attributeName' => 'bbb', 'relatedModelData' => array('attributeName' => 'ccc', 'relatedModelData' => array('attributeName' => 'date', 'operatorType' => 'greaterThanOrEqualTo', 'value' => '1991-03-04'))), 3 => array('attributeName' => 'bbb', 'relatedModelData' => array('attributeName' => 'ccc', 'relatedModelData' => array('attributeName' => 'dateTime', 'operatorType' => 'greaterThanOrEqualTo', 'value' => DateTimeUtil::convertDateIntoTimeZoneAdjustedDateTimeBeginningOfDay($today)))), 4 => array('attributeName' => 'bbb', 'relatedModelData' => array('attributeName' => 'ccc', 'relatedModelData' => array('attributeName' => 'dateTime', 'operatorType' => 'lessThanOrEqualTo', 'value' => DateTimeUtil::convertDateIntoTimeZoneAdjustedDateTimeEndOfDay($today)))), 5 => array('attributeName' => 'bbb', 'relatedModelData' => array('attributeName' => 'ccc', 'relatedModelData' => array('attributeName' => 'eee', 'relatedModelData' => array('attributeName' => 'eeeMember', 'operatorType' => 'startsWith', 'value' => 'eeeMemberValue')))), 6 => array('attributeName' => 'bbb', 'relatedModelData' => array('attributeName' => 'ccc', 'relatedModelData' => array('attributeName' => 'iii', 'relatedModelData' => array('attributeName' => 'date', 'operatorType' => 'greaterThanOrEqualTo', 'value' => '1991-03-04')))), 7 => array('attributeName' => 'bbb', 'relatedModelData' => array('attributeName' => 'ccc', 'relatedModelData' => array('attributeName' => 'iii', 'relatedModelData' => array('attributeName' => 'dateTime', 'operatorType' => 'greaterThanOrEqualTo', 'value' => DateTimeUtil::convertDateIntoTimeZoneAdjustedDateTimeBeginningOfDay($today))))), 8 => array('attributeName' => 'bbb', 'relatedModelData' => array('attributeName' => 'ccc', 'relatedModelData' => array('attributeName' => 'iii', 'relatedModelData' => array('attributeName' => 'dateTime', 'operatorType' => 'lessThanOrEqualTo', 'value' => DateTimeUtil::convertDateIntoTimeZoneAdjustedDateTimeEndOfDay($today))))));
     $compareStructure = '1 and (2) and (3 and 4) and 5 and (6) and (7 and 8)';
     $this->assertEquals($compareClauses, $metadata['clauses']);
     $this->assertEquals($compareStructure, $metadata['structure']);
 }
 public function testSearchFormDynamicAttributes()
 {
     $super = User::getByUsername('super');
     Yii::app()->user->userModel = $super;
     $searchAttributes = array('date__Date' => array('type' => MixedDateTypesSearchFormAttributeMappingRules::TYPE_AFTER, 'firstDate' => '1991-03-04'), 'dateTime__DateTime' => array('type' => MixedDateTypesSearchFormAttributeMappingRules::TYPE_TODAY), 'dateTime2__DateTime' => array('value' => null));
     $searchForm = new MixedRelationsModelSearchFormTestModel(new MixedRelationsModel());
     $metadataAdapter = new SearchDataProviderMetadataAdapter($searchForm, $super->id, $searchAttributes);
     $todayDateTime = new DateTime(null, new DateTimeZone(Yii::app()->timeZoneHelper->getForCurrentUser()));
     $today = Yii::app()->dateFormatter->format(DatabaseCompatibilityUtil::getDateFormat(), $todayDateTime->getTimeStamp());
     $todayPlus7Days = MixedDateTypesSearchFormAttributeMappingRules::calculateNewDateByDaysFromNow(7);
     $metadata = $metadataAdapter->getAdaptedMetadata();
     $compareClauses = array(1 => array('attributeName' => 'date', 'operatorType' => 'greaterThanOrEqualTo', 'value' => '1991-03-04'), 2 => array('attributeName' => 'dateTime', 'operatorType' => 'greaterThanOrEqualTo', 'value' => DateTimeUtil::convertDateIntoTimeZoneAdjustedDateTimeBeginningOfDay($today)), 3 => array('attributeName' => 'dateTime', 'operatorType' => 'lessThanOrEqualTo', 'value' => DateTimeUtil::convertDateIntoTimeZoneAdjustedDateTimeEndOfDay($today)));
     $compareStructure = '(1) and (2 and 3)';
     $this->assertEquals($compareClauses, $metadata['clauses']);
     $this->assertEquals($compareStructure, $metadata['structure']);
 }
 /**
  * Goes on to the next iteration
  *
  * @return void
  */
 public function next()
 {
     /*
             if (!is_null($this->count) && $this->counter >= $this->count) {
                 $this->currentDate = null;
             }*/
     $previousStamp = $this->currentDate->getTimeStamp();
     while (true) {
         $this->currentOverriddenEvent = null;
         // If we have a next date 'stored', we use that
         if ($this->nextDate) {
             $this->currentDate = $this->nextDate;
             $currentStamp = $this->currentDate->getTimeStamp();
             $this->nextDate = null;
         } else {
             // Otherwise, we calculate it
             switch ($this->frequency) {
                 case 'hourly':
                     $this->nextHourly();
                     break;
                 case 'daily':
                     $this->nextDaily();
                     break;
                 case 'weekly':
                     $this->nextWeekly();
                     break;
                 case 'monthly':
                     $this->nextMonthly();
                     break;
                 case 'yearly':
                     $this->nextYearly();
                     break;
             }
             $currentStamp = $this->currentDate->getTimeStamp();
             // Checking exception dates
             foreach ($this->exceptionDates as $exceptionDate) {
                 if ($this->currentDate == $exceptionDate) {
                     $this->counter++;
                     continue 2;
                 }
             }
             foreach ($this->overriddenDates as $overriddenDate) {
                 if ($this->currentDate == $overriddenDate) {
                     continue 2;
                 }
             }
         }
         // Checking overridden events
         foreach ($this->overriddenEvents as $index => $event) {
             if ($index > $previousStamp && $index <= $currentStamp) {
                 // We're moving the 'next date' aside, for later use.
                 $this->nextDate = clone $this->currentDate;
                 $this->currentDate = $event->DTSTART->getDateTime();
                 $this->currentOverriddenEvent = $event;
                 break;
             }
         }
         break;
     }
     /*
             if (!is_null($this->until)) {
                 if($this->currentDate > $this->until) {
                     $this->currentDate = null;
                 }
             }*/
     $this->counter++;
 }
Example #21
0
 protected function setAndGetDateTimeAttribute($attributeName, $withDefaultData)
 {
     $this->assertTrue(isset($attributeName) && $attributeName != '');
     $this->assertTrue(isset($withDefaultData) && is_bool($withDefaultData));
     $attributeForm = new DateTimeAttributeForm();
     $attributeForm->attributeName = $attributeName;
     $attributeForm->attributeLabels = array('de' => 'Test DateTime 2 de', 'en' => 'Test DateTime 2 en', 'es' => 'Test DateTime 2 es', 'fr' => 'Test DateTime 2 fr', 'it' => 'Test DateTime 2 it');
     $attributeForm->isAudited = true;
     $attributeForm->isRequired = true;
     if ($withDefaultData) {
         $attributeForm->defaultValueCalculationType = DateTimeCalculatorUtil::NOW;
     } else {
         $attributeForm->defaultValueCalculationType = null;
     }
     $modelAttributesAdapterClassName = $attributeForm::getModelAttributeAdapterNameForSavingAttributeFormData();
     $adapter = new $modelAttributesAdapterClassName(new Account());
     try {
         $adapter->setAttributeMetadataFromForm($attributeForm);
     } catch (FailedDatabaseSchemaChangeException $e) {
         echo $e->getMessage();
         $this->fail();
     }
     $attributeForm = AttributesFormFactory::createAttributeFormByAttributeName(new Account(), $attributeName . 'Cstm');
     $this->assertEquals('DateTime', $attributeForm->getAttributeTypeName());
     $this->assertEquals($attributeName . 'Cstm', $attributeForm->attributeName);
     $compareAttributeLabels = array('de' => 'Test DateTime 2 de', 'en' => 'Test DateTime 2 en', 'es' => 'Test DateTime 2 es', 'fr' => 'Test DateTime 2 fr', 'it' => 'Test DateTime 2 it');
     $this->assertEquals($compareAttributeLabels, $attributeForm->attributeLabels);
     $this->assertEquals(true, $attributeForm->isAudited);
     $this->assertEquals(true, $attributeForm->isRequired);
     if ($withDefaultData) {
         $this->assertEquals(DateTimeCalculatorUtil::NOW, $attributeForm->defaultValueCalculationType);
         //Confirm default calculation loads correct default value for Account.
         $account = new Account();
         $nowDateTime = new DateTime(null, new DateTimeZone(Yii::app()->timeZoneHelper->getForCurrentUser()));
         $this->assertWithinTolerance($nowDateTime->getTimeStamp(), DateTimeUtil::convertDbFormatDateTimeToTimestamp($account->{$attributeName . 'Cstm'}), 1);
     } else {
         $this->assertEquals(null, $attributeForm->defaultValueCalculationType);
         //Confirm default calculation loads correct default value (null) for Account.
         $account = new Account();
         $this->assertEquals(null, $account->{$attributeName . 'Cstm'});
     }
 }
 public function testGetMetadataForDynamicDateTimeAttributeThatIsOnManyRelatedModel()
 {
     $super = User::getByUsername('super');
     Yii::app()->user->userModel = $super;
     $searchForm = new ASearchFormTestModel(new MixedRelationsModel());
     //Make sure the timeZone is different than UTC for testing.
     Yii::app()->user->userModel->timeZone = 'America/Chicago';
     //TEST when no value present
     $metadata = SearchFormAttributesToSearchDataProviderMetadataUtil::getMetadata($searchForm, 'dateDateTimeADate__Date', null);
     $compareData = array(array('manyMany' => array('value' => array('aDate' => null))));
     $this->assertEquals($compareData, $metadata);
     //Test Date = Today
     $value = array();
     $value['type'] = MixedDateTypesSearchFormAttributeMappingRules::TYPE_TODAY;
     $metadata = SearchFormAttributesToSearchDataProviderMetadataUtil::getMetadata($searchForm, 'dateDateTimeADateTime__DateTime', $value);
     $todayDateTime = new DateTime(null, new DateTimeZone(Yii::app()->timeZoneHelper->getForCurrentUser()));
     $today = Yii::app()->dateFormatter->format(DatabaseCompatibilityUtil::getDateFormat(), $todayDateTime->getTimeStamp());
     $compareData = array(array('manyMany' => array('value' => array('aDateTime' => DateTimeUtil::convertDateIntoTimeZoneAdjustedDateTimeBeginningOfDay($today)), 'operatorType' => 'greaterThanOrEqualTo', 'appendStructureAsAnd' => true)), array('manyMany' => array('value' => array('aDateTime' => DateTimeUtil::convertDateIntoTimeZoneAdjustedDateTimeEndOfDay($today)), 'operatorType' => 'lessThanOrEqualTo', 'appendStructureAsAnd' => true)));
     $this->assertEquals($compareData, $metadata);
 }
Example #23
0
             if (!$value) {
                 $event["statustime"] = 0;
                 break;
             }
             if (!isset($params["timezone"])) {
                 $app->response->status(400);
                 return;
             }
             $timezone = new DateTimeZone($params["timezone"]);
             $statustime = $old_event["statustime"];
             $edate = new DateTime("@{$statustime}");
             $edate->setTimezone($timezone);
             $new_date = date_parse($value);
             $edate->setTime($new_date["hour"], $new_date["minute"]);
             $edate->setDate($new_date["year"], $new_date["month"], $new_date["day"]);
             $event["statustime"] = $edate->getTimeStamp();
             break;
         case "severity":
             $event["severity"] = $value;
             break;
         case "contact":
             $event["contact"] = $value;
             break;
         case "gcal":
             $event["gcal"] = $value;
             break;
     }
 }
 $event = Postmortem::save_event($event);
 if (is_null($event["id"])) {
     var_dump($event);
Example #24
0
 /**
  * Parses some information from calendar objects, used for optimized
  * calendar-queries.
  *
  * Returns an array with the following keys:
  *   * etag - An md5 checksum of the object without the quotes.
  *   * size - Size of the object in bytes
  *   * componentType - VEVENT, VTODO or VJOURNAL
  *   * firstOccurence
  *   * lastOccurence
  *   * uid - value of the UID property
  *
  * @param string $calendarData
  * @return array
  */
 public function getDenormalizedData($calendarData)
 {
     $vObject = Reader::read($calendarData);
     $componentType = null;
     $component = null;
     $firstOccurrence = null;
     $lastOccurrence = null;
     $uid = null;
     $classification = self::CLASSIFICATION_PUBLIC;
     foreach ($vObject->getComponents() as $component) {
         if ($component->name !== 'VTIMEZONE') {
             $componentType = $component->name;
             $uid = (string) $component->UID;
             break;
         }
     }
     if (!$componentType) {
         throw new \Sabre\DAV\Exception\BadRequest('Calendar objects must have a VJOURNAL, VEVENT or VTODO component');
     }
     if ($componentType === 'VEVENT' && $component->DTSTART) {
         $firstOccurrence = $component->DTSTART->getDateTime()->getTimeStamp();
         // Finding the last occurrence is a bit harder
         if (!isset($component->RRULE)) {
             if (isset($component->DTEND)) {
                 $lastOccurrence = $component->DTEND->getDateTime()->getTimeStamp();
             } elseif (isset($component->DURATION)) {
                 $endDate = clone $component->DTSTART->getDateTime();
                 $endDate->add(DateTimeParser::parse($component->DURATION->getValue()));
                 $lastOccurrence = $endDate->getTimeStamp();
             } elseif (!$component->DTSTART->hasTime()) {
                 $endDate = clone $component->DTSTART->getDateTime();
                 $endDate->modify('+1 day');
                 $lastOccurrence = $endDate->getTimeStamp();
             } else {
                 $lastOccurrence = $firstOccurrence;
             }
         } else {
             $it = new EventIterator($vObject, (string) $component->UID);
             $maxDate = new \DateTime(self::MAX_DATE);
             if ($it->isInfinite()) {
                 $lastOccurrence = $maxDate->getTimeStamp();
             } else {
                 $end = $it->getDtEnd();
                 while ($it->valid() && $end < $maxDate) {
                     $end = $it->getDtEnd();
                     $it->next();
                 }
                 $lastOccurrence = $end->getTimeStamp();
             }
         }
     }
     if ($component->CLASS) {
         $classification = CalDavBackend::CLASSIFICATION_PRIVATE;
         switch ($component->CLASS->getValue()) {
             case 'PUBLIC':
                 $classification = CalDavBackend::CLASSIFICATION_PUBLIC;
                 break;
             case 'CONFIDENTIAL':
                 $classification = CalDavBackend::CLASSIFICATION_CONFIDENTIAL;
                 break;
         }
     }
     return ['etag' => md5($calendarData), 'size' => strlen($calendarData), 'componentType' => $componentType, 'firstOccurence' => is_null($firstOccurrence) ? null : max(0, $firstOccurrence), 'lastOccurence' => $lastOccurrence, 'uid' => $uid, 'classification' => $classification];
 }
Example #25
0
        preg_match('/\\"\\>\\<code\\>([0-9\\.]+)(B|k|M|G|T)\\<\\/code\\>.*\\>(.*)_.*_(\\d+)_(\\d+)_(\\d+)_(\\d+)_(\\d+)_(\\d+).*?wtv/', $line, $matches);
        if ($matches) {
            // Parse details
            $size = bytes($matches[1], $matches[2]);
            $title = $matches[3];
            $date = new DateTime($matches[4] . '-' . $matches[5] . '-' . $matches[6] . ' ' . $matches[7] . ':' . $matches[8] . ':' . $matches[9]);
            // Check if it's a new show
            if ($title != $prevTitle) {
                if ($prevTitle != '') {
                    $shows[] = $show;
                }
                $show = array('title' => $title, 'episodes' => array());
                $prevTitle = $title;
            }
            // Add this episode
            $show['episodes'][] = array('date' => $date->format('D, M j, Y'), 'timestamp' => $date->getTimeStamp(), 'size' => $size);
        }
    }
    // Add in last show
    if ($prevTitle != '') {
        $shows[] = $show;
    }
} catch (Exception $e) {
    $json['error'] = $e->getMessage();
}
$json['shows'] = $shows;
print json_encode($json);
function bytes($size, $unit)
{
    return intval($size * (1 << strpos('BkMGT', $unit) * 10));
}
 public function rssGenerator($updates = null)
 {
     if ($updates == "updates") {
         $sites = DB::table('archive')->where('action', 'UPDATE')->take(100)->orderBy('archive_date', 'desc')->get();
     } else {
         if ($updates == "all") {
             $sites = DB::table('archive')->take(100)->orderBy('archive_date', 'desc')->get();
         } else {
             $sites = DB::table('archive')->whereNotIn('action', array('UPDATE'))->orderBy('archive_date', 'desc')->take(100)->get();
         }
     }
     foreach ($sites as $site) {
         $site = (array) $site;
         $major = 0;
         $minor = 0;
         if ($site['show_counts'] == 0) {
             $site['patients'] = 0;
             $site['encounters'] = 0;
             $site['observations'] = 0;
         }
         $atlasVersion = json_decode($site['atlas_version']);
         if ($atlasVersion != null) {
             list($major, $minor) = explode(".", $atlasVersion);
         }
         if ($major >= 1 && $minor > 1) {
             unset($site['data']);
             //TODO
             $sitesList[] = $site;
         } else {
             $dataJson = json_decode($site['data'], true);
             $version = $dataJson['version'];
             $site['version'] = $version;
             unset($site['data']);
             $sitesList[] = $site;
         }
     }
     $feed = Feed::make();
     $openmrs = new FeedPerson();
     $openmrs->name('OpenMRS');
     $openmrs->email('*****@*****.**');
     $logo = new FeedImage();
     $logo->title('OpenMRS Atlas Feed');
     $logo->imageUrl(asset('images/openmrs.gif'));
     $logo->linkUrl(route('home'));
     $feed->channel()->BaseURL(route('home'));
     $feed->channel()->Title()->Add('text', 'OpenMRS Atlas Feed');
     $feed->channel()->Author(0, $openmrs);
     $feed->channel()->permalink(route('rss'));
     $feed->channel()->Description()->Add('text', 'Latest updates on OpenMRS Atlas');
     $feed->links()->add(new FeedLink('text', route('home')));
     $feed->logo()->title('OpenMRS Atlas Feed')->imageUrl(asset('images/openmrs.gif'))->linkUrl(route('home'))->up()->pubdate(time())->permalink(route('rss'))->baseurl(route('home'));
     foreach ($sitesList as $site) {
         $title = $site['name'];
         if ($site['action'] === "ADD") {
             $title = $site['name'] . " joined the OpenMRS Atlas";
         }
         if ($site['action'] === "UPDATE") {
             $title = $site['name'] . " updated on OpenMRS Atlas";
         }
         if ($site['action'] === "DELETE") {
             $title = "OpenMRS Atlas bids farewell to " . $site['name'];
         }
         $dateCreated = new DateTime($site['date_created']);
         $notes = $site['notes'] == "" ? "" : "<br><b>Notes:</b> " . $site['notes'];
         $url = $site['url'] == "" && filter_var($site['url'], FILTER_VALIDATE_URL) ? "" : "<br><a href=\"" . $site['url'] . "\">" . $site['url'] . "</a>";
         $observations = preg_match("/^\$|0/", $site['observations']) ? "" : "<br><b>Observation:</b> " . $site['observations'];
         $encounters = preg_match("/^\$|0/", $site['encounters']) ? "" : "<br><b>Encounters:</b> " . $site['encounters'];
         $patients = preg_match("/^\$|0/", $site['patients']) ? "" : "<br><b>Patients:</b> " . $site['patients'];
         $counts = $encounters . $patients . $observations;
         $site['version'] = $site['version'] == "" ? "Unknown" : $site['version'];
         $content = '<b>OpenMRS Version :</b> ' . $site['version'] . $counts . $notes . "<br><b>Date created :</b> " . $dateCreated->format('Y-m-d H:i:s') . $url;
         $date = new DateTime($site['archive_date']);
         $feed->entry()->published($date->getTimeStamp())->author()->name($site['contact'])->email($site['email'])->up()->title($title)->guid($site['id'])->permalink(route('home') . '?site=' . $site['site_uuid'])->category($site['type'])->content()->add('html', $content)->up();
     }
     $response = Response::make($feed->Rss20(), 200);
     $response->header('Content-Type', 'application/rss+xml');
     return $response;
 }
Example #27
0
 public static function saveVote()
 {
     self::check_logged_in();
     $p = $_POST;
     $user = User::findByPK($p['user_id']);
     $poll = Poll::findByPK($p['poll_id']);
     $polloptions = PollOption::findByPollId($poll->id);
     $curruser = self::get_user_logged_in();
     if (!($curruser->id == $user->id)) {
         Redirect::to('/user/' . $curruser->id, array('error' => 'Virheellinen pyyntö!'));
     }
     $status = Poll::checkVoteStatus($user->id, $poll->id);
     if ($status === NULL) {
         Redirect::to('/user/' . $curruser->id, array('error' => 'Sinulla ei ole äänioikeutta pyytämääsi äänestykseen!'));
     } elseif ($status === TRUE) {
         Redirect::to('/user/' . $curruser->id, array('error' => 'Olet jo käyttänyt äänioikeutesi äänestyksessä ' . $poll->name . '!'));
     }
     $errors = array();
     $poll_start = new DateTime($poll->start_time);
     $poll_end = new DateTime($poll->end_time);
     if ($poll_start->getTimeStamp() >= time()) {
         $errors[] = 'Äänestys ei ole vielä alkanut!';
     }
     if ($poll_end->getTimeStamp() <= time()) {
         $errors[] = 'Äänestys on päättynyt – et voi enää äänestää!';
     }
     if (!isset($_POST['choice'])) {
         $errors[] = 'Et valinnut yhtään vaihtoehtoa. Valitse vaihtoehto äänestääksesi!';
     } else {
         $polloptions[$p['choice']]->chosen = TRUE;
     }
     if (!isset($_POST['accept'])) {
         $errors[] = 'Et ilmaissut hyväksyväsi äänioikeutesi ainutkertaisuuttä. Et voi äänestää hyväksymättä sitä.';
     }
     if (!empty($errors)) {
         View::make('poll/vote.html', array('user' => $user, 'poll' => $poll, 'polloptions' => $polloptions, 'errors' => $errors));
     } else {
         $vote = new Vote(array('users_id' => $user->id, 'polls_id' => $poll->id, 'poll_options_id' => $polloptions[$p['choice']]->id, 'time' => date('c')));
         $vote->save();
         Redirect::to('/user/' . $curruser->id, array('message' => 'Äänesi äänestyksessä ' . $poll->name . ' on tallennettu! Antamaasi ääntä ei voida yhdistää sinuun myöhemmin.'));
     }
 }
 /**
  * Parses some information from calendar objects, used for optimized
  * calendar-queries.
  *
  * Returns an array with the following keys:
  *   * etag
  *   * size
  *   * componentType
  *   * firstOccurence
  *   * lastOccurence
  *
  * @param string $calendarData
  * @throws Sabre_DAV_Exception_BadRequest
  * @return array
  */
 protected function getDenormalizedData($calendarData)
 {
     /** @var Sabre\VObject\Component\VEvent $vObject */
     $vObject = Sabre\VObject\Reader::read($calendarData);
     $componentType = null;
     $component = null;
     $firstOccurence = null;
     $lastOccurence = null;
     foreach ($vObject->getComponents() as $component) {
         if ($component->name !== 'VTIMEZONE') {
             $componentType = $component->name;
             break;
         }
     }
     if (!$componentType) {
         throw new Sabre_DAV_Exception_BadRequest('Calendar objects must have a VJOURNAL, VEVENT or VTODO component');
     }
     if ($componentType === 'VEVENT') {
         /** @var Sabre\VObject\Component\VEvent $component */
         /** @var Sabre\VObject\Property\DateTime $dtstart  */
         $dtstart = $component->__get("DTSTART");
         $firstOccurence = $dtstart->getDateTime()->getTimeStamp();
         // Finding the last occurence is a bit harder
         if (!$component->__get("RRULE")) {
             $lastOccurence = self::getDtEndTimeStamp($component);
         } else {
             $it = new Sabre\VObject\RecurrenceIterator($vObject, (string) $component->__get("UID"));
             $maxDate = new DateTime(CALDAV_MAX_YEAR . "-01-01");
             if ($it->isInfinite()) {
                 $lastOccurence = $maxDate->getTimeStamp();
             } else {
                 $end = $it->getDtEnd();
                 while ($it->valid() && $end < $maxDate) {
                     $end = $it->getDtEnd();
                     $it->next();
                 }
                 $lastOccurence = $end->getTimeStamp();
             }
         }
     }
     return array('etag' => md5($calendarData), 'size' => strlen($calendarData), 'componentType' => $componentType, 'firstOccurence' => $firstOccurence, 'lastOccurence' => $lastOccurence);
 }
Example #29
0
 /**
  * Parses some information from calendar objects, used for optimized
  * calendar-queries.
  *
  * Returns an array with the following keys:
  *   * etag
  *   * size
  *   * componentType
  *   * firstOccurence
  *   * lastOccurence
  *
  * @param string $calendarData
  * @return array
  */
 protected function getDenormalizedData($calendarData)
 {
     $vObject = VObject\Reader::read($calendarData);
     $componentType = null;
     $component = null;
     $firstOccurence = null;
     $lastOccurence = null;
     foreach ($vObject->getComponents() as $component) {
         if ($component->name !== 'VTIMEZONE') {
             $componentType = $component->name;
             break;
         }
     }
     if (!$componentType) {
         throw new \SabreForRainLoop\DAV\Exception\BadRequest('Calendar objects must have a VJOURNAL, VEVENT or VTODO component');
     }
     if ($componentType === 'VEVENT') {
         $firstOccurence = $component->DTSTART->getDateTime()->getTimeStamp();
         // Finding the last occurence is a bit harder
         if (!isset($component->RRULE)) {
             if (isset($component->DTEND)) {
                 $lastOccurence = $component->DTEND->getDateTime()->getTimeStamp();
             } elseif (isset($component->DURATION)) {
                 $endDate = clone $component->DTSTART->getDateTime();
                 $endDate->add(VObject\DateTimeParser::parse($component->DURATION->getValue()));
                 $lastOccurence = $endDate->getTimeStamp();
             } elseif (!$component->DTSTART->hasTime()) {
                 $endDate = clone $component->DTSTART->getDateTime();
                 $endDate->modify('+1 day');
                 $lastOccurence = $endDate->getTimeStamp();
             } else {
                 $lastOccurence = $firstOccurence;
             }
         } else {
             $it = new VObject\RecurrenceIterator($vObject, (string) $component->UID);
             $maxDate = new \DateTime(self::MAX_DATE);
             if ($it->isInfinite()) {
                 $lastOccurence = $maxDate->getTimeStamp();
             } else {
                 $end = $it->getDtEnd();
                 while ($it->valid() && $end < $maxDate) {
                     $end = $it->getDtEnd();
                     $it->next();
                 }
                 $lastOccurence = $end->getTimeStamp();
             }
         }
     }
     return array('etag' => md5($calendarData), 'size' => strlen($calendarData), 'componentType' => $componentType, 'firstOccurence' => $firstOccurence, 'lastOccurence' => $lastOccurence);
 }
Example #30
0
 /**
  * Processes recurrence rules
  *
  * @return void or false if no Events exist
  */
 public function processRecurrences()
 {
     $events = isset($this->cal['VEVENT']) ? $this->cal['VEVENT'] : array();
     if (empty($events)) {
         return false;
     }
     foreach ($events as $anEvent) {
         if (isset($anEvent['RRULE']) && $anEvent['RRULE'] != '') {
             if (isset($anEvent['DTSTART_array'][0]['TZID']) && $this->isValidTimeZoneId($anEvent['DTSTART_array'][0]['TZID'])) {
                 $initialStartTimeZone = $anEvent['DTSTART_array'][0]['TZID'];
             }
             $initialStart = new \DateTime($anEvent['DTSTART_array'][1], isset($initialStartTimeZone) ? new \DateTimeZone($initialStartTimeZone) : null);
             $initialStartOffset = $initialStart->getOffset();
             if (isset($anEvent['DTEND'])) {
                 if (isset($anEvent['DTEND_array'][0]['TZID']) && $this->isValidTimeZoneId($anEvent['DTSTART_array'][0]['TZID'])) {
                     $initialEndTimeZone = $anEvent['DTSTART_array'][0]['TZID'];
                 }
                 $initialEnd = new \DateTime($anEvent['DTEND_array'][1], isset($initialEndTimeZone) ? new \DateTimeZone($initialEndTimeZone) : null);
                 $initialEndOffset = $initialEnd->getOffset();
             }
             // Recurring event, parse RRULE and add appropriate duplicate events
             $rrules = array();
             $rruleStrings = explode(';', $anEvent['RRULE']);
             foreach ($rruleStrings as $s) {
                 list($k, $v) = explode('=', $s);
                 $rrules[$k] = $v;
             }
             // Get frequency
             $frequency = $rrules['FREQ'];
             // Get Start timestamp
             $startTimestamp = $initialStart->getTimeStamp();
             if (isset($anEvent['DTEND'])) {
                 $endTimestamp = $initialEnd->getTimestamp();
             } else {
                 if (isset($anEvent['DURATION'])) {
                     $duration = end($anEvent['DURATION_array']);
                     $endTimestamp = date_create($anEvent['DTSTART']);
                     $endTimestamp->modify($duration->y . ' year');
                     $endTimestamp->modify($duration->m . ' month');
                     $endTimestamp->modify($duration->d . ' day');
                     $endTimestamp->modify($duration->h . ' hour');
                     $endTimestamp->modify($duration->i . ' minute');
                     $endTimestamp->modify($duration->s . ' second');
                     $endTimestamp = date_format($endTimestamp, 'U');
                 } else {
                     $endTimestamp = $anEvent['DTSTART_array'][2];
                 }
             }
             $eventTimestampOffset = $endTimestamp - $startTimestamp;
             // Get Interval
             $interval = isset($rrules['INTERVAL']) && $rrules['INTERVAL'] != '' ? $rrules['INTERVAL'] : 1;
             $dayNumber = null;
             $weekDay = null;
             if (in_array($frequency, array('MONTHLY', 'YEARLY')) && isset($rrules['BYDAY']) && $rrules['BYDAY'] != '') {
                 // Deal with BYDAY
                 $dayNumber = intval($rrules['BYDAY']);
                 if (empty($dayNumber)) {
                     // Returns 0 when no number defined in BYDAY
                     if (!isset($rrules['BYSETPOS'])) {
                         $dayNumber = 1;
                         // Set first as default
                     } else {
                         if (is_numeric($rrules['BYSETPOS'])) {
                             $dayNumber = $rrules['BYSETPOS'];
                         }
                     }
                 }
                 $dayNumber = $dayNumber == -1 ? 6 : $dayNumber;
                 // Override for our custom key (6 => 'last')
                 $weekDay = substr($rrules['BYDAY'], -2);
             }
             $untilDefault = date_create('now');
             $untilDefault->modify($this->defaultSpan . ' year');
             $untilDefault->setTime(23, 59, 59);
             // End of the day
             if (isset($rrules['UNTIL'])) {
                 // Get Until
                 $until = strtotime($rrules['UNTIL']);
             } else {
                 if (isset($rrules['COUNT'])) {
                     $countOrig = is_numeric($rrules['COUNT']) && $rrules['COUNT'] > 1 ? $rrules['COUNT'] : 0;
                     $count = $countOrig - 1;
                     // Remove one to exclude the occurrence that initialises the rule
                     $count += $count > 0 ? $count * ($interval - 1) : 0;
                     $countNb = 1;
                     $offset = "+{$count} " . $this->frequencyConversion[$frequency];
                     $until = strtotime($offset, $startTimestamp);
                     if (in_array($frequency, array('MONTHLY', 'YEARLY')) && isset($rrules['BYDAY']) && $rrules['BYDAY'] != '') {
                         $dtstart = date_create($anEvent['DTSTART']);
                         for ($i = 1; $i <= $count; $i++) {
                             $dtstartClone = clone $dtstart;
                             $dtstartClone->modify('next ' . $this->frequencyConversion[$frequency]);
                             $offset = "{$this->dayOrdinals[$dayNumber]} {$this->weekdays[$weekDay]} of " . $dtstartClone->format('F Y H:i:01');
                             $dtstart->modify($offset);
                         }
                         /**
                          * Jumping X months forwards doesn't mean
                          * the end date will fall on the same day defined in BYDAY
                          * Use the largest of these to ensure we are going far enough
                          * in the future to capture our final end day
                          */
                         $until = max($until, $dtstart->format('U'));
                     }
                     unset($offset);
                 } else {
                     $until = $untilDefault->getTimestamp();
                 }
             }
             if (!isset($anEvent['EXDATE_array'])) {
                 $anEvent['EXDATE_array'][1] = array();
             }
             // Decide how often to add events and do so
             switch ($frequency) {
                 case 'DAILY':
                     // Simply add a new event each interval of days until UNTIL is reached
                     $offset = "+{$interval} day";
                     $recurringTimestamp = strtotime($offset, $startTimestamp);
                     while ($recurringTimestamp <= $until) {
                         $dayRecurringTimestamp = $recurringTimestamp;
                         // Adjust timezone from initial event
                         $recurringTimeZone = \DateTime::createFromFormat('U', $dayRecurringTimestamp);
                         $timezoneOffset = $initialStart->getTimezone()->getOffset($recurringTimeZone);
                         $dayRecurringTimestamp += $timezoneOffset != $initialStartOffset ? $initialStartOffset - $timezoneOffset : 0;
                         // Add event
                         $anEvent['DTSTART'] = gmdate(self::DATE_TIME_FORMAT, $dayRecurringTimestamp) . 'Z';
                         $anEvent['DTSTART_array'] = array(array(), $anEvent['DTSTART'], $dayRecurringTimestamp);
                         $anEvent['DTEND_array'] = $anEvent['DTSTART_array'];
                         $anEvent['DTEND_array'][2] += $eventTimestampOffset;
                         $anEvent['DTEND'] = gmdate(self::DATE_TIME_FORMAT, $anEvent['DTEND_array'][2]) . 'Z';
                         $anEvent['DTEND_array'][1] = $anEvent['DTEND'];
                         $searchDate = $anEvent['DTSTART'];
                         $isExcluded = array_filter($anEvent['EXDATE_array'][1], function ($val) use($searchDate) {
                             return is_string($val) && strpos($searchDate, $val) === 0;
                         });
                         if (isset($this->alteredRecurrenceInstances[$anEvent['UID']]) && in_array($dayRecurringTimestamp, $this->alteredRecurrenceInstances[$anEvent['UID']])) {
                             $isExcluded = true;
                         }
                         if (!$isExcluded) {
                             $events[] = $anEvent;
                             $this->eventCount++;
                             // If RRULE[COUNT] is reached then break
                             if (isset($rrules['COUNT'])) {
                                 $countNb++;
                                 if ($countNb >= $countOrig) {
                                     break 2;
                                 }
                             }
                         }
                         // Move forwards
                         $recurringTimestamp = strtotime($offset, $recurringTimestamp);
                     }
                     break;
                 case 'WEEKLY':
                     // Create offset
                     $offset = "+{$interval} week";
                     // Use RRULE['WKST'] setting or a default week start (UK = SU, Europe = MO)
                     $weeks = array('SA' => array('SA', 'SU', 'MO', 'TU', 'WE', 'TH', 'FR'), 'SU' => array('SU', 'MO', 'TU', 'WE', 'TH', 'FR', 'SA'), 'MO' => array('MO', 'TU', 'WE', 'TH', 'FR', 'SA', 'SU'));
                     $wkst = isset($rrules['WKST']) && in_array($rrules['WKST'], array('SA', 'SU', 'MO')) ? $rrules['WKST'] : $this->defaultWeekStart;
                     $aWeek = $weeks[$wkst];
                     $days = array('SA' => 'Saturday', 'SU' => 'Sunday', 'MO' => 'Monday');
                     // Build list of days of week to add events
                     $weekdays = $aWeek;
                     if (isset($rrules['BYDAY']) && $rrules['BYDAY'] != '') {
                         $bydays = explode(',', $rrules['BYDAY']);
                     } else {
                         $findDay = $weekdays[gmdate('w', $startTimestamp)];
                         $bydays = array($findDay);
                     }
                     // Get timestamp of first day of start week
                     $weekRecurringTimestamp = gmdate('w', $startTimestamp) == 0 ? $startTimestamp : strtotime("last {$days[$wkst]} " . gmdate('H:i:s\\z', $startTimestamp), $startTimestamp);
                     // Step through weeks
                     while ($weekRecurringTimestamp <= $until) {
                         $dayRecurringTimestamp = $weekRecurringTimestamp;
                         // Adjust timezone from initial event
                         $dayRecurringTimeZone = \DateTime::createFromFormat('U', $dayRecurringTimestamp, new \DateTimeZone('UTC'));
                         $timezoneOffset = $initialStart->getTimezone()->getOffset($dayRecurringTimeZone);
                         $dayRecurringTimestamp += $timezoneOffset != $initialStartOffset ? $initialStartOffset - $timezoneOffset : 0;
                         foreach ($weekdays as $day) {
                             // Check if day should be added
                             if (in_array($day, $bydays) && $dayRecurringTimestamp > $startTimestamp && $dayRecurringTimestamp <= $until) {
                                 // Add event
                                 $anEvent['DTSTART'] = gmdate(self::DATE_TIME_FORMAT, $dayRecurringTimestamp) . 'Z';
                                 $anEvent['DTSTART_array'] = array(array(), $anEvent['DTSTART'], $dayRecurringTimestamp);
                                 $anEvent['DTEND_array'] = $anEvent['DTSTART_array'];
                                 $anEvent['DTEND_array'][2] += $eventTimestampOffset;
                                 $anEvent['DTEND'] = gmdate(self::DATE_TIME_FORMAT, $anEvent['DTEND_array'][2]) . 'Z';
                                 $anEvent['DTEND_array'][1] = $anEvent['DTEND'];
                                 $searchDate = $anEvent['DTSTART'];
                                 $isExcluded = array_filter($anEvent['EXDATE_array'][1], function ($val) use($searchDate) {
                                     return is_string($val) && strpos($searchDate, $val) === 0;
                                 });
                                 if (isset($this->alteredRecurrenceInstances[$anEvent['UID']]) && in_array($dayRecurringTimestamp, $this->alteredRecurrenceInstances[$anEvent['UID']])) {
                                     $isExcluded = true;
                                 }
                                 if (!$isExcluded) {
                                     $events[] = $anEvent;
                                     $this->eventCount++;
                                     // If RRULE[COUNT] is reached then break
                                     if (isset($rrules['COUNT'])) {
                                         $countNb++;
                                         if ($countNb >= $countOrig) {
                                             break 2;
                                         }
                                     }
                                 }
                             }
                             // Move forwards a day
                             $dayRecurringTimestamp = strtotime('+1 day', $dayRecurringTimestamp);
                         }
                         // Move forwards $interval weeks
                         $weekRecurringTimestamp = strtotime($offset, $weekRecurringTimestamp);
                     }
                     break;
                 case 'MONTHLY':
                     // Create offset
                     $offset = "+{$interval} month";
                     $recurringTimestamp = strtotime($offset, $startTimestamp);
                     if (isset($rrules['BYMONTHDAY']) && $rrules['BYMONTHDAY'] != '') {
                         // Deal with BYMONTHDAY
                         $monthdays = explode(',', $rrules['BYMONTHDAY']);
                         while ($recurringTimestamp <= $until) {
                             foreach ($monthdays as $key => $monthday) {
                                 if ($key === 0) {
                                     // Ensure original event conforms to monthday rule
                                     $events[0]['DTSTART'] = gmdate('Ym' . sprintf('%02d', $monthday) . '\\T' . self::TIME_FORMAT, strtotime($events[0]['DTSTART'])) . 'Z';
                                     $events[0]['DTEND'] = gmdate('Ym' . sprintf('%02d', $monthday) . '\\T' . self::TIME_FORMAT, strtotime($events[0]['DTEND'])) . 'Z';
                                     $events[0]['DTSTART_array'][1] = $events[0]['DTSTART'];
                                     $events[0]['DTSTART_array'][2] = $this->iCalDateToUnixTimestamp($events[0]['DTSTART']);
                                     $events[0]['DTEND_array'][1] = $events[0]['DTEND'];
                                     $events[0]['DTEND_array'][2] = $this->iCalDateToUnixTimestamp($events[0]['DTEND']);
                                     // Ensure recurring timestamp confirms to monthday rule
                                     $monthRecurringTimestamp = $this->iCalDateToUnixTimestamp(gmdate('Ym' . sprintf('%02d', $monthday) . '\\T' . self::TIME_FORMAT, $recurringTimestamp) . 'Z');
                                 }
                                 // Adjust timezone from initial event
                                 $recurringTimeZone = \DateTime::createFromFormat('U', $monthRecurringTimestamp);
                                 $timezoneOffset = $initialStart->getTimezone()->getOffset($recurringTimeZone);
                                 $monthRecurringTimestamp += $timezoneOffset != $initialStartOffset ? $initialStartOffset - $timezoneOffset : 0;
                                 // Add event
                                 $anEvent['DTSTART'] = gmdate('Ym' . sprintf('%02d', $monthday) . '\\T' . self::TIME_FORMAT, $monthRecurringTimestamp) . 'Z';
                                 $anEvent['DTSTART_array'] = array(array(), $anEvent['DTSTART'], $monthRecurringTimestamp);
                                 $anEvent['DTEND_array'] = $anEvent['DTSTART_array'];
                                 $anEvent['DTEND_array'][2] += $eventTimestampOffset;
                                 $anEvent['DTEND'] = gmdate(self::DATE_TIME_FORMAT, $anEvent['DTEND_array'][2]) . 'Z';
                                 $anEvent['DTEND_array'][1] = $anEvent['DTEND'];
                                 $searchDate = $anEvent['DTSTART'];
                                 $isExcluded = array_filter($anEvent['EXDATE_array'][1], function ($val) use($searchDate) {
                                     return is_string($val) && strpos($searchDate, $val) === 0;
                                 });
                                 if (isset($this->alteredRecurrenceInstances[$anEvent['UID']]) && in_array($monthRecurringTimestamp, $this->alteredRecurrenceInstances[$anEvent['UID']])) {
                                     $isExcluded = true;
                                 }
                                 if (!$isExcluded) {
                                     $events[] = $anEvent;
                                     $this->eventCount++;
                                     // If RRULE[COUNT] is reached then break
                                     if (isset($rrules['COUNT'])) {
                                         $countNb++;
                                         if ($countNb >= $countOrig) {
                                             break 2;
                                         }
                                     }
                                 }
                             }
                             // Move forwards
                             $recurringTimestamp = strtotime($offset, $recurringTimestamp);
                         }
                     } else {
                         if (isset($rrules['BYDAY']) && $rrules['BYDAY'] != '') {
                             while ($recurringTimestamp <= $until) {
                                 $monthRecurringTimestamp = $recurringTimestamp;
                                 // Adjust timezone from initial event
                                 $recurringTimeZone = \DateTime::createFromFormat('U', $monthRecurringTimestamp);
                                 $timezoneOffset = $initialStart->getTimezone()->getOffset($recurringTimeZone);
                                 $monthRecurringTimestamp += $timezoneOffset != $initialStartOffset ? $initialStartOffset - $timezoneOffset : 0;
                                 $eventStartDesc = "{$this->dayOrdinals[$dayNumber]} {$this->weekdays[$weekDay]} of " . gmdate('F Y H:i:s', $monthRecurringTimestamp);
                                 $eventStartTimestamp = strtotime($eventStartDesc);
                                 // Prevent 5th day of a month from showing up on the next month
                                 // If BYDAY and the event falls outside the current month, skip the event
                                 $compareCurrentMonth = date('F', $monthRecurringTimestamp);
                                 $compareEventMonth = date('F', $eventStartTimestamp);
                                 if ($compareCurrentMonth != $compareEventMonth) {
                                     $monthRecurringTimestamp = strtotime($offset, $monthRecurringTimestamp);
                                     continue;
                                 }
                                 if ($eventStartTimestamp > $startTimestamp && $eventStartTimestamp < $until) {
                                     $anEvent['DTSTART'] = gmdate(self::DATE_TIME_FORMAT, $eventStartTimestamp) . 'Z';
                                     $anEvent['DTSTART_array'] = array(array(), $anEvent['DTSTART'], $eventStartTimestamp);
                                     $anEvent['DTEND_array'] = $anEvent['DTSTART_array'];
                                     $anEvent['DTEND_array'][2] += $eventTimestampOffset;
                                     $anEvent['DTEND'] = gmdate(self::DATE_TIME_FORMAT, $anEvent['DTEND_array'][2]) . 'Z';
                                     $anEvent['DTEND_array'][1] = $anEvent['DTEND'];
                                     $searchDate = $anEvent['DTSTART'];
                                     $isExcluded = array_filter($anEvent['EXDATE_array'][1], function ($val) use($searchDate) {
                                         return is_string($val) && strpos($searchDate, $val) === 0;
                                     });
                                     if (isset($this->alteredRecurrenceInstances[$anEvent['UID']]) && in_array($monthRecurringTimestamp, $this->alteredRecurrenceInstances[$anEvent['UID']])) {
                                         $isExcluded = true;
                                     }
                                     if (!$isExcluded) {
                                         $events[] = $anEvent;
                                         $this->eventCount++;
                                         // If RRULE[COUNT] is reached then break
                                         if (isset($rrules['COUNT'])) {
                                             $countNb++;
                                             if ($countNb >= $countOrig) {
                                                 break 2;
                                             }
                                         }
                                     }
                                 }
                                 // Move forwards
                                 $recurringTimestamp = strtotime($offset, $recurringTimestamp);
                             }
                         }
                     }
                     break;
                 case 'YEARLY':
                     // Create offset
                     $offset = "+{$interval} year";
                     $recurringTimestamp = strtotime($offset, $startTimestamp);
                     // Check if BYDAY rule exists
                     if (isset($rrules['BYDAY']) && $rrules['BYDAY'] != '') {
                         while ($recurringTimestamp <= $until) {
                             $yearRecurringTimestamp = $recurringTimestamp;
                             // Adjust timezone from initial event
                             $recurringTimeZone = \DateTime::createFromFormat('U', $yearRecurringTimestamp);
                             $timezoneOffset = $initialStart->getTimezone()->getOffset($recurringTimeZone);
                             $yearRecurringTimestamp += $timezoneOffset != $initialStartOffset ? $initialStartOffset - $timezoneOffset : 0;
                             $eventStartDesc = "{$this->dayOrdinals[$dayNumber]} {$this->weekdays[$weekDay]}" . " of {$this->monthNames[$rrules['BYMONTH']]} " . gmdate('Y H:i:s', $yearRecurringTimestamp);
                             $eventStartTimestamp = strtotime($eventStartDesc);
                             if ($eventStartTimestamp > $startTimestamp && $eventStartTimestamp < $until) {
                                 $anEvent['DTSTART'] = gmdate(self::DATE_TIME_FORMAT, $eventStartTimestamp) . 'Z';
                                 $anEvent['DTSTART_array'] = array(array(), $anEvent['DTSTART'], $eventStartTimestamp);
                                 $anEvent['DTEND_array'] = $anEvent['DTSTART_array'];
                                 $anEvent['DTEND_array'][2] += $eventTimestampOffset;
                                 $anEvent['DTEND'] = gmdate(self::DATE_TIME_FORMAT, $anEvent['DTEND_array'][2]) . 'Z';
                                 $anEvent['DTEND_array'][1] = $anEvent['DTEND'];
                                 $searchDate = $anEvent['DTSTART'];
                                 $isExcluded = array_filter($anEvent['EXDATE_array'][1], function ($val) use($searchDate) {
                                     return is_string($val) && strpos($searchDate, $val) === 0;
                                 });
                                 if (isset($this->alteredRecurrenceInstances[$anEvent['UID']]) && in_array($yearRecurringTimestamp, $this->alteredRecurrenceInstances[$anEvent['UID']])) {
                                     $isExcluded = true;
                                 }
                                 if (!$isExcluded) {
                                     $events[] = $anEvent;
                                     $this->eventCount++;
                                     // If RRULE[COUNT] is reached then break
                                     if (isset($rrules['COUNT'])) {
                                         $countNb++;
                                         if ($countNb >= $countOrig) {
                                             break 2;
                                         }
                                     }
                                 }
                             }
                             // Move forwards
                             $recurringTimestamp = strtotime($offset, $recurringTimestamp);
                         }
                     } else {
                         $day = gmdate('d', $startTimestamp);
                         // Step through years
                         while ($recurringTimestamp <= $until) {
                             $yearRecurringTimestamp = $recurringTimestamp;
                             // Adjust timezone from initial event
                             $recurringTimeZone = \DateTime::createFromFormat('U', $yearRecurringTimestamp);
                             $timezoneOffset = $initialStart->getTimezone()->getOffset($recurringTimeZone);
                             $yearRecurringTimestamp += $timezoneOffset != $initialStartOffset ? $initialStartOffset - $timezoneOffset : 0;
                             // Add specific month dates
                             if (isset($rrules['BYMONTH']) && $rrules['BYMONTH'] != '') {
                                 $eventStartDesc = "{$day} {$this->monthNames[$rrules['BYMONTH']]} " . gmdate('Y H:i:s', $yearRecurringTimestamp);
                             } else {
                                 $eventStartDesc = $day . gmdate('F Y H:i:s', $yearRecurringTimestamp);
                             }
                             $eventStartTimestamp = strtotime($eventStartDesc);
                             if ($eventStartTimestamp > $startTimestamp && $eventStartTimestamp < $until) {
                                 $anEvent['DTSTART'] = gmdate(self::DATE_TIME_FORMAT, $eventStartTimestamp) . 'Z';
                                 $anEvent['DTSTART_array'] = array(array(), $anEvent['DTSTART'], $eventStartTimestamp);
                                 $anEvent['DTEND_array'] = $anEvent['DTSTART_array'];
                                 $anEvent['DTEND_array'][2] += $eventTimestampOffset;
                                 $anEvent['DTEND'] = gmdate(self::DATE_TIME_FORMAT, $anEvent['DTEND_array'][2]) . 'Z';
                                 $anEvent['DTEND_array'][1] = $anEvent['DTEND'];
                                 $searchDate = $anEvent['DTSTART'];
                                 $isExcluded = array_filter($anEvent['EXDATE_array'][1], function ($val) use($searchDate) {
                                     return is_string($val) && strpos($searchDate, $val) === 0;
                                 });
                                 if (isset($this->alteredRecurrenceInstances[$anEvent['UID']]) && in_array($yearRecurringTimestamp, $this->alteredRecurrenceInstances[$anEvent['UID']])) {
                                     $isExcluded = true;
                                 }
                                 if (!$isExcluded) {
                                     $events[] = $anEvent;
                                     $this->eventCount++;
                                     // If RRULE[COUNT] is reached then break
                                     if (isset($rrules['COUNT'])) {
                                         $countNb++;
                                         if ($countNb >= $countOrig) {
                                             break 2;
                                         }
                                     }
                                 }
                             }
                             // Move forwards
                             $recurringTimestamp = strtotime($offset, $recurringTimestamp);
                         }
                     }
                     break;
                     $events = isset($countOrig) && sizeof($events) > $countOrig ? array_slice($events, 0, $countOrig) : $events;
                     // Ensure we abide by COUNT if defined
             }
         }
     }
     $this->cal['VEVENT'] = $events;
 }