aboutsummaryrefslogtreecommitdiffstats
path: root/Zotlabs/Lib/ActivityStreams.php
blob: 1a6fe9c1b488f204c3ee88abcdbb678c9b7be265 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
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
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
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
315
316
317
318
319
320
321
322
323
324
325
326
327
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
357
358
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
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
<?php

namespace Zotlabs\Lib;

/**
 * @brief ActivityStreams class.
 *
 * Parses an ActivityStream JSON string.
 */
class ActivityStreams {

	public $raw = null;
	public $data = null;
	public $meta = null;
	public $valid = false;
	public $deleted = false;
	public $id = '';
	public $parent_id = '';
	public $type = '';
	public $actor = null;
	public $obj = null;
	public $tgt = null;
	public $origin = null;
	public $owner = null;
	public $signer = null;
	public $ldsig = null;
	public $sigok = false;
	public $recips = null;
	public $raw_recips = null;

	/**
	 * @brief Constructor for ActivityStreams.
	 *
	 * Takes a JSON string as parameter, decodes it and sets up this object.
	 *
	 * @param string $string
	 */
	function __construct($string) {

		if(!$string)
			return;

		$this->raw = $string;

		if (is_array($string)) {
			$this->data = $string;
			$this->raw = json_encode($string, JSON_UNESCAPED_SLASHES);
		}
		else {
			$this->data = json_decode($string, true);
		}

		if ($this->data) {

			// verify and unpack JSalmon signature if present

			if (is_array($this->data) && array_key_exists('signed', $this->data)) {
				$ret = JSalmon::verify($this->data);
				$tmp = JSalmon::unpack($this->data['data']);
				if ($ret && $ret['success']) {
					if ($ret['signer']) {
						$saved                     = json_encode($this->data, JSON_UNESCAPED_SLASHES);
						$this->data                = $tmp;
						$this->meta['signer']      = $ret['signer'];
						$this->meta['signed_data'] = $saved;
						if ($ret['hubloc']) {
							$this->meta['hubloc'] = $ret['hubloc'];
						}
					}
				}
			}

			// This indicates only that we have sucessfully decoded JSON.
			$this->valid = true;

			// Special handling for Mastodon "delete actor" activities which will often fail to verify
			// because the key cannot be fetched. We will catch this condition elsewhere.
			if (is_array($this->data) && array_key_exists('type', $this->data) && array_key_exists('actor', $this->data) && array_key_exists('object', $this->data)) {
				if ($this->data['type'] === 'Delete' && $this->data['actor'] === $this->data['object']) {
					$this->deleted = $this->data['actor'];
					$this->valid   = false;
				}
			}

		}

		// Attempt to assemble an Activity from what we were given.
		if ($this->is_valid()) {
			$this->id     = $this->get_property_obj('id');
			$this->type   = $this->get_primary_type();
			$this->actor  = $this->get_actor('actor', '', '');
			$this->obj    = $this->get_compound_property('object');
			$this->tgt    = $this->get_compound_property('target');
			$this->origin = $this->get_compound_property('origin');
			$this->recips = $this->collect_recips();

			$this->ldsig = $this->get_compound_property('signature');
			if ($this->ldsig) {
				$this->signer = $this->get_actor('creator', $this->ldsig);
				if ($this->signer && is_array($this->signer) && array_key_exists('publicKey', $this->signer) && is_array($this->signer['publicKey']) && $this->signer['publicKey']['publicKeyPem']) {
					$this->sigok = LDSignatures::verify($this->data, $this->signer['publicKey']['publicKeyPem']);
				}
			}

			if (!$this->obj) {
				$this->obj  = $this->data;
				$this->type = 'Create';
				if (!$this->actor) {
					$this->actor = $this->get_actor('attributedTo', $this->obj);
				}
			}

			// fetch recursive or embedded activities

			if ($this->obj && is_array($this->obj) && array_key_exists('object', $this->obj)) {
				$this->obj['object'] = $this->get_compound_property('object', $this->obj);
			}

			if ($this->obj && is_array($this->obj) && isset($this->obj['actor']))
				$this->obj['actor'] = $this->get_actor('actor', $this->obj);
			if ($this->tgt && is_array($this->tgt) && isset($this->tgt['actor']))
				$this->tgt['actor'] = $this->get_actor('actor', $this->tgt);

			$this->parent_id = $this->get_property_obj('inReplyTo');

			if ((!$this->parent_id) && is_array($this->obj) && isset($this->obj['inReplyTo'])) {
				$this->parent_id = $this->obj['inReplyTo'];
			}
			if ((!$this->parent_id) && is_array($this->obj) && isset($this->obj['id'])) {
				$this->parent_id = $this->obj['id'];
			}
		}
	}

	/**
	 * @brief Return if instantiated ActivityStream is valid.
	 *
	 * @return boolean Return true if the JSON string could be decoded.
	 */
	function is_valid() {
		return $this->valid;
	}

	function set_recips($arr) {
		$this->saved_recips = $arr;
	}

	/**
	 * @brief get single property from Activity object
	 *
	 * @param string $property
	 * @param mixed $default return value if property or object not set
	 *    or object is a string id which could not be fetched.
	 * @return mixed
	 */
	public function objprop(string $property, mixed $default = false): mixed {
		$x = $this->get_property_obj($property,$this->obj);
		return (isset($x)) ? $x : $default;
	}

	/**
	 * @brief Collects all recipients.
	 *
	 * @param mixed $base
	 * @param string $namespace (optional) default empty
	 * @return array
	 */
	public function collect_recips(mixed $base = '', string $namespace = ''): array {
		$result = [];
		$tmp = [];

		$fields = ['to', 'cc', 'bto', 'bcc', 'audience'];
		foreach ($fields as $field) {
			// don't expand these yet
			$values = $this->get_property_obj($field, $base, $namespace);
			if ($values) {
				$values = force_array($values);
				$tmp[$field] = $values;
				$result = array_values(array_unique(array_merge($result, $values)));
			}
			// Merge the object recipients if they exist.
			$values = $this->objprop($field);
			if ($values) {
				$values = force_array($values);
				$tmp[$field] = (($tmp[$field]) ? array_merge($tmp[$field], $values) : $values);
				$result = array_values(array_unique(array_merge($result, $values)));
			}
			// remove duplicates
			if (is_array($tmp[$field])) {
				$tmp[$field] = array_values(array_unique($tmp[$field]));
			}
		}
		$this->raw_recips = $tmp;

		// not yet ready for prime time
		//      $result = $this->expand($result,$base,$namespace);
		return $result;
	}


	function expand($arr, $base = '', $namespace = '') {
		$ret = [];

		// right now use a hardwired recursion depth of 5

		for ($z = 0; $z < 5; $z++) {
			if (is_array($arr) && $arr) {
				foreach ($arr as $a) {
					if (is_array($a)) {
						$ret[] = $a;
					}
					else {
						$x = $this->get_compound_property($a, $base, $namespace);
						if ($x) {
							$ret = array_merge($ret, $x);
						}
					}
				}
			}
		}

		/// @fixme de-duplicate

		return $ret;
	}

	/**
	 * @brief
	 *
	 * @param array $base
	 * @param string $namespace if not set return empty string
	 * @return string|NULL
	 */
	function get_namespace($base, $namespace) {

		if (!$namespace)
			return '';

		$key = null;

		foreach ([$this->data, $base] as $b) {
			if (!$b)
				continue;

			if (array_key_exists('@context', $b)) {
				if (is_array($b['@context'])) {
					foreach ($b['@context'] as $ns) {
						if (is_array($ns)) {
							foreach ($ns as $k => $v) {
								if ($namespace === $v)
									$key = $k;
							}
						}
						else {
							if ($namespace === $ns) {
								$key = '';
							}
						}
					}
				}
				else {
					if ($namespace === $b['@context']) {
						$key = '';
					}
				}
			}
		}

		return $key;
	}

	/**
	 * @brief
	 *
	 * @param string $property
	 * @param array $base (optional)
	 * @param string $namespace (optional) default empty
	 * @return NULL|mixed
	 */
	function get_property_obj($property, $base = '', $namespace = '') {
		$prefix = $this->get_namespace($base, $namespace);
		if ($prefix === null)
			return null;

		$base     = (($base) ? $base : $this->data);
		$propname = (($prefix) ? $prefix . ':' : '') . $property;

		if (!is_array($base)) {
			btlogger('not an array: ' . print_r($base, true));
			return null;
		}

		return ((array_key_exists($propname, $base)) ? $base[$propname] : null);
	}


	/**
	 * @brief Fetches a property from an URL.
	 *
	 * @param string $url
	 * @return NULL|mixed
	 */

	function fetch_property($url) {
		return self::fetch($url);
	}

	static function fetch($url, $channel = null) {
		return Activity::fetch($url, $channel);
	}

	static function is_an_actor($s) {
		return (in_array($s, ['Application', 'Group', 'Organization', 'Person', 'Service']));
	}

	static function is_response_activity($s) {
		if (!$s) {
			return false;
		}
		return (in_array($s, ['Like', 'Dislike', 'Flag', 'Block', 'Accept', 'Reject', 'TentativeAccept', 'TentativeReject', 'emojiReaction', 'EmojiReaction', 'EmojiReact']));
	}

	/**
	 * @brief
	 *
	 * @param string $property
	 * @param array $base
	 * @param string $namespace (optional) default empty
	 * @return NULL|mixed
	 */

	function get_actor($property, $base = '', $namespace = '') {
		$x = $this->get_property_obj($property, $base, $namespace);

		if ($this->is_url($x)) {
			$y = Activity::get_cached_actor($x);
			if ($y) {
				return $y;
			}
		}

		$actor = $this->get_compound_property($property, $base, $namespace, true);

		if (is_array($actor) && self::is_an_actor($actor['type'])) {
			if (array_key_exists('id', $actor) && (!array_key_exists('inbox', $actor))) {
				$actor = $this->fetch_property($actor['id']);
			}
			return $actor;
		}

		return Activity::get_unknown_actor($this->data);

	}


	/**
	 * @brief
	 *
	 * @param string $property
	 * @param array $base
	 * @param string $namespace (optional) default empty
	 * @param boolean $first (optional) default false, if true and result is a sequential array return only the first element
	 * @return NULL|mixed
	 */
	function get_compound_property($property, $base = '', $namespace = '', $first = false) {
		$x = $this->get_property_obj($property, $base, $namespace);

		if ($this->is_url($x)) {
			$y = $this->fetch_property($x);
			if (is_array($y)) {
				$x = $y;
			}
		}

		// verify and unpack JSalmon signature if present

		if (is_array($x) && array_key_exists('signed', $x)) {
			$ret = JSalmon::verify($x);
			$tmp = JSalmon::unpack($x['data']);
			if ($ret && $ret['success']) {
				if ($ret['signer']) {
					$saved            = json_encode($x, JSON_UNESCAPED_SLASHES);
					$x                = $tmp;
					$x['meta']['signer']      = $ret['signer'];
					$x['meta']['signed_data'] = $saved;
					if ($ret['hubloc']) {
						$x['meta']['hubloc'] = $ret['hubloc'];
					}
				}
			}
		}
		if ($first && is_array($x) && array_key_exists(0, $x)) {
			return $x[0];
		}

		return $x;
	}

	/**
	 * @brief Check if string starts with http.
	 *
	 * @param string $url
	 * @return boolean
	 */
	function is_url($url) {
		if (($url) && (!is_array($url)) && (strpos($url, 'http') === 0)) {
			return true;
		}

		return false;
	}

	/**
	 * @brief Gets the type property.
	 *
	 * @param array $base
	 * @param string $namespace (optional) default empty
	 * @return NULL|mixed
	 */
	function get_primary_type($base = '', $namespace = '') {
		if (!$base)
			$base = $this->data;

		$x = $this->get_property_obj('type', $base, $namespace);
		if (is_array($x)) {
			foreach ($x as $y) {
				if (strpos($y, ':') === false) {
					return $y;
				}
			}
		}

		return $x;
	}

	function debug() {
		$x = var_export($this, true);
		return $x;
	}

	static function is_as_request($channel = null) {

		$hookdata = [];
		if ($channel)
			$hookdata['channel'] = $channel;

		$hookdata['data'] = ['application/x-zot-activity+json'];

		call_hooks('is_as_request', $hookdata);

		$x = getBestSupportedMimeType($hookdata['data']);
		return (($x) ? true : false);

	}

	static function get_accept_header_string($channel = null) {

		$ret = '';

		$hookdata = [];
		if ($channel)
			$hookdata['channel'] = $channel;

		$hookdata['data'] = ['application/x-zot-activity+json'];

		call_hooks('get_accept_header_string', $hookdata);

		$ret = implode(', ', $hookdata['data']);

		return $ret;

	}

}