1<?php
2/**
3 * EGroupware - Calendar's buisness-object - access + update
4 *
5 * @link http://www.egroupware.org
6 * @package calendar
7 * @author Ralf Becker <RalfBecker-AT-outdoor-training.de>
8 * @author Joerg Lehrke <jlehrke@noc.de>
9 * @copyright (c) 2005-16 by RalfBecker-At-outdoor-training.de
10 * @license http://opensource.org/licenses/gpl-license.php GPL - GNU General Public License
11 * @version $Id$
12 */
13
14use EGroupware\Api;
15use EGroupware\Api\Acl;
16use EGroupware\Api\Link;
17
18// types of messsages send by calendar_boupdate::send_update
19define('MSG_DELETED',0);
20define('MSG_MODIFIED',1);
21define('MSG_ADDED',2);
22define('MSG_REJECTED',3);
23define('MSG_TENTATIVE',4);
24define('MSG_ACCEPTED',5);
25define('MSG_ALARM',6);
26define('MSG_DISINVITE',7);
27define('MSG_DELEGATED',8);
28define('MSG_REQUEST',9);
29
30/**
31 * Class to access AND manipulate all calendar data (business object)
32 *
33 * The new UI, BO and SO classes have a strikt definition, in which time-zone they operate:
34 *  UI only operates in user-time, so there have to be no conversation at all !!!
35 *  BO's functions take and return user-time only (!), they convert internaly everything to servertime, because
36 *  SO operates only on server-time
37 *
38 * As this BO class deals with dates/times of several types and timezone, each variable should have a postfix
39 * appended, telling with type it is: _s = seconds, _su = secs in user-time, _ss = secs in server-time, _h = hours
40 *
41 * All new BO code (should be true for eGW in general) NEVER use any $_REQUEST ($_POST or $_GET) vars itself.
42 * Nor does it store the state of any UI-elements (eg. cat-id selectbox). All this is the task of the UI class(es) !!!
43 *
44 * All permanent debug messages of the calendar-code should done via the debug-message method of the bocal class !!!
45 */
46
47class calendar_boupdate extends calendar_bo
48{
49	/**
50	 * Category ACL allowing to add a given category
51	 */
52	const CAT_ACL_ADD = 512;
53	/**
54	 * Category ACL allowing to change status of a participant
55	 */
56	const CAT_ACL_STATUS = 1024;
57
58	/**
59	 * name of method to debug or level of debug-messages:
60	 *	False=Off as higher as more messages you get ;-)
61	 *	1 = function-calls incl. parameters to general functions like search, read, write, delete
62	 *	2 = function-calls to exported helper-functions like check_perms
63	 *	4 = function-calls to exported conversation-functions like date2ts, date2array, ...
64	 *	5 = function-calls to private functions
65	 * @var mixed
66	 */
67	var $debug;
68
69	/**
70	 * Set Logging
71	 *
72	 * @var boolean
73	 */
74	var $log = false;
75	var $logfile = '/tmp/log-calendar-boupdate';
76
77	/**
78	 * Cached timezone data
79	 *
80	 * @var array id => data
81	 */
82	protected static $tz_cache = array();
83
84	/**
85	 * Constructor
86	 */
87	function __construct()
88	{
89		if ($this->debug > 0) $this->debug_message('calendar_boupdate::__construct() started',True);
90
91		parent::__construct();	// calling the parent constructor
92
93		if ($this->debug > 0) $this->debug_message('calendar_boupdate::__construct() finished',True);
94	}
95
96	/**
97	 * updates or creates an event, it (optionaly) checks for conflicts and sends the necessary notifications
98	 *
99	 * @param array &$event event-array, on return some values might be changed due to set defaults
100	 * @param boolean $ignore_conflicts =false just ignore conflicts or do a conflict check and return the conflicting events
101	 * @param boolean $touch_modified =true NOT USED ANYMORE (was only used in old csv-import), modified&modifier is always updated!
102	 * @param boolean $ignore_acl =false should we ignore the acl
103	 * @param boolean $updateTS =true update the content history of the event (ignored, as updating timestamps is required for sync!)
104	 * @param array &$messages=null messages about because of missing ACL removed participants or categories
105	 * @param boolean $skip_notification =false true: send NO notifications, default false = send them
106	 * @return mixed on success: int $cal_id > 0, on error false or array with conflicting events (only if $check_conflicts)
107	 * 		Please note: the events are not garantied to be readable by the user (no read grant or private)!
108	 *
109	 * @ToDo current conflict checking code does NOT cope quantity-wise correct with multiple non-overlapping
110	 * 	events overlapping the event to store: the quantity sum is used, even as the events dont overlap!
111	 *
112	 * ++++++++ ++++++++
113	 * +      + +  B   +	If A get checked for conflicts, the check used for resource quantity is
114	 * +      + ++++++++
115	 * +  A   +				quantity(A,resource)+quantity(B,resource)+quantity(C,resource) > maxBookable(resource)
116	 * +      + ++++++++
117	 * +      + +  C   +	which is clearly wrong for everything with a maximum quantity > 1
118	 * ++++++++ ++++++++
119	 */
120	function update(&$event,$ignore_conflicts=false,$touch_modified=true,$ignore_acl=false,$updateTS=true,&$messages=null, $skip_notification=false)
121	{
122		$update_type = 'edit';
123		unset($updateTS);	// ignored, as updating timestamps is required for sync!
124		//error_log(__METHOD__."(".array2string($event).",$ignore_conflicts,$touch_modified,$ignore_acl)");
125		if (!is_array($messages)) $messages = $messages ? (array)$messages : array();
126
127		if ($this->debug > 1 || $this->debug == 'update')
128		{
129			$this->debug_message('calendar_boupdate::update(%1,ignore_conflict=%2,touch_modified=%3,ignore_acl=%4)',
130				false,$event,$ignore_conflicts,$touch_modified,$ignore_acl);
131		}
132		// check some minimum requirements:
133		// - new events need start, end and title
134		// - updated events cant set start, end or title to empty
135		if (!$event['id'] && (!$event['start'] || !$event['end'] || !$event['title']) ||
136			$event['id'] && (isset($event['start']) && !$event['start'] || isset($event['end']) && !$event['end'] ||
137			isset($event['title']) && !$event['title']))
138		{
139			$messages[] = lang('Required information (start, end, title, ...) missing!');
140			return false;
141		}
142
143		$status_reset_to_unknown = false;
144
145		if (($new_event = !$event['id']))	// some defaults for new entries
146		{
147			// if no owner given, set user to owner
148			if (!$event['owner']) $event['owner'] = $this->user;
149			// set owner as participant if none is given
150			if (!is_array($event['participants']) || !count($event['participants']))
151			{
152				$status = calendar_so::combine_status($event['owner'] == $this->user ? 'A' : 'U', 1, 'CHAIR');
153				$event['participants'] = array($event['owner'] => $status);
154			}
155			$update_type = 'add';
156		}
157
158		// check if user has the permission to update / create the event
159		if (!$ignore_acl && (!$new_event && !$this->check_perms(Acl::EDIT,$event['id']) ||
160			$new_event && !$this->check_perms(Acl::EDIT,0,$event['owner'])) &&
161			!$this->check_perms(Acl::ADD,0,$event['owner']))
162		{
163			$messages[] = lang('Access to calendar of %1 denied!',Api\Accounts::username($event['owner']));
164			return false;
165		}
166		if ($new_event)
167		{
168			$old_event = array();
169		}
170		else
171		{
172			$old_event = $this->read((int)$event['id'],null,$ignore_acl);
173		}
174
175		// do we need to check, if user is allowed to invite the invited participants
176		if ($this->require_acl_invite && ($removed = $this->remove_no_acl_invite($event,$old_event)))
177		{
178			// report removed participants back to user
179			foreach($removed as $key => $account_id)
180			{
181				$removed[$key] = $this->participant_name($account_id);
182			}
183			$messages[] = lang('%1 participants removed because of missing invite grants',count($removed)).
184				': '.implode(', ',$removed);
185		}
186		// check category based ACL
187		if ($event['category'])
188		{
189			if (!is_array($event['category'])) $event['category'] = explode(',',$event['category']);
190			if (!$old_event || !isset($old_event['category']))
191			{
192				$old_event['category'] = array();
193			}
194			elseif (!is_array($old_event['category']))
195			{
196				$old_event['category'] = explode(',', $old_event['category']);
197			}
198			foreach($event['category'] as $key => $cat_id)
199			{
200				// check if user is allowed to update event categories
201				if ((!$old_event || !in_array($cat_id,$old_event['category'])) &&
202					self::has_cat_right(self::CAT_ACL_ADD,$cat_id,$this->user) === false)
203				{
204					unset($event['category'][$key]);
205					// report removed category to user
206					$removed_cats[$cat_id] = $this->categories->id2name($cat_id);
207					continue;	// no further check, as cat was removed
208				}
209				// for new or moved events check status of participants, if no category status right --> set all status to 'U' = unknown
210				if (!$status_reset_to_unknown &&
211					self::has_cat_right(self::CAT_ACL_STATUS,$cat_id,$this->user) === false &&
212					(!$old_event || $old_event['start'] != $event['start'] || $old_event['end'] != $event['end']))
213				{
214					foreach((array)$event['participants'] as $uid => $status)
215					{
216						$q = $r = null;
217						calendar_so::split_status($status,$q,$r);
218						if ($status != 'U')
219						{
220							$event['participants'][$uid] = calendar_so::combine_status('U',$q,$r);
221							// todo: report reset status to user
222						}
223					}
224					$status_reset_to_unknown = true;	// once is enough
225				}
226			}
227			if ($removed_cats)
228			{
229				$messages[] = lang('Category %1 removed because of missing rights',implode(', ',$removed_cats));
230			}
231			if ($status_reset_to_unknown)
232			{
233				$messages[] = lang('Status of participants set to unknown because of missing category rights');
234			}
235		}
236
237		// generate a video-room-url, if we need one and not already have one
238		if ($event['videoconference'] && empty($event['##videoconference']) && class_exists('EGroupware\\Status\\Videoconference\\Call')
239			&& !EGroupware\Status\Hooks::isVideoconferenceDisabled())
240		{
241			$event['##videoconference'] = EGroupware\Status\Videoconference\Call::genUniqueRoomID();
242		}
243		elseif (isset($event['videoconference']) && !$event['videoconference'])
244		{
245			$event['##videoconference'] = '';
246		}
247		// update videoconference resource amounts based on number of participants
248		if ($event['videoconference'] && !empty($event['##videoconference']) && class_exists('EGroupware\\Status\\Videoconference\\Call')
249			&& !EGroupware\Status\Hooks::isVideoconferenceDisabled() && ($videoconferenceResId = \EGroupware\Status\Hooks::getVideoconferenceResourceId()))
250		{
251			$participant_total = 0;
252			foreach(['u','e','c'] as $p_type)
253			{
254				if(is_array($event['participant_types'][$p_type]))
255				{
256					$participant_total += count($event['participant_types'][$p_type]);
257				}
258			}
259			$event['participant_types']['r'][$videoconferenceResId] =
260			$event['participants']['r'.$videoconferenceResId] = 'A'.$participant_total;
261		}
262
263		// check for conflicts only happens !$ignore_conflicts AND if start + end date are given
264		$checked_excluding = null;
265		if (!$ignore_conflicts && !$event['non_blocking'] && isset($event['start']) && isset($event['end']) &&
266			(($conflicts = $this->conflicts($event, $checked_excluding)) || $checked_excluding))
267		{
268			if ($checked_excluding)	// warn user if not all recurrences have been checked
269			{
270				$conflicts['warning'] = array(
271					'start' => $checked_excluding,
272					'title' => lang('Only recurrences until %1 (excluding) have been checked!', $checked_excluding->format(true)),
273				);
274			}
275			return $conflicts;
276		}
277
278
279
280		//echo "saving $event[id]="; _debug_array($event);
281		$event2save = $event;
282
283		if (!($cal_id = $this->save($event, $ignore_acl)))
284		{
285			return $cal_id;
286		}
287
288		// we re-read the event, in case only partial information was update and we need the full info for the notifies
289		// The check for new private events is to at least show the private version,
290		// otherwise we get FALSE
291		$event = $this->read($cal_id, null, $ignore_acl, 'ts', $new_event && !$event['public'] ? $this->user : null);
292		//error_log("new $cal_id=". array2string($event));
293
294		if($old_event['deleted'] && $event['deleted'] == null)
295		{
296			// Restored, bring back links
297			Link::restore('calendar', $cal_id);
298			$update_type = 'add';
299		}
300		if ($this->log_file)
301		{
302			$this->log2file($event2save,$event,$old_event);
303		}
304		// send notifications if the event is in the future
305		if(!$skip_notification && $event['end'] > $this->now_su)
306		{
307			if ($new_event)
308			{
309				$this->send_update(MSG_ADDED,$event['participants'],'',$event);
310			}
311			else // update existing event
312			{
313				$this->check4update($event,$old_event);
314			}
315		}
316
317		// notify the link-class about the update, as other apps may be subscribed to it
318		Link::notify_update('calendar',$cal_id,$event,$update_type);
319
320		return $cal_id;
321	}
322
323	/**
324	 * Check given event for conflicts and return them
325	 *
326	 * For recurring events we check a configurable fixed number of recurrences
327	 * and for a fixed maximum time (default 3s).
328	 *
329	 * Conflict check skips past events/recurrences and is always limited by recurrence horizont,
330	 * as it would only report non-recurring events after.
331	 *
332	 * @param array $event
333	 * @param Api\DateTime& $checked_excluding =null time until which (excluding) recurrences have been checked
334	 * @return array or events
335	 */
336	function conflicts(array $event, &$checked_excluding=null)
337	{
338		$types_with_quantity = array();
339		foreach($this->resources as $type => $data)
340		{
341			if ($data['max_quantity']) $types_with_quantity[] = $type;
342		}
343		// get all NOT rejected participants and evtl. their quantity
344		$quantity = $users = array();
345		foreach($event['participants'] as $uid => $status)
346		{
347			$q = $role = null;
348			calendar_so::split_status($status, $q, $role);
349			if ($status == 'R' || $role == 'NON-PARTICIPANT') continue;	// ignore rejected or non-participants
350
351			if ($uid < 0)	// group, check it's members too
352			{
353				$users = array_unique(array_merge($users, (array)$GLOBALS['egw']->accounts->members($uid,true)));
354			}
355			$users[] = $uid;
356			if (in_array($uid[0],$types_with_quantity))
357			{
358				$quantity[$uid] = $q;
359			}
360		}
361		$max_quantity = $possible_quantity_conflicts = $conflicts = array();
362
363		if ($event['recur_type'])
364		{
365			$recurences = calendar_rrule::event2rrule($event);
366		}
367		else
368		{
369			$recurences = array(new Api\DateTime((int)$event['start']));
370		}
371		$checked_excluding = null;
372		$max_checked = $GLOBALS['egw_info']['server']['conflict_max_checked'];
373		if (($max_check_time = (float)$GLOBALS['egw_info']['server']['conflict_max_check_time']) < 1.0)
374		{
375			$max_check_time = 3.0;
376		}
377		$checked = 0;
378		$start = microtime(true);
379		$duration = $event['end']-$event['start'];
380		foreach($recurences as $date)
381		{
382			$startts = $date->format('ts');
383
384			// skip past events or recurrences
385			if ($startts+$duration < $this->now_su) continue;
386
387			// abort check if configured limits are exceeded
388			if ($event['recur_type'] &&
389				(++$checked > $max_checked && $max_checked > 0 || // maximum number of checked recurrences exceeded
390				microtime(true) > $start+$max_check_time ||	// max check time exceeded
391				$startts > $this->config['horizont']))	// we are behind horizon for which recurrences are rendered
392			{
393				if ($this->debug > 2 || $this->debug == 'conflicts')
394				{
395					$this->debug_message(__METHOD__.'() conflict check limited to %1 recurrences, %2 seconds, until (excluding) %3',
396						$checked, microtime(true)-$start, $date);
397				}
398				$checked_excluding = $date;
399				break;
400			}
401			$overlapping_events =& $this->search(array(
402				'start' => $startts,
403				'end'   => $startts+$duration,
404				'users' => $users,
405				'ignore_acl' => true,	// otherwise we get only events readable by the user
406				'enum_groups' => true,	// otherwise group-events would not block time
407				'query' => array(
408					'cal_non_blocking' => 0,
409				),
410				'no_integration' => true,	// do NOT use integration of other apps
411			));
412			if ($this->debug > 2 || $this->debug == 'conflicts')
413			{
414				$this->debug_message(__METHOD__.'() checking for potential overlapping events for users %1 from %2 to %3',false,$users,$startts,$startts+$duration);
415			}
416			foreach((array) $overlapping_events as $k => $overlap)
417			{
418				if ($overlap['id'] == $event['id'] ||	// that's the event itself
419					$overlap['id'] == $event['reference'] ||	// event is an exception of overlap
420					$overlap['non_blocking'])			// that's a non_blocking event
421				{
422					continue;
423				}
424				if ($this->debug > 3 || $this->debug == 'conflicts')
425				{
426					$this->debug_message(__METHOD__.'() checking overlapping event %1',false,$overlap);
427				}
428				// check if the overlap is with a rejected participant or within the allowed quantity
429				$common_parts = array_intersect($users,array_keys($overlap['participants']));
430				foreach($common_parts as $n => $uid)
431				{
432					$status = $overlap['participants'][$uid];
433					calendar_so::split_status($status, $q, $role);
434					if ($status == 'R' || $role == 'NON-PARTICIPANT')
435					{
436						unset($common_parts[$n]);
437						continue;
438					}
439					if (is_numeric($uid) || !in_array($uid[0],$types_with_quantity))
440					{
441						continue;	// no quantity check: quantity allways 1 ==> conflict
442					}
443					if (!isset($max_quantity[$uid]))
444					{
445						$res_info = $this->resource_info($uid);
446						$max_quantity[$uid] = $res_info[$this->resources[$uid[0]]['max_quantity']];
447					}
448					$quantity[$uid] += $q;
449					if ($quantity[$uid] <= $max_quantity[$uid])
450					{
451						$possible_quantity_conflicts[$uid][] =& $overlapping_events[$k];	// an other event can give the conflict
452						unset($common_parts[$n]);
453						continue;
454					}
455					// now we have a quantity conflict for $uid
456				}
457				if (count($common_parts))
458				{
459					if ($this->debug > 3 || $this->debug == 'conflicts')
460					{
461						$this->debug_message(__METHOD__.'() conflicts with the following participants found %1',false,$common_parts);
462					}
463					$conflicts[$overlap['id'].'-'.$this->date2ts($overlap['start'])] =& $overlapping_events[$k];
464				}
465			}
466		}
467		//error_log(__METHOD__."() conflict check took ".number_format(microtime(true)-$start, 3).'s');
468		// check if we are withing the allowed quantity and if not add all events using that resource
469		// seems this function is doing very strange things, it gives empty conflicts
470		foreach($max_quantity as $uid => $max)
471		{
472			if ($quantity[$uid] > $max)
473			{
474				foreach((array)$possible_quantity_conflicts[$uid] as $conflict)
475				{
476					$conflicts[$conflict['id'].'-'.$this->date2ts($conflict['start'])] =& $possible_quantity_conflicts[$k];
477				}
478			}
479		}
480		unset($possible_quantity_conflicts);
481
482		if (count($conflicts))
483		{
484			foreach($conflicts as $key => $conflict)
485			{
486					$conflict['participants'] = array_intersect_key((array)$conflict['participants'],$event['participants']);
487				if (!$this->check_perms(Acl::READ,$conflict))
488				{
489					$conflicts[$key] = array(
490						'id'    => $conflict['id'],
491						'title' => lang('busy'),
492						'participants' => $conflict['participants'],
493						'start' => $conflict['start'],
494						'end'   => $conflict['end'],
495					);
496				}
497			}
498			if ($this->debug > 2 || $this->debug == 'conflicts')
499			{
500				$this->debug_message(__METHOD__.'() %1 conflicts found %2',false,count($conflicts),$conflicts);
501			}
502		}
503		return $conflicts;
504	}
505	/**
506	 * Remove participants current user has no right to invite
507	 *
508	 * @param array &$event new event
509	 * @param array $old_event =null old event with already invited participants
510	 * @return array removed participants because of missing invite grants
511	 */
512	public function remove_no_acl_invite(array &$event,array $old_event=null)
513	{
514		if (!$this->require_acl_invite)
515		{
516			return array();	// nothing to check, everyone can invite everyone else
517		}
518		if ($event['id'] && is_null($old_event))
519		{
520			$old_event = $this->read($event['id']);
521		}
522		$removed = array();
523		foreach(array_keys((array)$event['participants']) as $uid)
524		{
525			if ((is_null($old_event) || !isset($old_event['participants'][$uid])) && !$this->check_acl_invite($uid))
526			{
527				unset($event['participants'][$uid]);	// remove participant
528				$removed[] = $uid;
529			}
530		}
531		//echo "<p>".__METHOD__."($event[title],".($old_event?'$old_event':'NULL').") returning ".array2string($removed)."</p>";
532		return $removed;
533	}
534
535	/**
536	 * Check if current user is allowed to invite a given participant
537	 *
538	 * @param int|string $uid
539	 * @return boolean
540	 */
541	public function check_acl_invite($uid)
542	{
543		if (!is_numeric($uid) && $this->resources[$uid[0]]['check_invite'])
544		{
545			// Resource specific ACL check
546			return call_user_func($this->resources[$uid[0]]['check_invite'], $uid);
547		}
548		elseif (!$this->require_acl_invite)
549		{
550			$ret = true;	// no grant required
551		}
552		elseif ($this->require_acl_invite == 'groups' && $GLOBALS['egw']->accounts->get_type($uid) != 'g')
553		{
554			$ret = true;	// grant only required for groups
555		}
556		else
557		{
558			$ret = $this->check_perms(self::ACL_INVITE,0,$uid);
559		}
560		//error_log(__METHOD__."($uid) = ".array2string($ret));
561		//echo "<p>".__METHOD__."($uid) require_acl_invite=$this->require_acl_invite returning ".array2string($ret)."</p>\n";
562		return $ret;
563	}
564
565	/**
566	 * Check for added, modified or deleted participants AND notify them
567	 *
568	 * @param array $new_event the updated event
569	 * @param array $old_event the event before the update
570	 * @todo check if there is a real change, not assume every save is a change
571	 */
572	function check4update($new_event,$old_event)
573	{
574		//error_log(__METHOD__."($new_event[title])");
575		$modified = $added = $deleted = array();
576
577		//echo "<p>calendar_boupdate::check4update() new participants = ".print_r($new_event['participants'],true).", old participants =".print_r($old_event['participants'],true)."</p>\n";
578
579		// Find modified and deleted participants ...
580		foreach ((array)$old_event['participants'] as $old_userid => $old_status)
581		{
582			if (isset($new_event['participants'][$old_userid]))
583			{
584				$modified[$old_userid] = $new_event['participants'][$old_userid];
585			}
586			else
587			{
588				$deleted[$old_userid] = $old_status;
589			}
590		}
591		// Find new participants ...
592		foreach(array_keys((array)$new_event['participants']) as $new_userid)
593		{
594			if(!isset($old_event['participants'][$new_userid]))
595			{
596				$added[$new_userid] = 'U';
597			}
598		}
599		//echo "<p>calendar_boupdate::check4update() added=".print_r($added,true).", modified=".print_r($modified,true).", deleted=".print_r($deleted,true)."</p>\n";
600		if(count($added) || count($modified) || count($deleted))
601		{
602			if(count($added))
603			{
604				$this->send_update(MSG_ADDED,$added,$old_event,$new_event);
605			}
606			if(count($modified))
607			{
608				$this->send_update(MSG_MODIFIED,$modified,$old_event,$new_event);
609			}
610			if(count($deleted))
611			{
612				$this->send_update(MSG_DISINVITE,$deleted,$new_event);
613			}
614		}
615	}
616
617	/**
618	 * checks if $userid has requested (in $part_prefs) updates for $msg_type
619	 *
620	 * @param int $userid numerical user-id
621	 * @param array $part_prefs preferces of the user $userid
622	 * @param int &$msg_type type of the notification: MSG_ADDED, MSG_MODIFIED, MSG_ACCEPTED, ...
623	 * @param array $old_event Event before the change
624	 * @param array $new_event Event after the change
625	 * @param string $role we treat CHAIR like event owners
626	 * @param string $status of current user
627	 * @return boolean true = update requested, false otherwise
628	 */
629	public static function update_requested($userid, $part_prefs, &$msg_type, $old_event ,$new_event, $role, $status=null)
630	{
631		if ($msg_type == MSG_ALARM)
632		{
633			return True;	// always True for now
634		}
635		$want_update = 0;
636
637		// the following switch falls through all cases, as each included the following too
638		//
639		$msg_is_response = $msg_type == MSG_REJECTED || $msg_type == MSG_ACCEPTED || $msg_type == MSG_TENTATIVE || $msg_type == MSG_DELEGATED;
640
641		// Check if user is not participating, and does not want notifications
642		if($msg_is_response && !$part_prefs['calendar']['receive_not_participating'] && !array_key_exists($userid, $old_event['participants']))
643		{
644			return false;
645		}
646
647		// always notify externals chairs
648		// EGroupware owner only get notified about responses, if pref is NOT "no"
649		if (!is_numeric($userid) && $role == 'CHAIR' &&
650			($msg_is_response || in_array($msg_type, array(MSG_ADDED, MSG_DELETED))))
651		{
652			switch($msg_type)
653			{
654				case MSG_DELETED:	// treat deleting event as rejection to organizer
655					$msg_type = MSG_REJECTED;
656					break;
657				case MSG_ADDED:		// new events use added, but organizer needs status
658					switch($status[0])
659					{
660						case 'A': $msg_type = MSG_ACCEPTED; break;
661						case 'R': $msg_type = MSG_REJECTED; break;
662						case 'T': $msg_type = MSG_TENTATIVE; break;
663						case 'D': $msg_type = MSG_DELEGATED; break;
664					}
665					break;
666			}
667			++$want_update;
668		}
669		else
670		{
671			switch($ru = $part_prefs['calendar']['receive_updates'])
672			{
673				case 'responses':
674					++$want_update;
675				case 'modifications':
676					if (!$msg_is_response)
677					{
678						++$want_update;
679					}
680				case 'time_change_4h':
681				case 'time_change':
682				default:
683					if (is_array($new_event) && is_array($old_event))
684					{
685						$diff = max(abs(self::date2ts($old_event['start'])-self::date2ts($new_event['start'])),
686							abs(self::date2ts($old_event['end'])-self::date2ts($new_event['end'])));
687						$check = $ru == 'time_change_4h' ? 4 * 60 * 60 - 1 : 0;
688						if ($msg_type == MSG_MODIFIED && $diff > $check)
689						{
690							++$want_update;
691						}
692					}
693				case 'add_cancel':
694					if ($msg_is_response && ($old_event['owner'] == $userid || $role == 'CHAIR') ||
695						$msg_type == MSG_DELETED || $msg_type == MSG_ADDED || $msg_type == MSG_DISINVITE)
696					{
697						++$want_update;
698					}
699					break;
700				case 'no':
701					break;
702			}
703		}
704		//error_log(__METHOD__."(userid=$userid, receive_updates='$ru', msg_type=$msg_type, ..., role='$role') msg_is_response=$msg_is_response --> want_update=$want_update");
705		return $want_update > 0;
706	}
707
708	/**
709	 * Check calendar prefs, if a given user (integer account_id) or email (user or externals) should get notified
710	 *
711	 * @param int|string $user_or_email
712	 * @param string $ical_method ='REQUEST'
713	 * @param string $role ='REQ-PARTICIPANT'
714	 * @param string $notify_externals =null event-specific overwrite, default preferences
715	 * @return boolean true if user requested to be notified, false if not
716	 */
717	static public function email_update_requested($user_or_email, $ical_method='REQUEST', $role='REQ-PARTICIPANT',$notify_externals=null)
718	{
719		// check if email is from a user
720		if (is_numeric($user_or_email))
721		{
722			$account_id = $user_or_email;
723		}
724		else
725		{
726			$account_id = $GLOBALS['egw']->accounts->name2id($user_or_email, 'account_email');
727		}
728		if ($account_id)
729		{
730			$pref_obj = new Api\Preferences($account_id);
731			$prefs = $pref_obj->read_repository();
732		}
733		else
734		{
735			$prefs = array(
736				'calendar' => array(
737					'receive_updates' => $notify_externals ?: $GLOBALS['egw_info']['user']['preferences']['calendar']['notify_externals'],
738				)
739			);
740		}
741		switch($ical_method)
742		{
743			default:
744			case 'REQUEST':
745				$msg_type = MSG_ADDED;
746				break;
747			case 'REPLY':
748				$msg_type = MSG_ACCEPTED;
749				break;
750			case 'CANCEL':
751				$msg_type = MSG_DELETED;
752				break;
753		}
754		$ret = self::update_requested($account_id, $prefs, $msg_type, array(), array(), $role);
755		//error_log(__METHOD__."('$user_or_email', '$ical_method', '$role') account_id=$account_id --> updated_requested returned ".array2string($ret));
756		return $ret;
757	}
758
759	/**
760	 * Get iCal/iMip method from internal nummeric msg-type plus optional notification message and verbose name
761	 *
762	 * @param int $msg_type see MSG_* defines
763	 * @param string& $action=null on return verbose name
764	 * @param string& $msg=null on return notification message
765	 */
766	function msg_type2ical_method($msg_type, &$action=null, &$msg=null, $prefs=null)
767	{
768		switch($msg_type)
769		{
770			case MSG_DELETED:
771				$action = 'Canceled';
772				$pref = 'Canceled';
773				$method = 'CANCEL';
774				break;
775			case MSG_MODIFIED:
776				$action = 'Modified';
777				$pref = 'Modified';
778				$method = 'REQUEST';
779				break;
780			case MSG_DISINVITE:
781				$action = 'Disinvited';
782				$pref = 'Disinvited';
783				$method = 'CANCEL';
784				break;
785			case MSG_ADDED:
786				$action = 'Added';
787				$pref = 'Added';
788				$method = 'REQUEST';
789				break;
790			case MSG_REJECTED:
791				$action = 'Rejected';
792				$pref = 'Response';
793				$method = 'REPLY';
794				break;
795			case MSG_TENTATIVE:
796				$action = 'Tentative';
797				$pref = 'Response';
798				$method = 'REPLY';
799				break;
800			case MSG_ACCEPTED:
801				$action = 'Accepted';
802				$pref = 'Response';
803				$method = 'REPLY';
804				break;
805			case MSG_DELEGATED:
806				$action = 'Delegated';
807				$pref = 'Response';
808				$method = 'REPLY';
809				break;
810			case MSG_ALARM:
811				$action = 'Alarm';
812				$pref = 'Alarm';
813				break;
814			case MSG_REQUEST:
815				$method = 'REQUEST';
816				break;
817			default:
818				$method = 'PUBLISH';
819		}
820		if(is_null($prefs))
821		{
822			$prefs = $this->cal_prefs;
823		}
824		$msg = $prefs['notify'.$pref];
825		if (empty($msg))
826		{
827			$msg = $prefs['notifyAdded'];	// use a default
828		}
829		//error_log(__METHOD__."($msg_type) action='$action', $msg='$msg' returning '$method'");
830		return $method;
831	}
832
833	/**
834	 * sends update-messages to certain participants of an event
835	 *
836	 * @param int $msg_type type of the notification: MSG_ADDED, MSG_MODIFIED, MSG_ACCEPTED, ...
837	 * @param array $to_notify numerical user-ids as keys (!) (value is not used)
838	 * @param array $old_event Event before the change
839	 * @param array $new_event =null Event after the change
840	 * @param int|string $user =0 User/participant who started the notify, default current user
841	 * @param array $alarm =null values for "offset", "start", etc.
842	 * @return bool true/false
843	 */
844	function send_update($msg_type, $to_notify, $old_event, $new_event=null, $user=0, array $alarm=null)
845	{
846		Api\Egw::on_shutdown([$this, '_send_update'], func_get_args());
847	}
848
849	/**
850	 * sends update-messages to certain participants of an event
851	 *
852	 * @param int $msg_type type of the notification: MSG_ADDED, MSG_MODIFIED, MSG_ACCEPTED, ...
853	 * @param array $to_notify numerical user-ids as keys (!) (value is not used)
854	 * @param array $old_event Event before the change
855	 * @param array $new_event =null Event after the change
856	 * @param int|string $user =0 User/participant who started the notify, default current user
857	 * @param array $alarm =null values for "offset", "start", etc.
858	 * @parqm boolean $ignore_prefs Ignore the user's preferences about when they want to be notified and send it
859	 * @return bool true/false
860	 */
861	function _send_update($msg_type, $to_notify, $old_event, $new_event=null, $user=0, array $alarm=null, $ignore_prefs = false)
862	{
863		//error_log(__METHOD__."($msg_type,".array2string($to_notify).",...) ".array2string($new_event));
864		if (!is_array($to_notify))
865		{
866			$to_notify = array();
867		}
868		$notify_externals = $new_event ? $new_event['##notify_externals'] : $old_event['##notify_externals'];
869		$disinvited = $msg_type == MSG_DISINVITE ? array_keys($to_notify) : array();
870
871		$owner = $old_event ? $old_event['owner'] : $new_event['owner'];
872		if ($owner && !isset($to_notify[$owner]) && $msg_type != MSG_ALARM)
873		{
874			$to_notify[$owner] = 'OCHAIR';	// always include the event-owner
875		}
876
877		// ignore events in the past (give a tolerance of 10 seconds for the script)
878		if($old_event && $this->date2ts($old_event['start']) < ($this->now_su - 10))
879		{
880			return False;
881		}
882		// check if default timezone is set correctly to server-timezone (ical-parser messes with it!!!)
883		if ($GLOBALS['egw_info']['server']['server_timezone'] && ($tz = date_default_timezone_get()) != $GLOBALS['egw_info']['server']['server_timezone'])
884		{
885			$restore_tz = $tz;
886			date_default_timezone_set($GLOBALS['egw_info']['server']['server_timezone']);
887		}
888		$temp_user = $GLOBALS['egw_info']['user'];	// save user-date of the enviroment to restore it after
889
890		if (!$user)
891		{
892			$user = $temp_user['account_id'];
893		}
894		$lang = $GLOBALS['egw_info']['user']['preferences']['common']['lang'];
895		if ($GLOBALS['egw']->preferences->account_id != $user)
896		{
897			// Get correct preferences
898			$GLOBALS['egw']->preferences->__construct(is_numeric($user) ? $user : $temp_user['account_id']);
899			$GLOBALS['egw_info']['user']['preferences'] = $GLOBALS['egw']->preferences->read_repository();
900
901			// If target user/participant is not an account, try to get good notification message
902			if(!is_numeric($user))
903			{
904				$res_info = $this->resource_info($user);
905				$title = $res_info['name'] ?: Link::title($res_info['app'], $res_info['res_id']) ?: $res_info['res_id'] ?: $user;
906				$GLOBALS['egw']->preferences->values['fullname'] = $GLOBALS['egw']->preferences->values['lastname'] = $title;
907				$GLOBALS['egw']->preferences->values['firstname'] = '';
908				$msg = $GLOBALS['egw']->preferences->user['calendar']['notifyResponse'] ?: $GLOBALS['egw']->preferences->default['calendar']['notifyResponse'] ?: $GLOBALS['egw']->preferences->forced['calendar']['notifyResponse'];
909				$GLOBALS['egw_info']['user']['preferences']['calendar']['notifyResponse'] = $GLOBALS['egw']->preferences->parse_notify(
910					$msg
911				);
912			}
913
914		}
915		$senderid = $this->user;
916		$event = $msg_type == MSG_ADDED || $msg_type == MSG_MODIFIED ? $new_event : $old_event;
917
918		// add all group-members to the notification, unless they are already participants
919		foreach($to_notify as $userid => $statusid)
920		{
921			if (is_numeric($userid) && $GLOBALS['egw']->accounts->get_type($userid) == 'g' &&
922				($members = $GLOBALS['egw']->accounts->members($userid, true)))
923			{
924				foreach($members as $member)
925				{
926					if (!isset($to_notify[$member]))
927					{
928						$to_notify[$member] = 'G';	// Group-invitation
929					}
930				}
931			}
932		}
933		// unless we notfiy externals about everything aka 'responses'
934		// we will notify only an external chair, if only one exists
935		if (($notify_externals ?: $GLOBALS['egw_info']['user']['calendar']['notify_externals']) !== 'responses')
936		{
937			// check if we have *only* an external chair
938			$chair = null;
939			foreach($to_notify as $userid => $statusid)
940			{
941				$res_info = $quantity = $role = null;
942				calendar_so::split_status($statusid, $quantity, $role);
943				if ($role == 'CHAIR' && (empty($chair) || !is_numeric($chair)))
944				{
945					$chair = $userid;
946				}
947			}
948			// *only* an external chair --> do not notify anyone, but the external chair and the current user
949			if (!empty($chair) && !is_numeric($chair))
950			{
951				$to_notify = array($chair => $to_notify[$chair])+
952					(isset($to_notify[$user]) ? array($user => $to_notify[$user]) : array());
953			}
954		}
955
956		// Event is passed in user time, make sure that's taken into account for date calculations
957		$user_prefs = $GLOBALS['egw_info']['user']['preferences'];
958		$startdate = new Api\DateTime($event['start'], new DateTimeZone($user_prefs['common']['tz']));
959		$enddate = new Api\DateTime($event['end'], new DateTimeZone($user_prefs['common']['tz']));
960		$modified = new Api\DateTime($event['modified'], new DateTimeZone($user_prefs['common']['tz']));
961		if ($old_event) $olddate = new Api\DateTime($old_event['start'], new DateTimeZone($user_prefs['common']['tz']));
962
963		//error_log(__METHOD__."() date_default_timezone_get()=".date_default_timezone_get().", user-timezone=".Api\DateTime::$user_timezone->getName().", startdate=".$startdate->format().", enddate=".$enddate->format().", updated=".$modified->format().", olddate=".($olddate ? $olddate->format() : ''));
964		$owner_prefs = $ics = null;
965		foreach($to_notify as $userid => $statusid)
966		{
967			$res_info = $quantity = $role = null;
968			calendar_so::split_status($statusid, $quantity, $role);
969			if ($this->debug > 0) error_log(__METHOD__." trying to notify $userid, with $statusid ($role)");
970
971			// hack to add videoconference in event description, by always setting $cleared_event
972			// Can't re-load, if we're notifying of a cancelled recurrence we'll load the next event in the series
973			$cleared_event = $event;
974
975			if (!is_numeric($userid))
976			{
977				$res_info = $this->resource_info($userid);
978
979				// check if responsible of a resource has read rights on event (might be private!)
980				if ($res_info['app'] == 'resources' && $res_info['responsible'] &&
981					!$this->check_perms(Acl::READ, $event, 0, 'ts', null, $res_info['responsible']))
982				{
983					// --> use only details from (private-)cleared event only containing resource ($userid)
984					// reading server timezone, to be able to use cleared event for iCal generation further down
985					//$cleared_event = $this->read($event['id'], null, true, 'server');
986					$this->clear_private_infos($cleared_event, array($userid));
987				}
988				$userid = $res_info['responsible'];
989
990				if (empty($userid))	// no resource responsible: $userid===0
991				{
992					if (empty($res_info['email'])) continue;	// no way to notify
993					// check if event-owner wants non-EGroupware users notified
994					if (is_null($owner_prefs))
995					{
996						$preferences = new Api\Preferences($owner);
997						$owner_prefs = $preferences->read_repository();
998						if (!empty($notify_externals)) $owner_prefs['calendar']['notify_externals'] = $notify_externals;
999					}
1000					if ($role != 'CHAIR' &&		// always notify externals CHAIRs
1001						(empty($owner_prefs['calendar']['notify_externals']) ||
1002						$owner_prefs['calendar']['notify_externals'] == 'no'))
1003					{
1004						continue;
1005					}
1006					$userid = $res_info['email'];
1007				}
1008			}
1009
1010			if ($statusid == 'R' || $GLOBALS['egw']->accounts->get_type($userid) == 'g')
1011			{
1012				continue;	// dont notify rejected participants or groups
1013			}
1014
1015			if ($userid != $GLOBALS['egw_info']['user']['account_id'] ||
1016				($userid == $GLOBALS['egw_info']['user']['account_id'] &&
1017					$user_prefs['calendar']['receive_own_updates']==1) ||
1018				$msg_type == MSG_ALARM)
1019			{
1020				$tfn = $tln = $lid = null; //cleanup of lastname and fullname (in case they are set in a previous loop)
1021				if (is_numeric($userid))
1022				{
1023					$preferences = new Api\Preferences($userid);
1024					$GLOBALS['egw_info']['user']['preferences'] = $part_prefs = $preferences->read_repository();
1025					$fullname = Api\Accounts::username($userid);
1026					$tfn = Api\Accounts::id2name($userid,'account_firstname');
1027					$tln = Api\Accounts::id2name($userid,'account_lastname');
1028				}
1029				else	// external email address: use Api\Preferences of event-owner, plus some hardcoded settings (eg. ical notification)
1030				{
1031					if (is_null($owner_prefs))
1032					{
1033						$preferences = new Api\Preferences($owner);
1034						$GLOBALS['egw_info']['user']['preferences'] = $owner_prefs = $preferences->read_repository();
1035						if (!empty($notify_externals)) $owner_prefs['calendar']['notify_externals'] = $notify_externals;
1036					}
1037					$part_prefs = $owner_prefs;
1038					$part_prefs['calendar']['receive_updates'] = $owner_prefs['calendar']['notify_externals'];
1039					$part_prefs['calendar']['update_format'] = 'ical';	// use ical format
1040					$fullname = $res_info && !empty($res_info['name']) ? $res_info['name'] : $userid;
1041				}
1042				$m_type = $msg_type;
1043				if (!$ignore_prefs && !self::update_requested($userid, $part_prefs, $m_type, $old_event, $new_event, $role,
1044					$event['participants'][$GLOBALS['egw_info']['user']['account_id']]))
1045				{
1046					continue;
1047				}
1048				$action = $notify_msg = null;
1049				$method = $this->msg_type2ical_method($m_type, $action, $notify_msg, $user_prefs['calendar']);
1050
1051				if ($lang !== $part_prefs['common']['lang'])
1052				{
1053					Api\Translation::init();
1054					$lang = $part_prefs['common']['lang'];
1055				}
1056
1057				// Since we're running from cron, make sure notifications uses user's theme (for images)
1058				$GLOBALS['egw_info']['server']['template_set'] = $GLOBALS['egw_info']['user']['preferences']['common']['template_set'];
1059
1060				$event_arr = null;
1061				$details = $this->_get_event_details(isset($cleared_event) ? $cleared_event : $event,
1062					$action, $event_arr, $disinvited);
1063				$details['to-fullname'] = $fullname;
1064				$details['to-firstname'] = isset($tfn)? $tfn: '';
1065				$details['to-lastname'] = isset($tln)? $tln: '';
1066
1067				// event is in user-time of current user, now we need to calculate the tz-difference to the notified user and take it into account
1068				if (!isset($part_prefs['common']['tz'])) $part_prefs['common']['tz'] = $GLOBALS['egw_info']['server']['server_timezone'];
1069				try
1070				{
1071					$timezone = new DateTimeZone($part_prefs['common']['tz']);
1072				}
1073				catch(Exception $e)
1074				{
1075					$timezone = new DateTimeZone($GLOBALS['egw_info']['server']['server_timezone']);
1076				}
1077				$timeformat = $part_prefs['common']['timeformat'];
1078				switch($timeformat)
1079				{
1080			  		case '24':
1081						$timeformat = 'H:i';
1082						break;
1083					case '12':
1084						$timeformat = 'h:i a';
1085						break;
1086				}
1087				$timeformat = $part_prefs['common']['dateformat'] . ', ' . $timeformat;
1088
1089				// Set dates:
1090				// $details in "preference" format, $cleared_event as DateTime so calendar_ical->exportVCal() gets
1091				// the times right, since it assumes a timestamp is in server time
1092				$startdate->setTimezone($timezone);
1093				$details['startdate'] = $startdate->format($timeformat);
1094				$cleared_event['start'] = $startdate;
1095
1096				$enddate->setTimezone($timezone);
1097				$details['enddate'] = $enddate->format($timeformat);
1098				$cleared_event['end'] = $enddate;
1099
1100				$modified->setTimezone($timezone);
1101				$details['updated'] = $modified->format($timeformat) . ', ' . Api\Accounts::username($event['modifier']);
1102				$cleared_event['updated'] = $modified;
1103
1104				if ($old_event != False)
1105				{
1106					$olddate->setTimezone($timezone);
1107					$details['olddate'] = $olddate->format($timeformat);
1108				}
1109				// generate a personal videoconference url, if we need one
1110				if (!empty($event['##videoconference']) && class_exists('EGroupware\\Status\\Videoconference\\Call')
1111					&& !EGroupware\Status\Hooks::isVideoconferenceDisabled())
1112				{
1113					$avatar = new Api\Contacts\Photo(is_numeric($userid) ? "account:$userid" :
1114						(isset($res_info) && $res_info['type'] === 'c' ? $res_info['res_id'] : $userid),
1115						// disable sharing links currently, as sharing links from a different EGroupware user destroy the session
1116						true);
1117
1118					$details['videoconference'] = EGroupware\Status\Videoconference\Call::genMeetingUrl($event['##videoconference'], [
1119						'name' => $fullname,
1120						'email' => is_numeric($userid) ? Api\Accounts::id2name($userid, 'account_email') : $userid,
1121						'avatar' => (string)$avatar,
1122						'account_id' => $userid,
1123							'cal_id' => $details['id']
1124					], ['participants' =>array_filter($event['participants'], function($key){return is_numeric($key);}, ARRAY_FILTER_USE_KEY)], $startdate, $enddate);
1125					$event_arr['videoconference'] = [
1126						'field' => lang('Video Conference'),
1127						'data'  => $details['videoconference'],
1128					];
1129					// hack to add videoconference-url to ical, only if description was NOT cleared
1130					if (isset($cleared_event['description']))
1131					{
1132						$cleared_event['description'] = lang('Video conference').': '.$details['videoconference']."\n\n".$event['description'];
1133					}
1134				}
1135				//error_log(__METHOD__."() userid=$userid, timezone=".$timezone->getName().", startdate=$details[startdate], enddate=$details[enddate], updated=$details[updated], olddate=$details[olddate]");
1136
1137				list($subject,$notify_body) = explode("\n",$GLOBALS['egw']->preferences->parse_notify($notify_msg,$details),2);
1138				// alarm is NOT an iCal method, therefore we have to use extened (no iCal)
1139				switch($msg_type == MSG_ALARM ? 'extended' : $part_prefs['calendar']['update_format'])
1140				{
1141					case 'ical':
1142						if (is_null($ics) || $m_type != $msg_type || $event['##videoconference'])	// need different ical for organizer notification or videoconference join urls
1143						{
1144							$calendar_ical = new calendar_ical();
1145							$calendar_ical->setSupportedFields('full');	// full iCal fields+event TZ
1146							// we need to pass $event[id] so iCal class reads event again,
1147							// as event is in user TZ, but iCal class expects server TZ!
1148							$ics = $calendar_ical->exportVCal([$cleared_event],
1149								'2.0', $method, $cleared_event['recur_date'],
1150								'', 'utf-8', $method == 'REPLY' ? $user : 0
1151							);
1152							unset($calendar_ical);
1153						}
1154						$attachment = array(
1155							'string' => $ics,
1156							'filename' => 'cal.ics',
1157							'encoding' => '8bit',
1158							'type' => 'text/calendar; method='.$method,
1159						);
1160						if ($m_type != $msg_type) unset($ics);
1161						$subject = isset($cleared_event) ? $cleared_event['title'] : $event['title'];
1162						// fall through
1163					case 'extended':
1164
1165						$details_body = lang('Event Details follow').":\n";
1166						foreach($event_arr as $key => $val)
1167						{
1168							if(!empty($details[$key]))
1169							{
1170								switch($key)
1171								{
1172							 		case 'access':
1173									case 'priority':
1174									case 'link':
1175									case 'description':
1176									case 'title':
1177										break;
1178									default:
1179										$details_body .= sprintf("%-20s %s\n",$val['field'].':',$details[$key]);
1180										break;
1181							 	}
1182							}
1183						}
1184						break;
1185				}
1186				// send via notification_app
1187				if($GLOBALS['egw_info']['apps']['notifications']['enabled'])
1188				{
1189					try {
1190						//error_log(__METHOD__."() notifying $userid from $senderid: $subject");
1191						$notification = new notifications();
1192						$notification->set_receivers(array($userid));
1193						$notification->set_sender($senderid);
1194						$notification->set_subject($subject);
1195						// as we want ical body to be just description, we can NOT set links, as they get appended to body
1196						if ($part_prefs['calendar']['update_format'] != 'ical')
1197						{
1198							$notification->set_message($notify_body."\n\n".$details['description']."\n\n".$details_body);
1199							$notification->set_links(array($details['link_arr']));
1200						}
1201						else
1202						{
1203							// iCal: description need to be separated from body by fancy separator
1204							$notification->set_message($notify_body."\n\n".$details_body."\n*~*~*~*~*~*~*~*~*~*\n\n".$details['description']);
1205						}
1206						// popup notifiactions: set subject, different message (without separator) and (always) links
1207						$notification->set_popupsubject($subject);
1208
1209						if ($method =='REQUEST')
1210						{
1211							// Add ACCEPT|REHECT|TENTATIVE actions
1212							$notification->set_popupdata('calendar', array(
1213								'event_id' => $event['id'],
1214								'user_id' => $userid,
1215								'type' => $m_type,
1216								'id' => $event['id'],
1217								'app' => 'calendar',
1218								'videoconference' => $details['videoconference'],
1219							));
1220						}
1221						if ($m_type === MSG_ALARM)
1222						{
1223							$notification->set_popupdata('calendar',
1224								array('egw_pr_notify' => 1,
1225									'type' => $m_type,
1226									'videoconference' => $details['videoconference'],
1227									'account_id' => $senderid,
1228									'name' =>  Api\Accounts::username($senderid)
1229								)
1230								+ ($alarm ? ['alarm-offset' => (int)$alarm['offset']] : []));
1231						}
1232						$notification->set_popupmessage($subject."\n\n".$notify_body."\n\n".$details['description']."\n\n".$details_body."\n\n");
1233						$notification->set_popuplinks(array($details['link_arr']+array('app'=>'calendar')));
1234
1235						if(is_array($attachment)) { $notification->set_attachments(array($attachment)); }
1236						$notification->send();
1237						$errors = notifications::errors(true);
1238					}
1239					catch (Exception $exception) {
1240						$errors = [$exception->getMessage()];
1241						continue;
1242					}
1243				}
1244				else
1245				{
1246					$errors = [lang('Can not send any notifications because notifications app is not installed!')];
1247				}
1248				foreach($errors as $error)
1249				{
1250					error_log(__METHOD__."() Error notifying $userid from $senderid: $subject: $error");
1251					// send notification errors via push to current user (not session, as alarms send via async job have none!)
1252					(new Api\Json\Push($GLOBALS['egw_info']['user']['account_id']))->message(
1253						lang('Error notifying %1', !is_numeric($userid) ? $userid :
1254							Api\Accounts::id2name($userid, 'account_fullname').' <'.Api\Accounts::id2name($userid, 'account_email').'>').
1255						"\n".$subject."\n".$error, 'error');
1256				}
1257			}
1258		}
1259		// restore the enviroment (preferences->read_repository() sets the timezone!)
1260		$GLOBALS['egw_info']['user'] = $temp_user;
1261		if ($GLOBALS['egw']->preferences->account_id != $temp_user['account_id'])
1262		{
1263			$GLOBALS['egw']->preferences->__construct($temp_user['account_id']);
1264			$GLOBALS['egw_info']['user']['preferences'] = $GLOBALS['egw']->preferences->read_repository();
1265			//echo "<p>".__METHOD__."() restored enviroment of #$temp_user[account_id] $temp_user[account_fullname]: tz={$GLOBALS['egw_info']['user']['preferences']['common']['tz']}</p>\n";
1266		}
1267		else
1268		{
1269			// Loading other user's preferences can change current user's tz
1270			$GLOBALS['egw']->preferences->check_set_tz_offset();
1271		}
1272		if ($lang !== $GLOBALS['egw_info']['user']['preferences']['common']['lang'])
1273		{
1274			Api\Translation::init();
1275		}
1276		// restore timezone, in case we had to reset it to server-timezone
1277		if ($restore_tz) date_default_timezone_set($restore_tz);
1278
1279		return true;
1280	}
1281
1282	function get_update_message($event,$added)
1283	{
1284		$nul = null;
1285		$details = $this->_get_event_details($event,$added ? lang('Added') : lang('Modified'),$nul);
1286
1287		$notify_msg = $this->cal_prefs[$added || empty($this->cal_prefs['notifyModified']) ? 'notifyAdded' : 'notifyModified'];
1288
1289		return explode("\n",$GLOBALS['egw']->preferences->parse_notify($notify_msg,$details),2);
1290	}
1291
1292	/**
1293	 * Function called via async service, when an alarm is to be send
1294	 *
1295	 * @param array $alarm array with keys owner, cal_id, all
1296	 * @return boolean
1297	 */
1298	function send_alarm($alarm)
1299	{
1300		//echo "<p>bocalendar::send_alarm("; print_r($alarm); echo ")</p>\n";
1301		$GLOBALS['egw_info']['user']['account_id'] = $this->owner = $alarm['owner'];
1302
1303		$event_time_user = Api\DateTime::server2user($alarm['time'] + $alarm['offset']);	// alarm[time] is in server-time, read requires user-time
1304		if (!$alarm['owner'] || !$alarm['cal_id'] || !($event = $this->read($alarm['cal_id'],$event_time_user)))
1305		{
1306			return False;	// event not found
1307		}
1308		if ($alarm['all'])
1309		{
1310			$to_notify = $event['participants'];
1311		}
1312		elseif ($this->check_perms(Acl::READ,$event))	// checks agains $this->owner set to $alarm[owner]
1313		{
1314			$to_notify[$alarm['owner']] = 'A';
1315		}
1316		else
1317		{
1318			return False;	// no rights
1319		}
1320		// need to load calendar translations and set currentapp, so calendar can reload a different lang
1321		Api\Translation::add_app('calendar');
1322		$GLOBALS['egw_info']['flags']['currentapp'] = 'calendar';
1323
1324		$ret = $this->_send_update(MSG_ALARM, $to_notify, $event, False, $alarm['owner'], $alarm);
1325
1326		// create a new alarm for recuring events for the next event, if one exists
1327		if ($event['recur_type'] != MCAL_RECUR_NONE && ($event = $this->read($alarm['cal_id'],$event_time_user+1)))
1328		{
1329			$alarm['time'] = $this->date2ts($event['start']) - $alarm['offset'];
1330			unset($alarm['times']);
1331			unset($alarm['next']);
1332			unset($alarm['keep_time']);	// need to remove the keep_time, as otherwise the alarm would be deleted automatically
1333			//error_log(__METHOD__."() moving alarm to next recurrence ".array2string($alarm));
1334			$this->save_alarm($alarm['cal_id'], $alarm, false);	// false = do NOT update timestamp, as nothing changed for iCal clients
1335		}
1336		return $ret;
1337	}
1338
1339	/**
1340	 * saves an event to the database, does NOT do any notifications, see calendar_boupdate::update for that
1341	 *
1342	 * This methode converts from user to server time and handles the insertion of users and dates of repeating events
1343	 *
1344	 * @param array $event
1345	 * @param boolean $ignore_acl =false should we ignore the acl
1346	 * @param boolean $updateTS =true update the content history of the event
1347	 * Please note: you should ALLWAYS update timestamps, as they are required for sync!
1348	 * @return int|boolean $cal_id > 0 or false on error (eg. permission denied)
1349	 */
1350	function save($event,$ignore_acl=false,$updateTS=true)
1351	{
1352		//error_log(__METHOD__.'('.array2string($event).", $ignore_acl, $updateTS)");
1353
1354		// check if user has the permission to update / create the event
1355		if (!$ignore_acl && ($event['id'] && !$this->check_perms(Acl::EDIT,$event['id']) ||
1356			!$event['id'] && !$this->check_perms(Acl::EDIT,0,$event['owner']) &&
1357			!$this->check_perms(Acl::ADD,0,$event['owner'])))
1358		{
1359			return false;
1360		}
1361
1362		if ($event['id'])
1363		{
1364			// invalidate the read-cache if it contains the event we store now
1365			if ($event['id'] == self::$cached_event['id']) self::$cached_event = array();
1366			$old_event = $this->read($event['id'], $event['recurrence'], $ignore_acl, 'server');
1367		}
1368		else
1369		{
1370			$old_event = null;
1371		}
1372		if (!isset($event['whole_day'])) $event['whole_day'] = $this->isWholeDay($event);
1373
1374		$this->check_reset_statuses($event, $old_event);
1375
1376		// set recur-enddate/range-end to real end-date of last recurrence
1377		if ($event['recur_type'] != MCAL_RECUR_NONE && $event['recur_enddate'] && $event['start'])
1378		{
1379			$event['recur_enddate'] = new Api\DateTime($event['recur_enddate'], calendar_timezones::DateTimeZone($event['tzid']));
1380			$event['recur_enddate']->setTime(23,59,59);
1381			$rrule = calendar_rrule::event2rrule($event, true, Api\DateTime::$user_timezone->getName());
1382			$rrule->rewind();
1383			$enddate = $rrule->current();
1384			do
1385			{
1386				$rrule->next_no_exception();
1387				$occurrence = $rrule->current();
1388			}
1389			while ($rrule->valid($event['whole_day']) && ($enddate = $occurrence));
1390			$enddate->modify(($event['end'] - $event['start']).' second');
1391			$event['recur_enddate'] = $save_event['recur_enddate'] = $enddate->format('ts');
1392			//error_log(__METHOD__."($event[title]) start=".Api\DateTime::to($event['start'],'string').', end='.Api\DateTime::to($event['end'],'string').', range_end='.Api\DateTime::to($event['recur_enddate'],'string'));
1393		}
1394
1395		$save_event = $event;
1396		if ($event['whole_day'])
1397		{
1398			if (!empty($event['start']))
1399			{
1400				$time = $this->so->startOfDay(new Api\DateTime($event['start'], Api\DateTime::$user_timezone));
1401				$event['start'] = Api\DateTime::to($time, 'ts');
1402				$save_event['start'] = $time;
1403			}
1404			if (!empty($event['end']))
1405			{
1406				$time = new Api\DateTime($event['end'], Api\DateTime::$user_timezone);
1407
1408				// Check to see if switching timezones changes the date, we'll need to adjust for that
1409				$end_event_timezone = clone $time;
1410				$time->setServer();
1411				$delta = (int)$end_event_timezone->format('z') - (int)$time->format('z');
1412				$time->add("$delta days");
1413
1414				$time->setTime(23, 59, 59);
1415				$event['end'] = Api\DateTime::to($time, 'ts');
1416				$save_event['end'] = $time;
1417			}
1418			if (!empty($event['recurrence']))
1419			{
1420				$time = $this->so->startOfDay(new Api\DateTime($event['recurrence'], Api\DateTime::$user_timezone));
1421				$event['recurrence'] = Api\DateTime::to($time, 'ts');
1422			}
1423			if (!empty($event['recur_enddate']))
1424			{
1425				// all-day events are handled in server time, but here (BO) it's in user time
1426				$time = new Api\DateTime($event['recur_enddate'], Api\DateTime::$user_timezone);
1427				$time->setTime(23, 59, 59);
1428				// Check to see if switching timezones changes the date, we'll need to adjust for that
1429				$enddate_event_timezone = clone $time;
1430				$time->setServer();
1431				$delta = (int)$enddate_event_timezone->format('z') - (int)$time->format('z');
1432				$time->add("$delta days");
1433
1434				//$time->setServer();
1435				$time->setTime(23, 59, 59);
1436
1437				$event['recur_enddate'] = $save_event['recur_enddate'] = $time;
1438			}
1439			$timestamps = array('modified','created');
1440			// all-day events are handled in server time
1441		//	$event['tzid'] = $save_event['tzid'] = Api\DateTime::$server_timezone->getName();
1442		}
1443		else
1444		{
1445			$timestamps = array('start','end','modified','created','recur_enddate','recurrence');
1446		}
1447		// we run all dates through date2ts, to adjust to server-time and the possible date-formats
1448		foreach($timestamps as $ts)
1449		{
1450			// we convert here from user-time to timestamps in server-time!
1451			if (isset($event[$ts])) $event[$ts] = $event[$ts] ? $this->date2ts($event[$ts],true) : 0;
1452		}
1453		// convert tzid name to integer tz_id, of set user default
1454		if (empty($event['tzid']) || !($event['tz_id'] = calendar_timezones::tz2id($event['tzid'])))
1455		{
1456			$event['tz_id'] = calendar_timezones::tz2id($event['tzid'] = Api\DateTime::$user_timezone->getName());
1457		}
1458		// same with the recur exceptions
1459		if (isset($event['recur_exception']) && is_array($event['recur_exception']))
1460		{
1461			foreach($event['recur_exception'] as &$date)
1462			{
1463				if ($event['whole_day'])
1464				{
1465					$time = $this->so->startOfDay(new Api\DateTime($date, Api\DateTime::$user_timezone));
1466					$date = Api\DateTime::to($time, 'ts');
1467				}
1468				else
1469				{
1470					$date = $this->date2ts($date,true);
1471				}
1472			}
1473			unset($date);
1474		}
1475		// same with the alarms
1476		if (isset($event['alarm']) && is_array($event['alarm']) && isset($event['start']))
1477		{
1478			// Expand group invitations so we don't lose individual alarms
1479			$expanded = $event;
1480			$this->enum_groups($expanded);
1481			foreach($event['alarm'] as $id => &$alarm)
1482			{
1483				if($alarm['time'])
1484				{
1485					$alarm['time'] = $this->date2ts($alarm['time'], true);    // user to server-time
1486				}
1487
1488				// remove alarms belonging to not longer existing or rejected participants
1489				if ($alarm['owner'] && isset($expanded['participants']))
1490				{
1491					// Don't auto-delete alarm if for all users
1492					if($alarm['all']) continue;
1493
1494					$status = $expanded['participants'][$alarm['owner']];
1495					if (!isset($status) || calendar_so::split_status($status) === 'R')
1496					{
1497						unset($event['alarm'][$id]);
1498						$this->so->delete_alarm($id);
1499						//error_log(__LINE__.': '.__METHOD__."(".array2string($event).") deleting alarm=".array2string($alarm).", $status=".array2string($alarm));
1500					}
1501				}
1502				else if (!$alarm['owner'])
1503				{
1504					$alarm['owner'] = $event['owner'];
1505				}
1506			}
1507		}
1508		// update all existing alarm times, in case alarm got moved and alarms are not include in $event
1509		if ($old_event && is_array($old_event['alarm']) && isset($event['start']))
1510		{
1511			foreach($old_event['alarm'] as $id => &$alarm)
1512			{
1513				if (!isset($event['alarm'][$id]))
1514				{
1515					$alarm['time'] = $event['start'] - $alarm['offset'];
1516					if ($alarm['time'] < time()) calendar_so::shift_alarm($event, $alarm);
1517						// remove (not store) alarms belonging to not longer existing or rejected participants
1518					$status = isset($event['participants']) ? $event['participants'][$alarm['owner']] :
1519						$old_event['participants'][$alarm['owner']];
1520					if (!$alarm['owner'] || isset($status) && calendar_so::split_status($status) !== 'R')
1521					{
1522						$this->so->save_alarm($event['id'], $alarm);
1523						//error_log(__LINE__.': '.__METHOD__."() so->save_alarm($event[id], ".array2string($alarm).")");
1524					}
1525					else
1526					{
1527						$this->so->delete_alarm($id);
1528						//error_log(__LINE__.': '.__METHOD__."(".array2string($event).") deleting alarm=".array2string($alarm).", $status=".array2string($alarm));
1529					}
1530				}
1531			}
1532		}
1533
1534		// you should always update modification time (ctag depends on it!)
1535		if ($updateTS)
1536		{
1537			$event['modified'] = $save_event['modified'] = $this->now;
1538			$event['modifier'] = $save_event['modifier'] = $this->user;
1539		}
1540
1541		if (empty($event['id']) && (!isset($event['created']) || $event['created'] > $this->now))
1542		{
1543			$event['created'] = $save_event['created'] = $this->now;
1544			$event['creator'] = $save_event['creator'] = $this->user;
1545		}
1546		$set_recurrences = $old_event ? abs($event['recur_enddate'] - $old_event['recur_enddate']) > 1 : false;
1547		$set_recurrences_start = 0;
1548		if (($cal_id = $this->so->save($event,$set_recurrences,$set_recurrences_start,0,$event['etag'])) && $set_recurrences && $event['recur_type'] != MCAL_RECUR_NONE)
1549		{
1550			$save_event['id'] = $cal_id;
1551			// unset participants to enforce the default stati for all added recurrences
1552			unset($save_event['participants']);
1553			$this->set_recurrences($save_event, $set_recurrences_start);
1554		}
1555
1556		// create links for new participants from addressbook, if configured
1557		if ($cal_id && $GLOBALS['egw_info']['server']['link_contacts'] && $event['participants'])
1558		{
1559			foreach($event['participants'] as $uid => $status)
1560			{
1561				$user_type = $user_id = null;
1562				calendar_so::split_user($uid, $user_type, $user_id);
1563				if ($user_type == 'c' && (!$old_event || !isset($old_event['participants'][$uid])))
1564				{
1565					Link::link('calendar', $cal_id, 'addressbook', $user_id);
1566				}
1567			}
1568		}
1569
1570		// Update history
1571		$tracking = new calendar_tracking($this);
1572		if (empty($event['id']) && !empty($cal_id)) $event['id'] = $cal_id;
1573		// we run all dates through date2ts, to adjust to server-time and the possible date-formats
1574		// This is done here to avoid damaging the actual event when saving, but the old event is in server-time
1575		foreach ($timestamps as $ts)
1576		{
1577			// we convert here from user-time to timestamps in server-time!
1578			if (isset($save_event[$ts])) $save_event[$ts] = $save_event[$ts] ? calendar_bo::date2ts($save_event[$ts], true) : 0;
1579		}
1580		foreach(['start','end','recur_enddate'] as $ts)
1581		{
1582			if(is_object($save_event[$ts]))
1583			{
1584				$save_event[$ts] = $save_event[$ts]->format('ts');
1585			}
1586		}
1587		$tracking->track($save_event, $old_event);
1588
1589		return $cal_id;
1590	}
1591
1592	/**
1593	 * Check if the current user has the necessary ACL rights to change the status of $uid
1594	 *
1595	 * For contacts we use edit rights of the owner of the event (aka. edit rights of the event).
1596	 *
1597	 * @param int|string $uid account_id or 1-char type-identifer plus id (eg. c15 for addressbook entry #15)
1598	 * @param array|int $event event array or id of the event
1599	 * @return boolean
1600	 */
1601	function check_status_perms($uid,$event)
1602	{
1603		if ($uid[0] == 'c' || $uid[0] == 'e')	// for contact we use the owner of the event
1604		{
1605			if (!is_array($event) && !($event = $this->read($event))) return false;
1606
1607			return $this->check_perms(Acl::EDIT,0,$event['owner']);
1608		}
1609		// check if we have a category Acl for the event or not (null)
1610		$access = $this->check_cat_acl(self::CAT_ACL_STATUS,$event);
1611		if (!is_null($access))
1612		{
1613			return $access;
1614		}
1615		// no access or denied access because of category acl --> regular check
1616		if (!is_numeric($uid))	// this is eg. for resources (r123)
1617		{
1618			$resource = $this->resource_info($uid);
1619
1620			return Acl::EDIT & $resource['rights'];
1621		}
1622		if (!is_array($event) && !($event = $this->read($event))) return false;
1623
1624		// regular user and groups (need to check memberships too)
1625		if (!isset($event['participants'][$uid]))
1626		{
1627			$memberships = $GLOBALS['egw']->accounts->memberships($uid,true);
1628		}
1629		$memberships[] = $uid;
1630		return array_intersect($memberships, array_keys($event['participants'])) && $this->check_perms(Acl::EDIT,0,$uid);
1631	}
1632
1633	/**
1634	 * Check if current user has a certain right on the categories of an event
1635	 *
1636	 * Not having the given right for a single category, means not having it!
1637	 *
1638	 * @param int $right self::CAT_ACL_{ADD|STATUS}
1639	 * @param int|array $event
1640	 * @return boolean true if use has the right, false if not
1641	 * @return boolean false=access denied because of cat acl, true access granted because of cat acl,
1642	 * 	null = cat has no acl
1643	 */
1644	function check_cat_acl($right,$event)
1645	{
1646		if (!is_array($event)) $event = $this->read($event);
1647
1648		$ret = null;
1649		if ($event['category'])
1650		{
1651			foreach(is_array($event['category']) ? $event['category'] : explode(',',$event['category']) as $cat_id)
1652			{
1653				$access = self::has_cat_right($right,$cat_id,$this->user);
1654				if ($access === true)
1655				{
1656					$ret = true;
1657					break;
1658				}
1659				if ($access === false)
1660				{
1661					$ret = false;	// cat denies access --> check further cats
1662				}
1663			}
1664		}
1665		//echo "<p>".__METHOD__."($event[id]: $event[title], $right) = ".array2string($ret)."</p>\n";
1666		return $ret;
1667	}
1668
1669	/**
1670	 * Array with $cat_id => $rights pairs for current user (no entry means, cat is not limited by ACL!)
1671	 *
1672	 * @var array
1673	 */
1674	private static $cat_rights_cache;
1675
1676	/**
1677	 * Get rights for a given category id
1678	 *
1679	 * @param int $cat_id =null null to return array with all cats
1680	 * @return array with account_id => right pairs
1681	 */
1682	public static function get_cat_rights($cat_id=null)
1683	{
1684		if (!isset(self::$cat_rights_cache))
1685		{
1686			self::$cat_rights_cache = Api\Cache::getSession('calendar','cat_rights',
1687				array($GLOBALS['egw']->acl,'get_location_grants'),array('L%','calendar'));
1688		}
1689		//echo "<p>".__METHOD__."($cat_id) = ".array2string($cat_id ? self::$cat_rights_cache['L'.$cat_id] : self::$cat_rights_cache)."</p>\n";
1690		return $cat_id ? self::$cat_rights_cache['L'.$cat_id] : self::$cat_rights_cache;
1691	}
1692
1693	/**
1694	 * Set rights for a given single category and user
1695	 *
1696	 * @param int $cat_id
1697	 * @param int $user
1698	 * @param int $rights self::CAT_ACL_{ADD|STATUS} or'ed together
1699	 */
1700	public static function set_cat_rights($cat_id,$user,$rights)
1701	{
1702		//echo "<p>".__METHOD__."($cat_id,$user,$rights)</p>\n";
1703		if (!isset(self::$cat_rights_cache)) self::get_cat_rights($cat_id);
1704
1705		if ((int)$rights != (int)self::$cat_rights_cache['L'.$cat_id][$user])
1706		{
1707			if ($rights)
1708			{
1709				self::$cat_rights_cache['L'.$cat_id][$user] = $rights;
1710				$GLOBALS['egw']->acl->add_repository('calendar','L'.$cat_id,$user,$rights);
1711			}
1712			else
1713			{
1714				unset(self::$cat_rights_cache['L'.$cat_id][$user]);
1715				if (!self::$cat_rights_cache['L'.$cat_id]) unset(self::$cat_rights_cache['L'.$cat_id]);
1716				$GLOBALS['egw']->acl->delete_repository('calendar','L'.$cat_id,$user);
1717			}
1718			Api\Cache::setSession('calendar','cat_rights',self::$cat_rights_cache);
1719		}
1720	}
1721
1722	/**
1723	 * Check if current user has a given right on a category (if it's restricted!)
1724	 *
1725	 * @param int $cat_id
1726	 * @return boolean false=access denied because of cat acl, true access granted because of cat acl,
1727	 * 	null = cat has no acl
1728	 */
1729	public static function has_cat_right($right,$cat_id,$user)
1730	{
1731		static $cache=null;
1732
1733		if (!isset($cache[$cat_id]))
1734		{
1735			$all = $own = 0;
1736			$cat_rights = self::get_cat_rights($cat_id);
1737			if (!is_null($cat_rights))
1738			{
1739				static $memberships=null;
1740				if (is_null($memberships))
1741				{
1742					$memberships = $GLOBALS['egw']->accounts->memberships($user,true);
1743					$memberships[] = $user;
1744				}
1745				foreach($cat_rights as $uid => $value)
1746				{
1747					$all |= $value;
1748					if (in_array($uid,$memberships)) $own |= $value;
1749				}
1750			}
1751			foreach(array(self::CAT_ACL_ADD,self::CAT_ACL_STATUS) as $mask)
1752			{
1753				$cache[$cat_id][$mask] = !($all & $mask) ? null : !!($own & $mask);
1754			}
1755		}
1756		//echo "<p>".__METHOD__."($right,$cat_id) all=$all, own=$own returning ".array2string($cache[$cat_id][$right])."</p>\n";
1757		return $cache[$cat_id][$right];
1758	}
1759
1760	/**
1761	 * set the status of one participant for a given recurrence or for all recurrences since now (includes recur_date=0)
1762	 *
1763	 * @param int|array $event event-array or id of the event
1764	 * @param string|int $uid account_id or 1-char type-identifer plus id (eg. c15 for addressbook entry #15)
1765	 * @param int|char $status numeric status (defines) or 1-char code: 'R', 'U', 'T' or 'A'
1766	 * @param int $recur_date =0 date to change, or 0 = all since now
1767	 * @param boolean $ignore_acl =false do not check the permisions for the $uid, if true
1768	 * @param boolean $updateTS =true update the content history of the event
1769	 * DEPRECATED: we allways (have to) update timestamp, as they are required for sync!
1770	 * @param boolean $skip_notification =false true: do not send notification messages
1771	 * @return int number of changed recurrences
1772	 */
1773	function set_status($event,$uid,$status,$recur_date=0,$ignore_acl=false,$updateTS=true,$skip_notification=false)
1774	{
1775		unset($updateTS);
1776
1777		$cal_id = is_array($event) ? $event['id'] : $event;
1778		//echo "<p>calendar_boupdate::set_status($cal_id,$uid,$status,$recur_date)</p>\n";
1779		if (!$cal_id || (!$ignore_acl && !$this->check_status_perms($uid,$event)))
1780		{
1781			return false;
1782		}
1783		$quantity = $role = null;
1784		calendar_so::split_status($status, $quantity, $role);
1785		if ($this->log)
1786		{
1787			error_log(__FILE__.'['.__LINE__.'] '.__METHOD__.
1788				"($cal_id, $uid, $status, $recur_date)\n",3,$this->logfile);
1789		}
1790		$old_event = $this->read($cal_id, $recur_date, $ignore_acl, 'server');
1791		if (($Ok = $this->so->set_status($cal_id,is_numeric($uid)?'u':$uid[0],
1792				is_numeric($uid)?$uid:substr($uid,1),$status,
1793				$recur_date?$this->date2ts($recur_date,true):0,$role)))
1794		{
1795			if ($status == 'R')	// remove alarms belonging to rejected participants
1796			{
1797				foreach(is_array($event) && isset($event['alarm']) ? $event['alarm'] : $old_event['alarm'] as $id => $alarm)
1798				{
1799					if ((string)$alarm['owner'] === (string)$uid)
1800					{
1801						$this->so->delete_alarm($id);
1802						//error_log(__LINE__.': '.__METHOD__."(".array2string($event).", '$uid', '$status', ...) deleting alarm=".array2string($alarm).", $status=".array2string($alarm));
1803					}
1804				}
1805			}
1806
1807			static $status2msg = array(
1808				'R' => MSG_REJECTED,
1809				'T' => MSG_TENTATIVE,
1810				'A' => MSG_ACCEPTED,
1811				'D' => MSG_DELEGATED,
1812			);
1813			// Reset cached event
1814			static::$cached_event = array();
1815
1816			if (isset($status2msg[$status]) && !$skip_notification)
1817			{
1818				if (!is_array($event)) $event = $this->read($cal_id);
1819				if (isset($recur_date)) $event = $this->read($event['id'],$recur_date); //re-read the actually edited recurring event
1820				$user_id = is_numeric($uid) ? (int)$uid : $uid;
1821				$this->send_update($status2msg[$status],$event['participants'],$event, null, $user_id);
1822			}
1823
1824			// Update history
1825			$event = $this->read($cal_id, $recur_date, $ignore_acl, 'server');
1826			$tracking = new calendar_tracking($this);
1827			$tracking->track($event, $old_event);
1828
1829			// notify the link-class about the update, as other apps may be subscribed to it
1830			Link::notify_update('calendar',$event['id'],$event,"update");
1831		}
1832		return $Ok;
1833	}
1834
1835	/**
1836	 * update the status of all participant for a given recurrence or for all recurrences since now (includes recur_date=0)
1837	 *
1838	 * @param array $new_event event-array with the new stati
1839	 * @param array $old_event event-array with the old stati
1840	 * @param int $recur_date =0 date to change, or 0 = all since now
1841	 * @param boolean $skip_notification Do not send notifications.  Parameter passed on to set_status().
1842	 */
1843	function update_status($new_event, $old_event , $recur_date=0, $skip_notification=false)
1844	{
1845		if (!isset($new_event['participants'])) return;
1846
1847		// check the old list against the new list
1848		foreach ($old_event['participants'] as $userid => $status)
1849  		{
1850            if (!isset($new_event['participants'][$userid])){
1851            	// Attendee will be deleted this way
1852            	$new_event['participants'][$userid] = 'G';
1853            }
1854            elseif ($new_event['participants'][$userid] == $status)
1855            {
1856            	// Same status -- nothing to do.
1857            	unset($new_event['participants'][$userid]);
1858            }
1859		}
1860		// write the changes
1861		foreach ($new_event['participants'] as $userid => $status)
1862		{
1863			$this->set_status($old_event, $userid, $status, $recur_date, true, false,$skip_notification);
1864		}
1865
1866		// notify the link-class about the update, as other apps may be subscribed to it
1867		Link::notify_update('calendar',$new_event['id'],$new_event,"update");
1868  }
1869
1870	/**
1871	 * deletes an event
1872	 *
1873	 * @param int $cal_id id of the event to delete
1874	 * @param int $recur_date =0 if a single event from a series should be deleted, its date
1875	 * @param boolean $ignore_acl =false true for no ACL check, default do ACL check
1876	 * @param boolean|array $skip_notification =false or array with uid to skip eg. [5,'eemail@example.org']
1877	 * @param boolean $delete_exceptions =true true: delete, false: keep exceptions (with new UID)
1878	 * @param int &$exceptions_kept=null on return number of kept exceptions
1879	 * @return boolean true on success, false on error (usually permission denied)
1880	 */
1881	function delete($cal_id, $recur_date=0, $ignore_acl=false, $skip_notification=false,
1882		$delete_exceptions=true, &$exceptions_kept=null)
1883	{
1884		//error_log(__METHOD__."(cal_id=$cal_id, recur_date=$recur_date, ignore_acl=$ignore_acl, skip_notifications=$skip_notification)");
1885		if (!($event = $this->read($cal_id,$recur_date)) ||
1886			!$ignore_acl && !$this->check_perms(Acl::DELETE,$event))
1887		{
1888			return false;
1889		}
1890
1891		// Don't send notification if the event has already been deleted
1892		if (!$event['deleted'] && (!$skip_notification || is_array($skip_notification)))
1893		{
1894			$to_notify = !is_array($skip_notification) ? $event['participants'] :
1895				array_diff_key($event['participants'], array_flip($skip_notification));
1896			$this->send_update(MSG_DELETED, $to_notify, $event);
1897		}
1898
1899		if (!$recur_date || $event['recur_type'] == MCAL_RECUR_NONE)
1900		{
1901			$config = Api\Config::read('phpgwapi');
1902			if(!$config['calendar_delete_history'] || $event['deleted'])
1903			{
1904				$this->so->delete($cal_id);
1905
1906				// delete all links to the event
1907				Link::unlink(0,'calendar',$cal_id);
1908			}
1909			elseif ($config['calendar_delete_history'])
1910			{
1911				// mark all links to the event as deleted, but keep them
1912				Link::unlink(0,'calendar',$cal_id,'','','',true);
1913
1914				$event['deleted'] = $this->now;
1915				$this->save($event, $ignore_acl);
1916				// Actually delete alarms
1917				if (isset($event['alarm']) && is_array($event['alarm']))
1918				{
1919					foreach($event['alarm'] as $id => $alarm)
1920					{
1921						$this->delete_alarm($id);
1922					}
1923				}
1924			}
1925
1926			// delete or keep (with new uid) exceptions of a recurring event
1927			if ($event['recur_type'] != MCAL_RECUR_NONE)
1928			{
1929				$exceptions_kept = 0;
1930				foreach ($this->so->get_related($event['uid']) as $id)
1931				{
1932					if ($delete_exceptions)
1933					{
1934						$this->delete($id, 0, $ignore_acl, true);
1935					}
1936					else
1937					{
1938						if (!($exception = $this->read($id))) continue;
1939						$exception['uid'] = Api\CalDAV::generate_uid('calendar', $id);
1940						$exception['reference'] = $exception['recurrence'] = 0;
1941						$this->update($exception, true, true, false, true, $msg=null, true);
1942						++$exceptions_kept;
1943					}
1944				}
1945			}
1946		}
1947		else	// delete an exception
1948		{
1949			// check if deleted recurrance has alarms (because it's the next recurrance) --> move it to next recurrance
1950			if ($event['alarm'])
1951			{
1952				$next_recurrance = null;
1953				foreach($event['alarm'] as &$alarm)
1954				{
1955					if (($alarm['time'] == $recur_date) || ($alarm['time']+$alarm['offset'] == $recur_date))
1956					{
1957						//error_log(__METHOD__.__LINE__.'->'.array2string($recur_date));
1958						//error_log(__METHOD__.__LINE__.array2string($event));
1959						if (is_null($next_recurrance))
1960						{
1961							$checkdate = $recur_date;
1962							//if ($alarm['time']+$alarm['offset'] == $recur_date) $checkdate = $recur_date + $alarm['offset'];
1963							if (($e = $this->read($cal_id,$checkdate+1)))
1964							{
1965								$next_recurrance = $this->date2ts($e['start']);
1966							}
1967						}
1968						$alarm['time'] = $this->date2ts($next_recurrance, true);	// user to server-time
1969						$alarm['cal_id'] = $cal_id;
1970						unset($alarm['times']);
1971						unset($alarm['next']);
1972						$this->so->save_alarm($event['id'], $alarm);
1973					}
1974				}
1975			}
1976			// need to read series master, as otherwise existing exceptions will be lost!
1977			$recur_date = $this->date2ts($event['start']);
1978			//if ($event['alarm']) $alarmbuffer = $event['alarm'];
1979			$event = $this->read($cal_id);
1980			//if (isset($alarmbuffer)) $event['alarm'] = $alarmbuffer;
1981			$event['recur_exception'][] = $recur_date;
1982			$this->save($event);// updates the content-history
1983
1984			// for "real" push, need to push delete of recurence
1985			if (!Api\Json\Push::onlyFallback())
1986			{
1987				Api\Link::notify_update('calendar', $cal_id.':'.$recur_date, $event, 'delete');
1988			}
1989		}
1990		if ($event['reference'])
1991		{
1992			// evtl. delete recur_exception $event['recurrence'] from event with cal_id=$event['reference']
1993		}
1994		return true;
1995	}
1996
1997	/**
1998	 * helper for send_update and get_update_message
1999	 * @internal
2000	 * @param array $event
2001	 * @param string $action
2002	 * @param array $event_arr
2003	 * @param array $disinvited
2004	 * @return array
2005	 */
2006	function _get_event_details($event,$action,&$event_arr,$disinvited=array())
2007	{
2008		$details = array(			// event-details for the notify-msg
2009			'id'          => $event['id'],
2010			'action'      => lang($action),
2011		);
2012		$event_arr = $this->event2array($event);
2013		foreach($event_arr as $key => $val)
2014		{
2015			if ($key == 'recur_type') $key = 'repetition';
2016			$details[$key] = $val['data'];
2017		}
2018		$details['participants'] = $details['participants'] ? implode("\n",$details['participants']) : '';
2019
2020		$event_arr['link']['field'] = lang('URL');
2021		$eventStart_arr = $this->date2array($event['start']); // give this as 'date' to the link to pick the right recurrence for the participants state
2022		$link = $GLOBALS['egw_info']['server']['webserver_url'].'/index.php?menuaction=calendar.calendar_uiforms.edit&cal_id='.$event['id'].'&date='.$eventStart_arr['full'].'&no_popup=1&ajax=true';
2023		// if url is only a path, try guessing the rest ;-)
2024		if ($link[0] == '/') $link = Api\Framework::getUrl($link);
2025		$event_arr['link']['data'] = $details['link'] = $link;
2026
2027		/* this is needed for notification-app
2028		 * notification-app creates the link individual for
2029		 * every user, so we must provide a neutral link-style
2030		 * if calendar implements tracking in near future, this part can be deleted
2031		 */
2032		$link_arr = array();
2033		$link_arr['text'] = $event['title'];
2034		$link_arr['view'] = array(	'menuaction' => 'calendar.calendar_uiforms.edit',
2035									'cal_id' => $event['id'],
2036									'date' => $eventStart_arr['full'],
2037									'ajax' => true
2038									);
2039		$link_arr['popup'] = '750x400';
2040		$details['link_arr'] = $link_arr;
2041
2042		$dis = array();
2043		foreach($disinvited as $uid)
2044		{
2045			$dis[] = $this->participant_name($uid);
2046		}
2047		$details['disinvited'] = implode(', ',$dis);
2048		return $details;
2049	}
2050
2051	/**
2052	 * create array with name, translated name and readable content of each attributes of an event
2053	 *
2054	 * old function, so far only used by send_update (therefor it's in bocalupdate and not bocal)
2055	 *
2056	 * @param array $event event to use
2057	 * @returns array of attributes with fieldname as key and array with the 'field'=translated name 'data' = readable content (for participants this is an array !)
2058	 */
2059	function event2array($event)
2060	{
2061		$var['title'] = Array(
2062			'field'		=> lang('Title'),
2063			'data'		=> $event['title']
2064		);
2065
2066		$var['description'] = Array(
2067			'field'	=> lang('Description'),
2068			'data'	=> $event['description']
2069		);
2070
2071		foreach(explode(',',$event['category']) as $cat_id)
2072		{
2073			$cat_string[] = stripslashes(Api\Categories::id2name($cat_id));
2074		}
2075		$var['category'] = Array(
2076			'field'	=> lang('Category'),
2077			'data'	=> implode(', ',$cat_string)
2078		);
2079
2080		$var['location'] = Array(
2081			'field'	=> lang('Location'),
2082			'data'	=> $event['location']
2083		);
2084
2085		$var['startdate'] = Array(
2086			'field'	=> lang('Start Date/Time'),
2087			'data'	=> $this->format_date($event['start']),
2088		);
2089
2090		$var['enddate'] = Array(
2091			'field'	=> lang('End Date/Time'),
2092			'data'	=> $this->format_date($event['end']),
2093		);
2094
2095		$pri = Array(
2096			0   => lang('None'),
2097			1	=> lang('Low'),
2098			2	=> lang('Normal'),
2099			3	=> lang('High')
2100		);
2101		$var['priority'] = Array(
2102			'field'	=> lang('Priority'),
2103			'data'	=> $pri[$event['priority']]
2104		);
2105
2106		$var['owner'] = Array(
2107			'field'	=> lang('Owner'),
2108			'data'	=> Api\Accounts::username($event['owner'])
2109		);
2110
2111		$var['updated'] = Array(
2112			'field'	=> lang('Updated'),
2113			'data'	=> $this->format_date($event['modtime']).', '.Api\Accounts::username($event['modifier'])
2114		);
2115
2116		$var['access'] = Array(
2117			'field'	=> lang('Access'),
2118			'data'	=> $event['public'] ? lang('Public') : lang('Private')
2119		);
2120
2121		if (isset($event['participants']) && is_array($event['participants']) && !empty($event['participants']))
2122		{
2123			$participants = $this->participants($event,true);
2124
2125			// fix external organiser to not be included as participant and shown as organiser
2126			foreach($event['participants'] as $uid => $status)
2127			{
2128				$role = $quantity = null;
2129				calendar_so::split_status($status, $quantity, $role);
2130				if ($role == 'CHAIR' && $status == 'D' && !is_numeric($uid))
2131				{
2132					$var['owner']['data'] = $this->participant_name($uid);
2133					unset($participants[$uid]);
2134					break;
2135				}
2136			}
2137		}
2138
2139		$var['participants'] = Array(
2140			'field'	=> lang('Participants'),
2141			'data'	=> $participants
2142		);
2143
2144		// Repeated Events
2145		$var['recur_type'] = Array(
2146			'field'	=> lang('Repetition'),
2147			'data'	=> ($event['recur_type'] != MCAL_RECUR_NONE) ? $this->recure2string($event) : '',
2148		);
2149		return $var;
2150	}
2151
2152	/**
2153	 * log all updates to a file
2154	 *
2155	 * @param array $event2save event-data before calling save
2156	 * @param array $event_saved event-data read back from the DB
2157	 * @param array $old_event =null event-data in the DB before calling save
2158	 * @param string $type ='update'
2159	 */
2160	function log2file($event2save,$event_saved,$old_event=null,$type='update')
2161	{
2162		if (!($f = fopen($this->log_file,'a')))
2163		{
2164			echo "<p>error opening '$this->log_file' !!!</p>\n";
2165			return false;
2166		}
2167		fwrite($f,$type.': '.Api\Accounts::username($this->user).': '.date('r')."\n");
2168		fwrite($f,"Time: time to save / saved time read back / old time before save\n");
2169		foreach(array('start','end') as $name)
2170		{
2171			fwrite($f,$name.': '.(isset($event2save[$name]) ? $this->format_date($event2save[$name]) : 'not set').' / '.
2172				$this->format_date($event_saved[$name]) .' / '.
2173				(is_null($old_event) ? 'no old event' : $this->format_date($old_event[$name]))."\n");
2174		}
2175		foreach(array('event2save','event_saved','old_event') as $name)
2176		{
2177			fwrite($f,$name.' = '.print_r($$name,true));
2178		}
2179		fwrite($f,"\n");
2180		fclose($f);
2181
2182		return true;
2183	}
2184
2185	/**
2186	 * Check alarms and move them if needed
2187	 *
2188	 * Used when the start time has changed, and alarms need to be updated
2189	 *
2190	 * @param array $event
2191	 * @param array $old_event
2192	 * @param Api\DateTime|int|null $instance_date For recurring events, this is the date we
2193	 *	are dealing with
2194	 */
2195	function check_move_alarms(Array &$event, Array $old_event = null, $instance_date = null)
2196	{
2197		if ($old_event !== null && $event['start'] == $old_event['start']) return;
2198
2199		$time = new Api\DateTime($event['start']);
2200		if(!is_array($event['alarm']))
2201		{
2202			$event['alarm'] = $this->so->read_alarms($event['id']);
2203		}
2204
2205		if (is_object($instance_date))
2206		{
2207			if (!is_a($instance_date, 'EGroupware\\Api\\DateTime'))
2208			{
2209				throw new Api\Exception\WrongParameter('$instance_date must be integer or Api\DateTime!');
2210			}
2211			$instance_date = $instance_date->format('ts');
2212		}
2213
2214		foreach($event['alarm'] as &$alarm)
2215		{
2216			if($event['recur_type'] != MCAL_RECUR_NONE && $instance_date)
2217			{
2218				calendar_so::shift_alarm($event, $alarm, $instance_date);
2219			}
2220			else if ($alarm['time'] !== $time->format('ts') - $alarm['offset'])
2221			{
2222				$alarm['time'] = $time->format('ts') - $alarm['offset'];
2223				$this->save_alarm($event['id'], $alarm);
2224			}
2225		}
2226	}
2227
2228	/**
2229	 * saves a new or updated alarm
2230	 *
2231	 * @param int $cal_id Id of the calendar-entry
2232	 * @param array $alarm array with fields: text, owner, enabled, ..
2233	 * @param boolean $update_modified =true call update modified, default true
2234	 * @return string id of the alarm, or false on error (eg. no perms)
2235	 */
2236	function save_alarm($cal_id, $alarm, $update_modified=true)
2237	{
2238		if (!$cal_id || !$this->check_perms(Acl::EDIT,$alarm['all'] ? $cal_id : 0,!$alarm['all'] ? $alarm['owner'] : 0))
2239		{
2240			//echo "<p>no rights to save the alarm=".print_r($alarm,true)." to event($cal_id)</p>";
2241			return false;	// no rights to add the alarm
2242		}
2243		$alarm['time'] = $this->date2ts($alarm['time'],true);	// user to server-time
2244
2245		return $this->so->save_alarm($cal_id, $alarm, $update_modified);
2246	}
2247
2248	/**
2249	 * delete one alarms identified by its id
2250	 *
2251	 * @param string $id alarm-id is a string of 'cal:'.$cal_id.':'.$alarm_nr, it is used as the job-id too
2252	 * @return int number of alarms deleted, false on error (eg. no perms)
2253	 */
2254	function delete_alarm($id)
2255	{
2256		list(,$cal_id) = explode(':',$id);
2257
2258		if (!($alarm = $this->so->read_alarm($id)) || !$cal_id || !$this->check_perms(Acl::EDIT,$alarm['all'] ? $cal_id : 0,!$alarm['all'] ? $alarm['owner'] : 0))
2259		{
2260			return false;	// no rights to delete the alarm
2261		}
2262
2263		return $this->so->delete_alarm($id);
2264	}
2265
2266	/**
2267	 * Find existing categories in database by name or add categories that do not exist yet
2268	 * currently used for ical/sif import
2269	 *
2270	 * @param array $catname_list names of the categories which should be found or added
2271	 * @param int|array $old_event =null match against existing event and expand the returned category ids
2272	 *  by the ones the user normally does not see due to category permissions - used to preserve categories
2273	 * @return array category ids (found, added and preserved categories)
2274	 */
2275	function find_or_add_categories($catname_list, $old_event=null)
2276	{
2277		if (is_array($old_event) || $old_event > 0)
2278		{
2279			// preserve categories without users read access
2280			if (!is_array($old_event)) $old_event = $this->read($old_event);
2281			$old_categories = explode(',',$old_event['category']);
2282			$old_cats_preserve = array();
2283			if (is_array($old_categories) && count($old_categories) > 0)
2284			{
2285				foreach ($old_categories as $cat_id)
2286				{
2287					if (!$this->categories->check_perms(Acl::READ, $cat_id))
2288					{
2289						$old_cats_preserve[] = $cat_id;
2290					}
2291				}
2292			}
2293		}
2294
2295		$cat_id_list = array();
2296		foreach ((array)$catname_list as $cat_name)
2297		{
2298			$cat_name = trim($cat_name);
2299			$cat_id = $this->categories->name2id($cat_name, 'X-');
2300
2301			if (!$cat_id)
2302			{
2303				// some SyncML clients (mostly phones) add an X- to the category names
2304				if (strncmp($cat_name, 'X-', 2) == 0)
2305				{
2306					$cat_name = substr($cat_name, 2);
2307				}
2308				$cat_id = $this->categories->add(array('name' => $cat_name, 'descr' => $cat_name, 'access' => 'private'));
2309			}
2310
2311			if ($cat_id)
2312			{
2313				$cat_id_list[] = $cat_id;
2314			}
2315		}
2316
2317		if (is_array($old_cats_preserve) && count($old_cats_preserve) > 0)
2318		{
2319			$cat_id_list = array_merge($cat_id_list, $old_cats_preserve);
2320		}
2321
2322		if (count($cat_id_list) > 1)
2323		{
2324			$cat_id_list = array_unique($cat_id_list);
2325			sort($cat_id_list, SORT_NUMERIC);
2326		}
2327
2328		return $cat_id_list;
2329	}
2330
2331	function get_categories($cat_id_list)
2332	{
2333		if (!is_array($cat_id_list))
2334		{
2335			$cat_id_list = explode(',',$cat_id_list);
2336		}
2337		$cat_list = array();
2338		foreach ($cat_id_list as $cat_id)
2339		{
2340			if ($cat_id && $this->categories->check_perms(Acl::READ, $cat_id) &&
2341					($cat_name = $this->categories->id2name($cat_id)) && $cat_name != '--')
2342			{
2343				$cat_list[] = $cat_name;
2344			}
2345		}
2346
2347		return $cat_list;
2348	}
2349
2350	/**
2351	 * Try to find a matching db entry
2352	 *
2353	 * @param array $event	the vCalendar data we try to find
2354	 * @param string filter='exact' exact	-> find the matching entry
2355	 * 								check	-> check (consitency) for identical matches
2356	 * 							    relax	-> be more tolerant
2357	 *                              master	-> try to find a releated series master
2358	 * @return array calendar_ids of matching entries
2359	 */
2360	function find_event($event, $filter='exact')
2361	{
2362		$matchingEvents = array();
2363		$query = array();
2364
2365		if ($this->log)
2366		{
2367			error_log(__FILE__.'['.__LINE__.'] '.__METHOD__.
2368				"($filter)[EVENT]:" . array2string($event)."\n",3,$this->logfile);
2369		}
2370
2371		if (!isset($event['recurrence'])) $event['recurrence'] = 0;
2372
2373		if ($filter == 'master')
2374		{
2375			$query[] = 'recur_type!='. MCAL_RECUR_NONE;
2376			$query['cal_recurrence'] = 0;
2377		}
2378		elseif ($filter == 'exact')
2379		{
2380			if ($event['recur_type'] != MCAL_RECUR_NONE)
2381			{
2382				$query[] = 'recur_type='.$event['recur_type'];
2383			}
2384			else
2385			{
2386				$query[] = 'recur_type IS NULL';
2387			}
2388			$query['cal_recurrence'] = $event['recurrence'];
2389		}
2390
2391		if ($event['id'])
2392		{
2393			if ($this->log)
2394			{
2395				error_log(__FILE__.'['.__LINE__.'] '.__METHOD__.
2396					'(' . $event['id'] . ")[EventID]\n",3,$this->logfile);
2397			}
2398			if (($egwEvent = $this->read($event['id'], 0, false, 'server')))
2399			{
2400				if ($this->log)
2401				{
2402					error_log(__FILE__.'['.__LINE__.'] '.__METHOD__.
2403						'()[FOUND]:' . array2string($egwEvent)."\n",3,$this->logfile);
2404				}
2405				if ($egwEvent['recur_type'] != MCAL_RECUR_NONE &&
2406					(empty($event['uid']) || $event['uid'] == $egwEvent['uid']))
2407				{
2408					if ($filter == 'master')
2409					{
2410						$matchingEvents[] = $egwEvent['id']; // we found the master
2411					}
2412					if ($event['recur_type'] == $egwEvent['recur_type'])
2413					{
2414						$matchingEvents[] = $egwEvent['id']; // we found the event
2415					}
2416					elseif ($event['recur_type'] == MCAL_RECUR_NONE &&
2417								$event['recurrence'] != 0)
2418					{
2419						$exceptions = $this->so->get_recurrence_exceptions($egwEvent, $event['tzid']);
2420						if (in_array($event['recurrence'], $exceptions))
2421						{
2422							$matchingEvents[] = $egwEvent['id'] . ':' . (int)$event['recurrence'];
2423						}
2424					}
2425				} elseif ($filter != 'master' && ($filter == 'exact' ||
2426							$event['recur_type'] == $egwEvent['recur_type'] &&
2427							strpos($egwEvent['title'], $event['title']) === 0))
2428				{
2429					$matchingEvents[] = $egwEvent['id']; // we found the event
2430				}
2431			}
2432			if (!empty($matchingEvents) || $filter == 'exact') return $matchingEvents;
2433		}
2434		unset($event['id']);
2435
2436		// No chance to find a master without [U]ID
2437		if ($filter == 'master' && empty($event['uid'])) return $matchingEvents;
2438
2439		// only query calendars of users, we have READ-grants from
2440		$users = array();
2441		foreach(array_keys($this->grants) as $user)
2442		{
2443			$user = trim($user);
2444			if ($this->check_perms(Acl::READ|self::ACL_READ_FOR_PARTICIPANTS|self::ACL_FREEBUSY,0,$user))
2445			{
2446				if ($user && !in_array($user,$users))	// already added?
2447				{
2448					$users[] = $user;
2449				}
2450			}
2451			elseif ($GLOBALS['egw']->accounts->get_type($user) != 'g')
2452			{
2453				continue;	// for non-groups (eg. users), we stop here if we have no read-rights
2454			}
2455			// the further code is only for real users
2456			if (!is_numeric($user)) continue;
2457
2458			// for groups we have to include the members
2459			if ($GLOBALS['egw']->accounts->get_type($user) == 'g')
2460			{
2461				$members = $GLOBALS['egw']->accounts->members($user, true);
2462				if (is_array($members))
2463				{
2464					foreach($members as $member)
2465					{
2466						// use only members which gave the user a read-grant
2467						if (!in_array($member, $users) &&
2468								$this->check_perms(Acl::READ|self::ACL_FREEBUSY, 0, $member))
2469						{
2470							$users[] = $member;
2471						}
2472					}
2473				}
2474			}
2475			else	// for users we have to include all the memberships, to get the group-events
2476			{
2477				$memberships = $GLOBALS['egw']->accounts->memberships($user, true);
2478				if (is_array($memberships))
2479				{
2480					foreach($memberships as $group)
2481					{
2482						if (!in_array($group, $users))
2483						{
2484							$users[] = $group;
2485						}
2486					}
2487				}
2488			}
2489		}
2490
2491		if ($filter != 'master' && ($filter != 'exact' || empty($event['uid'])))
2492		{
2493			if (!empty($event['whole_day']))
2494			{
2495				if ($filter == 'relax')
2496				{
2497					$delta = 1800;
2498				}
2499				else
2500				{
2501					$delta = 60;
2502				}
2503
2504				// check length with some tolerance
2505				$length = $event['end'] - $event['start'] - $delta;
2506				$query[] = ('(cal_end-cal_start)>' . $length);
2507				$length += 2 * $delta;
2508				$query[] = ('(cal_end-cal_start)<' . $length);
2509				$query[] = ('cal_start>' . ($event['start'] - 86400));
2510				$query[] = ('cal_start<' . ($event['start'] + 86400));
2511			}
2512			elseif (isset($event['start']))
2513			{
2514				if ($filter == 'relax')
2515				{
2516					$query[] = ('cal_start>' . ($event['start'] - 3600));
2517					$query[] = ('cal_start<' . ($event['start'] + 3600));
2518				}
2519				else
2520				{
2521					// we accept a tiny tolerance
2522					$query[] = ('cal_start>' . ($event['start'] - 2));
2523					$query[] = ('cal_start<' . ($event['start'] + 2));
2524				}
2525			}
2526			if ($filter == 'relax')
2527			{
2528				$matchFields = array();
2529			}
2530			else
2531			{
2532				$matchFields = array('priority', 'public');
2533			}
2534			foreach ($matchFields as $key)
2535			{
2536				if (isset($event[$key])) $query['cal_'.$key] = $event[$key];
2537			}
2538		}
2539
2540		if (!empty($event['uid']))
2541		{
2542			$query['cal_uid'] = $event['uid'];
2543			if ($this->log)
2544			{
2545				error_log(__FILE__.'['.__LINE__.'] '.__METHOD__.
2546					'(' . $event['uid'] . ")[EventUID]\n",3,$this->logfile);
2547			}
2548		}
2549
2550		if ($this->log)
2551		{
2552			error_log(__FILE__.'['.__LINE__.'] '.__METHOD__.
2553				'[QUERY]: ' . array2string($query)."\n",3,$this->logfile);
2554		}
2555		if (!count($users) || !($foundEvents =
2556			$this->so->search(null, null, $users, 0, 'owner', false, 0, array('query' => $query))))
2557		{
2558			if ($this->log)
2559			{
2560				error_log(__FILE__.'['.__LINE__.'] '.__METHOD__.
2561				"[NO MATCH]\n",3,$this->logfile);
2562			}
2563			return $matchingEvents;
2564		}
2565
2566		$pseudos = array();
2567
2568		foreach($foundEvents as $egwEvent)
2569		{
2570			if ($this->log)
2571			{
2572				error_log(__FILE__.'['.__LINE__.'] '.__METHOD__.
2573					'[FOUND]: ' . array2string($egwEvent)."\n",3,$this->logfile);
2574			}
2575
2576			if (in_array($egwEvent['id'], $matchingEvents)) continue;
2577
2578			// convert timezone id of event to tzid (iCal id like 'Europe/Berlin')
2579			if (!$egwEvent['tz_id'] || !($egwEvent['tzid'] = calendar_timezones::id2tz($egwEvent['tz_id'])))
2580			{
2581				$egwEvent['tzid'] = Api\DateTime::$server_timezone->getName();
2582			}
2583			if (!isset(self::$tz_cache[$egwEvent['tzid']]))
2584			{
2585				self::$tz_cache[$egwEvent['tzid']] = calendar_timezones::DateTimeZone($egwEvent['tzid']);
2586			}
2587			if (!$event['tzid'])
2588			{
2589				$event['tzid'] = Api\DateTime::$server_timezone->getName();
2590			}
2591			if (!isset(self::$tz_cache[$event['tzid']]))
2592			{
2593				self::$tz_cache[$event['tzid']] = calendar_timezones::DateTimeZone($event['tzid']);
2594			}
2595
2596			if (!empty($event['uid']))
2597			{
2598				if ($filter == 'master')
2599				{
2600					// We found the master
2601					$matchingEvents = array($egwEvent['id']);
2602					break;
2603				}
2604				if ($filter == 'exact')
2605				{
2606					// UID found
2607					if (empty($event['recurrence']))
2608					{
2609						$egwstart = new Api\DateTime($egwEvent['start'], Api\DateTime::$server_timezone);
2610						$egwstart->setTimezone(self::$tz_cache[$egwEvent['tzid']]);
2611						$dtstart = new Api\DateTime($event['start'], Api\DateTime::$server_timezone);
2612						$dtstart->setTimezone(self::$tz_cache[$event['tzid']]);
2613						if ($egwEvent['recur_type'] == MCAL_RECUR_NONE &&
2614							$event['recur_type'] == MCAL_RECUR_NONE ||
2615								$egwEvent['recur_type'] != MCAL_RECUR_NONE &&
2616									$event['recur_type'] != MCAL_RECUR_NONE)
2617						{
2618							if ($egwEvent['recur_type'] == MCAL_RECUR_NONE &&
2619								$egwstart->format('Ymd') == $dtstart->format('Ymd') ||
2620									$egwEvent['recur_type'] != MCAL_RECUR_NONE)
2621							{
2622								// We found an exact match
2623								$matchingEvents = array($egwEvent['id']);
2624								break;
2625							}
2626							else
2627							{
2628								$matchingEvents[] = $egwEvent['id'];
2629							}
2630						}
2631						continue;
2632					}
2633					elseif ($egwEvent['recurrence'] == $event['recurrence'])
2634					{
2635						// We found an exact match
2636						$matchingEvents = array($egwEvent['id']);
2637						break;
2638					}
2639					if ($egwEvent['recur_type'] != MCAL_RECUR_NONE &&
2640						$event['recur_type'] == MCAL_RECUR_NONE &&
2641							!$egwEvent['recurrence'] && $event['recurrence'])
2642					{
2643						$exceptions = $this->so->get_recurrence_exceptions($egwEvent, $event['tzid']);
2644						if (in_array($event['recurrence'], $exceptions))
2645						{
2646							// We found a pseudo exception
2647							$matchingEvents = array($egwEvent['id'] . ':' . (int)$event['recurrence']);
2648							break;
2649						}
2650					}
2651					continue;
2652				}
2653			}
2654
2655			// check times
2656			if ($filter != 'relax')
2657			{
2658				if (empty($event['whole_day']))
2659				{
2660					if (abs($event['end'] - $egwEvent['end']) >= 120)
2661					{
2662						if ($this->log)
2663						{
2664							error_log(__FILE__.'['.__LINE__.'] '.__METHOD__.
2665							"() egwEvent length does not match!\n",3,$this->logfile);
2666						}
2667						continue;
2668					}
2669				}
2670				else
2671				{
2672					if (!$this->so->isWholeDay($egwEvent))
2673					{
2674						if ($this->log)
2675						{
2676							error_log(__FILE__.'['.__LINE__.'] '.__METHOD__.
2677							"() egwEvent is not a whole-day event!\n",3,$this->logfile);
2678						}
2679						continue;
2680					}
2681				}
2682			}
2683
2684			// check for real match
2685			$matchFields = array('title', 'description');
2686			if ($filter != 'relax')
2687			{
2688				$matchFields[] = 'location';
2689			}
2690			foreach ($matchFields as $key)
2691			{
2692				if (!empty($event[$key]) && (empty($egwEvent[$key])
2693						|| strpos(str_replace("\r\n", "\n", $egwEvent[$key]), $event[$key]) !== 0))
2694				{
2695					if ($this->log)
2696					{
2697						error_log(__FILE__.'['.__LINE__.'] '.__METHOD__.
2698							"() event[$key] differ: '" . $event[$key] .
2699							"' <> '" . $egwEvent[$key] . "'\n",3,$this->logfile);
2700					}
2701					continue 2; // next foundEvent
2702				}
2703			}
2704
2705			if (is_array($event['category']))
2706			{
2707				// check categories
2708				$egwCategories = explode(',', $egwEvent['category']);
2709				foreach ($egwCategories as $cat_id)
2710				{
2711					if ($this->categories->check_perms(Acl::READ, $cat_id) &&
2712							!in_array($cat_id, $event['category']))
2713					{
2714						if ($this->log)
2715						{
2716							error_log(__FILE__.'['.__LINE__.'] '.__METHOD__.
2717							"() egwEvent category $cat_id is missing!\n",3,$this->logfile);
2718						}
2719						continue 2;
2720					}
2721				}
2722				$newCategories = array_diff($event['category'], $egwCategories);
2723				if (!empty($newCategories))
2724				{
2725					if ($this->log)
2726					{
2727						error_log(__FILE__.'['.__LINE__.'] '.__METHOD__.
2728							'() event has additional categories:'
2729							. array2string($newCategories)."\n",3,$this->logfile);
2730					}
2731					continue;
2732				}
2733			}
2734
2735			if ($filter != 'relax')
2736			{
2737				// check participants
2738				if (is_array($event['participants']))
2739				{
2740					foreach ($event['participants'] as $attendee => $status)
2741					{
2742						if (!isset($egwEvent['participants'][$attendee]) &&
2743								$attendee != $egwEvent['owner']) // ||
2744							//(!$relax && $egw_event['participants'][$attendee] != $status))
2745						{
2746							if ($this->log)
2747							{
2748								error_log(__FILE__.'['.__LINE__.'] '.__METHOD__.
2749								"() additional event['participants']: $attendee\n",3,$this->logfile);
2750							}
2751							continue 2;
2752						}
2753						else
2754						{
2755							unset($egwEvent['participants'][$attendee]);
2756						}
2757					}
2758					// ORGANIZER and Groups may be missing
2759					unset($egwEvent['participants'][$egwEvent['owner']]);
2760					foreach ($egwEvent['participants'] as $attendee => $status)
2761					{
2762						if (is_numeric($attendee) && $attendee < 0)
2763						{
2764							unset($egwEvent['participants'][$attendee]);
2765						}
2766					}
2767					if (!empty($egwEvent['participants']))
2768					{
2769						if ($this->log)
2770						{
2771							error_log(__FILE__.'['.__LINE__.'] '.__METHOD__.
2772								'() missing event[participants]: ' .
2773								array2string($egwEvent['participants'])."\n",3,$this->logfile);
2774						}
2775						continue;
2776					}
2777				}
2778			}
2779
2780			if ($event['recur_type'] == MCAL_RECUR_NONE)
2781			{
2782				if ($egwEvent['recur_type'] != MCAL_RECUR_NONE)
2783				{
2784					// We found a pseudo Exception
2785					$pseudos[] = $egwEvent['id'] . ':' . $event['start'];
2786					continue;
2787				}
2788			}
2789			elseif ($filter != 'relax')
2790			{
2791				// check exceptions
2792				// $exceptions[$remote_ts] = $egw_ts
2793				$exceptions = $this->so->get_recurrence_exceptions($egwEvent, $event['$tzid'], 0, 0, 'map');
2794				if (is_array($event['recur_exception']))
2795				{
2796					foreach ($event['recur_exception'] as $key => $day)
2797					{
2798						if (isset($exceptions[$day]))
2799						{
2800							unset($exceptions[$day]);
2801						}
2802						else
2803						{
2804							if ($this->log)
2805							{
2806								error_log(__FILE__.'['.__LINE__.'] '.__METHOD__.
2807								"() additional event['recur_exception']: $day\n",3,$this->logfile);
2808							}
2809							continue 2;
2810						}
2811					}
2812					if (!empty($exceptions))
2813					{
2814						if ($this->log)
2815						{
2816							error_log(__FILE__.'['.__LINE__.'] '.__METHOD__.
2817								'() missing event[recur_exception]: ' .
2818								array2string($event['recur_exception'])."\n",3,$this->logfile);
2819						}
2820						continue;
2821					}
2822				}
2823
2824				// check recurrence information
2825				foreach (array('recur_type', 'recur_interval', 'recur_enddate') as $key)
2826				{
2827					if (isset($event[$key])
2828							&& $event[$key] != $egwEvent[$key])
2829					{
2830						if ($this->log)
2831						{
2832							error_log(__FILE__.'['.__LINE__.'] '.__METHOD__.
2833								"() events[$key] differ: " . $event[$key] .
2834								' <> ' . $egwEvent[$key]."\n",3,$this->logfile);
2835						}
2836						continue 2;
2837					}
2838				}
2839			}
2840			$matchingEvents[] = $egwEvent['id']; // exact match
2841		}
2842
2843		if ($filter == 'exact' && !empty($event['uid']) && count($matchingEvents) > 1
2844			|| $filter != 'master' && !empty($egwEvent['recur_type']) && empty($event['recur_type']))
2845		{
2846			// Unknown exception for existing series
2847			if ($this->log)
2848			{
2849				error_log(__FILE__.'['.__LINE__.'] '.__METHOD__.
2850					"() new exception for series found.\n",3,$this->logfile);
2851			}
2852			$matchingEvents = array();
2853		}
2854
2855		// append pseudos as last entries
2856		$matches = array_merge($matchingEvents, $pseudos);
2857
2858		if ($this->log)
2859		{
2860			error_log(__FILE__.'['.__LINE__.'] '.__METHOD__.
2861				'[MATCHES]:' . array2string($matches)."\n",3,$this->logfile);
2862		}
2863		return $matches;
2864	}
2865
2866	/**
2867	 * classifies an incoming event from the eGW point-of-view
2868	 *
2869     * exceptions: unlike other calendar apps eGW does not create an event exception
2870     * if just the participant state changes - therefore we have to distinguish between
2871     * real exceptions and status only exceptions
2872     *
2873     * @param array $event the event to check
2874     *
2875     * @return array
2876     * 	type =>
2877     * 		SINGLE a single event
2878     * 		SERIES-MASTER the series master
2879     * 		SERIES-EXCEPTION event is a real exception
2880	  * 		SERIES-PSEUDO-EXCEPTION event is a status only exception
2881	  * 		SERIES-EXCEPTION-PROPAGATE event was a status only exception in the past and is now a real exception
2882	  * 	stored_event => if event already exists in the database array with event data or false
2883	  * 	master_event => for event type SERIES-EXCEPTION, SERIES-PSEUDO-EXCEPTION or SERIES-EXCEPTION-PROPAGATE
2884	  * 		the corresponding series master event array
2885	  * 		NOTE: this param is false if event is of type SERIES-MASTER
2886     */
2887	function get_event_info($event)
2888	{
2889		$type = 'SINGLE'; // default
2890		$master_event = false; //default
2891		$stored_event = false;
2892		$recurrence_event = false;
2893		$wasPseudo = false;
2894
2895		if (($foundEvents = $this->find_event($event, 'exact')))
2896		{
2897			// We found the exact match
2898			$eventID = array_shift($foundEvents);
2899			if (strstr($eventID, ':'))
2900			{
2901				$type = 'SERIES-PSEUDO-EXCEPTION';
2902				$wasPseudo = true;
2903				list($eventID, $date) = explode(':', $eventID);
2904				$recur_date = $this->date2usertime($date);
2905				$stored_event = $this->read($eventID, $recur_date, false, 'server');
2906				$master_event = $this->read($eventID, 0, false, 'server');
2907				$recurrence_event = $stored_event;
2908			}
2909			else
2910			{
2911				$stored_event = $this->read($eventID, 0, false, 'server');
2912			}
2913			if (!empty($stored_event['uid']) && empty($event['uid']))
2914			{
2915				$event['uid'] = $stored_event['uid']; // restore the UID if it was not delivered
2916			}
2917		}
2918
2919		if ($event['recur_type'] != MCAL_RECUR_NONE)
2920		{
2921			$type = 'SERIES-MASTER';
2922		}
2923
2924		if ($type == 'SINGLE' &&
2925			($foundEvents = $this->find_event($event, 'master')))
2926		{
2927			// SINGLE, SERIES-EXCEPTION OR SERIES-EXCEPTON-STATUS
2928			foreach ($foundEvents  as $eventID)
2929			{
2930				// Let's try to find a related series
2931				if ($this->log)
2932				{
2933					error_log(__FILE__.'['.__LINE__.'] '.__METHOD__.
2934					"()[MASTER]: $eventID\n",3,$this->logfile);
2935				}
2936				$type = 'SERIES-EXCEPTION';
2937				if (($master_event = $this->read($eventID, 0, false, 'server')))
2938				{
2939					if (isset($stored_event['id']) &&
2940						$master_event['id'] != $stored_event['id'])
2941					{
2942						break; // this is an existing exception
2943					}
2944					elseif (isset($event['recurrence']) &&
2945						in_array($event['recurrence'], $master_event['recur_exception']))
2946					{
2947						$type = 'SERIES-PSEUDO-EXCEPTION'; // could also be a real one
2948						$recurrence_event = $master_event;
2949						$recurrence_event['start'] = $event['recurrence'];
2950						$recurrence_event['end'] -= $master_event['start'] - $event['recurrence'];
2951						break;
2952					}
2953					elseif (in_array($event['start'], $master_event['recur_exception']))
2954					{
2955						$type='SERIES-PSEUDO-EXCEPTION'; // new pseudo exception?
2956						$recurrence_event = $master_event;
2957						$recurrence_event['start'] = $event['start'];
2958						$recurrence_event['end'] -= $master_event['start'] - $event['start'];
2959						break;
2960					}
2961					else
2962					{
2963						// try to find a suitable pseudo exception date
2964						$egw_rrule = calendar_rrule::event2rrule($master_event, false);
2965						$egw_rrule->current = clone $egw_rrule->time;
2966						while ($egw_rrule->valid())
2967						{
2968							$occurrence = Api\DateTime::to($egw_rrule->current(), 'server');
2969							if ($this->log)
2970							{
2971								error_log(__FILE__.'['.__LINE__.'] '.__METHOD__.
2972									'() try occurrence ' . $egw_rrule->current()
2973									. " ($occurrence)\n",3,$this->logfile);
2974							}
2975							if ($event['start'] == $occurrence)
2976							{
2977								$type = 'SERIES-PSEUDO-EXCEPTION'; // let's try a pseudo exception
2978								$recurrence_event = $master_event;
2979								$recurrence_event['start'] = $occurrence;
2980								$recurrence_event['end'] -= $master_event['start'] - $occurrence;
2981								break 2;
2982							}
2983							if (isset($event['recurrence']) && $event['recurrence'] == $occurrence)
2984							{
2985								$type = 'SERIES-EXCEPTION-PROPAGATE';
2986								if ($stored_event)
2987								{
2988									unset($stored_event['id']); // signal the true exception
2989									$stored_event['recur_type'] = MCAL_RECUR_NONE;
2990								}
2991								break 2;
2992							}
2993							$egw_rrule->next_no_exception();
2994						}
2995					}
2996				}
2997			}
2998		}
2999
3000		// check pseudo exception propagation
3001		if ($recurrence_event)
3002		{
3003			// default if we cannot find a proof for a fundamental change
3004			// the recurrence_event is the master event with start and end adjusted to the recurrence
3005			// check for changed data
3006			foreach (array('start','end','uid','title','location','description',
3007				'priority','public','special','non_blocking') as $key)
3008			{
3009				if (!empty($event[$key]) && $recurrence_event[$key] != $event[$key])
3010				{
3011					if ($wasPseudo)
3012					{
3013						// We started with a pseudo exception
3014						$type = 'SERIES-EXCEPTION-PROPAGATE';
3015					}
3016					else
3017					{
3018						$type = 'SERIES-EXCEPTION';
3019					}
3020
3021					if ($stored_event)
3022					{
3023						unset($stored_event['id']); // signal the true exception
3024						$stored_event['recur_type'] = MCAL_RECUR_NONE;
3025					}
3026					break;
3027				}
3028			}
3029			// the event id here is always the id of the master event
3030			// unset it to prevent confusion of stored event and master event
3031			unset($event['id']);
3032		}
3033
3034		// check ACL
3035		if (is_array($master_event))
3036		{
3037			$acl_edit = $this->check_perms(Acl::EDIT, $master_event['id']);
3038		}
3039		else
3040		{
3041			if (is_array($stored_event))
3042			{
3043				$acl_edit = $this->check_perms(Acl::EDIT, $stored_event['id']);
3044			}
3045			else
3046			{
3047				$acl_edit = true; // new event
3048			}
3049		}
3050
3051		return array(
3052			'type' => $type,
3053			'acl_edit' => $acl_edit,
3054			'stored_event' => $stored_event,
3055			'master_event' => $master_event,
3056		);
3057    }
3058
3059    /**
3060     * Translates all timestamps for a given event from server-time to user-time.
3061     * The update() and save() methods expect timestamps in user-time.
3062     * @param &$event	the event we are working on
3063     *
3064     */
3065    function server2usertime (&$event)
3066    {
3067		// we run all dates through date2usertime, to adjust to user-time
3068		foreach(array('start','end','recur_enddate','recurrence') as $ts)
3069		{
3070			// we convert here from server-time to timestamps in user-time!
3071			if (isset($event[$ts])) $event[$ts] = $event[$ts] ? $this->date2usertime($event[$ts]) : 0;
3072		}
3073		// same with the recur exceptions
3074		if (isset($event['recur_exception']) && is_array($event['recur_exception']))
3075		{
3076			foreach($event['recur_exception'] as $n => $date)
3077			{
3078				$event['recur_exception'][$n] = $this->date2usertime($date);
3079			}
3080		}
3081		// same with the alarms
3082		if (isset($event['alarm']) && is_array($event['alarm']))
3083		{
3084			foreach($event['alarm'] as $id => $alarm)
3085			{
3086				$event['alarm'][$id]['time'] = $this->date2usertime($alarm['time']);
3087			}
3088		}
3089    }
3090	/**
3091	 * Delete events that are more than $age years old
3092	 *
3093	 * Purges old events from the database
3094	 *
3095	 * @param int|float $age How many years old the event must be before it is deleted
3096	 */
3097	function purge($age)
3098	{
3099		if (is_numeric($age) && $age > 0)	// just make sure bogus values dont delete everything
3100		{
3101			$this->so->purge(time() - 365*24*3600*(float)$age);
3102		}
3103	}
3104
3105	/**
3106	 * Check to see if we need to reset the status of any of the participants
3107	 * - Current user is never reset
3108	 * - Other users we respect their preference
3109	 * - Non-users status is always reset
3110	 *
3111	 * @param Array $event New event
3112	 * @param Array $old_event Event before modification
3113	 *
3114	 * @return boolean true if any statuses were reset
3115	 */
3116	protected function check_reset_statuses(&$event, $old_event)
3117	{
3118		// Event passed is still in user time at this point, convert to servertime for
3119		// comparison, but don't modify it in event
3120		if(!$old_event || !is_array($old_event) || $this->date2ts($event['start'],true) == $old_event['start'])
3121		{
3122			return false;
3123		}
3124
3125		$status_reset = false;
3126		$sameday = (date('Ymd', $old_event['start']) == date('Ymd', $event['start']));
3127		foreach((array)$event['participants'] as $uid => $status)
3128		{
3129			$q = $r = null;
3130			calendar_so::split_status($status,$q,$r);
3131			if($uid == $this->user || $status == 'U')
3132			{
3133				continue;
3134			}
3135
3136			// Just user accounts
3137			if (is_int($uid))
3138			{
3139				$preferences = new Api\Preferences($uid);
3140				$part_prefs = $preferences->read_repository();
3141				switch ($part_prefs['calendar']['reset_stati'])
3142				{
3143					case 'no':
3144						break;
3145					case 'startday':
3146						if ($sameday) break;
3147					default:
3148						$status_reset = true;
3149						$event['participants'][$uid] = calendar_so::combine_status('U',$q,$r);
3150				}
3151			}
3152			// All other participant types
3153			else
3154			{
3155				$status_reset = true;
3156				$event['participants'][$uid] = calendar_so::combine_status('U',$q,$r);
3157			}
3158		}
3159		return $status_reset;
3160
3161	}
3162}
3163