event.php 37.1 KB
Newer Older
1 2 3
<?php
/**
 * @file include/event.php
4
 * @brief Event related functions.
5 6
 */

7 8
use Sabre\VObject;

9 10
require_once('include/bbcode.php');

11
/**
12
 * @brief Returns an event as HTML.
13 14
 *
 * @param array $ev
15
 * @return string HTML formatted event
16
 */
Friendika's avatar
Friendika committed
17
function format_event_html($ev) {
Friendika's avatar
Friendika committed
18

Friendika's avatar
Friendika committed
19

Friendika's avatar
Friendika committed
20 21 22
	if(! ((is_array($ev)) && count($ev)))
		return '';

redmatrix's avatar
redmatrix committed
23

friendica's avatar
friendica committed
24
	$bd_format = t('l F d, Y \@ g:i A') ; // Friday January 18, 2011 @ 8:01 AM
25

26
	/// @TODO move this to template
Friendika's avatar
Friendika committed
27

Mario's avatar
Mario committed
28
	$o = '<div class="vevent">' . "\r\n";
friendica's avatar
friendica committed
29

30
	$o .= '<div class="event-title"><h3><i class="fa fa-calendar"></i>&nbsp;' . zidify_links(smilies(bbcode($ev['summary']))) .  '</h3></div>' . "\r\n";
Friendika's avatar
Friendika committed
31

Mario's avatar
Mario committed
32
	$o .= '<div class="event-start"><span class="event-label">' . t('Starts:') . '</span>&nbsp;<span class="dtstart" title="'
33
		. datetime_convert('UTC', 'UTC', $ev['dtstart'], (($ev['adjust']) ? ATOM_TIME : 'Y-m-d\TH:i:s' ))
34 35
		. '" >'
		. (($ev['adjust']) ? day_translate(datetime_convert('UTC', date_default_timezone_get(),
36
			$ev['dtstart'] , $bd_format ))
37
			:  day_translate(datetime_convert('UTC', 'UTC',
38
			$ev['dtstart'] , $bd_format)))
Mario's avatar
Mario committed
39
		. '</span></div>' . "\r\n";
Friendika's avatar
Friendika committed
40

Friendika's avatar
Friendika committed
41
	if(! $ev['nofinish'])
Mario's avatar
Mario committed
42
		$o .= '<div class="event-end" ><span class="event-label">' . t('Finishes:') . '</span>&nbsp;<span class="dtend" title="'
43
			. datetime_convert('UTC','UTC',$ev['dtend'], (($ev['adjust']) ? ATOM_TIME : 'Y-m-d\TH:i:s' ))
44 45
			. '" >'
			. (($ev['adjust']) ? day_translate(datetime_convert('UTC', date_default_timezone_get(),
46
				$ev['dtend'] , $bd_format ))
47
				:  day_translate(datetime_convert('UTC', 'UTC',
48
				$ev['dtend'] , $bd_format )))
Mario's avatar
Mario committed
49 50
			. '</span></div>'  . "\r\n";

51
	$o .= '<div class="event-description">' . zidify_links(smilies(bbcode($ev['description']))) .  '</div>' . "\r\n";
Friendika's avatar
Friendika committed
52 53

	if(strlen($ev['location']))
54
		$o .= '<div class="event-location"><span class="event-label"> ' . t('Location:') . '</span>&nbsp;<span class="location">'
55
			. zidify_links(smilies(bbcode($ev['location'])))
Mario's avatar
Mario committed
56
			. '</span></div>' . "\r\n";
Friendika's avatar
Friendika committed
57

58
	$o .= '</div>' . "\r\n";
59

Friendika's avatar
Friendika committed
60 61 62
	return $o;
}

63 64 65 66 67 68 69 70 71 72 73
function format_event_obj($jobject) {
	$event = array();

	$object = json_decode($jobject,true);

	//ensure compatibility with older items - this check can be removed at a later point
	if(array_key_exists('description', $object)) {

		$bd_format = t('l F d, Y \@ g:i A'); // Friday January 18, 2011 @ 8:01 AM

		$event['header'] = replace_macros(get_markup_template('event_item_header.tpl'),array(
74
			'$title'	 => zidify_links(smilies(bbcode($object['title']))),
75 76 77 78 79 80 81 82 83 84
			'$dtstart_label' => t('Starts:'),
			'$dtstart_title' => datetime_convert('UTC', 'UTC', $object['dtstart'], (($object['adjust']) ? ATOM_TIME : 'Y-m-d\TH:i:s' )),
			'$dtstart_dt'	 => (($object['adjust']) ? day_translate(datetime_convert('UTC', date_default_timezone_get(), $object['dtstart'] , $bd_format )) : day_translate(datetime_convert('UTC', 'UTC', $object['dtstart'] , $bd_format))),
			'$finish'	 => (($object['nofinish']) ? false : true),
			'$dtend_label'	 => t('Finishes:'),
			'$dtend_title'	 => datetime_convert('UTC','UTC',$object['dtend'], (($object['adjust']) ? ATOM_TIME : 'Y-m-d\TH:i:s' )),
			'$dtend_dt'	 => (($object['adjust']) ? day_translate(datetime_convert('UTC', date_default_timezone_get(), $object['dtend'] , $bd_format )) :  day_translate(datetime_convert('UTC', 'UTC', $object['dtend'] , $bd_format )))
		));

		$event['content'] = replace_macros(get_markup_template('event_item_content.tpl'),array(
85
			'$description'	  => zidify_links(smilies(bbcode($object['description']))),
86
			'$location_label' => t('Location:'),
87
			'$location'	  => zidify_links(smilies(bbcode($object['location'])))
88 89 90 91 92 93
		));

	}

	return $event;
}
94 95 96 97 98 99 100

function ical_wrapper($ev) {

	if(! ((is_array($ev)) && count($ev)))
		return '';

	$o .= "BEGIN:VCALENDAR";
101 102
	$o .= "\r\nVERSION:2.0";
	$o .= "\r\nMETHOD:PUBLISH";
103
	$o .= "\r\nPRODID:-//" . get_config('system','sitename') . "//" . Zotlabs\Lib\System::get_platform_name() . "//" . strtoupper(App::$language). "\r\n";
104
	if(array_key_exists('dtstart', $ev))
105 106 107 108 109 110
		$o .= format_event_ical($ev);
	else {
		foreach($ev as $e) {
			$o .= format_event_ical($e);
		}
	}
111
	$o .= "\r\nEND:VCALENDAR\r\n";
112 113 114 115 116 117

	return $o;
}

function format_event_ical($ev) {

118
	if($ev['etype'] === 'task')
119 120
		return format_todo_ical($ev);

121 122
	$o = '';

123
	$o .= "\r\nBEGIN:VEVENT";
124

125 126 127
	$o .= "\r\nCREATED:" . datetime_convert('UTC','UTC', $ev['created'],'Ymd\\THis\\Z');
	$o .= "\r\nLAST-MODIFIED:" . datetime_convert('UTC','UTC', $ev['edited'],'Ymd\\THis\\Z');
	$o .= "\r\nDTSTAMP:" . datetime_convert('UTC','UTC', $ev['edited'],'Ymd\\THis\\Z');
128
	if($ev['dtstart'])
129
		$o .= "\r\nDTSTART:" . datetime_convert('UTC','UTC', $ev['dtstart'],'Ymd\\THis' . (($ev['adjust']) ? '\\Z' : ''));
130
	if($ev['dtend'] && ! $ev['nofinish'])
131
		$o .= "\r\nDTEND:" . datetime_convert('UTC','UTC', $ev['dtend'],'Ymd\\THis' . (($ev['adjust']) ? '\\Z' : ''));
132
	if($ev['summary']) {
133
		$o .= "\r\nSUMMARY:" . format_ical_text($ev['summary']);
134 135 136
		$o .= "\r\nX-ZOT-SUMMARY:" . format_ical_sourcetext($ev['summary']);
	}
	if($ev['location']) {
137
		$o .= "\r\nLOCATION:" . format_ical_text($ev['location']);
138 139 140
		$o .= "\r\nX-ZOT-LOCATION:" . format_ical_sourcetext($ev['location']);
	}
	if($ev['description']) {
141
		$o .= "\r\nDESCRIPTION:" . format_ical_text($ev['description']);
142 143
		$o .= "\r\nX-ZOT-DESCRIPTION:" . format_ical_sourcetext($ev['description']);
	}
redmatrix's avatar
redmatrix committed
144 145
	if($ev['event_priority'])
		$o .= "\r\nPRIORITY:" . intval($ev['event_priority']);
146 147
	$o .= "\r\nUID:" . $ev['event_hash'] ;
	$o .= "\r\nEND:VEVENT\r\n";
148

149 150 151 152
	return $o;
}


153 154 155 156
function format_todo_ical($ev) {

	$o = '';

157 158 159 160
	$o .= "\r\nBEGIN:VTODO";
	$o .= "\r\nCREATED:" . datetime_convert('UTC','UTC', $ev['created'],'Ymd\\THis\\Z');
	$o .= "\r\nLAST-MODIFIED:" . datetime_convert('UTC','UTC', $ev['edited'],'Ymd\\THis\\Z');
	$o .= "\r\nDTSTAMP:" . datetime_convert('UTC','UTC', $ev['edited'],'Ymd\\THis\\Z');
161
	if($ev['dtstart'])
162
		$o .= "\r\nDTSTART:" . datetime_convert('UTC','UTC', $ev['dtstart'],'Ymd\\THis' . (($ev['adjust']) ? '\\Z' : ''));
163
	if($ev['dtend'] && ! $ev['nofinish'])
164
		$o .= "\r\nDUE:" . datetime_convert('UTC','UTC', $ev['dtend'],'Ymd\\THis' . (($ev['adjust']) ? '\\Z' : ''));
165
	if($ev['summary']) {
166
		$o .= "\r\nSUMMARY:" . format_ical_text($ev['summary']);
167 168
		$o .= "\r\nX-ZOT-SUMMARY:" . format_ical_sourcetext($ev['summary']);
	}
169
	if($ev['event_status']) {
170
		$o .= "\r\nSTATUS:" . $ev['event_status'];
171
		if($ev['event_status'] === 'COMPLETED')
172
			$o .= "\r\nCOMPLETED:" . datetime_convert('UTC','UTC', $ev['event_status_date'],'Ymd\\THis\\Z');
173 174
	}
	if(intval($ev['event_percent']))
175 176
		$o .= "\r\nPERCENT-COMPLETE:" . $ev['event_percent'];
	if(intval($ev['event_sequence']))
177
		$o .= "\r\nSEQUENCE:" . $ev['event_sequence'];
178
	if($ev['location']) {
179
		$o .= "\r\nLOCATION:" . format_ical_text($ev['location']);
180 181 182
		$o .= "\r\nX-ZOT-LOCATION:" . format_ical_sourcetext($ev['location']);
	}
	if($ev['description']) {
183
		$o .= "\r\nDESCRIPTION:" . format_ical_text($ev['description']);
184 185
		$o .= "\r\nX-ZOT-DESCRIPTION:" . format_ical_sourcetext($ev['description']);
	}
186
	$o .= "\r\nUID:" . $ev['event_hash'] ;
redmatrix's avatar
redmatrix committed
187 188
	if($ev['event_priority'])
		$o .= "\r\nPRIORITY:" . intval($ev['event_priority']);
189
	$o .= "\r\nEND:VTODO\r\n";
190 191 192 193 194

	return $o;
}


195
function format_ical_text($s) {
196

197
	require_once('include/html2plain.php');
198

199 200
	$s = html2plain(bbcode($s));
	$s = str_replace(["\r\n","\n"],["",""],$s);
201

202
	return(wordwrap(str_replace(['\\',',',';'],['\\\\','\\,','\\;'],$s),72,"\r\n ",true));
203 204 205 206
}

function format_ical_sourcetext($s) {
	$s = base64_encode($s);
207

208
	return(wordwrap(str_replace(['\\',',',';'],['\\\\','\\,','\\;'],$s),72,"\r\n ",true));
209 210 211
}


Friendika's avatar
Friendika committed
212
function format_event_bbcode($ev) {
213

Friendika's avatar
Friendika committed
214
	$o = '';
215

Zot's avatar
Zot committed
216 217 218 219
	if($ev['event_vdata']) {
		$o .= '[event]' . $ev['event_vdata'] . '[/event]';
	}

friendica's avatar
friendica committed
220 221 222
	if($ev['summary'])
		$o .= '[event-summary]' . $ev['summary'] . '[/event-summary]';

223 224
	if($ev['description'])
		$o .= '[event-description]' . $ev['description'] . '[/event-description]';
225

226 227
	if($ev['dtstart'])
		$o .= '[event-start]' . $ev['dtstart'] . '[/event-start]';
228

229 230
	if(($ev['dtend']) && (! $ev['nofinish']))
		$o .= '[event-finish]' . $ev['dtend'] . '[/event-finish]';
231

Friendika's avatar
Friendika committed
232 233
	if($ev['location'])
		$o .= '[event-location]' . $ev['location'] . '[/event-location]';
234

235 236 237
	if($ev['event_hash'])
		$o .= '[event-id]' . $ev['event_hash'] . '[/event-id]';

Friendika's avatar
Friendika committed
238 239
	if($ev['adjust'])
		$o .= '[event-adjust]' . $ev['adjust'] . '[/event-adjust]';
240

Friendika's avatar
Friendika committed
241 242 243
	return $o;
}

244

Friendika's avatar
Friendika committed
245 246 247
function bbtovcal($s) {
	$o = '';
	$ev = bbtoevent($s);
248
	if($ev['description'])
Friendika's avatar
Friendika committed
249
		$o = format_event_html($ev);
250

Friendika's avatar
Friendika committed
251 252 253 254 255
	return $o;
}


function bbtoevent($s) {
256

Friendika's avatar
Friendika committed
257
	$ev = array();
258

259 260 261 262 263 264 265 266
	$match = '';
	if(preg_match("/\[event\](.*?)\[\/event\]/is",$s,$match)) {
		// only parse one object per event tag
		$x = ical_to_ev($match[1]);
		if($x)
			$ev = $x[0];
	}

friendica's avatar
friendica committed
267 268 269
	$match = '';
	if(preg_match("/\[event\-summary\](.*?)\[\/event\-summary\]/is",$s,$match))
		$ev['summary'] = $match[1];
Friendika's avatar
Friendika committed
270 271
	$match = '';
	if(preg_match("/\[event\-description\](.*?)\[\/event\-description\]/is",$s,$match))
272
		$ev['description'] = $match[1];
Friendika's avatar
Friendika committed
273 274
	$match = '';
	if(preg_match("/\[event\-start\](.*?)\[\/event\-start\]/is",$s,$match))
275
		$ev['dtstart'] = $match[1];
Friendika's avatar
Friendika committed
276 277
	$match = '';
	if(preg_match("/\[event\-finish\](.*?)\[\/event\-finish\]/is",$s,$match))
278
		$ev['dtend'] = $match[1];
Friendika's avatar
Friendika committed
279 280 281 282
	$match = '';
	if(preg_match("/\[event\-location\](.*?)\[\/event\-location\]/is",$s,$match))
		$ev['location'] = $match[1];
	$match = '';
283 284 285
	if(preg_match("/\[event\-id\](.*?)\[\/event\-id\]/is",$s,$match))
		$ev['event_hash'] = $match[1];
	$match = '';
Friendika's avatar
Friendika committed
286 287
	if(preg_match("/\[event\-adjust\](.*?)\[\/event\-adjust\]/is",$s,$match))
		$ev['adjust'] = $match[1];
288 289 290
	if(array_key_exists('dtstart',$ev)) {
		if(array_key_exists('dtend',$ev)) {
			if($ev['dtend'] === $ev['dtstart'])
redmatrix's avatar
redmatrix committed
291
				$ev['nofinish'] = 1;
292
			elseif($ev['dtend'])
redmatrix's avatar
redmatrix committed
293 294 295 296
				$ev['nofinish'] = 0;
			else
				$ev['nofinish'] = 1;
		}
redmatrix's avatar
redmatrix committed
297 298 299
		else
			$ev['nofinish'] = 1;
	}
Friendika's avatar
Friendika committed
300

Zot's avatar
Zot committed
301
//	logger('bbtoevent: ' . print_r($ev,true));
302

303
	return $ev;
Friendika's avatar
Friendika committed
304
}
305

306 307 308 309 310
/**
 * @brief Sorts the given array of events by date.
 *
 * @see ev_compare()
 * @param array $arr
311
 * @return array Date sorted array of events
312
 */
313
function sort_by_date($arr) {
314 315 316
	if (is_array($arr))
		usort($arr, 'ev_compare');

317
	return $arr;
Friendika's avatar
Friendika committed
318 319
}

320 321 322
/**
 * @brief Compare function for events.
 *
323 324
 * This function can be used in usort() to sort events by date.
 *
325 326 327 328 329 330
 * @see sort_by_date()
 * @param array $a
 * @param array $b
 * @return number return values like strcmp()
 */
function ev_compare($a, $b) {
Friendika's avatar
Friendika committed
331

332 333
	$date_a = (($a['adjust']) ? datetime_convert('UTC',date_default_timezone_get(),$a['dtstart']) : $a['dtstart']);
	$date_b = (($b['adjust']) ? datetime_convert('UTC',date_default_timezone_get(),$b['dtstart']) : $b['dtstart']);
334

335 336 337 338
	if ($date_a === $date_b)
		return strcasecmp($a['description'], $b['description']);

	return strcmp($date_a, $date_b);
Friendika's avatar
Friendika committed
339 340 341
}


342
function event_store_event($arr) {
friendica's avatar
friendica committed
343

redmatrix's avatar
redmatrix committed
344 345
	$arr['created']        = (($arr['created'])        ? $arr['created']        : datetime_convert());
	$arr['edited']         = (($arr['edited'])         ? $arr['edited']         : datetime_convert());
346
	$arr['etype']          = (($arr['etype'])          ? $arr['etype']          : 'event' );
redmatrix's avatar
redmatrix committed
347 348
	$arr['event_xchan']    = (($arr['event_xchan'])    ? $arr['event_xchan']    : '');
	$arr['event_priority'] = (($arr['event_priority']) ? $arr['event_priority'] : 0);
friendica's avatar
friendica committed
349

350

351 352 353 354 355
	if(array_key_exists('event_status_date',$arr))
		$arr['event_status_date'] = datetime_convert('UTC','UTC', $arr['event_status_date']);
	else
		$arr['event_status_date'] = NULL_DATE;

356

357
	$existing_event = null;
358

359 360 361 362 363 364 365 366 367
	if($arr['event_hash']) {
		$r = q("SELECT * FROM event WHERE event_hash = '%s' AND uid = %d LIMIT 1",
			dbesc($arr['event_hash']),
			intval($arr['uid'])
		);
		if($r) {
			$existing_event = $r[0];
		}
	}
368

369 370 371 372 373 374 375
	if($arr['id']) {
		$r = q("SELECT * FROM event WHERE id = %d AND uid = %d LIMIT 1",
			intval($arr['id']),
			intval($arr['uid'])
		);
		if($r) {
			$existing_event = $r[0];
376 377
		}
		else {
378
			return false;
379
		}
380
	}
381

382 383 384 385 386 387 388 389 390 391 392 393 394
	$hook_info = [
			'event' => $arr,
			'existing_event' => $existing_event,
			'cancel' => false
	];
	/**
	 * @hooks event_store_event
	 *   Called when an event record is created or updated.
	 *   * \e array \b event
	 *   * \e array \b existing_event
	 *   * \e boolean \b cancel - default false
	 */
	call_hooks('event_store_event', $hook_info);
redmatrix's avatar
redmatrix committed
395 396 397 398 399
	if($hook_info['cancel'])
		return false;

	$arr = $hook_info['event'];
	$existing_event = $hook_info['existing_event'];
400

401 402 403
	if($existing_event) {

		if($existing_event['edited'] >= $arr['edited']) {
404
			// Nothing has changed.
405
			return $existing_event;
406 407
		}

408
		$hash = $existing_event['event_hash'];
409

Friendika's avatar
Friendika committed
410
		// The event changed. Update it.
411

Zot's avatar
Zot committed
412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433
		$r = q("UPDATE event SET
			edited = '%s',
			dtstart = '%s',
			dtend = '%s',
			summary = '%s',
			description = '%s',
			location = '%s',
			etype = '%s',
			adjust = %d,
			nofinish = %d,
			event_status = '%s',
			event_status_date = '%s',
			event_percent = %d,
			event_repeat = '%s',
			event_sequence = %d,
			event_priority = %d,
			event_vdata = '%s',
			allow_cid = '%s',
			allow_gid = '%s',
			deny_cid = '%s',
			deny_gid = '%s'
			WHERE id = %d AND uid = %d",
Friendika's avatar
Friendika committed
434 435

			dbesc($arr['edited']),
436 437
			dbesc($arr['dtstart']),
			dbesc($arr['dtend']),
friendica's avatar
friendica committed
438
			dbesc($arr['summary']),
439
			dbesc($arr['description']),
Friendika's avatar
Friendika committed
440
			dbesc($arr['location']),
441
			dbesc($arr['etype']),
Friendika's avatar
Friendika committed
442 443
			intval($arr['adjust']),
			intval($arr['nofinish']),
444 445 446 447 448
			dbesc($arr['event_status']),
			dbesc($arr['event_status_date']),
			intval($arr['event_percent']),
			dbesc($arr['event_repeat']),
			intval($arr['event_sequence']),
redmatrix's avatar
redmatrix committed
449
			intval($arr['event_priority']),
Zot's avatar
Zot committed
450
			dbesc($arr['event_vdata']),
Friendika's avatar
Friendika committed
451 452 453 454
			dbesc($arr['allow_cid']),
			dbesc($arr['allow_gid']),
			dbesc($arr['deny_cid']),
			dbesc($arr['deny_gid']),
455
			intval($existing_event['id']),
Friendika's avatar
Friendika committed
456 457
			intval($arr['uid'])
		);
458
	} else {
459

460
		// New event. Store it.
461

462 463
		if(array_key_exists('external_id',$arr))
			$hash = $arr['external_id'];
464 465
		elseif(array_key_exists('event_hash',$arr))
			$hash = $arr['event_hash'];
466
		else
redmatrix's avatar
redmatrix committed
467
			$hash = random_string() . '@' . App::get_hostname();
468

469
		$r = q("INSERT INTO event ( uid,aid,event_xchan,event_hash,created,edited,dtstart,dtend,summary,description,location,etype,
Zot's avatar
Zot committed
470 471
			adjust,nofinish, event_status, event_status_date, event_percent, event_repeat, event_sequence, event_priority, event_vdata, allow_cid,allow_gid,deny_cid,deny_gid)
			VALUES ( %d, %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d, '%s', '%s', %d, '%s', %d, %d, '%s', '%s', '%s', '%s', '%s' ) ",
472 473 474 475 476 477
			intval($arr['uid']),
			intval($arr['account']),
			dbesc($arr['event_xchan']),
			dbesc($hash),
			dbesc($arr['created']),
			dbesc($arr['edited']),
478 479
			dbesc($arr['dtstart']),
			dbesc($arr['dtend']),
480 481 482
			dbesc($arr['summary']),
			dbesc($arr['description']),
			dbesc($arr['location']),
483
			dbesc($arr['etype']),
484 485
			intval($arr['adjust']),
			intval($arr['nofinish']),
486 487 488 489 490
			dbesc($arr['event_status']),
			dbesc($arr['event_status_date']),
			intval($arr['event_percent']),
			dbesc($arr['event_repeat']),
			intval($arr['event_sequence']),
redmatrix's avatar
redmatrix committed
491
			intval($arr['event_priority']),
Zot's avatar
Zot committed
492
			dbesc($arr['event_vdata']),
493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509
			dbesc($arr['allow_cid']),
			dbesc($arr['allow_gid']),
			dbesc($arr['deny_cid']),
			dbesc($arr['deny_gid'])
		);
	}

	$r = q("SELECT * FROM event WHERE event_hash = '%s' AND uid = %d LIMIT 1",
		dbesc($hash),
		intval($arr['uid'])
	);
	if($r)
		return $r[0];

	return false;
}

510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525
function event_addtocal($item_id, $uid) {

	$c = q("select * from channel where channel_id = %d limit 1",
		intval($uid)
	);

	if(! $c)
		return false;

	$channel = $c[0];

	$r = q("select * from item where id = %d and uid = %d limit 1",
		intval($item_id),
		intval($channel['channel_id'])
	);

friendica's avatar
friendica committed
526
	if((! $r) || ($r[0]['obj_type'] !== ACTIVITY_OBJ_EVENT))
527
		return false;
528

529 530 531
	$item = $r[0];

	$ev = bbtoevent($r[0]['body']);
friendica's avatar
friendica committed
532

533
	if(x($ev,'summary') && x($ev,'dtstart')) {
534 535 536 537 538 539 540 541 542
		$ev['event_xchan'] = $item['author_xchan'];
		$ev['uid']         = $channel['channel_id'];
		$ev['account']     = $channel['channel_account_id'];
		$ev['edited']      = $item['edited'];
		$ev['mid']         = $item['mid'];
		$ev['private']     = $item['item_private'];

		// is this an edit?

543
		if($item['resource_type'] === 'event' && (! $ev['event_hash'])) {
544 545 546
			$ev['event_hash'] = $item['resource_id'];
		}

547
		if($ev->private)
548
			$ev['allow_cid'] = '<' . $channel['channel_hash'] . '>';
549 550 551 552 553 554 555 556 557
		else {
			$acl = new Zotlabs\Access\AccessList($channel);
			$x = $acl->get();
			$ev['allow_cid'] = $x['allow_cid'];
			$ev['allow_gid'] = $x['allow_gid'];
			$ev['deny_cid']  = $x['deny_cid'];
			$ev['deny_gid']  = $x['deny_gid'];
		}

558 559
		$event = event_store_event($ev);
		if($event) {
560
			$r = q("update item set resource_id = '%s', resource_type = 'event' where id = %d and uid = %d",
friendica's avatar
friendica committed
561
				dbesc($event['event_hash']),
562 563 564
				intval($item['id']),
				intval($channel['channel_id'])
			);
565

redmatrix's avatar
redmatrix committed
566 567 568 569 570 571 572 573 574 575 576 577 578
			$item['resource_id'] = $event['event_hash'];
			$item['resource_type'] = 'event';

			$i = array($item);
			xchan_query($i);
			$sync_item = fetch_post_tags($i);
			$z = q("select * from event where event_hash = '%s' and uid = %d limit 1",
				dbesc($event['event_hash']),
				intval($channel['channel_id'])
			);
			if($z) {
				build_sync_packet($channel['channel_id'],array('event_item' => array(encode_item($sync_item[0],true)),'event' => $z));
			}
579 580 581
			return true;
		}
	}
582

583 584
	return false;
}
585 586


587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628
function ical_to_ev($s) {
	require_once('vendor/autoload.php');

	$saved_timezone = date_default_timezone_get();
	date_default_timezone_set('Australia/Sydney');

	$ical = VObject\Reader::read($s);

	$ev = [];

	if($ical) {
		if($ical->VEVENT) {
			foreach($ical->VEVENT as $event) {
				$ev[] = parse_vobject($event,'event');
			}
		}
		if($ical->VTODO) {
			foreach($ical->VTODO as $event) {
				$ev[] = parse_vobject($event,'task');
			}
		}
	}

	date_default_timezone_set($saved_timezone);

	return $ev;
}



function parse_vobject($ical, $type) {

	$ev = [];

	if(! isset($ical->DTSTART)) {
		logger('no event start');
		return $ev;
	}

	$ev['etype'] = $type;

	$dtstart = $ical->DTSTART->getDateTime();
Zot's avatar
Zot committed
629
	$ev['adjust'] = (($ical->DTSTART->isFloating()) ? 0 : 1);
630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712

	$ev['dtstart'] = datetime_convert((($ev['adjust']) ? 'UTC' : date_default_timezone_get()),'UTC',
		$dtstart->format(\DateTime::W3C));


	if(isset($ical->DUE)) {
		$dtend = $ical->DUE->getDateTime();
		$ev['dtend'] = datetime_convert((($ev['adjust']) ? 'UTC' : date_default_timezone_get()),'UTC',
			$dtend->format(\DateTime::W3C));
	}
	elseif(isset($ical->DTEND)) {
		$dtend = $ical->DTEND->getDateTime();
		$ev['dtend'] = datetime_convert((($ev['adjust']) ? 'UTC' : date_default_timezone_get()),'UTC',
			$dtend->format(\DateTime::W3C));
	}
	else
		$ev['nofinish'] = 1;


	if($ev['dtstart'] === $ev['dtend'])
		$ev['nofinish'] = 1;

	if(isset($ical->CREATED)) {
		$created = $ical->CREATED->getDateTime();
		$ev['created'] = datetime_convert('UTC','UTC',$created->format(\DateTime::W3C));
	}

	if(isset($ical->{'DTSTAMP'})) {
		$edited = $ical->{'DTSTAMP'}->getDateTime();
		$ev['edited'] = datetime_convert('UTC','UTC',$edited->format(\DateTime::W3C));
	}
	if(isset($ical->{'LAST-MODIFIED'})) {
		$edited = $ical->{'LAST-MODIFIED'}->getDateTime();
		$ev['edited'] = datetime_convert('UTC','UTC',$edited->format(\DateTime::W3C));
	}

	if(isset($ical->{'X-ZOT-LOCATION'}))
		$ev['location'] = event_ical_get_sourcetext( (string) $ical->{'X-ZOT-LOCATION'});
	elseif(isset($ical->LOCATION))
		$ev['location'] = (string) $ical->LOCATION;

	if(isset($ical->{'X-ZOT-DESCRIPTION'}))
		$ev['description'] = event_ical_get_sourcetext( (string) $ical->{'X-ZOT-DESCRIPTION'});
	elseif(isset($ical->DESCRIPTION))
		$ev['description'] = (string) $ical->DESCRIPTION;

	if(isset($ical->{'X-ZOT-SUMMARY'}))
		$ev['summary'] = event_ical_get_sourcetext( (string) $ical->{'X-ZOT-SUMMARY'});
	elseif(isset($ical->SUMMARY))
		$ev['summary'] = (string) $ical->SUMMARY;

	if(isset($ical->PRIORITY))
		$ev['event_priority'] = intval((string) $ical->PRIORITY);

	if(isset($ical->UID)) {
		$evuid = (string) $ical->UID;
		$ev['event_hash'] = $evuid;
	}

	if(isset($ical->SEQUENCE)) {
		$ev['event_sequence'] = (string) $ical->SEQUENCE;
	}

	if(isset($ical->STATUS)) {
		$ev['event_status'] = (string) $ical->STATUS;
	}

	if(isset($ical->{'COMPLETED'})) {
		$completed = $ical->{'COMPLETED'}->getDateTime();
		$ev['event_status_date'] = datetime_convert('UTC','UTC',$completed->format(\DateTime::W3C));
	}

	if(isset($ical->{'PERCENT-COMPLETE'})) {
		$ev['event_percent'] = (string) $ical->{'PERCENT-COMPLETE'} ;
	}

	$ev['event_vdata'] = $ical->serialize();

	return $ev;
}



713
function parse_ical_file($f,$uid) {
714
	require_once('vendor/autoload.php');
715 716 717 718 719 720 721 722 723 724 725 726

	$s = @file_get_contents($f);

	// Change the current timezone to something besides UTC.
	// Doesn't matter what it is, as long as it isn't UTC.
	// Save the current timezone so we can reset it when we're done processing.

	$saved_timezone = date_default_timezone_get();
	date_default_timezone_set('Australia/Sydney');

	$ical = VObject\Reader::read($s);

727
	if($ical) {
728 729 730 731 732 733 734 735 736
		if($ical->VEVENT) {
			foreach($ical->VEVENT as $event) {
				event_import_ical($event,$uid);
			}
		}
		if($ical->VTODO) {
			foreach($ical->VTODO as $event) {
				event_import_ical_task($event,$uid);
			}
737 738
		}
	}
739 740 741

	date_default_timezone_set($saved_timezone);

redmatrix's avatar
redmatrix committed
742
	if($ical)
743
		return true;
744

745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761
	return false;
}



function event_import_ical($ical, $uid) {

	$c = q("select * from channel where channel_id = %d limit 1",
		intval($uid)
	);

	if(! $c)
		return false;

	$channel = $c[0];
	$ev = array();

762

763 764 765 766
	if(! isset($ical->DTSTART)) {
		logger('no event start');
		return false;
	}
767

768
	$dtstart = $ical->DTSTART->getDateTime();
Zot's avatar
Zot committed
769
	$ev['adjust'] = (($ical->DTSTART->isFloating()) ? 0 : 1);
770

771 772
//	logger('dtstart: ' . var_export($dtstart,true));

773
	$ev['dtstart'] = datetime_convert((($ev['adjust']) ? 'UTC' : date_default_timezone_get()),'UTC',
774 775
		$dtstart->format(\DateTime::W3C));

776 777
	if(isset($ical->DTEND)) {
		$dtend = $ical->DTEND->getDateTime();
778
		$ev['dtend'] = datetime_convert((($ev['adjust']) ? 'UTC' : date_default_timezone_get()),'UTC',
779 780
			$dtend->format(\DateTime::W3C));
	}
781
	else {
782
		$ev['nofinish'] = 1;
783
	}
784

785
	if($ev['dtstart'] === $ev['dtend'])
786
		$ev['nofinish'] = 1;
787

788 789 790 791
	if(isset($ical->CREATED)) {
		$created = $ical->CREATED->getDateTime();
		$ev['created'] = datetime_convert('UTC','UTC',$created->format(\DateTime::W3C));
	}
792

793 794 795 796
	if(isset($ical->{'LAST-MODIFIED'})) {
		$edited = $ical->{'LAST-MODIFIED'}->getDateTime();
		$ev['edited'] = datetime_convert('UTC','UTC',$edited->format(\DateTime::W3C));
	}
797

798 799 800
	if(isset($ical->{'X-ZOT-LOCATION'}))
		$ev['location'] = event_ical_get_sourcetext( (string) $ical->{'X-ZOT-LOCATION'});
	elseif(isset($ical->LOCATION))
801
		$ev['location'] = (string) $ical->LOCATION;
802 803 804 805

	if(isset($ical->{'X-ZOT-DESCRIPTION'}))
		$ev['description'] = event_ical_get_sourcetext( (string) $ical->{'X-ZOT-DESCRIPTION'});
	elseif(isset($ical->DESCRIPTION))
806
		$ev['description'] = (string) $ical->DESCRIPTION;
807 808 809 810

	if(isset($ical->{'X-ZOT-SUMMARY'}))
		$ev['summary'] = event_ical_get_sourcetext( (string) $ical->{'X-ZOT-SUMMARY'});
	elseif(isset($ical->SUMMARY))
811
		$ev['summary'] = (string) $ical->SUMMARY;
812

redmatrix's avatar
redmatrix committed
813 814
	if(isset($ical->PRIORITY))
		$ev['event_priority'] = intval((string) $ical->PRIORITY);
815

816 817
	if(isset($ical->UID)) {
		$evuid = (string) $ical->UID;
818
		$r = q("SELECT * FROM event WHERE event_hash = '%s' AND uid = %d LIMIT 1",
819 820
			dbesc($evuid),
			intval($uid)
821 822
		);
		if($r)
823
			$ev['event_hash'] = $evuid;
824
		else
825
			$ev['external_id'] = $evuid;
826
	}
827

828
	if($ev['summary'] && $ev['dtstart']) {
829 830 831 832
		$ev['event_xchan'] = $channel['channel_hash'];
		$ev['uid']         = $channel['channel_id'];
		$ev['account']     = $channel['channel_account_id'];
		$ev['private']     = 1;
redmatrix's avatar
redmatrix committed
833
		$ev['allow_cid']   = '<' . $channel['channel_hash'] . '>';
834

835
		logger('storing event: ' . print_r($ev,true), LOGGER_ALL);
836 837
		$event = event_store_event($ev);
		if($event) {
838
			$item_id = event_store_item($ev,$event);
839 840 841 842 843 844 845
			return true;
		}
	}

	return false;
}

846 847 848 849
function event_ical_get_sourcetext($s) {
	return base64_decode($s);
}

850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869
function event_import_ical_task($ical, $uid) {

	$c = q("select * from channel where channel_id = %d limit 1",
		intval($uid)
	);

	if(! $c)
		return false;

	$channel = $c[0];
	$ev = array();


	if(! isset($ical->DTSTART)) {
		logger('no event start');
		return false;
	}

	$dtstart = $ical->DTSTART->getDateTime();

Zot's avatar
Zot committed
870
	$ev['adjust'] = (($ical->DTSTART->isFloating()) ? 0 : 1);
871

872 873
//	logger('dtstart: ' . var_export($dtstart,true));

874
	$ev['dtstart'] = datetime_convert((($ev['adjust']) ? 'UTC' : date_default_timezone_get()),'UTC',
875 876 877 878 879
		$dtstart->format(\DateTime::W3C));


	if(isset($ical->DUE)) {
		$dtend = $ical->DUE->getDateTime();
880
		$ev['dtend'] = datetime_convert((($ev['adjust']) ? 'UTC' : date_default_timezone_get()),'UTC',
881 882 883 884 885 886
			$dtend->format(\DateTime::W3C));
	}
	else
		$ev['nofinish'] = 1;


887
	if($ev['dtstart'] === $ev['dtend'])
888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904
		$ev['nofinish'] = 1;

	if(isset($ical->CREATED)) {
		$created = $ical->CREATED->getDateTime();
		$ev['created'] = datetime_convert('UTC','UTC',$created->format(\DateTime::W3C));
	}

	if(isset($ical->{'DTSTAMP'})) {
		$edited = $ical->{'DTSTAMP'}->getDateTime();
		$ev['edited'] = datetime_convert('UTC','UTC',$edited->format(\DateTime::W3C));
	}

	if(isset($ical->{'LAST-MODIFIED'})) {
		$edited = $ical->{'LAST-MODIFIED'}->getDateTime();
		$ev['edited'] = datetime_convert('UTC','UTC',$edited->format(\DateTime::W3C));
	}

905 906 907
	if(isset($ical->{'X-ZOT-LOCATION'}))
		$ev['location'] = event_ical_get_sourcetext( (string) $ical->{'X-ZOT-LOCATION'});
	elseif(isset($ical->LOCATION))
908
		$ev['location'] = (string) $ical->LOCATION;
909 910 911 912

	if(isset($ical->{'X-ZOT-DESCRIPTION'}))
		$ev['description'] = event_ical_get_sourcetext( (string) $ical->{'X-ZOT-DESCRIPTION'});
	elseif(isset($ical->DESCRIPTION))
913
		$ev['description'] = (string) $ical->DESCRIPTION;
914 915 916 917

	if(isset($ical->{'X-ZOT-SUMMARY'}))
		$ev['summary'] = event_ical_get_sourcetext( (string) $ical->{'X-ZOT-SUMMARY'});
	elseif(isset($ical->SUMMARY))
918
		$ev['summary'] = (string) $ical->SUMMARY;
919

redmatrix's avatar
redmatrix committed
920 921
	if(isset($ical->PRIORITY))
		$ev['event_priority'] = intval((string) $ical->PRIORITY);
922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942

	$stored_event = null;

	if(isset($ical->UID)) {
		$evuid = (string) $ical->UID;
		$r = q("SELECT * FROM event WHERE event_hash = '%s' AND uid = %d LIMIT 1",
			dbesc($evuid),
			intval($uid)
		);
		if($r) {
			$ev['event_hash'] = $evuid;
			$stored_event = $r[0];
		}
		else {
			$ev['external_id'] = $evuid;
		}
	}

	if(isset($ical->SEQUENCE)) {
		$ev['event_sequence'] = (string) $ical->SEQUENCE;
		// see if our stored event is more current than the one we're importing
943
		if((intval($ev['event_sequence']) <= intval($stored_event['event_sequence']))
944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960
			&& ($ev['edited'] <= $stored_event['edited']))
			return false;
	}

	if(isset($ical->STATUS)) {
		$ev['event_status'] = (string) $ical->STATUS;
	}

	if(isset($ical->{'COMPLETED'})) {
		$completed = $ical->{'COMPLETED'}->getDateTime();
		$ev['event_status_date'] = datetime_convert('UTC','UTC',$completed->format(\DateTime::W3C));
	}

	if(isset($ical->{'PERCENT-COMPLETE'})) {
		$ev['event_percent'] = (string) $ical->{'PERCENT-COMPLETE'} ;
	}

961
	$ev['etype'] = 'task';
962

963
	if($ev['summary'] && $ev['dtstart']) {
964 965 966 967 968 969
		$ev['event_xchan'] = $channel['channel_hash'];
		$ev['uid']         = $channel['channel_id'];
		$ev['account']     = $channel['channel_account_id'];
		$ev['private']     = 1;
		$ev['allow_cid']   = '<' . $channel['channel_hash'] . '>';

970
		logger('storing event: ' . print_r($ev,true), LOGGER_ALL);
971 972 973 974 975 976 977 978 979 980 981 982
		$event = event_store_event($ev);
		if($event) {
			$item_id = event_store_item($ev,$event);
			return true;
		}
	}

	return false;
}



983
function event_store_item($arr, $event) {
984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999

	require_once('include/datetime.php');
	require_once('include/items.php');

	$item = null;

	if($arr['mid'] && $arr['uid']) {
		$i = q("select * from item where mid = '%s' and uid = %d limit 1",
			dbesc($arr['mid']),
			intval($arr['uid'])
		);
		if($i) {
			xchan_query($i);
			$item = fetch_post_tags($i,true);
		}
	}
1000

1001

1002 1003
	$item_arr = array();
	$prefix = '';
1004
//	$birthday = false;
1005

1006 1007 1008
	if(($event) && array_key_exists('event_hash',$event) && (! array_key_exists('event_hash',$arr)))
		$arr['event_hash'] = $event['event_hash'];

1009
	if($event['etype'] === 'birthday') {
1010 1011
		if(! is_sys_channel($arr['uid']))
			$prefix =  t('This event has been added to your calendar.');
1012
//		$birthday = true;
1013

1014
		// The event is created on your own site by the system, but appears to belong
1015
		// to the birthday person. It also isn't propagated - so we need to prevent
1016
		// folks from trying to comment on it. If you're looking at this and trying to
1017
		// fix it, you'll need to completely change the way birthday events are created
1018
		// and send them out from the source. This has its own issues.
1019 1020 1021

		$item_arr['comment_policy'] = 'none';
	}
friendica's avatar
friendica committed
1022

friendica's avatar
friendica committed
1023
	$r = q("SELECT * FROM item left join xchan on author_xchan = xchan_hash WHERE resource_id = '%s' AND resource_type = 'event' and uid = %d LIMIT 1",
1024
		dbesc($event['event_hash']),
friendica's avatar
friendica committed
1025 1026
		intval($arr['uid'])
	);
1027

friendica's avatar
friendica committed
1028
	if($r) {
1029
		$object = json_encode(array(
friendica's avatar
friendica committed
1030 1031 1032
			'type'    => ACTIVITY_OBJ_EVENT,
			'id'      => z_root() . '/event/' . $r[0]['resource_id'],
			'title'   => $arr['summary'],
1033 1034
			'dtstart' => $arr['dtstart'],
			'dtend'  => $arr['dtend'],
1035
			'nofinish'  => $arr['nofinish'],
1036 1037 1038
			'description' => $arr['description'],
			'location'   => $arr['location'],
			'adjust'   => $arr['adjust'],
friendica's avatar
friendica committed
1039 1040
			'content' => format_event_bbcode($arr),
			'author'  => array(
1041 1042 1043 1044 1045 1046 1047 1048
				'name'     => $r[0]['xchan_name'],
				'address'  => $r[0]['xchan_addr'],
				'guid'     => $r[0]['xchan_guid'],
				'guid_sig' => $r[0]['xchan_guid_sig'],
				'link'     => array(
					array('rel' => 'alternate', 'type' => 'text/html', 'href' => $r[0]['xchan_url']),
					array('rel' => 'photo', 'type' => $r[0]['xchan_photo_mimetype'], 'href' => $r[0]['xchan_photo_m'])
				),
friendica's avatar
friendica committed
1049 1050
			),
		));
1051

friendica's avatar
friendica committed
1052
		$private = (($arr['allow_cid'] || $arr['allow_gid'] || $arr['deny_cid'] || $arr['deny_gid']) ? 1 : 0);
1053

1054 1055 1056 1057
		/**
		 * @FIXME can only update sig if we have the author's channel on this site
		 * Until fixed, set it to nothing so it won't give us signature errors.
		 */
1058 1059
		$sig = '';

1060
		q("UPDATE item SET title = '%s', body = '%s', obj = '%s', allow_cid = '%s', allow_gid = '%s', deny_cid = '%s', deny_gid = '%s', edited = '%s', sig = '%s', item_flags = %d, item_private = %d, obj_type = '%s'  WHERE id = %d AND uid = %d",
friendica's avatar
friendica committed
1061
			dbesc($arr['summary']),
friendica's avatar
friendica committed
1062
			dbesc($prefix . format_event_bbcode($arr)),
friendica's avatar
friendica committed
1063 1064 1065 1066 1067 1068
			dbesc($object),
			dbesc($arr['allow_cid']),
			dbesc($arr['allow_gid']),
			dbesc($arr['deny_cid']),
			dbesc($arr['deny_gid']),
			dbesc($arr['edited']),
1069
			dbesc($sig),
friendica's avatar
friendica committed
1070 1071
			intval($r[0]['item_flags']),
			intval($private),
1072
			dbesc(ACTIVITY_OBJ_EVENT),
friendica's avatar
friendica committed
1073 1074 1075
			intval($r[0]['id']),
			intval($arr['uid'])
		);
1076

1077
		q("delete from term where oid = %d and otype = %d",
friendica's avatar
friendica committed
1078 1079 1080 1081 1082 1083
			intval($r[0]['id']),
			intval(TERM_OBJ_POST)
		);

		if(($arr['term']) && (is_array($arr['term']))) {
			foreach($arr['term'] as $t) {
redmatrix's avatar
redmatrix committed
1084
				q("insert into term (uid,oid,otype,ttype,term,url)
friendica's avatar
friendica committed
1085 1086 1087 1088
					values(%d,%d,%d,%d,'%s','%s') ",
					intval($arr['uid']),
					intval($r[0]['id']),
					intval(TERM_OBJ_POST),
redmatrix's avatar
redmatrix committed
1089
					intval($t['ttype']),
friendica's avatar
friendica committed
1090 1091 1092 1093
					dbesc($t['term']),
					dbesc($t['url'])
				);
			}
1094
		}
friendica's avatar
friendica committed
1095

friendica's avatar
friendica committed
1096
		$item_id = $r[0]['id'];
1097 1098 1099 1100
		/**
		 * @hooks event_updated
		 *   Called when an event record is modified.
		 */
friendica's avatar
friendica committed
1101
		call_hooks('event_updated', $event['id']);
1102

1103
		return $item_id;
1104
	} else {
Friendika's avatar
Friendika committed
1105

1106
		$z = q("select * from channel where channel_id = %d limit 1",
1107 1108
			intval($arr['uid'])
		);
Friendika's avatar
Friendika committed
1109

1110
		$private = (($arr['allow_cid'] || $arr['allow_gid'] || $arr['deny_cid'] || $arr['deny_gid']) ? 1 : 0);
1111 1112 1113

		$item_wall = 0;
		$item_origin = 0;
1114
		$item_thread_top = 0;
1115

friendica's avatar
friendica committed
1116 1117 1118 1119
		if($item) {
			$item_arr['id'] = $item['id'];
		}
		else {
1120
			$wall = (($z[0]['channel_hash'] == $event['event_xchan']) ? true : false);
1121
			$item_thread_top = 1;
friendica's avatar
friendica committed
1122
			if($wall) {
1123 1124
				$item_wall = 1;
				$item_origin = 1;
friendica's avatar
friendica committed
1125 1126 1127
			}
		}

friendica's avatar
friendica committed
1128 1129 1130
		if(! $arr['mid'])
			$arr['mid'] = item_message_id();

1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146
		$item_arr['aid']             = $z[0]['channel_account_id'];
		$item_arr['uid']             = $arr['uid'];
		$item_arr['author_xchan']    = $arr['event_xchan'];
		$item_arr['mid']             = $arr['mid'];
		$item_arr['parent_mid']      = $arr['mid'];
		$item_arr['owner_xchan']     = (($wall) ? $z[0]['channel_hash'] : $arr['event_xchan']);
		$item_arr['author_xchan']    = $arr['event_xchan'];
		$item_arr['title']           = $arr['summary'];
		$item_arr['allow_cid']       = $arr['allow_cid'];
		$item_arr['allow_gid']       = $arr['allow_gid'];
		$item_arr['deny_cid']        = $arr['deny_cid'];
		$item_arr['deny_gid']        = $arr['deny_gid'];
		$item_arr['item_private']    = $private;
		$item_arr['verb']            = ACTIVITY_POST;
		$item_arr['item_wall']       = $item_wall;
		$item_arr['item_origin']     = $item_origin;
Mario's avatar
Mario committed
1147
		$item_arr['item_thread_top'] = $item_thread_top;
Friendika's avatar
Friendika committed
1148

1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159
		$attach = array(array(
			'href' => z_root() . '/events/ical/' .  urlencode($event['event_hash']),
			'length' => 0,
			'type' => 'text/calendar',
			'title' => t('event') . '-' . $event['event_hash'],
			'revision' => ''
		));

		$item_arr['attach'] = $attach;


1160 1161
		if(array_key_exists('term', $arr))
			$item_arr['term'] = $arr['term'];
friendica's avatar
friendica committed
1162

1163 1164 1165 1166
		$item_arr['resource_type']   = 'event';
		$item_arr['resource_id']     = $event['event_hash'];
		$item_arr['obj_type']        = ACTIVITY_OBJ_EVENT;
		$item_arr['body']            = $prefix . format_event_bbcode($arr);
Friendika's avatar
Friendika committed
1167

1168 1169 1170 1171
		// if it's local send the permalink to the channel page.
		// otherwise we'll fallback to /display/$message_id

		if($wall)
1172
			$item_arr['plink'] = z_root() . '/channel/' . $z[0]['channel_address'] . '/?f=&mid=' . urlencode($item_arr['mid']);
1173
		else
1174
			$item_arr['plink'] = z_root() . '/display/' . gen_link_id($item_arr['mid']);
1175

1176 1177
		$x = q("select * from xchan where xchan_hash = '%s' limit 1",
				dbesc($arr['event_xchan'])
Friendika's avatar
Friendika committed
1178
		);
1179
		if($x) {
1180
			$item_arr['obj'] = json_encode(array(
1181
				'type'    => ACTIVITY_OBJ_EVENT,
1182
				'id'      => z_root() . '/event/' . $event['event_hash'],
1183
				'title'   => $arr['summary'],
1184 1185
				'dtstart' => $arr['dtstart'],
				'dtend'  => $arr['dtend'],
1186
				'nofinish'  => $arr['nofinish'],
Mario's avatar
Mario committed
1187 1188 1189
				'description' => $arr['description'],
				'location'   => $arr['location'],
				'adjust'   => $arr['adjust'],
1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201
				'content' => format_event_bbcode($arr),
				'author'  => array(
					'name'     => $x[0]['xchan_name'],
					'address'  => $x[0]['xchan_addr'],
					'guid'     => $x[0]['xchan_guid'],
					'guid_sig' => $x[0]['xchan_guid_sig'],
					'link'     => array(
						array('rel' => 'alternate', 'type' => 'text/html', 'href' => $x[0]['xchan_url']),
						array('rel' => 'photo', 'type' => $x[0]['xchan_photo_mimetype'], 'href' => $x[0]['xchan_photo_m'])),
					),
			));
		}
Friendika's avatar
Friendika committed
1202

1203 1204 1205 1206 1207 1208 1209
		// propagate the event resource_id so that posts containing it are easily searchable in downstream copies
		// of the item which have not stored the actual event. Required for Diaspora event federation as Diaspora 
		// event_participation messages refer to the event resource_id as a parent, while out own event attendance
		// activities refer to the item message_id as the parent. 

		set_iconfig($item_arr, 'system','event_id',$event['event_hash'],true);

friendica's avatar
friendica committed
1210
		$res = item_store($item_arr);
friendica's avatar
friendica committed
1211

1212
		$item_id = $res['item_id'];
1213

1214 1215 1216 1217
		/**
		 * @hooks event_created
		 *   Called when an event record is created.
		 */
1218
		call_hooks('event_created', $event['id']);
friendica's avatar
friendica committed
1219

Friendika's avatar
Friendika committed
1220 1221 1222
		return $item_id;
	}
}
1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233


function todo_stat() {
	return array(
		''             => t('Not specified'),
		'NEEDS-ACTION' => t('Needs Action'),
		'COMPLETED'    => t('Completed'),
		'IN-PROCESS'   => t('In Process'),
		'CANCELLED'    => t('Cancelled')
	);
}
redmatrix's avatar
redmatrix committed
1234 1235 1236 1237


function tasks_fetch($arr) {

1238 1239
	if(! local_channel())
		return;
redmatrix's avatar
redmatrix committed
1240

1241 1242 1243 1244
	$ret = array();
	$sql_extra = " and event_status != 'COMPLETED' ";
	if($arr && $arr['all'] == 1)
		$sql_extra = '';
redmatrix's avatar
redmatrix committed
1245

1246 1247 1248
	$r = q("select * from event where etype = 'task' and uid = %d $sql_extra order by created desc",
		intval(local_channel())
	);
redmatrix's avatar
redmatrix committed
1249

1250 1251 1252 1253
	$ret['success'] = (($r) ? true : false);
	if($r) {
		$ret['tasks'] = $r;
	}
redmatrix's avatar
redmatrix committed
1254 1255

	return $ret;
1256
}
Zot's avatar
Zot committed
1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324

function cdav_principal($uri) {
	$r = q("SELECT uri FROM principals WHERE uri = '%s' LIMIT 1",
		dbesc($uri)
	);

	if($r[0]['uri'] === $uri)
		return true;
	else
		return false;
}

function cdav_perms($needle, $haystack, $check_rw = false) {
	foreach ($haystack as $item) {
		if($check_rw) {
			if(is_array($item['id'])) {
				if ($item['id'][0] == $needle && $item['share-access'] != 2) {
					return $item['{DAV:}displayname'];
				}
			}
			else {
				if ($item['id'] == $needle && $item['share-access'] != 2) {
					return $item['{DAV:}displayname'];
				}
			}
		}
		else {
			if(is_array($item['id'])) {
				if ($item['id'][0] == $needle) {
					return $item['{DAV:}displayname'];
				}
			}
			else {
				if ($item['id'] == $needle) {
					return $item['{DAV:}displayname'];
				}
			}
		}
	}
	return false;
}


function translate_type($type) {

	if(!$type)
		return;

	$type = strtoupper($type);

	$map = [
		'CELL' => t('Mobile'),
		'HOME' => t('Home'),
		'HOME,VOICE' => t('Home, Voice'),
		'HOME,FAX' => t('Home, Fax'),
		'WORK' => t('Work'),
		'WORK,VOICE' => t('Work, Voice'),
		'WORK,FAX' => t('Work, Fax'),
		'OTHER' => t('Other')
	];

	if (array_key_exists($type, $map)) {
		return [$type, $map[$type]];
	}
	else {
		return [$type, t('Other') . ' (' . $type . ')'];
	}
}
1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342