1<?php
2/**
3 * EGroupware - Calendar's buisness-object - access only
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) 2004-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
18if (!defined('ACL_TYPE_IDENTIFER'))	// used to mark ACL-values for the debug_message methode
19{
20	define('ACL_TYPE_IDENTIFER','***ACL***');
21}
22
23define('HOUR_s',60*60);
24define('DAY_s',24*HOUR_s);
25define('WEEK_s',7*DAY_s);
26
27/**
28 * Required (!) include, as we use the MCAL_* constants, BEFORE instanciating (and therefore autoloading) the class
29 */
30require_once(EGW_INCLUDE_ROOT.'/calendar/inc/class.calendar_so.inc.php');
31
32/**
33 * Class to access all calendar data
34 *
35 * For updating calendar data look at the bocalupdate class, which extends this class.
36 *
37 * The new UI, BO and SO classes have a strikt definition, in which time-zone they operate:
38 *  UI only operates in user-time, so there have to be no conversation at all !!!
39 *  BO's functions take and return user-time only (!), they convert internaly everything to servertime, because
40 *  SO operates only in server-time
41 *
42 * As this BO class deals with dates/times of several types and timezone, each variable should have a postfix
43 * appended, telling with type it is: _s = seconds, _su = secs in user-time, _ss = secs in server-time, _h = hours
44 *
45 * All new BO code (should be true for eGW in general) NEVER use any $_REQUEST ($_POST or $_GET) vars itself.
46 * Nor does it store the state of any UI-elements (eg. cat-id selectbox). All this is the task of the UI class(es) !!!
47 *
48 * All permanent debug messages of the calendar-code should done via the debug-message method of this class !!!
49 */
50class calendar_bo
51{
52	/**
53	 * Gives read access to the calendar, but all events the user is not participating are private!
54	 * Used by addressbook.
55	 */
56	const ACL_READ_FOR_PARTICIPANTS = Acl::CUSTOM1;
57	/**
58	 * Right to see free/busy data only
59	 */
60	const ACL_FREEBUSY = Acl::CUSTOM2;
61	/**
62	 * Allows to invite an other user (if configured to be used!)
63	 */
64	const ACL_INVITE = Acl::CUSTOM3;
65
66	/**
67	 * @var int $debug name of method to debug or level of debug-messages:
68	 *	False=Off as higher as more messages you get ;-)
69	 *	1 = function-calls incl. parameters to general functions like search, read, write, delete
70	 *	2 = function-calls to exported helper-functions like check_perms
71	 *	4 = function-calls to exported conversation-functions like date2ts, date2array, ...
72	 *	5 = function-calls to private functions
73	 */
74	var $debug=false;
75
76	/**
77	 * @var int $now timestamp in server-time
78	 */
79	var $now;
80
81	/**
82	 * @var int $now_su timestamp of actual user-time
83	 */
84	var $now_su;
85
86	/**
87	 * @var array $cal_prefs calendar-specific prefs
88	 */
89	var $cal_prefs;
90
91	/**
92	 * @var array $common_prefs common preferences
93	 */
94	var $common_prefs;
95	/**
96	 * Custom fields read from the calendar config
97	 *
98	 * @var array
99	 */
100	var $customfields = array();
101	/**
102	 * @var int $user nummerical id of the current user-id
103	 */
104	var $user=0;
105
106	/**
107	 * @var array $grants grants of the current user, array with user-id / ored-ACL-rights pairs
108	 */
109	var $grants=array();
110
111	/**
112	 * @var array $verbose_status translated 1-char status values to a verbose name, run through lang() by the constructor
113	 */
114	var $verbose_status = array(
115		'A' => 'Accepted',
116		'R' => 'Rejected',
117		'T' => 'Tentative',
118		'U' => 'No Response',
119		'D' => 'Delegated',
120		'G' => 'Group invitation',
121	);
122	/**
123	 * @var array recur_types translates MCAL recur-types to verbose labels
124	 */
125	var $recur_types = Array(
126		MCAL_RECUR_NONE         => 'No recurrence',
127		MCAL_RECUR_DAILY        => 'Daily',
128		MCAL_RECUR_WEEKLY       => 'Weekly',
129		MCAL_RECUR_MONTHLY_WDAY => 'Monthly (by day)',
130		MCAL_RECUR_MONTHLY_MDAY => 'Monthly (by date)',
131		MCAL_RECUR_YEARLY       => 'Yearly'
132	);
133	/**
134	 * @var array recur_days translates MCAL recur-days to verbose labels
135	 */
136	var $recur_days = array(
137		MCAL_M_MONDAY    => 'Monday',
138		MCAL_M_TUESDAY   => 'Tuesday',
139		MCAL_M_WEDNESDAY => 'Wednesday',
140		MCAL_M_THURSDAY  => 'Thursday',
141		MCAL_M_FRIDAY    => 'Friday',
142		MCAL_M_SATURDAY  => 'Saturday',
143		MCAL_M_SUNDAY    => 'Sunday',
144	);
145	/**
146	 * Standard iCal attendee roles
147	 *
148	 * @var array
149	 */
150	var $roles = array(
151		'REQ-PARTICIPANT' => 'Requested',
152		'CHAIR'           => 'Chair',
153		'OPT-PARTICIPANT' => 'Optional',
154		'NON-PARTICIPANT' => 'None',
155	);
156	/**
157	 * Alarm times
158	 *
159	 * @var array
160	 */
161	var $alarms = array(
162		300 => '5 Minutes',
163		600 => '10 Minutes',
164		900 => '15 Minutes',
165		1800 => '30 Minutes',
166		3600 => '1 Hour',
167		7200 => '2 Hours',
168		43200 => '12 Hours',
169		86400 => '1 Day',
170		172800 => '2 Days',
171		604800 => '1 Week',
172	);
173	/**
174	 * @var array $resources registered scheduling resources of the calendar (gets cached in the session for performance reasons)
175	 */
176	var $resources;
177	/**
178	 * @var array $cached_event here we do some caching to read single events only once
179	 */
180	protected static $cached_event = array();
181	protected static $cached_event_date_format = false;
182	protected static $cached_event_date = 0;
183
184	/**
185	 * Instance of the socal class
186	 *
187	 * @var calendar_so
188	 */
189	var $so;
190	/**
191	 * Instance of the categories class
192	 *
193	 * @var Api\Categories
194	 */
195	var $categories;
196	/**
197	 * Config values for "calendar", only used for horizont, regular calendar config is under phpgwapi
198	 *
199	 * @var array
200	 */
201	var $config;
202
203	/**
204	 * Does a user require an extra invite grant, to be able to invite an other user, default no
205	 *
206	 * @var string 'all', 'groups' or null
207	 */
208	public $require_acl_invite = null;
209
210	/**
211	 * Warnings to show in regular UI
212	 *
213	 * @var array
214	 */
215	var $warnings = array();
216
217	/**
218	 * Constructor
219	 */
220	function __construct()
221	{
222		if ($this->debug > 0) $this->debug_message('calendar_bo::bocal() started',True);
223
224		$this->so = new calendar_so();
225
226		$this->common_prefs =& $GLOBALS['egw_info']['user']['preferences']['common'];
227		$this->cal_prefs =& $GLOBALS['egw_info']['user']['preferences']['calendar'];
228
229		$this->now = time();
230		$this->now_su = Api\DateTime::server2user($this->now,'ts');
231
232		$this->user = $GLOBALS['egw_info']['user']['account_id'];
233
234		$this->grants = $GLOBALS['egw']->acl->get_grants('calendar');
235
236		if (!is_array($this->resources = Api\Cache::getSession('calendar', 'resources')))
237		{
238			$this->resources = array();
239			foreach(Api\Hooks::process('calendar_resources') as $app => $data)
240			{
241				if ($data && $data['type'])
242				{
243					$this->resources[$data['type']] = $data + array('app' => $app);
244				}
245			}
246			$this->resources['e'] = array(
247				'type' => 'e',
248				'info' => __CLASS__.'::email_info',
249				'app'  => 'email',
250			);
251			$this->resources['l'] = array(
252				'type' => 'l',// one char type-identifier for this resources
253				'info' => __CLASS__ .'::mailing_lists',// info method, returns array with id, type & name for a given id
254				'app' => 'Distribution list'
255			);
256			$this->resources[''] = array(
257				'type' => '',
258				'app' => 'api-accounts',
259			);
260			Api\Cache::setSession('calendar', 'resources', $this->resources);
261		}
262		//error_log(__METHOD__ . " registered resources=". array2string($this->resources));
263
264		$this->config = Api\Config::read('calendar');	// only used for horizont, regular calendar config is under phpgwapi
265		$this->require_acl_invite = $GLOBALS['egw_info']['server']['require_acl_invite'];
266
267		$this->categories = new Api\Categories($this->user,'calendar');
268
269		$this->customfields = Api\Storage\Customfields::get('calendar');
270
271		foreach($this->alarms as $secs => &$label)
272		{
273			$label = self::secs2label($secs);
274		}
275	}
276
277	/**
278	 * Generate translated label for a given number of seconds
279	 *
280	 * @param int $secs
281	 * @return string
282	 */
283	static public function secs2label($secs)
284	{
285		if ($secs <= 3600)
286		{
287			$label = lang('%1 minutes', $secs/60);
288		}
289		elseif($secs <= 86400)
290		{
291			$label = lang('%1 hours', $secs/3600);
292		}
293		else
294		{
295			$label = lang('%1 days', $secs/86400);
296		}
297		return $label;
298	}
299
300	/**
301	 * returns info about email addresses as participants
302	 *
303	 * @param int|array $ids single contact-id or array of id's
304	 * @return array
305	 */
306	static function email_info($ids)
307	{
308		if (!$ids) return null;
309
310		$data = array();
311		foreach((array)$ids as $id)
312		{
313			$email = $id;
314			$name = '';
315			$matches = null;
316			if (preg_match('/^(.*) *<([a-z0-9_.@-]{8,})>$/iU',$email,$matches))
317			{
318				$name = $matches[1];
319				$email = $matches[2];
320			}
321			$data[] = array(
322				'res_id' => $id,
323				'email' => $email,
324				'rights' => self::ACL_READ_FOR_PARTICIPANTS | self::ACL_INVITE,
325				'name' => $name,
326			);
327		}
328		//error_log(__METHOD__.'('.array2string($ids).')='.array2string($data).' '.function_backtrace());
329		return $data;
330	}
331
332	/**
333	 * returns info about mailing lists as participants
334	 *
335	 * @param int|array $ids single mailing list ID or array of id's
336	 * @return array
337	 */
338	static function mailing_lists($ids)
339	{
340		if(!is_array($ids))
341		{
342			$ids = array($ids);
343		}
344		$data = array();
345
346		// Email list
347		$contacts_obj = new Api\Contacts();
348		$bo = new calendar_bo();
349		foreach($ids as $id)
350		{
351			$list = $contacts_obj->read_list((int)$id);
352
353			if(!$list && $id < 0)
354			{
355				$list = array(
356						'list_name' => Link::title('api-accounts',$id) ?: Api\Accounts::username($id)
357				);
358			}
359			$data[] = array(
360				'res_id' => $id,
361				'rights' => self::ACL_READ_FOR_PARTICIPANTS,
362				'name' => $list['list_name'],
363				'resources' => $bo->enum_mailing_list('l'.$id, false, false)
364			);
365		}
366
367		return $data;
368	}
369
370	/**
371	 * Enumerates the contacts in a contact list, and returns the list of contact IDs
372	 *
373	 * This is used to enable mailing lists as owner/participant
374	 *
375	 * @param string $id Mailing list participant ID, which is the mailing list
376	 *	ID prefixed with 'l'
377	 * @param boolean $ignore_acl = false Flag to skip ACL checks
378	 * @param boolean $use_freebusy =true should freebusy rights are taken into account, default true, can be set to false eg. for a search
379	 *
380	 * @return array
381	 */
382	public function enum_mailing_list($id, $ignore_acl= false, $use_freebusy = true)
383	{
384		$contact_list = array();
385		$contacts = new Api\Contacts();
386		if($contacts->check_list((int)substr($id,1), ACL::READ) || (int)substr($id,1) < 0)
387		{
388			$options = array('list' => substr($id,1));
389			$lists = $contacts->search('',true,'','','',false,'AND',false,$options);
390			if(!$lists)
391			{
392				return $contact_list;
393			}
394			foreach($lists as &$contact)
395			{
396				// Check for user account
397				if (($account_id = $GLOBALS['egw']->accounts->name2id($contact['id'],'person_id')))
398				{
399					$contact = ''.$account_id;
400				}
401				else
402				{
403					$contact = 'c'.$contact['id'];
404				}
405				if ($ignore_acl || $this->check_perms(ACL::READ|self::ACL_READ_FOR_PARTICIPANTS|($use_freebusy?self::ACL_FREEBUSY:0),0,$contact))
406				{
407					if ($contact && !in_array($contact,$contact_list))	// already added?
408					{
409						$contact_list[] = $contact;
410					}
411				}
412			}
413		}
414		return $contact_list;
415	}
416
417	/**
418	 * Add group-members as participants with status 'G'
419	 *
420	 * @param array $event event-array
421	 * @return int number of added participants
422	 */
423	function enum_groups(&$event)
424	{
425		$added = 0;
426		foreach (array_keys((array)$event['participants']) as $uid)
427		{
428			if (is_numeric($uid) && $GLOBALS['egw']->accounts->get_type($uid) == 'g' &&
429					($members = $GLOBALS['egw']->accounts->members($uid, true)))
430			{
431				foreach ($members as $member)
432				{
433					if (!isset($event['participants'][$member]))
434					{
435						$event['participants'][$member] = 'G';
436						++$added;
437					}
438				}
439			}
440		}
441		return $added;
442	}
443
444	/**
445	 * Resolve users to add memberships for users and members for groups
446	 *
447	 * @param int|array $_users
448	 * @param boolean $no_enum_groups =true
449	 * @param boolean $ignore_acl =false
450	 * @param boolean $use_freebusy =true should freebusy rights are taken into account, default true, can be set to false eg. for a search
451	 * @return array of user-ids
452	 */
453	private function resolve_users($_users, $no_enum_groups=true, $ignore_acl=false, $use_freebusy=true)
454	{
455		if (!is_array($_users))
456		{
457			$_users = $_users ? array($_users) : array();
458		}
459		// only query calendars of users, we have READ-grants from
460		$users = array();
461		foreach($_users as $user)
462		{
463			$user = trim($user);
464
465			// Handle email lists
466			if(!is_numeric($user) && $user[0] == 'l')
467			{
468				foreach($this->enum_mailing_list($user, $ignore_acl, $use_freebusy) as $contact)
469				{
470					if ($contact && !in_array($contact,$users))	// already added?
471					{
472						$users[] = $contact;
473					}
474				}
475				continue;
476			}
477			if ($ignore_acl || $this->check_perms(ACL::READ|self::ACL_READ_FOR_PARTICIPANTS|($use_freebusy?self::ACL_FREEBUSY:0),0,$user))
478			{
479				if ($user && !in_array($user,$users))	// already added?
480				{
481					// General expansion check
482					if (!is_numeric($user) && $this->resources[$user[0]]['info'])
483					{
484						$info = $this->resource_info($user);
485						if($info && $info['resources'])
486						{
487							foreach($info['resources'] as $_user)
488							{
489								if($_user && !in_array($_user, $users))
490								{
491									$users[] = $_user;
492								}
493							}
494							continue;
495						}
496					}
497					$users[] = $user;
498				}
499			}
500			elseif ($GLOBALS['egw']->accounts->get_type($user) != 'g')
501			{
502				continue;	// for non-groups (eg. users), we stop here if we have no read-rights
503			}
504			// the further code is only for real users
505			if (!is_numeric($user)) continue;
506
507			// for groups we have to include the members
508			if ($GLOBALS['egw']->accounts->get_type($user) == 'g')
509			{
510				if ($no_enum_groups) continue;
511
512				$members = $GLOBALS['egw']->accounts->members($user, true);
513				if (is_array($members))
514				{
515					foreach($members as $member)
516					{
517						// use only members which gave the user a read-grant
518						if (!in_array($member, $users) &&
519							($ignore_acl || $this->check_perms(Acl::READ|($use_freebusy?self::ACL_FREEBUSY:0),0,$member)))
520						{
521							$users[] = $member;
522						}
523					}
524				}
525			}
526			else	// for users we have to include all the memberships, to get the group-events
527			{
528				$memberships = $GLOBALS['egw']->accounts->memberships($user, true);
529				if (is_array($memberships))
530				{
531					foreach($memberships as $group)
532					{
533						if (!in_array($group,$users))
534						{
535							$users[] = $group;
536						}
537					}
538				}
539			}
540		}
541		return $users;
542	}
543
544	/**
545	 * Searches / lists calendar entries, including repeating ones
546	 *
547	 * @param array $params array with the following keys
548	 *	start date startdate of the search/list, defaults to today
549	 *	end   date enddate of the search/list, defaults to start + one day
550	 *	users  int|array integer user-id or array of user-id's to use, defaults to the current user
551	 *  cat_id int|array category-id or array of cat-id's (incl. all sub-categories), default 0 = all
552	 *	filter string all (not rejected), accepted, unknown, tentative, rejected, hideprivate or everything (incl. rejected, deleted)
553	 *	query string pattern so search for, if unset or empty all matching entries are returned (no search)
554	 *		Please Note: a search never returns repeating events more then once AND does not honor start+end date !!!
555	 *	daywise boolean on True it returns an array with YYYYMMDD strings as keys and an array with events
556	 *		(events spanning multiple days are returned each day again (!)) otherwise it returns one array with
557	 *		the events (default), not honored in a search ==> always returns an array of events!
558	 *	date_format string date-formats: 'ts'=timestamp (default), 'array'=array, or string with format for date
559	 *  offset boolean|int false (default) to return all entries or integer offset to return only a limited result
560	 *  enum_recuring boolean if true or not set (default) or daywise is set, each recurence of a recuring events is returned,
561	 *		otherwise the original recuring event (with the first start- + enddate) is returned
562	 *  num_rows int number of entries to return, default or if 0, max_entries from the prefs
563	 *  order column-names plus optional DESC|ASC separted by comma
564	 *  private_allowed array Array of user IDs that are allowed when clearing private
565	 *		info, defaults to users
566	 *  ignore_acl if set and true no check_perms for a general Acl::READ grants is performed
567	 *  enum_groups boolean if set and true, group-members will be added as participants with status 'G'
568	 *  cols string|array columns to select, if set an iterator will be returned
569	 *  append string to append to the query, eg. GROUP BY
570	 *  cfs array if set, query given custom fields or all for empty array, none are returned, if not set (default)
571	 *  master_only boolean default false, true only take into account participants/status from master (for AS)
572	 * @param string $sql_filter =null sql to be and'ed into query (fully quoted), default none
573	 * @return iterator|array|boolean array of events or array with YYYYMMDD strings / array of events pairs (depending on $daywise param)
574	 *	or false if there are no read-grants from _any_ of the requested users or iterator/recordset if cols are given
575	 */
576	function &search($params,$sql_filter=null)
577	{
578		$params_in = $params;
579
580		$params['sql_filter'] = $sql_filter;	// dont allow to set it via UI or xmlrpc
581
582		// check if any resource wants to hook into
583		foreach($this->resources as $data)
584		{
585			if (isset($data['search_filter']))
586			{
587				$params = ExecMethod($data['search_filter'],$params);
588			}
589		}
590
591		if (empty($params['users']) ||
592			is_array($params['users']) && count($params['users']) == 1 && empty($params['users'][0]))	// null or '' casted to an array
593		{
594			// for a search use all account you have read grants from
595			$params['users'] = $params['query'] ? array_keys($this->grants) : $this->user;
596		}
597		// resolve users to add memberships for users and members for groups
598		// for search, do NOT use freebusy rights, as it would allow to probe the content of event entries
599		$users = $this->resolve_users($params['users'], $params['filter'] == 'no-enum-groups', $params['ignore_acl'], empty($params['query']));
600		if($params['private_allowed'])
601		{
602			$params['private_allowed'] = $this->resolve_users($params['private_allowed'],$params['filter'] == 'no-enum-groups',$params['ignore_acl'], empty($params['query']));
603		}
604
605		// supply so with private_grants, to not query them again from the database
606		if (!empty($params['query']))
607		{
608			$params['private_grants'] = array();
609			foreach($this->grants as $user => $rights)
610			{
611				if ($rights & Acl::PRIVAT) $params['private_grants'][] = $user;
612			}
613		}
614
615		// replace (by so not understood filter 'no-enum-groups' with 'default' filter
616		if ($params['filter'] == 'no-enum-groups')
617		{
618			$params['filter'] = 'default';
619		}
620		// if we have no grants from the given user(s), we directly return no events / an empty array,
621		// as calling the so-layer without users would give the events of all users (!)
622		if (!count($users) && !$params['ignore_acl'])
623		{
624			return false;
625		}
626		if (isset($params['start'])) $start = $this->date2ts($params['start']);
627
628		if (isset($params['end']))
629		{
630			$end = $this->date2ts($params['end']);
631			$this->check_move_horizont($end);
632		}
633		$daywise = !isset($params['daywise']) ? False : !!$params['daywise'];
634		$params['enum_recuring'] = $enum_recuring = $daywise || !isset($params['enum_recuring']) || !!$params['enum_recuring'];
635		$cat_id = isset($params['cat_id']) ? $params['cat_id'] : 0;
636		$filter = isset($params['filter']) ? $params['filter'] : 'all';
637		$offset = isset($params['offset']) && $params['offset'] !== false ? (int) $params['offset'] : false;
638		// socal::search() returns rejected group-invitations, as only the user not also the group is rejected
639		// as we cant remove them efficiantly in SQL, we kick them out here, but only if just one user is displayed
640		$users_in = (array)$params_in['users'];
641		$remove_rejected_by_user = !in_array($filter,array('all','rejected','everything')) &&
642			count($users_in) == 1 && $users_in[0] > 0 ? $users_in[0] : null;
643		//error_log(__METHOD__.'('.array2string($params_in).", $sql_filter) params[users]=".array2string($params['users']).' --> remove_rejected_by_user='.array2string($remove_rejected_by_user));
644
645		if ($this->debug && ($this->debug > 1 || $this->debug == 'search'))
646		{
647			$this->debug_message('calendar_bo::search(%1) start=%2, end=%3, daywise=%4, cat_id=%5, filter=%6, query=%7, offset=%8, num_rows=%9, order=%10, sql_filter=%11)',
648				True,$params,$start,$end,$daywise,$cat_id,$filter,$params['query'],$offset,(int)$params['num_rows'],$params['order'],$params['sql_filter']);
649		}
650		// date2ts(,true) converts to server time, db2data converts again to user-time
651		$events =& $this->so->search(isset($start) ? $this->date2ts($start,true) : null,isset($end) ? $this->date2ts($end,true) : null,
652			$users,$cat_id,$filter,$offset,(int)$params['num_rows'],$params,$remove_rejected_by_user);
653
654		if (isset($params['cols']))
655		{
656			return $events;
657		}
658		$this->total = $this->so->total;
659		$this->db2data($events,isset($params['date_format']) ? $params['date_format'] : 'ts');
660
661		//echo "<p align=right>remove_rejected_by_user=$remove_rejected_by_user, filter=$filter, params[users]=".print_r($param['users'])."</p>\n";
662		foreach($events as $id => $event)
663		{
664			if ($params['enum_groups'] && $this->enum_groups($event))
665			{
666				$events[$id] = $event;
667			}
668			$matches = null;
669			if (!(int)$event['id'] && preg_match('/^([a-z_]+)([0-9]+)$/',$event['id'],$matches))
670			{
671				$is_private = self::integration_get_private($matches[1],$matches[2],$event);
672			}
673			else
674			{
675				$is_private = !$this->check_perms(Acl::READ,$event);
676			}
677			if (!$params['ignore_acl'] && ($is_private || (!$event['public'] && $filter == 'hideprivate')))
678			{
679				$this->clear_private_infos($events[$id],$params['private_allowed'] ? $params['private_allowed'] : $users);
680			}
681		}
682
683		if ($daywise)
684		{
685			if ($this->debug && ($this->debug > 2 || $this->debug == 'search'))
686			{
687				$this->debug_message('socalendar::search daywise sorting from %1 to %2 of %3',False,$start,$end,$events);
688			}
689			// create empty entries for each day in the reported time
690			for($ts = $start; $ts <= $end; $ts += DAY_s) // good enough for array creation, but see while loop below.
691			{
692				$daysEvents[$this->date2string($ts)] = array();
693			}
694			foreach($events as $k => $event)
695			{
696				$e_start = max($this->date2ts($event['start']),$start);
697				// $event['end']['raw']-1 to allow events to end on a full hour/day without the need to enter it as minute=59
698				$e_end   = min($this->date2ts($event['end'])-1,$end);
699
700				// add event to each day in the reported time
701				$ts = $e_start;
702				//  $ts += DAY_s in a 'for' loop does not work for daylight savings in week view
703				// because the day is longer than DAY_s: Fullday events will be added twice.
704				$ymd = null;
705				while ($ts <= $e_end)
706				{
707					$daysEvents[$ymd = $this->date2string($ts)][] =& $events[$k];
708					$ts = strtotime("+1 day",$ts);
709				}
710				if ($ymd != ($last = $this->date2string($e_end)))
711				{
712					$daysEvents[$last][] =& $events[$k];
713				}
714			}
715			$events =& $daysEvents;
716			if ($this->debug && ($this->debug > 2 || $this->debug == 'search'))
717			{
718				$this->debug_message('socalendar::search daywise events=%1',False,$events);
719			}
720		}
721		if ($this->debug && ($this->debug > 0 || $this->debug == 'search'))
722		{
723			$this->debug_message('calendar_bo::search(%1)=%2',True,$params,$events);
724		}
725		//error_log(__METHOD__."() returning ".count($events)." entries, total=$this->total ".function_backtrace());
726		return $events;
727	}
728
729	/**
730	 * Get integration data for a given app of a part (value for a certain key) of it
731	 *
732	 * @param string $app
733	 * @param string $part
734	 * @return array
735	 */
736	static function integration_get_data($app,$part=null)
737	{
738		static $integration_data=null;
739
740		if (!isset($integration_data))
741		{
742			$integration_data = calendar_so::get_integration_data();
743		}
744
745		if (!isset($integration_data[$app])) return null;
746
747		return $part ? $integration_data[$app][$part] : $integration_data[$app];
748	}
749
750	/**
751	 * Get private attribute for an integration event
752	 *
753	 * Attribute 'is_private' is either a boolean value, eg. false to make all events of $app public
754	 * or an ExecMethod callback with parameters $id,$event
755	 *
756	 * @param string $app
757	 * @param int|string $id
758	 * @return string
759	 */
760	static function integration_get_private($app,$id,$event)
761	{
762		$app_data = self::integration_get_data($app,'is_private');
763
764		// no method, fall back to link title
765		if (is_null($app_data))
766		{
767			$is_private = !Link::title($app,$id);
768		}
769		// boolean value to make all events of $app public (false) or private (true)
770		elseif (is_bool($app_data))
771		{
772			$is_private = $app_data;
773		}
774		else
775		{
776			$is_private = (bool)ExecMethod2($app_data,$id,$event);
777		}
778		//echo '<p>'.__METHOD__."($app,$id,) app_data=".array2string($app_data).' returning '.array2string($is_private)."</p>\n";
779		return $is_private;
780	}
781
782	/**
783	 * Clears all non-private info from a privat event
784	 *
785	 * That function only returns the infos allowed to be viewed by people without Acl::PRIVAT grants
786	 *
787	 * @param array &$event
788	 * @param array $allowed_participants ids of the allowed participants, eg. the ones the search is over or eg. the owner of the calendar
789	 */
790	function clear_private_infos(&$event,$allowed_participants = array())
791	{
792		if ($event == false) return;
793		if (!is_array($event['participants'])) error_log(__METHOD__.'('.array2string($event).', '.array2string($allowed_participants).') NO PARTICIPANTS '.function_backtrace());
794
795		$event = array(
796			'id'    => $event['id'],
797			'start' => $event['start'],
798			'end'   => $event['end'],
799			'whole_day' => $event['whole_day'],
800			'tzid'  => $event['tzid'],
801			'title' => lang('private'),
802			'modified'	=> $event['modified'],
803			'owner'		=> $event['owner'],
804			'uid'	=> $event['uid'],
805			'etag'	=> $event['etag'],
806			'participants' => array_intersect_key($event['participants'],array_flip($allowed_participants)),
807			'public'=> 0,
808			'category' => $event['category'],	// category is visible anyway, eg. by using planner by cat
809			'non_blocking' => $event['non_blocking'],
810			'caldav_name' => $event['caldav_name'],
811		// we need full recurrence information, as they are relevant free/busy information
812		)+($event['recur_type'] ? array(
813			'recur_type'     => $event['recur_type'],
814			'recur_interval' => $event['recur_interval'],
815			'recur_data'     => $event['recur_data'],
816			'recur_enddate'  => $event['recur_enddate'],
817			'recur_exception'=> $event['recur_exception'],
818		):array(
819			'reference'      => $event['reference'],
820			'recurrence'     => $event['recurrence'],
821		));
822	}
823
824	/**
825	 * check and evtl. move the horizont (maximum date for unlimited recuring events) to a new date
826	 *
827	 * @internal automaticaly called by search
828	 * @param mixed $_new_horizont time to set the horizont to (user-time)
829	 */
830	function check_move_horizont($_new_horizont)
831	{
832		if ((int) $this->debug >= 2 || $this->debug == 'check_move_horizont')
833		{
834			$this->debug_message('calendar_bo::check_move_horizont(%1) horizont=%2',true,$_new_horizont,(int)$this->config['horizont']);
835		}
836		$new_horizont = $this->date2ts($_new_horizont,true);	// now we are in server-time, where this function operates
837
838		if ($new_horizont <= $this->config['horizont'])	// no move necessary
839		{
840			if ($this->debug == 'check_move_horizont') $this->debug_message('calendar_bo::check_move_horizont(%1) horizont=%2 is bigger ==> nothing to do',true,$new_horizont,(int)$this->config['horizont']);
841			return;
842		}
843		if (!empty($GLOBALS['egw_info']['server']['calendar_horizont']))
844		{
845			$maxdays = abs($GLOBALS['egw_info']['server']['calendar_horizont']);
846		}
847		if (empty($maxdays)) $maxdays = 1000; // old default
848		if ($new_horizont > time()+$maxdays*DAY_s)		// some user tries to "look" more then the maximum number of days in the future
849		{
850			if ($this->debug == 'check_move_horizont') $this->debug_message('calendar_bo::check_move_horizont(%1) horizont=%2 new horizont more then %3 days from now --> ignoring it',true,$new_horizont,(int)$this->config['horizont'],$maxdays);
851			$this->warnings['horizont'] = lang('Requested date %1 outside allowed range of %2 days: recurring events obmitted!', Api\DateTime::to($new_horizont,true), $maxdays);
852			return;
853		}
854		if ($new_horizont < time()+31*DAY_s)
855		{
856			$new_horizont = time()+31*DAY_s;
857		}
858		$old_horizont = $this->config['horizont'];
859		$this->config['horizont'] = $new_horizont;
860
861		// create further recurrences for all recurring and not yet (at the old horizont) ended events
862		if (($recuring = $this->so->unfinished_recuring($old_horizont)))
863		{
864			@set_time_limit(0);	// disable time-limit, in case it takes longer to calculate the recurrences
865			foreach($this->read(array_keys($recuring)) as $cal_id => $event)
866			{
867				if ($this->debug == 'check_move_horizont')
868				{
869					$this->debug_message('calendar_bo::check_move_horizont(%1): calling set_recurrences(%2,%3)',true,$new_horizont,$event,$old_horizont);
870				}
871				// insert everything behind max(cal_start), which can be less then $old_horizont because of bugs in the past
872				$this->set_recurrences($event,Api\DateTime::server2user($recuring[$cal_id]+1));	// set_recurences operates in user-time!
873			}
874		}
875		// update the horizont
876		Api\Config::save_value('horizont',$this->config['horizont'],'calendar');
877
878		if ($this->debug == 'check_move_horizont') $this->debug_message('calendar_bo::check_move_horizont(%1) new horizont=%2, exiting',true,$new_horizont,(int)$this->config['horizont']);
879	}
880
881	/**
882	 * set all recurrences for an event until the defined horizont $this->config['horizont']
883	 *
884	 * This methods operates in usertime, while $this->config['horizont'] is in servertime!
885	 *
886	 * @param array $event
887	 * @param mixed $start =0 minimum start-time for new recurrences or !$start = since the start of the event
888	 */
889	function set_recurrences($event,$start=0)
890	{
891		if ($this->debug && ((int) $this->debug >= 2 || $this->debug == 'set_recurrences' || $this->debug == 'check_move_horizont'))
892		{
893			$this->debug_message('calendar_bo::set_recurrences(%1,%2)',true,$event,$start);
894		}
895		// check if the caller gave us enough information and if not read it from the DB
896		if (!isset($event['participants']) || !isset($event['start']) || !isset($event['end']))
897		{
898			$event_read = current($this->so->read($event['id']));
899			if (!isset($event['participants']))
900			{
901				$event['participants'] = $event_read['participants'];
902			}
903			if (!isset($event['start']) || !isset($event['end']))
904			{
905				$event['start'] = $this->date2usertime($event_read['start']);
906				$event['end'] = $this->date2usertime($event_read['end']);
907			}
908		}
909		if (!$start) $start = $event['start'];
910
911		$events = array();
912
913		$this->insert_all_recurrences($event,$start,$this->date2usertime($this->config['horizont']),$events);
914
915		$exceptions = array();
916		foreach((array)$event['recur_exception'] as $exception)
917		{
918			$exceptions[] = Api\DateTime::to($exception, true);	// true = date
919		}
920		foreach($events as $event)
921		{
922			$is_exception = in_array(Api\DateTime::to($event['start'], true), $exceptions);
923			$start = $this->date2ts($event['start'],true);
924			if ($event['whole_day'])
925			{
926				$start = new Api\DateTime($event['start'], Api\DateTime::$server_timezone);
927				$start->setTime(0,0,0);
928				$start = $start->format('ts');
929				$time = $this->so->startOfDay(new Api\DateTime($event['end'], Api\DateTime::$user_timezone));
930				$time->setTime(23, 59, 59);
931				$end = $this->date2ts($time,true);
932			}
933			else
934			{
935				$end = $this->date2ts($event['end'],true);
936			}
937			//error_log(__METHOD__."() start=".Api\DateTime::to($start).", is_exception=".array2string($is_exception));
938			$this->so->recurrence($event['id'], $start, $end, $event['participants'], $is_exception);
939		}
940	}
941
942	/**
943	 * Convert data read from the db, eg. convert server to user-time
944	 *
945	 * Also make sure all timestamps comming from DB as string are converted to integer,
946	 * to avoid misinterpretation by Api\DateTime as Ymd string.
947	 *
948	 * @param array &$events array of event-arrays (reference)
949	 * @param $date_format ='ts' date-formats: 'ts'=timestamp, 'server'=timestamp in server-time, 'array'=array or string with date-format
950	 */
951	function db2data(&$events,$date_format='ts')
952	{
953		if (!is_array($events)) echo "<p>calendar_bo::db2data(\$events,$date_format) \$events is no array<br />\n".function_backtrace()."</p>\n";
954		foreach ($events as &$event)
955		{
956			// convert timezone id of event to tzid (iCal id like 'Europe/Berlin')
957			if (empty($event['tzid']) && (!$event['tz_id'] || !($event['tzid'] = calendar_timezones::id2tz($event['tz_id']))))
958			{
959				$event['tzid'] = Api\DateTime::$server_timezone->getName();
960			}
961			// database returns timestamps as string, convert them to integer
962			// to avoid misinterpretation by Api\DateTime as Ymd string
963			// (this will fail on 32bit systems for times > 2038!)
964			$event['start'] = (int)$event['start'];	// this is for isWholeDay(), which also calls Api\DateTime
965			$event['end'] = (int)$event['end'];
966			$event['whole_day'] = self::isWholeDay($event);
967			if ($event['whole_day'] && $date_format != 'server')
968			{
969				// Adjust dates to user TZ
970				$stime =& $this->so->startOfDay(new Api\DateTime((int)$event['start'], Api\DateTime::$server_timezone), $event['tzid']);
971				$event['start'] = Api\DateTime::to($stime, $date_format);
972				$time =& $this->so->startOfDay(new Api\DateTime((int)$event['end'], Api\DateTime::$server_timezone), $event['tzid']);
973				$time->setTime(23, 59, 59);
974				$event['end'] = Api\DateTime::to($time, $date_format);
975				if (!empty($event['recurrence']))
976				{
977					$time =& $this->so->startOfDay(new Api\DateTime((int)$event['recurrence'], Api\DateTime::$server_timezone), $event['tzid']);
978					$event['recurrence'] = Api\DateTime::to($time, $date_format);
979				}
980				if (!empty($event['recur_enddate']))
981				{
982					$time =& $this->so->startOfDay(new Api\DateTime((int)$event['recur_enddate'], Api\DateTime::$server_timezone), $event['tzid']);
983					$time->setTime(23, 59, 59);
984					$event['recur_enddate'] = Api\DateTime::to($time, $date_format);
985				}
986				$timestamps = array('modified','created','deleted');
987			}
988			else
989			{
990				$timestamps = array('start','end','modified','created','recur_enddate','recurrence','recur_date','deleted');
991			}
992			// we convert here from the server-time timestamps to user-time and (optional) to a different date-format!
993			foreach ($timestamps as $ts)
994			{
995				if (!empty($event[$ts]))
996				{
997					$event[$ts] = $this->date2usertime((int)$event[$ts],$date_format);
998				}
999			}
1000			// same with the recur exceptions
1001			if (isset($event['recur_exception']) && is_array($event['recur_exception']))
1002			{
1003				foreach($event['recur_exception'] as &$date)
1004				{
1005					if ($event['whole_day'] && $date_format != 'server')
1006					{
1007						// Adjust dates to user TZ
1008						$time =& $this->so->startOfDay(new Api\DateTime((int)$date, Api\DateTime::$server_timezone), $event['tzid']);
1009						$date = Api\DateTime::to($time, $date_format);
1010					}
1011					else
1012					{
1013						$date = $this->date2usertime((int)$date,$date_format);
1014					}
1015				}
1016			}
1017			// same with the alarms
1018			if (isset($event['alarm']) && is_array($event['alarm']))
1019			{
1020				foreach($event['alarm'] as &$alarm)
1021				{
1022					$alarm['time'] = $this->date2usertime((int)$alarm['time'],$date_format);
1023				}
1024			}
1025		}
1026	}
1027
1028	/**
1029	 * convert a date from server to user-time
1030	 *
1031	 * @param int $ts timestamp in server-time
1032	 * @param string $date_format ='ts' date-formats: 'ts'=timestamp, 'server'=timestamp in server-time, 'array'=array or string with date-format
1033	 * @return mixed depending of $date_format
1034	 */
1035	function date2usertime($ts,$date_format='ts')
1036	{
1037		if (empty($ts) || $date_format == 'server') return $ts;
1038
1039		return Api\DateTime::server2user($ts,$date_format);
1040	}
1041
1042	/**
1043	 * Reads a calendar-entry
1044	 *
1045	 * @param int|array|string $ids id or array of id's of the entries to read, or string with a single uid
1046	 * @param mixed $date =null date to specify a single event of a series
1047	 * @param boolean $ignore_acl should we ignore the acl, default False for a single id, true for multiple id's
1048	 * @param string $date_format ='ts' date-formats: 'ts'=timestamp, 'server'=timestamp in servertime, 'array'=array, or string with date-format
1049	 * @param array|int $clear_private_infos_users =null if not null, return events with self::ACL_FREEBUSY too,
1050	 * 	but call clear_private_infos() with the given users
1051	 * @param boolean $read_recurrence =false true: read the exception, not the series master (only for recur_date && $ids='<uid>'!)
1052	 * @return boolean|array event or array of id => event pairs, false if the acl-check went wrong, null if $ids not found
1053	 */
1054	function read($ids,$date=null, $ignore_acl=False, $date_format='ts', $clear_private_infos_users=null, $read_recurrence=false)
1055	{
1056		if (!$ids) return false;
1057
1058		if ($date) $date = $this->date2ts($date);
1059
1060		$return = null;
1061
1062		$check = $clear_private_infos_users ? self::ACL_FREEBUSY : Acl::READ;
1063		if ($ignore_acl || is_array($ids) || ($return = $this->check_perms($check,$ids,0,$date_format,$date)))
1064		{
1065			if (is_array($ids) || !isset(self::$cached_event['id']) || self::$cached_event['id'] != $ids ||
1066				self::$cached_event_date_format != $date_format || $read_recurrence ||
1067				self::$cached_event['recur_type'] != MCAL_RECUR_NONE && self::$cached_event_date != $date)
1068			{
1069				$events = $this->so->read($ids,$date ? $this->date2ts($date,true) : 0, $read_recurrence);
1070
1071				if ($events)
1072				{
1073					$this->db2data($events,$date_format);
1074
1075					if (is_array($ids))
1076					{
1077						$return =& $events;
1078					}
1079					else
1080					{
1081						self::$cached_event = array_shift($events);
1082						self::$cached_event_date_format = $date_format;
1083						self::$cached_event_date = $date;
1084						$return = self::$cached_event;
1085					}
1086				}
1087			}
1088			else
1089			{
1090				$return = self::$cached_event;
1091			}
1092		}
1093		if ($clear_private_infos_users && !is_array($ids) && !$this->check_perms(Acl::READ,$return))
1094		{
1095			$this->clear_private_infos($return, (array)$clear_private_infos_users);
1096		}
1097		if ($this->debug && ($this->debug > 1 || $this->debug == 'read'))
1098		{
1099			$this->debug_message('calendar_bo::read(%1,%2,%3,%4,%5)=%6',True,$ids,$date,$ignore_acl,$date_format,$clear_private_infos_users,$return);
1100		}
1101		return $return;
1102	}
1103
1104	/**
1105	 * Inserts all repetions of $event in the timespan between $start and $end into $events
1106	 *
1107	 * The new entries are just appended to $events, so $events is no longer sorted by startdate !!!
1108	 *
1109	 * Recurrences get calculated by rrule iterator implemented in calendar_rrule class.
1110	 *
1111	 * @param array $event repeating event whos repetions should be inserted
1112	 * @param mixed $start start-date
1113	 * @param mixed $end end-date
1114	 * @param array $events where the repetions get inserted
1115	 * @param array $recur_exceptions with date (in Ymd) as key (and True as values), seems not to be used anymore
1116	 */
1117	function insert_all_recurrences($event,$_start,$end,&$events)
1118	{
1119		if ((int) $this->debug >= 3 || $this->debug == 'set_recurrences' || $this->debug == 'check_move_horizont' || $this->debug == 'insert_all_recurrences')
1120		{
1121			$this->debug_message(__METHOD__.'(%1,%2,%3,&$events)',true,$event,$_start,$end);
1122		}
1123		$end_in = $end;
1124
1125		$start = $this->date2ts($_start);
1126		$event_start_ts = $this->date2ts($event['start']);
1127		$event_length = $this->date2ts($event['end']) - $event_start_ts;	// we use a constant event-length, NOT a constant end-time!
1128
1129		// if $end is before recur_enddate, use it instead
1130		if (!$event['recur_enddate'] || $this->date2ts($event['recur_enddate']) > $this->date2ts($end))
1131		{
1132			//echo "<p>recur_enddate={$event['recur_enddate']}=".Api\DateTime::to($event['recur_enddate'])." > end=$end=".Api\DateTime::to($end)." --> using end instead of recur_enddate</p>\n";
1133			// insert at least the event itself, if it's behind the horizont
1134			$event['recur_enddate'] = $this->date2ts($end) < $this->date2ts($event['end']) ? $event['end'] : $end;
1135		}
1136		$event['recur_enddate'] = is_a($event['recur_enddate'],'DateTime') ?
1137				$event['recur_enddate'] :
1138				new Api\DateTime($event['recur_enddate'], calendar_timezones::DateTimeZone($event['tzid']));
1139
1140		// unset exceptions, as we need to add them as recurrence too, but marked as exception
1141		unset($event['recur_exception']);
1142		// loop over all recurrences and insert them, if they are after $start
1143 		$rrule = calendar_rrule::event2rrule($event, !$event['whole_day'], Api\DateTime::$user_timezone->getName());	// true = we operate in usertime, like the rest of calendar_bo
1144		foreach($rrule as $time)
1145		{
1146			$time->setUser();	// $time is in timezone of event, convert it to usertime used here
1147			if($event['whole_day'])
1148			{
1149				// All day events are processed in server timezone
1150				$time->setServer();
1151				$time->setTime(0,0,0);
1152			}
1153			if (($ts = $this->date2ts($time)) < $start-$event_length)
1154			{
1155				//echo "<p>".$time." --> ignored as $ts < $start-$event_length</p>\n";
1156				continue;	// to early or original event (returned by interator too)
1157			}
1158
1159			$ts_end = $ts + $event_length;
1160			// adjust ts_end for whole day events in case it does not fit due to
1161			// spans over summer/wintertime adjusted days
1162			if($event['whole_day'] && ($arr_end = $this->date2array($ts_end)) &&
1163				!($arr_end['hour'] == 23 && $arr_end['minute'] == 59 && $arr_end['second'] == 59))
1164			{
1165				$arr_end['hour'] = 23;
1166				$arr_end['minute'] = 59;
1167				$arr_end['second'] = 59;
1168				$ts_end_guess = $this->date2ts($arr_end);
1169				if($ts_end_guess - $ts_end > DAY_s/2)
1170				{
1171					$ts_end = $ts_end_guess - DAY_s; // $ts_end_guess was one day too far in the future
1172				}
1173				else
1174				{
1175					$ts_end = $ts_end_guess; // $ts_end_guess was ok
1176				}
1177			}
1178
1179			$event['start'] = $ts;
1180			$event['end'] = $ts_end;
1181			$events[] = $event;
1182		}
1183		if ($this->debug && ((int) $this->debug > 2 || $this->debug == 'set_recurrences' || $this->debug == 'check_move_horizont' || $this->debug == 'insert_all_recurrences'))
1184		{
1185			$event['start'] = $event_start_ts;
1186			$event['end'] = $event_start_ts + $event_length;
1187			$this->debug_message(__METHOD__.'(%1,start=%2,end=%3,events) events=%5',True,$event,$_start,$end_in,$events);
1188		}
1189	}
1190
1191	/**
1192	 * Adds one repetion of $event for $date_ymd to the $events array, after adjusting its start- and end-time
1193	 *
1194	 * @param array $events array in which the event gets inserted
1195	 * @param array $event event to insert, it has start- and end-date of the first recurrence, not of $date_ymd
1196	 * @param int|string $date_ymd of the date of the event
1197	 */
1198	function add_adjusted_event(&$events,$event,$date_ymd)
1199	{
1200		$event_in = $event;
1201		// calculate the new start- and end-time
1202		$length_s = $this->date2ts($event['end']) - $this->date2ts($event['start']);
1203		$event_start_arr = $this->date2array($event['start']);
1204
1205		$date_arr = $this->date2array((string) $date_ymd);
1206		$date_arr['hour'] = $event_start_arr['hour'];
1207		$date_arr['minute'] = $event_start_arr['minute'];
1208		$date_arr['second'] = $event_start_arr['second'];
1209		unset($date_arr['raw']);	// else date2ts would use it
1210		$event['start'] = $this->date2ts($date_arr);
1211		$event['end'] = $event['start'] + $length_s;
1212
1213		$events[] = $event;
1214
1215		if ($this->debug && ($this->debug > 2 || $this->debug == 'add_adjust_event'))
1216		{
1217			$this->debug_message('calendar_bo::add_adjust_event(,%1,%2) as %3',True,$event_in,$date_ymd,$event);
1218		}
1219	}
1220
1221	/**
1222	 * Fetch information about a resource
1223	 *
1224	 * We do some caching here, as the resource itself might not do it.
1225	 *
1226	 * @param string $uid string with one-letter resource-type and numerical resource-id, eg. "r19"
1227	 * @return array|boolean array with keys res_id,cat_id,name,useable (name definied by max_quantity in $this->resources),rights,responsible or false if $uid is not found
1228	 */
1229	function resource_info($uid)
1230	{
1231		static $res_info_cache = array();
1232
1233		if (!is_scalar($uid)) throw new Api\Exception\WrongParameter(__METHOD__.'('.array2string($uid).') parameter must be scalar');
1234
1235		if (!isset($res_info_cache[$uid]))
1236		{
1237			if (is_numeric($uid))
1238			{
1239				$info = array(
1240					'res_id'    => $uid,
1241					'email' => $GLOBALS['egw']->accounts->id2name($uid,'account_email'),
1242					'name'  => trim($GLOBALS['egw']->accounts->id2name($uid,'account_firstname'). ' ' .
1243					$GLOBALS['egw']->accounts->id2name($uid,'account_lastname')),
1244					'type'  => $GLOBALS['egw']->accounts->get_type($uid),
1245					'app'   => 'accounts',
1246				);
1247			}
1248			else
1249			{
1250				list($info) = $this->resources[$uid[0]]['info'] ? ExecMethod($this->resources[$uid[0]]['info'],substr($uid,1)) : false;
1251				if ($info)
1252				{
1253					$info['type'] = $uid[0];
1254					if (!$info['email'] && $info['responsible'])
1255					{
1256						$info['email'] = $GLOBALS['egw']->accounts->id2name($info['responsible'],'account_email');
1257					}
1258					$info['app'] = $this->resources[$uid[0]]['app'];
1259				}
1260			}
1261			$res_info_cache[$uid] = $info;
1262		}
1263		if ($this->debug && ($this->debug > 2 || $this->debug == 'resource_info'))
1264		{
1265			$this->debug_message('calendar_bo::resource_info(%1) = %2',True,$uid,$res_info_cache[$uid]);
1266		}
1267		return $res_info_cache[$uid];
1268	}
1269
1270	/**
1271	 * Checks if the current user has the necessary ACL rights
1272	 *
1273	 * The check is performed on an event or generally on the cal of an other user
1274	 *
1275	 * Note: Participating in an event is considered as haveing read-access on that event,
1276	 *	even if you have no general read-grant from that user.
1277	 *
1278	 * @param int $needed necessary ACL right: Acl::{READ|EDIT|DELETE}
1279	 * @param mixed $event event as array or the event-id or 0 for a general check
1280	 * @param int $other uid to check (if event==0) or 0 to check against $this->user
1281	 * @param string $date_format ='ts' date-format used for reading: 'ts'=timestamp, 'array'=array, 'string'=iso8601 string for xmlrpc
1282	 * @param mixed $date_to_read =null date used for reading, internal param for the caching
1283	 * @param int $user =null for which user to check, default current user
1284	 * @return boolean true permission granted, false for permission denied or null if event not found
1285	 */
1286	function check_perms($needed,$event=0,$other=0,$date_format='ts',$date_to_read=null,$user=null)
1287	{
1288		if (!$user) $user = $this->user;
1289		if ($user == $this->user)
1290		{
1291			$grants = $this->grants;
1292		}
1293		else
1294		{
1295			$grants = $GLOBALS['egw']->acl->get_grants('calendar',true,$user);
1296		}
1297
1298		if ($other && !is_numeric($other))
1299		{
1300			$resource = $this->resource_info($other);
1301			return $needed & $resource['rights'];
1302		}
1303		if (is_int($event) && $event == 0)
1304		{
1305			$owner = $other ? $other : $user;
1306		}
1307		else
1308		{
1309			if (!is_array($event))
1310			{
1311				$event = $this->read($event,$date_to_read,true,$date_format);	// = no ACL check !!!
1312			}
1313			if (!is_array($event))
1314			{
1315				if ($this->xmlrpc)
1316				{
1317					$GLOBALS['server']->xmlrpc_error($GLOBALS['xmlrpcerr']['not_exist'],$GLOBALS['xmlrpcstr']['not_exist']);
1318				}
1319				return null;	// event not found
1320			}
1321			$owner = $event['owner'];
1322			$private = !$event['public'];
1323		}
1324		$grant = $grants[$owner];
1325
1326		// now any ACL rights (but invite rights!) implicate FREEBUSY rights (at least READ has to include FREEBUSY)
1327		if ($grant & ~self::ACL_INVITE) $grant |= self::ACL_FREEBUSY;
1328
1329		if (is_array($event) && ($needed == Acl::READ || $needed == self::ACL_FREEBUSY))
1330		{
1331			// Check if the $user is one of the participants or has a read-grant from one of them
1332			// in that case he has an implicite READ grant for that event
1333			//
1334			if ($event['participants'] && is_array($event['participants']))
1335			{
1336				foreach(array_keys($event['participants']) as $uid)
1337				{
1338					if ($uid == $user || $uid < 0 && in_array($user, (array)$GLOBALS['egw']->accounts->members($uid,true)))
1339					{
1340						// if we are a participant, we have an implicite FREEBUSY, READ and PRIVAT grant
1341						$grant |= self::ACL_FREEBUSY | Acl::READ | Acl::PRIVAT;
1342						break;
1343					}
1344					elseif ($grants[$uid] & Acl::READ)
1345					{
1346						// if we have a READ grant from a participant, we dont give an implicit privat grant too
1347						$grant |= self::ACL_FREEBUSY | Acl::READ;
1348						// we cant break here, as we might be a participant too, and would miss the privat grant
1349					}
1350					elseif (!is_numeric($uid))
1351					{
1352						// if the owner only grants self::ACL_FREEBUSY we are not interested in the recources explicit rights
1353						if ($grant == self::ACL_FREEBUSY) continue;
1354						// if we have a resource as participant
1355						$resource = $this->resource_info($uid);
1356						$grant |= $resource['rights'];
1357					}
1358				}
1359			}
1360		}
1361		if ($GLOBALS['egw']->accounts->get_type($owner) == 'g' && $needed == Acl::ADD)
1362		{
1363			$access = False;	// a group can't be the owner of an event
1364		}
1365		else
1366		{
1367			$access = $user == $owner || $grant & $needed
1368				&& ($needed == self::ACL_FREEBUSY || !$private || $grant & Acl::PRIVAT);
1369		}
1370		// do NOT allow users to purge deleted events, if we dont have 'userpurge' enabled
1371		if ($access && $needed == Acl::DELETE && $event['deleted'] &&
1372			!$GLOBALS['egw_info']['user']['apps']['admin'] &&
1373			$GLOBALS['egw_info']['server']['calendar_delete_history'] != 'userpurge')
1374		{
1375			$access = false;
1376		}
1377		if ($this->debug && ($this->debug > 2 || $this->debug == 'check_perms'))
1378		{
1379			$this->debug_message('calendar_bo::check_perms(%1,%2,other=%3,%4,%5,user=%6)=%7',True,ACL_TYPE_IDENTIFER.$needed,$event,$other,$date_format,$date_to_read,$user,$access);
1380		}
1381		//error_log(__METHOD__."($needed,".array2string($event).",$other,...,$user) returning ".array2string($access));
1382		return $access;
1383	}
1384
1385	/**
1386	 * Converts several date-types to a timestamp and optionally converts user- to server-time
1387	 *
1388	 * @param mixed $date date to convert, should be one of the following types
1389	 *	string (!) in form YYYYMMDD or iso8601 YYYY-MM-DDThh:mm:ss or YYYYMMDDThhmmss
1390	 *	int already a timestamp
1391	 *	array with keys 'second', 'minute', 'hour', 'day' or 'mday' (depricated !), 'month' and 'year'
1392	 * @param boolean $user2server =False conversion between user- and server-time; default False == Off
1393	 */
1394	static function date2ts($date,$user2server=False)
1395	{
1396		return $user2server ? Api\DateTime::user2server($date,'ts') : Api\DateTime::to($date,'ts');
1397	}
1398
1399	/**
1400	 * Converts a date to an array and optionally converts server- to user-time
1401	 *
1402	 * @param mixed $date date to convert
1403	 * @param boolean $server2user conversation between user- and server-time default False == Off
1404	 * @return array with keys 'second', 'minute', 'hour', 'day', 'month', 'year', 'raw' (timestamp) and 'full' (Ymd-string)
1405	 */
1406	static function date2array($date,$server2user=False)
1407	{
1408		return $server2user ? Api\DateTime::server2user($date,'array') : Api\DateTime::to($date,'array');
1409	}
1410
1411	/**
1412	 * Converts a date as timestamp or array to a date-string and optionaly converts server- to user-time
1413	 *
1414	 * @param mixed $date integer timestamp or array with ('year','month',..,'second') to convert
1415	 * @param boolean $server2user conversation between user- and server-time default False == Off, not used if $format ends with \Z
1416	 * @param string $format ='Ymd' format of the date to return, eg. 'Y-m-d\TH:i:sO' (2005-11-01T15:30:00+0100)
1417	 * @return string date formatted according to $format
1418	 */
1419	static function date2string($date,$server2user=False,$format='Ymd')
1420	{
1421		return $server2user ? Api\DateTime::server2user($date,$format) : Api\DateTime::to($date,$format);
1422	}
1423
1424	/**
1425	 * Formats a date given as timestamp or array
1426	 *
1427	 * @param mixed $date integer timestamp or array with ('year','month',..,'second') to convert
1428	 * @param string|boolean $format ='' default common_prefs[dateformat], common_prefs[timeformat], false=time only, true=date only
1429	 * @return string the formated date (incl. time)
1430	 */
1431	static function format_date($date,$format='')
1432	{
1433		return Api\DateTime::to($date,$format);
1434	}
1435
1436	/**
1437	 * Gives out a debug-message with certain parameters
1438	 *
1439	 * All permanent debug-messages in the calendar should be done by this function !!!
1440	 *	(In future they may be logged or sent as xmlrpc-faults back.)
1441	 *
1442	 * Permanent debug-message need to make sure NOT to give secret information like passwords !!!
1443	 *
1444	 * This function do NOT honor the setting of the debug variable, you may use it like
1445	 * if ($this->debug > N) $this->debug_message('Error ;-)');
1446	 *
1447	 * The parameters get formated depending on their type. ACL-values need a ACL_TYPE_IDENTIFER prefix.
1448	 *
1449	 * @param string $msg message with parameters/variables like lang(), eg. '%1'
1450	 * @param boolean $backtrace =True include a function-backtrace, default True=On
1451	 *	should only be set to False=Off, if your code ensures a call with backtrace=On was made before !!!
1452	 * @param mixed $param a variable number of parameters, to be inserted in $msg
1453	 *	arrays get serialized with print_r() !
1454	 */
1455	static function debug_message($msg,$backtrace=True)
1456	{
1457		static $acl2string = array(
1458			0               => 'ACL-UNKNOWN',
1459			Acl::READ    => 'ACL_READ',
1460			Acl::ADD     => 'ACL_ADD',
1461			Acl::EDIT    => 'ACL_EDIT',
1462			Acl::DELETE  => 'ACL_DELETE',
1463			Acl::PRIVAT => 'ACL_PRIVATE',
1464			self::ACL_FREEBUSY => 'ACL_FREEBUSY',
1465		);
1466		for($i = 2; $i < func_num_args(); ++$i)
1467		{
1468			$param = func_get_arg($i);
1469
1470			if (is_null($param))
1471			{
1472				$param='NULL';
1473			}
1474			else
1475			{
1476				switch(gettype($param))
1477				{
1478					case 'string':
1479						if (substr($param,0,strlen(ACL_TYPE_IDENTIFER))== ACL_TYPE_IDENTIFER)
1480						{
1481							$param = (int) substr($param,strlen(ACL_TYPE_IDENTIFER));
1482							$param = (isset($acl2string[$param]) ? $acl2string[$param] : $acl2string[0])." ($param)";
1483						}
1484						else
1485						{
1486							$param = "'$param'";
1487						}
1488						break;
1489					case 'EGroupware\\Api\\DateTime':
1490					case 'egw_time':
1491					case 'datetime':
1492						$p = $param;
1493						unset($param);
1494						$param = $p->format('l, Y-m-d H:i:s').' ('.$p->getTimeZone()->getName().')';
1495						break;
1496					case 'array':
1497					case 'object':
1498						$param = array2string($param);
1499						break;
1500					case 'boolean':
1501						$param = $param ? 'True' : 'False';
1502						break;
1503					case 'integer':
1504						if ($param >= mktime(0,0,0,1,1,2000)) $param = adodb_date('Y-m-d H:i:s',$param)." ($param)";
1505						break;
1506				}
1507			}
1508			$msg = str_replace('%'.($i-1),$param,$msg);
1509		}
1510		error_log($msg);
1511		if ($backtrace) error_log(function_backtrace(1));
1512	}
1513
1514	/**
1515	 * Formats one or two dates (range) as long date (full monthname), optionaly with a time
1516	 *
1517	 * @param mixed $_first first date
1518	 * @param mixed $last =0 last date if != 0 (default)
1519	 * @param boolean $display_time =false should a time be displayed too
1520	 * @param boolean $display_day =false should a day-name prefix the date, eg. monday June 20, 2006
1521	 * @return string with formated date
1522	 */
1523	function long_date($_first,$last=0,$display_time=false,$display_day=false)
1524	{
1525		$first = $this->date2array($_first);
1526		if ($last)
1527		{
1528			$last = $this->date2array($last);
1529		}
1530		$datefmt = $this->common_prefs['dateformat'];
1531		$timefmt = $this->common_prefs['timeformat'] == 12 ? 'h:i a' : 'H:i';
1532
1533		$month_before_day = strtolower($datefmt[0]) == 'm' ||
1534			strtolower($datefmt[2]) == 'm' && $datefmt[4] == 'd';
1535
1536		if ($display_day)
1537		{
1538			$range = lang(adodb_date('l',$first['raw'])).($this->common_prefs['dateformat'][0] != 'd' ? ' ' : ', ');
1539		}
1540		for ($i = 0; $i < 5; $i += 2)
1541		{
1542			switch($datefmt[$i])
1543			{
1544				case 'd':
1545					$range .= $first['day'] . ($datefmt[1] == '.' ? '.' : '');
1546					if ($first['month'] != $last['month'] || $first['year'] != $last['year'])
1547					{
1548						if (!$month_before_day)
1549						{
1550							$range .= ' '.lang(strftime('%B',$first['raw']));
1551						}
1552						if ($first['year'] != $last['year'] && $datefmt[0] != 'Y')
1553						{
1554							$range .= ($datefmt[0] != 'd' ? ', ' : ' ') . $first['year'];
1555						}
1556						if ($display_time)
1557						{
1558							$range .= ' '.adodb_date($timefmt,$first['raw']);
1559						}
1560						if (!$last)
1561						{
1562							return $range;
1563						}
1564						$range .= ' - ';
1565
1566						if ($first['year'] != $last['year'] && $datefmt[0] == 'Y')
1567						{
1568							$range .= $last['year'] . ', ';
1569						}
1570
1571						if ($month_before_day)
1572						{
1573							$range .= lang(strftime('%B',$last['raw']));
1574						}
1575					}
1576					else
1577					{
1578						if ($display_time)
1579						{
1580							$range .= ' '.adodb_date($timefmt,$first['raw']);
1581						}
1582						$range .= ' - ';
1583					}
1584					$range .= ' ' . $last['day'] . ($datefmt[1] == '.' ? '.' : '');
1585					break;
1586				case 'm':
1587				case 'M':
1588					$range .= ' '.lang(strftime('%B',$month_before_day ? $first['raw'] : $last['raw'])) . ' ';
1589					break;
1590				case 'Y':
1591					if ($datefmt[0] != 'm')
1592					{
1593						$range .= ' ' . ($datefmt[0] == 'Y' ? $first['year'].($datefmt[2] == 'd' ? ', ' : ' ') : $last['year'].' ');
1594					}
1595					break;
1596			}
1597		}
1598		if ($display_time && $last)
1599		{
1600			$range .= ' '.adodb_date($timefmt,$last['raw']);
1601		}
1602		if ($datefmt[4] == 'Y' && $datefmt[0] == 'm')
1603		{
1604			$range .= ', ' . $last['year'];
1605		}
1606		return $range;
1607	}
1608
1609	/**
1610	 * Displays a timespan, eg. $both ? "10:00 - 13:00: 3h" (10:00 am - 1 pm: 3h) : "10:00 3h" (10:00 am 3h)
1611	 *
1612	 * @param int $start_m start time in minutes since 0h
1613	 * @param int $end_m end time in minutes since 0h
1614	 * @param boolean $both =false display the end-time too, duration is always displayed
1615	 */
1616	function timespan($start_m,$end_m,$both=false)
1617	{
1618		$duration = $end_m - $start_m;
1619		if ($end_m == 24*60-1) ++$duration;
1620		$duration = floor($duration/60).lang('h').($duration%60 ? $duration%60 : '');
1621
1622		$timespan = $t = Api\DateTime::to('20000101T'.sprintf('%02d',$start_m/60).sprintf('%02d',$start_m%60).'00', false);
1623
1624		if ($both)	// end-time too
1625		{
1626			$timespan .= ' - '.Api\DateTime::to('20000101T'.sprintf('%02d',$end_m/60).sprintf('%02d',$end_m%60).'00', false);
1627			// dont double am/pm if they are the same in both times
1628			if ($this->common_prefs['timeformat'] == 12 && substr($timespan,-2) == substr($t,-2))
1629			{
1630				$timespan = str_replace($t,substr($t,0,-3),$timespan);
1631			}
1632			$timespan .= ':';
1633		}
1634		return $timespan . ' ' . $duration;
1635	}
1636
1637	/**
1638	* Converts a participant into a (readable) user- or resource-name
1639	*
1640	* @param string|int $id id of user or resource
1641	* @param string|boolean $use_type =false type-letter or false
1642	* @param boolean $append_email =false append email (Name <email>)
1643	* @return string with name
1644	*/
1645	function participant_name($id,$use_type=false, $append_email=false)
1646	{
1647		static $id2lid = array();
1648		static $id2email = array();
1649
1650		if ($use_type && $use_type != 'u') $id = $use_type.$id;
1651
1652		if (!isset($id2lid[$id]))
1653		{
1654			if (!is_numeric($id))
1655			{
1656				$id2lid[$id] = '#'.$id;
1657				if (($info = $this->resource_info($id)))
1658				{
1659					$id2lid[$id] = $info['name'] ? $info['name'] : $info['email'];
1660					if ($info['name']) $id2email[$id] = $info['email'];
1661				}
1662			}
1663			else
1664			{
1665				$id2lid[$id] = Api\Accounts::username($id);
1666				$id2email[$id] = $GLOBALS['egw']->accounts->id2name($id,'account_email');
1667			}
1668		}
1669		return $id2lid[$id].(($append_email || $id[0] == 'e') && $id2email[$id] ? ' <'.$id2email[$id].'>' : '');
1670	}
1671
1672	/**
1673	* Converts participants array of an event into array of (readable) participant-names with status
1674	*
1675	* @param array $event event-data
1676	* @param boolean $long_status =false should the long/verbose status or an icon be use
1677	* @param boolean $show_group_invitation =false show group-invitations (status == 'G') or not (default)
1678	* @return array with id / names with status pairs
1679	*/
1680	function participants($event,$long_status=false,$show_group_invitation=false)
1681	{
1682		//error_log(__METHOD__.__LINE__.array2string($event['participants']));
1683		$names = array();
1684		foreach((array)$event['participants'] as $id => $status)
1685		{
1686			if (!is_string($status)) continue;
1687			$quantity = $role = null;
1688			calendar_so::split_status($status,$quantity,$role);
1689
1690			if ($status == 'G' && !$show_group_invitation) continue;	// dont show group-invitation
1691
1692			$lang_status = lang($this->verbose_status[$status]);
1693			if (!$long_status)
1694			{
1695				switch($status[0])
1696				{
1697					case 'A':	// accepted
1698						$status = Api\Html::image('calendar','accepted',$lang_status);
1699						break;
1700					case 'R':	// rejected
1701						$status = Api\Html::image('calendar','rejected',$lang_status);
1702						break;
1703					case 'T':	// tentative
1704						$status = Api\Html::image('calendar','tentative',$lang_status);
1705						break;
1706					case 'U':	// no response = unknown
1707						$status = Api\Html::image('calendar','needs-action',$lang_status);
1708						break;
1709					case 'D':	// delegated
1710						$status = Api\Html::image('calendar','forward',$lang_status);
1711						break;
1712					case 'G':	// group invitation
1713						// Todo: Image, seems not to be used
1714						$status = '('.$lang_status.')';
1715						break;
1716				}
1717			}
1718			else
1719			{
1720				$status = '('.$lang_status.')';
1721			}
1722			$names[$id] = Api\Html::htmlspecialchars($this->participant_name($id)).($quantity > 1 ? ' ('.$quantity.')' : '').' '.$status;
1723
1724			// add role, if not a regular participant
1725			if ($role != 'REQ-PARTICIPANT')
1726			{
1727				if (isset($this->roles[$role]))
1728				{
1729					$role = lang($this->roles[$role]);
1730				}
1731				// allow to use cats as roles (beside regular iCal ones)
1732				elseif (substr($role,0,6) == 'X-CAT-' && ($cat_id = (int)substr($role,6)) > 0)
1733				{
1734					$role = $GLOBALS['egw']->categories->id2name($cat_id);
1735				}
1736				else
1737				{
1738					$role = lang(str_replace('X-','',$role));
1739				}
1740				$names[$id] .= ' '.$role;
1741			}
1742		}
1743		natcasesort($names);
1744
1745		return $names;
1746	}
1747
1748	/**
1749	* Converts category string of an event into array of (readable) category-names
1750	*
1751	* @param string $category cat-id (multiple id's commaseparated)
1752	* @param int $color color of the category, if multiple cats, the color of the last one with color is returned
1753	* @return array with id / names
1754	*/
1755	function categories($category,&$color)
1756	{
1757		static $id2cat = array();
1758		$cats = array();
1759		$color = 0;
1760
1761		foreach(explode(',',$category) as $cat_id)
1762		{
1763			if (!$cat_id) continue;
1764
1765			if (!isset($id2cat[$cat_id]))
1766			{
1767				$id2cat[$cat_id] = Api\Categories::read($cat_id);
1768			}
1769			$cat = $id2cat[$cat_id];
1770
1771			$parts = null;
1772			if (is_array($cat['data']) && !empty($cat['data']['color']))
1773			{
1774				$color = $cat['data']['color'];
1775			}
1776			elseif(preg_match('/(#[0-9A-Fa-f]{6})/', $cat['description'], $parts))
1777			{
1778				$color = $parts[1];
1779			}
1780			$cats[$cat_id] = stripslashes($cat['name']);
1781		}
1782		return $cats;
1783	}
1784
1785	/**
1786	 *  This is called only by list_cals().  It was moved here to remove fatal error in php5 beta4
1787	 */
1788	private static function _list_cals_add($id,&$users,&$groups)
1789	{
1790		$name = Api\Accounts::username($id);
1791		if (!($egw_name = $GLOBALS['egw']->accounts->id2name($id)))
1792		{
1793			return;	// do not return no longer existing accounts which eg. still mentioned in acl
1794		}
1795		if (($type = $GLOBALS['egw']->accounts->get_type($id)) == 'g')
1796		{
1797			$arr = &$groups;
1798		}
1799		else
1800		{
1801			$arr = &$users;
1802		}
1803		$arr[$id] = array(
1804			'grantor' => $id,
1805			'value'   => ($type == 'g' ? 'g_' : '') . $id,
1806			'name'    => $name,
1807			'sname'	  => $egw_name
1808		);
1809	}
1810
1811	/**
1812	 * generate list of user- / group-calendars for the selectbox in the header
1813	 *
1814	 * @return array alphabeticaly sorted array with users first and then groups: array('grantor'=>$id,'value'=>['g_'.]$id,'name'=>$name)
1815	 */
1816	function list_cals()
1817	{
1818		return self::list_calendars($GLOBALS['egw_info']['user']['account_id'], $this->grants);
1819	}
1820
1821	/**
1822	 * generate list of user- / group-calendars or a given user
1823	 *
1824	 * @param int $user account_id of user to generate list for
1825	 * @param array $grants =null calendar grants from user, or null to query them from acl class
1826	 */
1827	public static function list_calendars($user, array $grants=null)
1828	{
1829		if (is_null($grants)) $grants = $GLOBALS['egw']->acl->get_grants('calendar', true, $user);
1830
1831		$users = $groups = array();
1832		foreach(array_keys($grants) as $id)
1833		{
1834			self::_list_cals_add($id,$users,$groups);
1835		}
1836		if (($memberships = $GLOBALS['egw']->accounts->memberships($user, true)))
1837		{
1838			foreach($memberships as $group)
1839			{
1840				self::_list_cals_add($group,$users,$groups);
1841
1842				if (($account_perms = $GLOBALS['egw']->acl->get_ids_for_location($group,Acl::READ,'calendar')))
1843				{
1844					foreach($account_perms as $id)
1845					{
1846						self::_list_cals_add($id,$users,$groups);
1847					}
1848				}
1849			}
1850		}
1851		usort($users, array(__CLASS__, 'name_cmp'));
1852		usort($groups, array(__CLASS__, 'name_cmp'));
1853
1854		return array_merge($users, $groups);	// users first and then groups, both alphabeticaly
1855	}
1856
1857	/**
1858	 * Compare function for sort by value of key 'name'
1859	 *
1860	 * @param array $a
1861	 * @param array $b
1862	 * @return int
1863	 */
1864	public static function name_cmp(array $a, array $b)
1865	{
1866		return strnatcasecmp($a['name'], $b['name']);
1867	}
1868
1869	/**
1870	 * Convert the recurrence-information of an event, into a human readable string
1871	 *
1872	 * @param array $event
1873	 * @return string
1874	 */
1875	function recure2string($event)
1876	{
1877		if (!is_array($event)) return false;
1878		return (string)calendar_rrule::event2rrule($event);
1879	}
1880
1881	/**
1882	 * Read the holidays for a given $year
1883	 *
1884	 * The holidays get cached in the session (performance), so changes in holidays or birthdays do NOT affect a current session!!!
1885	 *
1886	 * @param int $year =0 year, defaults to 0 = current year
1887	 * @return array indexed with Ymd of array of holidays. A holiday is an array with the following fields:
1888	 *	name: string
1889	 *  title: optional string with description
1890	 *	day: numerical day in month
1891	 *	month: numerical month
1892	 *	occurence: numerical year or 0 for every year
1893	 */
1894	function read_holidays($year=0)
1895	{
1896		if (!$year) $year = (int) date('Y',$this->now_su);
1897
1898		$holidays = calendar_holidays::read(
1899				!empty($GLOBALS['egw_info']['server']['ical_holiday_url']) ?
1900				$GLOBALS['egw_info']['server']['ical_holiday_url'] :
1901				$GLOBALS['egw_info']['user']['preferences']['common']['country'], $year);
1902
1903		// search for birthdays
1904		if ($GLOBALS['egw_info']['server']['hide_birthdays'] != 'yes')
1905		{
1906			$contacts = new Api\Contacts();
1907			foreach($contacts->get_addressbooks() as $owner => $name)
1908			{
1909				$birthdays = $contacts->read_birthdays($owner, $year);
1910
1911				// Add them in, being careful not to override any existing
1912				foreach($birthdays as $date => $bdays)
1913				{
1914					if(!array_key_exists($date, $holidays))
1915					{
1916						$holidays[$date] = array();
1917					}
1918					foreach($bdays as $birthday)
1919					{
1920						// Skip if name / date are already there - duplicate contacts
1921						if(in_array($birthday['name'], array_column($holidays[$date], 'name'))) continue;
1922						$holidays[$date][] = $birthday;
1923					}
1924				}
1925			}
1926		}
1927
1928		if ((int) $this->debug >= 2 || $this->debug == 'read_holidays')
1929		{
1930			$this->debug_message('calendar_bo::read_holidays(%1)=%2',true,$year,$holidays);
1931		}
1932		return $holidays;
1933	}
1934
1935	/**
1936	 * Get translated calendar event fields, presenting as link title options
1937	 *
1938	 * @param type $event
1939	 * @return array array of selected calendar fields
1940	 */
1941	public static function get_link_options ($event = array())
1942	{
1943		unset($event);	// not used, but required by function signature
1944		$options = array (
1945			'end' => lang('End date'),
1946			'id' => lang('ID'),
1947			'owner' => lang('Owner'),
1948			'category' => lang('Category'),
1949			'location' => lang('Location'),
1950			'creator' => lang('Creator'),
1951			'participants' => lang('Participants')
1952		);
1953		return $options;
1954	}
1955
1956	/**
1957	 * get title for an event identified by $event
1958	 *
1959	 * Is called as hook to participate in the linking
1960	 *
1961	 * @param int|array $entry int cal_id or array with event
1962	 * @param string|boolean string with title, null if not found or false if not read perms
1963	 */
1964	function link_title($event)
1965	{
1966		if (!is_array($event) && strpos($event, '-') !== false)
1967		{
1968			list($id, $recur) = explode('-', $event, 2);
1969			$event = $this->read($id, $recur);
1970		}
1971		else if (!is_array($event) && (int) $event > 0)
1972		{
1973			$event = $this->read($event);
1974		}
1975		if (!is_array($event))
1976		{
1977			return $event;
1978		}
1979		$type = explode(',',$this->cal_prefs['link_title']);
1980		if (is_array($type))
1981		{
1982			foreach ($type as &$val)
1983			{
1984				switch ($val)
1985				{
1986					case 'end':
1987					case 'modified':
1988						$extra_fields [$val] = $this->format_date($event[$val]);
1989						break;
1990					case 'participants':
1991						foreach (array_keys($event[$val]) as $key)
1992						{
1993							$extra_fields [$val] = Api\Accounts::id2name($key, 'account_fullname');
1994						}
1995						break;
1996					case 'modifier':
1997					case 'creator':
1998					case 'owner':
1999						$extra_fields [$val] = Api\Accounts::id2name($event[$val], 'account_fullname');
2000						break;
2001					case 'category':
2002						$extra_fields [$val] = Api\Categories::id2name($event[$val]);
2003						break;
2004					default:
2005						$extra_fields [] = $event[$val];
2006				}
2007			}
2008			$str_fields = implode(', ',$extra_fields);
2009			if (is_array($extra_fields)) return $this->format_date($event['start']) . ': ' . $event['title'] . ($str_fields? ', ' . $str_fields:'');
2010		}
2011		return $this->format_date($event['start']) . ': ' . $event['title'];
2012	}
2013
2014	/**
2015	 * query calendar for events matching $pattern
2016	 *
2017	 * Is called as hook to participate in the linking
2018	 *
2019	 * @param string $pattern pattern to search
2020	 * @return array with cal_id - title pairs of the matching entries
2021	 */
2022	function link_query($pattern, Array &$options = array())
2023	{
2024		$result = array();
2025		$query = array(
2026			'query'	=>	$pattern,
2027			'offset' =>	$options['start'],
2028			'order' => 'cal_start DESC',
2029		);
2030		if($options['num_rows']) {
2031			$query['num_rows'] = $options['num_rows'];
2032		}
2033		foreach((array) $this->search($query) as $event)
2034		{
2035			$result[$event['id']] = $this->link_title($event);
2036		}
2037		$options['total'] = $this->total;
2038		return $result;
2039	}
2040
2041	/**
2042	 * Check access to the file store
2043	 *
2044	 * @param int $id id of entry
2045	 * @param int $check Acl::READ for read and Acl::EDIT for write or delete access
2046	 * @param string $rel_path =null currently not used in calendar
2047	 * @param int $user =null for which user to check, default current user
2048	 * @return boolean true if access is granted or false otherwise
2049	 */
2050	function file_access($id,$check,$rel_path,$user=null)
2051	{
2052		unset($rel_path);	// not used, but required by function signature
2053
2054		return $this->check_perms($check,$id,0,'ts',null,$user);
2055	}
2056
2057	/**
2058	 * sets the default prefs, if they are not already set (on a per pref. basis)
2059	 *
2060	 * It sets a flag in the app-session-data to be called only once per session
2061	 */
2062	function check_set_default_prefs()
2063	{
2064		if ($this->cal_prefs['interval'] && ($set = Api\Cache::getSession('calendar', 'default_prefs_set')))
2065		{
2066			return;
2067		}
2068		Api\Cache::setSession('calendar', 'default_prefs_set', 'set');
2069
2070		$default_prefs =& $GLOBALS['egw']->preferences->default['calendar'];
2071		$forced_prefs  =& $GLOBALS['egw']->preferences->forced['calendar'];
2072
2073		$subject = lang('Calendar Event') . ' - $$action$$: $$startdate$$ $$title$$'."\n";
2074		$values = array(
2075			'notifyAdded'     => $subject . lang ('You have a meeting scheduled for %1','$$startdate$$'),
2076			'notifyCanceled'  => $subject . lang ('Your meeting scheduled for %1 has been canceled','$$startdate$$'),
2077			'notifyModified'  => $subject . lang ('Your meeting that had been scheduled for %1 has been rescheduled to %2','$$olddate$$','$$startdate$$'),
2078			'notifyDisinvited'=> $subject . lang ('You have been uninvited from the meeting at %1','$$startdate$$'),
2079			'notifyResponse'  => $subject . lang ('On %1 %2 %3 your meeting request for %4','$$date$$','$$fullname$$','$$action$$','$$startdate$$'),
2080			'notifyAlarm'     => lang('Alarm for %1 at %2 in %3','$$title$$','$$startdate$$','$$location$$')."\n".lang ('Here is your requested alarm.'),
2081			'interval'        => 30,
2082		);
2083		foreach($values as $var => $default)
2084		{
2085			$type = substr($var,0,6) == 'notify' ? 'forced' : 'default';
2086
2087			// only set, if neither default nor forced pref exists
2088			if ((!isset($default_prefs[$var]) || (string)$default_prefs[$var] === '') && (!isset($forced_prefs[$var]) || (string)$forced_prefs[$var] === ''))
2089			{
2090				$GLOBALS['egw']->preferences->add('calendar',$var,$default,'default');	// always store default, even if we have a forced too
2091				if ($type == 'forced') $GLOBALS['egw']->preferences->add('calendar',$var,$default,'forced');
2092				$this->cal_prefs[$var] = $default;
2093				$need_save = True;
2094			}
2095		}
2096		if ($need_save)
2097		{
2098			$GLOBALS['egw']->preferences->save_repository(False,'default');
2099			$GLOBALS['egw']->preferences->save_repository(False,'forced');
2100		}
2101	}
2102
2103	/**
2104	 * Get the freebusy URL of a user
2105	 *
2106	 * @param int|string $user account_id or account_lid
2107	 * @param string $pw =null password
2108	 */
2109	static function freebusy_url($user='',$pw=null)
2110	{
2111		if (is_numeric($user)) $user = $GLOBALS['egw']->accounts->id2name($user);
2112
2113		$credentials = '';
2114
2115		if ($pw)
2116		{
2117			$credentials = '&password='.urlencode($pw);
2118		}
2119		elseif ($GLOBALS['egw_info']['user']['preferences']['calendar']['freebusy'] == 2)
2120		{
2121			$credentials = $GLOBALS['egw_info']['user']['account_lid']
2122				. ':' . $GLOBALS['egw_info']['user']['passwd'];
2123			$credentials = '&cred=' . base64_encode($credentials);
2124		}
2125		return Api\Framework::getUrl($GLOBALS['egw_info']['server']['webserver_url']).
2126			'/calendar/freebusy.php/?user='.urlencode($user).$credentials;
2127	}
2128
2129	/**
2130	 * Check if the event is the whole day
2131	 *
2132	 * @param array $event event
2133	 * @return boolean true if whole day event, false othwerwise
2134	 */
2135	public static function isWholeDay($event)
2136	{
2137		// check if the event is the whole day
2138		$start = self::date2array($event['start']);
2139		$end = self::date2array($event['end']);
2140
2141		return !$start['hour'] && !$start['minute'] && $end['hour'] == 23 && $end['minute'] == 59;
2142	}
2143
2144	/**
2145	 * Get the etag for an entry
2146	 *
2147	 * As all update routines (incl. set_status and add/delete alarms) update (series master) modified timestamp,
2148	 * we do NOT need any special handling for series master anymore
2149	 *
2150	 * @param array|int|string $entry array with event or cal_id, or cal_id:recur_date for virtual exceptions
2151	 * @param string &$schedule_tag=null on return schedule-tag (egw_cal.cal_id:egw_cal.cal_etag, no participant modifications!)
2152	 * @return string|boolean string with etag or false
2153	 */
2154	function get_etag($entry, &$schedule_tag=null)
2155	{
2156		if (!is_array($entry))
2157		{
2158			list($id,$recur_date) = explode(':',$entry);
2159			$entry = $this->read($id, $recur_date, true, 'server');
2160		}
2161		$etag = $schedule_tag = $entry['id'].':'.$entry['etag'];
2162		$etag .= ':'.$entry['modified'];
2163
2164		//error_log(__METHOD__ . "($entry[id],$client_share_uid_excpetions) entry=".array2string($entry)." --> etag=$etag");
2165		return $etag;
2166	}
2167
2168	/**
2169	 * Query ctag for calendar
2170	 *
2171	 * @param int|string|array $user integer user-id or array of user-id's to use, defaults to the current user
2172	 * @param string $filter ='owner' all (not rejected), accepted, unknown, tentative, rejected or hideprivate
2173	 * @param boolean $master_only =false only check recurance master (egw_cal_user.recur_date=0)
2174	 * @return integer
2175	 */
2176	public function get_ctag($user, $filter='owner', $master_only=false)
2177	{
2178		if ($this->debug > 1) $startime = microtime(true);
2179
2180		// resolve users to add memberships for users and members for groups
2181		$users = $this->resolve_users($user);
2182		$ctag = $users ? $this->so->get_ctag($users, $filter == 'owner', $master_only) : 0;	// no rights, return 0 as ctag (otherwise we get SQL error!)
2183
2184		if ($this->debug > 1) error_log(__METHOD__. "($user, '$filter', $master_only) = $ctag = ".date('Y-m-d H:i:s',$ctag)." took ".(microtime(true)-$startime)." secs");
2185		return $ctag;
2186	}
2187
2188	/**
2189	 * Hook for infolog  to set some extra data and links
2190	 *
2191	 * @param array $data event-array preset by infolog plus
2192	 * @param int $data[id] cal_id
2193	 * @return array with key => value pairs to set in new event and link_app/link_id arrays
2194	 */
2195	function infolog_set($data)
2196	{
2197		if (!($calendar = $this->read($data['id'])))
2198		{
2199			return array();
2200		}
2201
2202		$content = array(
2203			'info_cat'       => $GLOBALS['egw']->categories->check_list(Acl::READ, $calendar['category']),
2204			'info_priority'  => $calendar['priority'] ,
2205			'info_public'    => $calendar['public'] != 'private',
2206			'info_subject'   => $calendar['title'],
2207			'info_des'       => $calendar['description'],
2208			'info_location'  => $calendar['location'],
2209			'info_startdate' => $calendar['range_start'],
2210			//'info_enddate' => $calendar['range_end'] ? $calendar['range_end'] : $calendar['uid']
2211			'info_contact'   => 'calendar:'.$data['id'],
2212		);
2213
2214		unset($content['id']);
2215		// Add calendar link to infolog entry
2216		$content['link_app'][] = $calendar['info_link']['app'];
2217		$content['link_id'][]  = $calendar['info_link']['id'];
2218		// Copy claendar's links
2219		foreach(Link::get_links('calendar',$calendar['id'],'','link_lastmod DESC',true) as $link)
2220		{
2221			if ($link['app'] != Link::VFS_APPNAME)
2222			{
2223				$content['link_app'][] = $link['app'];
2224				$content['link_id'][]  = $link['id'];
2225			}
2226			if ($link['app'] == 'addressbook')	// prefering contact as primary contact over calendar entry set above
2227			{
2228				$content['info_contact'] = 'addressbook:'.$link['id'];
2229			}
2230		}
2231		// Copy same custom fields
2232		foreach(array_keys(Api\Storage\Customfields::get('infolog')) as $name)
2233		{
2234			if ($this->customfields[$name]) $content['#'.$name] = $calendar['#'.$name];
2235		}
2236		//error_log(__METHOD__.'('.array2string($data).') calendar='.array2string($calendar).' returning '.array2string($content));
2237		return $content;
2238	}
2239
2240	/**
2241	 * Hook for timesheet to set some extra data and links
2242	 *
2243	 * @param array $data
2244	 * @param int $data[id] cal_id:recurrence
2245	 * @return array with key => value pairs to set in new timesheet and link_app/link_id arrays
2246	 */
2247	function timesheet_set($data)
2248	{
2249		$set = array();
2250		list($id,$recurrence) = explode(':',$data['id']);
2251		if ((int)$id && ($event = $this->read($id,$recurrence)))
2252		{
2253			$set['ts_start'] = $event['start'];
2254			$set['ts_title'] = $this->link_title($event);
2255			$set['start_time'] = Api\DateTime::to($event['start'],'H:i');
2256			$set['ts_description'] = $event['description'];
2257			if ($this->isWholeDay($event)) $event['end']++;	// whole day events are 1sec short
2258			$set['ts_duration']	= ($event['end'] - $event['start']) / 60;
2259			$set['ts_quantity'] = ($event['end'] - $event['start']) / 3600;
2260			$set['end_time'] = null;	// unset end-time
2261			$set['cat_id'] = (int)$event['category'];
2262
2263			foreach(Link::get_links('calendar',$id,'','link_lastmod DESC',true) as $link)
2264			{
2265				if ($link['app'] != 'timesheet' && $link['app'] != Link::VFS_APPNAME)
2266				{
2267					$set['link_app'][] = $link['app'];
2268					$set['link_id'][]  = $link['id'];
2269				}
2270			}
2271		}
2272		return $set;
2273	}
2274}
2275