Activity.php 96.2 KB
Newer Older
1
2
3
4
<?php

namespace Zotlabs\Lib;

5
use App;
DM42.Net Zap Dev's avatar
DM42.Net Zap Dev committed
6
use Zotlabs\Access\PermissionLimits;
7
8
use Zotlabs\Access\PermissionRoles;
use Zotlabs\Access\Permissions;
Mario's avatar
Mario committed
9
use Zotlabs\Daemon\Master;
Zot's avatar
Zot committed
10
use Zotlabs\Web\HTTPSig;
11
12
use Zotlabs\Lib\XConfig;
use Zotlabs\Lib\Libzot;
13

Zot's avatar
Zot committed
14
require_once('include/event.php');
15
require_once('include/html2plain.php');
Mario's avatar
Mario committed
16
require_once('include/items.php');
Zot's avatar
Zot committed
17

18
19
20
21
class Activity {

	static function encode_object($x) {

22
23
		if (($x) && (!is_array($x)) && (substr(trim($x), 0, 1)) === '{') {
			$x = json_decode($x, true);
24
		}
25

26
		if (is_array($x)) {
27

28
			if (array_key_exists('asld', $x)) {
29
30
31
				return $x['asld'];
			}

32
33
			if ($x['type'] === ACTIVITY_OBJ_PERSON) {
				return self::fetch_person($x);
34
			}
35
36
			if ($x['type'] === ACTIVITY_OBJ_PROFILE) {
				return self::fetch_profile($x);
37
			}
38
39
			if (in_array($x['type'], [ACTIVITY_OBJ_NOTE, ACTIVITY_OBJ_ARTICLE])) {
				return self::fetch_item($x);
40
			}
41
42
			if ($x['type'] === ACTIVITY_OBJ_THING) {
				return self::fetch_thing($x);
43
			}
44
45
			if ($x['type'] === ACTIVITY_OBJ_EVENT) {
				return self::fetch_event($x);
46
			}
47

48
			call_hooks('encode_object', $x);
Zot's avatar
Zot committed
49
		}
50
51
52
53
54

		return $x;

	}

55
	static function fetch($url, $channel = null) {
Zot's avatar
Zot committed
56
		$redirects = 0;
57
		if (!check_siteallowed($url)) {
Zot's avatar
Zot committed
58
59
60
			logger('blacklisted: ' . $url);
			return null;
		}
61
		if (!$channel) {
Zot's avatar
Zot committed
62
63
64
65
66
			$channel = get_sys_channel();
		}

		logger('fetch: ' . $url, LOGGER_DEBUG);

67
68
		if (strpos($url, 'x-zot:') === 0) {
			$x = ZotURL::fetch($url, $channel);
Zot's avatar
Zot committed
69
70
71
		}
		else {
			$m = parse_url($url);
Zot's avatar
Zot committed
72
73
74

			// handle bearcaps
			if ($m['scheme'] === 'bear') {
75
				$params = explode('&', $m['query']);
Zot's avatar
Zot committed
76
77
				if ($params) {
					foreach ($params as $p) {
78
79
						if (substr($p, 0, 2) === 'u=') {
							$url = substr($p, 2);
Zot's avatar
Zot committed
80
						}
81
82
						if (substr($p, 0, 2) === 't=') {
							$token = substr($p, 2);
Zot's avatar
Zot committed
83
84
						}
					}
Zot's avatar
Zot committed
85
					$m = parse_url($url);
Zot's avatar
Zot committed
86
87
88
				}
			}

Zot's avatar
Zot committed
89
			$headers = [
90
				'Accept'           => ActivityStreams::get_accept_header_string($channel),
Zot's avatar
Zot committed
91
				'Host'             => $m['host'],
92
				'Date'             => datetime_convert('UTC', 'UTC', 'now', 'D, d M Y H:i:s \\G\\M\\T'),
93
				'(request-target)' => 'get ' . get_request_string($url)
Zot's avatar
Zot committed
94
			];
95

Zot's avatar
Zot committed
96
97
98
			if (isset($token)) {
				$headers['Authorization'] = 'Bearer ' . $token;
			}
99

100
101
			$h = HTTPSig::create_sig($headers, $channel['channel_prvkey'], channel_url($channel), false);
			$x = z_fetch_url($url, true, $redirects, ['headers' => $h]);
Zot's avatar
Zot committed
102
103
		}

104
		if ($x['success']) {
Mario's avatar
Mario committed
105
106
			$m = parse_url($url);
			if ($m) {
107
108
109
110
				$y = [ 'scheme' => $m['scheme'], 'host' => $m['host'] ];
				if (array_key_exists('port', $m))
					$y['port'] = $m['port'];
				$site_url = unparse_url($y);
Mario's avatar
Mario committed
111
112
113
114
115
116
117
118
				q("UPDATE site SET site_update = '%s', site_dead = 0 WHERE site_url = '%s' AND site_update < %s - INTERVAL %s",
					dbesc(datetime_convert()),
					dbesc($site_url),
					db_utcnow(),
					db_quoteinterval('1 DAY')
				);
			}

119
120
			$y = json_decode($x['body'], true);
			logger('returned: ' . json_encode($y, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES), LOGGER_DEBUG);
Zot's avatar
Zot committed
121
122
123
124
			return json_decode($x['body'], true);
		}
		else {
			logger('fetch failed: ' . $url);
Mario's avatar
Mario committed
125
			logger($x['body']);
Zot's avatar
Zot committed
126
127
128
129
		}
		return null;
	}

130
131
132
133
134
	static function fetch_person($x) {
		return self::fetch_profile($x);
	}

	static function fetch_profile($x) {
Mario's avatar
Mario committed
135
136
		$r = q("select * from xchan where xchan_url = '%s' limit 1",
			dbesc($x['id'])
137
		);
138
		if (!$r) {
139
140
141
142
			$r = q("select * from xchan where xchan_hash = '%s' limit 1",
				dbesc($x['id'])
			);

143
144
		}
		if (!$r)
145
146
147
148
149
150
151
152
153
154
155
156
157
			return [];

		return self::encode_person($r[0]);

	}

	static function fetch_thing($x) {

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

158
		if (!$r)
159
160
161
162
163
164
165
166
			return [];

		$x = [
			'type' => 'Object',
			'id'   => z_root() . '/thing/' . $r[0]['obj_obj'],
			'name' => $r[0]['obj_term']
		];

167
		if ($r[0]['obj_image'])
168
169
170
171
172
173
174
175
			$x['image'] = $r[0]['obj_image'];

		return $x;

	}

	static function fetch_item($x) {

176
		if (array_key_exists('source', $x)) {
177
178
179
180
181
182
183
			// This item is already processed and encoded
			return $x;
		}

		$r = q("select * from item where mid = '%s' limit 1",
			dbesc($x['id'])
		);
184
185
		if ($r) {
			xchan_query($r, true);
Mario's avatar
Mario committed
186
			$r = fetch_post_tags($r);
187
			if (in_array($r[0]['verb'], ['Create', 'Invite']) && $r[0]['obj_type'] === ACTIVITY_OBJ_EVENT) {
Zot's avatar
Zot committed
188
189
190
				$r[0]['verb'] = 'Invite';
				return self::encode_activity($r[0]);
			}
191
192
193
194
			return self::encode_item($r[0]);
		}
	}

Zot's avatar
Zot committed
195
	static function fetch_image($x) {
Mario's avatar
Mario committed
196

Zot's avatar
Zot committed
197
		$ret = [
198
199
200
201
202
203
204
205
206
207
208
209
210
			'type'      => 'Image',
			'id'        => $x['id'],
			'name'      => $x['title'],
			'content'   => bbcode($x['body'], ['cache' => true]),
			'source'    => ['mediaType' => 'text/bbcode', 'content' => $x['body']],
			'published' => datetime_convert('UTC', 'UTC', $x['created'], ATOM_TIME),
			'updated'   => datetime_convert('UTC', 'UTC', $x['edited'], ATOM_TIME),
			'url'       => [
				'type'      => 'Link',
				'mediaType' => $x['link'][0]['type'],
				'href'      => $x['link'][0]['href'],
				'width'     => $x['link'][0]['width'],
				'height'    => $x['link'][0]['height']
Zot's avatar
Zot committed
211
212
213
214
215
			]
		];
		return $ret;
	}

Zot's avatar
Zot committed
216
217
218
219
	static function fetch_event($x) {

		// convert old Zot event objects to ActivityStreams Event objects

220
		if (array_key_exists('content', $x) && array_key_exists('dtstart', $x)) {
Zot's avatar
Zot committed
221
			$ev = bbtoevent($x['content']);
222
			if ($ev) {
Zot's avatar
Zot committed
223

Zot's avatar
Zot committed
224

225
				if (!$ev['timezone']) {
Zot's avatar
Zot committed
226
227
228
					$ev['timezone'] = 'UTC';
				}

Zot's avatar
Zot committed
229
				$actor = null;
230
				if (array_key_exists('author', $x) && array_key_exists('link', $x['author'])) {
Zot's avatar
Zot committed
231
232
					$actor = $x['author']['link'][0]['href'];
				}
233
				$y = [
Zot's avatar
Zot committed
234
235
					'type'      => 'Event',
					'id'        => z_root() . '/event/' . $ev['event_hash'],
236
					'name'      => $ev['summary'],
237
					// 'summary'   => bbcode($ev['summary'], [ 'cache' => true ]),
Zot's avatar
Zot committed
238
					// RFC3339 Section 4.3
239
240
241
242
					'startTime' => (($ev['adjust']) ? datetime_convert($ev['timezone'], 'UTC', $ev['dtstart'], ATOM_TIME) : datetime_convert('UTC', 'UTC', $ev['dtstart'], 'Y-m-d\\TH:i:s-00:00')),
					'content'   => bbcode($ev['description'], ['cache' => true]),
					'location'  => ['type' => 'Place', 'content' => bbcode($ev['location'], ['cache' => true])],
					'source'    => ['content' => format_event_bbcode($ev, true), 'mediaType' => 'text/bbcode'],
Zot's avatar
Zot committed
243
244
					'actor'     => $actor,
				];
245
246
				if (!$ev['nofinish']) {
					$y['endTime'] = (($ev['adjust']) ? datetime_convert($ev['timezone'], 'UTC', $ev['dtend'], ATOM_TIME) : datetime_convert('UTC', 'UTC', $ev['dtend'], 'Y-m-d\\TH:i:s-00:00'));
247
				}
248

Max Kostikov's avatar
Max Kostikov committed
249
250
				// copy attachments from the passed object - these are already formatted for ActivityStreams

251
				if ($x['attachment']) {
Max Kostikov's avatar
Max Kostikov committed
252
253
254
					$y['attachment'] = $x['attachment'];
				}

255
				if ($actor) {
Zot's avatar
Zot committed
256
257
258
259
260
261
262
263
264
					return $y;
				}
			}
		}

		return $x;

	}

265
	static function paged_collection_init($total, $id, $type = 'OrderedCollection') {
266
267

		$ret = [
268
269
			'id'         => z_root() . '/' . $id,
			'type'       => $type,
270
			'totalItems' => $total,
271
		];
272
273
274
275
276
277
278
279
280
281
282
283
284

		$numpages = $total / App::$pager['itemspage'];
		$lastpage = (($numpages > intval($numpages)) ? intval($numpages) + 1 : $numpages);

		$ret['first'] = z_root() . '/' . App::$query_string . '?page=1';
		$ret['last']  = z_root() . '/' . App::$query_string . '?page=' . $lastpage;

		return $ret;

	}

	static function encode_item_collection($items, $id, $type, $total = 0) {

Mario's avatar
Mario committed
285
		if ($total > 30) {
286
287
288
289
290
291
292
			$ret = [
				'id'   => z_root() . '/' . $id,
				'type' => $type . 'Page',
			];

			$numpages = $total / App::$pager['itemspage'];
			$lastpage = (($numpages > intval($numpages)) ? intval($numpages) + 1 : $numpages);
293
			$url_parts = parse_url($id);
294

295
			$ret['partOf'] = z_root() . '/' . $url_parts['path'];
296

297
298
299
300
301
302
303
304
305
306
307
			$extra_query_args = '';
			$query_args = null;
			if(isset($url_parts['query'])) {
				parse_str($url_parts['query'], $query_args);
			}

			if(is_array($query_args)) {
				unset($query_args['page']);
				foreach($query_args as $k => $v)
					$extra_query_args .= '&' . urlencode($k) . '=' . urlencode($v);
			}
308
309

			if (App::$pager['page'] < $lastpage) {
310
				$ret['next'] = z_root() . '/' . $url_parts['path'] . '?page=' . (intval(App::$pager['page']) + 1) . $extra_query_args;
311
312
			}
			if (App::$pager['page'] > 1) {
313
				$ret['prev'] = z_root() . '/' . $url_parts['path'] . '?page=' . (intval(App::$pager['page']) - 1) . $extra_query_args;
314
315
316
317
318
319
			}
		}
		else {
			$ret = [
				'id'         => z_root() . '/' . $id,
				'type'       => $type,
320
				'totalItems' => $total,
321
322
			];
		}
323

324
		if ($items) {
325
			$x = [];
326
			foreach ($items as $i) {
327
				$m = get_iconfig($i['id'], 'activitypub', 'rawmsg');
Mario's avatar
Mario committed
328
329
				if ($m) {
					if (is_string($m))
330
						$t = json_decode($m, true);
Mario's avatar
Mario committed
331
332
					else
						$t = $m;
333
334
				}
				else {
Mario's avatar
Mario committed
335
336
337
338
					$t = self::encode_activity($i);
				}
				if ($t) {
					$x[] = $t;
339
				}
340
			}
341
			if ($type === 'OrderedCollection') {
342
				$ret['orderedItems'] = $x;
343
344
			}
			else {
345
				$ret['items'] = $x;
346
			}
347
348
349
350
351
		}

		return $ret;
	}

352
	static function encode_follow_collection($items, $id, $type, $extra = null) {
353
354

		$ret = [
355
356
			'id'         => z_root() . '/' . $id,
			'type'       => $type,
357
358
			'totalItems' => count($items),
		];
359
360
		if ($extra)
			$ret = array_merge($ret, $extra);
361

362
		if ($items) {
363
			$x = [];
364
365
			foreach ($items as $i) {
				if ($i['xchan_url']) {
366
367
368
369
					$x[] = $i['xchan_url'];
				}
			}

370
			if ($type === 'OrderedCollection')
371
372
373
374
375
376
377
378
379
380
381
382
				$ret['orderedItems'] = $x;
			else
				$ret['items'] = $x;
		}

		return $ret;
	}

	static function encode_item($i) {

		$ret = [];

Mario's avatar
Mario committed
383
384


385
		if ($i['verb'] === ACTIVITY_FRIEND) {
386
387
388
			// Hubzilla 'make-friend' activity, no direct mapping from AS1 to AS2 - make it a note
			$objtype = 'Note';
		}
389
		else {
390
391
			$objtype = self::activity_obj_mapper($i['obj_type']);
		}
392
393
394
395
396

		if ($i['obj']) {
			$ret = Activity::encode_object($i['obj']);
		}

397
		if (intval($i['item_deleted'])) {
398
			$ret['type']       = 'Tombstone';
399
			$ret['formerType'] = $objtype;
400
401
			$ret['id']         = $i['mid'];
			if ($i['id'] != $i['parent'])
402
403
				$ret['inReplyTo'] = $i['thr_parent'];

404
			$ret['to'] = [ACTIVITY_PUBLIC_INBOX];
405
406
407
408
409
410
411
412
			return $ret;
		}

		if ($i['obj']) {
			if (is_array($i['obj'])) {
				$ret = $i['obj'];
			}
			else {
413
				$ret = json_decode($i['obj'], true);
414
415
416
			}
		}

417
418
		$ret['type'] = $objtype;

Zot's avatar
Zot committed
419
420
421
422
423
424
		if ($objtype === 'Question') {
			if ($i['obj']) {
				if (is_array($i['obj'])) {
					$ret = $i['obj'];
				}
				else {
425
					$ret = json_decode($i['obj'], true);
Zot's avatar
Zot committed
426
				}
427
428

				if (array_path_exists('actor/id', $ret)) {
Zot's avatar
Zot committed
429
430
431
432
433
					$ret['actor'] = $ret['actor']['id'];
				}
			}
		}

434
		$ret['id']            = ((strpos($i['mid'], 'http') === 0) ? $i['mid'] : z_root() . '/item/' . urlencode($i['mid']));
Mario's avatar
Mario committed
435
		$ret['diaspora:guid'] = $i['uuid'];
436

437
		if ($i['title'])
Zot's avatar
Zot committed
438
			$ret['name'] = $i['title'];
439

440
441
442
		$ret['published'] = datetime_convert('UTC', 'UTC', $i['created'], ATOM_TIME);
		if ($i['created'] !== $i['edited'])
			$ret['updated'] = datetime_convert('UTC', 'UTC', $i['edited'], ATOM_TIME);
443
		if ($i['expires'] > NULL_DATE) {
444
			$ret['expires'] = datetime_convert('UTC', 'UTC', $i['expires'], ATOM_TIME);
Zot's avatar
Zot committed
445
446
		}

447
448
		if ($i['app']) {
			$ret['generator'] = ['type' => 'Application', 'name' => $i['app']];
449
		}
450
451
452
		if ($i['location'] || $i['coord']) {
			$ret['location'] = ['type' => 'Place'];
			if ($i['location']) {
453
454
				$ret['location']['name'] = $i['location'];
			}
455
456
457
			if ($i['coord']) {
				$l                            = explode(' ', $i['coord']);
				$ret['location']['latitude']  = $l[0];
458
459
460
461
				$ret['location']['longitude'] = $l[1];
			}
		}

462
		if (intval($i['item_wall']) && $i['mid'] === $i['parent_mid']) {
463
			$ret['commentPolicy'] = map_scope(PermissionLimits::Get($i['uid'], 'post_comments'));
464
465
		}

466
467
468
469
		if (intval($i['item_private']) === 2) {
			$ret['directMessage'] = true;
		}

470
		if (array_key_exists('comments_closed', $i) && $i['comments_closed'] !== EMPTY_STR && $i['comments_closed'] > NULL_DATE) {
471
			if ($ret['commentPolicy']) {
472
473
				$ret['commentPolicy'] .= ' ';
			}
474
			$ret['commentPolicy'] .= 'until=' . datetime_convert('UTC', 'UTC', $i['comments_closed'], ATOM_TIME);
475
476
		}

477
478
		$ret['attributedTo'] = $i['author']['xchan_url'];

479
480
		if ($i['id'] != $i['parent']) {
			$ret['inReplyTo'] = ((strpos($i['thr_parent'], 'http') === 0) ? $i['thr_parent'] : z_root() . '/item/' . urlencode($i['thr_parent']));
481
482
		}

483
484
485
486
487
488
489
		if ($i['mimetype'] === 'text/bbcode') {
			if ($i['title'])
				$ret['name'] = bbcode($i['title'], ['cache' => true]);
			if ($i['summary'])
				$ret['summary'] = bbcode($i['summary'], ['cache' => true]);
			$ret['content'] = bbcode($i['body'], ['cache' => true]);
			$ret['source']  = ['content' => $i['body'], 'mediaType' => 'text/bbcode'];
490
491
		}

492
493
		$actor = self::encode_person($i['author'], false);
		if ($actor)
494
495
496
497
498
			$ret['actor'] = $actor;
		else
			return [];

		$t = self::encode_taxonomy($i);
499
500
		if ($t) {
			$ret['tag'] = $t;
501
502
503
		}

		$a = self::encode_attachment($i);
504
		if ($a) {
505
506
507
			$ret['attachment'] = $a;
		}

508
		$public    = (($i['item_private']) ? false : true);
509
510
511
		$top_level = (($i['mid'] === $i['parent_mid']) ? true : false);

		if ($public) {
512
513
			$ret['to'] = [ACTIVITY_PUBLIC_INBOX];
			$ret['cc'] = [z_root() . '/followers/' . substr($i['author']['xchan_addr'], 0, strpos($i['author']['xchan_addr'], '@'))];
514
515
516
517
518
519
520
521
522
523
524
525
		}
		else {

			// private activity

			if ($top_level) {
				$ret['to'] = self::map_acl($i);
			}
			else {
				$ret['to'] = [];
				if ($ret['tag']) {
					foreach ($ret['tag'] as $mention) {
526
						if (is_array($mention) && array_key_exists('href', $mention) && $mention['href']) {
527
528
529
530
531
532
533
534
535
536
							$h = q("select * from hubloc where hubloc_id_url = '%s' limit 1",
								dbesc($mention['href'])
							);
							if ($h) {
								if ($h[0]['hubloc_network'] === 'activitypub') {
									$addr = $h[0]['hubloc_hash'];
								}
								else {
									$addr = $h[0]['hubloc_id_url'];
								}
537
								if (!in_array($addr, $ret['to'])) {
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
									$ret['to'][] = $addr;
								}
							}
						}
					}
				}
				$d = q("select hubloc.*  from hubloc left join item on hubloc_hash = owner_xchan where item.id = %d limit 1",
					intval($i['parent'])
				);
				if ($d) {
					if ($d[0]['hubloc_network'] === 'activitypub') {
						$addr = $d[0]['hubloc_hash'];
					}
					else {
						$addr = $d[0]['hubloc_id_url'];
					}
554
					if (!in_array($addr, $ret['to'])) {
555
556
557
558
559
560
561
562
						$ret['cc'][] = $addr;
					}
				}
			}
		}

		$mentions = self::map_mentions($i);
		if (count($mentions) > 0) {
563
			if (!$ret['to']) {
564
565
566
567
568
569
570
				$ret['to'] = $mentions;
			}
			else {
				$ret['to'] = array_values(array_unique(array_merge($ret['to'], $mentions)));
			}
		}

571
		return $ret;
572

573
574
575
576
577
578
	}

	static function decode_taxonomy($item) {

		$ret = [];

579
		if (array_key_exists('tag', $item) && is_array($item['tag'])) {
580
			$ptr = $item['tag'];
581
582
			if (!array_key_exists(0, $ptr)) {
				$ptr = [$ptr];
583
584
			}
			foreach ($ptr as $t) {
585
				if (!array_key_exists('type', $t))
586
587
					$t['type'] = 'Hashtag';

588
589
590
591
592
593
594
				if (array_key_exists('href', $t) && array_key_exists('name', $t)) {
					switch ($t['type']) {
						case 'Hashtag':
							$ret[] = ['ttype' => TERM_HASHTAG, 'url' => $t['href'], 'term' => escape_tags((substr($t['name'], 0, 1) === '#') ? substr($t['name'], 1) : $t['name'])];
							break;

						case 'Mention':
595
596
597
598
							$ret[] = ['ttype' => TERM_MENTION, 'url' => $t['href'], 'term' => escape_tags((substr($t['name'], 0, 1) === '@') ? substr($t['name'], 1) : $t['name'])];
							break;

						case 'Bookmark':
Mario's avatar
Mario committed
599
							$ret[] = ['ttype' => TERM_BOOKMARK, 'url' => $t['href'], 'term' => escape_tags($t['name'])];
600
							break;
601

602
603
604
						default:
							break;
					}
605
606
607
608
609
610
611
612
613
614
615
				}
			}
		}

		return $ret;
	}

	static function encode_taxonomy($item) {

		$ret = [];

616
		if (array_key_exists('term', $item) && is_array($item['term'])) {
617
618
			foreach ($item['term'] as $t) {
				switch ($t['ttype']) {
619
					case TERM_HASHTAG:
620
						// href is required so if we don't have a url in the taxonomy, ignore it and keep going.
621
622
						if ($t['url']) {
							$ret[] = ['type' => 'Hashtag', 'href' => $t['url'], 'name' => '#' . $t['term']];
623
624
625
626
						}
						break;

					case TERM_MENTION:
627
						$ret[] = ['type' => 'Mention', 'href' => $t['url'], 'name' => '@' . $t['term']];
628
						break;
629

630
631
632
633
					case TERM_BOOKMARK:
						$ret[] = ['type' => 'Bookmark', 'href' => $t['url'], 'name' => $t['term']];
						break;

634
635
636
637
638
639
640
641
642
643
644
645
646
					default:
						break;
				}
			}
		}

		return $ret;
	}

	static function encode_attachment($item) {

		$ret = [];

647
		if (array_key_exists('attach', $item)) {
648
649
650
			$atts = ((is_array($item['attach'])) ? $item['attach'] : json_decode($item['attach'], true));
			if ($atts) {
				foreach ($atts as $att) {
Mario's avatar
Mario committed
651
					if (isset($att['type']) && strpos($att['type'], 'image')) {
652
						$ret[] = ['type' => 'Image', 'url' => $att['href']];
653
654
					}
					else {
655
						$ret[] = ['type' => 'Link', 'mediaType' => $att['type'], 'href' => $att['href']];
656
657
658
659
					}
				}
			}
		}
660
		if (array_key_exists('iconfig', $item) && is_array($item['iconfig'])) {
Zot's avatar
Zot committed
661
662
			foreach ($item['iconfig'] as $att) {
				if ($att['sharing']) {
663
					$value = ((is_string($att['v']) && preg_match('|^a:[0-9]+:{.*}$|s', $att['v'])) ? unserialize($att['v']) : $att['v']);
664
					$ret[] = ['type' => 'PropertyValue', 'name' => 'zot.' . $att['cat'] . '.' . $att['k'], 'value' => $value];
Zot's avatar
Zot committed
665
666
667
				}
			}
		}
668

669
670
671
		return $ret;
	}

Zot's avatar
Zot committed
672
673
674
675
676
677
	static function decode_iconfig($item) {

		$ret = [];

		if (is_array($item['attachment']) && $item['attachment']) {
			$ptr = $item['attachment'];
678
679
			if (!array_key_exists(0, $ptr)) {
				$ptr = [$ptr];
Zot's avatar
Zot committed
680
681
682
683
			}
			foreach ($ptr as $att) {
				$entry = [];
				if ($att['type'] === 'PropertyValue') {
684
685
					if (array_key_exists('name', $att) && $att['name']) {
						$key = explode('.', $att['name']);
Zot's avatar
Zot committed
686
						if (count($key) === 3 && $key[0] === 'zot') {
687
688
689
							$entry['cat']     = $key[1];
							$entry['k']       = $key[2];
							$entry['v']       = $att['value'];
Zot's avatar
Zot committed
690
							$entry['sharing'] = '1';
691
							$ret[]            = $entry;
Zot's avatar
Zot committed
692
693
694
695
696
697
698
699
						}
					}
				}
			}
		}
		return $ret;
	}

700
701
702
703
	static function decode_attachment($item) {

		$ret = [];

Max Kostikov's avatar
Max Kostikov committed
704
		if (array_key_exists('attachment', $item) && is_array($item['attachment'])) {
705
			foreach ($item['attachment'] as $att) {
706
				$entry = [];
707
				if (array_key_exists('href', $att))
708
					$entry['href'] = $att['href'];
709
				elseif (array_key_exists('url', $att))
710
					$entry['href'] = $att['url'];
711
				if (array_key_exists('mediaType', $att))
712
					$entry['type'] = $att['mediaType'];
713
				elseif (array_key_exists('type', $att) && $att['type'] === 'Image')
714
					$entry['type'] = 'image/jpeg';
715
				if ($entry)
716
717
718
719
720
721
722
					$ret[] = $entry;
			}
		}

		return $ret;
	}

Mario's avatar
Mario committed
723
	static function encode_activity($i, $recurse = false) {
724
725
726
727

		$ret   = [];
		$reply = false;

728
		if ($i['verb'] === ACTIVITY_FRIEND) {
729
730
731
732
			// Hubzilla 'make-friend' activity, no direct mapping from AS1 to AS2 - make it a note
			$ret['obj'] = [];
		}

Mario's avatar
Mario committed
733
		$ret['type'] = self::activity_mapper($i['verb']);
Mario's avatar
Mario committed
734

Mario's avatar
Mario committed
735
		if (intval($i['item_deleted']) && !$recurse) {
736
737
			$is_response = false;

Mario's avatar
Mario committed
738
			if (ActivityStreams::is_response_activity($ret['type'])) {
739
				$ret['type'] = 'Undo';
740
				$fragment    = 'undo';
741
				$is_response = true;
742
743
744
			}
			else {
				$ret['type'] = 'Delete';
745
				$fragment    = 'delete';
746
			}
Mario's avatar
Mario committed
747

748
749
			$ret['id'] = str_replace('/item/', '/activity/', $i['mid']) . '#' . $fragment;
			$actor     = self::encode_person($i['author'], false);
Mario's avatar
Mario committed
750
			if ($actor)
Zot's avatar
Zot committed
751
752
				$ret['actor'] = $actor;
			else
753
				return [];
Mario's avatar
Mario committed
754

755
			$obj = (($is_response) ? self::encode_activity($i, true) : self::encode_item($i));
756
			if ($obj) {
757
				if (array_path_exists('object/id', $obj)) {
Mario's avatar
Mario committed
758
759
					$obj['object'] = $obj['object']['id'];
				}
760
761
762
				if (isset($obj['cc'])) {
					unset($obj['cc']);
				}
763
				$obj['to']     = [ACTIVITY_PUBLIC_INBOX];
764
				$ret['object'] = $obj;
Mario's avatar
Mario committed
765
			}
766
767
			else
				return [];
Mario's avatar
Mario committed
768

769
			$ret['to'] = [ACTIVITY_PUBLIC_INBOX];
770

771
			return $ret;
772

773
774
		}

775
		if ($ret['type'] === 'emojiReaction') {
776
777
778
779
780
			// There may not be an object for these items for legacy reasons - it should be the conversation parent.
			$p = q("select * from item where mid = '%s' and uid = %d",
				dbesc($i['parent_mid']),
				intval($i['uid'])
			);
781
782
783
			if ($p) {
				xchan_query($p, true);
				$p        = fetch_post_tags($p);
784
				$i['obj'] = self::encode_item($p[0]);
785
786
787

				// convert to zot6 emoji reaction encoding which uses the target object to indicate the
				// specific emoji instead of overloading the verb or type.
788
789
790

				$im = explode('#', $i['verb']);
				if ($im && count($im) > 1)
791
					$emoji = $im[1];
792
				if (preg_match("/\[img(.*?)\](.*?)\[\/img\]/ism", $i['body'], $match)) {
793
794
795
796
					$ln = $match[2];
				}

				$i['tgt_type'] = 'Image';
797

798
799
800
801
802
				$i['target'] = [
					'type' => 'Image',
					'name' => $emoji,
					'url'  => (($ln) ? $ln : z_root() . '/images/emoji/' . $emoji . '.png')
				];
803

804
805
806
			}
		}

807
808
		if (strpos($i['mid'], z_root() . '/item/') !== false) {
			$ret['id'] = str_replace('/item/', '/activity/', $i['mid']);
809
		}
810
811
		elseif (strpos($i['mid'], z_root() . '/event/') !== false) {
			$ret['id'] = str_replace('/event/', '/activity/', $i['mid']);
812
813
		}
		else {
814
			$ret['id'] = ((strpos($i['mid'], 'http') === 0) ? $i['mid'] : z_root() . '/activity/' . urlencode($i['mid']));
815
		}
816

Mario's avatar
Mario committed
817
818
		$ret['diaspora:guid'] = $i['uuid'];

819
820
		if ($i['title'])
			$ret['name'] = html2plain(bbcode($i['title'], ['cache' => true]));
821

822
823
		if ($i['summary'])
			$ret['summary'] = bbcode($i['summary'], ['cache' => true]);
824

825
826
827
828
829
		if ($ret['type'] === 'Announce') {
			$tmp            = preg_replace('/\[share(.*?)\[\/share\]/ism', EMPTY_STR, $i['body']);
			$ret['content'] = bbcode($tmp, ['cache' => true]);
			$ret['source']  = [
				'content'   => $i['body'],
830
831
832
833
				'mediaType' => 'text/bbcode'
			];
		}

834
835
836
837
838
		$ret['published'] = datetime_convert('UTC', 'UTC', $i['created'], ATOM_TIME);
		if ($i['created'] !== $i['edited'])
			$ret['updated'] = datetime_convert('UTC', 'UTC', $i['edited'], ATOM_TIME);
		if ($i['app']) {
			$ret['generator'] = ['type' => 'Application', 'name' => $i['app']];
839
		}
840
841
842
		if ($i['location'] || $i['coord']) {
			$ret['location'] = ['type' => 'Place'];
			if ($i['location']) {
843
844
				$ret['location']['name'] = $i['location'];
			}
845
846
847
			if ($i['coord']) {
				$l                            = explode(' ', $i['coord']);
				$ret['location']['latitude']  = $l[0];
848
849
850
851
				$ret['location']['longitude'] = $l[1];
			}
		}

852
		if ($i['id'] != $i['parent']) {
853
854
			$reply = true;

855
856
			// inReplyTo needs to be set in the activity for followup actions (Like, Dislike, Announce, etc.),
			// but *not* for comments and RSVPs, where it should only be present in the object
Mario's avatar
Mario committed
857

858
859
			if (!in_array($ret['type'], ['Create', 'Update', 'Accept', 'Reject', 'TentativeAccept', 'TentativeReject'])) {
				$ret['inReplyTo'] = ((strpos($i['thr_parent'], 'http') === 0) ? $i['thr_parent'] : z_root() . '/item/' . urlencode($i['thr_parent']));
860
861
862
			}
		}

863
864
		$actor = self::encode_person($i['author'], false);
		if ($actor)
865
866
			$ret['actor'] = $actor;
		else
867
			return [];
868

869
		if (strpos($i['body'], '[/share]') !== false) {
Zot's avatar
Zot committed
870
871
872
			$i['obj'] = null;
		}

873
874
875
		if ($i['obj']) {
			if (!is_array($i['obj'])) {
				$i['obj'] = json_decode($i['obj'], true);
876
			}
877
			if ($i['obj']['type'] === ACTIVITY_OBJ_PHOTO) {
878
				$i['obj']['id'] = $i['mid'];
Zot's avatar
Zot committed
879
880
			}

881
			$obj = self::encode_object($i['obj']);
882
			if ($obj)
883
884
885
886
887
888
				$ret['object'] = $obj;
			else
				return [];
		}
		else {
			$obj = self::encode_item($i);
889
			if ($obj)
890
891
892
893
894
				$ret['object'] = $obj;
			else
				return [];
		}

895
		if (array_path_exists('object/type', $ret) && $ret['object']['type'] === 'Event' && $ret['type'] === 'Create') {
896
897
			$ret['type'] = 'Invite';
		}
Zot's avatar
Zot committed
898

899
900
901
		if ($i['target']) {
			if (!is_array($i['target'])) {
				$i['target'] = json_decode($i['target'], true);
902
903
			}
			$tgt = self::encode_object($i['target']);
904
			if ($tgt)
905
906
907
908
909
				$ret['target'] = $tgt;
			else
				return [];
		}

910
911
912
913
914
915
916
		$t = self::encode_taxonomy($i);
		if ($t) {
			$ret['tag'] = $t;
		}

		// addressing madness

917
		$public    = (($i['item_private']) ? false : true);
918
919
920
		$top_level = (($reply) ? false : true);

		if ($public) {
921
922
			$ret['to'] = [ACTIVITY_PUBLIC_INBOX];
			$ret['cc'] = [z_root() . '/followers/' . substr($i['author']['xchan_addr'], 0, strpos($i['author']['xchan_addr'], '@'))];
923
924
925
926
927
928
929
930
931
932
933
934
		}
		else {

			// private activity

			if ($top_level) {
				$ret['to'] = self::map_acl($i);
			}
			else {
				$ret['to'] = [];
				if ($ret['tag']) {
					foreach ($ret['tag'] as $mention) {
935
						if (is_array($mention) && array_key_exists('href', $mention) && $mention['href']) {
936
937
938
939
940
941
942
943
944
945
							$h = q("select * from hubloc where hubloc_id_url = '%s' limit 1",
								dbesc($mention['href'])
							);
							if ($h) {
								if ($h[0]['hubloc_network'] === 'activitypub') {
									$addr = $h[0]['hubloc_hash'];
								}
								else {
									$addr = $h[0]['hubloc_id_url'];
								}
946
								if (!in_array($addr, $ret['to'])) {
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
									$ret['to'][] = $addr;
								}
							}
						}
					}
				}

				$d = q("select hubloc.*  from hubloc left join item on hubloc_hash = owner_xchan where item.id = %d limit 1",
					intval($i['parent'])
				);
				if ($d) {
					if ($d[0]['hubloc_network'] === 'activitypub') {
						$addr = $d[0]['hubloc_hash'];
					}
					else {
						$addr = $d[0]['hubloc_id_url'];
					}
964
					if (!in_array($addr, $ret['to'])) {
965
966
967
968
969
970
971
972
						$ret['cc'][] = $addr;
					}
				}
			}
		}

		$mentions = self::map_mentions($i);
		if (count($mentions) > 0) {
973
			if (!$ret['to']) {
974
975
976
977
978
979
				$ret['to'] = $mentions;
			}
			else {
				$ret['to'] = array_values(array_unique(array_merge($ret['to'], $mentions)));
			}
		}
Mario's avatar
Mario committed
980

981
982
983
		return $ret;
	}

984
	// Returns an array of URLS for any mention tags found in the item array $i.
985
	static function map_mentions($i) {
986

987
988
		$list = [];

Max Kostikov's avatar
Max Kostikov committed
989
990
991
992
993
994
995
996
997
		if (array_key_exists('term', $i) && is_array($i['term'])) {
			foreach ($i['term'] as $t) {
				if (!$t['url']) {
					continue;
				}
				if ($t['ttype'] == TERM_MENTION) {
					$url    = self::lookup_term_url($t['url']);
					$list[] = (($url) ? $url : $t['url']);
				}
998
999
1000
1001
1002
1003
			}
		}

		return $list;
	}

1004
1005
1006
	// Returns an array of all recipients targeted by private item array $i.
	static function map_acl($i) {
		$ret = [];
Zot's avatar