diaspora.php 36.1 KB
Newer Older
1 2 3 4 5
<?php


/**
 * Name: Diaspora Protocol
6
 * Description: Diaspora Protocol. Install 'Diaspora Statistics' first if you wish to use public tag relays
7 8 9 10 11
 * Version: 1.0
 * Author: Mike Macgirvin
 * Maintainer: none
 */

Mario's avatar
Mario committed
12 13
use Zotlabs\Lib\Apps;

14
// use the new federation protocol
15
define('DIASPORA_V2',1);
16 17 18 19 20 21 22 23 24 25 26 27

require_once('include/crypto.php');
require_once('include/items.php');
require_once('include/markdown.php');
require_once('include/queue_fn.php');

require_once('addon/diaspora/inbound.php');
require_once('addon/diaspora/outbound.php');
require_once('addon/diaspora/util.php');


function diaspora_load() {
28 29 30 31

	Zotlabs\Extend\Hook::register_array('addon/diaspora/diaspora.php', [
		'notifier_hub'                => 'diaspora_process_outbound',
		'notifier_process'            => 'diaspora_notifier_process',
32
		'federated_transports'        => 'diaspora_federated_transports',
33 34 35 36 37 38
		'permissions_create'          => 'diaspora_permissions_create',
		'permissions_update'          => 'diaspora_permissions_update',
		'module_loaded'               => 'diaspora_load_module',
		'follow_allow'                => 'diaspora_follow_allow',
		'post_local'                  => 'diaspora_post_local',
		'well_known'                  => 'diaspora_well_known',
39
		'create_identity'             => 'diaspora_create_identity',
40 41 42 43 44 45 46 47 48
		'profile_sidebar'             => 'diaspora_profile_sidebar',
		'discover_channel_webfinger'  => 'diaspora_discover',
		'import_author'               => 'diaspora_import_author',
		'markdown_to_bb_init'         => 'diaspora_markdown_to_bb_init',
		'bb_to_markdown_bb'           => 'diaspora_bb_to_markdown_bb',
		'service_plink'               => 'diaspora_service_plink',
		'import_foreign_channel_data' => 'diaspora_import_foreign_channel_data',
		'personal_xrd'                => 'diaspora_personal_xrd',
		'author_is_pmable'            => 'diaspora_author_is_pmable',
49
		'can_comment_on_post'         => 'diaspora_can_comment_on_post',
50
		'queue_deliver'               => 'diaspora_queue_deliver',
51 52
		'webfinger'                   => 'diaspora_webfinger',
		'channel_protocols'           => 'diaspora_channel_protocols'
53
	]);
54

55
	Zotlabs\Extend\Route::register('addon/diaspora/Mod_Diaspora.php','diaspora');
Mario's avatar
Mario committed
56

57 58 59 60
	diaspora_init_relay();
}

function diaspora_unload() {
61
	Zotlabs\Extend\Hook::unregister_by_file('addon/diaspora/diaspora.php');
62
	Zotlabs\Extend\Route::unregister('addon/diaspora/Mod_Diaspora.php','diaspora');
63 64 65 66 67
}


function diaspora_init_relay() {
	if(! get_config('diaspora','relay_handle')) {
68
		if(plugin_is_installed('statistics')) {
69
			$x = ['author' => [ 'address' => 'relay@relay.iliketoast.net', 'network' => 'diaspora' ], 'result' => false ];
70
			diaspora_import_author($x);
71 72 73 74 75 76 77 78 79 80
			if($x['result']) {
				set_config('diaspora','relay_handle',$x['result']);
				// Now register
				$url = "https://the-federation.info/register/" . App::get_hostname();
				$ret = z_fetch_url($url);
			}
		}
	}
}

81
function diaspora_author_is_pmable(&$b) {
Zot's avatar
Zot committed
82 83 84
	if($b['abook'] && (! intval($b['abook']['abook_not_here'])) && (strpos($b['xchan']['xchan_network'],'diaspora') !== false))
		$b['result'] = true;
}
85

86 87 88 89
function diaspora_federated_transports(&$x) {
	$x[] = 'Diaspora';
}

90
function diaspora_load_module(&$b) {
91
	if($b['module'] === 'receive') {
92 93
		require_once('addon/diaspora/Mod_Receive.php');
		$b['controller'] = new \Zotlabs\Module\Receive();
94 95 96 97 98 99 100 101 102 103 104 105 106 107
		$b['installed'] = true;
	}
	if($b['module'] === 'p') {
		require_once('addon/diaspora/p.php');
		$b['installed'] = true;
	}
	if($b['module'] === 'fetch') {
		require_once('addon/diaspora/Mod_Fetch.php');
		$b['controller'] = new \Zotlabs\Module\Fetch();
		$b['installed'] = true;
	}
}


108
function diaspora_well_known(&$b) {
109 110 111 112 113 114
	if(argc() > 1 && argv(1) === 'x-social-relay') {
		$disabled = (get_config('system','disable_discover_tab') || get_config('system','disable_diaspora_discover_tab'));
		$scope = 'all';
		$tags = get_config('diaspora','relay_tags');
		if($tags) {
			$disabled = false;
115 116 117 118

			// set diaspora.firehose if you want to receive all public diaspora relay posts
			// otherwise, only import posts with tags that have been followed by your site members

Mario's avatar
Mario committed
119
			if(! get_config('diaspora','firehose')) {
120 121
				$scope = 'tags';
			}
122 123 124 125 126
		}

		$arr = array(
			'subscribe' => (($disabled) ? false : true),
			'scope' => $scope,
127
			'tags' => (($tags) ? array_values($tags) : [])
128 129 130 131 132 133 134 135 136
		);

		header('Content-type: application/json');
		echo json_encode($arr);
		killme();			

	}
}

137 138 139

function diaspora_channel_protocols(&$b) {

Mario's avatar
Mario committed
140
	if(Apps::addon_app_installed($b['channel_id'], 'diaspora'))
141 142 143 144
		$b['protocols'][] = 'diaspora';

}

145
function diaspora_personal_xrd(&$b) {
146

Mario's avatar
Mario committed
147
	if(! Apps::addon_app_installed($b['user']['channel_id'], 'diaspora'))
Zot's avatar
Zot committed
148 149 150 151 152 153 154 155 156 157 158 159 160
		return;

	$dspr = replace_macros(get_markup_template('xrd_diaspora.tpl','addon/diaspora'),
		[
			'$baseurl'   => z_root(),
			'$dspr_guid' => $b['user']['channel_guid'] . str_replace('.','',\App::get_hostname()),
			'$dspr_key'  => base64_encode(pemtorsa($b['user']['channel_pubkey']))
		]
	);

	$b['xml'] = str_replace('</XRD>',$dspr . "\n" . '</XRD>',$b['xml']);

}
161 162


163 164
function diaspora_webfinger(&$b) {

165 166 167
	if(! $b['channel'])
		return;

Mario's avatar
Mario committed
168
	if(! Apps::addon_app_installed($b['channel']['channel_id'], 'diaspora'))
169 170 171 172 173 174 175 176
		return;

	$b['result']['links'][] = [ 
		'rel'  => 'http://joindiaspora.com/seed_location',
		'type' => 'text/html',
		'href' => z_root()
	];

177 178
	$b['result']['properties']['http://purl.org/zot/federation'] .= ',diaspora';

179 180 181 182 183 184 185 186 187 188
	// Diaspora requires a salmon link. 
	// Use this *only* if the gnusoc plugin is not installed and enabled

	if((! in_array('gnusoc',\App::$plugins)) || (! intval(get_pconfig($b['channel']['channel_id'],'system','gnusoc_allowed')))) {
		$b['result']['links'][] = [ 
			'rel'  => 'salmon',
			'href' => z_root() . '/receive/users/' . $b['channel']['channel_guid'] . str_replace('.','',App::get_hostname())
		];
	}

189
}
190 191


192
function diaspora_permissions_create(&$b) {
193 194 195 196 197 198 199 200
	if($b['recipient']['xchan_network'] === 'diaspora' || $b['recipient']['xchan_network'] === 'friendica-over-diaspora') {

		$b['deliveries'] = diaspora_share($b['sender'],$b['recipient']);
		if($b['deliveries'])
			$b['success'] = 1;
	}
}

201
function diaspora_permissions_update(&$b) {
202 203 204 205 206 207
	if($b['recipient']['xchan_network'] === 'diaspora' || $b['recipient']['xchan_network'] === 'friendica-over-diaspora') {
		discover_by_webbie($b['recipient']['xchan_hash']);
		$b['success'] = 1;
	}
}

208
function diaspora_notifier_process(&$arr) {
209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230

	// if it is a public post (reply, etc.), add the chosen relay channel to the recipients

	// If target_item isn't set it's likely to be refresh packet.

	if(! ((array_key_exists('target_item',$arr)) && (is_array($arr['target_item'])))) {
		return;
	} 

	// If item_wall doesn't exist, it's not a post - perhaps an email or other DB object

	if(! array_key_exists('item_wall',$arr['target_item']))
		return;
	if(($arr['normal_mode']) && (! $arr['env_recips']) && (! $arr['private']) && (! $arr['upstream'])) {
		$relay = get_config('diaspora','relay_handle');
		if($relay) {
			$arr['recipients'][] = "'" . $relay . "'";
		}
	}
}


231
function diaspora_process_outbound(&$arr) {
232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258
/*

	We are passed the following array from the notifier, providing everything we need to make delivery decisions.

			$arr = array(
				'channel' => $channel,
				'upstream' => $upstream,
				'env_recips' => $env_recips,
				'packet_recips' => $packet_recips,
				'recipients' => $recipients,
				'item' => $item,
				'target_item' => $target_item,
				'hub' => $hub,
				'top_level_post' => $top_level_post,
				'private' => $private,
				'relay_to_owner' => $relay_to_owner,
				'uplink' => $uplink,
				'cmd' => $cmd,
				'mail' => $mail,
				'location' => $location,
				'normal_mode' => $normal_mode,
				'packet_type' => $packet_type,
				'walltowall' => $walltowall,
				'queued' => pass these queued items (outq_hash) back to notifier.php for delivery
			);
*/

Zot's avatar
Zot committed
259 260 261
	if(! strstr($arr['hub']['hubloc_network'],'diaspora'))
		return;

262
	logger('upstream: ' . intval($arr['upstream']));
263 264 265
//	logger('notifier_array: ' . print_r($arr,true), LOGGER_ALL, LOG_INFO);


266

Zot's avatar
Zot committed
267
	// allow this to be set per message
268 269 270

	if(($arr['mail']) && intval($arr['item']['raw'])) {
		logger('Cannot send raw data to Diaspora mail service.');
271
		return;
272 273 274 275 276 277 278 279 280 281 282 283
	}

	if(array_key_exists('target_item',$arr) && is_array($arr['target_item'])) {
		if(intval($arr['target_item']['item_obscured'])) {
			logger('Cannot send raw data as a Diaspora activity.');
			return;
		}

		if(strpos($arr['target_item']['postopts'],'nodspr') !== false) {
			return;
		}
	}
284

Mario's avatar
Mario committed
285
	$allowed = Apps::addon_app_installed($arr['channel']['channel_id'], 'diaspora');
286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314

	if(! intval($allowed)) {
		logger('mod-diaspora: disallowed for channel ' . $arr['channel']['channel_name']);
		return;
	}


	if($arr['location'])
		return;

	// send to public relay server - not ready for prime time

	if(($arr['top_level_post']) && (! $arr['env_recips'])) {
		// Add the relay server to the list of hubs.	
		// = array('hubloc_callback' => 'https://relay.iliketoast.net/receive', 'xchan_pubkey' => 'bogus');
	}

	$target_item = $arr['target_item'];

	if($target_item && array_key_exists('item_obscured',$target_item) && intval($target_item['item_obscured'])) {
		$key = get_config('system','prvkey');
		if($target_item['title'])
			$target_item['title'] = crypto_unencapsulate(json_decode($target_item['title'],true),$key);
		if($target_item['body'])
			$target_item['body'] = crypto_unencapsulate(json_decode($target_item['body'],true),$key);
	}

	$prv_recips = $arr['env_recips'];

315 316 317
	// The Diaspora profile message is unusual and must be handled independently

	$is_profile = false;
318 319

	if($arr['cmd'] === 'refresh_all' && $arr['recipients']) {
320 321 322 323 324 325 326 327
		$is_profile = true;
		$profile_visible = perm_is_allowed($arr['channel']['channel_id'],'','view_profile');

		if(! $profile_visible) {
			$prv_recips = array();
			foreach($arr['recipients'] as $r) {
				$prv_recips[] = array('hash' => trim($r,"'"));
			}
328 329
		}
	}
330 331


332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356
	if($prv_recips) {
		$hashes = array();

		// re-explode the recipients, but only for this hub/pod

		foreach($prv_recips as $recip)
			$hashes[] = "'" . $recip['hash'] . "'";

		$r = q("select * from xchan left join hubloc on xchan_hash = hubloc_hash where hubloc_url = '%s' 
			and xchan_hash in (" . implode(',', $hashes) . ") and xchan_network in ('diaspora', 'friendica-over-diaspora') ",
			dbesc($arr['hub']['hubloc_url'])
		);


		if(! $r) {
			logger('diaspora_process_outbound: no recipients');
			return; 
		}

		foreach($r as $contact) {

			// is $contact connected with this channel - and if the channel is cloned, also on this hub? 
			$single = deliverable_singleton($arr['channel']['channel_id'],$contact);
	
			if($arr['packet_type'] == 'refresh' && $single) {
357 358
				// This packet is sent privately to contacts, so we can always send the full profile (the last argument)
				$qi = diaspora_profile_change($arr['channel'],$contact,false,true);
359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405
				if($qi)
					$arr['queued'][] = $qi;
				return;
			}
			if($arr['mail'] && $single) {
				$qi = diaspora_send_mail($arr['item'],$arr['channel'],$contact);
				if($qi)
					$arr['queued'][] = $qi;
				continue;
			}

			if(! $arr['normal_mode'])
				continue;

			// special handling for send_upstream to public post, not checked for $single
			// all other public posts processed as public batches further below

			if((! $arr['private']) && ($arr['upstream'])) {
				$qi = diaspora_send_upstream($target_item,$arr['channel'],$contact, true);
				if($qi)
					$arr['queued'][] = $qi;
				continue;
			}

			if(! $contact['xchan_pubkey'])
				continue;

			// singletons will be sent upstream regardless of $single state. They may be rejected.

			if(intval($target_item['item_deleted']) && ($arr['top_level_post'] || $arr['upstream'])) { 
				$qi = diaspora_send_retraction($target_item,$arr['channel'],$contact);
				if($qi)
					$arr['queued'][] = $qi;
				continue;
			}

			if($arr['upstream']) {
				// send comments and likes to owner to relay
				$qi = diaspora_send_upstream($target_item,$arr['channel'],$contact,false,(($arr['uplink'] && !$arr['relay_to_owner']) ? true : false));
				if($qi)
					$arr['queued'][] = $qi;
				continue;
			}

			// downstream (private) posts

			if(! $single) {
406
				logger('Singleton private delivery ignored on this site.');
407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428
				continue;
			}
				
			if($arr['top_level_post']) {
				$qi = diaspora_send_status($target_item,$arr['channel'],$contact);
				if($qi) {
					foreach($qi as $q)
						$arr['queued'][] = $q;
				}
				continue;
			}
			else {
				// we are the relay - send comments, likes and relayable_retractions
				// (of comments and likes) to our conversants
				$qi = diaspora_send_downstream($target_item,$arr['channel'],$contact);
				if($qi)
					$arr['queued'][] = $qi;
				continue;
			}
		}
	}
	else {
429

430 431 432 433
		// public message

		$contact = $arr['hub'];

434 435 436 437 438 439 440
		if($arr['packet_type'] === 'keychange') {
			$target_item = get_pconfig($arr['channel']['channel_id'],'system','keychange');
			$qi = diaspora_send_migration($target_item,$arr['channel'],$contact,true);
			if($qi)
				$arr['queued'][] = $qi;
			return;
		}
441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458
		if(intval($target_item['item_deleted']) 
			&& ($target_item['mid'] === $target_item['parent_mid'])) {
			// top-level retraction
			logger('delivery: diaspora retract: ' . $loc);
			$qi = diaspora_send_retraction($target_item,$arr['channel'],$contact,true);
			if($qi)
				$arr['queued'][] = $qi;
			return;
		}
		elseif($target_item['mid'] !== $target_item['parent_mid']) {
			// we are the relay - send comments, likes and relayable_retractions to our conversants
			logger('delivery: diaspora relay: ' . $loc);
			$qi = diaspora_send_downstream($target_item,$arr['channel'],$contact,true);
			if($qi)
				$arr['queued'][] = $qi;
			return;
		}
		elseif($arr['top_level_post']) {
459
			if(perm_is_allowed($arr['channel']['channel_id'],'','view_stream',false)) {
460 461 462 463 464 465 466 467 468 469
				logger('delivery: diaspora status: ' . $loc);
				$qi = diaspora_send_status($target_item,$arr['channel'],$contact,true);
				if($qi) {
					foreach($qi as $q)
						$arr['queued'][] = $q;
				}
				return;
			}
		}
	}
470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487

	if($is_profile) {

		// with either a public or private profile, send a profile message to the public endpoint of 
		// each hub. $profile_visible indicates if the recipients can see all the data or a limited subset.
		// @todo also find any other Diaspora pods who should get this message.

		$contact = $arr['hub'];
		$single = deliverable_singleton($arr['channel']['channel_id'],$contact);
	
		if($arr['packet_type'] == 'refresh' && $single) {
			$qi = diaspora_profile_change($arr['channel'],$contact,true,$profile_visible);
			if($qi)
				$arr['queued'][] = $qi;
			return;
		}
	}

488 489 490 491 492 493 494 495 496
}





function diaspora_queue($owner,$contact,$slap,$public_batch,$message_id = '') {


Mario's avatar
Mario committed
497
	$allowed = Apps::addon_app_installed($owner['channel_id'], 'diaspora');
498 499 500 501 502 503 504 505 506 507 508 509 510

	if(! intval($allowed)) {
		return false;
	}

	if($public_batch)
		$dest_url = $contact['hubloc_callback'] . '/public';
	else
		$dest_url = $contact['hubloc_callback'] . '/users/' . $contact['hubloc_guid'];


	logger('diaspora_queue: URL: ' . $dest_url, LOGGER_DEBUG);	

511 512
	if(intval(get_config('system','diaspora_test')) || intval(get_pconfig($owner['channel_id'],'system','diaspora_test'))) {
		logger('diaspora test mode - delivery disabled');
513
		return false;
514
	}
515 516 517 518 519 520 521 522 523

	$hash = random_string();

	logger('diaspora_queue: ' . $hash . ' ' . $dest_url, LOGGER_DEBUG);

	queue_insert(array(
		'hash'       => $hash,
		'account_id' => $owner['channel_account_id'],
		'channel_id' => $owner['channel_id'],
524
		'driver'     => 'diaspora',
525 526 527 528 529 530 531 532 533 534 535
		'posturl'    => $dest_url,
		'notify'     => '',
		'msg'        => $slap
	));

	if($message_id && (! get_config('system','disable_dreport'))) {
		q("insert into dreport ( dreport_mid, dreport_site, dreport_recip, dreport_result, dreport_time, dreport_xchan, dreport_queue ) values ( '%s','%s','%s','%s','%s','%s','%s' ) ",
			dbesc($message_id),
			dbesc($dest_url),
			dbesc($dest_url),
			dbesc('queued'),
536
			dbescdate(datetime_convert()),
537 538 539 540 541 542 543 544 545 546
			dbesc($owner['channel_hash']),
			dbesc($hash)
		);
	}

	return $hash;

}


547
function diaspora_follow_allow(&$b) {
548 549 550 551

	if($b['xchan']['xchan_network'] !== 'diaspora' && $b['xchan']['xchan_network'] !== 'friendica-over-diaspora')
		return;

Mario's avatar
Mario committed
552 553
	$allowed = Apps::addon_app_installed($b['channel_id'], 'diaspora');

554 555 556 557 558 559 560
	if($allowed === false)
		$allowed = 1;
	$b['allowed'] = $allowed;
	$b['singleton'] = 1;  // this network does not support channel clones
}


561
function diaspora_discover(&$b) {
562

563 564 565 566
	require_once('include/network.php');

	$webbie = $b['address'];

567 568 569 570 571
	$protocol = $b['protocol'];
	if($protocol && strtolower($protocol) !== 'diaspora')
		return;


572 573 574 575 576 577 578
	$result = array();
	$network = null;
	$diaspora = false;

	$diaspora_base = '';
	$diaspora_guid = '';
	$diaspora_key = '';
579 580
	$guid = '';

581 582
	$dfrn = false;

583 584 585 586 587 588 589
	$x = $b['webfinger'];

	if($x && array_key_exists('links',$x) && $x['links']) {
		foreach($x['links'] as $link) {
			if(array_key_exists('rel',$link)) {

				if($link['rel'] === NAMESPACE_DFRN)
Zot's avatar
Zot committed
590
					$dfrn = escape_tags($link['href']);				
591 592

				if($link['rel'] === 'http://joindiaspora.com/seed_location') {
Zot's avatar
Zot committed
593
					$diaspora_base = escape_tags($link['href']);
594 595 596
					$diaspora = true;
				}
				if($link['rel'] === 'http://joindiaspora.com/guid') {
Zot's avatar
Zot committed
597
					$diaspora_guid = escape_tags($link['href']);
598 599 600
					$diaspora = true;
				}
				if($link['rel'] === 'diaspora-public-key') {
Zot's avatar
Zot committed
601
					$diaspora_key = escape_tags(base64_decode($link['href']));
602 603 604 605 606 607 608
					if(strstr($diaspora_key,'RSA '))
						$pubkey = rsatopem($diaspora_key);
					else
						$pubkey = $diaspora_key;
					$diaspora = true;
				}
				if($link['rel'] === 'http://microformats.org/profile/hcard')
Zot's avatar
Zot committed
609
					$hcard = escape_tags($link['href']);
610
				if($link['rel'] === 'http://webfinger.net/rel/profile-page')
Zot's avatar
Zot committed
611
					$profile = escape_tags($link['href']);
612 613 614 615
			}
		}
	}

Zot's avatar
Zot committed
616
	if(! ($diaspora && $diaspora_base)) {
617 618 619 620 621 622 623
		$x = false;
	}

	if(! $x) {
		$x = old_webfinger($webbie);
	}

624 625 626
	if($x) {
		logger('old_webfinger: ' . print_r($x,true));
		foreach($x as $link) {
Zot's avatar
Zot committed
627 628
			if(is_array($link)) {
				if($link['@attributes']['rel'] === NAMESPACE_DFRN)
Zot's avatar
Zot committed
629
					$dfrn = escape_tags(unamp($link['@attributes']['href']));				
Zot's avatar
Zot committed
630
				if($link['@attributes']['rel'] === 'http://microformats.org/profile/hcard')
Zot's avatar
Zot committed
631
					$hcard = escape_tags(unamp($link['@attributes']['href']));
Zot's avatar
Zot committed
632
				if($link['@attributes']['rel'] === 'http://webfinger.net/rel/profile-page')
Zot's avatar
Zot committed
633
					$profile = escape_tags(unamp($link['@attributes']['href']));
Zot's avatar
Zot committed
634
				if($link['@attributes']['rel'] === 'http://joindiaspora.com/seed_location') {
Zot's avatar
Zot committed
635
					$diaspora_base = escape_tags(unamp($link['@attributes']['href']));
Zot's avatar
Zot committed
636 637 638 639
					$diaspora = true;
				}
			
				if($link['@attributes']['rel'] === 'http://joindiaspora.com/guid') {
Zot's avatar
Zot committed
640
					$diaspora_guid = escape_tags(unamp($link['@attributes']['href']));
Zot's avatar
Zot committed
641 642 643
					$diaspora = true;
				}
				if($link['@attributes']['rel'] === 'diaspora-public-key') {
Zot's avatar
Zot committed
644
					$diaspora_key = escape_tags(base64_decode(unamp($link['@attributes']['href'])));
Zot's avatar
Zot committed
645 646 647 648 649 650
					if(strstr($diaspora_key,'RSA '))
						$pubkey = rsatopem($diaspora_key);
					else
						$pubkey = $diaspora_key;
					$diaspora = true;
				}
651 652
			}
		}
653
	}
654

655 656 657 658 659
	if($diaspora && $diaspora_base) {

		if($diaspora_guid)
			$guid = $diaspora_guid;

660
		$diaspora_base = trim($diaspora_base,'/');
661

662
		$notify = $diaspora_base . '/receive';
663

664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680
		if(strpos($webbie,'@')) {
			$addr = str_replace('acct:', '', $webbie);
			$hostname = substr($webbie,strpos($webbie,'@')+1);
		}
		$network = 'diaspora';
		// until we get a dfrn layer, we'll use diaspora protocols for Friendica,
		// but give it a different network so we can go back and fix these when we get proper support. 
		// It really should be just 'friendica' but we also want to distinguish
		// between Friendica sites that we can use D* protocols with and those we can't.
		// Some Friendica sites will have Diaspora disabled. 
		if($dfrn)
			$network = 'friendica-over-diaspora';
		if($hcard) {
			$vcard = scrape_vcard($hcard);
			$vcard['nick'] = substr($webbie,0,strpos($webbie,'@'));
			if(! $vcard['fn'])
				$vcard['fn'] = $webbie;
681 682
			if(($vcard['uid']) && (! $diaspora_guid))
				$diaspora_guid = $guid = $vcard['uid'];
Zot's avatar
Zot committed
683 684 685 686 687 688 689 690 691

			if($vcard['public_key']) {
				$diaspora_key = $vcard['public_key'];
				if(strstr($diaspora_key,'RSA '))
					$pubkey = rsatopem($diaspora_key);
				else
					$pubkey = $diaspora_key;
			}

692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707
		} 

		$r = q("select * from xchan where xchan_hash = '%s' limit 1",
			dbesc($addr)
		);

		/**
		 *
		 * Diaspora communications are notoriously unreliable and receiving profile update messages (indeed any messages) 
		 * are pretty much random luck. We'll check the timestamp of the xchan_name_date at a higher level and refresh
		 * this record once a month; because if you miss a profile update message and they update their profile photo or name 
		 * you're otherwise stuck with stale info until they change their profile again - which could be years from now. 
		 *
		 */  			

		if($r) {
Zot's avatar
Zot committed
708
			$r = q("update xchan set xchan_name = '%s', xchan_network = '%s', xchan_name_date = '%s', xchan_pubkey = '%s' where xchan_hash = '%s'",
709 710
				dbesc($vcard['fn']),
				dbesc($network),
711
				dbescdate(datetime_convert()),
Zot's avatar
Zot committed
712
				dbesc($pubkey),
713 714
				dbesc($addr)
			);
715 716 717 718 719 720 721 722 723 724 725 726 727
		}
		else {
			$r = xchan_store_lowlevel(
				[
					'xchan_hash'         => $addr,
					'xchan_guid'         => $guid,
					'xchan_pubkey'       => $pubkey,
					'xchan_addr'         => $addr,
					'xchan_url'          => $profile,
					'xchan_name'         => $vcard['fn'],
					'xchan_name_date'    => datetime_convert(),
					'xchan_network'      => $network
				]
728
			);
729
		}
730

731 732 733
		$r = q("select * from hubloc where hubloc_hash = '%s' limit 1",
			dbesc($webbie)
		);
734

735 736 737 738 739 740 741 742 743 744 745 746 747
		if(! $r) {
			$r = hubloc_store_lowlevel(
				[
					'hubloc_guid'     => $guid,
					'hubloc_hash'     => $addr,
					'hubloc_addr'     => $addr,
					'hubloc_network'  => $network,
					'hubloc_url'      => trim($diaspora_base,'/'),
					'hubloc_host'     => $hostname,
					'hubloc_callback' => $notify,
					'hubloc_updated'  => datetime_convert(),
					'hubloc_primary'  => 1
				]
748 749 750
			);
		}

751 752
		$photos = import_xchan_photo($vcard['photo'],$addr);
		$r = q("update xchan set xchan_photo_date = '%s', xchan_photo_l = '%s', xchan_photo_m = '%s', xchan_photo_s = '%s', xchan_photo_mimetype = '%s' where xchan_hash = '%s'",
753
			dbescdate(datetime_convert()),
754 755 756 757 758 759
			dbesc($photos[0]),
			dbesc($photos[1]),
			dbesc($photos[2]),
			dbesc($photos[3]),
			dbesc($addr)
		);
Zot's avatar
Zot committed
760 761

		$b['xchan']   = $addr;
762
		$b['success'] = true;
763 764 765
	}
}

766
function diaspora_post_local(&$item) {
767 768 769 770 771 772 773 774 775 776 777 778

	require_once('include/markdown.php');

	if($item['mid'] === $item['parent_mid'])
		return;

	$meta = null;

	$author = channelx_by_hash($item['author_xchan']);
	if($author) {

		$handle = channel_reddress($author);
779
		$meta = null;
780

781
		if(activity_match($item['verb'], [ ACTIVITY_LIKE, ACTIVITY_DISLIKE ])) {
782
			if(activity_match($item['obj_type'], [ ACTIVITY_OBJ_NOTE, ACTIVITY_OBJ_ACTIVITY, ACTIVITY_OBJ_COMMENT ])) {
783
				$meta = [
Zot's avatar
Zot committed
784
					'positive'        => (($item['verb'] === ACTIVITY_LIKE) ? 'true' : 'false'),
785 786
					'guid'            => $item['mid'],
				];
787 788
				if(defined('DIASPORA_V2')) {
					$meta['author']      = $handle;
789 790
					$meta['parent_type'] = (($item['thr_parent'] === $item['parent_mid']) ? 'Post' : 'Comment');
					$meta['parent_guid'] = $item['thr_parent'];
791 792 793 794
				}
				else {
					$meta['diaspora_handle'] = $handle;
					$meta['target_type']     = 'Post';
795
					$meta['parent_guid']     = $item['parent_mid'];
796
				}
797 798
			}
		}
Mario's avatar
Mario committed
799
		elseif(activity_match($item['verb'], [ ACTIVITY_ATTEND, ACTIVITY_ATTENDNO, ACTIVITY_ATTENDMAYBE ])) {
800 801 802 803 804 805 806 807 808
			if(activity_match($item['obj_type'], [ ACTIVITY_OBJ_NOTE ])) {
				$status = 'tentative';
				if(activity_match($item['verb'], [ ACTIVITY_ATTEND ]))
					$status = 'accepted';
				if(activity_match($item['verb'], [ ACTIVITY_ATTENDNO ]))
					$status = 'declined';

				$rawobj = ((is_array($item['obj'])) ? $item['obj'] : json_decode($item['obj'],true));
				if($rawobj) {
Zot's avatar
Zot committed
809
					$ev = bbtoevent($rawobj);
810 811 812 813 814 815 816 817 818 819 820
					if($ev && $ev['hash'] && defined('DIASPORA_V2')) {
						$meta = [
							'author' => $handle,
							'guid'   => $item['mid'],
							'parent_guid' => $ev['hash'],
							'status'      => $status
						];
					}
				}
			}
		}
821
		else {
822
			$body = bb_to_markdown($item['body'], [ 'diaspora' ]);
823 824 825 826

			$meta = [
				'guid'            => $item['mid'],
				'parent_guid'     => $item['parent_mid'],
827
				'text'            => $body
828
			];
829 830

			if(defined('DIASPORA_V2')) {
Zot's avatar
Zot committed
831
				$meta['author']     = $handle;
832
				$meta['created_at'] = datetime_convert('UTC','UTC', $item['created'], ATOM_TIME );
833 834 835
				if($item['edited'] > $item['created']) {
					$meta['edited_at'] = datetime_convert('UTC','UTC', $item['edited'], ATOM_TIME );
				}
836 837
			}
			else {
Zot's avatar
Zot committed
838
				$meta['diaspora_handle'] = $handle;
839 840
			}

841 842
		}

843 844 845
		if(! $meta)
			return;

846
		$meta['author_signature'] = diaspora_sign_fields($meta, $author['channel_prvkey']);
847
		if($item['author_xchan'] === $item['owner_xchan']) {
848
			$meta['parent_author_signature'] = diaspora_sign_fields($meta,$author['channel_prvkey']);
849
		}
850 851 852 853 854 855 856 857
	}

	if($meta)
		set_iconfig($item,'diaspora','fields', $meta, true);


}

858
function diaspora_create_identity($b) {
Zot's avatar
Zot committed
859
	if(get_config('system','diaspora_allowed')) {
860
		Apps::app_install($b, 'Diaspora Protocol');
861 862 863
	}
}

864
function diaspora_import_foreign_channel_data(&$data) {
865 866 867 868 869 870 871 872 873

	if(array_key_exists('user',$data) && array_key_exists('version',$data)) {
		require_once('addon/diaspora/import_diaspora.php');
		$data['handled'] = true;
		import_diaspora_account($data);
		return;
	}
}
		
874
function diaspora_profile_sidebar(&$x) {
875 876 877

	$profile = $x['profile'];

Mario's avatar
Mario committed
878 879
	if(! Apps::addon_app_installed($profile['channel_id'], 'diaspora'))
		return;
Zot's avatar
Zot committed
880

881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901
	$firstname = ((strpos($profile['channel_name'],' '))
		? trim(substr($profile['channel_name'],0,strpos($profile['channel_name'],' '))) : $profile['channel_name']);
	$lastname = (($firstname === $profile['channel_name']) 
			? '' : trim(substr($profile['channel_name'],strlen($firstname))));

	$vcarddata = replace_macros(get_markup_template('diaspora_vcard.tpl','addon/diaspora'), 
		[
			'$podloc'     => z_root(),
			'$guid'       => $profile['channel_guid'] . str_replace('.','',App::get_hostname()),
			'$pubkey'     => pemtorsa($profile['channel_pubkey']),
			'$searchable' => ((observer_prohibited()) ? 'false' : 'true'),
			'$nickname'   => $profile['channel_address'],
			'$fullname'   => $profile['channel_name'],
			'$firstname'  => $firstname,
			'$lastname'   => $lastname,
			'$photo300'   => z_root() . '/photo/profile/300/' . $profile['uid'] . '.jpg',
			'$photo100'   => z_root() . '/photo/profile/100/' . $profile['uid'] . '.jpg',
			'$photo50'    => z_root() . '/photo/profile/50/'  . $profile['uid'] . '.jpg',
		]
	);

902
	$x['entry'] = str_replace('<div class="hcard-addon"></div>',$vcarddata . '<div class="hcard-addon"></div>', $x['entry']);
903 904 905 906

}


907
function diaspora_import_author(&$b) {
908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937

	$x = $b['author'];

	if(strpos($x['network'],'diaspora') === false)
		return;

	if(! $x['address'])
		return;

	$r = q("select * from xchan where xchan_addr = '%s' limit 1",
		dbesc($x['address'])
	);
	if($r) {
		logger('in_cache: ' . $x['address'], LOGGER_DATA);
		$b['result'] = $r[0]['xchan_hash'];
		return;
	}

	if(discover_by_webbie($x['address'])) {
		$r = q("select xchan_hash from xchan where xchan_addr = '%s' limit 1",
			dbesc($x['address'])
		);
		if($r) {
			$b['result'] = $r[0]['xchan_hash'];
			return;
		}
	}

	return;

938 939
}

940

941
function diaspora_md_mention_callback($matches) {
942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969

    $webbie = $matches[2] . '@' . $matches[3];
    $link = '';
    if($webbie) {
        $r = q("select * from hubloc left join xchan on hubloc_hash = xchan_hash where hubloc_addr = '%s' limit 1",
            dbesc($webbie)
        );
        if(! $r) {
            $x = discover_by_webbie($webbie);
            if($x) {
                $r = q("select * from hubloc left join xchan on hubloc_hash = xchan_hash where hubloc_addr = '%s' limit 1",
                    dbesc($webbie)
                );
            }
        }
        if($r)
            $link = $r[0]['xchan_url'];
    }
    if(! $link)
        $link = 'https://' . $matches[3] . '/u/' . $matches[2];

    if($r && $r[0]['hubloc_network'] === 'zot')
        return '@[zrl=' . $link . ']' . trim($matches[1]) . ((substr($matches[0],-1,1) === '+') ? '+' : '') . '[/zrl]' ;
    else
        return '@[url=' . $link . ']' . trim($matches[1]) . ((substr($matches[0],-1,1) === '+') ? '+' : '') . '[/url]' ;

}

970
function diaspora_md_mention_callback2($matches) {
971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001

    $webbie = $matches[1] . '@' . $matches[2];
    $link = '';
    if($webbie) {
        $r = q("select * from hubloc left join xchan on hubloc_hash = xchan_hash where hubloc_addr = '%s' limit 1",
            dbesc($webbie)
        );
        if(! $r) {
            $x = discover_by_webbie($webbie);
            if($x) {
                $r = q("select * from hubloc left join xchan on hubloc_hash = xchan_hash where hubloc_addr = '%s' limit 1",
                    dbesc($webbie)
                );
            }
        }
        if($r)
            $link = $r[0]['xchan_url'];
    }

    $name = (($r) ? $r[0]['xchan_name'] : $matches[1]);

    if(! $link)
        $link = 'https://' . $matches[2] . '/u/' . $matches[1];

    if($r && $r[0]['hubloc_network'] === 'zot')
        return '@[zrl=' . $link . ']' . trim($name) . ((substr($matches[0],-1,1) === '+') ? '+' : '') . '[/zrl]' ;
    else
        return '@[url=' . $link . ']' . trim($name) . ((substr($matches[0],-1,1) === '+') ? '+' : '') . '[/url]' ;

}

1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035
function diaspora_forum_mention_callback($matches) {

    $webbie = $matches[1] . '@' . $matches[2];
    $link = '';
    if($webbie) {
        $r = q("select * from hubloc left join xchan on hubloc_hash = xchan_hash where hubloc_addr = '%s' limit 1",
            dbesc($webbie)
        );
        if(! $r) {
            $x = discover_by_webbie($webbie);
            if($x) {
                $r = q("select * from hubloc left join xchan on hubloc_hash = xchan_hash where hubloc_addr = '%s' limit 1",
                    dbesc($webbie)
                );
            }
        }
        if($r)
            $link = $r[0]['xchan_url'];
    }

    $name = (($r) ? $r[0]['xchan_name'] : $matches[1]);

    if(! $link)
        $link = 'https://' . $matches[2] . '/u/' . $matches[1];

    if($r && $r[0]['hubloc_network'] === 'zot')
        return '![zrl=' . $link . ']' . trim($name) . '[/zrl]' ;
    else
        return '![url=' . $link . ']' . trim($name) . '[/url]' ;

}



Zot's avatar
Zot committed
1036 1037 1038
function diaspora_markdown_to_bb_init(&$x) {

	$s = $x['text'];
Zot's avatar
Zot committed
1039
	if(! (array_key_exists('diaspora',$x['options']) && intval($x['options']['diaspora'])))
Zot's avatar
Zot committed
1040
		return;
1041

1042 1043
	// if empty link text replace with the url
	$s = preg_replace("/\[\]\((.*?)\)/ism",'[$1]($1)',$s);
1044

1045 1046
	$s = preg_replace_callback("/\!*\[(.*?)\]\((.*?)\)/ism",'diaspora_markdown_media_cb',$s);

1047 1048
  	$s = preg_replace_callback('/\@\{(.+?)\; (.+?)\@(.+?)\}\+/','diaspora_md_mention_callback',$s);
	$s = preg_replace_callback('/\@\{(.+?)\; (.+?)\@(.+?)\}/','diaspora_md_mention_callback',$s);
1049

1050 1051
	$s = preg_replace_callback('/\@\{(.+?)\@(.+?)\}\+/','diaspora_md_mention_callback2',$s);
	$s = preg_replace_callback('/\@\{(.+?)\@(.+?)\}/','diaspora_md_mention_callback2',$s);
1052

1053
	$s = preg_replace_callback('/\!\{(.+?)\@(.+?)\}/','diaspora_forum_mention_callback',$s);
1054 1055


1056 1057 1058 1059 1060
	// replace diaspora://$author_handle/$post_type/$guid with a local representation.
	// Ideally we should eventually pass the author_handle and post_type to mod_display and from a hook
	// fetch the post from the source if it isn't already available locally. 

	$s = preg_replace('#diaspora://(.*?)/(.*?)/([^\s\]]*)#ism', z_root() . '/display/$3', $s);
1061

Zot's avatar
Zot committed
1062 1063
	$x['text'] = $s;

1064 1065 1066
}


1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084
function diaspora_markdown_media_cb($matches) {

	$audios = [ '.mp3', '.ogg', '.oga', '.m4a' ];
	$videos = [ '.mp4', '.ogv', '.ogm', '.webm', '.opus' ];

	foreach($audios as $aud) {
		if(strpos(strtolower($matches[2]),$aud) !== false)
			return '[audio]' . $matches[2] . '[/audio]';
	}
	foreach($videos as $vid) {
		if(strpos(strtolower($matches[2]),$vid) !== false)
			return '[video]' . $matches[2] . '[/video]';
	}

	return $matches[0];

}

1085 1086 1087 1088 1089 1090
function diaspora_bb_to_markdown_bb(&$x) {

	if(! in_array('diaspora',$x['options']))
		return;	

	$Text = $x['bbcode'];
1091 1092 1093 1094

	$Text = preg_replace_callback('/\@\!?\[([zu])rl\=(\w+.*?)\](\w+.*?)\[\/([zu])rl\]/i', 
		'diaspora_bb_to_markdown_mention_callback', $Text);

1095 1096 1097
	$Text = preg_replace_callback('/\!\[([zu])rl\=(\w+.*?)\](\w+.*?)\[\/([zu])rl\]/i', 
		'diaspora_bb_to_markdown_fmention_callback', $Text);

1098
	// strip map and embed tags, as the rendering is performed in bbcode() and the resulting output
1099 1100 1101 1102 1103 1104
	// is not compatible with Diaspora (at least in the case of openstreetmap and probably
	// due to the inclusion of an html iframe)

	$Text = preg_replace("/\[map\=(.*?)\]/ism", '$1', $Text);
	$Text = preg_replace("/\[map\](.*?)\[\/map\]/ism", '$1', $Text);

1105 1106
	$Text = preg_replace("/\[embed\](.*?)\[\/embed\]/ism", '$1', $Text);

1107
	$x['bbcode'] = $Text;
1108 1109
}

1110 1111


1112 1113
function diaspora_bb_to_markdown_mention_callback($match) {

1114
    $r = q("select xchan_addr, xchan_url from xchan where xchan_url = '%s' and xchan_network not in('rss', 'anon', 'unknown')",
1115 1116 1117
        dbesc($match[2])
    );

1118 1119 1120 1121
    if($r) {
        $addr = (($r[0]['xchan_addr']) ? $r[0]['xchan_addr'] : $r[0]['xchan_url']);
        return '@{' . $addr . '}';
    }
1122 1123 1124 1125

    return '@' . $match[3];
}

1126 1127 1128

function diaspora_bb_to_markdown_fmention_callback($match) {

1129
    $r = q("select xchan_addr, xchan_url from xchan where xchan_url = '%s' and xchan_network not in('rss', 'anon', 'unknown')",
1130 1131 1132
        dbesc($match[2])
    );

1133 1134 1135 1136
    if($r) {
        $addr = (($r[0]['xchan_addr']) ? $r[0]['xchan_addr'] : $r[0]['xchan_url']);
        return '!{' . $addr . '}';
    }
1137 1138 1139 1140

    return '!' . $match[3];
}

1141
function diaspora_service_plink(&$b) {
Zot's avatar
Zot committed
1142 1143 1144 1145 1146 1147 1148 1149 1150 1151
	$contact = $b['xchan'];
	$url     = $b['url'];
	$guid    = $b['guid'];

	if($contact['xchan_network'] === 'diaspora')
		$b['plink'] = $url . '/posts/' . $guid;
	if($contact['xchan_network'] === 'friendica-over-diaspora')
		$b['plink'] = $url . '/display/' . $handle . '/' . $guid;


1152 1153
}

1154
function diaspora_can_comment_on_post(&$b) {
1155
	if(local_channel() && strpos($b['item']['comment_policy'],'diaspora') !== false) {
Mario's avatar
Mario committed
1156
		$b['allowed'] = Apps::addon_app_installed(local_channel(), 'diaspora');
1157
	}
1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168
}


function diaspora_queue_deliver(&$b) {

	$outq = $b['outq'];
	$base = $b['base'];
	$immediate = $b['immediate'];


	if($outq['outq_driver'] === 'diaspora') {
1169
		$b['handled'] = true;
1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186
		$first_char = substr(trim($outq['outq_msg']),0,1);

		if($first_char === '{')
			$content_type = 'application/json';
		elseif($first_char === '<')
			$content_type = 'application/magic-envelope+xml';
		else
			$content_type = 'application/x-www-form-urlencoded';


		$retries = 0;
		$result = z_post_url($outq['outq_posturl'],$outq['outq_msg'],$retries,[ 'headers' => [ 'Content-type: ' . $content_type ]] );

		if($result['success'] && $result['return_code'] < 300) {
			logger('deliver: queue post success to ' . $outq['outq_posturl'], LOGGER_DEBUG);
			if($base) {
				q("update site set site_update = '%s', site_dead = 0 where site_url = '%s' ",
1187
					dbescdate(datetime_convert()),
1188 1189 1190 1191 1192
					dbesc($base)
				);
			}
			q("update dreport set dreport_result = '%s', dreport_time = '%s' where dreport_queue = '%s'",
				dbesc('accepted for delivery'),
1193
				dbescdate(datetime_convert()),
1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213
				dbesc($outq['outq_hash'])
			);
			remove_queue_item($outq['outq_hash']);

			// server is responding - see if anything else is going to this destination and is piled up 
			// and try to send some more. We're relying on the fact that do_delivery() results in an 
			// immediate delivery otherwise we could get into a queue loop. 

			if(! $immediate) {
				$x = q("select outq_hash from outq where outq_posturl = '%s' and outq_delivered = 0",
					dbesc($outq['outq_posturl'])
				);

				$piled_up = array();
				if($x) {
					foreach($x as $xx) {
						 $piled_up[] = $xx['outq_hash'];
					}
				}
				if($piled_up) {
Zot's avatar
Zot committed
1214 1215 1216 1217 1218 1219 1220 1221

					// add a pre-deliver interval, this should not be necessary

					$interval = ((get_config('system','delivery_interval') !== false)
						? intval(get_config('system','delivery_interval')) : 2 );
					if($interval)
						@time_sleep_until(microtime(true) + (float) $interval);

Zot's avatar
Zot committed
1222
					do_delivery($piled_up,true);
1223 1224 1225 1226 1227
				}
			}
		}
	}
}
1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255


function diaspora_create_event($ev, $author) {

	require_once('include/html2plain.php');
	require_once('include/markdown.php');

	$ret = [];

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

	$ret['author']  = $author;
	$ret['guid']    = $ev['event_hash'];
	$ret['summary'] = html2plain($ev['summary']);
	$ret['start']   = $ev['dtstart'];
	if(! $ev['nofinish'])
		$ret['end'] = $ev['dtend'];
	if(! $ev['adjust'])
		$ret['all_day'] = true;

	$ret['description'] = html2markdown($ev['description'] . (($ev['location']) ? "\n\n" . $ev['location'] : ''));
	if($ev['created'] !== $ev['edited'])
		$ret['edited_at'] = datetime_convert('UTC','UTC',$ev['edited'], ATOM_TIME);

	return $ret;


Mario's avatar
Mario committed
1256
}