infolog_groupdav::put()   B
last analyzed

Complexity

Conditions 11
Paths 50

Size

Total Lines 50
Code Lines 24

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 11
eloc 24
nc 50
nop 4
dl 0
loc 50
rs 7.3166
c 0
b 0
f 0

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
/**
3
 * EGroupware: CalDAV/CardDAV/GroupDAV access: InfoLog handler
4
 *
5
 * @link http://www.egroupware.org
6
 * @license http://opensource.org/licenses/gpl-license.php GPL - GNU General Public License
7
 * @package infolog
8
 * @subpackage caldav
9
 * @author Ralf Becker <RalfBecker-AT-outdoor-training.de>
10
 * @copyright (c) 2007-16 by Ralf Becker <RalfBecker-AT-outdoor-training.de>
11
 * @version $Id$
12
 */
13
14
use EGroupware\Api;
15
use EGroupware\Api\Acl;
16
17
/**
18
 * EGroupware: CalDAV access: infolog handler
19
 *
20
 * Permanent error_log() calls should use $this->caldav->log($str) instead, to be send to PHP error_log()
21
 * and our request-log (prefixed with "### " after request and response, like exceptions).
22
 */
23
class infolog_groupdav extends Api\CalDAV\Handler
24
{
25
	/**
26
	 * bo class of the application
27
	 *
28
	 * @var infolog_bo
29
	 */
30
	var $bo;
31
32
	/**
33
	 * vCalendar Instance for parsing
34
	 *
35
	 * @var array
36
	 */
37
	var $vCalendar;
38
39
	var $filter_prop2infolog = array(
40
		'SUMMARY'	=> 'info_subject',
41
		'UID'		=> 'info_uid',
42
		'DTSTART'	=> 'info_startdate',
43
		'DUE'		=> 'info_enddate',
44
		'DESCRIPTION'	=> 'info_des',
45
		'STATUS'	=> 'info_status',
46
		'PRIORITY'	=> 'info_priority',
47
		'LOCATION'	=> 'info_location',
48
		'COMPLETED'	=> 'info_datecompleted',
49
		'CREATED'   => 'info_created',
50
	);
51
52
	/**
53
	 * Are we using info_id, info_uid or caldav_name for the path/url
54
	 *
55
	 * Get's set in constructor to 'caldav_name' and self::$path_extension = ''!
56
	 */
57
	static $path_attr = 'info_id';
58
59
	/**
60
	 * Constructor
61
	 *
62
	 * @param string $app 'calendar', 'addressbook' or 'infolog'
63
	 * @param Api\CalDAV $caldav calling class
64
	 */
65
	function __construct($app, Api\CalDAV $caldav)
66
	{
67
		parent::__construct($app, $caldav);
68
69
		$this->bo = new infolog_bo();
70
		$this->vCalendar = new Horde_Icalendar;
0 ignored issues
show
Documentation Bug introduced by
It seems like new Horde_Icalendar() of type Horde_Icalendar is incompatible with the declared type array of property $vCalendar.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
71
72
		// since 1.9.002 we allow clients to specify the URL when creating a new event, as specified by CalDAV
73
		if (version_compare($GLOBALS['egw_info']['apps']['calendar']['version'], '1.9.002', '>='))
74
		{
75
			self::$path_attr = 'caldav_name';
76
			self::$path_extension = '';
77
		}
78
	}
79
80
	/**
81
	 * Create the path for an event
82
	 *
83
	 * @param array|int $info
84
	 * @return string
85
	 */
86
	function get_path($info)
87
	{
88
		if (is_numeric($info) && self::$path_attr == 'info_id')
89
		{
90
			$name = $info;
91
		}
92
		else
93
		{
94
			if (!is_array($info)) $info = $this->bo->read($info);
95
			$name = $info[self::$path_attr];
96
		}
97
		return $name.self::$path_extension;
98
	}
99
100
	/**
101
	 * Get filter-array for infolog_bo::search used by getctag and propfind
102
	 *
103
	 * @param string $path
104
	 * @param int $user account_id
105
	 * @return array
106
	 */
107
	private function get_infolog_filter($path, $user)
108
	{
109
		if (!($infolog_types = $GLOBALS['egw_info']['user']['preferences']['groupdav']['infolog-types']))
110
		{
111
			$infolog_types = 'task';
112
		}
113
		if ($path == '/infolog/')
114
		{
115
			$task_filter= 'own';
116
		}
117
		else
118
		{
119
			if ($user == $GLOBALS['egw_info']['user']['account_id'])
120
			{
121
				$task_filter = 'own';
122
			}
123
			else
124
			{
125
				$task_filter = 'user' . $user;
126
			}
127
		}
128
129
		$ret = array(
130
			'filter'	=> $task_filter,
131
			'info_type' => explode(',', $infolog_types),
132
		);
133
		//error_log(__METHOD__."('$path', $user) returning ".array2string($ret));
134
		return $ret;
135
	}
136
137
	/**
138
	 * Handle propfind in the infolog folder
139
	 *
140
	 * @param string $path
141
	 * @param array &$options
142
	 * @param array &$files
143
	 * @param int $user account_id
144
	 * @return mixed boolean true on success, false on failure or string with http status (eg. '404 Not Found')
145
	 */
146
	function propfind($path,&$options,&$files,$user,$id='')
147
	{
148
		// todo add a filter to limit how far back entries from the past get synced
149
		$filter = $this->get_infolog_filter($path, $user);
150
151
		// process REPORT filters or multiget href's
152
		$nresults = null;
153
		if (($id || $options['root']['name'] != 'propfind') && !$this->_report_filters($options, $filter, $id, $nresults))
154
		{
155
			// return empty collection, as iCal under iOS 5 had problems with returning "404 Not found" status
156
			// when trying to request not supported components, eg. VTODO on a calendar collection
157
			return true;
158
		}
159
		// enable time-range filter for tests via propfind / autoindex
160
		//$filter[] = $sql = $this->_time_range_filter(array('end' => '20001231T000000Z'));
161
162
		if ($id) $path = dirname($path).'/';	// caldav_name get's added anyway in the callback
163
164
		if ($this->debug > 1)
165
		{
166
			error_log(__METHOD__."($path,,,$user,$id) filter=".
167
				array2string($filter));
168
		}
169
170
		// check if we have to return the full calendar data or just the etag's
171
		if (!($filter['calendar_data'] = $options['props'] == 'all' &&
172
			$options['root']['ns'] == Api\CalDAV::CALDAV) && is_array($options['props']))
173
		{
174
			foreach($options['props'] as $prop)
175
			{
176
				if ($prop['name'] == 'calendar-data')
177
				{
178
					$filter['calendar_data'] = true;
179
					break;
180
				}
181
			}
182
		}
183
184
		// rfc 6578 sync-collection report: filter for sync-token is already set in _report_filters
185
		if ($options['root']['name'] == 'sync-collection')
186
		{
187
			// callback to query sync-token, after propfind_callbacks / iterator is run and
188
			// stored max. modification-time in $this->sync_collection_token
189
			$files['sync-token'] = array($this, 'get_sync_collection_token');
190
			$files['sync-token-params'] = array($path, $user);
191
192
			$this->sync_collection_token = null;
193
194
			$filter['order'] = 'info_datemodified ASC';	// return oldest modifications first
195
			$filter['sync-collection'] = true;
196
		}
197
198
		if (isset($nresults))
199
		{
200
			$files['files'] = $this->propfind_callback($path, $filter, array(0, (int)$nresults));
201
202
			// hack to support limit with sync-collection report: contacts are returned in modified ASC order (oldest first)
203
			// if limit is smaller then full result, return modified-1 as sync-token, so client requests next chunk incl. modified
204
			// (which might contain further entries with identical modification time)
205
			if ($options['root']['name'] == 'sync-collection' && $this->bo->total > $nresults)
206
			{
207
				--$this->sync_collection_token;
208
				$files['sync-token-params'][] = true;	// tel get_sync_collection_token that we have more entries
209
			}
210
		}
211
		else
212
		{
213
			// return iterator, calling ourself to return result in chunks
214
			$files['files'] = new Api\CalDAV\PropfindIterator($this,$path,$filter,$files['files']);
215
		}
216
		return true;
217
	}
218
219
	/**
220
	 * Callback for profind interator
221
	 *
222
	 * @param string $path
223
	 * @param array $filter
224
	 * @param array|boolean $start =false false=return all or array(start,num)
225
	 * @return array with "files" array with values for keys path and props
226
	 */
227
	function &propfind_callback($path,array $filter,$start=false)
228
	{
229
		if ($this->debug) $starttime = microtime(true);
230
231
		if (($calendar_data = $filter['calendar_data']))
232
		{
233
			$handler = self::_get_handler();
0 ignored issues
show
Bug Best Practice introduced by
The method infolog_groupdav::_get_handler() is not static, but was called statically. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

233
			/** @scrutinizer ignore-call */ 
234
   $handler = self::_get_handler();
Loading history...
234
		}
235
		unset($filter['calendar_data']);
236
		$task_filter = $filter['filter'];
237
		unset($filter['filter']);
238
239
		$order = 'info_datemodified';
240
		$sort = 'DESC';
241
		$matches = null;
242
		if (preg_match('/^([a-z0-9_]+)( DESC| ASC)?$/i', $filter['order'], $matches))
243
		{
244
			$order = $matches[1];
245
			if ($matches[2]) $sort = $matches[2];
246
			unset($filter['order']);
247
		}
248
		$query = array(
249
			'order'			=> $order,
250
			'sort'			=> $sort,
251
			'filter'    	=> $task_filter,
252
			'date_format'	=> 'server',
253
			'col_filter'	=> $filter,
254
			'custom_fields' => true,	// otherwise custom fields get NOT loaded!
255
		);
256
		$check_responsible = false;
257
		if (substr($task_filter, -8) == '+deleted')
258
		{
259
			$check_responsible = substr($task_filter, 0, 4) == 'user' ?
260
				(int)substr($task_filter, 4) : $GLOBALS['egw_info']['user']['account_id'];
261
		}
262
263
		if (!$calendar_data)
264
		{
265
			$query['cols'] = array('main.info_id AS info_id', 'info_datemodified', 'info_uid', 'caldav_name', 'info_subject', 'info_status', 'info_owner');
266
		}
267
268
		if (is_array($start))
269
		{
270
			$query['start'] = $offset = $start[0];
271
			$query['num_rows'] = $start[1];
272
		}
273
		else
274
		{
275
			$offset = 0;
276
		}
277
278
		$requested_multiget_ids = (array)$filter[self::$path_attr];
279
280
		$files = array();
281
		// ToDo: add parameter to only return id & etag
282
		$tasks =& $this->bo->search($query);
283
		if ($tasks && $offset == $query['start'])
284
		{
285
			foreach($tasks as $task)
286
			{
287
				// remove task from requested multiget ids, to be able to report not found urls
288
				if ($requested_multiget_ids && ($k = array_search($task[self::$path_attr], $requested_multiget_ids)) !== false)
0 ignored issues
show
Bug Best Practice introduced by
The expression $requested_multiget_ids of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
289
				{
290
					unset($requested_multiget_ids[$k]);
291
				}
292
				// sync-collection report: deleted entry need to be reported without properties
293
				if ($task['info_status'] == 'deleted' ||
294
					// or event is reported as removed from collection, because collection owner is no longer an attendee
295
					$check_responsible && $task['info_owner'] != $check_responsible &&
296
						!infolog_so::is_responsible_user($task, $check_responsible))
297
				{
298
					$files[] = array('path' => $path.urldecode($this->get_path($task)));
299
					continue;
300
				}
301
				$props = array(
302
					'getcontenttype' => $this->agent != 'kde' ? 'text/calendar; charset=utf-8; component=VTODO' : 'text/calendar',	// Konqueror (3.5) dont understand it otherwise
303
					'getlastmodified' => $task['info_datemodified'],
304
					'displayname' => $task['info_subject'],
305
				);
306
				if ($calendar_data)
307
				{
308
					$content = $handler->exportVTODO($task, '2.0', null);	// no METHOD:PUBLISH for CalDAV
309
					$props['getcontentlength'] = bytes($content);
310
					$props[] = Api\CalDAV::mkprop(Api\CalDAV::CALDAV,'calendar-data',$content);
311
				}
312
				$files[] = $this->add_resource($path, $task, $props);
313
			}
314
		}
315
		// report not found multiget urls
316
		if ($requested_multiget_ids)
0 ignored issues
show
Bug Best Practice introduced by
The expression $requested_multiget_ids of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
317
		{
318
			foreach($requested_multiget_ids as $id)
319
			{
320
				$files[] = array('path' => $path.$id.self::$path_extension);
321
			}
322
		}
323
		// sync-collection report --> return modified of last contact as sync-token
324
		$sync_collection_report =  $filter['sync-collection'];
325
		if ($sync_collection_report)
326
		{
327
			$this->sync_collection_token = $task['date_modified'];
328
329
			// hack to support limit with sync-collection report: tasks are returned in modified ASC order (oldest first)
330
			// if limit is smaller then full result, return modified-1 as sync-token, so client requests next chunk incl. modified
331
			// (which might contain further entries with identical modification time)
332
			if ($start[0] == 0 && $start[1] != Api\CalDAV\PropfindIterator::CHUNK_SIZE && $this->bo->total > $start[1])
333
			{
334
				--$this->sync_collection_token;
335
			}
336
		}
337
		if ($this->debug) error_log(__METHOD__."($path) took ".(microtime(true) - $starttime).' to return '.count($files).' items');
338
		return $files;
339
	}
340
341
	/**
342
	 * Process the filters from the CalDAV REPORT request
343
	 *
344
	 * @param array $options
345
	 * @param array &$cal_filters
346
	 * @param string $id
347
	 * @param int &$nresult on return limit for number or results or unchanged/null
348
	 * @return boolean true if filter could be processed
349
	 */
350
	function _report_filters($options,&$cal_filters,$id, &$nresults)
351
	{
352
		if ($options['filters'])
353
		{
354
			foreach($options['filters'] as $filter)
355
			{
356
				switch($filter['name'])
357
				{
358
					case 'comp-filter':
359
						if ($this->debug > 1) error_log(__METHOD__."($options[path],...) comp-filter='{$filter['attrs']['name']}'");
360
361
						switch($filter['attrs']['name'])
362
						{
363
							case 'VTODO':
364
							case 'VCALENDAR':
365
								break;
366
							default:
367
								return false;
368
						}
369
						break;
370
					case 'prop-filter':
371
						if ($this->debug > 1) error_log(__METHOD__."($options[path],...) prop-filter='{$filter['attrs']['name']}'");
372
						$prop_filter = $filter['attrs']['name'];
373
						break;
374
					case 'text-match':
375
						if ($this->debug > 1) error_log(__METHOD__."($options[path],...) text-match: $prop_filter='{$filter['data']}'");
376
						if (!isset($this->filter_prop2infolog[strtoupper($prop_filter)]))
377
						{
378
							if ($this->debug) error_log(__METHOD__."($options[path],".array2string($options).",...) unknown property '$prop_filter' --> ignored");
379
						}
380
						else
381
						{
382
							$cal_filters[$this->filter_prop2infolog[strtoupper($prop_filter)]] = $filter['data'];
383
						}
384
						unset($prop_filter);
385
						break;
386
					case 'param-filter':
387
						if ($this->debug) error_log(__METHOD__."($options[path],...) param-filter='{$filter['attrs']['name']}' not (yet) implemented!");
388
						break;
389
					case 'time-range':
390
						$cal_filters[] = $this->_time_range_filter($filter['attrs']);
391
						break;
392
					default:
393
						if ($this->debug) error_log(__METHOD__."($options[path],".array2string($options).",...) unknown filter --> ignored");
394
						break;
395
				}
396
			}
397
		}
398
		// parse limit from $options['other']
399
		/* Example limit
400
		  <B:limit>
401
		    <B:nresults>10</B:nresults>
402
		  </B:limit>
403
		*/
404
		foreach((array)$options['other'] as $option)
405
		{
406
			switch($option['name'])
407
			{
408
				case 'nresults':
409
					$nresults = (int)$option['data'];
410
					//error_log(__METHOD__."(...) options[other]=".array2string($options['other'])." --> nresults=$nresults");
411
					break;
412
				case 'limit':
413
					break;
414
				case 'href':
415
					break;	// from addressbook-multiget, handled below
416
				// rfc 6578 sync-report
417
				case 'sync-token':
418
					if (!empty($option['data']))
419
					{
420
						$parts = explode('/', $option['data']);
421
						$sync_token = array_pop($parts);
422
						$cal_filters[] = 'info_datemodified>'.(int)$sync_token;
423
						$cal_filters['filter'] .= '+deleted';	// to return deleted entries too
424
					}
425
					break;
426
				case 'sync-level':
427
					if ($option['data'] != '1')
428
					{
429
						$this->caldav->log(__METHOD__."(...) only sync-level {$option['data']} requested, but only 1 supported! options[other]=".array2string($options['other']));
430
					}
431
					break;
432
				default:
433
					$this->caldav->log(__METHOD__."(...) unknown xml tag '{$option['name']}': options[other]=".array2string($options['other']));
434
					break;
435
			}
436
		}
437
		// multiget or propfind on a given id
438
		//error_log(__FILE__ . __METHOD__ . "multiget of propfind:");
439
		if ($options['root']['name'] == 'calendar-multiget' || $id)
440
		{
441
			$ids = array();
442
			if ($id)
443
			{
444
				$cal_filters[self::$path_attr] = self::$path_extension ?
445
					basename($id,self::$path_extension) : $id;
446
			}
447
			else	// fetch all given url's
448
			{
449
				foreach($options['other'] as $option)
450
				{
451
					if ($option['name'] == 'href')
452
					{
453
						$parts = explode('/',$option['data']);
454
						if (($id = basename(urldecode(array_pop($parts)))))
455
						{
456
							$cal_filters[self::$path_attr][] = self::$path_extension ?
457
								basename($id,self::$path_extension) : $id;
458
						}
459
					}
460
				}
461
			}
462
			if ($this->debug > 1) error_log(__METHOD__ ."($options[path],...,$id) calendar-multiget: ids=".implode(',',$ids));
463
		}
464
		return true;
465
	}
466
467
	/**
468
	 * Create SQL filter from time-range filter attributes
469
	 *
470
	 * CalDAV time-range for VTODO checks DTSTART, DTEND, DUE, CREATED and allways includes tasks if none given
471
	 * @see http://tools.ietf.org/html/rfc4791#section-9.9
472
	 *
473
	 * @param array $attrs values for keys 'start' and/or 'end', at least one is required by CalDAV rfc!
474
	 * @return string with sql
475
	 */
476
	private function _time_range_filter(array $attrs)
477
	{
478
		$to_or = $to_and = array();
479
 		if (!empty($attrs['start']))
480
 		{
481
 			$start = (int)$this->vCalendar->_parseDateTime($attrs['start']);
482
		}
483
 		if (!empty($attrs['end']))
484
 		{
485
 			$end = (int)$this->vCalendar->_parseDateTime($attrs['end']);
486
		}
487
		elseif (empty($attrs['start']))
488
		{
489
			$this->caldav->log(__METHOD__.'('.array2string($attrs).') minimum one of start or end is required!');
490
			return '1';	// to not give sql error, but simply not filter out anything
491
		}
492
		// we dont need to care for DURATION line in rfc4791#section-9.9, as we always put that in DUE/info_enddate
493
494
		// we have start- and/or enddate
495
		if (isset($start))
496
		{
497
			$to_and[] = "($start < info_enddate OR $start <= info_startdate)";
498
		}
499
		if (isset($end))
500
		{
501
			$to_and[] = "(info_startdate < $end OR info_enddate <= $end)";
502
		}
503
		$to_or[] = '('.implode(' AND ', $to_and).')';
504
505
		/* either start or enddate is already included in the above, because of OR!
506
		// only a startdate, no enddate
507
		$to_or[] = "NOT info_enddate > 0".($start ? " AND $start <= info_startdate" : '').
508
			($end ? " AND info_startdate < $end" : '');
509
510
		// only an enddate, no startdate
511
		$to_or[] = "NOT info_startdate > 0".($start ? " AND $start < info_enddate" : '').
512
			($end ? " AND info_enddate <= $end" : '');*/
513
514
		// no startdate AND no enddate (2. half of rfc4791#section-9.9) --> use created and due dates instead
515
		$to_or[] = 'NOT info_startdate > 0 AND NOT info_enddate > 0 AND ('.
516
			// we have a completed date
517
			"info_datecompleted > 0".(isset($start) ? " AND ($start <= info_datecompleted OR $start <= info_created)" : '').
518
				(isset($end) ? " AND (info_datecompleted <= $end OR info_created <= $end)" : '').' OR '.
519
			// we have no completed date, but always a created date
520
 			"NOT info_datecompleted > 0". (isset($end) ? " AND info_created < $end" : '').
521
		')';
522
		$sql = '('.implode(' OR ', $to_or).')';
523
		if ($this->debug > 1) error_log(__FILE__ . __METHOD__.'('.array2string($attrs).") time-range=$attrs[start]-$attrs[end] --> $sql");
524
		return $sql;
525
	}
526
527
	/**
528
	 * Handle get request for a task / infolog entry
529
	 *
530
	 * @param array &$options
531
	 * @param int $id
532
	 * @param int $user =null account_id
533
	 * @return mixed boolean true on success, false on failure or string with http status (eg. '404 Not Found')
534
	 */
535
	function get(&$options,$id,$user=null)
536
	{
537
		unset($user);	// not used, but required by function signature
538
539
		if (!is_array($task = $this->_common_get_put_delete('GET',$options,$id)))
0 ignored issues
show
introduced by
The condition is_array($task = $this->...('GET', $options, $id)) is always false.
Loading history...
540
		{
541
			return $task;
542
		}
543
		$handler = $this->_get_handler();
544
		$options['data'] = $handler->exportVTODO($task, '2.0', null);	// no METHOD:PUBLISH for CalDAV
545
		$options['mimetype'] = 'text/calendar; charset=utf-8';
546
		header('Content-Encoding: identity');
547
		header('ETag: "'.$this->get_etag($task).'"');
548
		return true;
549
	}
550
551
	/**
552
	 * Handle put request for a task / infolog entry
553
	 *
554
	 * @param array &$options
555
	 * @param int $id
556
	 * @param int $user =null account_id of owner, default null
557
	 * @param string $prefix =null user prefix from path (eg. /ralf from /ralf/addressbook)
558
	 * @return mixed boolean true on success, false on failure or string with http status (eg. '404 Not Found')
559
	 */
560
	function put(&$options,$id,$user=null,$prefix=null)
561
	{
562
		unset($prefix);	// not used, but required by function signature
563
564
		if ($this->debug) error_log(__METHOD__."($id, $user)".print_r($options,true));
565
566
		$oldTask = $this->_common_get_put_delete('PUT',$options,$id);
567
		if (!is_null($oldTask) && !is_array($oldTask))
0 ignored issues
show
introduced by
The condition is_array($oldTask) is always false.
Loading history...
introduced by
The condition is_null($oldTask) is always false.
Loading history...
568
		{
569
			return $oldTask;
570
		}
571
572
		$handler = $this->_get_handler();
573
		$vTodo = htmlspecialchars_decode($options['content']);
574
575
		if (is_array($oldTask))
576
		{
577
			$taskId = $oldTask['info_id'];
578
			$retval = true;
579
		}
580
		else	// new entry
581
		{
582
			$taskId = 0;
583
			$retval = '201 Created';
584
		}
585
		if ($GLOBALS['egw_info']['user']['preferences']['groupdav']['infolog-cat-action'] &&
586
			$GLOBALS['egw_info']['user']['preferences']['groupdav']['infolog-cat-action'] !== 'none')
587
		{
588
			$callback_data = array(array($this, 'cat_action'), $oldTask);
589
		}
590
		if (!($infoId = $handler->importVTODO($vTodo, $taskId, false, $user, null, $id, $callback_data)))
591
		{
592
			if ($this->debug) error_log(__METHOD__."(,$id) import_vtodo($options[content]) returned false");
593
			return '403 Forbidden';
594
		}
595
596
		if ($infoId != $taskId)
597
		{
598
			$retval = '201 Created';
599
		}
600
601
		// send evtl. necessary respose headers: Location, etag, ...
602
		// but only for new entries, as X-INFOLOG-STATUS get's not updated on client, if we confirm with an etag
603
		if ($retval !== true)
604
			// POST with add-member query parameter
605
			//$_SERVER['REQUEST_METHOD'] == 'POST' && isset($_GET['add-member'])))
606
		{
607
			$this->put_response_headers($infoId, $options['path'], $retval, self::$path_attr == 'caldav_name');
608
		}
609
		return $retval;
610
	}
611
612
	/**
613
	 * Update etag, ctag and sync-token to reflect changed attachments
614
	 *
615
	 * @param array|string|int $entry array with entry data from read, or id
616
	 */
617
	public function update_tags($entry)
618
	{
619
		if (!is_array($entry)) $entry = $this->read($entry);
620
621
		$this->bo->write($entry, true);
622
	}
623
624
	/**
625
	 * Callback for infolog_ical::importVTODO to implement infolog-cat-action
626
	 *
627
	 * @param array $task
628
	 * @param array $oldTask =null
629
	 * @return array modified task data
630
	 */
631
	public function cat_action(array $task, $oldTask=null)
632
	{
633
		$action = $GLOBALS['egw_info']['user']['preferences']['groupdav']['infolog-cat-action'];
634
635
		//error_log(__METHOD__.'('.array2string($task).', '.array2string($oldTask).") action=$action");
636
		if ($task['info_cat'] && ($new_cat = Api\Categories::id2name($task['info_cat'])) &&
637
			strpos($new_cat, '@') !== false)
638
		{
639
			$new_user = $GLOBALS['egw']->accounts->name2id($new_cat, 'account_email');
640
		}
641
		$old_responsible = $task['info_responsible'];
642
		// no action taken, if cat is not email of user
643
		if ($new_user)
644
		{
645
			// make sure category is global, as otherwise it will not be transmitted to other users
646
			if (!Api\Categories::is_global($task['info_cat']))
647
			{
648
				$cat_obj = new Api\Categories(Api\Categories::GLOBAL_ACCOUNT, 'infolog');
649
				if (($cat = Api\Categories::read($task['info_cat'])))
650
				{
651
					$cat['owner'] = Api\Categories::GLOBAL_ACCOUNT;
652
					$cat['access'] = 'public';
653
					$cat_obj->edit($cat);
654
				}
655
			}
656
			// if replace, remove user of old category from responsible
657
			if ($action == 'replace' && $oldTask && $oldTask['info_cat'] &&
658
				($old_cat = Api\Categories::id2name($oldTask['info_cat'])) && strpos($old_cat, '@') !== false &&
659
				($old_user = $GLOBALS['egw']->accounts->name2id($old_cat, 'account_email')) &&
660
				($key = array_search($old_user, (array)$task['info_responsible'])) !== false)
661
			{
662
				unset($task['info_responsible'][$key]);
663
			}
664
			switch($action)
665
			{
666
				case 'set':
667
					$task['info_responsible'] = array();
668
					// fall through
669
				case 'set-user':
670
					foreach($task['info_responsible'] as $key => $account_id)
671
					{
672
						if ($GLOBALS['egw']->accounts->get_type($account_id) == 'u')
673
						{
674
							unset($task['info_responsible'][$key]);
675
						}
676
					}
677
					// fall-through
678
				case 'add':
679
				case 'replace':
680
					if (!in_array($new_user, (array)$task['info_responsible']))
681
					{
682
						$task['info_responsible'][] = $new_user;
683
					}
684
					break;
685
			}
686
		}
687
		error_log(__METHOD__."() action=$action, new_cat=$new_cat --> new_user=$new_user, old_cat=$old_cat --> old_user=$old_user: responsible: ".array2string($old_responsible).' --> '.array2string($task['info_responsible']));
688
		return $task;
689
	}
690
691
	/**
692
	 * Handle delete request for a task / infolog entry
693
	 *
694
	 * @param array &$options
695
	 * @param int $id
696
	 * @param int $user account_id of collection owner
697
	 * @return mixed boolean true on success, false on failure or string with http status (eg. '404 Not Found')
698
	 */
699
	function delete(&$options,$id,$user)
700
	{
701
		unset($user);	// not used, but required by function signature
702
703
		if (!is_array($task = $this->_common_get_put_delete('DELETE',$options,$id)))
0 ignored issues
show
introduced by
The condition is_array($task = $this->...ELETE', $options, $id)) is always false.
Loading history...
704
		{
705
			return $task;
706
		}
707
		return $this->bo->delete($task['info_id']);
708
	}
709
710
	/**
711
	 * Read an entry
712
	 *
713
	 * We have to make sure to not return or even consider in read deleted infologs, as the might have
714
	 * the same UID and/or caldav_name as not deleted ones and would block access to valid entries
715
	 *
716
	 * @param string|id $id
0 ignored issues
show
Bug introduced by
The type id was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
717
	 * @return array|boolean array with entry, false if no read rights, null if $id does not exist
718
	 */
719
	function read($id)
720
	{
721
		return $this->bo->read(array(self::$path_attr => $id, "info_status!='deleted'"),false,'server');
722
	}
723
724
	/**
725
	 * Get id from entry-array returned by read()
726
	 *
727
	 * Reimplemented because id uses key 'info_id'
728
	 *
729
	 * @param int|string|array $entry
730
	 * @return int|string
731
	 */
732
	function get_id($entry)
733
	{
734
		return is_array($entry) ? $entry['info_id'] : $entry;
735
	}
736
737
	/**
738
	 * Check if user has the neccessary rights on a task / infolog entry
739
	 *
740
	 * @param int $acl Acl::READ, Acl::EDIT or Acl::DELETE
741
	 * @param array|int $task task-array or id
742
	 * @return boolean null if entry does not exist, false if no access, true if access permitted
743
	 */
744
	function check_access($acl,$task)
745
	{
746
		if (is_null($task)) return true;
0 ignored issues
show
introduced by
The condition is_null($task) is always false.
Loading history...
747
748
		$access = $this->bo->check_access($task,$acl);
749
750
		if (!$access && $acl == Acl::EDIT && $this->bo->is_responsible($task))
751
		{
752
			$access = true;	// access limited to $this->bo->responsible_edit fields (handled in infolog_bo::write())
753
		}
754
		if ($this->debug > 1) error_log(__METHOD__."($acl, ".array2string($task).') returning '.array2string($access));
755
		return $access;
756
	}
757
758
	/**
759
	 * Query ctag for infolog
760
	 *
761
	 * @return string
762
	 */
763
	public function getctag($path,$user)
764
	{
765
		return $this->bo->getctag($this->get_infolog_filter($path, $user));
766
	}
767
768
	/**
769
	 * Get the etag for an infolog entry
770
	 *
771
	 * etag currently uses the modifcation time (info_datemodified), 1.9.002 adds etag column, but it's not yet used!
772
	 *
773
	 * @param array|int $info array with infolog entry or info_id
774
	 * @return string|boolean string with etag or false
775
	 */
776
	function get_etag($info)
777
	{
778
		if (!is_array($info))
779
		{
780
			$info = $this->bo->read($info,true,'server');
781
		}
782
		if (!is_array($info) || !isset($info['info_id']) || !isset($info['info_datemodified']))
783
		{
784
			return false;
785
		}
786
		return $info['info_id'].':'.$info['info_datemodified'];
787
	}
788
789
	/**
790
	 * Add extra properties for calendar collections
791
	 *
792
	 * @param array $props =array() regular props by the Api\CalDAV handler
793
	 * @param string $displayname
794
	 * @param string $base_uri =null base url of handler
795
	 * @param int $user =null account_id of owner of collection
796
	 * @return array
797
	 */
798
	public function extra_properties(array $props, $displayname, $base_uri=null,$user=null)
799
	{
800
		unset($base_uri);	// not used, but required by function signature
801
802
		// calendar description
803
		$displayname = Api\Translation::convert(lang('Tasks of'),Api\Translation::charset(),'utf-8').' '.$displayname;
0 ignored issues
show
Bug introduced by
Are you sure EGroupware\Api\Translati...on::charset(), 'utf-8') of type array|null|string can be used in concatenation? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

803
		$displayname = /** @scrutinizer ignore-type */ Api\Translation::convert(lang('Tasks of'),Api\Translation::charset(),'utf-8').' '.$displayname;
Loading history...
804
		$props['calendar-description'] = Api\CalDAV::mkprop(Api\CalDAV::CALDAV,'calendar-description',$displayname);
805
		// supported components, currently only VTODO
806
		$props['supported-calendar-component-set'] = Api\CalDAV::mkprop(Api\CalDAV::CALDAV,'supported-calendar-component-set',array(
807
			Api\CalDAV::mkprop(Api\CalDAV::CALDAV,'comp',array('name' => 'VTODO')),
808
		));
809
		// supported reports
810
		$props['supported-report-set'] = array(
811
			'calendar-query' => Api\CalDAV::mkprop('supported-report',array(
812
				Api\CalDAV::mkprop('report',array(
813
					Api\CalDAV::mkprop(Api\CalDAV::CALDAV,'calendar-query',''))))),
814
			'calendar-multiget' => Api\CalDAV::mkprop('supported-report',array(
815
				Api\CalDAV::mkprop('report',array(
816
					Api\CalDAV::mkprop(Api\CalDAV::CALDAV,'calendar-multiget',''))))),
817
		);
818
		// only advertice rfc 6578 sync-collection report, if "delete-prevention" is switched on (deleted entries get marked deleted but not actualy deleted
819
		$config = Api\Config::read('infolog');
820
		if ($config['history'])
821
		{
822
			$props['supported-report-set']['sync-collection'] = Api\CalDAV::mkprop('supported-report',array(
823
				Api\CalDAV::mkprop('report',array(
824
					Api\CalDAV::mkprop('sync-collection','')))));
825
		}
826
		// get timezone of calendar
827
		if ($this->caldav->prop_requested('calendar-timezone'))
828
		{
829
			$props['calendar-timezone'] = Api\CalDAV::mkprop(Api\CalDAV::CALDAV,'calendar-timezone',
830
				calendar_timezones::user_timezone($user));
831
		}
832
		return $props;
833
	}
834
835
	/**
836
	 * Get the handler and set the supported fields
837
	 *
838
	 * @return infolog_ical
839
	 */
840
	private function _get_handler()
841
	{
842
		$handler = new infolog_ical();
843
		$handler->tzid = false;	//	as we read server-time timestamps (!= null=user-time), exports UTC times
0 ignored issues
show
Documentation Bug introduced by
The property $tzid was declared of type string, but false is of type false. Maybe add a type cast?

This check looks for assignments to scalar types that may be of the wrong type.

To ensure the code behaves as expected, it may be a good idea to add an explicit type cast.

$answer = 42;

$correct = false;

$correct = (bool) $answer;
Loading history...
844
		$handler->setSupportedFields('GroupDAV',$this->agent);
845
846
		return $handler;
847
	}
848
849
	/**
850
	 * Return appliction specific settings
851
	 *
852
	 * @param array $hook_data
853
	 * @return array of array with settings
854
	 */
855
	static function get_settings($hook_data)
856
	{
857
		if (!isset($hook_data['setup']))
858
		{
859
			Api\Translation::add_app('infolog');
860
			$infolog = new infolog_bo();
861
			$types = $infolog->enums['type'];
862
		}
863
		if (!isset($types))
864
		{
865
			$types = array(
866
				'task' => 'Tasks',
867
			);
868
		}
869
		$settings = array();
870
		$settings['infolog-types'] = array(
871
			'type'   => 'multiselect',
872
			'label'  => 'InfoLog types to sync',
873
			'name'   => 'infolog-types',
874
			'help'   => 'Which InfoLog types should be synced with the device, default only tasks.',
875
			'values' => $types,
876
			'default' => 'task',
877
			'xmlrpc' => True,
878
			'admin'  => False,
879
		);
880
		$settings['infolog-cat-action'] = array(
881
			'type'   => 'select',
882
			'label'  => 'Action when category is an EMail address',
883
			'name'   => 'infolog-cat-action',
884
			'help'   => 'Allows to modify responsible users from devices not supporting them, by setting EMail address of a user as category.',
885
			'values' => array(
886
				'none' => lang('none'),
887
				'add' => lang('add user to responsibles'),
888
				'replace' => lang('add user to responsibles, removing evtl. previous category user'),
889
				'set' => lang('set user as only responsible, removing all existing responsibles'),
890
				'set-user' => lang('set user as only responsible user, but keeping groups'),
891
			),
892
			'default' => 'none',
893
			'xmlrpc' => True,
894
			'admin'  => False,
895
		);
896
		return $settings;
897
	}
898
}
899