0011590: improve concurrent update check performance
[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      * search event with alarm
342      */
343     public function testSearchEventsWithAlarm()
344     {
345         $eventData = $this->_getEventWithAlarm(TRUE)->toArray();
346         $persistentEventData = $this->_uit->saveEvent($eventData);
347         
348         $searchResultData = $this->_uit->searchEvents($this->_getEventFilterArray(), array());
349         $this->assertTrue(! empty($searchResultData['results']));
350         $resultEventData = $searchResultData['results'][0];
351         
352         $this->_assertJsonEvent($persistentEventData, $resultEventData, 'failed to search event with alarm');
353     }
354     
355     /**
356      * testSetAttenderStatus
357      */
358     public function testSetAttenderStatus()
359     {
360         $eventData = $this->testCreateEvent();
361         $numAttendee = count($eventData['attendee']);
362         $eventData['attendee'][$numAttendee] = array(
363             'user_id' => $this->_getPersonasContacts('pwulf')->getId(),
364         );
365         
366         $updatedEventData = $this->_uit->saveEvent($eventData);
367         $pwulf = $this->_findAttender($updatedEventData['attendee'], 'pwulf');
368         
369         // he he, we don't have his authkey, cause json class sorts it out due to rights restrictions.
370         $attendeeBackend = new Calendar_Backend_Sql_Attendee();
371         $pwulf['status_authkey'] = $attendeeBackend->get($pwulf['id'])->status_authkey;
372         
373         $updatedEventData['container_id'] = $updatedEventData['container_id']['id'];
374         
375         $pwulf['status'] = Calendar_Model_Attender::STATUS_ACCEPTED;
376         $this->_uit->setAttenderStatus($updatedEventData, $pwulf, $pwulf['status_authkey']);
377         
378         $loadedEventData = $this->_uit->getEvent($eventData['id']);
379         $loadedPwulf = $this->_findAttender($loadedEventData['attendee'], 'pwulf');
380         $this->assertEquals(Calendar_Model_Attender::STATUS_ACCEPTED, $loadedPwulf['status']);
381     }
382     
383     /**
384      * testCreateRecurEvent
385      */
386     public function testCreateRecurEvent()
387     {
388         $eventData = $this->testCreateEvent();
389         $eventData['rrule'] = array(
390             'freq'     => 'WEEKLY',
391             'interval' => 1,
392             'byday'    => 'WE'
393         );
394         
395         $updatedEventData = $this->_uit->saveEvent($eventData);
396         $this->assertTrue(is_array($updatedEventData['rrule']));
397
398         return $updatedEventData;
399     }
400
401     /**
402      * testCreateRecurEventYearly
403      * 
404      * @see 0010610: yearly event is not shown in week view
405      */
406     public function testCreateRecurEventYearly()
407     {
408         $eventData = $this->_getEvent()->toArray();
409         $eventData['is_all_day_event'] = true;
410         $eventData['dtstart'] = '2015-01-04 00:00:00';
411         $eventData['dtend'] = '2015-01-04 23:59:59';
412         $eventData['rrule'] = array(
413             'freq'       => 'YEARLY',
414             'interval'   => 1,
415             'bymonthday' => 4,
416             'bymonth'    => 1,
417         );
418         
419         $updatedEventData = $this->_uit->saveEvent($eventData);
420         $this->assertTrue(is_array($updatedEventData['rrule']));
421         
422         $filter = array(
423             array('field' => 'container_id', 'operator' => 'equals', 'value' => $eventData['container_id']),
424             array('field' => 'period', 'operator' => 'within', 'value' =>
425                 array("from" => '2014-12-29 00:00:00', "until" => '2015-01-05 00:00:00')
426             )
427         );
428         $searchResultData = $this->_uit->searchEvents($filter, array());
429         $this->assertEquals(1, $searchResultData['totalcount'], 'event not found');
430     }
431     
432     /**
433      * testCreateRecurEventWithRruleUntil
434      * 
435      * @see 0008906: rrule_until is saved in usertime
436      */
437     public function testCreateRecurEventWithRruleUntil()
438     {
439         $eventData = $this->testCreateRecurEvent();
440         $localMidnight = Tinebase_DateTime::now()->setTime(23,59,59)->toString();
441         $eventData['rrule']['until'] = $localMidnight;
442         //$eventData['rrule']['freq']  = 'WEEKLY';
443         
444         $updatedEventData = $this->_uit->saveEvent($eventData);
445         $this->assertGreaterThanOrEqual($localMidnight, $updatedEventData['rrule']['until']);
446         
447         // check db record
448         $calbackend = new Calendar_Backend_Sql();
449         $db = $calbackend->getAdapter();
450         $select = $db->select();
451         $select->from(array($calbackend->getTableName() => $calbackend->getTablePrefix() . $calbackend->getTableName()), array('rrule_until', 'rrule'))->limit(1);
452         $select->where($db->quoteIdentifier($calbackend->getTableName() . '.id') . ' = ?', $updatedEventData['id']);
453         
454         $stmt = $db->query($select);
455         $queryResult = $stmt->fetch();
456         
457 //         echo Tinebase_Core::getUserTimezone();
458 //         echo date_default_timezone_get();
459         
460         $midnightInUTC = new Tinebase_DateTime($queryResult['rrule_until']);
461         $this->assertEquals(Tinebase_DateTime::now()->setTime(23,59,59)->toString(), $midnightInUTC->setTimezone(Tinebase_Core::getUserTimezone(), TRUE)->toString());
462     }
463     
464     /**
465     * testSearchRecuringIncludes
466     */
467     public function testSearchRecuringIncludes()
468     {
469         $recurEvent = $this->testCreateRecurEvent();
470     
471         $from = $recurEvent['dtstart'];
472         $until = new Tinebase_DateTime($from);
473         $until->addWeek(5)->addHour(10);
474         $until = $until->get(Tinebase_Record_Abstract::ISO8601LONG);
475     
476         $filter = array(
477         array('field' => 'container_id', 'operator' => 'equals', 'value' => $this->_getTestCalendar()->getId()),
478         array('field' => 'period',       'operator' => 'within', 'value' => array('from' => $from, 'until' => $until)),
479         );
480     
481         $searchResultData = $this->_uit->searchEvents($filter, array());
482     
483         $this->assertEquals(6, $searchResultData['totalcount']);
484         
485         // test appending tags to recurring instances
486         $this->assertTrue(isset($searchResultData['results'][4]['tags'][0]), 'tags not set: ' . print_r($searchResultData['results'][4], true));
487         $this->assertEquals('phpunit-', substr($searchResultData['results'][4]['tags'][0]['name'], 0, 8));
488     
489         return $searchResultData;
490     }
491     
492     /**
493      * testSearchRecuringIncludesAndSort
494      */
495     public function testSearchRecuringIncludesAndSort()
496     {
497         $recurEvent = $this->testCreateRecurEvent();
498         
499         $from = $recurEvent['dtstart'];
500         $until = new Tinebase_DateTime($from);
501         $until->addWeek(5)->addHour(10);
502         $until = $until->get(Tinebase_Record_Abstract::ISO8601LONG);
503         
504         $filter = array(
505             array('field' => 'container_id', 'operator' => 'equals', 'value' => $this->_getTestCalendar()->getId()),
506             array('field' => 'period',       'operator' => 'within', 'value' => array('from' => $from, 'until' => $until)),
507         );
508         
509         $searchResultData = $this->_uit->searchEvents($filter, array('sort' => 'dtstart', 'dir' => 'DESC'));
510         
511         $this->assertEquals(6, $searchResultData['totalcount']);
512         
513         // check sorting
514         $this->assertEquals('2009-04-29 06:00:00', $searchResultData['results'][0]['dtstart']);
515         $this->assertEquals('2009-04-22 06:00:00', $searchResultData['results'][1]['dtstart']);
516     }
517     
518     /**
519      * testCreateRecurException
520      */
521     public function testCreateRecurException()
522     {
523         $recurSet = Tinebase_Helper::array_value('results', $this->testSearchRecuringIncludes());
524         
525         $persistentException = $recurSet[1];
526         $persistentException['summary'] = 'go sleeping';
527         
528         // create persistent exception
529         $this->_uit->createRecurException($persistentException, FALSE, FALSE);
530         
531         // create exception date
532         $updatedBaseEvent = Calendar_Controller_Event::getInstance()->getRecurBaseEvent(new Calendar_Model_Event($recurSet[2]));
533         $recurSet[2]['last_modified_time'] = $updatedBaseEvent->last_modified_time;
534         $this->_uit->createRecurException($recurSet[2], TRUE, FALSE);
535         
536         // delete all following (including this)
537         $updatedBaseEvent = Calendar_Controller_Event::getInstance()->getRecurBaseEvent(new Calendar_Model_Event($recurSet[4]));
538         $recurSet[4]['last_modified_time'] = $updatedBaseEvent->last_modified_time;
539         $this->_uit->createRecurException($recurSet[4], TRUE, TRUE);
540         
541         $from = $recurSet[0]['dtstart'];
542         $until = new Tinebase_DateTime($from);
543         $until->addWeek(5)->addHour(10);
544         $until = $until->get(Tinebase_Record_Abstract::ISO8601LONG);
545         
546         $filter = array(
547             array('field' => 'container_id', 'operator' => 'equals', 'value' => $this->_getTestCalendar()->getId()),
548             array('field' => 'period',       'operator' => 'within', 'value' => array('from' => $from, 'until' => $until)),
549         );
550         
551         $searchResultData = $this->_uit->searchEvents($filter, array('sort' => 'dtstart'));
552         
553         // we deleted one and cropped
554         $this->assertEquals(3, count($searchResultData['results']));
555         
556         $summaryMap = array();
557         foreach ($searchResultData['results'] as $event) {
558             $summaryMap[$event['dtstart']] = $event['summary'];
559         }
560         $this->assertTrue((isset($summaryMap['2009-04-01 06:00:00']) || array_key_exists('2009-04-01 06:00:00', $summaryMap)));
561         $this->assertEquals($persistentException['summary'], $summaryMap['2009-04-01 06:00:00']);
562         
563         return $searchResultData;
564     }
565     
566     /**
567      * testCreateRecurExceptionWithOtherUser
568      * 
569      * @see 0008172: displaycontainer_id not set when recur exception is created
570      */
571     public function testCreateRecurExceptionWithOtherUser()
572     {
573         $recurSet = Tinebase_Helper::array_value('results', $this->testSearchRecuringIncludes());
574         
575         // create persistent exception (just status update)
576         $persistentException = $recurSet[1];
577         $scleverAttender = $this->_findAttender($persistentException['attendee'], 'sclever');
578         $attendeeBackend = new Calendar_Backend_Sql_Attendee();
579         $status_authkey = $attendeeBackend->get($scleverAttender['id'])->status_authkey;
580         $scleverAttender['status'] = Calendar_Model_Attender::STATUS_ACCEPTED;
581         $scleverAttender['status_authkey'] = $status_authkey;
582         foreach ($persistentException['attendee'] as $key => $attender) {
583             if ($attender['id'] === $scleverAttender['id']) {
584                 $persistentException['attendee'][$key] = $scleverAttender;
585                 break;
586             }
587         }
588         
589         // sclever has only READ grant
590         Tinebase_Container::getInstance()->setGrants($this->_getTestCalendar(), new Tinebase_Record_RecordSet('Tinebase_Model_Grants', array(array(
591             'account_id'    => $this->_getTestUser()->getId(),
592             'account_type'  => 'user',
593             Tinebase_Model_Grants::GRANT_READ     => true,
594             Tinebase_Model_Grants::GRANT_ADD      => true,
595             Tinebase_Model_Grants::GRANT_EDIT     => true,
596             Tinebase_Model_Grants::GRANT_DELETE   => true,
597             Tinebase_Model_Grants::GRANT_PRIVATE  => true,
598             Tinebase_Model_Grants::GRANT_ADMIN    => true,
599             Tinebase_Model_Grants::GRANT_FREEBUSY => true,
600         ), array(
601             'account_id'    => $this->_getPersona('sclever')->getId(),
602             'account_type'  => 'user',
603             Tinebase_Model_Grants::GRANT_READ     => true,
604             Tinebase_Model_Grants::GRANT_FREEBUSY => true,
605         ))), TRUE);
606         
607         $unittestUser = Tinebase_Core::getUser();
608         Tinebase_Core::set(Tinebase_Core::USER, $this->_getPersona('sclever'));
609         
610         // create persistent exception
611         $createdException = $this->_uit->createRecurException($persistentException, FALSE, FALSE);
612         Tinebase_Core::set(Tinebase_Core::USER, $this->_originalTestUser);
613         
614         $sclever = $this->_findAttender($createdException['attendee'], 'sclever');
615         $defaultCal = $this->_getPersonasDefaultCals('sclever');
616         $this->assertEquals('Susan Clever', $sclever['user_id']['n_fn']);
617         $this->assertEquals(Calendar_Model_Attender::STATUS_ACCEPTED, $sclever['status'], 'status mismatch: ' . print_r($sclever, TRUE));
618         $this->assertTrue(is_array($sclever['displaycontainer_id']));
619         $this->assertEquals($defaultCal['id'], $sclever['displaycontainer_id']['id']);
620     }
621     
622     /**
623      * testUpdateRecurSeries
624      */
625     public function testUpdateRecurSeries()
626     {
627         $recurSet = Tinebase_Helper::array_value('results', $this->testSearchRecuringIncludes());
628         
629         $persistentException = $recurSet[1];
630         $persistentException['summary'] = 'go sleeping';
631         $persistentException['dtstart'] = '2009-04-01 20:00:00';
632         $persistentException['dtend']   = '2009-04-01 20:30:00';
633         
634         // create persistent exception
635         $recurResult = $this->_uit->createRecurException($persistentException, FALSE, FALSE);
636         
637         // update recurseries 
638         $someRecurInstance = $recurSet[2];
639         $someRecurInstance['summary'] = 'go fishing';
640         $someRecurInstance['dtstart'] = '2009-04-08 10:00:00';
641         $someRecurInstance['dtend']   = '2009-04-08 12:30:00';
642         
643         $someRecurInstance['seq'] = 3;
644         $this->_uit->updateRecurSeries($someRecurInstance, FALSE, FALSE);
645         
646         $searchResultData = $this->_searchRecurSeries($recurSet[0]);
647         $this->assertEquals(6, count($searchResultData['results']));
648         
649         $summaryMap = array();
650         foreach ($searchResultData['results'] as $event) {
651             $summaryMap[$event['dtstart']] = $event['summary'];
652         }
653         
654         $this->assertTrue((isset($summaryMap['2009-04-01 20:00:00']) || array_key_exists('2009-04-01 20:00:00', $summaryMap)));
655         $this->assertEquals('go sleeping', $summaryMap['2009-04-01 20:00:00']);
656         
657         $fishings = array_keys($summaryMap, 'go fishing');
658         $this->assertEquals(5, count($fishings));
659         foreach ($fishings as $dtstart) {
660             $this->assertEquals('10:00:00', substr($dtstart, -8), 'all fishing events should start at 10:00');
661         }
662     }
663     
664     /**
665      * search updated recur set
666      * 
667      * @param array $firstInstance
668      * @return array
669      */
670     protected function _searchRecurSeries($firstInstance)
671     {
672         $from = $firstInstance['dtstart'];
673         $until = new Tinebase_DateTime($from);
674         $until->addWeek(5)->addHour(10);
675         $until = $until->get(Tinebase_Record_Abstract::ISO8601LONG);
676         
677         $filter = array(
678             array('field' => 'container_id', 'operator' => 'equals', 'value' => $this->_getTestCalendar()->getId()),
679             array('field' => 'period',       'operator' => 'within', 'value' => array('from' => $from, 'until' => $until)),
680         );
681         
682         return $this->_uit->searchEvents($filter, array());
683     }
684     
685     /**
686      * testUpdateRecurExceptionsFromSeriesOverDstMove
687      * 
688      * @todo implement
689      */
690     public function testUpdateRecurExceptionsFromSeriesOverDstMove()
691     {
692         /*
693          * 1. create recur event 1 day befor dst move
694          * 2. create an exception and exdate
695          * 3. move dtstart from 1 over dst boundary
696          * 4. test recurid and exdate by calculating series
697          */
698     }
699     
700     /**
701      * testDeleteRecurSeries
702      */
703     public function testDeleteRecurSeries()
704     {
705         $recurSet = Tinebase_Helper::array_value('results', $this->testSearchRecuringIncludes());
706         
707         $persistentException = $recurSet[1];
708         $persistentException['summary'] = 'go sleeping';
709         
710         // create persistent exception
711         $this->_uit->createRecurException($persistentException, FALSE, FALSE);
712         
713         // delete recurseries 
714         $someRecurInstance = $persistentException = $recurSet[2];
715         $this->_uit->deleteRecurSeries($someRecurInstance);
716         
717         $from = $recurSet[0]['dtstart'];
718         $until = new Tinebase_DateTime($from);
719         $until->addWeek(5)->addHour(10);
720         $until = $until->get(Tinebase_Record_Abstract::ISO8601LONG);
721         
722         $filter = array(
723             array('field' => 'container_id', 'operator' => 'equals', 'value' => $this->_getTestCalendar()->getId()),
724             array('field' => 'period',       'operator' => 'within', 'value' => array('from' => $from, 'until' => $until)),
725         );
726         
727         $searchResultData = $this->_uit->searchEvents($filter, array());
728         
729         $this->assertEquals(0, count($searchResultData['results']));
730     }
731     
732     /**
733      * testMeAsAttenderFilter
734      */
735     public function testMeAsAttenderFilter()
736     {
737         $eventData = $this->testCreateEvent(TRUE);
738         
739         $filter = $this->_getEventFilterArray();
740         $filter[] = array('field' => 'attender'    , 'operator' => 'equals', 'value' => array(
741             'user_type' => Calendar_Model_Attender::USERTYPE_USER,
742             'user_id'   => Addressbook_Model_Contact::CURRENTCONTACT,
743         ));
744         
745         $searchResultData = $this->_uit->searchEvents($filter, array());
746         $this->assertTrue(! empty($searchResultData['results']));
747         $resultEventData = $searchResultData['results'][0];
748         
749         $this->_assertJsonEvent($eventData, $resultEventData, 'failed to filter for me as attender');
750     }
751     
752     /**
753      * testFreeBusyCleanup
754      * 
755      * @return array event data
756      */
757     public function testFreeBusyCleanup()
758     {
759         // give fb grants from sclever
760         $scleverCal = Tinebase_Container::getInstance()->getContainerById($this->_getPersonasDefaultCals('sclever'));
761         Tinebase_Container::getInstance()->setGrants($scleverCal->getId(), new Tinebase_Record_RecordSet('Tinebase_Model_Grants', array(array(
762             'account_id'    => $this->_getPersona('sclever')->getId(),
763             'account_type'  => 'user',
764             Tinebase_Model_Grants::GRANT_READ     => true,
765             Tinebase_Model_Grants::GRANT_ADD      => true,
766             Tinebase_Model_Grants::GRANT_EDIT     => true,
767             Tinebase_Model_Grants::GRANT_DELETE   => true,
768             Tinebase_Model_Grants::GRANT_PRIVATE  => true,
769             Tinebase_Model_Grants::GRANT_ADMIN    => true,
770             Tinebase_Model_Grants::GRANT_FREEBUSY => true,
771         ), array(
772             'account_id'    => $this->_getTestUser()->getId(),
773             'account_type'  => 'user',
774             Tinebase_Model_Grants::GRANT_FREEBUSY => true,
775         ))), TRUE);
776         
777         Tinebase_Core::set(Tinebase_Core::USER, $this->_getPersona('sclever'));
778         $eventData = $this->_getEvent()->toArray();
779         unset($eventData['organizer']);
780         $eventData['container_id'] = $scleverCal->getId();
781         $eventData['attendee'] = array(array(
782             'user_id' => $this->_getPersonasContacts('sclever')->getId()
783         ));
784         $eventData['organizer'] = $this->_getPersonasContacts('sclever')->getId();
785         $eventData = $this->_uit->saveEvent($eventData);
786         $filter = $this->_getEventFilterArray($this->_getPersonasDefaultCals('sclever')->getId());
787         $filter[] = array('field' => 'summary', 'operator' => 'equals', 'value' => 'Wakeup');
788         $searchResultData = $this->_uit->searchEvents($filter, array());
789         $this->assertTrue(! empty($searchResultData['results']), 'expected event in search result (search by sclever): ' 
790             . print_r($eventData, TRUE) . 'search filter: ' . print_r($filter, TRUE));
791         
792         Tinebase_Core::set(Tinebase_Core::USER, $this->_getTestUser());
793         $searchResultData = $this->_uit->searchEvents($filter, array());
794         $this->assertTrue(! empty($searchResultData['results']), 'expected (freebusy cleanup) event in search result: ' 
795             . print_r($eventData, TRUE) . 'search filter: ' . print_r($filter, TRUE));
796         $eventData = $searchResultData['results'][0];
797         
798         $this->assertFalse((isset($eventData['summary']) || array_key_exists('summary', $eventData)), 'summary not empty: ' . print_r($eventData, TRUE));
799         $this->assertFalse((isset($eventData['description']) || array_key_exists('description', $eventData)), 'description not empty');
800         $this->assertFalse((isset($eventData['tags']) || array_key_exists('tags', $eventData)), 'tags not empty');
801         $this->assertFalse((isset($eventData['notes']) || array_key_exists('notes', $eventData)), 'notes not empty');
802         $this->assertFalse((isset($eventData['attendee']) || array_key_exists('attendee', $eventData)), 'attendee not empty');
803         $this->assertFalse((isset($eventData['organizer']) || array_key_exists('organizer', $eventData)), 'organizer not empty');
804         $this->assertFalse((isset($eventData['alarms']) || array_key_exists('alarms', $eventData)), 'alarms not empty');
805         
806         return $eventData;
807     }
808
809     /**
810      * testFreeBusyCleanupOfNotes
811      * 
812      * @see 0009918: shared (only free/busy) calendar is showing event details within the history tab.
813      */
814     public function testFreeBusyCleanupOfNotes()
815     {
816         $eventData = $this->testFreeBusyCleanup();
817         
818         $tinebaseJson = new Tinebase_Frontend_Json();
819         $filter = array(array(
820             'field' => "record_model",
821             'operator' => "equals",
822             'value' => "Calendar_Model_Event"
823         ), array(
824             'field' => 'record_id',
825             'operator' => 'equals',
826             'value' => $eventData['id']
827         ));
828         $notes = $tinebaseJson->searchNotes($filter, array());
829         
830         $this->assertEquals(0, $notes['totalcount'], 'should not find any notes of record');
831         $this->assertEquals(0, count($notes['results']), 'should not find any notes of record');
832     }
833     
834     /**
835      * test deleting container and the containing events
836      * #6704: events do not disappear when shared calendar got deleted
837      * https://forge.tine20.org/mantisbt/view.php?id=6704
838      */
839     public function testDeleteContainerAndEvents()
840     {
841         $fe = new Tinebase_Frontend_Json_Container();
842         $container = $fe->addContainer('Calendar', 'testdeletecontacts', Tinebase_Model_Container::TYPE_SHARED, '');
843         // test if model is set automatically
844         $this->assertEquals($container['model'], 'Calendar_Model_Event');
845         
846         $date = new Tinebase_DateTime();
847         $event = new Calendar_Model_Event(array(
848             'dtstart' => $date,
849             'dtend'    => $date->subHour(1),
850             'summary' => 'bla bla',
851             'class'    => 'PUBLIC',
852             'transp'    => 'OPAQUE',
853             'container_id' => $container['id'],
854             'organizer' => Tinebase_Core::getUser()->contact_id
855             ));
856         $event = Calendar_Controller_Event::getInstance()->create($event);
857         $this->assertEquals($container['id'], $event->container_id);
858         
859         $fe->deleteContainer($container['id']);
860         
861         $e = new Exception('dummy');
862         
863         $cb = new Calendar_Backend_Sql();
864         $deletedEvent = $cb->get($event->getId(), true);
865         // record should be deleted
866         $this->assertEquals($deletedEvent->is_deleted, 1);
867         
868         try {
869             Calendar_Controller_Event::getInstance()->get($event->getId(), $container['id']);
870             $this->fail('The expected exception was not thrown');
871         } catch (Tinebase_Exception_NotFound $e) {
872             // ok;
873         }
874         // record should not be found
875         $this->assertEquals($e->getMessage(), 'Calendar_Model_Event record with id '.$event->getId().' not found!');
876     }
877     
878     /**
879      * compare expected event data with test event
880      *
881      * @param array $expectedEventData
882      * @param array $eventData
883      * @param string $msg
884      */
885     protected function _assertJsonEvent($expectedEventData, $eventData, $msg)
886     {
887         $this->assertEquals($expectedEventData['summary'], $eventData['summary'], $msg . ': failed to create/load event');
888         
889         // assert effective grants are set
890         $this->assertEquals((bool) $expectedEventData[Tinebase_Model_Grants::GRANT_EDIT], (bool) $eventData[Tinebase_Model_Grants::GRANT_EDIT], $msg . ': effective grants mismatch');
891         // container, assert attendee, tags
892         $this->assertEquals($expectedEventData['dtstart'], $eventData['dtstart'], $msg . ': dtstart mismatch');
893         $this->assertTrue(is_array($eventData['container_id']), $msg . ': failed to "resolve" container');
894         $this->assertTrue(is_array($eventData['container_id']['account_grants']), $msg . ': failed to "resolve" container account_grants');
895         $this->assertGreaterThan(0, count($eventData['attendee']));
896         $this->assertEquals(count($eventData['attendee']), count($expectedEventData['attendee']), $msg . ': failed to append attendee');
897         $this->assertTrue(is_array($eventData['attendee'][0]['user_id']), $msg . ': failed to resolve attendee user_id');
898         // NOTE: due to sorting isshues $eventData['attendee'][0] may be a non resolvable container (due to rights restrictions)
899         $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');
900         $this->assertEquals(count($expectedEventData['tags']), count($eventData['tags']), $msg . ': failed to append tag');
901         $this->assertEquals(count($expectedEventData['notes']), count($eventData['notes']), $msg . ': failed to create note or wrong number of notes');
902         
903         if ((isset($expectedEventData['alarms']) || array_key_exists('alarms', $expectedEventData))) {
904             $this->assertTrue((isset($eventData['alarms']) || array_key_exists('alarms', $eventData)), ': failed to create alarms');
905             $this->assertEquals(count($expectedEventData['alarms']), count($eventData['alarms']), $msg . ': failed to create correct number of alarms');
906             if (count($expectedEventData['alarms']) > 0) {
907                 $this->assertTrue((isset($eventData['alarms'][0]['minutes_before']) || array_key_exists('minutes_before', $eventData['alarms'][0])));
908             }
909         }
910     }
911     
912     /**
913      * find attender 
914      *
915      * @param array $attendeeData
916      * @param string $name
917      * @return array
918      */
919     protected function _findAttender($attendeeData, $name) {
920         $attenderData = false;
921         $searchedId = $this->_getPersonasContacts($name)->getId();
922         
923         foreach ($attendeeData as $key => $attender) {
924             if ($attender['user_type'] == Calendar_Model_Attender::USERTYPE_USER) {
925                 if (is_array($attender['user_id']) && (isset($attender['user_id']['id']) || array_key_exists('id', $attender['user_id']))) {
926                     if ($attender['user_id']['id'] == $searchedId) {
927                         $attenderData = $attendeeData[$key];
928                     }
929                 }
930             }
931         }
932         
933         return $attenderData;
934     }
935     
936     /**
937      * test filter with hidden group -> should return empty result
938      * 
939      * @see 0006934: setting a group that is hidden from adb as attendee filter throws exception
940      */
941     public function testHiddenGroupFilter()
942     {
943         $hiddenGroup = new Tinebase_Model_Group(array(
944             'name'          => 'hiddengroup',
945             'description'   => 'hidden group',
946             'visibility'     => Tinebase_Model_Group::VISIBILITY_HIDDEN
947         ));
948         $hiddenGroup = Admin_Controller_Group::getInstance()->create($hiddenGroup);
949         $this->_groupIdsToDelete[] = $hiddenGroup->getId();
950         
951         $filter = array(array(
952             'field'    => 'attender',
953             'operator' => 'equals',
954             'value'    => array(
955                 'user_id'   => $hiddenGroup->list_id,
956                 'user_type' => 'group',
957             ),
958         ));
959         $result = $this->_uit->searchEvents($filter, array());
960         $this->assertEquals(0, $result['totalcount']);
961     }
962     
963     /**
964      * testExdateDeleteAll
965      * 
966      * @see 0007382: allow to edit / delete the whole series / thisandfuture when editing/deleting recur exceptions
967      */
968     public function testExdateDeleteAll()
969     {
970         $events = $this->testCreateRecurException();
971         $exception = $this->_getException($events);
972         $this->_uit->deleteEvents(array($exception['id']), Calendar_Model_Event::RANGE_ALL);
973         
974         $search = $this->_uit->searchEvents($events['filter'], NULL);
975         $this->assertEquals(0, $search['totalcount'], 'all events should be deleted: ' . print_r($search,TRUE));
976     }
977     
978     /**
979      * get exception from event resultset
980      * 
981      * @param array $events
982      * @param integer $index (1 = picks first, 2 = picks second, ...)
983      * @return array|NULL
984      */
985     protected function _getException($events, $index = 1)
986     {
987         $event = NULL;
988         $found = 0;
989         foreach ($events['results'] as $event) {
990             if (! empty($event['recurid'])) {
991                 $found++;
992                 if ($index === $found) {
993                     return $event;
994                 }
995             }
996         }
997         
998         return $event;
999     }
1000     
1001     /**
1002      * testExdateDeleteThis
1003      * 
1004      * @see 0007382: allow to edit / delete the whole series / thisandfuture when editing/deleting recur exceptions
1005      */
1006     public function testExdateDeleteThis()
1007     {
1008         $events = $this->testCreateRecurException();
1009         $exception = $this->_getException($events);
1010         $this->_uit->deleteEvents(array($exception['id']));
1011         
1012         $search = $this->_uit->searchEvents($events['filter'], NULL);
1013         $this->assertEquals(2, $search['totalcount'], '2 events should remain: ' . print_r($search,TRUE));
1014     }
1015     
1016     /**
1017      * testExdateDeleteThisAndFuture
1018      * 
1019      * @see 0007382: allow to edit / delete the whole series / thisandfuture when editing/deleting recur exceptions
1020      */
1021     public function testExdateDeleteThisAndFuture()
1022     {
1023         $events = $this->testCreateRecurException();
1024         $exception = $this->_getException($events, 1);
1025         $this->_uit->deleteEvents(array($exception['id']), Calendar_Model_Event::RANGE_THISANDFUTURE);
1026         
1027         $search = $this->_uit->searchEvents($events['filter'], NULL);
1028         $this->assertEquals(1, $search['totalcount'], '1 event should remain: ' . print_r($search,TRUE));
1029     }
1030     
1031     /**
1032      * assert grant handling
1033      */
1034     public function testSaveResource($grants = array('readGrant' => true,'editGrant' => true))
1035     {
1036         $resoureData = array(
1037             'name'  => Tinebase_Record_Abstract::generateUID(),
1038             'email' => Tinebase_Record_Abstract::generateUID() . '@unittest.com',
1039             'grants' => array(array_merge($grants, array(
1040                 'account_id' => Tinebase_Core::getUser()->getId(),
1041                 'account_type' => 'user'
1042             )))
1043         );
1044         
1045         $resoureData = $this->_uit->saveResource($resoureData);
1046         $this->assertTrue(is_array($resoureData['grants']), 'grants are not resolved');
1047         
1048         return $resoureData;
1049     }
1050     
1051     /**
1052      * assert only resources with read grant are returned if the user has no manage right
1053      */
1054     public function testSearchResources()
1055     {
1056         $readableResoureData = $this->testSaveResource();
1057         $nonReadableResoureData = $this->testSaveResource(array());
1058         
1059         $filer = array(
1060             array('field' => 'name', 'operator' => 'in', 'value' => array(
1061                 $readableResoureData['name'],
1062                 $nonReadableResoureData['name'],
1063             ))
1064         );
1065         
1066         $searchResultManager = $this->_uit->searchResources($filer, array());
1067         $this->assertEquals(2, count($searchResultManager['results']), 'with manage grants all records should be found');
1068         
1069         // steal manage right and reactivate container checks
1070         $roleManager = Tinebase_Acl_Roles::getInstance();
1071         $roleManager->deleteRoles(array(
1072                 $roleManager->getRoleByName('manager role')->getId(),
1073                 $roleManager->getRoleByName('admin role')->getId()
1074                 ));
1075         
1076         Calendar_Controller_Resource::getInstance()->doContainerACLChecks(TRUE);
1077         
1078         $searchResult = $this->_uit->searchResources($filer, array());
1079         $this->assertEquals(1, count($searchResult['results']), 'without manage grants only one record should be found');
1080     }
1081     
1082     /**
1083      * assert status authkey with editGrant
1084      * assert stauts can be set with editGrant
1085      * assert stauts can't be set without editGrant
1086      */
1087     public function testResourceAttendeeGrants()
1088     {
1089         $editableResoureData = $this->testSaveResource();
1090         $nonEditableResoureData = $this->testSaveResource(array('readGrant'));
1091         
1092         $event = $this->_getEvent(TRUE);
1093         $event->attendee = new Tinebase_Record_RecordSet('Calendar_Model_Attender', array(
1094             array(
1095                 'user_type'  => Calendar_Model_Attender::USERTYPE_RESOURCE,
1096                 'user_id'    => $editableResoureData['id'],
1097                 'status'     => Calendar_Model_Attender::STATUS_ACCEPTED
1098             ),
1099             array(
1100                 'user_type'  => Calendar_Model_Attender::USERTYPE_RESOURCE,
1101                 'user_id'    => $nonEditableResoureData['id'],
1102                 'status'     => Calendar_Model_Attender::STATUS_ACCEPTED
1103             )
1104         ));
1105         
1106         $persistentEventData = $this->_uit->saveEvent($event->toArray());
1107         
1108         $attendee = new Tinebase_Record_RecordSet('Calendar_Model_Attender', $persistentEventData['attendee']);
1109         $this->assertEquals(1, count($attendee->filter('status', Calendar_Model_Attender::STATUS_ACCEPTED)), 'one accepted');
1110         $this->assertEquals(1, count($attendee->filter('status', Calendar_Model_Attender::STATUS_NEEDSACTION)), 'one needs action');
1111         
1112         $this->assertEquals(1, count($attendee->filter('status_authkey', '/[a-z0-9]+/', TRUE)), 'one has authkey');
1113         
1114         $attendee->status = Calendar_Model_Attender::STATUS_TENTATIVE;
1115         $persistentEventData['attendee'] = $attendee->toArray();
1116         
1117         $updatedEventData = $this->_uit->saveEvent($persistentEventData);
1118         $attendee = new Tinebase_Record_RecordSet('Calendar_Model_Attender', $updatedEventData['attendee']);
1119         $this->assertEquals(1, count($attendee->filter('status', Calendar_Model_Attender::STATUS_TENTATIVE)), 'one tentative');
1120     }
1121
1122     /**
1123      * testExdateUpdateAllSummary
1124      * 
1125      * @see 0007690: allow to update the whole series / thisandfuture when updating recur exceptions
1126      */
1127     public function testExdateUpdateAllSummary()
1128     {
1129         $events = $this->testCreateRecurException();
1130         $exception = $this->_getException($events, 1);
1131         $exception['summary'] = 'new summary';
1132         
1133         $event = $this->_uit->saveEvent($exception, FALSE, Calendar_Model_Event::RANGE_ALL);
1134         
1135         $search = $this->_uit->searchEvents($events['filter'], NULL);
1136         foreach ($search['results'] as $event) {
1137             $this->assertEquals('new summary', $event['summary']);
1138         }
1139     }
1140
1141     /**
1142      * testExdateUpdateAllDtStart
1143      * 
1144      * @see 0007690: allow to update the whole series / thisandfuture when updating recur exceptions
1145      * 
1146      * @todo finish
1147      */
1148     public function testExdateUpdateAllDtStart()
1149     {
1150         $events = $this->testCreateRecurException();
1151         $exception = $this->_getException($events, 1);
1152         $exception['dtstart'] = '2009-04-01 08:00:00';
1153         $exception['dtend'] = '2009-04-01 08:15:00';
1154         
1155         $event = $this->_uit->saveEvent($exception, FALSE, Calendar_Model_Event::RANGE_ALL);
1156         
1157         $search = $this->_uit->searchEvents($events['filter'], NULL);
1158         foreach ($search['results'] as $event) {
1159             $this->assertContains('08:00:00', $event['dtstart'], 'wrong dtstart: ' . print_r($event, TRUE));
1160             $this->assertContains('08:15:00', $event['dtend']);
1161         }
1162     }
1163     
1164     /**
1165      * testExdateUpdateThis
1166      * 
1167      * @see 0007690: allow to update the whole series / thisandfuture when updating recur exceptions
1168      */
1169     public function testExdateUpdateThis()
1170     {
1171         $events = $this->testCreateRecurException();
1172         $exception = $this->_getException($events, 1);
1173         $exception['summary'] = 'exception';
1174         
1175         $event = $this->_uit->saveEvent($exception);
1176         $this->assertEquals('exception', $event['summary']);
1177         
1178         // check for summary (only changed in one event)
1179         $search = $this->_uit->searchEvents($events['filter'], NULL);
1180         foreach ($search['results'] as $event) {
1181             if (! empty($event['recurid']) && ! preg_match('/^fakeid/', $event['id'])) {
1182                 $this->assertEquals('exception', $event['summary'], 'summary not changed in exception: ' . print_r($event, TRUE));
1183             } else {
1184                 $this->assertEquals('Wakeup', $event['summary']);
1185             }
1186         }
1187     }
1188
1189     /**
1190      * testExdateUpdateThisAndFuture
1191      * 
1192      * @see 0007690: allow to update the whole series / thisandfuture when updating recur exceptions
1193      */
1194     public function testExdateUpdateThisAndFuture()
1195     {
1196         $events = $this->testCreateRecurException();
1197         $exception = $this->_getException($events, 1);
1198         $exception['summary'] = 'new summary';
1199         
1200         $updatedEvent = $this->_uit->saveEvent($exception, FALSE, Calendar_Model_Event::RANGE_THISANDFUTURE);
1201         $this->assertEquals('new summary', $updatedEvent['summary'], 'summary not changed in exception: ' . print_r($updatedEvent, TRUE));
1202         
1203         $search = $this->_uit->searchEvents($events['filter'], NULL);
1204         foreach ($search['results'] as $event) {
1205             if ($event['dtstart'] >= $updatedEvent['dtstart']) {
1206                 $this->assertEquals('new summary', $event['summary'], 'summary not changed in event: ' . print_r($event, TRUE));
1207             } else {
1208                 $this->assertEquals('Wakeup', $event['summary']);
1209             }
1210         }
1211     }
1212
1213     /**
1214      * testExdateUpdateThisAndFutureWithRruleUntil
1215      * 
1216      * @see 0008244: "rrule until must not be before dtstart" when updating recur exception (THISANDFUTURE)
1217      */
1218     public function testExdateUpdateThisAndFutureWithRruleUntil()
1219     {
1220         $events = $this->testCreateRecurException();
1221         
1222         $exception = $this->_getException($events, 1);
1223         $exception['dtstart'] = Tinebase_DateTime::now()->toString();
1224         $exception['dtend'] = Tinebase_DateTime::now()->addHour(1)->toString();
1225         
1226         // move exception
1227         $updatedEvent = $this->_uit->saveEvent($exception);
1228         // try to update the whole series
1229         $updatedEvent['summary'] = 'new summary';
1230         $updatedEvent = $this->_uit->saveEvent($updatedEvent, FALSE, Calendar_Model_Event::RANGE_THISANDFUTURE);
1231         
1232         $this->assertEquals('new summary', $updatedEvent['summary'], 'summary not changed in event: ' . print_r($updatedEvent, TRUE));
1233     }
1234     
1235     /**
1236      * testExdateUpdateThisAndFutureRemoveAttendee
1237      * 
1238      * @see 0007690: allow to update the whole series / thisandfuture when updating recur exceptions
1239      */
1240     public function testExdateUpdateThisAndFutureRemoveAttendee()
1241     {
1242         $events = $this->testCreateRecurException();
1243         $exception = $this->_getException($events, 1);
1244         // remove susan from attendee
1245         unset($exception['attendee'][0]);
1246         
1247         $updatedEvent = $this->_uit->saveEvent($exception, FALSE, Calendar_Model_Event::RANGE_THISANDFUTURE);
1248         $this->assertEquals(1, count($updatedEvent['attendee']), 'attender not removed from exception: ' . print_r($updatedEvent, TRUE));
1249         
1250         $search = $this->_uit->searchEvents($events['filter'], NULL);
1251         foreach ($search['results'] as $event) {
1252             if ($event['dtstart'] >= $updatedEvent['dtstart']) {
1253                 $this->assertEquals(1, count($event['attendee']), 'attendee count mismatch: ' . print_r($event, TRUE));
1254             } else {
1255                 $this->assertEquals(2, count($event['attendee']), 'attendee count mismatch: ' . print_r($event, TRUE));
1256             }
1257         }
1258     }
1259
1260     /**
1261      * testExdateUpdateAllAddAttendee
1262      * 
1263      * @see 0007690: allow to update the whole series / thisandfuture when updating recur exceptions
1264      */
1265     public function testExdateUpdateAllAddAttendee()
1266     {
1267         $events = $this->testCreateRecurException();
1268         $exception = $this->_getException($events, 1);
1269         // add new attender
1270         $exception['attendee'][] = $this->_getUserTypeAttender();
1271         
1272         $updatedEvent = $this->_uit->saveEvent($exception, FALSE, Calendar_Model_Event::RANGE_ALL);
1273         $this->assertEquals(3, count($updatedEvent['attendee']), 'attender not added to exception: ' . print_r($updatedEvent, TRUE));
1274         
1275         $search = $this->_uit->searchEvents($events['filter'], NULL);
1276         foreach ($search['results'] as $event) {
1277             $this->assertEquals(3, count($event['attendee']), 'attendee count mismatch: ' . print_r($event, TRUE));
1278         }
1279     }
1280     
1281     /**
1282      * testExdateUpdateThisAndFutureChangeDtstart
1283      * 
1284      * @see 0007690: allow to update the whole series / thisandfuture when updating recur exceptions
1285      */
1286     public function testExdateUpdateThisAndFutureChangeDtstart()
1287     {
1288         $events = $this->testCreateRecurException();
1289         $exception = $this->_getException($events, 1);
1290         $exception['dtstart'] = '2009-04-01 08:00:00';
1291         $exception['dtend'] = '2009-04-01 08:15:00';
1292         
1293         $updatedEvent = $this->_uit->saveEvent($exception, FALSE, Calendar_Model_Event::RANGE_THISANDFUTURE);
1294         
1295         $search = $this->_uit->searchEvents($events['filter'], NULL);
1296         foreach ($search['results'] as $event) {
1297             if ($event['dtstart'] >= $updatedEvent['dtstart']) {
1298                 $this->assertContains('08:00:00', $event['dtstart'], 'wrong dtstart: ' . print_r($event, TRUE));
1299                 $this->assertContains('08:15:00', $event['dtend']);
1300             } else {
1301                 $this->assertContains('06:00:00', $event['dtstart'], 'wrong dtstart: ' . print_r($event, TRUE));
1302                 $this->assertContains('06:15:00', $event['dtend']);
1303             }
1304         }
1305     }
1306     
1307     /**
1308      * testExdateUpdateAllWithModlog
1309      * - change base event, then update all
1310      * 
1311      * @see 0007690: allow to update the whole series / thisandfuture when updating recur exceptions
1312      * @see 0009340: fix Calendar_JsonTests::testExdateUpdateAllWithModlog*
1313      */
1314     public function testExdateUpdateAllWithModlog()
1315     {
1316         $this->markTestSkipped('this test is broken: see 0009340: fix Calendar_JsonTests::testExdateUpdateAllWithModlog*');
1317         
1318         $events = $this->testCreateRecurException();
1319         $baseEvent = $events['results'][0];
1320         $exception = $this->_getException($events, 1);
1321         
1322         $baseEvent['summary'] = 'Get up, lazyboy!';
1323         $baseEvent = $this->_uit->saveEvent($baseEvent);
1324         sleep(1);
1325         
1326         $exception['summary'] = 'new summary';
1327         $updatedEvent = $this->_uit->saveEvent($exception, FALSE, Calendar_Model_Event::RANGE_ALL);
1328         
1329         $search = $this->_uit->searchEvents($events['filter'], NULL);
1330         foreach ($search['results'] as $event) {
1331             if ($event['dtstart'] == $updatedEvent['dtstart']) {
1332                 $this->assertEquals('new summary', $event['summary'], 'Recur exception should have the new summary');
1333             } else {
1334                 $this->assertEquals('Get up, lazyboy!', $event['summary'], 'Wrong summary in base/recur event: ' . print_r($event, TRUE));
1335             }
1336         }
1337     }
1338
1339     /**
1340      * testExdateUpdateAllWithModlogAddAttender
1341      * - change base event, then update all
1342      * 
1343      * @see 0007690: allow to update the whole series / thisandfuture when updating recur exceptions
1344      * @see 0007826: add attendee changes to modlog
1345      * @see 0009340: fix Calendar_JsonTests::testExdateUpdateAllWithModlog*
1346      */
1347     public function testExdateUpdateAllWithModlogAddAttender()
1348     {
1349         $this->markTestSkipped('0009340: fix Calendar_JsonTests::testExdateUpdateAllWithModlogAddAttender');
1350         
1351         $events = $this->testCreateRecurException();
1352         $baseEvent = $events['results'][0];
1353         $exception = $this->_getException($events, 1);
1354         
1355         // add new attender
1356         $baseEvent['attendee'][] = $this->_getUserTypeAttender();
1357         $baseEvent = $this->_uit->saveEvent($baseEvent);
1358         $this->assertEquals(3, count($baseEvent['attendee']), 'Attendee count mismatch in baseEvent: ' . print_r($baseEvent, TRUE));
1359         sleep(1);
1360         
1361         // check recent changes (needs to contain attendee change)
1362         $exdate = Calendar_Controller_Event::getInstance()->get($exception['id']);
1363         $recentChanges = Tinebase_Timemachine_ModificationLog::getInstance()->getModifications('Calendar', $baseEvent['id'], NULL, 'Sql', $exdate->creation_time);
1364         $this->assertGreaterThan(2, count($recentChanges), 'Did not get all recent changes: ' . print_r($recentChanges->toArray(), TRUE));
1365         $this->assertTrue(in_array('attendee', $recentChanges->modified_attribute), 'Attendee change missing: ' . print_r($recentChanges->toArray(), TRUE));
1366         
1367         $exception['attendee'][] = $this->_getUserTypeAttender('unittestnotexists@example.com');
1368         $updatedEvent = $this->_uit->saveEvent($exception, FALSE, Calendar_Model_Event::RANGE_ALL);
1369         
1370         $search = $this->_uit->searchEvents($events['filter'], NULL);
1371         foreach ($search['results'] as $event) {
1372             if ($event['dtstart'] == $updatedEvent['dtstart']) {
1373                 $this->assertEquals(3, count($event['attendee']), 'Attendee count mismatch in exdate: ' . print_r($event, TRUE));
1374             } else {
1375                 $this->assertEquals(4, count($event['attendee']), 'Attendee count mismatch: ' . print_r($event, TRUE));
1376             }
1377         }
1378     }
1379
1380     /**
1381      * testConcurrentAttendeeChangeAdd
1382      * 
1383      * @see 0008078: concurrent attendee change should be merged
1384      */
1385     public function testConcurrentAttendeeChangeAdd()
1386     {
1387         $eventData = $this->testCreateEvent();
1388         $numAttendee = count($eventData['attendee']);
1389         $eventData['attendee'][$numAttendee] = array(
1390             'user_id' => $this->_getPersonasContacts('pwulf')->getId(),
1391         );
1392         $this->_uit->saveEvent($eventData);
1393         
1394         $eventData['attendee'][$numAttendee] = array(
1395             'user_id' => $this->_getPersonasContacts('jsmith')->getId(),
1396         );
1397         $event = $this->_uit->saveEvent($eventData);
1398         
1399         $this->assertEquals(4, count($event['attendee']), 'both new attendee (pwulf + jsmith) should be added: ' . print_r($event['attendee'], TRUE));
1400     }
1401
1402     /**
1403      * testConcurrentAttendeeChangeRemove
1404      * 
1405      * @see 0008078: concurrent attendee change should be merged
1406      */
1407     public function testConcurrentAttendeeChangeRemove()
1408     {
1409         $eventData = $this->testCreateEvent();
1410         $currentAttendee = $eventData['attendee'];
1411         unset($eventData['attendee'][1]);
1412         $event = $this->_uit->saveEvent($eventData);
1413         
1414         $eventData['attendee'] = $currentAttendee;
1415         $numAttendee = count($eventData['attendee']);
1416         $eventData['attendee'][$numAttendee] = array(
1417             'user_id' => $this->_getPersonasContacts('pwulf')->getId(),
1418         );
1419         $event = $this->_uit->saveEvent($eventData);
1420         
1421         $this->assertEquals(2, count($event['attendee']), 'one attendee should added and one removed: ' . print_r($event['attendee'], TRUE));
1422     }
1423
1424     /**
1425      * testConcurrentAttendeeChangeUpdate
1426      * 
1427      * @see 0008078: concurrent attendee change should be merged
1428      */
1429     public function testConcurrentAttendeeChangeUpdate()
1430     {
1431         $eventData = $this->testCreateEvent();
1432         $currentAttendee = $eventData['attendee'];
1433         $adminIndex = ($eventData['attendee'][0]['user_id']['n_fn'] === 'Susan Clever') ? 1 : 0;
1434         $eventData['attendee'][$adminIndex]['status'] = Calendar_Model_Attender::STATUS_TENTATIVE;
1435         $event = $this->_uit->saveEvent($eventData);
1436         
1437         $loggedMods = Tinebase_Timemachine_ModificationLog::getInstance()->getModificationsBySeq(
1438             Tinebase_Application::getInstance()->getApplicationByName('Calendar')->getId(),
1439             new Calendar_Model_Attender($eventData['attendee'][$adminIndex]), 2);
1440         $this->assertEquals(1, count($loggedMods), 'attender modification has not been logged');
1441         
1442         $eventData['attendee'] = $currentAttendee;
1443         $scleverIndex = ($adminIndex === 1) ? 0 : 1;
1444         $attendeeBackend = new Calendar_Backend_Sql_Attendee();
1445         $eventData['attendee'][$scleverIndex]['status_authkey'] = $attendeeBackend->get($eventData['attendee'][$scleverIndex]['id'])->status_authkey;
1446         $eventData['attendee'][$scleverIndex]['status'] = Calendar_Model_Attender::STATUS_TENTATIVE;
1447         $event = $this->_uit->saveEvent($eventData);
1448
1449         foreach ($event['attendee'] as $attender) {
1450             $this->assertEquals(Calendar_Model_Attender::STATUS_TENTATIVE, $attender['status'], 'both attendee status should be TENTATIVE: ' . print_r($attender, TRUE));
1451         }
1452     }
1453
1454     /**
1455      * testFreeBusyCheckForExdates
1456      * 
1457      * @see 0008464: freebusy check does not work when creating recur exception
1458      */
1459     public function testFreeBusyCheckForExdates()
1460     {
1461         $events = $this->testCreateRecurException();
1462         $exception = $this->_getException($events, 1);
1463         
1464         $anotherEvent = $this->_getEvent(TRUE);
1465         $anotherEvent = $this->_uit->saveEvent($anotherEvent->toArray());
1466         
1467         $exception['dtstart'] = $anotherEvent['dtstart'];
1468         $exception['dtend'] = $anotherEvent['dtend'];
1469         
1470         try {
1471             $event = $this->_uit->saveEvent($exception, TRUE);
1472             $this->fail('Calendar_Exception_AttendeeBusy expected when saving exception: ' . print_r($exception, TRUE));
1473         } catch (Calendar_Exception_AttendeeBusy $ceab) {
1474             $this->assertEquals('Calendar_Exception_AttendeeBusy', get_class($ceab));
1475         }
1476     }
1477     
1478     /**
1479      * testAddAttachmentToRecurSeries
1480      * 
1481      * @see 0005024: allow to attach external files to records
1482      */
1483     public function testAddAttachmentToRecurSeries()
1484     {
1485         $tempFile = $this->_getTempFile();
1486         $recurSet = Tinebase_Helper::array_value('results', $this->testSearchRecuringIncludes());
1487         // update recurseries 
1488         $someRecurInstance = $recurSet[2];
1489         $someRecurInstance['attachments'] = array(array('tempFile' => array('id' => $tempFile->getId())));
1490         $someRecurInstance['seq'] = 2;
1491         $this->_uit->updateRecurSeries($someRecurInstance, FALSE, FALSE);
1492         
1493         $searchResultData = $this->_searchRecurSeries($recurSet[0]);
1494         foreach ($searchResultData['results'] as $recurInstance) {
1495             $this->assertTrue(isset($recurInstance['attachments']), 'no attachments found in event: ' . print_r($recurInstance, TRUE));
1496             $this->assertEquals(1, count($recurInstance['attachments']));
1497             $attachment = $recurInstance['attachments'][0];
1498             $this->assertEquals('text/plain', $attachment['contenttype'], print_r($attachment, TRUE));
1499         }
1500     }
1501     
1502     /**
1503      * checks if manipulated dtend and dtstart gets set to the correct values on creating or updating an event
1504      * 
1505      * @see 0009696: time is not grayed out for all-day events
1506      */
1507     public function testWholedayEventTimes()
1508     {
1509         $event = $this->_getEvent(TRUE);
1510         $event->is_all_day_event = TRUE;
1511         
1512         $event = Calendar_Controller_Event::getInstance()->create($event);
1513         $event->setTimezone(Tinebase_Core::getUserTimezone());
1514         
1515         $this->assertEquals('00:00:00', $event->dtstart->format('H:i:s'));
1516         $this->assertEquals('23:59:59', $event->dtend->format('H:i:s'));
1517         
1518         $event->dtstart = Tinebase_DateTime::now();
1519         $event->dtend   = Tinebase_DateTime::now()->addHour(1);
1520         
1521         $event = Calendar_Controller_Event::getInstance()->update($event);
1522         $event->setTimezone(Tinebase_Core::getUserTimezone());
1523         
1524         $this->assertEquals('00:00:00', $event->dtstart->format('H:i:s'));
1525         $this->assertEquals('23:59:59', $event->dtend->format('H:i:s'));
1526     }
1527     
1528      /**
1529      * testAttendeeChangeQuantityToInvalid
1530      * 
1531      * @see 9630: sanitize attender quantity
1532      */
1533     public function testAttendeeChangeQuantityToInvalid()
1534     {
1535         $eventData = $this->testCreateEvent();
1536         $currentAttendee = $eventData['attendee'];
1537         $eventData['attendee'][1]['quantity'] = '';
1538         $event = $this->_uit->saveEvent($eventData);
1539         $this->assertEquals(1, $event['attendee'][1]['quantity'], 'The invalid quantity should be saved as 1');
1540     }
1541
1542     /**
1543      * trigger caldav import by json frontend
1544      * 
1545      * @todo use mock as fallback (if server can not be reached by curl)
1546      * @todo get servername from unittest config / skip or mock if no servername found
1547      */
1548     public function testCalDAVImport()
1549     {
1550         // Skip if tine20.com.local could not be resolved
1551         if (gethostbyname('tine20.com.local') == 'tine20.com.local') {
1552             $this->markTestSkipped('Can\'t perform test, because instance is not reachable.');
1553         }
1554
1555         $this->_testNeedsTransaction();
1556         
1557         $event = $this->testCreateEvent(/* $now = */ true);
1558         
1559         $fe = new Calendar_Frontend_Json();
1560         $testUserCredentials = TestServer::getInstance()->getTestCredentials();
1561         $fe->importRemoteEvents(
1562             'http://tine20.com.local/calendars/' . Tinebase_Core::getUser()->contact_id . '/' . $event['container_id']['id'],
1563             Tinebase_Model_Import::INTERVAL_DAILY,
1564             array(
1565                 'container_id'          => 'remote_caldav_calendar',
1566                 'sourceType'            => 'remote_caldav',
1567                 'importFileByScheduler' => false,
1568                 'allowDuplicateEvents'  => true,
1569                 'username'              => $testUserCredentials['username'],
1570                 'password'              => $testUserCredentials['password'],
1571             ));
1572
1573         $importScheduler = Tinebase_Controller_ScheduledImport::getInstance();
1574         $record = $importScheduler->runNextScheduledImport();
1575
1576         $container = Tinebase_Container::getInstance()->getContainerByName('Calendar', 'remote_caldav_calendar', Tinebase_Model_Container::TYPE_PERSONAL, Tinebase_Core::getUser()->getId());
1577         $this->_testCalendars[] = $container;
1578         $this->assertTrue($container instanceof Tinebase_Model_Container, 'Container was not created');
1579
1580         $this->assertNotEquals($record, null, 'The import could not start!');
1581         
1582         $filter = $this->_getEventFilterArray($container->getId());
1583         $result = $this->_uit->searchEvents($filter, array());
1584         $this->assertEquals(1, $result['totalcount']);
1585     }
1586     
1587     /**
1588      * testGetRelations
1589      * 
1590      * @see 0009542: load event relations on demand
1591      */
1592     public function testGetRelations()
1593     {
1594         $contact = Addressbook_Controller_Contact::getInstance()->create(new Addressbook_Model_Contact(array(
1595             'n_family' => 'Contact for relations test'
1596         )));
1597         $eventData = $this->_getEvent()->toArray();
1598         $eventData['relations'] = array(
1599             array(
1600                 'own_model' => 'Calendar_Model_Event',
1601                 'own_backend' => 'Sql',
1602                 'own_id' => 0,
1603                 'own_degree' => Tinebase_Model_Relation::DEGREE_SIBLING,
1604                 'type' => '',
1605                 'related_backend' => 'Sql',
1606                 'related_id' => $contact->getId(),
1607                 'related_model' => 'Addressbook_Model_Contact',
1608                 'remark' => NULL,
1609             ));
1610         $event = $this->_uit->saveEvent($eventData);
1611
1612         $tfj = new Tinebase_Frontend_Json();
1613         $relations = $tfj->getRelations('Calendar_Model_Event', $event['id']);
1614
1615         $this->assertEquals(1, $relations['totalcount']);
1616         $this->assertEquals($contact->n_fn, $relations['results'][0]['related_record']['n_family'], print_r($relations['results'], true));
1617     }
1618 }