pubcrawl.php 30.3 KB
Newer Older
1 2 3
<?php

/**
4
 * Name: PubCrawl
5 6 7 8
 * Description: An unapologetically non-compliant ActivityPub Protocol implemention
 * 
 */

Zot's avatar
Zot committed
9 10 11 12 13 14
/**
 * This connector is undergoing heavy development at the moment. If you think some shortcuts were taken 
 * - you are probably right. These will be cleaned up and moved to generalised interfaces once we actually 
 * get communication flowing. 
 */

Mario's avatar
Mario committed
15 16 17
use Zotlabs\Lib\Apps;
use Zotlabs\Extend\Hook;
use Zotlabs\Extend\Route;
Zot's avatar
Zot committed
18
use Zotlabs\Lib\ActivityStreams;
19

Mario's avatar
Mario committed
20
require_once('addon/pubcrawl/as.php');
21 22

function pubcrawl_load() {
Mario's avatar
Mario committed
23
	Hook::register_array('addon/pubcrawl/pubcrawl.php', [
24
		'module_loaded'              => 'pubcrawl_load_module',
25
		'webfinger'                  => 'pubcrawl_webfinger',
26 27
		'channel_mod_init'           => 'pubcrawl_channel_mod_init',
		'profile_mod_init'           => 'pubcrawl_profile_mod_init',
28
		'follow_mod_init'            => 'pubcrawl_follow_mod_init',
29
		'item_mod_init'              => 'pubcrawl_item_mod_init',
30
		'thing_mod_init'             => 'pubcrawl_thing_mod_init',
Zot's avatar
Zot committed
31
		'locs_mod_init'              => 'pubcrawl_locs_mod_init',
32
		'follow_allow'               => 'pubcrawl_follow_allow',
Zot's avatar
Zot committed
33
		'discover_channel_webfinger' => 'pubcrawl_discover_channel_webfinger',
34
		'permissions_create'         => 'pubcrawl_permissions_create',
Zot's avatar
Zot committed
35
		'permissions_accept'         => 'pubcrawl_permissions_accept',
Zot's avatar
Zot committed
36
		'connection_remove'          => 'pubcrawl_connection_remove',
Zot's avatar
Zot committed
37
		'notifier_hub'               => 'pubcrawl_notifier_process',
38
		'channel_links'              => 'pubcrawl_channel_links',
Zot's avatar
Zot committed
39
		'personal_xrd'               => 'pubcrawl_personal_xrd',
40
		'queue_deliver'              => 'pubcrawl_queue_deliver',
41
		'import_author'              => 'pubcrawl_import_author',
42
		'channel_protocols'          => 'pubcrawl_channel_protocols',
43
		'federated_transports'       => 'pubcrawl_federated_transports',
44 45
		'create_identity'            => 'pubcrawl_create_identity',
		'can_comment_on_post'        => 'pubcrawl_can_comment_on_post'
46
	]);
Mario's avatar
Mario committed
47
	Route::register('addon/pubcrawl/Mod_Pubcrawl.php','pubcrawl');
48 49 50
}

function pubcrawl_unload() {
Mario's avatar
Mario committed
51 52
	Hook::unregister_by_file('addon/pubcrawl/pubcrawl.php');
	Route::unregister('addon/pubcrawl/Mod_Pubcrawl.php','pubcrawl');
53 54 55
}


56 57
function pubcrawl_channel_protocols(&$b) {

58
	if(Apps::addon_app_installed($b['channel_id'],'pubcrawl'))
59 60 61 62
		$b['protocols'][] = 'activitypub';

}

63 64 65 66
function pubcrawl_federated_transports(&$x) {
	$x[] = 'ActivityPub';
}

67

68 69 70 71 72
function pubcrawl_follow_allow(&$b) {

	if($b['xchan']['xchan_network'] !== 'activitypub')
		return;

73
	$allowed = Apps::addon_app_installed($b['channel_id'],'pubcrawl');
74 75 76 77 78 79 80
	if($allowed === false)
		$allowed = 1;
	$b['allowed'] = $allowed;
	$b['singleton'] = 1;  // this network does not support channel clones

}

81 82
function pubcrawl_channel_links(&$b) {
	$c = channelx_by_nick($b['channel_address']);
83
	if($c && Apps::addon_app_installed($c['channel_id'],'pubcrawl')) {
84 85
		$b['channel_links'][] = [
			'rel' => 'alternate',
86
			'type' => 'application/ld+json; profile="https://www.w3.org/ns/activitystreams"',
87 88
			'url' => z_root() . '/channel/' . $c['channel_address']
		];
89 90 91 92 93
		$b['channel_links'][] = [
			'rel' => 'alternate',
			'type' => 'application/activity+json',
			'url' => z_root() . '/channel/' . $c['channel_address']
		];
94 95 96
	}
}

97
function pubcrawl_webfinger(&$b) {
98 99 100
	if(! $b['channel'])
		return;

Mario's avatar
Mario committed
101
	if(! Apps::addon_app_installed($b['channel']['channel_id'],'pubcrawl'))
102 103 104 105
		return;

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

106 107
	$b['result']['links'][] = [ 
		'rel'  => 'self', 
108
		'type' => 'application/ld+json; profile="https://www.w3.org/ns/activitystreams"',
109 110
		'href' => z_root() . '/channel/' . $b['channel']['channel_address']
	];
111 112 113 114 115
	$b['result']['links'][] = [ 
		'rel'  => 'self', 
		'type' => 'application/activity+json',
		'href' => z_root() . '/channel/' . $b['channel']['channel_address']
	];
116 117
}

Zot's avatar
Zot committed
118 119
function pubcrawl_personal_xrd(&$b) {

120
	if(! Apps::addon_app_installed($b['user']['channel_id'],'pubcrawl'))
Zot's avatar
Zot committed
121 122
		return;

123
	$s = '<Link rel="self" type="application/ld+json" href="' . z_root() . '/channel/' . $b['user']['channel_address'] . '" />';
Zot's avatar
Zot committed
124 125 126 127 128
	$s = '<Link rel="self" type="application/activity+json" href="' . z_root() . '/channel/' . $b['user']['channel_address'] . '" />';

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

}
129

Zot's avatar
Zot committed
130 131
function pubcrawl_discover_channel_webfinger(&$b) {

132 133
	$url      = $b['address'];
	$x        = $b['webfinger'];
134
	$protocol = $b['protocol'];
135

Zot's avatar
Zot committed
136 137
	logger('probing: activitypub');

138 139 140
	if($protocol && strtolower($protocol) !== 'activitypub')
		return;

Zot's avatar
Zot committed
141 142
	if(is_array($x)) {

143

Zot's avatar
Zot committed
144
		$address = EMPTY_STR;
145

Zot's avatar
Zot committed
146 147 148 149 150 151 152 153
		if(array_key_exists('subject',$x) && strpos($x['subject'],'acct:') === 0)
			$address = str_replace('acct:','',$x['subject']);
		if(array_key_exists('aliases',$x) && count($x['aliases'])) {
			foreach($x['aliases'] as $a) {
				if(strpos($a,'acct:') === 0) {
					$address = str_replace('acct:','',$a);
					break;
				}
154
			}
Zot's avatar
Zot committed
155 156 157 158 159 160 161 162 163 164 165 166
		}	

	    if(strpos($url,'@') && $x && array_key_exists('links',$x) && $x['links']) {
    	    foreach($x['links'] as $link) {
        	    if(array_key_exists('rel',$link) && array_key_exists('type',$link)) {
            	    if($link['rel'] === 'self' && ($link['type'] === 'application/activity+json' || strpos($link['type'],'ld+json') !== false)) {
						$url = $link['href'];
                	}
            	}
        	}
    	}
	}
167 168
	
	if(($url) && (strpos($url,'http') === 0)) {
169
		$x = as_fetch($url);
170
		if(! $x) {
171
			return;
172 173 174 175
		}
	}
	else {
		return;
176 177
	}

178
	$AS = new \Zotlabs\Lib\ActivityStreams($x);
179

180
	if(! $AS->is_valid()) {
181
		return;
182
	}
183 184 185 186

	// Now find the actor and see if there is something we can follow	

	$person_obj = null;
Zot's avatar
Zot committed
187
	if(in_array($AS->type, [ 'Application', 'Group', 'Organization', 'Person', 'Service' ])) {
188 189
		$person_obj = $AS->data;
	}
Zot's avatar
Zot committed
190
	elseif($AS->obj && ( in_array($AS->obj['type'], [ 'Application', 'Group', 'Organization', 'Person', 'Service' ] ))) {
191
		$person_obj = $AS->obj;
192 193 194 195 196
	}
	else {
		return;
	}

197
	as_actor_store($url,$person_obj);
198

199 200
	if($address) {
		q("update xchan set xchan_addr = '%s' where xchan_hash = '%s' and xchan_network = 'activitypub'",
201 202
			dbesc($address),
			dbesc($url)
203 204
		);
		q("update hubloc set hubloc_addr = '%s' where hubloc_hash = '%s' and hubloc_network = 'activitypub'",
205 206
			dbesc($address),
			dbesc($url)
207 208 209
		);
	}

Zot's avatar
Zot committed
210
	$b['xchan']   = $url;
211
	$b['success'] = true;
212 213 214

}

215 216
function pubcrawl_import_author(&$b) {

217
	if(! $b['author']['url'])
218 219
		return;

220
	$url = $b['author']['url'];
221 222 223 224 225 226 227 228 229 230 231 232

	// let somebody upgrade from an 'unknown' connection which has no xchan_addr
	$r = q("select xchan_hash, xchan_url, xchan_name, xchan_photo_s from xchan where xchan_url = '%s' limit 1",
		dbesc($url)
	);
	if(! $r) {
		$r = q("select xchan_hash, xchan_url, xchan_name, xchan_photo_s from xchan where xchan_hash = '%s' limit 1",
			dbesc($url)
		);
	}
	if($r) {
		logger('in_cache: ' . $r[0]['xchan_name'], LOGGER_DATA);
233 234
		$b['result'] = $r[0]['xchan_hash'];
		return;
235 236 237 238 239 240 241 242 243 244 245 246 247 248
	}

	$x = discover_by_webbie($url);

	if($x) {
		$r = q("select xchan_hash, xchan_url, xchan_name, xchan_photo_s from xchan where xchan_url = '%s' limit 1",
			dbesc($url)
		);
		if(! $r) {
			$r = q("select xchan_hash, xchan_url, xchan_name, xchan_photo_s from xchan where xchan_hash = '%s' limit 1",
				dbesc($url)
			);
		}
		if($r) {
249 250
			$b['result'] = $r[0]['xchan_hash'];
			return;
251 252 253 254 255 256 257
		}
	}

	return;

}

258 259

function pubcrawl_load_module(&$b) {
260

Zot's avatar
Zot committed
261
	//logger('module: ' . \App::$query_string);
262

263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282
	if($b['module'] === 'inbox') {
		require_once('addon/pubcrawl/Mod_Inbox.php');
		$b['controller'] = new \Zotlabs\Module\Inbox();
		$b['installed'] = true;
	}
	if($b['module'] === 'outbox') {
		require_once('addon/pubcrawl/Mod_Outbox.php');
		$b['controller'] = new \Zotlabs\Module\Outbox();
		$b['installed'] = true;
	}
	if($b['module'] === 'activity') {
		require_once('addon/pubcrawl/Mod_Activity.php');
		$b['controller'] = new \Zotlabs\Module\Activity();
		$b['installed'] = true;
	}
	if($b['module'] === 'nullbox') {
		require_once('addon/pubcrawl/Mod_Nullbox.php');
		$b['controller'] = new \Zotlabs\Module\Nullbox();
		$b['installed'] = true;
	}
Zot's avatar
Zot committed
283 284 285 286 287
	if($b['module'] === 'ap_probe') {
		require_once('addon/pubcrawl/Mod_Ap_probe.php');
		$b['controller'] = new \Zotlabs\Module\Ap_probe();
		$b['installed'] = true;
	}
Zot's avatar
Zot committed
288 289 290 291 292
	if($b['module'] === 'apschema') {
		require_once('addon/pubcrawl/Mod_Apschema.php');
		$b['controller'] = new \Zotlabs\Module\Apschema();
		$b['installed'] = true;
	}
Zot's avatar
Zot committed
293 294 295 296 297 298 299 300 301 302
	if($b['module'] === 'followers') {
		require_once('addon/pubcrawl/Mod_Followers.php');
		$b['controller'] = new \Zotlabs\Module\Followers();
		$b['installed'] = true;
	}
	if($b['module'] === 'following') {
		require_once('addon/pubcrawl/Mod_Following.php');
		$b['controller'] = new \Zotlabs\Module\Following();
		$b['installed'] = true;
	}
303 304 305 306 307
}


function pubcrawl_is_as_request() {

308 309 310
	if(strpos($_SERVER['HTTP_ACCEPT'],'activity') !== false) {
		logger('Accept: ' . $_SERVER['HTTP_ACCEPT'], LOGGER_DATA);
	}
311

312 313 314 315 316
	if($_REQUEST['module_format'] === 'json')
		return true;

	$x = getBestSupportedMimeType([
		'application/ld+json;profile="https://www.w3.org/ns/activitystreams"',
317
		'application/activity+json',
Zot's avatar
Zot committed
318
		'application/ld+json;profile="http://www.w3.org/ns/activitystreams"'
319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337
	]);

	return(($x) ? true : false);

}


function pubcrawl_magic_env_allowed() {

	$x = getBestSupportedMimeType([
		'application/magic-envelope+json'
	]);

	return(($x) ? true : false);
}

function pubcrawl_salmon_sign($data,$channel) {

  	$data      = base64url_encode($data, false); // do not strip padding
Zot's avatar
Zot committed
338
    $data_type = 'application/activity+json';
339 340
    $encoding  = 'base64url';
    $algorithm = 'RSA-SHA256';
341
    $keyhash   = base64url_encode(z_root() . '/channel/' . $channel['channel_address']);
342 343 344 345 346 347 348 349 350 351

    $data = str_replace(array(" ","\t","\r","\n"),array("","","",""),$data);

    // precomputed base64url encoding of data_type, encoding, algorithm concatenated with periods

    $precomputed = '.' . base64url_encode($data_type,false) . '.YmFzZTY0dXJs.UlNBLVNIQTI1Ng==';

    $signature  = base64url_encode(rsa_sign($data . $precomputed,$channel['channel_prvkey']));

    return ([
352 353 354 355 356 357
        'data'       => $data,
		'data_type'  => $data_type,
        'encoding'   => $encoding,
        'alg'        => $algorithm,
		'sigs'       => [
			'value'  => $signature,
358 359 360 361 362 363 364 365 366 367 368
			'key_id' => $keyhash
		]
	]);

}

function pubcrawl_channel_mod_init($x) {
	
	if(pubcrawl_is_as_request()) {
		$chan = channelx_by_nick(argv(1));
		if(! $chan)
369 370
			http_status_exit(404, 'Not found');

371
		if(! Apps::addon_app_installed($chan['channel_id'],'pubcrawl'))
372
			http_status_exit(404, 'Not found');
373

374 375 376 377
		$y = asencode_person($chan);
		if(! $y)
			http_status_exit(404, 'Not found');

378
		$x = array_merge(['@context' => [
Zot's avatar
Zot committed
379
			ACTIVITYSTREAMS_JSONLD_REV,
Zot's avatar
Zot committed
380
			'https://w3id.org/security/v1',
Zot's avatar
Zot committed
381
			z_root() . ZOT_APSCHEMA_REV
382
			]], $y);
383 384


385
		$headers = [];
386
		$headers['Content-Type'] = 'application/ld+json; profile="https://www.w3.org/ns/activitystreams"' ;
Zot's avatar
Zot committed
387

Zot's avatar
Zot committed
388
		$x['signature'] = \Zotlabs\Lib\LDSignatures::dopplesign($x,$chan);
Zot's avatar
Zot committed
389
		$ret = json_encode($x, JSON_UNESCAPED_SLASHES);
Zot's avatar
Zot committed
390
		$hash = \Zotlabs\Web\HTTPSig::generate_digest($ret,false);
391
		$headers['Digest'] = 'SHA-256=' . $hash;  
Zot's avatar
Zot committed
392
		\Zotlabs\Web\HTTPSig::create_sig('',$headers,$chan['channel_prvkey'],z_root() . '/channel/' . $chan['channel_address'],true);
393
		echo $ret;
394
		logger('channel: ' . $ret, LOGGER_DATA);
395
		killme();
396 397 398
	}
}

Mario's avatar
Mario committed
399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414
function pubcrawl_notifier_process(&$arr) {

	if($arr['hub']['hubloc_network'] !== 'activitypub')
		return;

	logger('upstream: ' . intval($arr['upstream']));

	logger('notifier_array: ' . print_r($arr,true), LOGGER_ALL, LOG_INFO);

	// allow this to be set per message

	if($arr['mail']) {
		logger('Cannot send mail to activitypub.');
		return;
	}

415 416
	$signed_msg = null;

Mario's avatar
Mario committed
417 418 419 420 421 422 423 424 425 426
	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 an activitypub activity.');
			return;
		}

		if(strpos($arr['target_item']['postopts'],'nopub') !== false) {
			return;
		}
427 428 429 430 431 432

		// don't forward guest comments to activitypub at the moment

		if(strpos($arr['target_item']['author']['xchan_url'],z_root() . '/guest/') !== false) {
			return;
		}
433

434 435 436 437 438 439 440 441 442
		$signed_msg = get_iconfig($arr['target_item'],'activitypub','rawmsg');


		// If we have an activity already stored with an LD-signature
		// which we are sending downstream, use that signed activity as is.
		// The channel will then sign the HTTP transaction. 

		// It is unclear if Mastodon supports the federation delivery model. Initial tests were
		// inconclusive and the behaviour varied. 
443

444
		if(($arr['channel']['channel_hash'] != $arr['target_item']['author_xchan']) && (! $signed_msg)) {
445 446
			return;
		}
447
		
Mario's avatar
Mario committed
448 449
	}

450
	$allowed = Apps::addon_app_installed($arr['channel']['channel_id'],'pubcrawl');
Mario's avatar
Mario committed
451 452 453 454 455 456

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

457

Mario's avatar
Mario committed
458 459 460 461 462
	if($arr['location'])
		return;

	$target_item = $arr['target_item'];

463 464 465
	if(! $target_item['mid'])
		return;

Mario's avatar
Mario committed
466 467 468
	$prv_recips = $arr['env_recips'];


469 470 471 472
	if($signed_msg) {
		$jmsg = $signed_msg;
	}
	else {
473 474 475 476
		$ti = asencode_activity($target_item);
		if(! $ti)
			return;

477 478 479 480
		$msg = array_merge(['@context' => [
			ACTIVITYSTREAMS_JSONLD_REV,
			'https://w3id.org/security/v1',
			z_root() . ZOT_APSCHEMA_REV
481
		]], $ti);
482 483
	
		$msg['signature'] = \Zotlabs\Lib\LDSignatures::dopplesign($msg,$arr['channel']);
Mario's avatar
Mario committed
484

485 486
		$jmsg = json_encode($msg, JSON_UNESCAPED_SLASHES);
	}
487

Mario's avatar
Mario committed
488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513
	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 = 'activitypub' ",
			dbesc($arr['hub']['hubloc_url'])
		);

		if(! $r) {
			logger('activitypub_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['normal_mode'])
				continue;

Zot's avatar
Zot committed
514 515 516 517 518
			if($single) {
				$qi = pubcrawl_queue_message($jmsg,$arr['channel'],$contact,$target_item['mid']);
				if($qi)
					$arr['queued'][] = $qi;
			}
Mario's avatar
Mario committed
519 520 521 522 523 524 525 526
			continue;
		}

	}
	else {

		// public message

527
		// See if we can deliver all of them at once
Mario's avatar
Mario committed
528

529 530 531 532 533 534 535 536
		$x = get_xconfig($arr['hub']['hubloc_hash'],'activitypub','collections');
		if($x && $x['sharedInbox']) {
			logger('using publicInbox delivery for ' . $arr['hub']['hubloc_url'], LOGGER_DEBUG);
			$contact['hubloc_callback'] = $x['sharedInbox'];
			$qi = pubcrawl_queue_message($jmsg,$arr['channel'],$contact,$target_item['mid']);
			if($qi) {
				$arr['queued'][] = $qi;
			}
537
		}
538
		else {
539

540 541 542
			$r = q("select * from xchan left join hubloc on xchan_hash = hubloc_hash where hubloc_url = '%s' and xchan_network = 'activitypub' ",
				dbesc($arr['hub']['hubloc_url'])
			);
Zot's avatar
Zot committed
543

544 545 546
			if(! $r) {
				logger('activitypub_process_outbound: no recipients');
				return;
547
			}
548 549 550 551 552 553 554 555 556 557 558 559 560

		
			foreach($r as $contact) {

				$single = deliverable_singleton($arr['channel']['channel_id'],$contact);

				if($single) {
					$qi = pubcrawl_queue_message($jmsg,$arr['channel'],$contact,$target_item['mid']);
					if($qi)
						$arr['queued'][] = $qi;
				}
			}	
		}
Mario's avatar
Mario committed
561
	}
562 563
	
	return;
Mario's avatar
Mario committed
564 565 566 567 568 569

}


function pubcrawl_queue_message($msg,$sender,$recip,$message_id = '') {

570
    $allowed = Apps::addon_app_installed($sender['channel_id'],'pubcrawl');
Mario's avatar
Mario committed
571 572 573 574 575 576 577 578

    if(! intval($allowed)) {
        return false;
    }
        
	$dest_url = $recip['hubloc_callback'];

    logger('URL: ' . $dest_url, LOGGER_DEBUG);
Zot's avatar
Zot committed
579
	logger('DATA: ' . jindent($msg), LOGGER_DATA);
Mario's avatar
Mario committed
580 581 582 583 584 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

    if(intval(get_config('system','activitypub_test')) || intval(get_pconfig($sender['channel_id'],'system','activitypub_test'))) {
        logger('test mode - delivery disabled');
        return false;
    }

    $hash = random_string();

    logger('queue: ' . $hash . ' ' . $dest_url, LOGGER_DEBUG);
	queue_insert(array(
        'hash'       => $hash,
        'account_id' => $sender['channel_account_id'],
        'channel_id' => $sender['channel_id'],
        'driver'     => 'pubcrawl',
        'posturl'    => $dest_url,
        'notify'     => '',
        'msg'        => $msg
    ));

    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'),
            dbesc(datetime_convert()),
            dbesc($sender['channel_hash']),
            dbesc($hash)
        );
    }

    return $hash;

}

615

Zot's avatar
Zot committed
616 617 618 619 620 621 622 623 624 625 626 627 628
function pubcrawl_connection_remove(&$x) {

	$recip = q("select * from abook left join xchan on abook_xchan = xchan_hash where abook_id = %d",
		intval($x['abook_id'])
	);

	if((! $recip) || $recip[0]['xchan_network'] !== 'activitypub')
		return; 

	$channel = channelx_by_n($recip[0]['abook_channel']);
	if(! $channel)
		return;

629 630 631 632
	$p = asencode_person($channel);
	if(! $p)
		return;

Zot's avatar
Zot committed
633 634 635 636
	// send an unfollow activity to the followee's inbox

	$orig_activity = get_abconfig($recip[0]['abook_channel'],$recip[0]['xchan_hash'],'pubcrawl','follow_id');

637
	if($orig_activity && $recip[0]['abook_pending']) {
Zot's avatar
Zot committed
638

639

Zot's avatar
Zot committed
640 641 642
		// was never approved

		$msg = array_merge(['@context' => [
Zot's avatar
Zot committed
643
				ACTIVITYSTREAMS_JSONLD_REV,
Zot's avatar
Zot committed
644
				'https://w3id.org/security/v1',
Zot's avatar
Zot committed
645
				z_root() . ZOT_APSCHEMA_REV
Zot's avatar
Zot committed
646

Zot's avatar
Zot committed
647 648
			]], 
			[
649
				'id'    => z_root() . '/follow/' . $recip[0]['abook_id'] . '#reject',
650
				'type'  => 'Reject',
651
				'actor' => $p,
652 653 654
				'object'     => [
					'type'   => 'Follow',
					'id'     => $orig_activity,
655
					'actor'  => $recip[0]['xchan_hash'],
656
					'object' => $p
657 658
				],
				'to' => [ $recip[0]['xchan_hash'] ]
Zot's avatar
Zot committed
659 660 661 662 663
		]);
		del_abconfig($recip[0]['abook_channel'],$recip[0]['xchan_hash'],'pubcrawl','follow_id');

	}
	else {
664 665 666

		// send an unfollow

Zot's avatar
Zot committed
667
		$msg = array_merge(['@context' => [
Zot's avatar
Zot committed
668
				ACTIVITYSTREAMS_JSONLD_REV,
Zot's avatar
Zot committed
669
				'https://w3id.org/security/v1',
Zot's avatar
Zot committed
670
				z_root() . ZOT_APSCHEMA_REV
Zot's avatar
Zot committed
671 672
			]], 
			[
673 674
				'id'    => z_root() . '/follow/' . $recip[0]['abook_id'] . '#Undo',
				'type'  => 'Undo',
675
				'actor' => $p,
676 677 678
				'object'     => [
					'id'     => z_root() . '/follow/' . $recip[0]['abook_id'],
					'type'   => 'Follow',
679
					'actor'  => $p,
680
					'object' => $recip[0]['xchan_hash']
681 682
				],
				'to' => [ $recip[0]['xchan_hash'] ]
683 684
			]
		);
Zot's avatar
Zot committed
685 686
	}

Zot's avatar
Zot committed
687 688
	$msg['signature'] = \Zotlabs\Lib\LDSignatures::dopplesign($msg,$channel);

Zot's avatar
Zot committed
689
	$jmsg = json_encode($msg, JSON_UNESCAPED_SLASHES);
Zot's avatar
Zot committed
690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709

	// is $contact connected with this channel - and if the channel is cloned, also on this hub?
	$single = deliverable_singleton($channel['channel_id'],$recip[0]);

	$h = q("select * from hubloc where hubloc_hash = '%s' limit 1",
		dbesc($recip[0]['xchan_hash'])
	);

	if($single && $h) {
		$qi = pubcrawl_queue_message($jmsg,$channel,$h[0]);
		if($qi) {
			\Zotlabs\Daemon\Master::Summon([ 'Deliver' , $qi ]);
		}
	}
		
}




710 711 712 713 714 715 716 717
function pubcrawl_permissions_create(&$x) {

	// send a follow activity to the followee's inbox

	if($x['recipient']['xchan_network'] !== 'activitypub') {
		return;
	}

718 719 720 721
	$p = asencode_person($x['sender']);
	if(! $p)
		return;

Zot's avatar
Zot committed
722
	$msg = array_merge(['@context' => [
Zot's avatar
Zot committed
723
			ACTIVITYSTREAMS_JSONLD_REV,
724 725
			'https://w3id.org/security/v1',
			z_root() . ZOT_APSCHEMA_REV
Zot's avatar
Zot committed
726 727 728 729
		]], 
		[
			'id'     => z_root() . '/follow/' . $x['recipient']['abook_id'],
			'type'   => 'Follow',
730
			'actor'  => $p,
Zot's avatar
Zot committed
731 732 733
			'object' => $x['recipient']['xchan_url'],
			'to'     => [ $x['recipient']['xchan_hash'] ]
	]);
Zot's avatar
Zot committed
734 735


Zot's avatar
Zot committed
736
	$msg['signature'] = \Zotlabs\Lib\LDSignatures::dopplesign($msg,$x['sender']);
Zot's avatar
Zot committed
737

Zot's avatar
Zot committed
738 739 740 741 742 743 744 745 746 747 748 749 750
	$jmsg = json_encode($msg, JSON_UNESCAPED_SLASHES);

	// is $contact connected with this channel - and if the channel is cloned, also on this hub?
	$single = deliverable_singleton($x['sender']['channel_id'],$x['recipient']);

	$h = q("select * from hubloc where hubloc_hash = '%s' limit 1",
		dbesc($x['recipient']['xchan_hash'])
	);

	if($single && $h) {
		$qi = pubcrawl_queue_message($jmsg,$x['sender'],$h[0]);
		if($qi)
			$x['deliveries'] = $qi;
Zot's avatar
Zot committed
751
	}
Zot's avatar
Zot committed
752 753 754 755 756 757 758 759 760 761 762 763
		
	$x['success'] = true;

}


function pubcrawl_permissions_accept(&$x) {

	// send an accept activity to the followee's inbox

	if($x['recipient']['xchan_network'] !== 'activitypub') {
		return;
Zot's avatar
Zot committed
764
	}
765

Zot's avatar
Zot committed
766 767 768 769 770 771
	// we currently are not handling send of reject follow activities; this is permitted by protocol

	$accept = get_abconfig($x['recipient']['abook_channel'],$x['recipient']['xchan_hash'],'pubcrawl','their_follow_id');
	if(! $accept)
		return;

Zot's avatar
Zot committed
772
	$p = asencode_person($x['sender']);
773 774 775
	if(! $p)
		return;

Zot's avatar
Zot committed
776
	$msg = array_merge(['@context' => [
Zot's avatar
Zot committed
777
			ACTIVITYSTREAMS_JSONLD_REV,
Zot's avatar
Zot committed
778
			'https://w3id.org/security/v1',
Zot's avatar
Zot committed
779
			z_root() . ZOT_APSCHEMA_REV
Zot's avatar
Zot committed
780 781 782 783
		]], 
		[
			'id'     => z_root() . '/follow/' . $x['recipient']['abook_id'],
			'type'   => 'Accept',
784
			'actor'  => $p,
Zot's avatar
Zot committed
785 786 787 788 789 790 791 792 793
			'object' => [
				'type'   => 'Follow',
				'id'     => $accept,
				'actor'  => $x['recipient']['xchan_hash'],
				'object' => z_root() . '/channel/' . $x['sender']['channel_address']
			],
			'to' => [ $x['recipient']['xchan_hash'] ]
	]);

Zot's avatar
Zot committed
794 795
	$msg['signature'] = \Zotlabs\Lib\LDSignatures::dopplesign($msg,$x['sender']);

Zot's avatar
Zot committed
796
	$jmsg = json_encode($msg, JSON_UNESCAPED_SLASHES);
797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815

	// is $contact connected with this channel - and if the channel is cloned, also on this hub?
	$single = deliverable_singleton($x['sender']['channel_id'],$x['recipient']);

	$h = q("select * from hubloc where hubloc_hash = '%s' limit 1",
		dbesc($x['recipient']['xchan_hash'])
	);

	if($single && $h) {
		$qi = pubcrawl_queue_message($jmsg,$x['sender'],$h[0]);
		if($qi)
			$x['deliveries'] = $qi;
	}
		
	$x['success'] = true;

}


816 817 818 819 820
function pubcrawl_profile_mod_init($x) {
	
	if(pubcrawl_is_as_request()) {
		$chan = channelx_by_nick(argv(1));
		if(! $chan)
821 822
			http_status_exit(404, 'Not found');

Mario's avatar
Mario committed
823 824


825
		if(! Apps::addon_app_installed($chan['channel_id'],'pubcrawl'))
826 827
			http_status_exit(404, 'Not found');

828 829 830
		$p = asencode_person($chan);
		if(! $p)
			http_status_exit(404, 'Not found');
831

832
		$x = [
Zot's avatar
Zot committed
833
			'@context' => [ 
Zot's avatar
Zot committed
834
				ACTIVITYSTREAMS_JSONLD_REV,
Zot's avatar
Zot committed
835
				'https://w3id.org/security/v1',
Zot's avatar
Zot committed
836
				z_root() . ZOT_APSCHEMA_REV
837 838
			],
			'type' => 'Profile',
839
			'describes' => $p
840 841
		];
				
842
		$headers = [];
843
		$headers['Content-Type'] = 'application/ld+json; profile="https://www.w3.org/ns/activitystreams"' ;
Zot's avatar
Zot committed
844
		$x['signature'] = \Zotlabs\Lib\LDSignatures::dopplesign($x,$chan);
Zot's avatar
Zot committed
845
		$ret = json_encode($x, JSON_UNESCAPED_SLASHES);
Zot's avatar
Zot committed
846
		$hash = \Zotlabs\Web\HTTPSig::generate_digest($ret,false);
847
		$headers['Digest'] = 'SHA-256=' . $hash;  
Zot's avatar
Zot committed
848
		\Zotlabs\Web\HTTPSig::create_sig('',$headers,$chan['channel_prvkey'],z_root() . '/channel/' . $chan['channel_address'],true);
849 850
		echo $ret;
		killme();
851

852 853 854 855 856 857 858 859 860
	}
}


function pubcrawl_item_mod_init($x) {
	
	if(pubcrawl_is_as_request()) {
		$item_id = argv(1);
		if(! $item_id)
861 862
			http_status_exit(404, 'Not found');

863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886

		$item_normal = " and item.item_hidden = 0 and item.item_type = 0 and item.item_unpublished = 0 
			and item.item_delayed = 0 and item.item_blocked = 0 ";

		$sql_extra = item_permissions_sql(0);

		$r = q("select * from item where mid like '%s' $item_normal $sql_extra limit 1",
			dbesc($item_id . '%')
		);
		if(! $r) {
			$r = q("select * from item where mid like '%s' $item_normal limit 1",
				dbesc($item_id . '%')
			);
			if($r) {
				http_status_exit(403, 'Forbidden');
			}
			http_status_exit(404, 'Not found');
		}

		xchan_query($r,true);
		$items = fetch_post_tags($r,true);

		// Wrong object type

Zot's avatar
Zot committed
887
		if(! in_array(activity_obj_mapper($items[0]['obj_type']), [ 'Note', 'Article' ])) {
888 889 890
			http_status_exit(418, "I'm a teapot"); 
		}

891 892
		$chan = channelx_by_n($items[0]['uid']);

893 894 895 896 897 898
		if(! $chan)
			http_status_exit(404, 'Not found');

		if(! perm_is_allowed($chan['channel_id'],get_observer_hash(),'view_stream'))
			http_status_exit(403, 'Forbidden');

899 900 901 902
		$i = asencode_item($items[0]);
		if(! $i)
			http_status_exit(404, 'Not found');

903

904
		$x = array_merge(['@context' => [
Zot's avatar
Zot committed
905
			ACTIVITYSTREAMS_JSONLD_REV,
Zot's avatar
Zot committed
906
			'https://w3id.org/security/v1',
Zot's avatar
Zot committed
907
			z_root() . ZOT_APSCHEMA_REV
908
			]], $i);
909

910

911
		$headers = [];
912
		$headers['Content-Type'] = 'application/ld+json; profile="https://www.w3.org/ns/activitystreams"' ;
Zot's avatar
Zot committed
913
		$x['signature'] = \Zotlabs\Lib\LDSignatures::dopplesign($x,$chan);
Zot's avatar
Zot committed
914
		$ret = json_encode($x, JSON_UNESCAPED_SLASHES);
Zot's avatar
Zot committed
915
		$hash = \Zotlabs\Web\HTTPSig::generate_digest($ret,false);
916
		$headers['Digest'] = 'SHA-256=' . $hash;  
Zot's avatar
Zot committed
917
		\Zotlabs\Web\HTTPSig::create_sig('',$headers,$chan['channel_prvkey'],z_root() . '/channel/' . $chan['channel_address'],true);
918 919
		echo $ret;
		killme();
920 921 922

	}
}
923

924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941

function pubcrawl_thing_mod_init($x) {
	
	if(pubcrawl_is_as_request()) {
		$item_id = argv(1);
		if(! $item_id)
			return;

		$r = q("select * from obj where obj_type = %d and obj_obj = '%s' limit 1",
			intval(TERM_OBJ_THING),
			dbesc($item_id)
		);

		if(! $r)
			return;

		$chan = channelx_by_n($r[0]['obj_channel']);

942 943 944
		if(! $chan)
			http_status_exit(404, 'Not found');

945
		$x = array_merge(['@context' => [
Zot's avatar
Zot committed
946
			ACTIVITYSTREAMS_JSONLD_REV,
Zot's avatar
Zot committed
947
			'https://w3id.org/security/v1',
Zot's avatar
Zot committed
948
			z_root() . ZOT_APSCHEMA_REV
949 950 951 952 953 954 955 956 957 958 959 960
			]],
			[ 
				'type' => 'Object',
				'id'   => z_root() . '/thing/' . $r[0]['obj_obj'],
 				'name' => $r[0]['obj_term']
			]
		);

		if($r[0]['obj_image'])
			$x['image'] = $r[0]['obj_image'];


Zot's avatar
Zot committed
961
		$headers = [];
962
		$headers['Content-Type'] = 'application/ld+json; profile="https://www.w3.org/ns/activitystreams"' ;
Zot's avatar
Zot committed
963
		$x['signature'] = \Zotlabs\Lib\LDSignatures::dopplesign($x,$chan);
Zot's avatar
Zot committed
964
		$ret = json_encode($x, JSON_UNESCAPED_SLASHES);
Zot's avatar
Zot committed
965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982
		$hash = \Zotlabs\Web\HTTPSig::generate_digest($ret,false);
		$headers['Digest'] = 'SHA-256=' . $hash;  
		\Zotlabs\Web\HTTPSig::create_sig('',$headers,$chan['channel_prvkey'],z_root() . '/channel/' . $chan['channel_address'],true);
		echo $ret;
		killme();
	}
}


function pubcrawl_locs_mod_init($x) {
	
	if(pubcrawl_is_as_request()) {
		$channel_address = argv(1);
		if(! $channel_address)
			return;

		$chan = channelx_by_nick($channel_address);

983 984 985
		if(! $chan)
			http_status_exit(404, 'Not found');

Zot's avatar
Zot committed
986
		$x = array_merge(['@context' => [
Zot's avatar
Zot committed
987
			ACTIVITYSTREAMS_JSONLD_REV,
Zot's avatar
Zot committed
988
			'https://w3id.org/security/v1',
Zot's avatar
Zot committed
989
			z_root() . ZOT_APSCHEMA_REV
Zot's avatar
Zot committed
990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010
			]],
			[ 
				'type' => 'nomadicHubs',
				'id'   => z_root() . '/locs/' . $chan['channel_address']
			]
		);

		$locs = zot_encode_locations($chan);
		if($locs) {
			$x['nomadicLocations'] = [];
			foreach($locs as $loc) {
				$x['nomadicLocations'][] = [
					'id'      => $loc['url'] . '/locs/' . substr($loc['address'],0,strpos($loc['address'],'@')),
					'type'            => 'nomadicLocation',
					'locationAddress' => 'acct:' . $loc['address'],
					'locationPrimary' => (boolean) $loc['primary'],
					'locationDeleted' => (boolean) $loc['deleted']
				];
			}
		}

1011
		$headers = [];
1012
		$headers['Content-Type'] = 'application/ld+json; profile="https://www.w3.org/ns/activitystreams"' ;
Zot's avatar
Zot committed
1013
		$x['signature'] = \Zotlabs\Lib\LDSignatures::dopplesign($x,$chan);
Zot's avatar
Zot committed
1014
		$ret = json_encode($x, JSON_UNESCAPED_SLASHES);
Zot's avatar
Zot committed
1015
		$hash = \Zotlabs\Web\HTTPSig::generate_digest($ret,false);
1016
		$headers['Digest'] = 'SHA-256=' . $hash;  
Zot's avatar
Zot committed
1017
		\Zotlabs\Web\HTTPSig::create_sig('',$headers,$chan['channel_prvkey'],z_root() . '/channel/' . $chan['channel_address'],true);
1018 1019 1020 1021 1022 1023 1024
		echo $ret;
		killme();
	}
}



1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038
function pubcrawl_follow_mod_init($x) {

	if(pubcrawl_is_as_request() && argc() == 2) {
		$abook_id = intval(argv(1));
		if(! $abook_id)
			return;
		$r = q("select * from abook left join xchan on abook_xchan = xchan_hash where abook_id = %d",
			intval($abook_id)
		);
		if (! $r)
			return;

		$chan = channelx_by_n($r[0]['abook_channel']);

1039 1040 1041
		if(! $chan)
			http_status_exit(404, 'Not found');

1042 1043 1044 1045 1046
		$actor = asencode_person($chan);
		if(! $actor)
			http_status_exit(404, 'Not found');


1047
		$x = array_merge(['@context' => [
Zot's avatar
Zot committed
1048
				ACTIVITYSTREAMS_JSONLD_REV,
Zot's avatar
Zot committed
1049
				'https://w3id.org/security/v1',
Zot's avatar
Zot committed
1050
				z_root() . ZOT_APSCHEMA_REV
1051 1052
			]], 
			[
1053 1054
				'id'     => z_root() . '/follow/' . $r[0]['abook_id'],
				'type'   => 'Follow',
1055
				'actor'  => $actor,
Zot's avatar
Zot committed
1056
				'object' => $r[0]['xchan_url']
1057 1058
		]);
				
1059

1060
		$headers = [];
1061
		$headers['Content-Type'] = 'application/ld+json; profile="https://www.w3.org/ns/activitystreams"' ;
Zot's avatar
Zot committed
1062
		$x['signature'] = \Zotlabs\Lib\LDSignatures::dopplesign($x,$chan);
Zot's avatar
Zot committed
1063
		$ret = json_encode($x, JSON_UNESCAPED_SLASHES);
Zot's avatar
Zot committed
1064
		$hash = \Zotlabs\Web\HTTPSig::generate_digest($ret,false);
1065
		$headers['Digest'] = 'SHA-256=' . $hash;  
Zot's avatar
Zot committed
1066
		\Zotlabs\Web\HTTPSig::create_sig('',$headers,$chan['channel_prvkey'],z_root() . '/channel/' . $chan['channel_address'],true);
1067 1068
		echo $ret;
		killme();
1069

1070
	}
1071 1072 1073
}


1074 1075 1076 1077 1078 1079 1080 1081 1082 1083
function pubcrawl_queue_deliver(&$b) {

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


	if($outq['outq_driver'] === 'pubcrawl') {
		$b['handled'] = true;

Zot's avatar
Zot committed
1084 1085
		$channel = channelx_by_n($outq['outq_channel']);

1086
		$retries = 0;
Zot's avatar
Zot committed
1087 1088

		$headers = [];
1089
		$headers['Content-Type'] = 'application/ld+json; profile="https://www.w3.org/ns/activitystreams"' ;
Zot's avatar
Zot committed
1090
		$ret = $outq['outq_msg'];
Zot's avatar
Zot committed
1091
		$hash = \Zotlabs\Web\HTTPSig::generate_digest($ret,false);
Zot's avatar
Zot committed
1092
		$headers['Digest'] = 'SHA-256=' . $hash;  
Zot's avatar
Zot committed
1093
		$xhead = \Zotlabs\Web\HTTPSig::create_sig('',$headers,$channel['channel_prvkey'],z_root() . '/channel/' . $channel['channel_address'],false);
Zot's avatar
Zot committed
1094 1095
	
		$result = z_post_url($outq['outq_posturl'],$outq['outq_msg'],$retries,[ 'headers' => $xhead ]);
1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127

		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' ",
					dbesc(datetime_convert()),
					dbesc($base)
				);
			}
			q("update dreport set dreport_result = '%s', dreport_time = '%s' where dreport_queue = '%s'",
				dbesc('accepted for delivery'),
				dbesc(datetime_convert()),
				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
1128
					do_delivery($piled_up,true);
1129 1130 1131 1132 1133
				}
			}
		}
	}
}
1134

1135 1136 1137
function pubcrawl_create_identity($b) {

	if(get_config('system','activitypub_allowed')) {
Mario's avatar
Mario committed
1138
		Apps::app_install($b, 'Activitypub Protocol');
1139 1140 1141
	}

}
1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152

function pubcrawl_can_comment_on_post(&$x) {
	if(local_channel()) {
		$c = App::get_channel();
		$recips = get_iconfig($x['item'],'activitypub','recips',[]);
		if($recips && (in_array(ACTIVITY_PUBLIC_INBOX,$recips) || in_array(channel_url($c),$recips))) {
			$x['allowed'] = true;
		}
	}
}