Merge branch '2014.11' into 2015.11
[tine20] / tests / tine20 / Calendar / JsonTests.php
1 <?php
2 /**
3  * Tine 2.0 - http://www.tine20.org
4  * 
5  * @package     Calendar
6  * @license     http://www.gnu.org/licenses/agpl.html AGPL Version 3
7  * @copyright   Copyright (c) 2009-2014 Metaways Infosystems GmbH (http://www.metaways.de)
8  * @author      Cornelius Weiss <c.weiss@metaways.de>
9  */
10
11 /**
12  * Test class for Json Frontend
13  * 
14  * @package     Calendar
15  */
16 class Calendar_JsonTests extends Calendar_TestCase
17 {
18     /**
19      * Calendar Json Object
20      *
21      * @var Calendar_Frontend_Json
22      */
23     protected $_uit = null;
24     
25     /**
26      * (non-PHPdoc)
27      * @see Calendar/Calendar_TestCase::setUp()
28      */
29     public function setUp()
30     {
31         parent::setUp();
32         
33         Calendar_Controller_Event::getInstance()->doContainerACLChecks(true);
34         
35         $this->_uit = new Calendar_Frontend_Json();
36     }
37     
38     /**
39      * testGetRegistryData
40      */
41     public function testGetRegistryData()
42     {
43         // enforce fresh instance of calendar preferences
44         Tinebase_Core::set(Tinebase_Core::PREFERENCES, array());
45         
46         $registryData = $this->_uit->getRegistryData();
47         
48         $this->assertTrue(is_array($registryData['defaultContainer']['account_grants']));
49     }
50     
51     /**
52      * testCreateEvent
53      * 
54      * @param $now should the current date be used
55      */
56     public function testCreateEvent($now = FALSE)
57     {
58         $scleverDisplayContainerId = Tinebase_Core::getPreference('Calendar')->getValueForUser(Calendar_Preference::DEFAULTCALENDAR, $this->_getPersona('sclever')->getId());
59         $contentSeqBefore = Tinebase_Container::getInstance()->getContentSequence($scleverDisplayContainerId);
60         
61         $eventData = $this->_getEvent($now)->toArray();
62         
63         $tag = Tinebase_Tags::getInstance()->createTag(new Tinebase_Model_Tag(array(
64             'name' => 'phpunit-' . substr(Tinebase_Record_Abstract::generateUID(), 0, 10),
65             'type' => Tinebase_Model_Tag::TYPE_PERSONAL
66         )));
67         $eventData['tags'] = array($tag->toArray());
68         
69         $note = new Tinebase_Model_Note(array(
70             'note'         => 'very important note!',
71             'note_type_id' => Tinebase_Notes::getInstance()->getNoteTypes()->getFirstRecord()->getId(),
72         ));
73         $eventData['notes'] = array($note->toArray());
74         $eventData['etag'] = Tinebase_Record_Abstract::generateUID();
75         
76         $persistentEventData = $this->_uit->saveEvent($eventData);
77         $loadedEventData = $this->_uit->getEvent($persistentEventData['id']);
78         
79         $this->_assertJsonEvent($eventData, $loadedEventData, 'failed to create/load event');
80         $this->assertEquals($eventData['etag'], $loadedEventData['etag']);
81         
82         $contentSeqAfter = Tinebase_Container::getInstance()->getContentSequence($scleverDisplayContainerId);
83         $this->assertEquals($contentSeqBefore + 1, $contentSeqAfter,
84             'content sequence of display container should be increased by 1:' . $contentSeqAfter);
85         $this->assertEquals($contentSeqAfter, Tinebase_Container::getInstance()->get($scleverDisplayContainerId)->content_seq);
86         
87         return $loadedEventData;
88     }
89     
90     public function testStripWindowsLinebreaks()
91     {
92         $e = $this->_getEvent(TRUE);
93         $e->description = 'Hello my friend,' . chr(13) . chr(10) .'bla bla bla.'  . chr(13) . chr(10) .'good bye.';
94         $persistentEventData = $this->_uit->saveEvent($e->toArray());
95         $loadedEventData = $this->_uit->getEvent($persistentEventData['id']);
96         $this->assertEquals($loadedEventData['description'], 'Hello my friend,' . chr(10) . 'bla bla bla.' . chr(10) . 'good bye.');
97     }
98
99     /**
100     * testCreateEventWithNonExistantAttender
101     */
102     public function testCreateEventWithNonExistantAttender()
103     {
104         $testEmail = 'unittestnotexists@example.org';
105         $eventData = $this->_getEvent(TRUE)->toArray();
106         $eventData['attendee'][] = $this->_getUserTypeAttender($testEmail);
107         
108         $persistentEventData = $this->_uit->saveEvent($eventData);
109         $found = FALSE;
110         foreach ($persistentEventData['attendee'] as $attender) {
111             if ($attender['user_id']['email'] === $testEmail) {
112                 $this->assertEquals($testEmail, $attender['user_id']['n_fn']);
113                 $found = TRUE;
114             }
115         }
116         $this->assertTrue($found);
117     }
118     
119     /**
120      * get single attendee array
121      * 
122      * @param string $email
123      * @return array
124      */
125     protected function _getUserTypeAttender($email = 'unittestnotexists@example.org')
126     {
127         return array(
128             'user_id'        => $email,
129             'user_type'      => Calendar_Model_Attender::USERTYPE_USER,
130             'role'           => Calendar_Model_Attender::ROLE_REQUIRED,
131         );
132     }
133     
134     /**
135      * test create event with alarm
136      *
137      * @todo add testUpdateEventWithAlarm
138      */
139     public function testCreateEventWithAlarm()
140     {
141         $eventData = $this->_getEventWithAlarm(TRUE)->toArray();
142         $persistentEventData = $this->_uit->saveEvent($eventData);
143         $loadedEventData = $this->_uit->getEvent($persistentEventData['id']);
144         
145         //print_r($loadedEventData);
146         
147         // check if alarms are created / returned
148         $this->assertGreaterThan(0, count($loadedEventData['alarms']));
149         $this->assertEquals('Calendar_Model_Event', $loadedEventData['alarms'][0]['model']);
150         $this->assertEquals(Tinebase_Model_Alarm::STATUS_PENDING, $loadedEventData['alarms'][0]['sent_status']);
151         $this->assertTrue((isset($loadedEventData['alarms'][0]['minutes_before']) || array_key_exists('minutes_before', $loadedEventData['alarms'][0])), 'minutes_before is missing');
152         
153         $scheduler = Tinebase_Core::getScheduler();
154         $scheduler->addTask('Tinebase_Alarm', $this->createTask());
155         $scheduler->run();
156         
157         // check alarm status
158         $loadedEventData = $this->_uit->getEvent($persistentEventData['id']);
159         $this->assertEquals(Tinebase_Model_Alarm::STATUS_SUCCESS, $loadedEventData['alarms'][0]['sent_status']);
160     }
161     
162     /**
163      * createTask
164      */
165     public function createTask()
166     {
167         $request = new Zend_Controller_Request_Http();
168         $request->setControllerName('Tinebase_Alarm');
169         $request->setActionName('sendPendingAlarms');
170         $request->setParam('eventName', 'Tinebase_Event_Async_Minutely');
171         
172         $task = new Tinebase_Scheduler_Task();
173         $task->setMonths("Jan-Dec");
174         $task->setWeekdays("Sun-Sat");
175         $task->setDays("1-31");
176         $task->setHours("0-23");
177         $task->setMinutes("0/1");
178         $task->setRequest($request);
179         return $task;
180     }
181     
182     /**
183      * testUpdateEvent
184      */
185     public function testUpdateEvent()
186     {
187         $event = new Calendar_Model_Event($this->testCreateEvent(), true);
188         $event->dtstart->addHour(5);
189         $event->dtend->addHour(5);
190         $event->description = 'are you kidding?';
191         
192         $eventData = $event->toArray();
193         foreach ($eventData['attendee'] as $key => $attenderData) {
194             if ($eventData['attendee'][$key]['user_id'] != $this->_getTestUserContact()->getId()) {
195                 unset($eventData['attendee'][$key]);
196             }
197         }
198         
199         $updatedEventData = $this->_uit->saveEvent($eventData);
200         
201         $this->_assertJsonEvent($eventData, $updatedEventData, 'failed to update event');
202         
203         return $updatedEventData;
204     }
205
206     /**
207      * testDeleteEvent
208      */
209     public function testDeleteEvent() {
210         $eventData = $this->testCreateEvent();
211         
212         $this->_uit->deleteEvents(array($eventData['id']));
213         
214         $this->setExpectedException('Tinebase_Exception_NotFound');
215         $this->_uit->getEvent($eventData['id']);
216     }
217     
218     /**
219      * testSearchEvents
220      */
221     public function testSearchEvents()
222     {
223         $eventData = $this->testCreateEvent(TRUE); 
224         
225         $filter = $this->_getEventFilterArray();
226         $searchResultData = $this->_uit->searchEvents($filter, array());
227         
228         $this->assertTrue(! empty($searchResultData['results']));
229         $resultEventData = $searchResultData['results'][0];
230         
231         $this->_assertJsonEvent($eventData, $resultEventData, 'failed to search event');
232         return $searchResultData;
233     }
234     
235     /**
236      * get filter array with container and period filter
237      * 
238      * @param string|int $containerId
239      * @return multitype:multitype:string Ambigous <number, multitype:>  multitype:string multitype:string
240      */
241     protected function _getEventFilterArray($containerId = NULL)
242     {
243         $containerId = ($containerId) ? $containerId : $this->_getTestCalendar()->getId();
244         return array(
245             array('field' => 'container_id', 'operator' => 'equals', 'value' => $containerId),
246             array('field' => 'period', 'operator' => 'within', 'value' =>
247                 array("from" => '2009-03-20 06:15:00', "until" => Tinebase_DateTime::now()->addDay(1)->toString())
248             )
249         );
250     }
251     
252     /**
253      * testSearchEvents with period filter
254      * 
255      * @todo add an event that is in result set of Calendar_Controller_Event::search() 
256      *       but should be removed in Calendar_Frontend_Json::_multipleRecordsToJson()
257      */
258     public function testSearchEventsWithPeriodFilter()
259     {
260         $eventData = $this->testCreateRecurEvent();
261         
262         $filter = array(
263             array('field' => 'period', 'operator' => 'within', 'value' => array(
264                 'from'  => '2009-03-25 00:00:00',
265                 'until' => '2009-03-25 23:59:59',
266             )),
267             array('field' => 'container_id', 'operator' => 'equals', 'value' => $this->_getTestCalendar()->getId()),
268         );
269         
270         $searchResultData = $this->_uit->searchEvents($filter, array());
271         
272         $this->assertTrue(isset($searchResultData['results'][0]), 'event not found in result: ' . print_r($searchResultData['results'], true));
273         $resultEventData = $searchResultData['results'][0];
274         
275         $this->_assertJsonEvent($eventData, $resultEventData, 'failed to search event');
276     }
277     
278     /**
279      * #7688: Internal Server Error on calendar search
280      * 
281      * add period filter if none is given
282      * 
283      * https://forge.tine20.org/mantisbt/view.php?id=7688
284      */
285     public function testSearchEventsWithOutPeriodFilter()
286     {
287         $eventData = $this->testCreateRecurEvent();
288         $filter = array(array('field' => 'container_id', 'operator' => 'equals', 'value' => $this->_getTestCalendar()->getId()));
289         
290         $searchResultData = $this->_uit->searchEvents($filter, array());
291         $returnedFilter = $searchResultData['filter'];
292         $this->assertEquals(2, count($returnedFilter), 'Two filters shoud have been returned!');
293         $this->assertTrue($returnedFilter[1]['field'] == 'period' || $returnedFilter[0]['field'] == 'period', 'One returned filter shoud be a period filter');
294     }
295     
296     /**
297      * add period filter if none is given / configure from+until
298      * 
299      * @see 0009688: allow to configure default period filter in json frontend
300      */
301     public function testSearchEventsWithOutPeriodFilterConfiguredFromAndUntil()
302     {
303         Calendar_Config::getInstance()->set(Calendar_Config::MAX_JSON_DEFAULT_FILTER_PERIOD_FROM, 12);
304         
305         $filter = array(array('field' => 'container_id', 'operator' => 'equals', 'value' => $this->_getTestCalendar()->getId()));
306         $searchResultData = $this->_uit->searchEvents($filter, array());
307         
308         $now = Tinebase_DateTime::now()->setTime(0,0,0);
309         foreach ($searchResultData['filter'] as $filter) {
310             if ($filter['field'] === 'period') {
311                 $this->assertEquals($now->getClone()->subYear(1)->toString(), $filter['value']['from']);
312                 $this->assertEquals($now->getClone()->addMonth(1)->toString(), $filter['value']['until']);
313             }
314         }
315     }
316     
317     /**
318      * testSearchEvents with organizer = me filter
319      * 
320      * @see #6716: default favorite "me" is not resolved properly
321      */
322     public function testSearchEventsWithOrganizerMeFilter()
323     {
324         $eventData = $this->testCreateEvent(TRUE);
325         
326         $filter = $this->_getEventFilterArray();
327         $filter[] = array('field' => 'organizer', 'operator' => 'equals', 'value' => Addressbook_Model_Contact::CURRENTCONTACT);
328         
329         $searchResultData = $this->_uit->searchEvents($filter, array());
330         $this->assertTrue(! empty($searchResultData['results']));
331         $resultEventData = $searchResultData['results'][0];
332         $this->_assertJsonEvent($eventData, $resultEventData, 'failed to search event');
333         
334         // check organizer filter resolving
335         $organizerfilter = $searchResultData['filter'][2];
336         $this->assertTrue(is_array($organizerfilter['value']), 'organizer should be resolved: ' . print_r($organizerfilter, TRUE));
337         $this->assertEquals(Tinebase_Core::getUser()->contact_id, $organizerfilter['value']['id']);
338     }
339
340     /**
341      * testSearchEventsWithSharedContainerFilter
342      *
343      * @see 0011968: shared calendars filter leads to sql error with pgsql
344      */
345     public function testSearchEventsWithSharedContainerFilter()
346     {
347         $filter = $this->_getEventFilterArray();
348         $pathFilterValue = array("path" => "/shared");
349         $filter[0]['value'] = $pathFilterValue;
350         $searchResultData = $this->_uit->searchEvents($filter, array());
351
352         $this->assertEquals($pathFilterValue, $searchResultData['filter'][0]['value'], print_r($searchResultData['filter'], true));
353     }
354
355     /**
356      * search event with alarm
357      */
358     public function testSearchEventsWithAlarm()
359     {
360         $eventData = $this->_getEventWithAlarm(TRUE)->toArray();
361         $persistentEventData = $this->_uit->saveEvent($eventData);
362         
363         $searchResultData = $this->_uit->searchEvents($this->_getEventFilterArray(), array());
364         $this->assertTrue(! empty($searchResultData['results']));
365         $resultEventData = $searchResultData['results'][0];
366         
367         $this->_assertJsonEvent($persistentEventData, $resultEventData, 'failed to search event with alarm');
368     }
369     
370     /**
371      * testSetAttenderStatus
372      */
373     public function testSetAttenderStatus()
374     {
375         $eventData = $this->testCreateEvent();
376         $numAttendee = count($eventData['attendee']);
377         $eventData['attendee'][$numAttendee] = array(
378             'user_id' => $this->_getPersonasContacts('pwulf')->getId(),
379         );
380         
381         $updatedEventData = $this->_uit->saveEvent($eventData);
382         $pwulf = $this->_findAttender($updatedEventData['attendee'], 'pwulf');
383         
384         // he he, we don't have his authkey, cause json class sorts it out due to rights restrictions.
385         $attendeeBackend = new Calendar_Backend_Sql_Attendee();
386         $pwulf['status_authkey'] = $attendeeBackend->get($pwulf['id'])->status_authkey;
387         
388         $updatedEventData['container_id'] = $updatedEventData['container_id']['id'];
389         
390         $pwulf['status'] = Calendar_Model_Attender::STATUS_ACCEPTED;
391         $this->_uit->setAttenderStatus($updatedEventData, $pwulf, $pwulf['status_authkey']);
392         
393         $loadedEventData = $this->_uit->getEvent($eventData['id']);
394         $loadedPwulf = $this->_findAttender($loadedEventData['attendee'], 'pwulf');
395         $this->assertEquals(Calendar_Model_Attender::STATUS_ACCEPTED, $loadedPwulf['status']);
396     }
397     
398     /**
399      * testCreateRecurEvent
400      */
401     public function testCreateRecurEvent()
402     {
403         $eventData = $this->testCreateEvent();
404         $eventData['rrule'] = array(
405             'freq'     => 'WEEKLY',
406             'interval' => 1,
407             'byday'    => 'WE'
408         );
409         
410         $updatedEventData = $this->_uit->saveEvent($eventData);
411         $this->assertTrue(is_array($updatedEventData['rrule']));
412
413         return $updatedEventData;
414     }
415
416     /**
417      * testCreateRecurEventYearly
418      * 
419      * @see 0010610: yearly event is not shown in week view
420      */
421     public function testCreateRecurEventYearly()
422     {
423         $eventData = $this->_getEvent()->toArray();
424         $eventData['is_all_day_event'] = true;
425         $eventData['dtstart'] = '2015-01-04 00:00:00';
426         $eventData['dtend'] = '2015-01-04 23:59:59';
427         $eventData['rrule'] = array(
428             'freq'       => 'YEARLY',
429             'interval'   => 1,
430             'bymonthday' => 4,
431             'bymonth'    => 1,
432         );
433         
434         $updatedEventData = $this->_uit->saveEvent($eventData);
435         $this->assertTrue(is_array($updatedEventData['rrule']));
436         
437         $filter = array(
438             array('field' => 'container_id', 'operator' => 'equals', 'value' => $eventData['container_id']),
439             array('field' => 'period', 'operator' => 'within', 'value' =>
440                 array("from" => '2014-12-29 00:00:00', "until" => '2015-01-05 00:00:00')
441             )
442         );
443         $searchResultData = $this->_uit->searchEvents($filter, array());
444         $this->assertEquals(1, $searchResultData['totalcount'], 'event not found');
445     }
446     
447     /**
448      * testCreateRecurEventWithRruleUntil
449      * 
450      * @see 0008906: rrule_until is saved in usertime
451      */
452     public function testCreateRecurEventWithRruleUntil()
453     {
454         $eventData = $this->testCreateRecurEvent();
455         $localMidnight = Tinebase_DateTime::now()->setTime(23,59,59)->toString();
456         $eventData['rrule']['until'] = $localMidnight;
457         //$eventData['rrule']['freq']  = 'WEEKLY';
458         
459         $updatedEventData = $this->_uit->saveEvent($eventData);
460         $this->assertGreaterThanOrEqual($localMidnight, $updatedEventData['rrule']['until']);
461         
462         // check db record
463         $calbackend = new Calendar_Backend_Sql();
464         $db = $calbackend->getAdapter();
465         $select = $db->select();
466         $select->from(array($calbackend->getTableName() => $calbackend->getTablePrefix() . $calbackend->getTableName()), array('rrule_until', 'rrule'))->limit(1);
467         $select->where($db->quoteIdentifier($calbackend->getTableName() . '.id') . ' = ?', $updatedEventData['id']);
468         
469         $stmt = $db->query($select);
470         $queryResult = $stmt->fetch();
471         
472 //         echo Tinebase_Core::getUserTimezone();
473 //         echo date_default_timezone_get();
474         
475         $midnightInUTC = new Tinebase_DateTime($queryResult['rrule_until']);
476         $this->assertEquals(Tinebase_DateTime::now()->setTime(23,59,59)->toString(), $midnightInUTC->setTimezone(Tinebase_Core::getUserTimezone(), TRUE)->toString());
477     }
478     
479     /**
480     * testSearchRecuringIncludes
481     */
482     public function testSearchRecuringIncludes()
483     {
484         $recurEvent = $this->testCreateRecurEvent();
485     
486         $from = $recurEvent['dtstart'];
487         $until = new Tinebase_DateTime($from);
488         $until->addWeek(5)->addHour(10);
489         $until = $until->get(Tinebase_Record_Abstract::ISO8601LONG);
490     
491         $filter = array(
492         array('field' => 'container_id', 'operator' => 'equals', 'value' => $this->_getTestCalendar()->getId()),
493         array('field' => 'period',       'operator' => 'within', 'value' => array('from' => $from, 'until' => $until)),
494         );
495     
496         $searchResultData = $this->_uit->searchEvents($filter, array());
497     
498         $this->assertEquals(6, $searchResultData['totalcount']);
499         
500         // test appending tags to recurring instances
501         $this->assertTrue(isset($searchResultData['results'][4]['tags'][0]), 'tags not set: ' . print_r($searchResultData['results'][4], true));
502         $this->assertEquals('phpunit-', substr($searchResultData['results'][4]['tags'][0]['name'], 0, 8));
503     
504         return $searchResultData;
505     }
506     
507     /**
508      * testSearchRecuringIncludesAndSort
509      */
510     public function testSearchRecuringIncludesAndSort()
511     {
512         $recurEvent = $this->testCreateRecurEvent();
513         
514         $from = $recurEvent['dtstart'];
515         $until = new Tinebase_DateTime($from);
516         $until->addWeek(5)->addHour(10);
517         $until = $until->get(Tinebase_Record_Abstract::ISO8601LONG);
518         
519         $filter = array(
520             array('field' => 'container_id', 'operator' => 'equals', 'value' => $this->_getTestCalendar()->getId()),
521             array('field' => 'period',       'operator' => 'within', 'value' => array('from' => $from, 'until' => $until)),
522         );
523         
524         $searchResultData = $this->_uit->searchEvents($filter, array('sort' => 'dtstart', 'dir' => 'DESC'));
525         
526         $this->assertEquals(6, $searchResultData['totalcount']);
527         
528         // check sorting
529         $this->assertEquals('2009-04-29 06:00:00', $searchResultData['results'][0]['dtstart']);
530         $this->assertEquals('2009-04-22 06:00:00', $searchResultData['results'][1]['dtstart']);
531     }
532     
533     /**
534      * testCreateRecurException
535      */
536     public function testCreateRecurException()
537     {
538         $recurSet = Tinebase_Helper::array_value('results', $this->testSearchRecuringIncludes());
539         
540         $persistentException = $recurSet[1];
541         $persistentException['summary'] = 'go sleeping';
542         
543         // create persistent exception
544         $this->_uit->createRecurException($persistentException, FALSE, FALSE);
545         
546         // create exception date
547         $updatedBaseEvent = Calendar_Controller_Event::getInstance()->getRecurBaseEvent(new Calendar_Model_Event($recurSet[2]));
548         $recurSet[2]['last_modified_time'] = $updatedBaseEvent->last_modified_time;
549         $this->_uit->createRecurException($recurSet[2], TRUE, FALSE);
550         
551         // delete all following (including this)
552         $updatedBaseEvent = Calendar_Controller_Event::getInstance()->getRecurBaseEvent(new Calendar_Model_Event($recurSet[4]));
553         $recurSet[4]['last_modified_time'] = $updatedBaseEvent->last_modified_time;
554         $this->_uit->createRecurException($recurSet[4], TRUE, TRUE);
555         
556         $from = $recurSet[0]['dtstart'];
557         $until = new Tinebase_DateTime($from);
558         $until->addWeek(5)->addHour(10);
559         $until = $until->get(Tinebase_Record_Abstract::ISO8601LONG);
560         
561         $filter = array(
562             array('field' => 'container_id', 'operator' => 'equals', 'value' => $this->_getTestCalendar()->getId()),
563             array('field' => 'period',       'operator' => 'within', 'value' => array('from' => $from, 'until' => $until)),
564         );
565         
566         $searchResultData = $this->_uit->searchEvents($filter, array('sort' => 'dtstart'));
567         
568         // we deleted one and cropped
569         $this->assertEquals(3, count($searchResultData['results']));
570         
571         $summaryMap = array();
572         foreach ($searchResultData['results'] as $event) {
573             $summaryMap[$event['dtstart']] = $event['summary'];
574         }
575         $this->assertTrue((isset($summaryMap['2009-04-01 06:00:00']) || array_key_exists('2009-04-01 06:00:00', $summaryMap)));
576         $this->assertEquals($persistentException['summary'], $summaryMap['2009-04-01 06:00:00']);
577         
578         return $searchResultData;
579     }
580     
581     /**
582      * testCreateRecurExceptionWithOtherUser
583      * 
584      * @see 0008172: displaycontainer_id not set when recur exception is created
585      */
586     public function testCreateRecurExceptionWithOtherUser()
587     {
588         $recurSet = Tinebase_Helper::array_value('results', $this->testSearchRecuringIncludes());
589         
590         // create persistent exception (just status update)
591         $persistentException = $recurSet[1];
592         $scleverAttender = $this->_findAttender($persistentException['attendee'], 'sclever');
593         $attendeeBackend = new Calendar_Backend_Sql_Attendee();
594         $status_authkey = $attendeeBackend->get($scleverAttender['id'])->status_authkey;
595         $scleverAttender['status'] = Calendar_Model_Attender::STATUS_ACCEPTED;
596         $scleverAttender['status_authkey'] = $status_authkey;
597         foreach ($persistentException['attendee'] as $key => $attender) {
598             if ($attender['id'] === $scleverAttender['id']) {
599                 $persistentException['attendee'][$key] = $scleverAttender;
600                 break;
601             }
602         }
603         
604         // sclever has only READ grant
605         Tinebase_Container::getInstance()->setGrants($this->_getTestCalendar(), new Tinebase_Record_RecordSet('Tinebase_Model_Grants', array(array(
606             'account_id'    => $this->_getTestUser()->getId(),
607             'account_type'  => 'user',
608             Tinebase_Model_Grants::GRANT_READ     => true,
609             Tinebase_Model_Grants::GRANT_ADD      => true,
610             Tinebase_Model_Grants::GRANT_EDIT     => true,
611             Tinebase_Model_Grants::GRANT_DELETE   => true,
612             Tinebase_Model_Grants::GRANT_PRIVATE  => true,
613             Tinebase_Model_Grants::GRANT_ADMIN    => true,
614             Tinebase_Model_Grants::GRANT_FREEBUSY => true,
615         ), array(
616             'account_id'    => $this->_getPersona('sclever')->getId(),
617             'account_type'  => 'user',
618             Tinebase_Model_Grants::GRANT_READ     => true,
619             Tinebase_Model_Grants::GRANT_FREEBUSY => true,
620         ))), TRUE);
621         
622         $unittestUser = Tinebase_Core::getUser();
623         Tinebase_Core::set(Tinebase_Core::USER, $this->_getPersona('sclever'));
624         
625         // create persistent exception
626         $createdException = $this->_uit->createRecurException($persistentException, FALSE, FALSE);
627         Tinebase_Core::set(Tinebase_Core::USER, $this->_originalTestUser);
628         
629         $sclever = $this->_findAttender($createdException['attendee'], 'sclever');
630         $defaultCal = $this->_getPersonasDefaultCals('sclever');
631         $this->assertEquals('Susan Clever', $sclever['user_id']['n_fn']);
632         $this->assertEquals(Calendar_Model_Attender::STATUS_ACCEPTED, $sclever['status'], 'status mismatch: ' . print_r($sclever, TRUE));
633         $this->assertTrue(is_array($sclever['displaycontainer_id']));
634         $this->assertEquals($defaultCal['id'], $sclever['displaycontainer_id']['id']);
635     }
636     
637     /**
638      * testUpdateRecurSeries
639      */
640     public function testUpdateRecurSeries()
641     {
642         $recurSet = Tinebase_Helper::array_value('results', $this->testSearchRecuringIncludes());
643         
644         $persistentException = $recurSet[1];
645         $persistentException['summary'] = 'go sleeping';
646         $persistentException['dtstart'] = '2009-04-01 20:00:00';
647         $persistentException['dtend']   = '2009-04-01 20:30:00';
648         
649         // create persistent exception
650         $recurResult = $this->_uit->createRecurException($persistentException, FALSE, FALSE);
651         
652         // update recurseries 
653         $someRecurInstance = $recurSet[2];
654         $someRecurInstance['summary'] = 'go fishing';
655         $someRecurInstance['dtstart'] = '2009-04-08 10:00:00';
656         $someRecurInstance['dtend']   = '2009-04-08 12:30:00';
657         
658         $someRecurInstance['seq'] = 3;
659         $this->_uit->updateRecurSeries($someRecurInstance, FALSE, FALSE);
660         
661         $searchResultData = $this->_searchRecurSeries($recurSet[0]);
662         $this->assertEquals(6, count($searchResultData['results']));
663         
664         $summaryMap = array();
665         foreach ($searchResultData['results'] as $event) {
666             $summaryMap[$event['dtstart']] = $event['summary'];
667         }
668         
669         $this->assertTrue((isset($summaryMap['2009-04-01 20:00:00']) || array_key_exists('2009-04-01 20:00:00', $summaryMap)));
670         $this->assertEquals('go sleeping', $summaryMap['2009-04-01 20:00:00']);
671         
672         $fishings = array_keys($summaryMap, 'go fishing');
673         $this->assertEquals(5, count($fishings));
674         foreach ($fishings as $dtstart) {
675             $this->assertEquals('10:00:00', substr($dtstart, -8), 'all fishing events should start at 10:00');
676         }
677     }
678     
679     /**
680      * search updated recur set
681      * 
682      * @param array $firstInstance
683      * @return array
684      */
685     protected function _searchRecurSeries($firstInstance)
686     {
687         $from = $firstInstance['dtstart'];
688         $until = new Tinebase_DateTime($from);
689         $until->addWeek(5)->addHour(10);
690         $until = $until->get(Tinebase_Record_Abstract::ISO8601LONG);
691         
692         $filter = array(
693             array('field' => 'container_id', 'operator' => 'equals', 'value' => $this->_getTestCalendar()->getId()),
694             array('field' => 'period',       'operator' => 'within', 'value' => array('from' => $from, 'until' => $until)),
695         );
696         
697         return $this->_uit->searchEvents($filter, array());
698     }
699     
700     /**
701      * testUpdateRecurExceptionsFromSeriesOverDstMove
702      * 
703      * @todo implement
704      */
705     public function testUpdateRecurExceptionsFromSeriesOverDstMove()
706     {
707         /*
708          * 1. create recur event 1 day befor dst move
709          * 2. create an exception and exdate
710          * 3. move dtstart from 1 over dst boundary
711          * 4. test recurid and exdate by calculating series
712          */
713     }
714     
715     /**
716      * testDeleteRecurSeries
717      */
718     public function testDeleteRecurSeries()
719     {
720         $recurSet = Tinebase_Helper::array_value('results', $this->testSearchRecuringIncludes());
721         
722         $persistentException = $recurSet[1];
723         $persistentException['summary'] = 'go sleeping';
724         
725         // create persistent exception
726         $this->_uit->createRecurException($persistentException, FALSE, FALSE);
727         
728         // delete recurseries 
729         $someRecurInstance = $persistentException = $recurSet[2];
730         $this->_uit->deleteRecurSeries($someRecurInstance);
731         
732         $from = $recurSet[0]['dtstart'];
733         $until = new Tinebase_DateTime($from);
734         $until->addWeek(5)->addHour(10);
735         $until = $until->get(Tinebase_Record_Abstract::ISO8601LONG);
736         
737         $filter = array(
738             array('field' => 'container_id', 'operator' => 'equals', 'value' => $this->_getTestCalendar()->getId()),
739             array('field' => 'period',       'operator' => 'within', 'value' => array('from' => $from, 'until' => $until)),
740         );
741         
742         $searchResultData = $this->_uit->searchEvents($filter, array());
743         
744         $this->assertEquals(0, count($searchResultData['results']));
745     }
746     
747     /**
748      * testMeAsAttenderFilter
749      */
750     public function testMeAsAttenderFilter()
751     {
752         $eventData = $this->testCreateEvent(TRUE);
753         
754         $filter = $this->_getEventFilterArray();
755         $filter[] = array('field' => 'attender'    , 'operator' => 'equals', 'value' => array(
756             'user_type' => Calendar_Model_Attender::USERTYPE_USER,
757             'user_id'   => Addressbook_Model_Contact::CURRENTCONTACT,
758         ));
759         
760         $searchResultData = $this->_uit->searchEvents($filter, array());
761         $this->assertTrue(! empty($searchResultData['results']));
762         $resultEventData = $searchResultData['results'][0];
763         
764         $this->_assertJsonEvent($eventData, $resultEventData, 'failed to filter for me as attender');
765     }
766     
767     /**
768      * testFreeBusyCleanup
769      * 
770      * @return array event data
771      */
772     public function testFreeBusyCleanup()
773     {
774         // give fb grants from sclever
775         $scleverCal = Tinebase_Container::getInstance()->getContainerById($this->_getPersonasDefaultCals('sclever'));
776         Tinebase_Container::getInstance()->setGrants($scleverCal->getId(), new Tinebase_Record_RecordSet('Tinebase_Model_Grants', array(array(
777             'account_id'    => $this->_getPersona('sclever')->getId(),
778             'account_type'  => 'user',
779             Tinebase_Model_Grants::GRANT_READ     => true,
780             Tinebase_Model_Grants::GRANT_ADD      => true,
781             Tinebase_Model_Grants::GRANT_EDIT     => true,
782             Tinebase_Model_Grants::GRANT_DELETE   => true,
783             Tinebase_Model_Grants::GRANT_PRIVATE  => true,
784             Tinebase_Model_Grants::GRANT_ADMIN    => true,
785             Tinebase_Model_Grants::GRANT_FREEBUSY => true,
786         ), array(
787             'account_id'    => $this->_getTestUser()->getId(),
788             'account_type'  => 'user',
789             Tinebase_Model_Grants::GRANT_FREEBUSY => true,
790         ))), TRUE);
791         
792         Tinebase_Core::set(Tinebase_Core::USER, $this->_getPersona('sclever'));
793         $eventData = $this->_getEvent()->toArray();
794         unset($eventData['organizer']);
795         $eventData['container_id'] = $scleverCal->getId();
796         $eventData['attendee'] = array(array(
797             'user_id' => $this->_getPersonasContacts('sclever')->getId()
798         ));
799         $eventData['organizer'] = $this->_getPersonasContacts('sclever')->getId();
800         $eventData = $this->_uit->saveEvent($eventData);
801         $filter = $this->_getEventFilterArray($this->_getPersonasDefaultCals('sclever')->getId());
802         $filter[] = array('field' => 'summary', 'operator' => 'equals', 'value' => 'Wakeup');
803         $searchResultData = $this->_uit->searchEvents($filter, array());
804         $this->assertTrue(! empty($searchResultData['results']), 'expected event in search result (search by sclever): ' 
805             . print_r($eventData, TRUE) . 'search filter: ' . print_r($filter, TRUE));
806         
807         Tinebase_Core::set(Tinebase_Core::USER, $this->_getTestUser());
808         $searchResultData = $this->_uit->searchEvents($filter, array());
809         $this->assertTrue(! empty($searchResultData['results']), 'expected (freebusy cleanup) event in search result: ' 
810             . print_r($eventData, TRUE) . 'search filter: ' . print_r($filter, TRUE));
811         $eventData = $searchResultData['results'][0];
812         
813         $this->assertFalse((isset($eventData['summary']) || array_key_exists('summary', $eventData)), 'summary not empty: ' . print_r($eventData, TRUE));
814         $this->assertFalse((isset($eventData['description']) || array_key_exists('description', $eventData)), 'description not empty');
815         $this->assertFalse((isset($eventData['tags']) || array_key_exists('tags', $eventData)), 'tags not empty');
816         $this->assertFalse((isset($eventData['notes']) || array_key_exists('notes', $eventData)), 'notes not empty');
817         $this->assertFalse((isset($eventData['attendee']) || array_key_exists('attendee', $eventData)), 'attendee not empty');
818         $this->assertFalse((isset($eventData['organizer']) || array_key_exists('organizer', $eventData)), 'organizer not empty');
819         $this->assertFalse((isset($eventData['alarms']) || array_key_exists('alarms', $eventData)), 'alarms not empty');
820         
821         return $eventData;
822     }
823
824     /**
825      * testFreeBusyCleanupOfNotes
826      * 
827      * @see 0009918: shared (only free/busy) calendar is showing event details within the history tab.
828      */
829     public function testFreeBusyCleanupOfNotes()
830     {
831         $eventData = $this->testFreeBusyCleanup();
832         
833         $tinebaseJson = new Tinebase_Frontend_Json();
834         $filter = array(array(
835             'field' => "record_model",
836             'operator' => "equals",
837             'value' => "Calendar_Model_Event"
838         ), array(
839             'field' => 'record_id',
840             'operator' => 'equals',
841             'value' => $eventData['id']
842         ));
843         $notes = $tinebaseJson->searchNotes($filter, array());
844         
845         $this->assertEquals(0, $notes['totalcount'], 'should not find any notes of record');
846         $this->assertEquals(0, count($notes['results']), 'should not find any notes of record');
847     }
848     
849     /**
850      * test deleting container and the containing events
851      * #6704: events do not disappear when shared calendar got deleted
852      * https://forge.tine20.org/mantisbt/view.php?id=6704
853      */
854     public function testDeleteContainerAndEvents()
855     {
856         $fe = new Tinebase_Frontend_Json_Container();
857         $container = $fe->addContainer('Calendar', 'testdeletecontacts', Tinebase_Model_Container::TYPE_SHARED, '');
858         // test if model is set automatically
859         $this->assertEquals($container['model'], 'Calendar_Model_Event');
860         
861         $date = new Tinebase_DateTime();
862         $event = new Calendar_Model_Event(array(
863             'dtstart' => $date,
864             'dtend'    => $date->subHour(1),
865             'summary' => 'bla bla',
866             'class'    => 'PUBLIC',
867             'transp'    => 'OPAQUE',
868             'container_id' => $container['id'],
869             'organizer' => Tinebase_Core::getUser()->contact_id
870             ));
871         $event = Calendar_Controller_Event::getInstance()->create($event);
872         $this->assertEquals($container['id'], $event->container_id);
873         
874         $fe->deleteContainer($container['id']);
875         
876         $e = new Exception('dummy');
877         
878         $cb = new Calendar_Backend_Sql();
879         $deletedEvent = $cb->get($event->getId(), true);
880         // record should be deleted
881         $this->assertEquals($deletedEvent->is_deleted, 1);
882         
883         try {
884             Calendar_Controller_Event::getInstance()->get($event->getId(), $container['id']);
885             $this->fail('The expected exception was not thrown');
886         } catch (Tinebase_Exception_NotFound $e) {
887             // ok;
888         }
889         // record should not be found
890         $this->assertEquals($e->getMessage(), 'Calendar_Model_Event record with id '.$event->getId().' not found!');
891     }
892     
893     /**
894      * compare expected event data with test event
895      *
896      * @param array $expectedEventData
897      * @param array $eventData
898      * @param string $msg
899      */
900     protected function _assertJsonEvent($expectedEventData, $eventData, $msg)
901     {
902         $this->assertEquals($expectedEventData['summary'], $eventData['summary'], $msg . ': failed to create/load event');
903         
904         // assert effective grants are set
905         $this->assertEquals((bool) $expectedEventData[Tinebase_Model_Grants::GRANT_EDIT], (bool) $eventData[Tinebase_Model_Grants::GRANT_EDIT], $msg . ': effective grants mismatch');
906         // container, assert attendee, tags
907         $this->assertEquals($expectedEventData['dtstart'], $eventData['dtstart'], $msg . ': dtstart mismatch');
908         $this->assertTrue(is_array($eventData['container_id']), $msg . ': failed to "resolve" container');
909         $this->assertTrue(is_array($eventData['container_id']['account_grants']), $msg . ': failed to "resolve" container account_grants');
910         $this->assertGreaterThan(0, count($eventData['attendee']));
911         $this->assertEquals(count($eventData['attendee']), count($expectedEventData['attendee']), $msg . ': failed to append attendee');
912         $this->assertTrue(is_array($eventData['attendee'][0]['user_id']), $msg . ': failed to resolve attendee user_id');
913         // NOTE: due to sorting isshues $eventData['attendee'][0] may be a non resolvable container (due to rights restrictions)
914         $this->assertTrue(is_array($eventData['attendee'][0]['displaycontainer_id']) || (isset($eventData['attendee'][1]) && is_array($eventData['attendee'][1]['displaycontainer_id'])), $msg . ': failed to resolve attendee displaycontainer_id');
915         $this->assertEquals(count($expectedEventData['tags']), count($eventData['tags']), $msg . ': failed to append tag');
916         $this->assertEquals(count($expectedEventData['notes']), count($eventData['notes']), $msg . ': failed to create note or wrong number of notes');
917         
918         if ((isset($expectedEventData['alarms']) || array_key_exists('alarms', $expectedEventData))) {
919             $this->assertTrue((isset($eventData['alarms']) || array_key_exists('alarms', $eventData)), ': failed to create alarms');
920             $this->assertEquals(count($expectedEventData['alarms']), count($eventData['alarms']), $msg . ': failed to create correct number of alarms');
921             if (count($expectedEventData['alarms']) > 0) {
922                 $this->assertTrue((isset($eventData['alarms'][0]['minutes_before']) || array_key_exists('minutes_before', $eventData['alarms'][0])));
923             }
924         }
925     }
926     
927     /**
928      * find attender 
929      *
930      * @param array $attendeeData
931      * @param string $name
932      * @return array
933      */
934     protected function _findAttender($attendeeData, $name) {
935         $attenderData = false;
936         $searchedId = $this->_getPersonasContacts($name)->getId();
937         
938         foreach ($attendeeData as $key => $attender) {
939             if ($attender['user_type'] == Calendar_Model_Attender::USERTYPE_USER) {
940                 if (is_array($attender['user_id']) && (isset($attender['user_id']['id']) || array_key_exists('id', $attender['user_id']))) {
941                     if ($attender['user_id']['id'] == $searchedId) {
942                         $attenderData = $attendeeData[$key];
943                     }
944                 }
945             }
946         }
947         
948         return $attenderData;
949     }
950     
951     /**
952      * test filter with hidden group -> should return empty result
953      * 
954      * @see 0006934: setting a group that is hidden from adb as attendee filter throws exception
955      */
956     public function testHiddenGroupFilter()
957     {
958         $hiddenGroup = new Tinebase_Model_Group(array(
959             'name'          => 'hiddengroup',
960             'description'   => 'hidden group',
961             'visibility'     => Tinebase_Model_Group::VISIBILITY_HIDDEN
962         ));
963         $hiddenGroup = Admin_Controller_Group::getInstance()->create($hiddenGroup);
964         $this->_groupIdsToDelete[] = $hiddenGroup->getId();
965         
966         $filter = array(array(
967             'field'    => 'attender',
968             'operator' => 'equals',
969             'value'    => array(
970                 'user_id'   => $hiddenGroup->list_id,
971                 'user_type' => 'group',
972             ),
973         ));
974         $result = $this->_uit->searchEvents($filter, array());
975         $this->assertEquals(0, $result['totalcount']);
976     }
977     
978     /**
979      * testExdateDeleteAll
980      * 
981      * @see 0007382: allow to edit / delete the whole series / thisandfuture when editing/deleting recur exceptions
982      */
983     public function testExdateDeleteAll()
984     {
985         $events = $this->testCreateRecurException();
986         $exception = $this->_getException($events);
987         $this->_uit->deleteEvents(array($exception['id']), Calendar_Model_Event::RANGE_ALL);
988         
989         $search = $this->_uit->searchEvents($events['filter'], NULL);
990         $this->assertEquals(0, $search['totalcount'], 'all events should be deleted: ' . print_r($search,TRUE));
991     }
992     
993     /**
994      * get exception from event resultset
995      * 
996      * @param array $events
997      * @param integer $index (1 = picks first, 2 = picks second, ...)
998      * @return array|NULL
999      */
1000     protected function _getException($events, $index = 1)
1001     {
1002         $event = NULL;
1003         $found = 0;
1004         foreach ($events['results'] as $event) {
1005             if (! empty($event['recurid'])) {
1006                 $found++;
1007                 if ($index === $found) {
1008                     return $event;
1009                 }
1010             }
1011         }
1012         
1013         return $event;
1014     }
1015     
1016     /**
1017      * testExdateDeleteThis
1018      * 
1019      * @see 0007382: allow to edit / delete the whole series / thisandfuture when editing/deleting recur exceptions
1020      */
1021     public function testExdateDeleteThis()
1022     {
1023         $events = $this->testCreateRecurException();
1024         $exception = $this->_getException($events);
1025         $this->_uit->deleteEvents(array($exception['id']));
1026         
1027         $search = $this->_uit->searchEvents($events['filter'], NULL);
1028         $this->assertEquals(2, $search['totalcount'], '2 events should remain: ' . print_r($search,TRUE));
1029     }
1030     
1031     /**
1032      * testExdateDeleteThisAndFuture
1033      * 
1034      * @see 0007382: allow to edit / delete the whole series / thisandfuture when editing/deleting recur exceptions
1035      */
1036     public function testExdateDeleteThisAndFuture()
1037     {
1038         $events = $this->testCreateRecurException();
1039         $exception = $this->_getException($events, 1);
1040         $this->_uit->deleteEvents(array($exception['id']), Calendar_Model_Event::RANGE_THISANDFUTURE);
1041         
1042         $search = $this->_uit->searchEvents($events['filter'], NULL);
1043         $this->assertEquals(1, $search['totalcount'], '1 event should remain: ' . print_r($search,TRUE));
1044     }
1045     
1046     /**
1047      * assert grant handling
1048      */
1049     public function testSaveResource($grants = array('readGrant' => true,'editGrant' => true))
1050     {
1051         $resoureData = array(
1052             'name'  => Tinebase_Record_Abstract::generateUID(),
1053             'email' => Tinebase_Record_Abstract::generateUID() . '@unittest.com',
1054             'grants' => array(array_merge($grants, array(
1055                 'account_id' => Tinebase_Core::getUser()->getId(),
1056                 'account_type' => 'user'
1057             )))
1058         );
1059         
1060         $resoureData = $this->_uit->saveResource($resoureData);
1061         $this->assertTrue(is_array($resoureData['grants']), 'grants are not resolved');
1062         
1063         return $resoureData;
1064     }
1065     
1066     /**
1067      * assert only resources with read grant are returned if the user has no manage right
1068      */
1069     public function testSearchResources()
1070     {
1071         $readableResoureData = $this->testSaveResource();
1072         $nonReadableResoureData = $this->testSaveResource(array());
1073         
1074         $filer = array(
1075             array('field' => 'name', 'operator' => 'in', 'value' => array(
1076                 $readableResoureData['name'],
1077                 $nonReadableResoureData['name'],
1078             ))
1079         );
1080         
1081         $searchResultManager = $this->_uit->searchResources($filer, array());
1082         $this->assertEquals(2, count($searchResultManager['results']), 'with manage grants all records should be found');
1083         
1084         // steal manage right and reactivate container checks
1085         $roleManager = Tinebase_Acl_Roles::getInstance();
1086         $roleManager->deleteRoles(array(
1087                 $roleManager->getRoleByName('manager role')->getId(),
1088                 $roleManager->getRoleByName('admin role')->getId()
1089                 ));
1090         
1091         Calendar_Controller_Resource::getInstance()->doContainerACLChecks(TRUE);
1092         
1093         $searchResult = $this->_uit->searchResources($filer, array());
1094         $this->assertEquals(1, count($searchResult['results']), 'without manage grants only one record should be found');
1095     }
1096     
1097     /**
1098      * assert status authkey with editGrant
1099      * assert stauts can be set with editGrant
1100      * assert stauts can't be set without editGrant
1101      */
1102     public function testResourceAttendeeGrants()
1103     {
1104         $editableResoureData = $this->testSaveResource();
1105         $nonEditableResoureData = $this->testSaveResource(array('readGrant'));
1106         
1107         $event = $this->_getEvent(TRUE);
1108         $event->attendee = new Tinebase_Record_RecordSet('Calendar_Model_Attender', array(
1109             array(
1110                 'user_type'  => Calendar_Model_Attender::USERTYPE_RESOURCE,
1111                 'user_id'    => $editableResoureData['id'],
1112                 'status'     => Calendar_Model_Attender::STATUS_ACCEPTED
1113             ),
1114             array(
1115                 'user_type'  => Calendar_Model_Attender::USERTYPE_RESOURCE,
1116                 'user_id'    => $nonEditableResoureData['id'],
1117                 'status'     => Calendar_Model_Attender::STATUS_ACCEPTED
1118             )
1119         ));
1120         
1121         $persistentEventData = $this->_uit->saveEvent($event->toArray());
1122         
1123         $attendee = new Tinebase_Record_RecordSet('Calendar_Model_Attender', $persistentEventData['attendee']);
1124         $this->assertEquals(1, count($attendee->filter('status', Calendar_Model_Attender::STATUS_ACCEPTED)), 'one accepted');
1125         $this->assertEquals(1, count($attendee->filter('status', Calendar_Model_Attender::STATUS_NEEDSACTION)), 'one needs action');
1126         
1127         $this->assertEquals(1, count($attendee->filter('status_authkey', '/[a-z0-9]+/', TRUE)), 'one has authkey');
1128         
1129         $attendee->status = Calendar_Model_Attender::STATUS_TENTATIVE;
1130         $persistentEventData['attendee'] = $attendee->toArray();
1131         
1132         $updatedEventData = $this->_uit->saveEvent($persistentEventData);
1133         $attendee = new Tinebase_Record_RecordSet('Calendar_Model_Attender', $updatedEventData['attendee']);
1134         $this->assertEquals(1, count($attendee->filter('status', Calendar_Model_Attender::STATUS_TENTATIVE)), 'one tentative');
1135     }
1136
1137     /**
1138      * testExdateUpdateAllSummary
1139      * 
1140      * @see 0007690: allow to update the whole series / thisandfuture when updating recur exceptions
1141      */
1142     public function testExdateUpdateAllSummary()
1143     {
1144         $events = $this->testCreateRecurException();
1145         $exception = $this->_getException($events, 1);
1146         $exception['summary'] = 'new summary';
1147         
1148         $event = $this->_uit->saveEvent($exception, FALSE, Calendar_Model_Event::RANGE_ALL);
1149         
1150         $search = $this->_uit->searchEvents($events['filter'], NULL);
1151         foreach ($search['results'] as $event) {
1152             $this->assertEquals('new summary', $event['summary']);
1153         }
1154     }
1155
1156     /**
1157      * testExdateUpdateAllDtStart
1158      * 
1159      * @see 0007690: allow to update the whole series / thisandfuture when updating recur exceptions
1160      * 
1161      * @todo finish
1162      */
1163     public function testExdateUpdateAllDtStart()
1164     {
1165         $events = $this->testCreateRecurException();
1166         $exception = $this->_getException($events, 1);
1167         $exception['dtstart'] = '2009-04-01 08:00:00';
1168         $exception['dtend'] = '2009-04-01 08:15:00';
1169         
1170         $event = $this->_uit->saveEvent($exception, FALSE, Calendar_Model_Event::RANGE_ALL);
1171         
1172         $search = $this->_uit->searchEvents($events['filter'], NULL);
1173         foreach ($search['results'] as $event) {
1174             $this->assertContains('08:00:00', $event['dtstart'], 'wrong dtstart: ' . print_r($event, TRUE));
1175             $this->assertContains('08:15:00', $event['dtend']);
1176         }
1177     }
1178     
1179     /**
1180      * testExdateUpdateThis
1181      * 
1182      * @see 0007690: allow to update the whole series / thisandfuture when updating recur exceptions
1183      */
1184     public function testExdateUpdateThis()
1185     {
1186         $events = $this->testCreateRecurException();
1187         $exception = $this->_getException($events, 1);
1188         $exception['summary'] = 'exception';
1189         
1190         $event = $this->_uit->saveEvent($exception);
1191         $this->assertEquals('exception', $event['summary']);
1192         
1193         // check for summary (only changed in one event)
1194         $search = $this->_uit->searchEvents($events['filter'], NULL);
1195         foreach ($search['results'] as $event) {
1196             if (! empty($event['recurid']) && ! preg_match('/^fakeid/', $event['id'])) {
1197                 $this->assertEquals('exception', $event['summary'], 'summary not changed in exception: ' . print_r($event, TRUE));
1198             } else {
1199                 $this->assertEquals('Wakeup', $event['summary']);
1200             }
1201         }
1202     }
1203
1204     /**
1205      * testExdateUpdateThisAndFuture
1206      * 
1207      * @see 0007690: allow to update the whole series / thisandfuture when updating recur exceptions
1208      */
1209     public function testExdateUpdateThisAndFuture()
1210     {
1211         $events = $this->testCreateRecurException();
1212         $exception = $this->_getException($events, 1);
1213         $exception['summary'] = 'new summary';
1214         
1215         $updatedEvent = $this->_uit->saveEvent($exception, FALSE, Calendar_Model_Event::RANGE_THISANDFUTURE);
1216         $this->assertEquals('new summary', $updatedEvent['summary'], 'summary not changed in exception: ' . print_r($updatedEvent, TRUE));
1217         
1218         $search = $this->_uit->searchEvents($events['filter'], NULL);
1219         foreach ($search['results'] as $event) {
1220             if ($event['dtstart'] >= $updatedEvent['dtstart']) {
1221                 $this->assertEquals('new summary', $event['summary'], 'summary not changed in event: ' . print_r($event, TRUE));
1222             } else {
1223                 $this->assertEquals('Wakeup', $event['summary']);
1224             }
1225         }
1226     }
1227
1228     /**
1229      * testExdateUpdateThisAndFutureWithRruleUntil
1230      * 
1231      * @see 0008244: "rrule until must not be before dtstart" when updating recur exception (THISANDFUTURE)
1232      */
1233     public function testExdateUpdateThisAndFutureWithRruleUntil()
1234     {
1235         $events = $this->testCreateRecurException();
1236         
1237         $exception = $this->_getException($events, 1);
1238         $exception['dtstart'] = Tinebase_DateTime::now()->toString();
1239         $exception['dtend'] = Tinebase_DateTime::now()->addHour(1)->toString();
1240         
1241         // move exception
1242         $updatedEvent = $this->_uit->saveEvent($exception);
1243         // try to update the whole series
1244         $updatedEvent['summary'] = 'new summary';
1245         $updatedEvent = $this->_uit->saveEvent($updatedEvent, FALSE, Calendar_Model_Event::RANGE_THISANDFUTURE);
1246         
1247         $this->assertEquals('new summary', $updatedEvent['summary'], 'summary not changed in event: ' . print_r($updatedEvent, TRUE));
1248     }
1249     
1250     /**
1251      * testExdateUpdateThisAndFutureRemoveAttendee
1252      * 
1253      * @see 0007690: allow to update the whole series / thisandfuture when updating recur exceptions
1254      */
1255     public function testExdateUpdateThisAndFutureRemoveAttendee()
1256     {
1257         $events = $this->testCreateRecurException();
1258         $exception = $this->_getException($events, 1);
1259         // remove susan from attendee
1260         unset($exception['attendee'][0]);
1261         
1262         $updatedEvent = $this->_uit->saveEvent($exception, FALSE, Calendar_Model_Event::RANGE_THISANDFUTURE);
1263         $this->assertEquals(1, count($updatedEvent['attendee']), 'attender not removed from exception: ' . print_r($updatedEvent, TRUE));
1264         
1265         $search = $this->_uit->searchEvents($events['filter'], NULL);
1266         foreach ($search['results'] as $event) {
1267             if ($event['dtstart'] >= $updatedEvent['dtstart']) {
1268                 $this->assertEquals(1, count($event['attendee']), 'attendee count mismatch: ' . print_r($event, TRUE));
1269             } else {
1270                 $this->assertEquals(2, count($event['attendee']), 'attendee count mismatch: ' . print_r($event, TRUE));
1271             }
1272         }
1273     }
1274
1275     /**
1276      * testExdateUpdateAllAddAttendee
1277      * 
1278      * @see 0007690: allow to update the whole series / thisandfuture when updating recur exceptions
1279      */
1280     public function testExdateUpdateAllAddAttendee()
1281     {
1282         $events = $this->testCreateRecurException();
1283         $exception = $this->_getException($events, 1);
1284         // add new attender
1285         $exception['attendee'][] = $this->_getUserTypeAttender();
1286         
1287         $updatedEvent = $this->_uit->saveEvent($exception, FALSE, Calendar_Model_Event::RANGE_ALL);
1288         $this->assertEquals(3, count($updatedEvent['attendee']), 'attender not added to exception: ' . print_r($updatedEvent, TRUE));
1289         
1290         $search = $this->_uit->searchEvents($events['filter'], NULL);
1291         foreach ($search['results'] as $event) {
1292             $this->assertEquals(3, count($event['attendee']), 'attendee count mismatch: ' . print_r($event, TRUE));
1293         }
1294     }
1295     
1296     /**
1297      * testExdateUpdateThisAndFutureChangeDtstart
1298      * 
1299      * @see 0007690: allow to update the whole series / thisandfuture when updating recur exceptions
1300      */
1301     public function testExdateUpdateThisAndFutureChangeDtstart()
1302     {
1303         $events = $this->testCreateRecurException();
1304         $exception = $this->_getException($events, 1);
1305         $exception['dtstart'] = '2009-04-01 08:00:00';
1306         $exception['dtend'] = '2009-04-01 08:15:00';
1307         
1308         $updatedEvent = $this->_uit->saveEvent($exception, FALSE, Calendar_Model_Event::RANGE_THISANDFUTURE);
1309         
1310         $search = $this->_uit->searchEvents($events['filter'], NULL);
1311         foreach ($search['results'] as $event) {
1312             if ($event['dtstart'] >= $updatedEvent['dtstart']) {
1313                 $this->assertContains('08:00:00', $event['dtstart'], 'wrong dtstart: ' . print_r($event, TRUE));
1314                 $this->assertContains('08:15:00', $event['dtend']);
1315             } else {
1316                 $this->assertContains('06:00:00', $event['dtstart'], 'wrong dtstart: ' . print_r($event, TRUE));
1317                 $this->assertContains('06:15:00', $event['dtend']);
1318             }
1319         }
1320     }
1321     
1322     /**
1323      * testExdateUpdateAllWithModlog
1324      * - change base event, then update all
1325      * 
1326      * @see 0007690: allow to update the whole series / thisandfuture when updating recur exceptions
1327      * @see 0009340: fix Calendar_JsonTests::testExdateUpdateAllWithModlog*
1328      */
1329     public function testExdateUpdateAllWithModlog()
1330     {
1331         $this->markTestSkipped('this test is broken: see 0009340: fix Calendar_JsonTests::testExdateUpdateAllWithModlog*');
1332         
1333         $events = $this->testCreateRecurException();
1334         $baseEvent = $events['results'][0];
1335         $exception = $this->_getException($events, 1);
1336         
1337         $baseEvent['summary'] = 'Get up, lazyboy!';
1338         $baseEvent = $this->_uit->saveEvent($baseEvent);
1339         sleep(1);
1340         
1341         $exception['summary'] = 'new summary';
1342         $updatedEvent = $this->_uit->saveEvent($exception, FALSE, Calendar_Model_Event::RANGE_ALL);
1343         
1344         $search = $this->_uit->searchEvents($events['filter'], NULL);
1345         foreach ($search['results'] as $event) {
1346             if ($event['dtstart'] == $updatedEvent['dtstart']) {
1347                 $this->assertEquals('new summary', $event['summary'], 'Recur exception should have the new summary');
1348             } else {
1349                 $this->assertEquals('Get up, lazyboy!', $event['summary'], 'Wrong summary in base/recur event: ' . print_r($event, TRUE));
1350             }
1351         }
1352     }
1353
1354     /**
1355      * testExdateUpdateAllWithModlogAddAttender
1356      * - change base event, then update all
1357      * 
1358      * @see 0007690: allow to update the whole series / thisandfuture when updating recur exceptions
1359      * @see 0007826: add attendee changes to modlog
1360      * @see 0009340: fix Calendar_JsonTests::testExdateUpdateAllWithModlog*
1361      */
1362     public function testExdateUpdateAllWithModlogAddAttender()
1363     {
1364         $this->markTestSkipped('0009340: fix Calendar_JsonTests::testExdateUpdateAllWithModlogAddAttender');
1365         
1366         $events = $this->testCreateRecurException();
1367         $baseEvent = $events['results'][0];
1368         $exception = $this->_getException($events, 1);
1369         
1370         // add new attender
1371         $baseEvent['attendee'][] = $this->_getUserTypeAttender();
1372         $baseEvent = $this->_uit->saveEvent($baseEvent);
1373         $this->assertEquals(3, count($baseEvent['attendee']), 'Attendee count mismatch in baseEvent: ' . print_r($baseEvent, TRUE));
1374         sleep(1);
1375         
1376         // check recent changes (needs to contain attendee change)
1377         $exdate = Calendar_Controller_Event::getInstance()->get($exception['id']);
1378         $recentChanges = Tinebase_Timemachine_ModificationLog::getInstance()->getModifications('Calendar', $baseEvent['id'], NULL, 'Sql', $exdate->creation_time);
1379         $this->assertGreaterThan(2, count($recentChanges), 'Did not get all recent changes: ' . print_r($recentChanges->toArray(), TRUE));
1380         $this->assertTrue(in_array('attendee', $recentChanges->modified_attribute), 'Attendee change missing: ' . print_r($recentChanges->toArray(), TRUE));
1381         
1382         $exception['attendee'][] = $this->_getUserTypeAttender('unittestnotexists@example.com');
1383         $updatedEvent = $this->_uit->saveEvent($exception, FALSE, Calendar_Model_Event::RANGE_ALL);
1384         
1385         $search = $this->_uit->searchEvents($events['filter'], NULL);
1386         foreach ($search['results'] as $event) {
1387             if ($event['dtstart'] == $updatedEvent['dtstart']) {
1388                 $this->assertEquals(3, count($event['attendee']), 'Attendee count mismatch in exdate: ' . print_r($event, TRUE));
1389             } else {
1390                 $this->assertEquals(4, count($event['attendee']), 'Attendee count mismatch: ' . print_r($event, TRUE));
1391             }
1392         }
1393     }
1394
1395     /**
1396      * testConcurrentAttendeeChangeAdd
1397      * 
1398      * @see 0008078: concurrent attendee change should be merged
1399      */
1400     public function testConcurrentAttendeeChangeAdd()
1401     {
1402         $eventData = $this->testCreateEvent();
1403         $numAttendee = count($eventData['attendee']);
1404         $eventData['attendee'][$numAttendee] = array(
1405             'user_id' => $this->_getPersonasContacts('pwulf')->getId(),
1406         );
1407         $this->_uit->saveEvent($eventData);
1408         
1409         $eventData['attendee'][$numAttendee] = array(
1410             'user_id' => $this->_getPersonasContacts('jsmith')->getId(),
1411         );
1412         $event = $this->_uit->saveEvent($eventData);
1413         
1414         $this->assertEquals(4, count($event['attendee']), 'both new attendee (pwulf + jsmith) should be added: ' . print_r($event['attendee'], TRUE));
1415     }
1416
1417     /**
1418      * testConcurrentAttendeeChangeRemove
1419      * 
1420      * @see 0008078: concurrent attendee change should be merged
1421      */
1422     public function testConcurrentAttendeeChangeRemove()
1423     {
1424         $eventData = $this->testCreateEvent();
1425         $currentAttendee = $eventData['attendee'];
1426         unset($eventData['attendee'][1]);
1427         $event = $this->_uit->saveEvent($eventData);
1428         
1429         $eventData['attendee'] = $currentAttendee;
1430         $numAttendee = count($eventData['attendee']);
1431         $eventData['attendee'][$numAttendee] = array(
1432             'user_id' => $this->_getPersonasContacts('pwulf')->getId(),
1433         );
1434         $event = $this->_uit->saveEvent($eventData);
1435         
1436         $this->assertEquals(2, count($event['attendee']), 'one attendee should added and one removed: ' . print_r($event['attendee'], TRUE));
1437     }
1438
1439     /**
1440      * testConcurrentAttendeeChangeUpdate
1441      * 
1442      * @see 0008078: concurrent attendee change should be merged
1443      */
1444     public function testConcurrentAttendeeChangeUpdate()
1445     {
1446         $eventData = $this->testCreateEvent();
1447         $currentAttendee = $eventData['attendee'];
1448         $adminIndex = ($eventData['attendee'][0]['user_id']['n_fn'] === 'Susan Clever') ? 1 : 0;
1449         $eventData['attendee'][$adminIndex]['status'] = Calendar_Model_Attender::STATUS_TENTATIVE;
1450         $event = $this->_uit->saveEvent($eventData);
1451         
1452         $loggedMods = Tinebase_Timemachine_ModificationLog::getInstance()->getModificationsBySeq(
1453             Tinebase_Application::getInstance()->getApplicationByName('Calendar')->getId(),
1454             new Calendar_Model_Attender($eventData['attendee'][$adminIndex]), 2);
1455         $this->assertEquals(1, count($loggedMods), 'attender modification has not been logged');
1456         
1457         $eventData['attendee'] = $currentAttendee;
1458         $scleverIndex = ($adminIndex === 1) ? 0 : 1;
1459         $attendeeBackend = new Calendar_Backend_Sql_Attendee();
1460         $eventData['attendee'][$scleverIndex]['status_authkey'] = $attendeeBackend->get($eventData['attendee'][$scleverIndex]['id'])->status_authkey;
1461         $eventData['attendee'][$scleverIndex]['status'] = Calendar_Model_Attender::STATUS_TENTATIVE;
1462         $event = $this->_uit->saveEvent($eventData);
1463
1464         foreach ($event['attendee'] as $attender) {
1465             $this->assertEquals(Calendar_Model_Attender::STATUS_TENTATIVE, $attender['status'], 'both attendee status should be TENTATIVE: ' . print_r($attender, TRUE));
1466         }
1467     }
1468
1469     /**
1470      * testFreeBusyCheckForExdates
1471      * 
1472      * @see 0008464: freebusy check does not work when creating recur exception
1473      */
1474     public function testFreeBusyCheckForExdates()
1475     {
1476         $events = $this->testCreateRecurException();
1477         $exception = $this->_getException($events, 1);
1478         
1479         $anotherEvent = $this->_getEvent(TRUE);
1480         $anotherEvent = $this->_uit->saveEvent($anotherEvent->toArray());
1481         
1482         $exception['dtstart'] = $anotherEvent['dtstart'];
1483         $exception['dtend'] = $anotherEvent['dtend'];
1484         
1485         try {
1486             $event = $this->_uit->saveEvent($exception, TRUE);
1487             $this->fail('Calendar_Exception_AttendeeBusy expected when saving exception: ' . print_r($exception, TRUE));
1488         } catch (Calendar_Exception_AttendeeBusy $ceab) {
1489             $this->assertEquals('Calendar_Exception_AttendeeBusy', get_class($ceab));
1490         }
1491     }
1492     
1493     /**
1494      * testAddAttachmentToRecurSeries
1495      * 
1496      * @see 0005024: allow to attach external files to records
1497      */
1498     public function testAddAttachmentToRecurSeries()
1499     {
1500         $tempFile = $this->_getTempFile();
1501         $recurSet = Tinebase_Helper::array_value('results', $this->testSearchRecuringIncludes());
1502         // update recurseries 
1503         $someRecurInstance = $recurSet[2];
1504         $someRecurInstance['attachments'] = array(array('tempFile' => array('id' => $tempFile->getId())));
1505         $someRecurInstance['seq'] = 2;
1506         $this->_uit->updateRecurSeries($someRecurInstance, FALSE, FALSE);
1507         
1508         $searchResultData = $this->_searchRecurSeries($recurSet[0]);
1509         foreach ($searchResultData['results'] as $recurInstance) {
1510             $this->assertTrue(isset($recurInstance['attachments']), 'no attachments found in event: ' . print_r($recurInstance, TRUE));
1511             $this->assertEquals(1, count($recurInstance['attachments']));
1512             $attachment = $recurInstance['attachments'][0];
1513             $this->assertEquals('text/plain', $attachment['contenttype'], print_r($attachment, TRUE));
1514         }
1515     }
1516     
1517     /**
1518      * checks if manipulated dtend and dtstart gets set to the correct values on creating or updating an event
1519      * 
1520      * @see 0009696: time is not grayed out for all-day events
1521      */
1522     public function testWholedayEventTimes()
1523     {
1524         $event = $this->_getEvent(TRUE);
1525         $event->is_all_day_event = TRUE;
1526         
1527         $event = Calendar_Controller_Event::getInstance()->create($event);
1528         $event->setTimezone(Tinebase_Core::getUserTimezone());
1529         
1530         $this->assertEquals('00:00:00', $event->dtstart->format('H:i:s'));
1531         $this->assertEquals('23:59:59', $event->dtend->format('H:i:s'));
1532         
1533         $event->dtstart = Tinebase_DateTime::now();
1534         $event->dtend   = Tinebase_DateTime::now()->addHour(1);
1535         
1536         $event = Calendar_Controller_Event::getInstance()->update($event);
1537         $event->setTimezone(Tinebase_Core::getUserTimezone());
1538         
1539         $this->assertEquals('00:00:00', $event->dtstart->format('H:i:s'));
1540         $this->assertEquals('23:59:59', $event->dtend->format('H:i:s'));
1541     }
1542     
1543      /**
1544      * testAttendeeChangeQuantityToInvalid
1545      * 
1546      * @see 9630: sanitize attender quantity
1547      */
1548     public function testAttendeeChangeQuantityToInvalid()
1549     {
1550         $eventData = $this->testCreateEvent();
1551         $currentAttendee = $eventData['attendee'];
1552         $eventData['attendee'][1]['quantity'] = '';
1553         $event = $this->_uit->saveEvent($eventData);
1554         $this->assertEquals(1, $event['attendee'][1]['quantity'], 'The invalid quantity should be saved as 1');
1555     }
1556
1557     /**
1558      * trigger caldav import by json frontend
1559      * 
1560      * @todo use mock as fallback (if server can not be reached by curl)
1561      * @todo get servername from unittest config / skip or mock if no servername found
1562      */
1563     public function testCalDAVImport()
1564     {
1565         // Skip if tine20.com.local could not be resolved
1566         if (gethostbyname('tine20.com.local') == 'tine20.com.local') {
1567             $this->markTestSkipped('Can\'t perform test, because instance is not reachable.');
1568         }
1569
1570         $this->_testNeedsTransaction();
1571         
1572         $event = $this->testCreateEvent(/* $now = */ true);
1573         
1574         $fe = new Calendar_Frontend_Json();
1575         $testUserCredentials = TestServer::getInstance()->getTestCredentials();
1576         $fe->importRemoteEvents(
1577             'http://tine20.com.local/calendars/' . Tinebase_Core::getUser()->contact_id . '/' . $event['container_id']['id'],
1578             Tinebase_Model_Import::INTERVAL_DAILY,
1579             array(
1580                 'container_id'          => 'remote_caldav_calendar',
1581                 'sourceType'            => 'remote_caldav',
1582                 'importFileByScheduler' => false,
1583                 'allowDuplicateEvents'  => true,
1584                 'username'              => $testUserCredentials['username'],
1585                 'password'              => $testUserCredentials['password'],
1586             ));
1587
1588         $importScheduler = Tinebase_Controller_ScheduledImport::getInstance();
1589         $record = $importScheduler->runNextScheduledImport();
1590
1591         $container = Tinebase_Container::getInstance()->getContainerByName('Calendar', 'remote_caldav_calendar', Tinebase_Model_Container::TYPE_PERSONAL, Tinebase_Core::getUser()->getId());
1592         $this->_testCalendars[] = $container;
1593         $this->assertTrue($container instanceof Tinebase_Model_Container, 'Container was not created');
1594
1595         $this->assertNotEquals($record, null, 'The import could not start!');
1596         
1597         $filter = $this->_getEventFilterArray($container->getId());
1598         $result = $this->_uit->searchEvents($filter, array());
1599         $this->assertEquals(1, $result['totalcount']);
1600     }
1601     
1602     /**
1603      * testGetRelations
1604      * 
1605      * @see 0009542: load event relations on demand
1606      */
1607     public function testGetRelations()
1608     {
1609         $contact = Addressbook_Controller_Contact::getInstance()->create(new Addressbook_Model_Contact(array(
1610             'n_family' => 'Contact for relations test'
1611         )));
1612         $eventData = $this->_getEvent()->toArray();
1613         $eventData['relations'] = array(
1614             array(
1615                 'own_model' => 'Calendar_Model_Event',
1616                 'own_backend' => 'Sql',
1617                 'own_id' => 0,
1618                 'own_degree' => Tinebase_Model_Relation::DEGREE_SIBLING,
1619                 'type' => '',
1620                 'related_backend' => 'Sql',
1621                 'related_id' => $contact->getId(),
1622                 'related_model' => 'Addressbook_Model_Contact',
1623                 'remark' => NULL,
1624             ));
1625         $event = $this->_uit->saveEvent($eventData);
1626
1627         $tfj = new Tinebase_Frontend_Json();
1628         $relations = $tfj->getRelations('Calendar_Model_Event', $event['id']);
1629
1630         $this->assertEquals(1, $relations['totalcount']);
1631         $this->assertEquals($contact->n_fn, $relations['results'][0]['related_record']['n_family'], print_r($relations['results'], true));
1632     }
1633 }