/** * * @return type */ public function getFilterImap() { $format = "d-M-Y"; // prepare value $value = (array) $this->_getDateValues($this->_operator, $this->_value); $timezone = Tinebase_Helper::array_value('timezone', $this->_options); $timezone = $timezone ? $timezone : Tinebase_Core::getUserTimezone(); foreach ($value as &$date) { $date = new Tinebase_DateTime($date); // should be in user timezone $date->setTimezone(new DateTimeZone($timezone)); } switch ($this->_operator) { case 'within': case 'inweek': $value[1]->add(new DateInterval('P1D')); // before is not inclusive, so we have to add a day $return = "SINCE {$value[0]->format($format)} BEFORE {$value[1]->format($format)}"; break; case 'before': $return = "BEFORE {$value[0]->format($format)}"; break; case 'after': $return = "SINCE {$value[0]->format($format)}"; break; case 'equals': $return = "ON {$value[0]->format($format)}"; } return $return; }
/** * test search events */ public function testSearchEvents() { $from = '2009-04-03 00:00:00'; $until = '2009-04-10 23:59:59'; $events = new Tinebase_Record_RecordSet('Calendar_Model_Event', array(array('dtstart' => '2009-04-02 22:00:00', 'dtend' => '2009-04-02 23:59:59', 'summary' => 'non recur event ending before search period => should _not_ be found', 'attendee' => $this->_getAttendee(), 'container_id' => $this->_getTestCalendar()->getId(), 'organizer' => Tinebase_Core::getUser()->getId(), 'uid' => Calendar_Model_Event::generateUID(), Tinebase_Model_Grants::GRANT_READ => true), array('dtstart' => '2009-04-02 23:30:00', 'dtend' => '2009-04-03 00:30:00', 'summary' => 'non recur event ending within search period => should be found', 'attendee' => $this->_getAttendee(), 'container_id' => $this->_getTestCalendar()->getId(), 'organizer' => Tinebase_Core::getUser()->getId(), 'uid' => Calendar_Model_Event::generateUID(), Tinebase_Model_Grants::GRANT_READ => true), array('dtstart' => '2009-04-06 12:00:00', 'dtend' => '2009-04-07 12:00:00', 'summary' => 'non recur event completly within search period => should be found', 'attendee' => $this->_getAttendee(), 'container_id' => $this->_getTestCalendar()->getId(), 'organizer' => Tinebase_Core::getUser()->getId(), 'uid' => Calendar_Model_Event::generateUID(), Tinebase_Model_Grants::GRANT_READ => true), array('dtstart' => '2009-04-10 23:30:00', 'dtend' => '2009-04-11 00:30:00', 'summary' => 'non recur event starting within search period => should be found', 'attendee' => $this->_getAttendee(), 'container_id' => $this->_getTestCalendar()->getId(), 'organizer' => Tinebase_Core::getUser()->getId(), 'uid' => Calendar_Model_Event::generateUID(), Tinebase_Model_Grants::GRANT_READ => true), array('dtstart' => '2009-04-11 00:00:00', 'dtend' => '2009-04-11 02:00:00', 'summary' => 'non recur event starting after search period => should _not_ be found', 'attendee' => $this->_getAttendee(), 'container_id' => $this->_getTestCalendar()->getId(), 'organizer' => Tinebase_Core::getUser()->getId(), 'uid' => Calendar_Model_Event::generateUID(), Tinebase_Model_Grants::GRANT_READ => true), array('dtstart' => '2009-03-27 22:00:00', 'dtend' => '2009-03-27 23:59:59', 'rrule' => 'FREQ=DAILY;INTERVAL=1;UNTIL=2009-04-02 23:59:59', 'summary' => 'recur event ending before search period => should _not_ be found', 'attendee' => $this->_getAttendee(), 'container_id' => $this->_getTestCalendar()->getId(), 'organizer' => Tinebase_Core::getUser()->getId(), 'uid' => Calendar_Model_Event::generateUID(), 'rrule_until' => '2009-04-02 23:59:59', Tinebase_Model_Grants::GRANT_READ => true, 'originator_tz' => Tinebase_Core::getUserTimezone()), array('dtstart' => '2009-03-27 22:00:00', 'dtend' => '2009-03-27 23:59:59', 'rrule' => 'FREQ=DAILY;INTERVAL=1;UNTIL=2009-04-05 23:59:59', 'summary' => 'recur event ending within search period => should be found', 'attendee' => $this->_getAttendee(), 'container_id' => $this->_getTestCalendar()->getId(), 'organizer' => Tinebase_Core::getUser()->getId(), 'uid' => Calendar_Model_Event::generateUID(), 'rrule_until' => '2009-04-05 23:59:59', Tinebase_Model_Grants::GRANT_READ => true, 'originator_tz' => Tinebase_Core::getUserTimezone()), array('dtstart' => '2009-04-03 22:00:00', 'dtend' => '2009-04-03 23:59:59', 'rrule' => 'FREQ=DAILY;INTERVAL=1;UNTIL=2009-04-06 23:59:59', 'summary' => 'recur event completly within search period => should be found', 'attendee' => $this->_getAttendee(), 'container_id' => $this->_getTestCalendar()->getId(), 'organizer' => Tinebase_Core::getUser()->getId(), 'uid' => Calendar_Model_Event::generateUID(), 'rrule_until' => '2009-04-06 23:59:59', Tinebase_Model_Grants::GRANT_READ => true, 'originator_tz' => Tinebase_Core::getUserTimezone()), array('dtstart' => '2009-04-03 22:00:00', 'dtend' => '2009-04-03 23:59:59', 'rrule' => 'FREQ=DAILY;INTERVAL=1;UNTIL=2009-04-12 23:59:59', 'summary' => 'recur event starting within search period => should be found', 'attendee' => $this->_getAttendee(), 'container_id' => $this->_getTestCalendar()->getId(), 'organizer' => Tinebase_Core::getUser()->getId(), 'uid' => Calendar_Model_Event::generateUID(), 'rrule_until' => '2009-04-12 23:59:59', Tinebase_Model_Grants::GRANT_READ => true, 'originator_tz' => Tinebase_Core::getUserTimezone()), array('dtstart' => '2009-04-11 00:00:00', 'dtend' => '2009-04-11 02:00:00', 'rrule' => 'FREQ=DAILY;INTERVAL=1;UNTIL=2009-04-15 02:00:00', 'summary' => 'recur event starting after search period => should _not_ be found', 'attendee' => $this->_getAttendee(), 'container_id' => $this->_getTestCalendar()->getId(), 'organizer' => Tinebase_Core::getUser()->getId(), 'uid' => Calendar_Model_Event::generateUID(), 'rrule_until' => '2009-04-15 02:00:00', Tinebase_Model_Grants::GRANT_READ => true, 'originator_tz' => Tinebase_Core::getUserTimezone()))); foreach ($events as $event) { $persistentEvent = $this->_backend->create($event); $event->attendee->cal_event_id = $persistentEvent->getId(); foreach ($event->attendee as $attender) { $this->_backend->createAttendee($attender); } } $filter = new Calendar_Model_EventFilter(array(array('field' => 'container_id', 'operator' => 'equals', 'value' => $this->_getTestCalendar()->getId()), array('field' => 'period', 'operator' => 'within', 'value' => array('from' => $from, 'until' => $until)))); $eventsFound = $this->_backend->search($filter, new Tinebase_Model_Pagination()); $eventsFoundIds = $eventsFound->getArrayOfIds(); foreach ($events as $event) { $eventId = $event->getId(); if (strpos($event->summary, '_not_') === false) { $this->assertTrue(in_array($eventId, $eventsFoundIds), 'The following event is missing in the search result :' . print_r($event->toArray(), true)); } else { $this->assertFalse(in_array($eventId, $eventsFoundIds), 'The following event is in the search result, but should not be :' . print_r($event->toArray(), true)); } } $expectedAttendee = $this->_getAttendee(); foreach ($eventsFound as $fetchedEvent) { $this->_assertAttendee($expectedAttendee, $fetchedEvent->attendee); } }
/** * add one record * * @param Tinebase_Record_Interface $_record * @return Tinebase_Record_Interface * @throws Tinebase_Exception_AccessDenied * @throws Tinebase_Exception_Record_Validation */ public function create(Tinebase_Record_Interface $_task) { $this->_handleCompleted($_task); $_task->originator_tz = $_task->originator_tz ? $_task->originator_tz : Tinebase_Core::getUserTimezone(); $task = parent::create($_task); $this->_addAutomaticAlarms($task); return $task; }
/** * returns the interval of this billable * * @return array */ public function getInterval() { $startDate = clone new Tinebase_DateTime($this->start_date); $startDate->setTimezone(Tinebase_Core::getUserTimezone()); $startDate->setDate($startDate->format('Y'), $startDate->format('n'), 1); $startDate->setTime(0, 0, 0); $endDate = clone $startDate; $endDate->addMonth(1)->subSecond(1); return array($startDate, $endDate); }
/** * testTimezoneConversion */ public function testTimezoneConversion() { $exampleFilterData = self::getPersistentFilterData(); $savedFilterData = $this->testSaveFilter($exampleFilterData); $testUserTimezone = Tinebase_Core::getUserTimezone(); Tinebase_Core::set(Tinebase_Core::USERTIMEZONE, $testUserTimezone !== 'US/Pacific' ? 'US/Pacific' : 'UTC'); $originalDueDateFilter = $this->_getFilter('due', $exampleFilterData); $convertedDueDataFilter = $this->_getFilter('due', $this->_uit->getPersistentFilter($savedFilterData['id'])); Tinebase_Core::set(Tinebase_Core::USERTIMEZONE, $testUserTimezone); $this->assertNotEquals($originalDueDateFilter['value'], $convertedDueDataFilter['value']); }
/** * testUpdateEvent */ public function testUpdateEvent() { $persistentEvent = $this->testCreateEvent(); $currentTz = Tinebase_Core::getUserTimezone(); Tinebase_Core::set(Tinebase_Core::USERTIMEZONE, 'farfaraway'); $persistentEvent->summary = 'Lunchtime'; $updatedEvent = $this->_controller->update($persistentEvent); $this->assertEquals($persistentEvent->summary, $updatedEvent->summary); $this->assertEquals($currentTz, $updatedEvent->originator_tz, 'originator_tz must not be touchet if dtsart is not updatet!'); $updatedEvent->dtstart->addHour(1); $updatedEvent->dtend->addHour(1); $secondUpdatedEvent = $this->_controller->update($updatedEvent); $this->assertEquals(Tinebase_Core::getUserTimezone(), $secondUpdatedEvent->originator_tz, 'originator_tz must be adopted if dtsart is updatet!'); Tinebase_Core::set(Tinebase_Core::USERTIMEZONE, $currentTz); }
/** * calculates the date filter values * * @param string $_operator * @param string $_value * @param string $_dateFormat * @return array|string date value */ protected function _getDateValues($_operator, $_value) { if ($_operator === 'within') { // get beginning / end date and add 00:00:00 / 23:59:59 date_default_timezone_set((isset($this->_options['timezone']) || array_key_exists('timezone', $this->_options)) && !empty($this->_options['timezone']) ? $this->_options['timezone'] : Tinebase_Core::getUserTimezone()); $value = parent::_getDateValues($_operator, $_value); $value[0] .= ' 00:00:00'; $value[1] .= ' 23:59:59'; date_default_timezone_set('UTC'); // convert to utc $value[0] = $this->_convertStringToUTC($value[0]); $value[1] = $this->_convertStringToUTC($value[1]); } else { $value = $_value instanceof DateTime ? $_value->toString(Tinebase_Record_Abstract::ISO8601LONG) : $_value; } return $value; }
/** * create lead pdf * * @param Crm_Model_Lead $_lead lead data * * @return string the pdf */ public function generate(Crm_Model_Lead $_lead, $_pageNumber = 0) { $locale = Tinebase_Core::get('locale'); $translate = Tinebase_Translation::getTranslation('Crm'); // set user timezone $_lead->setTimezone(Tinebase_Core::getUserTimezone()); /*********************** build data array ***************************/ $record = $this->getRecord($_lead, $locale, $translate); /******************* build title / subtitle / description ***********/ $title = $_lead->lead_name; $subtitle = ""; $description = $_lead->description; $titleIcon = "/images/oxygen/32x32/actions/datashowchart.png"; /*********************** add linked objects *************************/ $linkedObjects = $this->getLinkedObjects($_lead, $locale, $translate); $tags = $_lead->tags instanceof Tinebase_Record_RecordSet ? $_lead->tags->toArray() : array(); /***************************** generate pdf now! ********************/ parent::generatePdf($record, $title, $subtitle, $tags, $description, $titleIcon, NULL, $linkedObjects, FALSE); }
/** * get sieve vacation object * * @return Felamimail_Sieve_Vacation */ public function getFSV() { $fsv = new Felamimail_Sieve_Vacation(); $fsv->setEnabled($this->enabled)->setDays($this->days && (int) $this->days > 0 ? (int) $this->days : 7)->setSubject($this->subject)->setFrom($this->from)->setMime($this->mime)->setReason($this->reason)->setDateEnabled($this->date_enabled); $this->setTimezone(Tinebase_Core::getUserTimezone()); if ($this->start_date instanceof Tinebase_DateTime) { $fsv->setStartdate($this->start_date->format('Y-m-d')); } if ($this->end_date instanceof Tinebase_DateTime) { $fsv->setEnddate($this->end_date->format('Y-m-d')); } $this->setTimezone('UTC'); if (is_array($this->addresses)) { foreach ($this->addresses as $address) { $fsv->addAddress($address); } } return $fsv; }
/** * send one message through smtp * * @param Expressomail_Model_Message $_message * @return Expressomail_Model_Message */ public function sendMessage(Expressomail_Model_Message $_message) { if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) { Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . ' Sending message with subject ' . $_message->subject . ' to ' . print_r($_message->to, TRUE)); } if (Tinebase_Core::isLogLevel(Zend_Log::TRACE)) { Tinebase_Core::getLogger()->trace(__METHOD__ . '::' . __LINE__ . ' ' . print_r($_message->toArray(), TRUE)); } // increase execution time (sending message with attachments can take a long time) $oldMaxExcecutionTime = Tinebase_Core::setExecutionLifeTime(300); // 5 minutes $account = Expressomail_Controller_Account::getInstance()->get($_message->account_id); $this->_resolveOriginalMessage($_message); $mail = $this->createMailForSending($_message, $account); date_default_timezone_set(Tinebase_Core::getUserTimezone()); //fetch date header to use GMT $this->_sendMailViaTransport($mail, $account, $_message, true); // get an array with all recipients $recipients = $this->_getRecipients($_message); $nonPrivateRecipients = array_merge($recipients['to'], $recipients['cc']); $allRecipients = array_merge($recipients['bcc'], $nonPrivateRecipients); $config = Tinebase_Core::getConfig(); $maxRecipients = Expressomail_Config::getInstance()->get(Expressomail_Config::MAX_CONTACT_ADD_TO_UNKNOWN); if (isset($config->email->maxContactAddToUnknown)) { $maxRecipients = $config->email->maxContactAddToUnknown; } if (count($allRecipients) <= $maxRecipients && $_message->add_contacts) { Tinebase_Core::getLogger()->debug(__METHOD__ . ' Starting search and import of ' . count($allRecipients) . ' contacts'); $_message->added_contacts = $this->_saveUnknownContacts($account->user_id, $allRecipients); Tinebase_Core::getLogger()->debug(__METHOD__ . ' Search and import completed, ' . $_message->added_contacts . ' where added'); } if ($_message->note) { // save note to contacts $this->_addEmailNote($nonPrivateRecipients, $_message->subject, $_message->getPlainTextBody()); } // reset max execution time to old value Tinebase_Core::setExecutionLifeTime($oldMaxExcecutionTime); $this->removeTempFiles($_message); return $_message; }
/** * prepares an iMIP (RFC 6047) Message * * @param array $iMIP * @return array prepared iMIP part */ public function iMIPPrepare($iMIP) { $iMIPMessage = $iMIP instanceof Calendar_Model_iMIP ? $iMIP : new Calendar_Model_iMIP($iMIP); $iMIPFrontend = new Calendar_Frontend_iMIP(); $iMIPMessage->preconditionsChecked = FALSE; $iMIPFrontend->prepareComponent($iMIPMessage); $iMIPMessage->setTimezone(Tinebase_Core::getUserTimezone()); return $iMIPMessage->toArray(); }
/** <<<<<<< HEAD * @see: https://forge.tine20.org/mantisbt/view.php?id=10122 */ public function testAlternatingContracts() { $date = Tinebase_DateTime::now()->setDate(2014, 1, 1)->setTimezone(Tinebase_Core::getUserTimezone())->setTime(0, 0, 0); $employee = $this->_getEmployee('unittest'); $employee->employment_begin = clone $date; $contract1 = $this->_getContract(); $contract1->start_date = clone $date; // 1.1.2014 $date->addMonth(7)->subDay(1); $contract1->end_date = clone $date; // 31.7.2014 $contract1->workingtime_json = '{"days": [8,8,8,8,8,0,0]}'; $contract1->vacation_days = 27; $date->addDay(1); // 1.8.2014 $contract2 = $this->_getContract(); $contract2->start_date = clone $date; $contract2->workingtime_json = '{"days": [8,8,8,8,8,0,0]}'; $contract2->vacation_days = 30; $recordData = $employee->toArray(); $recordData['contracts'] = array($contract1->toArray(), $contract2->toArray()); $recordData = $this->_json->saveEmployee($recordData); $recordData['vacation'] = array(array()); $res = $this->_json->searchAccounts(array(array('field' => 'year', 'operator' => 'equals', 'value' => '2014')), array()); $account = $res['results'][0]; $date->subDay(1); // 31.7.2014 $extraFreeTime = HumanResources_Controller_ExtraFreeTime::getInstance()->create(new HumanResources_Model_ExtraFreeTime(array('account_id' => $account['id'], 'days' => 4, 'expires' => clone $date, 'type' => 'payed'))); $res = $this->_json->getFeastAndFreeDays($recordData['id'], 2014); // at this point, vacation days are not created, so the extra freetime is expired $this->assertEquals(28, $res['results']['remainingVacation']); // create vacation days $day = Tinebase_DateTime::now()->setDate(2014, 1, 2)->setTimezone(Tinebase_Core::getUserTimezone())->setTime(0, 0, 0); $newFreeTime = array('account_id' => $account['id'], 'employee_id' => $recordData['id'], 'type' => 'vacation', 'status' => 'ACCEPTED', 'firstday_date' => $day->toString()); $newFreeTime['freedays'] = array(array('duration' => '1', 'date' => $day->toString()), array('duration' => '1', 'date' => $day->addDay(1)->toString())); $newFreeTime['days_count'] = 2; $newFreeTime['lastday_date'] = $day->toString(); $this->_json->saveFreeTime($newFreeTime); // create vacation days $day = Tinebase_DateTime::now()->setDate(2014, 6, 10)->setTimezone(Tinebase_Core::getUserTimezone())->setTime(0, 0, 0); $newFreeTime = array('account_id' => $account['id'], 'employee_id' => $recordData['id'], 'type' => 'vacation', 'status' => 'ACCEPTED', 'firstday_date' => $day->toString()); $newFreeTime['freedays'] = array(array('duration' => '1', 'date' => $day->toString()), array('duration' => '1', 'date' => $day->addDay(1)->toString()), array('duration' => '1', 'date' => $day->addDay(1)->toString()), array('duration' => '1', 'date' => $day->addDay(1)->toString())); $newFreeTime['days_count'] = 4; $newFreeTime['lastday_date'] = $day->toString(); $this->_json->saveFreeTime($newFreeTime); // create vacation days $day = Tinebase_DateTime::now()->setDate(2014, 7, 28)->setTimezone(Tinebase_Core::getUserTimezone())->setTime(0, 0, 0); $newFreeTime = array('account_id' => $account['id'], 'employee_id' => $recordData['id'], 'type' => 'vacation', 'status' => 'ACCEPTED', 'firstday_date' => $day->toString()); $newFreeTime['freedays'] = array(array('duration' => '1', 'date' => $day->toString()), array('duration' => '1', 'date' => $day->addDay(1)->toString()), array('duration' => '1', 'date' => $day->addDay(1)->toString()), array('duration' => '1', 'date' => $day->addDay(1)->toString()), array('duration' => '1', 'date' => $day->addDay(1)->toString())); $newFreeTime['days_count'] = 5; $newFreeTime['lastday_date'] = $day->toString(); $this->_json->saveFreeTime($newFreeTime); // create sickness days $day = Tinebase_DateTime::now()->setDate(2014, 1, 21)->setTimezone(Tinebase_Core::getUserTimezone())->setTime(0, 0, 0); $newFreeTime = array('account_id' => $account['id'], 'employee_id' => $recordData['id'], 'type' => 'sickness', 'status' => "EXCUSED", 'firstday_date' => $day->toString()); $newFreeTime['freedays'] = array(array('duration' => '1', 'date' => $day->toString()), array('duration' => '1', 'date' => $day->addDay(1)->toString()), array('duration' => '1', 'date' => $day->addDay(1)->toString()), array('duration' => '1', 'date' => $day->addDay(1)->toString())); $day->addDay(2); $newFreeTime['freedays'][] = array('duration' => '1', 'date' => $day->addDay(1)->toString()); $newFreeTime['freedays'][] = array('duration' => '1', 'date' => $day->addDay(1)->toString()); $newFreeTime['freedays'][] = array('duration' => '1', 'date' => $day->addDay(1)->toString()); $newFreeTime['freedays'][] = array('duration' => '1', 'date' => $day->addDay(1)->toString()); $newFreeTime['freedays'][] = array('duration' => '1', 'date' => $day->addDay(1)->toString()); $day->addDay(2); $newFreeTime['freedays'][] = array('duration' => '1', 'date' => $day->addDay(1)->toString()); $newFreeTime['freedays'][] = array('duration' => '1', 'date' => $day->addDay(1)->toString()); $newFreeTime['freedays'][] = array('duration' => '1', 'date' => $day->addDay(1)->toString()); $newFreeTime['freedays'][] = array('duration' => '1', 'date' => $day->addDay(1)->toString()); $newFreeTime['freedays'][] = array('duration' => '1', 'date' => $day->addDay(1)->toString()); $newFreeTime['days_count'] = 14; $newFreeTime['lastday_date'] = $day->toString(); $this->_json->saveFreeTime($newFreeTime); // create sickness days $day = Tinebase_DateTime::now()->setDate(2014, 1, 6)->setTimezone(Tinebase_Core::getUserTimezone())->setTime(0, 0, 0); $newFreeTime = array('account_id' => $account['id'], 'employee_id' => $recordData['id'], 'type' => 'sickness', 'status' => "UNEXCUSED", 'firstday_date' => $day->toString()); $newFreeTime['freedays'] = array(array('duration' => '1', 'date' => $day->toString())); $this->_json->saveFreeTime($newFreeTime); $res = $this->_json->getFeastAndFreeDays($recordData['id'], 2014); // at this point the extra freetime has been taken and is not expired // 28 + 4 - 11 = 21 $this->assertEquals(21, $res['results']['remainingVacation']); $account = $this->_json->getAccount($account['id']); $this->assertEquals(32, $account['possible_vacation_days']); $this->assertEquals(0, $account['expired_vacation_days']); $this->assertEquals(21, $account['remaining_vacation_days']); $this->assertEquals(11, $account['taken_vacation_days']); $this->assertEquals(14, $account['excused_sickness']); $this->assertEquals(1, $account['unexcused_sickness']); }
public function testInterval12LastAutobill() { $startDate = clone $this->_referenceDate; $startDate->subYear(1); $this->_createProducts(array(array('name' => 'bill yearly', 'description' => 'bill every year', 'price' => '1002', 'accountable' => 'Sales_Model_Product'))); $this->_createCustomers(1); $this->_createCostCenters(); $addressId = $this->_addressRecords->filter('customer_id', $this->_customerRecords->filter('name', 'Customer1')->getFirstRecord()->getId())->filter('type', 'billing')->getFirstRecord()->getId(); // this contract begins 6 months before the first invoice will be created $this->_createContracts(array(array('number' => 100, 'title' => 'MyContract', 'description' => 'unittest', 'container_id' => $this->_sharedContractsContainerId, 'billing_point' => 'begin', 'billing_address_id' => $addressId, 'interval' => 12, 'start_date' => $startDate, 'last_autobill' => $startDate, 'end_date' => NULL, 'products' => array(array('product_id' => $this->_productRecords->getByIndex(0)->getId(), 'quantity' => 1, 'interval' => 12, 'last_autobill' => $startDate))))); $startDate = clone $this->_referenceDate; $startDate->subMonth(1); $startDate = clone $this->_referenceDate; $startDate->addDay(5); $result = $this->_invoiceController->createAutoInvoices($startDate); $this->assertEquals(1, $result['created_count']); $invoices = $this->_invoiceController->getAll(); $firstInvoice = $invoices->getFirstRecord(); $this->assertEquals(1, $invoices->count()); $filter = new Sales_Model_InvoicePositionFilter(array()); $filter->addFilter(new Tinebase_Model_Filter_Text(array('field' => 'invoice_id', 'operator' => 'in', 'value' => $invoices->getArrayOfIds()))); $invoicePositions = Sales_Controller_InvoicePosition::getInstance()->search($filter); $this->assertEquals(12, $invoicePositions->count()); $contract = $this->_contractRecords->getFirstRecord(); $contract->setTimezone(Tinebase_Core::getUserTimezone()); $autobillDate = clone $this->_referenceDate; for ($i = 0; $i < 8; $i++) { $startDate->addDay(1); $result = $this->_invoiceController->createAutoInvoices($startDate); $this->assertEquals(0, $result['created_count']); } $productAggregate = Sales_Controller_ProductAggregate::getInstance()->getAll()->getFirstRecord(); $productAggregate->setTimezone(Tinebase_Core::getUserTimezone()); $this->assertEquals($autobillDate, $productAggregate->last_autobill); }
/** * (non-PHPdoc) * @see ActiveSync_Frontend_Abstract::toTineModel() */ public function toTineModel(Syncroton_Model_IEntry $data, $entry = null) { if ($entry instanceof Calendar_Model_Event) { $event = $entry; } else { $event = new Calendar_Model_Event(array(), true); } if ($data instanceof Syncroton_Model_Event) { $data->copyFieldsFromParent(); } // Update seq to entries seq to prevent concurrent update $event->seq = $entry['seq']; if (Tinebase_Core::isLogLevel(Zend_Log::TRACE)) { Tinebase_Core::getLogger()->trace(__METHOD__ . '::' . __LINE__ . " Event before mapping: " . print_r($event->toArray(), true)); } foreach ($this->_mapping as $syncrotonProperty => $tine20Property) { if (!isset($data->{$syncrotonProperty})) { if ($tine20Property === 'description' && $this->_device->devicetype == Syncroton_Model_Device::TYPE_IPHONE) { // @see #8230: added alarm to event on iOS 6.1 -> description removed // this should be removed when Tine 2.0 / Syncroton supports ghosted properties if (Tinebase_Core::isLogLevel(Zend_Log::TRACE)) { Tinebase_Core::getLogger()->trace(__METHOD__ . '::' . __LINE__ . ' Unsetting description'); } unset($event->{$tine20Property}); } else { if ($tine20Property === 'attendee' && $entry && $this->_device->devicetype === Syncroton_Model_Device::TYPE_IPHONE && $entry->container_id !== $this->_getDefaultContainerId()) { // keep attendees as the are / they were not sent to the device before } else { if (Tinebase_Core::isLogLevel(Zend_Log::TRACE)) { Tinebase_Core::getLogger()->trace(__METHOD__ . '::' . __LINE__ . ' Removing ' . $tine20Property); } $event->{$tine20Property} = null; } } continue; } switch ($tine20Property) { case 'alarms': // handled after switch statement break; case 'attendee': if ($entry && $this->_device->devicetype === Syncroton_Model_Device::TYPE_IPHONE && $entry->container_id !== $this->_getDefaultContainerId()) { // keep attendees as the are / they were not sent to the device before continue; } $newAttendees = array(); foreach ($data->{$syncrotonProperty} as $attendee) { if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) { Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . " attendee email " . $attendee->email); } if (isset($attendee->attendeeType) && (isset($this->_attendeeTypeMapping[$attendee->attendeeType]) || array_key_exists($attendee->attendeeType, $this->_attendeeTypeMapping))) { $role = $this->_attendeeTypeMapping[$attendee->attendeeType]; } else { $role = Calendar_Model_Attender::ROLE_REQUIRED; } // AttendeeStatus send only on repsonse if (preg_match('/(?P<firstName>\\S*) (?P<lastNameName>\\S*)/', $attendee->name, $matches)) { $firstName = $matches['firstName']; $lastName = $matches['lastNameName']; } else { $firstName = null; $lastName = $attendee->name; } // @todo handle resources $newAttendees[] = array('userType' => Calendar_Model_Attender::USERTYPE_USER, 'firstName' => $firstName, 'lastName' => $lastName, 'role' => $role, 'email' => $attendee->email); } Calendar_Model_Attender::emailsToAttendee($event, $newAttendees); break; case 'class': $event->{$tine20Property} = $data->{$syncrotonProperty} == 2 ? Calendar_Model_Event::CLASS_PRIVATE : Calendar_Model_Event::CLASS_PUBLIC; break; case 'exdate': // handle exceptions from recurrence $exdates = new Tinebase_Record_RecordSet('Calendar_Model_Event'); foreach ($data->{$syncrotonProperty} as $exception) { if ($exception->deleted == 0) { $eventException = $this->toTineModel($exception); $eventException->last_modified_time = new Tinebase_DateTime($this->_syncTimeStamp); $eventException->recurid = new Tinebase_DateTime($exception->exceptionStartTime); $eventException->is_deleted = false; } else { $eventException = new Calendar_Model_Event(array('recurid' => new Tinebase_DateTime($exception->exceptionStartTime), 'is_deleted' => true)); } $eventException->seq = $entry['seq']; $exdates->addRecord($eventException); } $event->{$tine20Property} = $exdates; break; case 'description': // @todo check $data->$fieldName->Type and convert to/from HTML if needed if ($data->{$syncrotonProperty} instanceof Syncroton_Model_EmailBody) { $event->{$tine20Property} = $data->{$syncrotonProperty}->data; } else { if (Tinebase_Core::isLogLevel(Zend_Log::TRACE)) { Tinebase_Core::getLogger()->trace(__METHOD__ . '::' . __LINE__ . ' Removing description.'); } $event->{$tine20Property} = null; } break; case 'rrule': // handle recurrence if ($data->{$syncrotonProperty} instanceof Syncroton_Model_EventRecurrence && isset($data->{$syncrotonProperty}->type)) { $rrule = new Calendar_Model_Rrule(); switch ($data->{$syncrotonProperty}->type) { case Syncroton_Model_EventRecurrence::TYPE_DAILY: $rrule->freq = Calendar_Model_Rrule::FREQ_DAILY; break; case Syncroton_Model_EventRecurrence::TYPE_WEEKLY: $rrule->freq = Calendar_Model_Rrule::FREQ_WEEKLY; $rrule->byday = $this->_convertBitMaskToDay($data->{$syncrotonProperty}->dayOfWeek); break; case Syncroton_Model_EventRecurrence::TYPE_MONTHLY: $rrule->freq = Calendar_Model_Rrule::FREQ_MONTHLY; $rrule->bymonthday = $data->{$syncrotonProperty}->dayOfMonth; break; case Syncroton_Model_EventRecurrence::TYPE_MONTHLY_DAYN: $rrule->freq = Calendar_Model_Rrule::FREQ_MONTHLY; $week = $data->{$syncrotonProperty}->weekOfMonth; $day = $data->{$syncrotonProperty}->dayOfWeek; $byDay = $week == 5 ? -1 : $week; $byDay .= $this->_convertBitMaskToDay($day); $rrule->byday = $byDay; break; case Syncroton_Model_EventRecurrence::TYPE_YEARLY: $rrule->freq = Calendar_Model_Rrule::FREQ_YEARLY; $rrule->bymonth = $data->{$syncrotonProperty}->monthOfYear; $rrule->bymonthday = $data->{$syncrotonProperty}->dayOfMonth; break; case Syncroton_Model_EventRecurrence::TYPE_YEARLY_DAYN: $rrule->freq = Calendar_Model_Rrule::FREQ_YEARLY; $rrule->bymonth = $data->{$syncrotonProperty}->monthOfYear; $week = $data->{$syncrotonProperty}->weekOfMonth; $day = $data->{$syncrotonProperty}->dayOfWeek; $byDay = $week == 5 ? -1 : $week; $byDay .= $this->_convertBitMaskToDay($day); $rrule->byday = $byDay; break; } $rrule->interval = isset($data->{$syncrotonProperty}->interval) ? $data->{$syncrotonProperty}->interval : 1; if (isset($data->{$syncrotonProperty}->occurrences)) { $rrule->count = $data->{$syncrotonProperty}->occurrences; $rrule->until = null; } else { if (isset($data->{$syncrotonProperty}->until)) { $rrule->count = null; $rrule->until = new Tinebase_DateTime($data->{$syncrotonProperty}->until); } else { $rrule->count = null; $rrule->until = null; } } $event->rrule = $rrule; } break; default: if ($data->{$syncrotonProperty} instanceof DateTime) { $event->{$tine20Property} = new Tinebase_DateTime($data->{$syncrotonProperty}); } else { $event->{$tine20Property} = $data->{$syncrotonProperty}; } break; } } // whole day events ends at 23:59:59 in Tine 2.0 but 00:00 the next day in AS if (isset($event->is_all_day_event) && $event->is_all_day_event == 1) { $event->dtend->subSecond(1); } // decode timezone data if (isset($data->timezone)) { $timeZoneConverter = ActiveSync_TimezoneConverter::getInstance(Tinebase_Core::getLogger(), Tinebase_Core::get(Tinebase_Core::CACHE)); try { $timezone = $timeZoneConverter->getTimezone($data->timezone, Tinebase_Core::getUserTimezone()); $event->originator_tz = $timezone; } catch (ActiveSync_TimezoneNotFoundException $e) { Tinebase_Core::getLogger()->crit(__METHOD__ . '::' . __LINE__ . " timezone data not found " . $data->timezone); $event->originator_tz = Tinebase_Core::getUserTimezone(); } if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) { Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . " timezone data " . $event->originator_tz); } } $this->_handleAlarms($data, $event); $this->_handleBusyStatus($data, $event); // event should be valid now $event->isValid(); if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) { Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . " eventData " . print_r($event->toArray(), true)); } return $event; }
/** * Test if updating a related record works * */ public function testSetRelationUpdateRelatedRecord() { $relations = $this->_object->getRelations($this->_crmId['model'], $this->_crmId['backend'], $this->_crmId['id']); $relatedContacts = $relations->filter('related_model', 'Addressbook_Model_Contact'); $relatedContacts->sort('related_model', 'ASC'); $relatedContacts[0]->related_record->note = "Testing to update from relation set"; // NOTE: At the moment we need to set timezone to users timzone, as related records come as arrays and don't get // their dates converted in the JSON frontends foreach ($relations as $relation) { $relation->setTimezone(Tinebase_Core::getUserTimezone()); $relation->related_record = $relation->related_record->toArray(); } $this->_object->setRelations($this->_crmId['model'], $this->_crmId['backend'], $this->_crmId['id'], $relations->toArray(), FALSE, TRUE); $updatedRelations = $this->_object->getRelations($this->_crmId['model'], $this->_crmId['backend'], $this->_crmId['id']); $updatedConacts = $updatedRelations->filter('related_model', 'Addressbook_Model_Contact'); $updatedConacts->sort('related_model', 'ASC'); $this->assertEquals("Testing to update from relation set", $updatedConacts[0]->related_record->note); }
/** * get datetime from sabredav datetime property (user TZ is fallback) * * @param Sabre\VObject\Property $dateTimeProperty * @param boolean $_useUserTZ * @return Tinebase_DateTime * * @todo try to guess some common timezones */ protected function _convertToTinebaseDateTime(\Sabre\VObject\Property $dateTimeProperty, $_useUserTZ = FALSE) { $defaultTimezone = date_default_timezone_get(); date_default_timezone_set((string) Tinebase_Core::getUserTimezone()); if ($dateTimeProperty instanceof Sabre\VObject\Property\ICalendar\DateTime) { $dateTime = $dateTimeProperty->getDateTime(); $tz = $_useUserTZ || isset($dateTimeProperty['VALUE']) && strtoupper($dateTimeProperty['VALUE']) == 'DATE' ? (string) Tinebase_Core::getUserTimezone() : $dateTime->getTimezone(); $result = new Tinebase_DateTime($dateTime->format(Tinebase_Record_Abstract::ISO8601LONG), $tz); } else { $result = new Tinebase_DateTime($dateTimeProperty->getValue()); } date_default_timezone_set($defaultTimezone); return $result; }
/** * the constructor * */ public function __construct() { $this->_userTimezone = Tinebase_Core::getUserTimezone(); $this->_serverTimezone = date_default_timezone_get(); }
/** * appends sql to given select statement * * @param Zend_Db_Select $_select * @param Tinebase_Backend_Sql_Abstract $_backend */ function appendFilterSql($_select, $_backend) { $months = array(); $db = $_backend->getAdapter(); $date = new Tinebase_DateTime(); $format = 'Y-m'; $like = FALSE; if ($this->_operator == 'within') { switch ($this->_value) { case 'monthThis': $months = array($date->format($format)); break; case 'monthLast': $months = array($date->subMonth(1)->format($format)); break; case 'beforeLastMonth': $months = array($date->subMonth(2)->format($format)); break; case 'quarterThis': $month = ceil(intval($date->format('m')) / 3) * 3; $date->setDate($date->format('Y'), $month, 15); $months = array($date->format($format), $date->subMonth(1)->format($format), $date->subMonth(1)->format($format)); break; case 'quarterLast': $date->subMonth(3); $month = ceil(intval($date->format('m')) / 3) * 3; $date->setDate($date->format('Y'), $month, 15); $months = array($date->format($format), $date->subMonth(1)->format($format), $date->subMonth(1)->format($format)); break; case 'beforeLastQuarter': $date->subMonth(6); $month = ceil(intval($date->format('m')) / 3) * 3; $date->setDate($date->format('Y'), $month, 15); $months = array($date->format($format), $date->subMonth(1)->format($format), $date->subMonth(1)->format($format)); break; case 'yearThis': $like = $date->format('Y') . '-%'; break; case 'yearLast': $date->subYear(1); $like = $date->format('Y') . '-%'; break; default: throw new Tinebase_Exception_InvalidArgument('The value for the within operator is not supported: ' . $this->_value); } if ($like) { $_select->where($db->quoteInto($this->_getQuotedFieldName($_backend) . " LIKE (?)", $like)); } else { $_select->where($db->quoteInto($this->_getQuotedFieldName($_backend) . " IN (?)", $months)); } } elseif ($this->_operator == 'equals') { if ('' == $this->_value) { $_select->where($this->_getQuotedFieldName($_backend) . " = '0000-00-00 00:00:00' OR " . $this->_getQuotedFieldName($_backend) . ' IS NULL'); } else { $split = explode('-', $this->_value); if (!(strlen($this->_value) == 7 && (int) $split[0] > 1900 && (int) $split[1] > 0 && (int) $split[1] < 13)) { throw new Tinebase_Exception_MonthFormat(); } $_select->where($db->quoteInto($this->_getQuotedFieldName($_backend) . " = (?)", $this->_value)); } } else { $date = new Tinebase_DateTime($this->_value); $date->setTimezone(Tinebase_Core::getUserTimezone()); $dateString = $date->format('Y-m'); switch ($this->_operator) { case 'before': $_select->where($db->quoteInto($this->_getQuotedFieldName($_backend) . " < (?)", $dateString)); break; case 'after': $_select->where($db->quoteInto($this->_getQuotedFieldName($_backend) . " > (?)", $dateString)); break; case 'before_or_equals': $_select->where($db->quoteInto($this->_getQuotedFieldName($_backend) . " <= (?)", $dateString)); break; case 'after_or_equals': $_select->where($db->quoteInto($this->_getQuotedFieldName($_backend) . " >= (?)", $dateString)); break; default: throw new Tinebase_Exception_InvalidArgument('The operator ' . $this->_operator . ' is not supported for this filter!'); } } }
/** * add birthday data to VCard * * @param Tinebase_Record_Abstract $record * @param \Sabre\VObject\Component $card */ protected function _fromTine20ModelAddBirthday(Tinebase_Record_Abstract $record, \Sabre\VObject\Component $card) { /** @var Addressbook_Model_Contact $record */ if ($record->bday instanceof Tinebase_DateTime) { $date = clone $record->bday; $date->setTimezone(Tinebase_Core::getUserTimezone()); $date = $date->format('Y-m-d'); $card->add('BDAY', $date); } }
/** * processUpdateBillingInformation * * @param Tinebase_Record_RecordSet $contracts */ public function processUpdateLastAutobillOfProductAggregates(Tinebase_Record_RecordSet $contracts) { $now = Tinebase_DateTime::now(); $billingPoints = array('Timetracker_Model_Timeaccount' => 'end', 'Sales_Model_Product' => 'end', 'WebAccounting_Model_BackupPath' => 'end', 'WebAccounting_Model_StoragePath' => 'end', 'WebAccounting_Model_MailAccount' => 'end', 'WebAccounting_Model_DReg' => 'begin', 'WebAccounting_Model_CertificateDomain' => 'begin', 'WebAccounting_Model_IPNet' => 'end', '' => 'end', 'Sales_Model_ProductAgregate' => 'end'); foreach ($contracts as $contract) { if ($contract->end_date && $contract->end_date < $now) { continue; } // find product aggregates for this contract $filter = new Sales_Model_ProductAggregateFilter(array()); $filter->addFilter(new Tinebase_Model_Filter_Text(array('field' => 'contract_id', 'operator' => 'equals', 'value' => $contract->getId()))); $productAggregates = Sales_Controller_ProductAggregate::getInstance()->search($filter); foreach ($productAggregates as $pa) { // find all invoices for the contract $filter = new Sales_Model_InvoiceFilter(array(array('field' => 'contract', 'operator' => 'AND', 'value' => array(array('field' => ':id', 'operator' => 'equals', 'value' => $contract->getId()))))); $invoices = Sales_Controller_Invoice::getInstance()->search($filter); // find last invoice position for this aggregate $filter = new Sales_Model_InvoicePositionFilter(); $filter->addFilter(new Tinebase_Model_Filter_Text(array('field' => 'invoice_id', 'operator' => 'in', 'value' => $invoices->getArrayOfIds()))); $pagination = new Tinebase_Model_Pagination(array('limit' => 1, 'sort' => 'month', 'dir' => 'DESC')); $lastInvoicePosition = Sales_Controller_InvoicePosition::getInstance()->search($filter, $pagination)->getFirstRecord(); // set billing_point, if none given if (!$pa->billing_point) { $pa->billing_point = $billingPoints[$lastInvoicePosition->model]; } if (!$lastInvoicePosition) { // if no invoice position has been found, this is a new contract, so set start_date to the first day of the month of the contracts start_date $date = clone $contract->start_date; $date->setTimezone(Tinebase_Core::getUserTimezone()); $date->setTime(0, 0, 0); $date->setDate($date->format('Y'), $date->format('m'), 1); $date->setTimezone('UTC'); $startDate = clone $date; $labDate = NULL; } else { $split = explode('-', $lastInvoicePosition->month); $date = Tinebase_DateTime::now(); $date->setTimezone(Tinebase_Core::getUserTimezone()); $date->setTime(0, 0, 0); $date->setDate($split[0], $split[1], 1); // set to next billing date $date->addMonth(1); // if the billing point is at the begin of the interval, set date back one interval if ($pa->billing_point == 'begin') { $date->subMonth($pa->interval); } $date->setTimezone('UTC'); $labDate = clone $date; // find first invoice position to calculate start_date $pagination = new Tinebase_Model_Pagination(array('limit' => 1, 'sort' => 'month', 'dir' => 'ASC')); $firstInvoicePosition = Sales_Controller_InvoicePosition::getInstance()->search($filter, $pagination)->getFirstRecord(); $split = explode('-', $firstInvoicePosition->month); $startDate = Tinebase_DateTime::now()->setTimezone(Tinebase_Core::getUserTimezone()); $startDate->setTime(0, 0, 0); $startDate->setDate($split[0], $split[1], 1); $startDate->setTimezone('UTC'); } $pa->start_date = $startDate; $pa->last_autobill = $labDate; Sales_Controller_ProductAggregate::getInstance()->update($pa); } } }
/** * converts Tinebase_Record_RecordSet to external format * * @param Tinebase_Record_RecordSet $_records * @param Tinebase_Model_Filter_FilterGroup $_filter * @param Tinebase_Model_Pagination $_pagination * * @return mixed */ public function fromTine20RecordSet(Tinebase_Record_RecordSet $_records = NULL, $_filter = NULL, $_pagination = NULL) { if (count($_records) == 0) { return array(); } Tinebase_Notes::getInstance()->getMultipleNotesOfRecords($_records); Tinebase_Tags::getInstance()->getMultipleTagsOfRecords($_records); if (Tinebase_Core::isFilesystemAvailable()) { Tinebase_FileSystem_RecordAttachments::getInstance()->getMultipleAttachmentsOfRecords($_records); } Calendar_Model_Attender::resolveAttendee($_records->attendee, TRUE, $_records); Calendar_Convert_Event_Json::resolveRrule($_records); Calendar_Controller_Event::getInstance()->getAlarms($_records); Calendar_Convert_Event_Json::resolveGrantsOfExternalOrganizers($_records); Calendar_Model_Rrule::mergeAndRemoveNonMatchingRecurrences($_records, $_filter); $_records->sortByPagination($_pagination); Tinebase_Frontend_Json_Abstract::resolveContainersAndTags($_records, array('container_id')); $_records->setTimezone(Tinebase_Core::getUserTimezone()); $_records->convertDates = true; $eventsData = $_records->toArray(); foreach ($eventsData as $idx => $eventData) { if (!(isset($eventData[Tinebase_Model_Grants::GRANT_READ]) || array_key_exists(Tinebase_Model_Grants::GRANT_READ, $eventData)) || !$eventData[Tinebase_Model_Grants::GRANT_READ]) { $eventsData[$idx] = array_intersect_key($eventsData[$idx], array_flip(array('id', 'dtstart', 'dtend', 'transp', 'is_all_day_event'))); } } return $eventsData; }
protected function _setReferenceDate() { // set reference date to the 1st january of last year $this->_referenceDate = Tinebase_DateTime::now(); $this->_referenceDate->setTimezone(Tinebase_Core::getUserTimezone()); $this->_referenceDate->subYear(1); $this->_referenceDate->setDate($this->_referenceDate->format('Y'), 1, 1); $this->_referenceDate->setTime(0, 0, 0); $this->_referenceYear = $this->_referenceDate->format('Y'); $this->_lastMonthDays = array(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31); // find out if year is a leap year if ((bool) $this->_referenceDate->format('L')) { $this->_isLeapYear = TRUE; $this->_lastMonthDays[1] = 29; } }
/** * parse birthday * * @param array $data * @param Sabre\VObject\Property $property */ protected function _toTine20ModelParseBday(&$_data, \Sabre\VObject\Property $_property) { $tzone = new DateTimeZone(Tinebase_Core::getUserTimezone()); $_data['bday'] = new Tinebase_DateTime($_property->getValue(), $tzone); $_data['bday']->setTimezone(new DateTimeZone('UTC')); }
/** * create contact pdf * * @param Addressbook_Model_Contact $_contact contact data * * @return string the contact pdf */ public function generate(Addressbook_Model_Contact $_contact) { $locale = Tinebase_Core::get('locale'); $translate = Tinebase_Translation::getTranslation('Addressbook'); // set user timezone $_contact->setTimezone(Tinebase_Core::getUserTimezone()); $contactFields = array(array('label' => $translate->_('Business Contact Data'), 'type' => 'separator'), array('label' => $translate->_('Organisation / Unit'), 'type' => 'singleRow', 'value' => array(array('org_name', 'org_unit')), 'glue' => ' / '), array('label' => $translate->_('Business Address'), 'type' => 'multiRow', 'value' => array('adr_one_street', 'adr_one_street2', array('adr_one_postalcode', 'adr_one_locality'), array('adr_one_region', 'adr_one_countryname'))), array('label' => $translate->_('Email'), 'value' => array('email')), array('label' => $translate->_('Telephone Work'), 'value' => array('tel_work')), array('label' => $translate->_('Telephone Cellphone'), 'value' => array('tel_cell')), array('label' => $translate->_('Telephone Car'), 'value' => array('tel_car')), array('label' => $translate->_('Telephone Fax'), 'value' => array('tel_fax')), array('label' => $translate->_('Telephone Page'), 'value' => array('tel_pager')), array('label' => $translate->_('URL'), 'value' => array('url')), array('label' => $translate->_('Role'), 'value' => array('role')), array('label' => $translate->_('Room'), 'value' => array('room')), array('label' => $translate->_('Assistant'), 'value' => array('assistent')), array('label' => $translate->_('Assistant Telephone'), 'value' => array('tel_assistent')), array('label' => $translate->_('Private Contact Data'), 'type' => 'separator'), array('label' => $translate->_('Private Address'), 'type' => 'multiRow', 'value' => array('adr_two_street', 'adr_two_street2', array('adr_two_postalcode', 'adr_two_locality'), array('adr_two_region', 'adr_two_countryname'))), array('label' => $translate->_('Email Home'), 'value' => array('email_home')), array('label' => $translate->_('Telephone Home'), 'value' => array('tel_home')), array('label' => $translate->_('Telephone Cellphone Private'), 'value' => array('tel_cell_private')), array('label' => $translate->_('Telephone Fax Home'), 'value' => array('tel_fax_home')), array('label' => $translate->_('URL Home'), 'value' => array('url_home')), array('label' => $translate->_('Other Data'), 'type' => 'separator'), array('label' => $translate->_('Birthday'), 'value' => array('bday')), array('label' => $translate->_('Job Title'), 'value' => array('title'))); try { $tineImage = Addressbook_Controller::getInstance()->getImage($_contact->getId()); Tinebase_ImageHelper::resize($tineImage, 160, 240, Tinebase_ImageHelper::RATIOMODE_PRESERVANDCROP); $tmpPath = tempnam(Tinebase_Core::getTempDir(), 'tine20_tmp_gd'); $tmpPath .= $tineImage->getImageExtension(); file_put_contents($tmpPath, $tineImage->blob); $contactPhoto = Zend_Pdf_Image::imageWithPath($tmpPath); unlink($tmpPath); } catch (Exception $e) { // gif images are not supported yet by zf (or some other error) if (Tinebase_Core::isLogLevel(Zend_Log::TRACE)) { Tinebase_Core::getLogger()->trace(__METHOD__ . '::' . __LINE__ . ' ' . $e->__toString()); } $contactPhoto = NULL; } // build title (name) + subtitle + icon $nameFields = array('n_prefix', 'n_given', 'n_middle', 'n_family', 'n_suffix'); $titleArray = array(); foreach ($nameFields as $nameField) { if (!empty($_contact[$nameField])) { $titleArray[] = $_contact[$nameField]; } } $title = implode(' ', $titleArray); $subtitle = $_contact->org_name; $titleIcon = "/images/oxygen/32x32/apps/system-users.png"; // add data to array $record = array(); foreach ($contactFields as $fieldArray) { if (!isset($fieldArray['type']) || $fieldArray['type'] !== 'separator') { $values = array(); foreach ($fieldArray['value'] as $valueFields) { $content = array(); if (is_array($valueFields)) { $keys = $valueFields; } else { $keys = array($valueFields); } foreach ($keys as $key) { if ($_contact->{$key} instanceof Tinebase_DateTime) { $content[] = Tinebase_Translation::dateToStringInTzAndLocaleFormat($_contact->{$key}, NULL, NULL, 'date'); } elseif (!empty($_contact->{$key})) { if (preg_match("/countryname/", $key)) { $content[] = Zend_Locale::getTranslation($_contact->{$key}, 'country', $locale); } else { $content[] = $_contact->{$key}; } } } if (!empty($content)) { $glue = isset($fieldArray['glue']) ? $fieldArray['glue'] : " "; $values[] = implode($glue, $content); } } if (!empty($values)) { $record[] = array('label' => $fieldArray['label'], 'type' => isset($fieldArray['type']) ? $fieldArray['type'] : 'singleRow', 'value' => sizeof($values) === 1 ? $values[0] : $values); } } elseif (isset($fieldArray['type']) && $fieldArray['type'] === 'separator') { $record[] = $fieldArray; } } // add notes $record = $this->_addActivities($record, $_contact->notes); //print_r($record); // tags $tags = isset($_contact['tags']) ? $_contact['tags'] : array(); // generate pdf $this->generatePdf($record, $title, $subtitle, $tags, $_contact->note, $titleIcon, $contactPhoto, array(), FALSE); }
/** * test import with mergeTheirs resolve strategy * * @see 0007226: tag handling and other import problems */ public function testImportWithResolveStrategyMergeTheirs() { $this->_testNeedsTransaction(); $result = $this->_importHelper(array('dryrun' => 0)); $this->assertEquals(2, count($result['results']), 'no import results'); $fritz = $result['results'][1]; $fritz['tags'][] = array('name' => 'new import tag'); $fritz['tel_work'] = '04040'; $clientRecords = array(array('recordData' => $fritz, 'resolveStrategy' => 'mergeTheirs', 'index' => 1)); $result = $this->_importHelper(array('dryrun' => 0), $clientRecords); $this->assertEquals(1, $result['totalcount'], 'Should merge fritz'); $this->assertEquals(2, count($result['results'][0]['tags']), 'Should merge tags'); $this->assertEquals(0, $result['failcount'], 'no failures expected'); $this->assertEquals(1, $result['duplicatecount'], 'klaus should still be a duplicate'); $fritz = $result['results'][0]; $fritz['tel_work'] = '04040'; // need to adjust user TZ $lastModified = new Tinebase_DateTime($fritz['last_modified_time']); $fritz['last_modified_time'] = $lastModified->setTimezone(Tinebase_Core::getUserTimezone())->toString(); $clientRecords = array(array('recordData' => $fritz, 'resolveStrategy' => 'mergeTheirs', 'index' => 1)); $result = $this->_importHelper(array('dryrun' => 0), $clientRecords); $this->assertEquals(1, $result['totalcount'], 'Should merge fritz: ' . print_r($result, TRUE)); }
/** * tests the corret handling of the usertimezone in the date filter */ public function testDateIntervalFilter() { $taController = Timetracker_Controller_Timeaccount::getInstance(); $tsController = Timetracker_Controller_Timesheet::getInstance(); $dateString = '2014-07-14 00:15:00'; $date = new Tinebase_DateTime($dateString, Tinebase_Core::getUserTimezone()); $ta = $taController->create(new Timetracker_Model_Timeaccount(array('number' => '123', 'title' => 'test'))); $r = new Timetracker_Model_Timesheet(array('timeaccount_id' => $ta->getId(), 'account_id' => Tinebase_Core::getUser()->getId(), 'description' => 'lazy boring', 'start_date' => $date, 'duration' => 30)); $r->setTimezone('UTC'); $ts = $tsController->create($r); $filter = new Timetracker_Model_TimesheetFilter(array()); $dateFilter = new Tinebase_Model_Filter_DateMock(array('field' => 'start_date', 'operator' => "within", "value" => "weekThis")); $dateFilter::$testDate = $date; $filter->addFilter($dateFilter); $results = $tsController->search($filter); $this->assertEquals(1, $results->count()); }
/** * returns the current date if no $date string is given (needed for mocking only) * * @param string $date * @param boolean $usertimezone */ protected function _getDate($date = NULL, $usertimezone = FALSE) { if (!$date) { $date = Tinebase_DateTime::now(); } else { $date = new Tinebase_DateTime($date); } if ($usertimezone) { $date->setTimezone(Tinebase_Core::getUserTimezone()); } return $date; }
/** * inspects delete action * * @param array $_ids * @return array of ids to actually delete */ protected function _inspectDelete(array $_ids) { $records = $this->_backend->getMultiple($_ids); $records->setTimezone(Tinebase_Core::getUserTimezone()); $invoicePositionController = Sales_Controller_InvoicePosition::getInstance(); $contractController = Sales_Controller_Contract::getInstance(); foreach ($records as $record) { if (!$record->is_auto) { continue; } if ($record->cleared == 'CLEARED') { // cleared invoices must not be deleted throw new Sales_Exception_InvoiceAlreadyClearedDelete(); } else { // try to find a invoice after this one // there should be a contract $contractRelation = Tinebase_Relations::getInstance()->getRelations('Sales_Model_Invoice', 'Sql', $record->getId(), NULL, array(), TRUE, array('Sales_Model_Contract'))->getFirstRecord(); if ($contractRelation) { $contract = $contractRelation->related_record; $contract->setTimezone(Tinebase_Core::getUserTimezone()); // get all invoices related to this contract. throw exception if a follwing invoice has been found $invoiceRelations = Tinebase_Relations::getInstance()->getRelations('Sales_Model_Contract', 'Sql', $contract->getId(), NULL, array(), TRUE, array('Sales_Model_Invoice')); foreach ($invoiceRelations as $invoiceRelation) { $invoiceRelation->related_record->setTimezone(Tinebase_Core::getUserTimezone()); if ($record->getId() !== $invoiceRelation->related_record->getId() && $record->creation_time < $invoiceRelation->related_record->creation_time) { throw new Sales_Exception_DeletePreviousInvoice(); } } $this->_currentBillingContract = $contract; $productAggregates = $this->_findProductAggregates(); } else { if (Tinebase_Core::isLogLevel(Zend_Log::NOTICE)) { Tinebase_Core::getLogger()->notice(__METHOD__ . '::' . __LINE__ . ' Could not find contract relation -> skip contract handling'); } $contract = null; $productAggregates = array(); } // remove invoice_id from billables $filter = new Sales_Model_InvoicePositionFilter(array()); $filter->addFilter(new Tinebase_Model_Filter_Text(array('field' => 'invoice_id', 'operator' => 'equals', 'value' => $record->getId()))); $invoicePositions = $invoicePositionController->search($filter); $allModels = array_unique($invoicePositions->model); foreach ($allModels as $model) { if ($model == 'Sales_Model_ProductAggregate') { continue; } $filteredInvoicePositions = $invoicePositions->filter('model', $model); $billableControllerName = $model::getBillableControllerName(); $billableFilterName = $model::getBillableFilterName(); $filterInstance = new $billableFilterName(array()); $filterInstance->addFilter(new Tinebase_Model_Filter_Text(array('field' => 'invoice_id', 'operator' => 'equals', 'value' => $record->getId()))); $billableControllerName::getInstance()->updateMultiple($filterInstance, array('invoice_id' => NULL)); // set invoice ids of the timeaccounts if ($model == 'Timetracker_Model_Timeaccount') { $filterInstance = new Timetracker_Model_TimeaccountFilter(array()); $filterInstance->addFilter(new Tinebase_Model_Filter_Text(array('field' => 'invoice_id', 'operator' => 'equals', 'value' => $record->getId()))); Timetracker_Controller_Timeaccount::getInstance()->updateMultiple($filterInstance, array('invoice_id' => NULL)); } } // delete invoice positions $invoicePositionController->delete($invoicePositions->getId()); // set last_autobill a period back if ($contract) { //find the month of each productAggregate we have to set it back to $undoProductAggregates = array(); $paController = Sales_Controller_ProductAggregate::getInstance(); foreach ($invoicePositions as $inPos) { if ($inPos->model != 'Sales_Model_ProductAggregate') { continue; } //if we didnt find a month for the productAggreagte yet or if the month found is greater than the one we have at hands if (!isset($undoProductAggregates[$inPos->accountable_id]) || strcmp($undoProductAggregates[$inPos->accountable_id], $inPos->month) > 0) { $undoProductAggregates[$inPos->accountable_id] = $inPos->month; } } foreach ($productAggregates as $productAggregate) { if (!$productAggregate->last_autobill) { continue; } if (!isset($undoProductAggregates[$productAggregate->id])) { $product = $this->_cachedProducts->getById($productAggregate->product_id); if (!$product) { $product = Sales_Controller_Product::getInstance()->get($productAggregate->product_id); $this->_cachedProducts->addRecord($product); } if ($product->accountable == 'Sales_Model_Product' || $record->date != null && $record->date->isLater($productAggregate->last_autobill)) { continue; } $productAggregate->last_autobill->subMonth($productAggregate->interval); } else { $productAggregate->last_autobill = new Tinebase_DateTime($undoProductAggregates[$productAggregate->id] . '-01 00:00:00', Tinebase_Core::getUserTimezone()); if ($productAggregate->billing_point == 'begin') { $productAggregate->last_autobill->subMonth($productAggregate->interval); } if ($productAggregate->start_date && $productAggregate->last_autobill < $productAggregate->start_date) { $tmp = clone $productAggregate->start_date; $tmp->setTimezone(Tinebase_Core::getUserTimezone()); $tmp->setDate($tmp->format('Y'), $tmp->format('m'), 1); $tmp->setTime(0, 0, 0); if ($productAggregate->last_autobill < $tmp || $productAggregate->billing_point == 'end' && $productAggregate->last_autobill == $tmp) { $productAggregate->last_autobill = NULL; } } } $productAggregate->setTimezone('UTC'); $paController->update($productAggregate); $productAggregate->setTimezone(Tinebase_Core::getUserTimezone()); } } } } return $_ids; }
/** * get all relations of a given record * * @param string $_model own model to get relations for * @param string $_id own id to get relations for * @param string $_degree only return relations of given degree * @param array $_type only return relations of given type * @param string $_relatedModel only return relations having this related model * @return array */ public function getRelations($model, $id, $degree = NULL, $type = array(), $relatedModel = NULL) { $relations = Tinebase_Relations::getInstance()->getRelations($model, 'Sql', $id, $degree, $type, false, $relatedModel); // @TODO we still have no converter for relations :-( // -> related records returned here are different to the records returned by the apps itself! // -> this problem also applies to to generic json converter! if (count($relations) > 0) { $relations->setTimezone(Tinebase_Core::getUserTimezone()); $relations->bypassFilters = true; $result = $relations->toArray(); } else { $result = array(); } return array('results' => array_values($result), 'totalcount' => count($result)); }
/** * resolves virtual field "is_editable" * * @param array $resultSet */ public function getEditableState($resultSet) { for ($i = 0; $i < count($resultSet); $i++) { $sDate = new Tinebase_DateTime($resultSet[$i]['start_date']); $sDate->setTimezone(Tinebase_Core::getUserTimezone()); $eDate = NULL; if ($resultSet[$i]['end_date']) { $eDate = new Tinebase_DateTime($resultSet[$i]['end_date']); $eDate->setTimezone(Tinebase_Core::getUserTimezone()); } $freeTimeFilter = new HumanResources_Model_FreeTimeFilter(array(array('field' => 'firstday_date', 'operator' => 'after', 'value' => $sDate), array('field' => 'type', 'operator' => 'equals', 'value' => 'vacation'))); if ($eDate) { $freeTimeFilter->addFilter(new Tinebase_Model_Filter_Date(array('field' => 'firstday_date', 'operator' => 'before', 'value' => $eDate))); } $freeTimeFilter->addFilter(new Tinebase_Model_Filter_Text(array('field' => 'employee_id', 'operator' => 'equals', 'value' => $resultSet[$i]['employee_id']))); $freeTimeController = HumanResources_Controller_FreeTime::getInstance(); $resultSet[$i]['is_editable'] = $freeTimeController->search($freeTimeFilter)->count() > 0 ? FALSE : TRUE; } return $resultSet; }