diff options
author | Max Kostikov <max@kostikov.co> | 2021-01-20 22:12:15 +0100 |
---|---|---|
committer | Max Kostikov <max@kostikov.co> | 2021-01-20 22:12:15 +0100 |
commit | ab4455c54c457d2eff773d7b7c1a723489c13bad (patch) | |
tree | 7c23d66e1f55bd4e2048a0a18297912f7628defa | |
parent | 15b2aa660ba99b7a17aa811041a40739f258672f (diff) | |
parent | 6cca06f6414547b3b7f38044ee808620e8dfdf43 (diff) | |
download | volse-hubzilla-ab4455c54c457d2eff773d7b7c1a723489c13bad.tar.gz volse-hubzilla-ab4455c54c457d2eff773d7b7c1a723489c13bad.tar.bz2 volse-hubzilla-ab4455c54c457d2eff773d7b7c1a723489c13bad.zip |
Merge branch 'dev' into 'dev'
Dev sync
See merge request kostikov/core!2
-rw-r--r-- | Zotlabs/Daemon/Cron.php | 5 | ||||
-rw-r--r-- | Zotlabs/Daemon/Externals.php | 2 | ||||
-rw-r--r-- | Zotlabs/Daemon/Onepoll.php | 149 | ||||
-rw-r--r-- | Zotlabs/Daemon/Poller.php | 2 | ||||
-rw-r--r-- | Zotlabs/Lib/ASCollection.php | 150 | ||||
-rw-r--r-- | Zotlabs/Lib/Activity.php | 1927 | ||||
-rw-r--r-- | Zotlabs/Lib/Libzot.php | 1276 | ||||
-rw-r--r-- | Zotlabs/Lib/ZotURL.php | 3 | ||||
-rw-r--r-- | Zotlabs/Module/Zotfeed.php | 126 | ||||
-rwxr-xr-x | include/items.php | 20 | ||||
-rw-r--r-- | include/network.php | 29 |
11 files changed, 1997 insertions, 1692 deletions
diff --git a/Zotlabs/Daemon/Cron.php b/Zotlabs/Daemon/Cron.php index e8fa3244f..cd7a710d3 100644 --- a/Zotlabs/Daemon/Cron.php +++ b/Zotlabs/Daemon/Cron.php @@ -170,11 +170,6 @@ class Cron { require_once('include/attach.php'); attach_upgrade(); - $abandon_days = intval(get_config('system', 'account_abandon_days')); - if ($abandon_days < 1) - $abandon_days = 0; - - // once daily run birthday_updates and then expire in background // FIXME: add birthday updates, both locally and for xprof for use diff --git a/Zotlabs/Daemon/Externals.php b/Zotlabs/Daemon/Externals.php index b657f9de4..3d6b0bd7b 100644 --- a/Zotlabs/Daemon/Externals.php +++ b/Zotlabs/Daemon/Externals.php @@ -82,7 +82,7 @@ class Externals { if ($j['success'] && $j['messages']) { $sys = get_sys_channel(); foreach ($j['messages'] as $message) { - // on these posts, clear any route info. + // on these posts, clear any route info. $message['route'] = ''; process_delivery(['hash' => 'undefined'], get_item_elements($message), [['hash' => $sys['xchan_hash']]], false, true); diff --git a/Zotlabs/Daemon/Onepoll.php b/Zotlabs/Daemon/Onepoll.php index 0228f10fb..388a78c81 100644 --- a/Zotlabs/Daemon/Onepoll.php +++ b/Zotlabs/Daemon/Onepoll.php @@ -2,13 +2,13 @@ namespace Zotlabs\Daemon; -use App; +use Zotlabs\Lib\Activity; +use Zotlabs\Lib\ActivityStreams; +use Zotlabs\Lib\ASCollection; use Zotlabs\Lib\Libzot; -require_once('include/zot.php'); require_once('include/socgraph.php'); - class Onepoll { static public function run($argc, $argv) { @@ -38,8 +38,7 @@ class Onepoll { return; } - $contact = $contacts[0]; - + $contact = array_shift($contacts); $importer_uid = $contact['abook_channel']; $r = q("SELECT * from channel left join xchan on channel_hash = xchan_hash where channel_id = %d limit 1", @@ -53,6 +52,7 @@ class Onepoll { logger("onepoll: poll: ({$contact['id']}) IMPORTER: {$importer['xchan_name']}, CONTACT: {$contact['xchan_name']}"); + // TODO: unused $last_update = ((($contact['abook_updated'] === $contact['abook_created']) || ($contact['abook_updated'] <= NULL_DATE)) ? datetime_convert('UTC', 'UTC', 'now - 7 days') : datetime_convert('UTC', 'UTC', $contact['abook_updated'] . ' - 2 days') @@ -103,80 +103,109 @@ class Onepoll { if (!$responded) return; - if ($contact['xchan_connurl']) { - $fetch_feed = true; - $x = null; + $fetch_feed = true; + $x = null; - // They haven't given us permission to see their stream + // They haven't given us permission to see their stream - $can_view_stream = intval(get_abconfig($importer_uid, $contact['abook_xchan'], 'their_perms', 'view_stream')); + $can_view_stream = intval(get_abconfig($importer_uid, $contact['abook_xchan'], 'their_perms', 'view_stream')); - if (!$can_view_stream) - $fetch_feed = false; + if (!$can_view_stream) + $fetch_feed = false; - // we haven't given them permission to send us their stream + // we haven't given them permission to send us their stream - $can_send_stream = intval(get_abconfig($importer_uid, $contact['abook_xchan'], 'my_perms', 'send_stream')); + $can_send_stream = intval(get_abconfig($importer_uid, $contact['abook_xchan'], 'my_perms', 'send_stream')); - if (!$can_send_stream) - $fetch_feed = false; + if (!$can_send_stream) + $fetch_feed = false; - if ($fetch_feed) { + if ($fetch_feed) { - if (strpos($contact['xchan_connurl'], z_root()) === 0) { - // local channel - save a network fetch - $c = channelx_by_hash($contact['xchan_hash']); - if ($c) { - $x = [ - 'success' => true, - 'body' => json_encode([ - 'success' => true, - 'messages' => zot_feed($c['channel_id'], $importer['xchan_hash'], ['mindate' => $last_update]) - ]) - ]; - } + $max = intval(get_config('system', 'max_imported_posts', 30)); + + if (intval($max)) { + $cl = get_xconfig($contact['abook_xchan'], 'activitypub', 'collections'); + + if (is_array($cl) && $cl) { + $url = ((array_key_exists('outbox', $cl)) ? $cl['outbox'] : ''); } else { - // remote fetch - - $feedurl = str_replace('/poco/', '/zotfeed/', $contact['xchan_connurl']); - $feedurl .= '?f=&mindate=' . urlencode($last_update) . '&zid=' . $importer['channel_address'] . '@' . App::get_hostname(); - $recurse = 0; - $x = z_fetch_url($feedurl, false, $recurse, ['session' => true]); + $url = str_replace('/poco/', '/zotfeed/', $contact['xchan_connurl']); } - logger('feed_update: ' . print_r($x, true), LOGGER_DATA); - } - - if (($x) && ($x['success'])) { - $total = 0; - logger('onepoll: feed update ' . $contact['xchan_name'] . ' ' . $feedurl); - - $j = json_decode($x['body'], true); - if ($j['success'] && $j['messages']) { - foreach ($j['messages'] as $message) { - $results = process_delivery(['hash' => $contact['xchan_hash']], get_item_elements($message), - [['hash' => $importer['xchan_hash']]], false); - logger('onepoll: feed_update: process_delivery: ' . print_r($results, true), LOGGER_DATA); - $total++; + if ($url) { + logger('fetching outbox'); + $obj = new ASCollection($url, $importer, 0, $max); + $messages = $obj->get(); + hz_syslog(print_r($messages,true)); + if ($messages) { + foreach ($messages as $message) { + if (is_string($message)) { + $message = Activity::fetch($message, $importer); + } + $AS = new ActivityStreams($message); + if ($AS->is_valid() && is_array($AS->obj)) { + $item = Activity::decode_note($AS); + Activity::store($importer, $contact['abook_xchan'], $AS, $item); + } + } } - logger("onepoll: $total messages processed"); } } } + /* if ($fetch_feed) { + + if (strpos($contact['xchan_connurl'], z_root()) === 0) { + // local channel - save a network fetch + $c = channelx_by_hash($contact['xchan_hash']); + if ($c) { + $x = [ + 'success' => true, + 'body' => json_encode([ + 'success' => true, + 'messages' => zot_feed($c['channel_id'], $importer['xchan_hash'], ['mindate' => $last_update]) + ]) + ]; + } + } + else { + // remote fetch + + $feedurl = str_replace('/poco/', '/zotfeed/', $contact['xchan_connurl']); + $feedurl .= '?f=&mindate=' . urlencode($last_update) . '&zid=' . $importer['channel_address'] . '@' . App::get_hostname(); + $recurse = 0; + $x = z_fetch_url($feedurl, false, $recurse, ['session' => true]); + } + + logger('feed_update: ' . print_r($x, true), LOGGER_DATA); + } - // update the poco details for this connection + if (($x) && ($x['success'])) { + $total = 0; + logger('onepoll: feed update ' . $contact['xchan_name'] . ' ' . $feedurl); + + $j = json_decode($x['body'], true); + if ($j['success'] && $j['messages']) { + foreach ($j['messages'] as $message) { + $results = process_delivery(['hash' => $contact['xchan_hash']], get_item_elements($message), + [['hash' => $importer['xchan_hash']]], false); + logger('onepoll: feed_update: process_delivery: ' . print_r($results, true), LOGGER_DATA); + $total++; + } + logger("onepoll: $total messages processed"); + } + } + */ - if ($contact['xchan_connurl']) { - $r = q("SELECT xlink_id from xlink - where xlink_xchan = '%s' and xlink_updated > %s - INTERVAL %s and xlink_static = 0 limit 1", - intval($contact['xchan_hash']), - db_utcnow(), db_quoteinterval('1 DAY') - ); - if (!$r) { - poco_load($contact['xchan_hash'], $contact['xchan_connurl']); - } + // update the poco details for this connection + $r = q("SELECT xlink_id from xlink where xlink_xchan = '%s' and xlink_updated > %s - INTERVAL %s and xlink_static = 0 limit 1", + intval($contact['xchan_hash']), + db_utcnow(), db_quoteinterval('1 DAY') + ); + if (!$r) { + poco_load($contact['xchan_hash'], $contact['xchan_connurl']); } return; diff --git a/Zotlabs/Daemon/Poller.php b/Zotlabs/Daemon/Poller.php index 8cbdfab0d..762f1349c 100644 --- a/Zotlabs/Daemon/Poller.php +++ b/Zotlabs/Daemon/Poller.php @@ -57,7 +57,7 @@ class Poller { reload_plugins(); // Only poll from those with suitable relationships - + $abandon_days = intval(get_config('system', 'account_abandon_days', 0)); $abandon_sql = (($abandon_days) ? sprintf(" AND account_lastlog > %s - INTERVAL %s ", db_utcnow(), db_quoteinterval(intval($abandon_days) . ' DAY')) : '' diff --git a/Zotlabs/Lib/ASCollection.php b/Zotlabs/Lib/ASCollection.php new file mode 100644 index 000000000..392dd5d4e --- /dev/null +++ b/Zotlabs/Lib/ASCollection.php @@ -0,0 +1,150 @@ +<?php + +namespace Zotlabs\Lib; + +/** + * Class for dealing with fetching ActivityStreams collections (ordered or unordered, normal or paged). + * Construct with either an existing object or url and an optional channel to sign requests. + * $direction is 0 (default) to fetch from the beginning, and 1 to fetch from the end and reverse order the resultant array. + * An optional limit to the number of records returned may also be specified. + * Use $class->get() to return an array of collection members. + */ +class ASCollection { + + private $channel = null; + private $nextpage = null; + private $limit = 0; + private $direction = 0; // 0 = forward, 1 = reverse + private $data = []; + private $history = []; + + function __construct($obj, $channel = null, $direction = 0, $limit = 0) { + + $this->channel = $channel; + $this->direction = $direction; + $this->limit = $limit; + + if (is_array($obj)) { + $data = $obj; + } + + if (is_string($obj)) { + $data = Activity::fetch($obj, $channel); + $this->history[] = $obj; + } + + if (!is_array($data)) { + return; + } + + if (!in_array($data['type'], ['Collection', 'OrderedCollection', 'OrderedCollectionPage'])) { + return false; + } + + if ($this->direction) { + if (array_key_exists('last', $data) && $data['last']) { + $this->nextpage = $data['last']; + } + } + else { + if (array_key_exists('first', $data) && $data['first']) { + $this->nextpage = $data['first']; + } + } + + if (isset($data['items']) && is_array($data['items'])) { + $this->data = (($this->direction) ? array_reverse($data['items']) : $data['items']); + } + elseif (isset($data['orderedItems']) && is_array($data['orderedItems'])) { + $this->data = (($this->direction) ? array_reverse($data['orderedItems']) : $data['orderedItems']); + } + + if ($this->limit) { + if (count($this->data) > $limit) { + $this->data = array_slice($this->data, 0, $limit); + return; + } + } + + do { + $x = $this->next(); + } while ($x); + } + + function get() { + return $this->data; + } + + function next() { + + if (!$this->nextpage) { + return false; + } + + if (is_array($this->nextpage)) { + $data = $this->nextpage; + } + + if (is_string($this->nextpage)) { + if (in_array($this->nextpage, $this->history)) { + // recursion detected + return false; + } + $data = Activity::fetch($this->nextpage, $this->channel); + $this->history[] = $this->nextpage; + } + + if (!is_array($data)) { + return false; + } + + if (!in_array($data['type'], ['CollectionPage', 'OrderedCollectionPage'])) { + return false; + } + + $this->setnext($data); + + if (isset($data['items']) && is_array($data['items'])) { + $this->data = array_merge($this->data, (($this->direction) ? array_reverse($data['items']) : $data['items'])); + } + elseif (isset($data['orderedItems']) && is_array($data['orderedItems'])) { + $this->data = array_merge($this->data, (($this->direction) ? array_reverse($data['orderedItems']) : $data['orderedItems'])); + } + + if ($this->limit) { + if (count($this->data) > $this->limit) { + $this->data = array_slice($this->data, 0, $this->limit); + $this->nextpage = false; + return true; + } + } + + return true; + } + + function setnext($data) { + if ($this->direction) { + if (array_key_exists('prev', $data) && $data['prev']) { + $this->nextpage = $data['prev']; + } + elseif (array_key_exists('first', $data) && $data['first']) { + $this->nextpage = $data['first']; + } + else { + $this->nextpage = false; + } + } + else { + if (array_key_exists('next', $data) && $data['next']) { + $this->nextpage = $data['next']; + } + elseif (array_key_exists('last', $data) && $data['last']) { + $this->nextpage = $data['last']; + } + else { + $this->nextpage = false; + } + } + logger('nextpage: ' . $this->nextpage, LOGGER_DEBUG); + } +}
\ No newline at end of file diff --git a/Zotlabs/Lib/Activity.php b/Zotlabs/Lib/Activity.php index 807216400..aa121d98b 100644 --- a/Zotlabs/Lib/Activity.php +++ b/Zotlabs/Lib/Activity.php @@ -2,7 +2,10 @@ namespace Zotlabs\Lib; +use App; use Zotlabs\Access\PermissionLimits; +use Zotlabs\Access\PermissionRoles; +use Zotlabs\Access\Permissions; use Zotlabs\Daemon\Master; use Zotlabs\Web\HTTPSig; @@ -13,71 +16,70 @@ class Activity { static function encode_object($x) { - - if(($x) && (! is_array($x)) && (substr(trim($x),0,1)) === '{' ) { - $x = json_decode($x,true); + if (($x) && (!is_array($x)) && (substr(trim($x), 0, 1)) === '{') { + $x = json_decode($x, true); } - if(is_array($x)) { + if (is_array($x)) { - if(array_key_exists('asld',$x)) { + if (array_key_exists('asld', $x)) { return $x['asld']; } - if($x['type'] === ACTIVITY_OBJ_PERSON) { - return self::fetch_person($x); + if ($x['type'] === ACTIVITY_OBJ_PERSON) { + return self::fetch_person($x); } - if($x['type'] === ACTIVITY_OBJ_PROFILE) { - return self::fetch_profile($x); + if ($x['type'] === ACTIVITY_OBJ_PROFILE) { + return self::fetch_profile($x); } - if(in_array($x['type'], [ ACTIVITY_OBJ_NOTE, ACTIVITY_OBJ_ARTICLE ] )) { - return self::fetch_item($x); + if (in_array($x['type'], [ACTIVITY_OBJ_NOTE, ACTIVITY_OBJ_ARTICLE])) { + return self::fetch_item($x); } - if($x['type'] === ACTIVITY_OBJ_THING) { - return self::fetch_thing($x); + if ($x['type'] === ACTIVITY_OBJ_THING) { + return self::fetch_thing($x); } - if($x['type'] === ACTIVITY_OBJ_EVENT) { - return self::fetch_event($x); + if ($x['type'] === ACTIVITY_OBJ_EVENT) { + return self::fetch_event($x); } - if($x['type'] === ACTIVITY_OBJ_PHOTO) { - return self::fetch_image($x); + if ($x['type'] === ACTIVITY_OBJ_PHOTO) { + return self::fetch_image($x); } - call_hooks('encode_object',$x); + call_hooks('encode_object', $x); } return $x; } - static function fetch($url,$channel = null) { + static function fetch($url, $channel = null) { $redirects = 0; - if(! check_siteallowed($url)) { + if (!check_siteallowed($url)) { logger('blacklisted: ' . $url); return null; } - if(! $channel) { + if (!$channel) { $channel = get_sys_channel(); } logger('fetch: ' . $url, LOGGER_DEBUG); - if(strpos($url,'x-zot:') === 0) { - $x = ZotURL::fetch($url,$channel); + if (strpos($url, 'x-zot:') === 0) { + $x = ZotURL::fetch($url, $channel); } else { $m = parse_url($url); // handle bearcaps if ($m['scheme'] === 'bear') { - $params = explode('&',$m['query']); + $params = explode('&', $m['query']); if ($params) { foreach ($params as $p) { - if (substr($p,0,2) === 'u=') { - $url = substr($p,2); + if (substr($p, 0, 2) === 'u=') { + $url = substr($p, 2); } - if (substr($p,0,2) === 't=') { - $token = substr($p,2); + if (substr($p, 0, 2) === 't=') { + $token = substr($p, 2); } } $m = parse_url($url); @@ -87,19 +89,19 @@ class Activity { $headers = [ 'Accept' => 'application/activity+json, application/ld+json; profile="https://www.w3.org/ns/activitystreams"', 'Host' => $m['host'], - 'Date' => datetime_convert('UTC','UTC', 'now', 'D, d M Y H:i:s \\G\\M\\T'), + 'Date' => datetime_convert('UTC', 'UTC', 'now', 'D, d M Y H:i:s \\G\\M\\T'), '(request-target)' => 'get ' . get_request_string($url) ]; if (isset($token)) { $headers['Authorization'] = 'Bearer ' . $token; } - $h = HTTPSig::create_sig($headers,$channel['channel_prvkey'],channel_url($channel),false); - $x = z_fetch_url($url, true, $redirects, [ 'headers' => $h ] ); + $h = HTTPSig::create_sig($headers, $channel['channel_prvkey'], channel_url($channel), false); + $x = z_fetch_url($url, true, $redirects, ['headers' => $h]); } - if($x['success']) { - $y = json_decode($x['body'],true); - logger('returned: ' . json_encode($y,JSON_PRETTY_PRINT|JSON_UNESCAPED_SLASHES), LOGGER_DEBUG); + if ($x['success']) { + $y = json_decode($x['body'], true); + logger('returned: ' . json_encode($y, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES), LOGGER_DEBUG); return json_decode($x['body'], true); } else { @@ -110,8 +112,6 @@ class Activity { } - - static function fetch_person($x) { return self::fetch_profile($x); } @@ -120,13 +120,13 @@ class Activity { $r = q("select * from xchan where xchan_url like '%s' limit 1", dbesc($x['id'] . '/%') ); - if(! $r) { + if (!$r) { $r = q("select * from xchan where xchan_hash = '%s' limit 1", dbesc($x['id']) ); - } - if(! $r) + } + if (!$r) return []; return self::encode_person($r[0]); @@ -140,7 +140,7 @@ class Activity { dbesc($x['id']) ); - if(! $r) + if (!$r) return []; $x = [ @@ -149,7 +149,7 @@ class Activity { 'name' => $r[0]['obj_term'] ]; - if($r[0]['obj_image']) + if ($r[0]['obj_image']) $x['image'] = $r[0]['obj_image']; return $x; @@ -158,7 +158,7 @@ class Activity { static function fetch_item($x) { - if (array_key_exists('source',$x)) { + if (array_key_exists('source', $x)) { // This item is already processed and encoded return $x; } @@ -166,8 +166,8 @@ class Activity { $r = q("select * from item where mid = '%s' limit 1", dbesc($x['id']) ); - if($r) { - xchan_query($r,true); + if ($r) { + xchan_query($r, true); $r = fetch_post_tags($r); if (in_array($r[0]['verb'], ['Create', 'Invite']) && $r[0]['obj_type'] === ACTIVITY_OBJ_EVENT) { $r[0]['verb'] = 'Invite'; @@ -180,19 +180,19 @@ class Activity { static function fetch_image($x) { $ret = [ - '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'] + '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'] ] ]; return $ret; @@ -202,42 +202,42 @@ class Activity { // convert old Zot event objects to ActivityStreams Event objects - if (array_key_exists('content',$x) && array_key_exists('dtstart',$x)) { + if (array_key_exists('content', $x) && array_key_exists('dtstart', $x)) { $ev = bbtoevent($x['content']); - if($ev) { + if ($ev) { - if (! $ev['timezone']) { + if (!$ev['timezone']) { $ev['timezone'] = 'UTC'; } $actor = null; - if(array_key_exists('author',$x) && array_key_exists('link',$x['author'])) { + if (array_key_exists('author', $x) && array_key_exists('link', $x['author'])) { $actor = $x['author']['link'][0]['href']; } - $y = [ + $y = [ 'type' => 'Event', 'id' => z_root() . '/event/' . $ev['event_hash'], 'name' => $ev['summary'], -// 'summary' => bbcode($ev['summary'], [ 'cache' => true ]), + // 'summary' => bbcode($ev['summary'], [ 'cache' => true ]), // RFC3339 Section 4.3 - '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' ], + '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'], 'actor' => $actor, ]; - 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')); + 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')); } - + // copy attachments from the passed object - these are already formatted for ActivityStreams - if($x['attachment']) { + if ($x['attachment']) { $y['attachment'] = $x['attachment']; } - if($actor) { + if ($actor) { return $y; } } @@ -247,52 +247,99 @@ class Activity { } - - static function encode_item_collection($items,$id,$type,$extra = null) { + static function paged_collection_init($total, $id, $type = 'OrderedCollection') { $ret = [ - 'id' => z_root() . '/' . $id, - 'type' => $type, - 'totalItems' => count($items), + 'id' => z_root() . '/' . $id, + 'type' => $type, + 'totalItems' => $total, ]; - if($extra) - $ret = array_merge($ret,$extra); - if($items) { + $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) { + + if ($total > 100) { + $ret = [ + 'id' => z_root() . '/' . $id, + 'type' => $type . 'Page', + ]; + + $numpages = $total / App::$pager['itemspage']; + $lastpage = (($numpages > intval($numpages)) ? intval($numpages) + 1 : $numpages); + + $stripped = preg_replace('/([&|\?]page=[0-9]*)/', '', $id); + $stripped = rtrim($stripped, '/'); + + $ret['partOf'] = z_root() . '/' . $stripped; + + if (App::$pager['page'] < $lastpage) { + $ret['next'] = z_root() . '/' . $stripped . '?page=' . (intval(App::$pager['page']) + 1); + } + if (App::$pager['page'] > 1) { + $ret['prev'] = z_root() . '/' . $stripped . '?page=' . (intval(App::$pager['page']) - 1); + } + } + else { + $ret = [ + 'id' => z_root() . '/' . $id, + 'type' => $type, + 'totalItems' => $total, + ]; + } + + if ($items) { $x = []; - foreach($items as $i) { - $t = self::encode_activity($i); - if($t) + foreach ($items as $i) { + $m = get_iconfig($i['id'], 'activitypub', 'rawmsg'); + if (is_string($m)) { + $t = json_decode($m, true); + } + else { + $t = $m; + } + if ($t) { $x[] = $t; + } } - if($type === 'OrderedCollection') + if ($type === 'OrderedCollection') { $ret['orderedItems'] = $x; - else + } + else { $ret['items'] = $x; + } } return $ret; } - static function encode_follow_collection($items,$id,$type,$extra = null) { + static function encode_follow_collection($items, $id, $type, $extra = null) { $ret = [ - 'id' => z_root() . '/' . $id, - 'type' => $type, + 'id' => z_root() . '/' . $id, + 'type' => $type, 'totalItems' => count($items), ]; - if($extra) - $ret = array_merge($ret,$extra); + if ($extra) + $ret = array_merge($ret, $extra); - if($items) { + if ($items) { $x = []; - foreach($items as $i) { - if($i['xchan_url']) { + foreach ($items as $i) { + if ($i['xchan_url']) { $x[] = $i['xchan_url']; } } - if($type === 'OrderedCollection') + if ($type === 'OrderedCollection') $ret['orderedItems'] = $x; else $ret['items'] = $x; @@ -302,17 +349,15 @@ class Activity { } - - static function encode_item($i) { $ret = []; - if($i['verb'] === ACTIVITY_FRIEND) { + if ($i['verb'] === ACTIVITY_FRIEND) { // Hubzilla 'make-friend' activity, no direct mapping from AS1 to AS2 - make it a note $objtype = 'Note'; } - else { + else { $objtype = self::activity_obj_mapper($i['obj_type']); } @@ -321,13 +366,13 @@ class Activity { } if (intval($i['item_deleted'])) { - $ret['type'] = 'Tombstone'; + $ret['type'] = 'Tombstone'; $ret['formerType'] = $objtype; - $ret['id'] = $i['mid']; - if($i['id'] != $i['parent']) + $ret['id'] = $i['mid']; + if ($i['id'] != $i['parent']) $ret['inReplyTo'] = $i['thr_parent']; - $ret['to'] = [ ACTIVITY_PUBLIC_INBOX ]; + $ret['to'] = [ACTIVITY_PUBLIC_INBOX]; return $ret; } @@ -336,7 +381,7 @@ class Activity { $ret = $i['obj']; } else { - $ret = json_decode($i['obj'],true); + $ret = json_decode($i['obj'], true); } } @@ -348,96 +393,95 @@ class Activity { $ret = $i['obj']; } else { - $ret = json_decode($i['obj'],true); + $ret = json_decode($i['obj'], true); } - - if(array_path_exists('actor/id',$ret)) { + + if (array_path_exists('actor/id', $ret)) { $ret['actor'] = $ret['actor']['id']; } } } - - $ret['id'] = ((strpos($i['mid'],'http') === 0) ? $i['mid'] : z_root() . '/item/' . urlencode($i['mid'])); + $ret['id'] = ((strpos($i['mid'], 'http') === 0) ? $i['mid'] : z_root() . '/item/' . urlencode($i['mid'])); $ret['diaspora:guid'] = $i['uuid']; - if($i['title']) + if ($i['title']) $ret['name'] = $i['title']; - $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); + $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['expires'] <= NULL_DATE) { - $ret['expires'] = datetime_convert('UTC','UTC',$i['expires'],ATOM_TIME); + $ret['expires'] = datetime_convert('UTC', 'UTC', $i['expires'], ATOM_TIME); } - if($i['app']) { - $ret['generator'] = [ 'type' => 'Application', 'name' => $i['app'] ]; + if ($i['app']) { + $ret['generator'] = ['type' => 'Application', 'name' => $i['app']]; } - if($i['location'] || $i['coord']) { - $ret['location'] = [ 'type' => 'Place' ]; - if($i['location']) { + if ($i['location'] || $i['coord']) { + $ret['location'] = ['type' => 'Place']; + if ($i['location']) { $ret['location']['name'] = $i['location']; } - if($i['coord']) { - $l = explode(' ',$i['coord']); - $ret['location']['latitude'] = $l[0]; + if ($i['coord']) { + $l = explode(' ', $i['coord']); + $ret['location']['latitude'] = $l[0]; $ret['location']['longitude'] = $l[1]; } } if (intval($i['item_wall']) && $i['mid'] === $i['parent_mid']) { - $ret['commentPolicy'] = map_scope(PermissionLimits::Get($i['uid'],'post_comments')); + $ret['commentPolicy'] = map_scope(PermissionLimits::Get($i['uid'], 'post_comments')); } if (intval($i['item_private']) === 2) { $ret['directMessage'] = true; } - if (array_key_exists('comments_closed',$i) && $i['comments_closed'] !== EMPTY_STR && $i['comments_closed'] !== NULL_DATE) { - if($ret['commentPolicy']) { + if (array_key_exists('comments_closed', $i) && $i['comments_closed'] !== EMPTY_STR && $i['comments_closed'] !== NULL_DATE) { + if ($ret['commentPolicy']) { $ret['commentPolicy'] .= ' '; } - $ret['commentPolicy'] .= 'until=' . datetime_convert('UTC','UTC',$i['comments_closed'],ATOM_TIME); + $ret['commentPolicy'] .= 'until=' . datetime_convert('UTC', 'UTC', $i['comments_closed'], ATOM_TIME); } $ret['attributedTo'] = $i['author']['xchan_url']; - if($i['id'] != $i['parent']) { - $ret['inReplyTo'] = ((strpos($i['thr_parent'],'http') === 0) ? $i['thr_parent'] : z_root() . '/item/' . urlencode($i['thr_parent'])); + if ($i['id'] != $i['parent']) { + $ret['inReplyTo'] = ((strpos($i['thr_parent'], 'http') === 0) ? $i['thr_parent'] : z_root() . '/item/' . urlencode($i['thr_parent'])); } - 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' ]; + 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']; } - $actor = self::encode_person($i['author'],false); - if($actor) + $actor = self::encode_person($i['author'], false); + if ($actor) $ret['actor'] = $actor; else return []; $t = self::encode_taxonomy($i); - if($t) { - $ret['tag'] = $t; + if ($t) { + $ret['tag'] = $t; } $a = self::encode_attachment($i); - if($a) { + if ($a) { $ret['attachment'] = $a; } - $public = (($i['item_private']) ? false : true); + $public = (($i['item_private']) ? false : true); $top_level = (($i['mid'] === $i['parent_mid']) ? true : false); if ($public) { - $ret['to'] = [ ACTIVITY_PUBLIC_INBOX ]; - $ret['cc'] = [ z_root() . '/followers/' . substr($i['author']['xchan_addr'],0,strpos($i['author']['xchan_addr'],'@')) ]; + $ret['to'] = [ACTIVITY_PUBLIC_INBOX]; + $ret['cc'] = [z_root() . '/followers/' . substr($i['author']['xchan_addr'], 0, strpos($i['author']['xchan_addr'], '@'))]; } else { @@ -450,7 +494,7 @@ class Activity { $ret['to'] = []; if ($ret['tag']) { foreach ($ret['tag'] as $mention) { - if (is_array($mention) && array_key_exists('href',$mention) && $mention['href']) { + if (is_array($mention) && array_key_exists('href', $mention) && $mention['href']) { $h = q("select * from hubloc where hubloc_id_url = '%s' limit 1", dbesc($mention['href']) ); @@ -461,7 +505,7 @@ class Activity { else { $addr = $h[0]['hubloc_id_url']; } - if (! in_array($addr,$ret['to'])) { + if (!in_array($addr, $ret['to'])) { $ret['to'][] = $addr; } } @@ -478,7 +522,7 @@ class Activity { else { $addr = $d[0]['hubloc_id_url']; } - if (! in_array($addr,$ret['to'])) { + if (!in_array($addr, $ret['to'])) { $ret['cc'][] = $addr; } } @@ -487,7 +531,7 @@ class Activity { $mentions = self::map_mentions($i); if (count($mentions) > 0) { - if (! $ret['to']) { + if (!$ret['to']) { $ret['to'] = $mentions; } else { @@ -505,25 +549,25 @@ class Activity { if ($item['tag'] && is_array($item['tag'])) { $ptr = $item['tag']; - if (! array_key_exists(0,$ptr)) { - $ptr = [ $ptr ]; + if (!array_key_exists(0, $ptr)) { + $ptr = [$ptr]; } foreach ($ptr as $t) { - if (! array_key_exists('type',$t)) + if (!array_key_exists('type', $t)) $t['type'] = 'Hashtag'; - switch($t['type']) { + 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']) ]; + $ret[] = ['ttype' => TERM_HASHTAG, 'url' => $t['href'], 'term' => escape_tags((substr($t['name'], 0, 1) === '#') ? substr($t['name'], 1) : $t['name'])]; break; case 'Mention': - $mention_type = substr($t['name'],0,1); + $mention_type = substr($t['name'], 0, 1); if ($mention_type === '!') { - $ret[] = [ 'ttype' => TERM_FORUM, 'url' => $t['href'], 'term' => escape_tags(substr($t['name'],1)) ]; + $ret[] = ['ttype' => TERM_FORUM, 'url' => $t['href'], 'term' => escape_tags(substr($t['name'], 1))]; } else { - $ret[] = [ 'ttype' => TERM_MENTION, 'url' => $t['href'], 'term' => escape_tags((substr($t['name'],0,1) === '@') ? substr($t['name'],1) : $t['name']) ]; + $ret[] = ['ttype' => TERM_MENTION, 'url' => $t['href'], 'term' => escape_tags((substr($t['name'], 0, 1) === '@') ? substr($t['name'], 1) : $t['name'])]; } break; @@ -537,29 +581,28 @@ class Activity { } - static function encode_taxonomy($item) { $ret = []; - if($item['term']) { - foreach($item['term'] as $t) { - switch($t['ttype']) { + if ($item['term']) { + foreach ($item['term'] as $t) { + switch ($t['ttype']) { case TERM_HASHTAG: // href is required so if we don't have a url in the taxonomy, ignore it and keep going. - if($t['url']) { - $ret[] = [ 'type' => 'Hashtag', 'href' => $t['url'], 'name' => '#' . $t['term'] ]; + if ($t['url']) { + $ret[] = ['type' => 'Hashtag', 'href' => $t['url'], 'name' => '#' . $t['term']]; } break; case TERM_FORUM: - $ret[] = [ 'type' => 'Mention', 'href' => $t['url'], 'name' => '!' . $t['term'] ]; + $ret[] = ['type' => 'Mention', 'href' => $t['url'], 'name' => '!' . $t['term']]; break; case TERM_MENTION: - $ret[] = [ 'type' => 'Mention', 'href' => $t['url'], 'name' => '@' . $t['term'] ]; + $ret[] = ['type' => 'Mention', 'href' => $t['url'], 'name' => '@' . $t['term']]; break; - + default: break; } @@ -573,15 +616,15 @@ class Activity { $ret = []; - if($item['attach']) { - $atts = ((is_array($item['attach'])) ? $item['attach'] : json_decode($item['attach'],true)); - if($atts) { - foreach($atts as $att) { - if(strpos($att['type'],'image')) { - $ret[] = [ 'type' => 'Image', 'url' => $att['href'] ]; + if ($item['attach']) { + $atts = ((is_array($item['attach'])) ? $item['attach'] : json_decode($item['attach'], true)); + if ($atts) { + foreach ($atts as $att) { + if (strpos($att['type'], 'image')) { + $ret[] = ['type' => 'Image', 'url' => $att['href']]; } else { - $ret[] = [ 'type' => 'Link', 'mediaType' => $att['type'], 'href' => $att['href'] ]; + $ret[] = ['type' => 'Link', 'mediaType' => $att['type'], 'href' => $att['href']]; } } } @@ -590,11 +633,11 @@ class Activity { foreach ($item['iconfig'] as $att) { if ($att['sharing']) { $value = ((is_string($att['v']) && preg_match('|^a:[0-9]+:{.*}$|s', $att['v'])) ? unserialize($att['v']) : $att['v']); - $ret[] = [ 'type' => 'PropertyValue', 'name' => 'zot.' . $att['cat'] . '.' . $att['k'], 'value' => $value ]; + $ret[] = ['type' => 'PropertyValue', 'name' => 'zot.' . $att['cat'] . '.' . $att['k'], 'value' => $value]; } } } - + return $ret; } @@ -604,20 +647,20 @@ class Activity { if (is_array($item['attachment']) && $item['attachment']) { $ptr = $item['attachment']; - if (! array_key_exists(0,$ptr)) { - $ptr = [ $ptr ]; + if (!array_key_exists(0, $ptr)) { + $ptr = [$ptr]; } foreach ($ptr as $att) { $entry = []; if ($att['type'] === 'PropertyValue') { - if (array_key_exists('name',$att) && $att['name']) { - $key = explode('.',$att['name']); + if (array_key_exists('name', $att) && $att['name']) { + $key = explode('.', $att['name']); if (count($key) === 3 && $key[0] === 'zot') { - $entry['cat'] = $key[1]; - $entry['k'] = $key[2]; - $entry['v'] = $att['value']; + $entry['cat'] = $key[1]; + $entry['k'] = $key[2]; + $entry['v'] = $att['value']; $entry['sharing'] = '1'; - $ret[] = $entry; + $ret[] = $entry; } } } @@ -627,23 +670,22 @@ class Activity { } - static function decode_attachment($item) { $ret = []; - if($item['attachment']) { - foreach($item['attachment'] as $att) { + if ($item['attachment']) { + foreach ($item['attachment'] as $att) { $entry = []; - if($att['href']) + if ($att['href']) $entry['href'] = $att['href']; - elseif($att['url']) + elseif ($att['url']) $entry['href'] = $att['url']; - if($att['mediaType']) + if ($att['mediaType']) $entry['type'] = $att['mediaType']; - elseif($att['type'] === 'Image') + elseif ($att['type'] === 'Image') $entry['type'] = 'image/jpeg'; - if($entry) + if ($entry) $ret[] = $entry; } } @@ -652,210 +694,187 @@ class Activity { } - static function encode_activity($i, $recurse = false) { $ret = []; $reply = false; - if($i['verb'] === ACTIVITY_FRIEND) { + if ($i['verb'] === ACTIVITY_FRIEND) { // Hubzilla 'make-friend' activity, no direct mapping from AS1 to AS2 - make it a note $ret['obj'] = []; } $ret['type'] = self::activity_mapper($i['verb']); - $fragment = ''; if (intval($i['item_deleted']) && !$recurse) { $is_response = false; if (ActivityStreams::is_response_activity($ret['type'])) { $ret['type'] = 'Undo'; - $fragment = 'undo'; + $fragment = 'undo'; $is_response = true; } else { $ret['type'] = 'Delete'; - $fragment = 'delete'; + $fragment = 'delete'; } - $ret['id'] = str_replace('/item/','/activity/',$i['mid']) . '#' . $fragment; - $actor = self::encode_person($i['author'],false); + $ret['id'] = str_replace('/item/', '/activity/', $i['mid']) . '#' . $fragment; + $actor = self::encode_person($i['author'], false); if ($actor) $ret['actor'] = $actor; else - return []; + return []; - $obj = (($is_response) ? self::encode_activity($i,true) : self::encode_item($i,true)); + $obj = (($is_response) ? self::encode_activity($i, true) : self::encode_item($i)); if ($obj) { - if (array_path_exists('object/id',$obj)) { + if (array_path_exists('object/id', $obj)) { $obj['object'] = $obj['object']['id']; } unset($obj['cc']); - $obj['to'] = [ ACTIVITY_PUBLIC_INBOX ]; + $obj['to'] = [ACTIVITY_PUBLIC_INBOX]; $ret['object'] = $obj; } else return []; - $ret['to'] = [ ACTIVITY_PUBLIC_INBOX ]; + $ret['to'] = [ACTIVITY_PUBLIC_INBOX]; return $ret; } - if($ret['type'] === 'emojiReaction') { + if ($ret['type'] === 'emojiReaction') { // 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']) ); - if($p) { - xchan_query($p,true); - $p = fetch_post_tags($p); + if ($p) { + xchan_query($p, true); + $p = fetch_post_tags($p); $i['obj'] = self::encode_item($p[0]); // convert to zot6 emoji reaction encoding which uses the target object to indicate the // specific emoji instead of overloading the verb or type. - - $im = explode('#',$i['verb']); - if($im && count($im) > 1) + + $im = explode('#', $i['verb']); + if ($im && count($im) > 1) $emoji = $im[1]; - if(preg_match("/\[img(.*?)\](.*?)\[\/img\]/ism", $i['body'], $match)) { + if (preg_match("/\[img(.*?)\](.*?)\[\/img\]/ism", $i['body'], $match)) { $ln = $match[2]; } $i['tgt_type'] = 'Image'; - + $i['target'] = [ 'type' => 'Image', 'name' => $emoji, 'url' => (($ln) ? $ln : z_root() . '/images/emoji/' . $emoji . '.png') ]; - + } } - if (strpos($i['mid'],z_root() . '/item/') !== false) { - $ret['id'] = str_replace('/item/','/activity/',$i['mid']); + if (strpos($i['mid'], z_root() . '/item/') !== false) { + $ret['id'] = str_replace('/item/', '/activity/', $i['mid']); } - elseif (strpos($i['mid'],z_root() . '/event/') !== false) { - $ret['id'] = str_replace('/event/','/activity/',$i['mid']); + elseif (strpos($i['mid'], z_root() . '/event/') !== false) { + $ret['id'] = str_replace('/event/', '/activity/', $i['mid']); } else { - $ret['id'] = ((strpos($i['mid'],'http') === 0) ? $i['mid'] : z_root() . '/activity/' . urlencode($i['mid'])); + $ret['id'] = ((strpos($i['mid'], 'http') === 0) ? $i['mid'] : z_root() . '/activity/' . urlencode($i['mid'])); } $ret['diaspora:guid'] = $i['uuid']; - if($i['title']) - $ret['name'] = html2plain(bbcode($i['title'], [ 'cache' => true ])); + if ($i['title']) + $ret['name'] = html2plain(bbcode($i['title'], ['cache' => true])); - if($i['summary']) - $ret['summary'] = bbcode($i['summary'], [ 'cache' => true ]); + if ($i['summary']) + $ret['summary'] = bbcode($i['summary'], ['cache' => true]); - 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'], + 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'], 'mediaType' => 'text/bbcode' ]; } - $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'] ]; + $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']]; } - if($i['location'] || $i['coord']) { - $ret['location'] = [ 'type' => 'Place' ]; - if($i['location']) { + if ($i['location'] || $i['coord']) { + $ret['location'] = ['type' => 'Place']; + if ($i['location']) { $ret['location']['name'] = $i['location']; } - if($i['coord']) { - $l = explode(' ',$i['coord']); - $ret['location']['latitude'] = $l[0]; + if ($i['coord']) { + $l = explode(' ', $i['coord']); + $ret['location']['latitude'] = $l[0]; $ret['location']['longitude'] = $l[1]; } } - if($i['id'] != $i['parent']) { + if ($i['id'] != $i['parent']) { $reply = true; // 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 - - 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'])); - } - - if($i['item_private']) { - $d = q("select xchan_url, xchan_addr, xchan_name from item left join xchan on xchan_hash = author_xchan where id = %d limit 1", - intval($i['parent']) - ); - if($d) { - $is_directmessage = false; - $recips = get_iconfig($i['parent'], 'activitypub', 'recips'); - - if(array_path_exists('to', $recips) && in_array($i['author']['xchan_url'], $recips['to'])) { - $reply_url = $d[0]['xchan_url']; - $is_directmessage = true; - } - else { - $reply_url = z_root() . '/followers/' . substr($i['author']['xchan_addr'],0,strpos($i['author']['xchan_addr'],'@')); - } - $reply_addr = (($d[0]['xchan_addr']) ? $d[0]['xchan_addr'] : $d[0]['xchan_name']); - } + 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'])); } - } - $actor = self::encode_person($i['author'],false); - if($actor) + $actor = self::encode_person($i['author'], false); + if ($actor) $ret['actor'] = $actor; else - return []; + return []; - if(strpos($i['body'],'[/share]') !== false) { + if (strpos($i['body'], '[/share]') !== false) { $i['obj'] = null; } - if($i['obj']) { - if(! is_array($i['obj'])) { - $i['obj'] = json_decode($i['obj'],true); + if ($i['obj']) { + if (!is_array($i['obj'])) { + $i['obj'] = json_decode($i['obj'], true); } - if($i['obj']['type'] === ACTIVITY_OBJ_PHOTO) { + if ($i['obj']['type'] === ACTIVITY_OBJ_PHOTO) { $i['obj']['id'] = $i['mid']; } $obj = self::encode_object($i['obj']); - if($obj) + if ($obj) $ret['object'] = $obj; else return []; } else { $obj = self::encode_item($i); - if($obj) + if ($obj) $ret['object'] = $obj; else return []; } - if(array_path_exists('object/type',$ret) && $ret['object']['type'] === 'Event' && $ret['type'] === 'Create') { + if (array_path_exists('object/type', $ret) && $ret['object']['type'] === 'Event' && $ret['type'] === 'Create') { $ret['type'] = 'Invite'; } - if($i['target']) { - if(! is_array($i['target'])) { - $i['target'] = json_decode($i['target'],true); + if ($i['target']) { + if (!is_array($i['target'])) { + $i['target'] = json_decode($i['target'], true); } $tgt = self::encode_object($i['target']); - if($tgt) + if ($tgt) $ret['target'] = $tgt; else return []; @@ -868,12 +887,12 @@ class Activity { // addressing madness - $public = (($i['item_private']) ? false : true); + $public = (($i['item_private']) ? false : true); $top_level = (($reply) ? false : true); if ($public) { - $ret['to'] = [ ACTIVITY_PUBLIC_INBOX ]; - $ret['cc'] = [ z_root() . '/followers/' . substr($i['author']['xchan_addr'],0,strpos($i['author']['xchan_addr'],'@')) ]; + $ret['to'] = [ACTIVITY_PUBLIC_INBOX]; + $ret['cc'] = [z_root() . '/followers/' . substr($i['author']['xchan_addr'], 0, strpos($i['author']['xchan_addr'], '@'))]; } else { @@ -886,7 +905,7 @@ class Activity { $ret['to'] = []; if ($ret['tag']) { foreach ($ret['tag'] as $mention) { - if (is_array($mention) && array_key_exists('href',$mention) && $mention['href']) { + if (is_array($mention) && array_key_exists('href', $mention) && $mention['href']) { $h = q("select * from hubloc where hubloc_id_url = '%s' limit 1", dbesc($mention['href']) ); @@ -897,7 +916,7 @@ class Activity { else { $addr = $h[0]['hubloc_id_url']; } - if (! in_array($addr,$ret['to'])) { + if (!in_array($addr, $ret['to'])) { $ret['to'][] = $addr; } } @@ -915,7 +934,7 @@ class Activity { else { $addr = $d[0]['hubloc_id_url']; } - if (! in_array($addr,$ret['to'])) { + if (!in_array($addr, $ret['to'])) { $ret['cc'][] = $addr; } } @@ -924,7 +943,7 @@ class Activity { $mentions = self::map_mentions($i); if (count($mentions) > 0) { - if (! $ret['to']) { + if (!$ret['to']) { $ret['to'] = $mentions; } else { @@ -939,18 +958,18 @@ class Activity { static function map_mentions($i) { - if (! $i['term']) { + if (!$i['term']) { return []; } $list = []; foreach ($i['term'] as $t) { - if (! $t['url']) { + if (!$t['url']) { continue; } if ($t['ttype'] == TERM_MENTION) { - $url = self::lookup_term_url($t['url']); + $url = self::lookup_term_url($t['url']); $list[] = (($url) ? $url : $t['url']); } } @@ -963,7 +982,7 @@ class Activity { static function map_acl($i) { $ret = []; - if (! $i['item_private']) { + if (!$i['item_private']) { return $ret; } @@ -977,8 +996,8 @@ class Activity { } if ($i['allow_cid']) { - $tmp = expand_acl($i['allow_cid']); - $list = stringify_array($tmp,true); + $tmp = expand_acl($i['allow_cid']); + $list = stringify_array($tmp, true); if ($list) { $details = q("select hubloc_id_url from hubloc where hubloc_hash in (" . $list . ") and hubloc_id_url != ''"); if ($details) { @@ -1013,22 +1032,22 @@ class Activity { static function encode_person($p, $extended = true) { - if(! $p['xchan_url']) + if (!$p['xchan_url']) return []; - if(! $extended) { + if (!$extended) { return $p['xchan_url']; } $ret = []; - $c = ((array_key_exists('channel_id',$p)) ? $p : channelx_by_hash($p['xchan_hash'])); + $c = ((array_key_exists('channel_id', $p)) ? $p : channelx_by_hash($p['xchan_hash'])); - $ret['type'] = 'Person'; + $ret['type'] = 'Person'; if ($c) { - $role = get_pconfig($c['channel_id'],'system','permissions_role'); - if (strpos($role,'forum') !== false) { + $role = get_pconfig($c['channel_id'], 'system', 'permissions_role'); + if (strpos($role, 'forum') !== false) { $ret['type'] = 'Group'; } } @@ -1037,23 +1056,23 @@ class Activity { $ret['id'] = channel_url($c); } else { - $ret['id'] = ((strpos($p['xchan_hash'],'http') === 0) ? $p['xchan_hash'] : $p['xchan_url']); + $ret['id'] = ((strpos($p['xchan_hash'], 'http') === 0) ? $p['xchan_hash'] : $p['xchan_url']); } - if($p['xchan_addr'] && strpos($p['xchan_addr'],'@')) - $ret['preferredUsername'] = substr($p['xchan_addr'],0,strpos($p['xchan_addr'],'@')); - $ret['name'] = $p['xchan_name']; - $ret['updated'] = datetime_convert('UTC','UTC',$p['xchan_name_date'],ATOM_TIME); - $ret['icon'] = [ + if ($p['xchan_addr'] && strpos($p['xchan_addr'], '@')) + $ret['preferredUsername'] = substr($p['xchan_addr'], 0, strpos($p['xchan_addr'], '@')); + $ret['name'] = $p['xchan_name']; + $ret['updated'] = datetime_convert('UTC', 'UTC', $p['xchan_name_date'], ATOM_TIME); + $ret['icon'] = [ 'type' => 'Image', - 'mediaType' => (($p['xchan_photo_mimetype']) ? $p['xchan_photo_mimetype'] : 'image/png' ), - 'updated' => datetime_convert('UTC','UTC',$p['xchan_photo_date'],ATOM_TIME), + 'mediaType' => (($p['xchan_photo_mimetype']) ? $p['xchan_photo_mimetype'] : 'image/png'), + 'updated' => datetime_convert('UTC', 'UTC', $p['xchan_photo_date'], ATOM_TIME), 'url' => $p['xchan_photo_l'], 'height' => 300, 'width' => 300, ]; - $ret['url'] = [ - [ + $ret['url'] = [ + [ 'type' => 'Link', 'mediaType' => 'text/html', 'href' => $p['xchan_url'] @@ -1071,7 +1090,7 @@ class Activity { 'publicKeyPem' => $p['xchan_pubkey'] ]; - $arr = [ 'xchan' => $p, 'encoded' => $ret ]; + $arr = ['xchan' => $p, 'encoded' => $ret]; call_hooks('encode_person', $arr); $ret = $arr['encoded']; @@ -1080,89 +1099,82 @@ class Activity { } - - - - - - static function activity_mapper($verb) { - if(strpos($verb,'/') === false) { + if (strpos($verb, '/') === false) { return $verb; } $acts = [ - 'http://activitystrea.ms/schema/1.0/post' => 'Create', - 'http://activitystrea.ms/schema/1.0/share' => 'Announce', - 'http://activitystrea.ms/schema/1.0/update' => 'Update', - 'http://activitystrea.ms/schema/1.0/like' => 'Like', - 'http://activitystrea.ms/schema/1.0/favorite' => 'Like', - 'http://purl.org/zot/activity/dislike' => 'Dislike', - 'http://activitystrea.ms/schema/1.0/tag' => 'Add', - 'http://activitystrea.ms/schema/1.0/follow' => 'Follow', - 'http://activitystrea.ms/schema/1.0/unfollow' => 'Unfollow', - 'http://purl.org/zot/activity/attendyes' => 'Accept', - 'http://purl.org/zot/activity/attendno' => 'Reject', - 'http://purl.org/zot/activity/attendmaybe' => 'TentativeAccept', - 'Invite' => 'Invite', - 'Delete' => 'Delete', - 'Undo' => 'Undo' + 'http://activitystrea.ms/schema/1.0/post' => 'Create', + 'http://activitystrea.ms/schema/1.0/share' => 'Announce', + 'http://activitystrea.ms/schema/1.0/update' => 'Update', + 'http://activitystrea.ms/schema/1.0/like' => 'Like', + 'http://activitystrea.ms/schema/1.0/favorite' => 'Like', + 'http://purl.org/zot/activity/dislike' => 'Dislike', + 'http://activitystrea.ms/schema/1.0/tag' => 'Add', + 'http://activitystrea.ms/schema/1.0/follow' => 'Follow', + 'http://activitystrea.ms/schema/1.0/unfollow' => 'Unfollow', + 'http://purl.org/zot/activity/attendyes' => 'Accept', + 'http://purl.org/zot/activity/attendno' => 'Reject', + 'http://purl.org/zot/activity/attendmaybe' => 'TentativeAccept', + 'Invite' => 'Invite', + 'Delete' => 'Delete', + 'Undo' => 'Undo' ]; - call_hooks('activity_mapper',$acts); + call_hooks('activity_mapper', $acts); - if(array_key_exists($verb,$acts) && $acts[$verb]) { + if (array_key_exists($verb, $acts) && $acts[$verb]) { return $acts[$verb]; } // Reactions will just map to normal activities - if(strpos($verb,ACTIVITY_REACT) !== false) + if (strpos($verb, ACTIVITY_REACT) !== false) return 'emojiReaction'; - if(strpos($verb,ACTIVITY_MOOD) !== false) + if (strpos($verb, ACTIVITY_MOOD) !== false) return 'Create'; - if(strpos($verb,ACTIVITY_FRIEND) !== false) + if (strpos($verb, ACTIVITY_FRIEND) !== false) return 'Create'; - if(strpos($verb,ACTIVITY_POKE) !== false) + if (strpos($verb, ACTIVITY_POKE) !== false) return 'Activity'; // We should return false, however this will trigger an uncaught execption and crash // the delivery system if encountered by the JSON-LDSignature library - + logger('Unmapped activity: ' . $verb); return 'Create'; - // return false; -} - + // return false; + } static function activity_decode_mapper($verb) { $acts = [ - 'http://activitystrea.ms/schema/1.0/post' => 'Create', - 'http://activitystrea.ms/schema/1.0/share' => 'Announce', - 'http://activitystrea.ms/schema/1.0/update' => 'Update', - 'http://activitystrea.ms/schema/1.0/like' => 'Like', - 'http://activitystrea.ms/schema/1.0/favorite' => 'Like', - 'http://purl.org/zot/activity/dislike' => 'Dislike', - 'http://activitystrea.ms/schema/1.0/tag' => 'Add', - 'http://activitystrea.ms/schema/1.0/follow' => 'Follow', - 'http://activitystrea.ms/schema/1.0/unfollow' => 'Unfollow', - 'http://purl.org/zot/activity/attendyes' => 'Accept', - 'http://purl.org/zot/activity/attendno' => 'Reject', - 'http://purl.org/zot/activity/attendmaybe' => 'TentativeAccept', - 'Invite' => 'Invite', - 'Delete' => 'Delete', - 'Undo' => 'Undo' + 'http://activitystrea.ms/schema/1.0/post' => 'Create', + 'http://activitystrea.ms/schema/1.0/share' => 'Announce', + 'http://activitystrea.ms/schema/1.0/update' => 'Update', + 'http://activitystrea.ms/schema/1.0/like' => 'Like', + 'http://activitystrea.ms/schema/1.0/favorite' => 'Like', + 'http://purl.org/zot/activity/dislike' => 'Dislike', + 'http://activitystrea.ms/schema/1.0/tag' => 'Add', + 'http://activitystrea.ms/schema/1.0/follow' => 'Follow', + 'http://activitystrea.ms/schema/1.0/unfollow' => 'Unfollow', + 'http://purl.org/zot/activity/attendyes' => 'Accept', + 'http://purl.org/zot/activity/attendno' => 'Reject', + 'http://purl.org/zot/activity/attendmaybe' => 'TentativeAccept', + 'Invite' => 'Invite', + 'Delete' => 'Delete', + 'Undo' => 'Undo' ]; - call_hooks('activity_decode_mapper',$acts); + call_hooks('activity_decode_mapper', $acts); - foreach($acts as $k => $v) { - if($verb === $v) { + foreach ($acts as $k => $v) { + if ($verb === $v) { return $k; } } @@ -1175,33 +1187,33 @@ class Activity { static function activity_obj_decode_mapper($obj) { $objs = [ - 'http://activitystrea.ms/schema/1.0/note' => 'Note', - 'http://activitystrea.ms/schema/1.0/note' => 'Article', - 'http://activitystrea.ms/schema/1.0/comment' => 'Note', - 'http://activitystrea.ms/schema/1.0/person' => 'Person', - 'http://purl.org/zot/activity/profile' => 'Profile', - 'http://activitystrea.ms/schema/1.0/photo' => 'Image', - 'http://activitystrea.ms/schema/1.0/profile-photo' => 'Icon', - 'http://activitystrea.ms/schema/1.0/event' => 'Event', - 'http://purl.org/zot/activity/location' => 'Place', - 'http://purl.org/zot/activity/chessgame' => 'Game', - 'http://purl.org/zot/activity/tagterm' => 'zot:Tag', - 'http://purl.org/zot/activity/thing' => 'Object', - 'http://purl.org/zot/activity/file' => 'zot:File', - 'http://purl.org/zot/activity/mood' => 'zot:Mood', - 'Invite' => 'Invite', - 'Question' => 'Question', - 'Document' => 'Document', - 'Audio' => 'Audio', - 'Video' => 'Video', - 'Delete' => 'Delete', - 'Undo' => 'Undo' + 'http://activitystrea.ms/schema/1.0/note' => 'Note', + 'http://activitystrea.ms/schema/1.0/note' => 'Article', + 'http://activitystrea.ms/schema/1.0/comment' => 'Note', + 'http://activitystrea.ms/schema/1.0/person' => 'Person', + 'http://purl.org/zot/activity/profile' => 'Profile', + 'http://activitystrea.ms/schema/1.0/photo' => 'Image', + 'http://activitystrea.ms/schema/1.0/profile-photo' => 'Icon', + 'http://activitystrea.ms/schema/1.0/event' => 'Event', + 'http://purl.org/zot/activity/location' => 'Place', + 'http://purl.org/zot/activity/chessgame' => 'Game', + 'http://purl.org/zot/activity/tagterm' => 'zot:Tag', + 'http://purl.org/zot/activity/thing' => 'Object', + 'http://purl.org/zot/activity/file' => 'zot:File', + 'http://purl.org/zot/activity/mood' => 'zot:Mood', + 'Invite' => 'Invite', + 'Question' => 'Question', + 'Document' => 'Document', + 'Audio' => 'Audio', + 'Video' => 'Video', + 'Delete' => 'Delete', + 'Undo' => 'Undo' ]; - call_hooks('activity_obj_decode_mapper',$objs); + call_hooks('activity_obj_decode_mapper', $objs); - foreach($objs as $k => $v) { - if($obj === $v) { + foreach ($objs as $k => $v) { + if ($obj === $v) { return $k; } } @@ -1211,44 +1223,42 @@ class Activity { } - - static function activity_obj_mapper($obj) { $objs = [ - 'http://activitystrea.ms/schema/1.0/note' => 'Note', - 'http://activitystrea.ms/schema/1.0/comment' => 'Note', - 'http://activitystrea.ms/schema/1.0/person' => 'Person', - 'http://purl.org/zot/activity/profile' => 'Profile', - 'http://activitystrea.ms/schema/1.0/photo' => 'Image', - 'http://activitystrea.ms/schema/1.0/profile-photo' => 'Icon', - 'http://activitystrea.ms/schema/1.0/event' => 'Event', - 'http://purl.org/zot/activity/location' => 'Place', - 'http://purl.org/zot/activity/chessgame' => 'Game', - 'http://purl.org/zot/activity/tagterm' => 'zot:Tag', - 'http://purl.org/zot/activity/thing' => 'Object', - 'http://purl.org/zot/activity/file' => 'zot:File', - 'http://purl.org/zot/activity/mood' => 'zot:Mood', - 'Invite' => 'Invite', - 'Question' => 'Question', - 'Audio' => 'Audio', - 'Video' => 'Video', - 'Delete' => 'Delete', - 'Undo' => 'Undo' + 'http://activitystrea.ms/schema/1.0/note' => 'Note', + 'http://activitystrea.ms/schema/1.0/comment' => 'Note', + 'http://activitystrea.ms/schema/1.0/person' => 'Person', + 'http://purl.org/zot/activity/profile' => 'Profile', + 'http://activitystrea.ms/schema/1.0/photo' => 'Image', + 'http://activitystrea.ms/schema/1.0/profile-photo' => 'Icon', + 'http://activitystrea.ms/schema/1.0/event' => 'Event', + 'http://purl.org/zot/activity/location' => 'Place', + 'http://purl.org/zot/activity/chessgame' => 'Game', + 'http://purl.org/zot/activity/tagterm' => 'zot:Tag', + 'http://purl.org/zot/activity/thing' => 'Object', + 'http://purl.org/zot/activity/file' => 'zot:File', + 'http://purl.org/zot/activity/mood' => 'zot:Mood', + 'Invite' => 'Invite', + 'Question' => 'Question', + 'Audio' => 'Audio', + 'Video' => 'Video', + 'Delete' => 'Delete', + 'Undo' => 'Undo' ]; - call_hooks('activity_obj_mapper',$objs); + call_hooks('activity_obj_mapper', $objs); if ($obj === 'Answer') { return 'Note'; } - if (strpos($obj,'/') === false) { + if (strpos($obj, '/') === false) { return $obj; } - if(array_key_exists($obj,$objs)) { + if (array_key_exists($obj, $objs)) { return $objs[$obj]; } @@ -1260,9 +1270,9 @@ class Activity { } - static function follow($channel,$act) { + static function follow($channel, $act) { - $contact = null; + $contact = null; $their_follow_id = null; /* @@ -1274,18 +1284,15 @@ class Activity { $person_obj = $act->actor; - if($act->type === 'Follow') { - $their_follow_id = $act->id; - } - elseif($act->type === 'Accept') { - $my_follow_id = z_root() . '/follow/' . $contact['id']; + if ($act->type === 'Follow') { + $their_follow_id = $act->id; } - - if(is_array($person_obj)) { + + if (is_array($person_obj)) { // store their xchan and hubloc - self::actor_store($person_obj['id'],$person_obj); + self::actor_store($person_obj['id'], $person_obj); // Find any existing abook record @@ -1293,74 +1300,74 @@ class Activity { dbesc($person_obj['id']), intval($channel['channel_id']) ); - if($r) { + if ($r) { $contact = $r[0]; } } - $x = \Zotlabs\Access\PermissionRoles::role_perms('social'); - $p = \Zotlabs\Access\Permissions::FilledPerms($x['perms_connect']); - $their_perms = \Zotlabs\Access\Permissions::serialise($p); + $x = PermissionRoles::role_perms('social'); + $p = Permissions::FilledPerms($x['perms_connect']); + $their_perms = Permissions::serialise($p); - if($contact && $contact['abook_id']) { + if ($contact && $contact['abook_id']) { // A relationship of some form already exists on this site. - switch($act->type) { + switch ($act->type) { case 'Follow': // A second Follow request, but we haven't approved the first one - if($contact['abook_pending']) { + if ($contact['abook_pending']) { return; } // We've already approved them or followed them first // Send an Accept back to them - set_abconfig($channel['channel_id'],$person_obj['id'],'pubcrawl','their_follow_id', $their_follow_id); - Master::Summon([ 'Notifier', 'permissions_accept', $contact['abook_id'] ]); + set_abconfig($channel['channel_id'], $person_obj['id'], 'pubcrawl', 'their_follow_id', $their_follow_id); + Master::Summon(['Notifier', 'permissions_accept', $contact['abook_id']]); return; case 'Accept': // They accepted our Follow request - set default permissions - - set_abconfig($channel['channel_id'],$contact['abook_xchan'],'system','their_perms',$their_perms); + + set_abconfig($channel['channel_id'], $contact['abook_xchan'], 'system', 'their_perms', $their_perms); $abook_instance = $contact['abook_instance']; - - if(strpos($abook_instance,z_root()) === false) { - if($abook_instance) + + if (strpos($abook_instance, z_root()) === false) { + if ($abook_instance) $abook_instance .= ','; $abook_instance .= z_root(); - $r = q("update abook set abook_instance = '%s', abook_not_here = 0 + q("update abook set abook_instance = '%s', abook_not_here = 0 where abook_id = %d and abook_channel = %d", dbesc($abook_instance), intval($contact['abook_id']), intval($channel['channel_id']) ); } - + return; default: return; - + } } // No previous relationship exists. - if($act->type === 'Accept') { + if ($act->type === 'Accept') { // This should not happen unless we deleted the connection before it was accepted. return; } // From here on out we assume a Follow activity to somebody we have no existing relationship with - set_abconfig($channel['channel_id'],$person_obj['id'],'pubcrawl','their_follow_id', $their_follow_id); + set_abconfig($channel['channel_id'], $person_obj['id'], 'pubcrawl', 'their_follow_id', $their_follow_id); // The xchan should have been created by actor_store() above @@ -1368,17 +1375,17 @@ class Activity { dbesc($person_obj['id']) ); - if(! $r) { + if (!$r) { logger('xchan not found for ' . $person_obj['id']); return; } $ret = $r[0]; - $p = \Zotlabs\Access\Permissions::connect_perms($channel['channel_id']); - $my_perms = \Zotlabs\Access\Permissions::serialise($p['perms']); + $p = Permissions::connect_perms($channel['channel_id']); + $my_perms = Permissions::serialise($p['perms']); $automatic = $p['automatic']; - $closeness = get_pconfig($channel['channel_id'],'system','new_abook_closeness',80); + $closeness = get_pconfig($channel['channel_id'], 'system', 'new_abook_closeness', 80); $r = abook_store_lowlevel( [ @@ -1394,64 +1401,64 @@ class Activity { 'abook_instance' => z_root() ] ); - - if($my_perms) - set_abconfig($channel['channel_id'],$ret['xchan_hash'],'system','my_perms',$my_perms); - if($their_perms) - set_abconfig($channel['channel_id'],$ret['xchan_hash'],'system','their_perms',$their_perms); + if ($my_perms) + set_abconfig($channel['channel_id'], $ret['xchan_hash'], 'system', 'my_perms', $my_perms); + if ($their_perms) + set_abconfig($channel['channel_id'], $ret['xchan_hash'], 'system', 'their_perms', $their_perms); - if($r) { + + if ($r) { logger("New ActivityPub follower for {$channel['channel_name']}"); $new_connection = q("select * from abook left join xchan on abook_xchan = xchan_hash left join hubloc on hubloc_hash = xchan_hash where abook_channel = %d and abook_xchan = '%s' order by abook_created desc limit 1", intval($channel['channel_id']), dbesc($ret['xchan_hash']) ); - if($new_connection) { - \Zotlabs\Lib\Enotify::submit( + if ($new_connection) { + Enotify::submit( [ - 'type' => NOTIFY_INTRO, - 'from_xchan' => $ret['xchan_hash'], - 'to_xchan' => $channel['channel_hash'], - 'link' => z_root() . '/connedit/' . $new_connection[0]['abook_id'], + 'type' => NOTIFY_INTRO, + 'from_xchan' => $ret['xchan_hash'], + 'to_xchan' => $channel['channel_hash'], + 'link' => z_root() . '/connedit/' . $new_connection[0]['abook_id'], ] ); - if($my_perms && $automatic) { + if ($my_perms && $automatic) { // send an Accept for this Follow activity - Master::Summon([ 'Notifier', 'permissions_accept', $new_connection[0]['abook_id'] ]); + Master::Summon(['Notifier', 'permissions_accept', $new_connection[0]['abook_id']]); // Send back a Follow notification to them - Master::Summon([ 'Notifier', 'permissions_create', $new_connection[0]['abook_id'] ]); + Master::Summon(['Notifier', 'permissions_create', $new_connection[0]['abook_id']]); } - $clone = array(); - foreach($new_connection[0] as $k => $v) { - if(strpos($k,'abook_') === 0) { + $clone = []; + foreach ($new_connection[0] as $k => $v) { + if (strpos($k, 'abook_') === 0) { $clone[$k] = $v; } } unset($clone['abook_id']); unset($clone['abook_account']); unset($clone['abook_channel']); - - $abconfig = load_abconfig($channel['channel_id'],$clone['abook_xchan']); - if($abconfig) + $abconfig = load_abconfig($channel['channel_id'], $clone['abook_xchan']); + + if ($abconfig) $clone['abconfig'] = $abconfig; - Libsync::build_sync_packet($channel['channel_id'], [ 'abook' => array($clone) ] ); + Libsync::build_sync_packet($channel['channel_id'], ['abook' => [$clone]]); } } /* If there is a default group for this channel and permissions are automatic, add this member to it */ - if($channel['channel_default_group'] && $automatic) { - $g = Group::rec_byhash($channel['channel_id'],$channel['channel_default_group']); - if($g) - Group::member_add($channel['channel_id'],'',$ret['xchan_hash'],$g['id']); + if ($channel['channel_default_group'] && $automatic) { + $g = Group::rec_byhash($channel['channel_id'], $channel['channel_default_group']); + if ($g) + Group::member_add($channel['channel_id'], '', $ret['xchan_hash'], $g['id']); } @@ -1460,7 +1467,7 @@ class Activity { } - static function unfollow($channel,$act) { + static function unfollow($channel, $act) { $contact = null; @@ -1470,15 +1477,15 @@ class Activity { $person_obj = $act->actor; - if(is_array($person_obj)) { + if (is_array($person_obj)) { $r = q("select * from abook left join xchan on abook_xchan = xchan_hash where abook_xchan = '%s' and abook_channel = %d limit 1", dbesc($person_obj['id']), intval($channel['channel_id']) ); - if($r) { + if ($r) { // remove all permissions they provided - del_abconfig($channel['channel_id'],$r[0]['xchan_hash'],'system','their_perms',EMPTY_STR); + del_abconfig($channel['channel_id'], $r[0]['xchan_hash'], 'system', 'their_perms'); } } @@ -1486,30 +1493,28 @@ class Activity { } + static function actor_store($url, $person_obj) { - - static function actor_store($url,$person_obj) { - - if(! is_array($person_obj)) + if (!is_array($person_obj)) return; $inbox = $person_obj['inbox']; // invalid identity - if (! $inbox || strpos($inbox,z_root()) !== false) { + if (!$inbox || strpos($inbox, z_root()) !== false) { return; } $name = $person_obj['name']; - if(! $name) + if (!$name) $name = $person_obj['preferredUsername']; - if(! $name) + if (!$name) $name = t('Unknown'); - if($person_obj['icon']) { - if(is_array($person_obj['icon'])) { - if(array_key_exists('url',$person_obj['icon'])) + if ($person_obj['icon']) { + if (is_array($person_obj['icon'])) { + if (array_key_exists('url', $person_obj['icon'])) $icon = $person_obj['icon']['url']; else $icon = $person_obj['icon'][0]['url']; @@ -1518,12 +1523,12 @@ class Activity { $icon = $person_obj['icon']; } - $links = false; + $links = false; $profile = false; if (is_array($person_obj['url'])) { - if (! array_key_exists(0,$person_obj['url'])) { - $links = [ $person_obj['url'] ]; + if (!array_key_exists(0, $person_obj['url'])) { + $links = [$person_obj['url']]; } else { $links = $person_obj['url']; @@ -1532,11 +1537,11 @@ class Activity { if ($links) { foreach ($links as $link) { - if (array_key_exists('mediaType',$link) && $link['mediaType'] === 'text/html') { + if (array_key_exists('mediaType', $link) && $link['mediaType'] === 'text/html') { $profile = $link['href']; } } - if (! $profile) { + if (!$profile) { $profile = $links[0]['href']; } } @@ -1544,28 +1549,28 @@ class Activity { $profile = $person_obj['url']; } - if (! $profile) { + if (!$profile) { $profile = $url; } $collections = []; - if($inbox) { + if ($inbox) { $collections['inbox'] = $inbox; - if($person_obj['outbox']) + if ($person_obj['outbox']) $collections['outbox'] = $person_obj['outbox']; - if($person_obj['followers']) + if ($person_obj['followers']) $collections['followers'] = $person_obj['followers']; - if($person_obj['following']) + if ($person_obj['following']) $collections['following'] = $person_obj['following']; - if($person_obj['endpoints'] && $person_obj['endpoints']['sharedInbox']) + if ($person_obj['endpoints'] && $person_obj['endpoints']['sharedInbox']) $collections['sharedInbox'] = $person_obj['endpoints']['sharedInbox']; } - if(array_key_exists('publicKey',$person_obj) && array_key_exists('publicKeyPem',$person_obj['publicKey'])) { - if($person_obj['id'] === $person_obj['publicKey']['owner']) { + if (array_key_exists('publicKey', $person_obj) && array_key_exists('publicKeyPem', $person_obj['publicKey'])) { + if ($person_obj['id'] === $person_obj['publicKey']['owner']) { $pubkey = $person_obj['publicKey']['publicKeyPem']; - if(strstr($pubkey,'RSA ')) { + if (strstr($pubkey, 'RSA ')) { $pubkey = rsatopem($pubkey); } } @@ -1574,19 +1579,19 @@ class Activity { $r = q("select * from xchan where xchan_hash = '%s' limit 1", dbesc($url) ); - if(! $r) { + if (!$r) { // create a new record - $r = xchan_store_lowlevel( + xchan_store_lowlevel( [ - 'xchan_hash' => $url, - 'xchan_guid' => $url, - 'xchan_pubkey' => $pubkey, - 'xchan_addr' => '', - 'xchan_url' => $profile, - 'xchan_name' => $name, - 'xchan_name_date' => datetime_convert(), - 'xchan_network' => 'activitypub' + 'xchan_hash' => $url, + 'xchan_guid' => $url, + 'xchan_pubkey' => $pubkey, + 'xchan_addr' => '', + 'xchan_url' => $profile, + 'xchan_name' => $name, + 'xchan_name_date' => datetime_convert(), + 'xchan_network' => 'activitypub' ] ); } @@ -1595,12 +1600,12 @@ class Activity { // Record exists. Cache existing records for one week at most // then refetch to catch updated profile photos, names, etc. - $d = datetime_convert('UTC','UTC','now - 1 week'); - if($r[0]['xchan_name_date'] > $d) + $d = datetime_convert('UTC', 'UTC', 'now - 1 week'); + if ($r[0]['xchan_name_date'] > $d) return; // update existing record - $r = q("update xchan set xchan_name = '%s', xchan_pubkey = '%s', xchan_network = '%s', xchan_name_date = '%s' where xchan_hash = '%s'", + q("update xchan set xchan_name = '%s', xchan_pubkey = '%s', xchan_network = '%s', xchan_name_date = '%s' where xchan_hash = '%s'", dbesc($name), dbesc($pubkey), dbesc('activitypub'), @@ -1609,23 +1614,22 @@ class Activity { ); } - if($collections) { - set_xconfig($url,'activitypub','collections',$collections); + if ($collections) { + set_xconfig($url, 'activitypub', 'collections', $collections); } $r = q("select * from hubloc where hubloc_hash = '%s' limit 1", dbesc($url) ); - $m = parse_url($url); - if($m) { + if ($m) { $hostname = $m['host']; - $baseurl = $m['scheme'] . '://' . $m['host'] . (($m['port']) ? ':' . $m['port'] : ''); + $baseurl = $m['scheme'] . '://' . $m['host'] . (($m['port']) ? ':' . $m['port'] : ''); } - if(! $r) { - $r = hubloc_store_lowlevel( + if (!$r) { + hubloc_store_lowlevel( [ 'hubloc_guid' => $url, 'hubloc_hash' => $url, @@ -1641,12 +1645,12 @@ class Activity { ); } - if(! $icon) + if (!$icon) $icon = z_root() . '/' . get_default_profile_photo(300); - $photos = import_xchan_photo($icon,$url); - $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'", - dbescdate(datetime_convert('UTC','UTC',$photos[5])), + $photos = import_xchan_photo($icon, $url); + 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'", + dbescdate(datetime_convert('UTC', 'UTC', $photos[5])), dbesc($photos[0]), dbesc($photos[1]), dbesc($photos[2]), @@ -1657,28 +1661,28 @@ class Activity { } - static function create_action($channel,$observer_hash,$act) { + static function create_action($channel, $observer_hash, $act) { - if(in_array($act->obj['type'], [ 'Note', 'Article', 'Video' ])) { - self::create_note($channel,$observer_hash,$act); + if (in_array($act->obj['type'], ['Note', 'Article', 'Video'])) { + self::create_note($channel, $observer_hash, $act); } } - static function announce_action($channel,$observer_hash,$act) { + static function announce_action($channel, $observer_hash, $act) { - if(in_array($act->type, [ 'Announce' ])) { - self::announce_note($channel,$observer_hash,$act); + if (in_array($act->type, ['Announce'])) { + self::announce_note($channel, $observer_hash, $act); } } - static function like_action($channel,$observer_hash,$act) { + static function like_action($channel, $observer_hash, $act) { - if(in_array($act->obj['type'], [ 'Note', 'Article', 'Video' ])) { - self::like_note($channel,$observer_hash,$act); + if (in_array($act->obj['type'], ['Note', 'Article', 'Video'])) { + self::like_note($channel, $observer_hash, $act); } @@ -1686,24 +1690,24 @@ class Activity { // sort function width decreasing - static function vid_sort($a,$b) { - if($a['width'] === $b['width']) + static function vid_sort($a, $b) { + if ($a['width'] === $b['width']) return 0; return (($a['width'] > $b['width']) ? -1 : 1); } - static function create_note($channel,$observer_hash,$act) { + static function create_note($channel, $observer_hash, $act) { $s = []; // Mastodon only allows visibility in public timelines if the public inbox is listed in the 'to' field. // They are hidden in the public timeline if the public inbox is listed in the 'cc' field. // This is not part of the activitypub protocol - we might change this to show all public posts in pubstream at some point. - $pubstream = ((is_array($act->obj) && array_key_exists('to', $act->obj) && in_array(ACTIVITY_PUBLIC_INBOX, $act->obj['to'])) ? true : false); + $pubstream = ((is_array($act->obj) && array_key_exists('to', $act->obj) && in_array(ACTIVITY_PUBLIC_INBOX, $act->obj['to'])) ? true : false); $is_sys_channel = is_sys_channel($channel['channel_id']); - $parent = ((array_key_exists('inReplyTo',$act->obj)) ? urldecode($act->obj['inReplyTo']) : ''); - if($parent) { + $parent = ((array_key_exists('inReplyTo', $act->obj)) ? urldecode($act->obj['inReplyTo']) : ''); + if ($parent) { $r = q("select * from item where uid = %d and ( mid = '%s' or mid = '%s' ) limit 1", intval($channel['channel_id']), @@ -1711,39 +1715,39 @@ class Activity { dbesc(basename($parent)) ); - if(! $r) { + if (!$r) { logger('parent not found.'); return; } - if($r[0]['owner_xchan'] === $channel['channel_hash']) { - if(! perm_is_allowed($channel['channel_id'],$observer_hash,'send_stream') && ! ($is_sys_channel && $pubstream)) { + if ($r[0]['owner_xchan'] === $channel['channel_hash']) { + if (!perm_is_allowed($channel['channel_id'], $observer_hash, 'send_stream') && !($is_sys_channel && $pubstream)) { logger('no comment permission.'); return; } } - $s['parent_mid'] = $r[0]['mid']; - $s['owner_xchan'] = $r[0]['owner_xchan']; + $s['parent_mid'] = $r[0]['mid']; + $s['owner_xchan'] = $r[0]['owner_xchan']; $s['author_xchan'] = $observer_hash; } else { - if(! perm_is_allowed($channel['channel_id'],$observer_hash,'send_stream') && ! ($is_sys_channel && $pubstream)) { + if (!perm_is_allowed($channel['channel_id'], $observer_hash, 'send_stream') && !($is_sys_channel && $pubstream)) { logger('no permission'); return; } $s['owner_xchan'] = $s['author_xchan'] = $observer_hash; } - + $abook = q("select * from abook where abook_xchan = '%s' and abook_channel = %d limit 1", dbesc($observer_hash), intval($channel['channel_id']) ); - + $content = self::get_content($act->obj); - if(! $content) { + if (!$content) { logger('no content'); return; } @@ -1756,105 +1760,105 @@ class Activity { $s['author_xchan'] = self::find_best_identity($s['author_xchan']); $s['owner_xchan'] = self::find_best_identity($s['owner_xchan']); - if(!$s['author_xchan']) { + if (!$s['author_xchan']) { logger('No author: ' . print_r($act, true)); } - if(!$s['owner_xchan']) { + if (!$s['owner_xchan']) { logger('No owner: ' . print_r($act, true)); } - if(!$s['author_xchan'] || !$s['owner_xchan']) + if (!$s['author_xchan'] || !$s['owner_xchan']) return; - $s['mid'] = urldecode($act->obj['id']); - $s['uuid'] = $act->obj['diaspora:guid']; + $s['mid'] = urldecode($act->obj['id']); + $s['uuid'] = $act->obj['diaspora:guid']; $s['plink'] = urldecode($act->obj['id']); - if($act->data['published']) { - $s['created'] = datetime_convert('UTC','UTC',$act->data['published']); + if ($act->data['published']) { + $s['created'] = datetime_convert('UTC', 'UTC', $act->data['published']); } - elseif($act->obj['published']) { - $s['created'] = datetime_convert('UTC','UTC',$act->obj['published']); + elseif ($act->obj['published']) { + $s['created'] = datetime_convert('UTC', 'UTC', $act->obj['published']); } - if($act->data['updated']) { - $s['edited'] = datetime_convert('UTC','UTC',$act->data['updated']); + if ($act->data['updated']) { + $s['edited'] = datetime_convert('UTC', 'UTC', $act->data['updated']); } - elseif($act->obj['updated']) { - $s['edited'] = datetime_convert('UTC','UTC',$act->obj['updated']); + elseif ($act->obj['updated']) { + $s['edited'] = datetime_convert('UTC', 'UTC', $act->obj['updated']); } if ($act->data['expires']) { - $s['expires'] = datetime_convert('UTC','UTC',$act->data['expires']); + $s['expires'] = datetime_convert('UTC', 'UTC', $act->data['expires']); } elseif ($act->obj['expires']) { - $s['expires'] = datetime_convert('UTC','UTC',$act->obj['expires']); + $s['expires'] = datetime_convert('UTC', 'UTC', $act->obj['expires']); } - if(! $s['created']) + if (!$s['created']) $s['created'] = datetime_convert(); - if(! $s['edited']) + if (!$s['edited']) $s['edited'] = $s['created']; - if(! $s['parent_mid']) + if (!$s['parent_mid']) $s['parent_mid'] = $s['mid']; - - $s['title'] = self::bb_content($content,'name'); - $s['summary'] = self::bb_content($content,'summary'); - $s['body'] = self::bb_content($content,'content'); + + $s['title'] = self::bb_content($content, 'name'); + $s['summary'] = self::bb_content($content, 'summary'); + $s['body'] = self::bb_content($content, 'content'); $s['verb'] = ACTIVITY_POST; $s['obj_type'] = ACTIVITY_OBJ_NOTE; $generator = $act->get_property_obj('generator'); - if(! $generator) - $generator = $act->get_property_obj('generator',$act->obj); + if (!$generator) + $generator = $act->get_property_obj('generator', $act->obj); - if($generator && array_key_exists('type',$generator) - && in_array($generator['type'], [ 'Application','Service' ] ) && array_key_exists('name',$generator)) { + if ($generator && array_key_exists('type', $generator) + && in_array($generator['type'], ['Application', 'Service']) && array_key_exists('name', $generator)) { $s['app'] = escape_tags($generator['name']); } - if($channel['channel_system']) { - if(! \Zotlabs\Lib\MessageFilter::evaluate($s,get_config('system','pubstream_incl'),get_config('system','pubstream_excl'))) { + if ($channel['channel_system']) { + if (!MessageFilter::evaluate($s, get_config('system', 'pubstream_incl'), get_config('system', 'pubstream_excl'))) { logger('post is filtered'); return; } } - if($abook) { - if(! post_is_importable($s,$abook[0])) { + if ($abook) { + if (!post_is_importable($s, $abook[0])) { logger('post is filtered'); return; } } - if($act->obj['conversation']) { - set_iconfig($s,'ostatus','conversation',$act->obj['conversation'],1); + if ($act->obj['conversation']) { + set_iconfig($s, 'ostatus', 'conversation', $act->obj['conversation'], 1); } $a = self::decode_taxonomy($act->obj); - if($a) { + if ($a) { $s['term'] = $a; } $a = self::decode_attachment($act->obj); - if($a) { + if ($a) { $s['attach'] = $a; } - if($act->obj['type'] === 'Note' && $s['attach']) { - $s['body'] .= self::bb_attach($s['attach'],$s['body']); + if ($act->obj['type'] === 'Note' && $s['attach']) { + $s['body'] .= self::bb_attach($s['attach'], $s['body']); } // we will need a hook here to extract magnet links e.g. peertube // right now just link to the largest mp4 we find that will fit in our // standard content region - if($act->obj['type'] === 'Video') { + if ($act->obj['type'] === 'Video') { $vtypes = [ 'video/mp4', @@ -1863,20 +1867,20 @@ class Activity { ]; $mps = []; - if(array_key_exists('url',$act->obj) && is_array($act->obj['url'])) { - foreach($act->obj['url'] as $vurl) { - if(in_array($vurl['mimeType'], $vtypes)) { - if(! array_key_exists('width',$vurl)) { + if (array_key_exists('url', $act->obj) && is_array($act->obj['url'])) { + foreach ($act->obj['url'] as $vurl) { + if (in_array($vurl['mimeType'], $vtypes)) { + if (!array_key_exists('width', $vurl)) { $vurl['width'] = 0; } $mps[] = $vurl; } } } - if($mps) { - usort($mps,[ __CLASS__, 'vid_sort' ]); - foreach($mps as $m) { - if(intval($m['width']) < 500) { + if ($mps) { + usort($mps, [__CLASS__, 'vid_sort']); + foreach ($mps as $m) { + if (intval($m['width']) < 500) { $s['body'] .= "\n\n" . '[video]' . $m['href'] . '[/video]'; break; } @@ -1884,17 +1888,17 @@ class Activity { } } - if($act->recips && (! in_array(ACTIVITY_PUBLIC_INBOX,$act->recips))) + if ($act->recips && (!in_array(ACTIVITY_PUBLIC_INBOX, $act->recips))) $s['item_private'] = 1; - if (array_key_exists('directMessage',$act->obj) && intval($act->obj['directMessage'])) { + if (array_key_exists('directMessage', $act->obj) && intval($act->obj['directMessage'])) { $s['item_private'] = 2; } - set_iconfig($s,'activitypub','recips',$act->raw_recips); - if($parent) { - set_iconfig($s,'activitypub','rawmsg',$act->raw,1); + set_iconfig($s, 'activitypub', 'recips', $act->raw_recips); + if ($parent) { + set_iconfig($s, 'activitypub', 'rawmsg', $act->raw, 1); } $x = null; @@ -1903,8 +1907,8 @@ class Activity { dbesc($s['mid']), intval($s['uid']) ); - if($r) { - if($s['edited'] > $r[0]['edited']) { + if ($r) { + if ($s['edited'] > $r[0]['edited']) { $x = item_store_update($s); } else { @@ -1915,20 +1919,20 @@ class Activity { $x = item_store($s); } - if(is_array($x) && $x['item_id']) { - if($parent) { - if($s['owner_xchan'] === $channel['channel_hash']) { + if (is_array($x) && $x['item_id']) { + if ($parent) { + if ($s['owner_xchan'] === $channel['channel_hash']) { // We are the owner of this conversation, so send all received comments back downstream - Master::Summon(array('Notifier','comment-import',$x['item_id'])); + Master::Summon(['Notifier', 'comment-import', $x['item_id']]); } $r = q("select * from item where id = %d limit 1", intval($x['item_id']) ); - if($r) { - send_status_notifications($x['item_id'],$r[0]); + if ($r) { + send_status_notifications($x['item_id'], $r[0]); } } - sync_an_item($channel['channel_id'],$x['item_id']); + sync_an_item($channel['channel_id'], $x['item_id']); } } @@ -1940,26 +1944,25 @@ class Activity { dbesc($id) ); - if($x) { - return sprintf('@[zrl=%s]%s[/zrl]',$x[0]['xchan_url'],$x[0]['xchan_name']); + if ($x) { + return sprintf('@[zrl=%s]%s[/zrl]', $x[0]['xchan_url'], $x[0]['xchan_name']); } return '@{' . $id . '}'; } - - static function update_poll($item,$post) { - $multi = false; - $mid = $post['mid']; + static function update_poll($item, $post) { + $multi = false; + $mid = $post['mid']; $content = $post['title']; - - if (! $item) { + + if (!$item) { return false; } - $o = json_decode($item['obj'],true); - if ($o && array_key_exists('anyOf',$o)) { + $o = json_decode($item['obj'], true); + if ($o && array_key_exists('anyOf', $o)) { $multi = true; } @@ -1969,7 +1972,7 @@ class Activity { ); // prevent any duplicate votes by same author for oneOf and duplicate votes with same author and same answer for anyOf - + if ($r) { if ($multi) { foreach ($r as $rv) { @@ -1986,55 +1989,55 @@ class Activity { } } } - + $answer_found = false; - $found = false; + $found = false; if ($multi) { - for ($c = 0; $c < count($o['anyOf']); $c ++) { + for ($c = 0; $c < count($o['anyOf']); $c++) { if ($o['anyOf'][$c]['name'] === $content) { $answer_found = true; if (is_array($o['anyOf'][$c]['replies'])) { - foreach($o['anyOf'][$c]['replies'] as $reply) { - if(is_array($reply) && array_key_exists('id',$reply) && $reply['id'] === $mid) { + foreach ($o['anyOf'][$c]['replies'] as $reply) { + if (is_array($reply) && array_key_exists('id', $reply) && $reply['id'] === $mid) { $found = true; } } } - if (! $found) { - $o['anyOf'][$c]['replies']['totalItems'] ++; - $o['anyOf'][$c]['replies']['items'][] = [ 'id' => $mid, 'type' => 'Note' ]; + if (!$found) { + $o['anyOf'][$c]['replies']['totalItems']++; + $o['anyOf'][$c]['replies']['items'][] = ['id' => $mid, 'type' => 'Note']; } } } } else { - for ($c = 0; $c < count($o['oneOf']); $c ++) { + for ($c = 0; $c < count($o['oneOf']); $c++) { if ($o['oneOf'][$c]['name'] === $content) { $answer_found = true; if (is_array($o['oneOf'][$c]['replies'])) { - foreach($o['oneOf'][$c]['replies'] as $reply) { - if(is_array($reply) && array_key_exists('id',$reply) && $reply['id'] === $mid) { + foreach ($o['oneOf'][$c]['replies'] as $reply) { + if (is_array($reply) && array_key_exists('id', $reply) && $reply['id'] === $mid) { $found = true; } } } - if (! $found) { - $o['oneOf'][$c]['replies']['totalItems'] ++; - $o['oneOf'][$c]['replies']['items'][] = [ 'id' => $mid, 'type' => 'Note' ]; + if (!$found) { + $o['oneOf'][$c]['replies']['totalItems']++; + $o['oneOf'][$c]['replies']['items'][] = ['id' => $mid, 'type' => 'Note']; } } } } - logger('updated_poll: ' . print_r($o,true),LOGGER_DATA); - if ($answer_found && ! $found) { - $x = q("update item set obj = '%s', edited = '%s' where id = %d", + logger('updated_poll: ' . print_r($o, true), LOGGER_DATA); + if ($answer_found && !$found) { + q("update item set obj = '%s', edited = '%s' where id = %d", dbesc(json_encode($o)), dbesc(datetime_convert()), intval($item['id']) ); - Master::Summon( [ 'Notifier', 'wall-new', $item['id'] ] ); + Master::Summon(['Notifier', 'wall-new', $item['id']]); return true; } @@ -2042,47 +2045,46 @@ class Activity { } - static function decode_note($act) { $response_activity = false; $s = []; - if(is_array($act->obj)) { + if (is_array($act->obj)) { $content = self::get_content($act->obj); } - + $s['owner_xchan'] = $act->actor['id']; $s['author_xchan'] = $act->actor['id']; // ensure we store the original actor - self::actor_store($act->actor['id'],$act->actor); + self::actor_store($act->actor['id'], $act->actor); $s['mid'] = $act->obj['id']; - $s['uuid'] = $act->obj['diaspora:guid']; + $s['uuid'] = $act->obj['diaspora:guid']; $s['parent_mid'] = $act->parent_id; - if($act->data['published']) { - $s['created'] = datetime_convert('UTC','UTC',$act->data['published']); + if ($act->data['published']) { + $s['created'] = datetime_convert('UTC', 'UTC', $act->data['published']); } - elseif($act->obj['published']) { - $s['created'] = datetime_convert('UTC','UTC',$act->obj['published']); + elseif ($act->obj['published']) { + $s['created'] = datetime_convert('UTC', 'UTC', $act->obj['published']); } - if($act->data['updated']) { - $s['edited'] = datetime_convert('UTC','UTC',$act->data['updated']); + if ($act->data['updated']) { + $s['edited'] = datetime_convert('UTC', 'UTC', $act->data['updated']); } - elseif($act->obj['updated']) { - $s['edited'] = datetime_convert('UTC','UTC',$act->obj['updated']); + elseif ($act->obj['updated']) { + $s['edited'] = datetime_convert('UTC', 'UTC', $act->obj['updated']); } if ($act->data['expires']) { - $s['expires'] = datetime_convert('UTC','UTC',$act->data['expires']); + $s['expires'] = datetime_convert('UTC', 'UTC', $act->data['expires']); } elseif ($act->obj['expires']) { - $s['expires'] = datetime_convert('UTC','UTC',$act->obj['expires']); + $s['expires'] = datetime_convert('UTC', 'UTC', $act->obj['expires']); } - if(ActivityStreams::is_response_activity($act->type)) { + if (ActivityStreams::is_response_activity($act->type)) { $response_activity = true; @@ -2092,85 +2094,85 @@ class Activity { // over-ride the object timestamp with the activity - if($act->data['published']) { - $s['created'] = datetime_convert('UTC','UTC',$act->data['published']); + if ($act->data['published']) { + $s['created'] = datetime_convert('UTC', 'UTC', $act->data['published']); } - if($act->data['updated']) { - $s['edited'] = datetime_convert('UTC','UTC',$act->data['updated']); + if ($act->data['updated']) { + $s['edited'] = datetime_convert('UTC', 'UTC', $act->data['updated']); } $obj_actor = ((isset($act->obj['actor'])) ? $act->obj['actor'] : $act->get_actor('attributedTo', $act->obj)); // ensure we store the original actor - self::actor_store($obj_actor['id'],$obj_actor); + self::actor_store($obj_actor['id'], $obj_actor); $mention = self::get_actor_bbmention($obj_actor['id']); - if($act->type === 'Like') { - $content['content'] = sprintf( t('Likes %1$s\'s %2$s'),$mention,$act->obj['type']) . "\n\n" . $content['content']; + if ($act->type === 'Like') { + $content['content'] = sprintf(t('Likes %1$s\'s %2$s'), $mention, $act->obj['type']) . "\n\n" . $content['content']; } - if($act->type === 'Dislike') { - $content['content'] = sprintf( t('Doesn\'t like %1$s\'s %2$s'),$mention,$act->obj['type']) . "\n\n" . $content['content']; + if ($act->type === 'Dislike') { + $content['content'] = sprintf(t('Doesn\'t like %1$s\'s %2$s'), $mention, $act->obj['type']) . "\n\n" . $content['content']; } // handle event RSVPs - if (($act->obj['type'] === 'Event') || ($act->obj['type'] === 'Invite' && array_path_exists('object/type',$act->obj) && $act->obj['object']['type'] === 'Event')) { + if (($act->obj['type'] === 'Event') || ($act->obj['type'] === 'Invite' && array_path_exists('object/type', $act->obj) && $act->obj['object']['type'] === 'Event')) { if ($act->type === 'Accept') { - $content['content'] = sprintf( t('Will attend %s\'s event'),$mention) . EOL . EOL . $content['content']; + $content['content'] = sprintf(t('Will attend %s\'s event'), $mention) . EOL . EOL . $content['content']; } if ($act->type === 'Reject') { - $content['content'] = sprintf( t('Will not attend %s\'s event'),$mention) . EOL . EOL . $content['content']; + $content['content'] = sprintf(t('Will not attend %s\'s event'), $mention) . EOL . EOL . $content['content']; } if ($act->type === 'TentativeAccept') { - $content['content'] = sprintf( t('May attend %s\'s event'),$mention) . EOL . EOL . $content['content']; + $content['content'] = sprintf(t('May attend %s\'s event'), $mention) . EOL . EOL . $content['content']; } if ($act->type === 'TentativeReject') { - $content['content'] = sprintf( t('May not attend %s\'s event'),$mention) . EOL . EOL . $content['content']; + $content['content'] = sprintf(t('May not attend %s\'s event'), $mention) . EOL . EOL . $content['content']; } } - if($act->type === 'Announce') { - $content['content'] = sprintf( t('🔁 Repeated %1$s\'s %2$s'), $mention, $act->obj['type']); + if ($act->type === 'Announce') { + $content['content'] = sprintf(t('🔁 Repeated %1$s\'s %2$s'), $mention, $act->obj['type']); } if ($act->type === 'emojiReaction') { $content['content'] = (($act->tgt && $act->tgt['type'] === 'Image') ? '[img=32x32]' . $act->tgt['url'] . '[/img]' : '&#x' . $act->tgt['name'] . ';'); - } + } } - if(! $s['created']) + if (!$s['created']) $s['created'] = datetime_convert(); - if(! $s['edited']) + if (!$s['edited']) $s['edited'] = $s['created']; - $s['title'] = (($response_activity) ? EMPTY_STR : self::bb_content($content,'name')); - $s['summary'] = self::bb_content($content,'summary'); - $s['body'] = ((self::bb_content($content,'bbcode') && (! $response_activity)) ? self::bb_content($content,'bbcode') : self::bb_content($content,'content')); + $s['title'] = (($response_activity) ? EMPTY_STR : self::bb_content($content, 'name')); + $s['summary'] = self::bb_content($content, 'summary'); + $s['body'] = ((self::bb_content($content, 'bbcode') && (!$response_activity)) ? self::bb_content($content, 'bbcode') : self::bb_content($content, 'content')); - $s['verb'] = self::activity_decode_mapper($act->type); + $s['verb'] = self::activity_decode_mapper($act->type); // Mastodon does not provide update timestamps when updating poll tallies which means race conditions may occur here. if ($act->type === 'Update' && $act->obj['type'] === 'Question' && $s['edited'] === $s['created']) { $s['edited'] = datetime_convert(); } - if(in_array($act->type, [ 'Delete', 'Undo', 'Tombstone' ]) || ($act->type === 'Create' && $act->obj['type'] === 'Tombstone')) { + if (in_array($act->type, ['Delete', 'Undo', 'Tombstone']) || ($act->type === 'Create' && $act->obj['type'] === 'Tombstone')) { $s['item_deleted'] = 1; } $s['obj_type'] = self::activity_obj_decode_mapper($act->obj['type']); - if($s['obj_type'] === ACTIVITY_OBJ_NOTE && $s['mid'] !== $s['parent_mid']) { + if ($s['obj_type'] === ACTIVITY_OBJ_NOTE && $s['mid'] !== $s['parent_mid']) { $s['obj_type'] = ACTIVITY_OBJ_COMMENT; } $eventptr = null; - if ($act->obj['type'] === 'Invite' && array_path_exists('object/type',$act->obj) && $act->obj['object']['type'] === 'Event') { + if ($act->obj['type'] === 'Invite' && array_path_exists('object/type', $act->obj) && $act->obj['object']['type'] === 'Event') { $eventptr = $act->obj['object']; $s['mid'] = $s['parent_mid'] = $act->obj['id']; } - - if($act->obj['type'] === 'Event') { + + if ($act->obj['type'] === 'Event') { if ($act->type === 'Invite') { $s['mid'] = $s['parent_mid'] = $act->id; } @@ -2179,52 +2181,52 @@ class Activity { if ($eventptr) { - $s['obj'] = []; - $s['obj']['asld'] = $eventptr; - $s['obj']['type'] = ACTIVITY_OBJ_EVENT; - $s['obj']['id'] = $eventptr['id']; + $s['obj'] = []; + $s['obj']['asld'] = $eventptr; + $s['obj']['type'] = ACTIVITY_OBJ_EVENT; + $s['obj']['id'] = $eventptr['id']; $s['obj']['title'] = $eventptr['name']; - if(strpos($act->obj['startTime'],'Z')) + if (strpos($act->obj['startTime'], 'Z')) $s['obj']['adjust'] = true; else $s['obj']['adjust'] = false; - $s['obj']['dtstart'] = datetime_convert('UTC','UTC',$eventptr['startTime']); - if($act->obj['endTime']) - $s['obj']['dtend'] = datetime_convert('UTC','UTC',$eventptr['endTime']); + $s['obj']['dtstart'] = datetime_convert('UTC', 'UTC', $eventptr['startTime']); + if ($act->obj['endTime']) + $s['obj']['dtend'] = datetime_convert('UTC', 'UTC', $eventptr['endTime']); else $s['obj']['nofinish'] = true; $s['obj']['description'] = $eventptr['content']; - if(array_path_exists('location/content',$eventptr)) + if (array_path_exists('location/content', $eventptr)) $s['obj']['location'] = $eventptr['location']['content']; } else { - $s['obj'] = $act->obj; + $s['obj'] = $act->obj; } $generator = $act->get_property_obj('generator'); - if((! $generator) && (! $response_activity)) { - $generator = $act->get_property_obj('generator',$act->obj); + if ((!$generator) && (!$response_activity)) { + $generator = $act->get_property_obj('generator', $act->obj); } - if($generator && array_key_exists('type',$generator) - && in_array($generator['type'], [ 'Application', 'Service' ] ) && array_key_exists('name',$generator)) { + if ($generator && array_key_exists('type', $generator) + && in_array($generator['type'], ['Application', 'Service']) && array_key_exists('name', $generator)) { $s['app'] = escape_tags($generator['name']); } - if(! $response_activity) { + if (!$response_activity) { $a = self::decode_taxonomy($act->obj); - if($a) { + if ($a) { $s['term'] = $a; - foreach($a as $b) { - if($b['ttype'] === TERM_EMOJI) { - $s['title'] = str_replace($b['term'],'[img=16x16]' . $b['url'] . '[/img]',$s['title']); - $s['summary'] = str_replace($b['term'],'[img=16x16]' . $b['url'] . '[/img]',$s['summary']); - $s['body'] = str_replace($b['term'],'[img=16x16]' . $b['url'] . '[/img]',$s['body']); + foreach ($a as $b) { + if ($b['ttype'] === TERM_EMOJI) { + $s['title'] = str_replace($b['term'], '[img=16x16]' . $b['url'] . '[/img]', $s['title']); + $s['summary'] = str_replace($b['term'], '[img=16x16]' . $b['url'] . '[/img]', $s['summary']); + $s['body'] = str_replace($b['term'], '[img=16x16]' . $b['url'] . '[/img]', $s['body']); } } } @@ -2241,28 +2243,27 @@ class Activity { $s['iconfig'] = $a; } - if($act->obj['type'] === 'Note' && $s['attach']) { - $s['body'] .= self::bb_attach($s['attach'],$s['body']); + if ($act->obj['type'] === 'Note' && $s['attach']) { + $s['body'] .= self::bb_attach($s['attach'], $s['body']); } - if ($act->obj['type'] === 'Question' && in_array($act->type,['Create','Update'])) { + if ($act->obj['type'] === 'Question' && in_array($act->type, ['Create', 'Update'])) { if ($act->obj['endTime']) { - $s['comments_closed'] = datetime_convert('UTC','UTC', $act->obj['endTime']); + $s['comments_closed'] = datetime_convert('UTC', 'UTC', $act->obj['endTime']); } } if ($act->obj['closed']) { - $s['comments_closed'] = datetime_convert('UTC','UTC', $act->obj['closed']); - } - + $s['comments_closed'] = datetime_convert('UTC', 'UTC', $act->obj['closed']); + } // we will need a hook here to extract magnet links e.g. peertube // right now just link to the largest mp4 we find that will fit in our // standard content region - if(! $response_activity) { - if($act->obj['type'] === 'Video') { + if (!$response_activity) { + if ($act->obj['type'] === 'Video') { $vtypes = [ 'video/mp4', @@ -2273,27 +2274,27 @@ class Activity { $mps = []; $ptr = null; - if(array_key_exists('url',$act->obj)) { - if(is_array($act->obj['url'])) { - if(array_key_exists(0,$act->obj['url'])) { + if (array_key_exists('url', $act->obj)) { + if (is_array($act->obj['url'])) { + if (array_key_exists(0, $act->obj['url'])) { $ptr = $act->obj['url']; } else { - $ptr = [ $act->obj['url'] ]; + $ptr = [$act->obj['url']]; } - foreach($ptr as $vurl) { + foreach ($ptr as $vurl) { // peertube uses the non-standard element name 'mimeType' here - if(array_key_exists('mimeType',$vurl)) { - if(in_array($vurl['mimeType'], $vtypes)) { - if(! array_key_exists('width',$vurl)) { + if (array_key_exists('mimeType', $vurl)) { + if (in_array($vurl['mimeType'], $vtypes)) { + if (!array_key_exists('width', $vurl)) { $vurl['width'] = 0; } $mps[] = $vurl; } } - elseif(array_key_exists('mediaType',$vurl)) { - if(in_array($vurl['mediaType'], $vtypes)) { - if(! array_key_exists('width',$vurl)) { + elseif (array_key_exists('mediaType', $vurl)) { + if (in_array($vurl['mediaType'], $vtypes)) { + if (!array_key_exists('width', $vurl)) { $vurl['width'] = 0; } $mps[] = $vurl; @@ -2301,22 +2302,22 @@ class Activity { } } } - if($mps) { - usort($mps,[ __CLASS__, 'vid_sort' ]); - foreach($mps as $m) { - if(intval($m['width']) < 500 && self::media_not_in_body($m['href'],$s['body'])) { + if ($mps) { + usort($mps, [__CLASS__, 'vid_sort']); + foreach ($mps as $m) { + if (intval($m['width']) < 500 && self::media_not_in_body($m['href'], $s['body'])) { $s['body'] .= "\n\n" . '[video]' . $m['href'] . '[/video]'; break; } } } - elseif(is_string($act->obj['url']) && self::media_not_in_body($act->obj['url'],$s['body'])) { + elseif (is_string($act->obj['url']) && self::media_not_in_body($act->obj['url'], $s['body'])) { $s['body'] .= "\n\n" . '[video]' . $act->obj['url'] . '[/video]'; } } } - if($act->obj['type'] === 'Audio') { + if ($act->obj['type'] === 'Audio') { $atypes = [ 'audio/mpeg', @@ -2326,50 +2327,50 @@ class Activity { $ptr = null; - if(array_key_exists('url',$act->obj)) { - if(is_array($act->obj['url'])) { - if(array_key_exists(0,$act->obj['url'])) { + if (array_key_exists('url', $act->obj)) { + if (is_array($act->obj['url'])) { + if (array_key_exists(0, $act->obj['url'])) { $ptr = $act->obj['url']; } else { - $ptr = [ $act->obj['url'] ]; + $ptr = [$act->obj['url']]; } - foreach($ptr as $vurl) { - if(in_array($vurl['mediaType'], $atypes) && self::media_not_in_body($vurl['href'],$s['body'])) { + foreach ($ptr as $vurl) { + if (in_array($vurl['mediaType'], $atypes) && self::media_not_in_body($vurl['href'], $s['body'])) { $s['body'] .= "\n\n" . '[audio]' . $vurl['href'] . '[/audio]'; break; } } } - elseif(is_string($act->obj['url']) && self::media_not_in_body($act->obj['url'],$s['body'])) { + elseif (is_string($act->obj['url']) && self::media_not_in_body($act->obj['url'], $s['body'])) { $s['body'] .= "\n\n" . '[audio]' . $act->obj['url'] . '[/audio]'; } } } - if($act->obj['type'] === 'Image') { + if ($act->obj['type'] === 'Image') { $ptr = null; - if(array_key_exists('url',$act->obj)) { - if(is_array($act->obj['url'])) { - if(array_key_exists(0,$act->obj['url'])) { + if (array_key_exists('url', $act->obj)) { + if (is_array($act->obj['url'])) { + if (array_key_exists(0, $act->obj['url'])) { $ptr = $act->obj['url']; } else { - $ptr = [ $act->obj['url'] ]; + $ptr = [$act->obj['url']]; } - foreach($ptr as $vurl) { - if(strpos($s['body'],$vurl['href']) === false) { - $bb_imgs .= '[zmg]' . $vurl['href'] . '[/zmg]' . "\n\n"; + foreach ($ptr as $vurl) { + if (strpos($s['body'], $vurl['href']) === false) { + $bb_imgs = '[zmg]' . $vurl['href'] . '[/zmg]' . "\n\n"; break; } } $s['body'] = $bb_imgs . $s['body']; } - elseif(is_string($act->obj['url'])) { - if(strpos($s['body'],$act->obj['url']) === false) { + elseif (is_string($act->obj['url'])) { + if (strpos($s['body'], $act->obj['url']) === false) { $s['body'] .= '[zmg]' . $act->obj['url'] . '[/zmg]' . "\n\n" . $s['body']; } } @@ -2377,36 +2378,36 @@ class Activity { } - if($act->obj['type'] === 'Page' && ! $s['body']) { + if ($act->obj['type'] === 'Page' && !$s['body']) { $ptr = null; $purl = EMPTY_STR; - if(array_key_exists('url',$act->obj)) { - if(is_array($act->obj['url'])) { - if(array_key_exists(0,$act->obj['url'])) { + if (array_key_exists('url', $act->obj)) { + if (is_array($act->obj['url'])) { + if (array_key_exists(0, $act->obj['url'])) { $ptr = $act->obj['url']; } else { - $ptr = [ $act->obj['url'] ]; + $ptr = [$act->obj['url']]; } - foreach($ptr as $vurl) { - if(array_key_exists('mediaType',$vurl) && $vurl['mediaType'] === 'text/html') { + foreach ($ptr as $vurl) { + if (array_key_exists('mediaType', $vurl) && $vurl['mediaType'] === 'text/html') { $purl = $vurl['href']; break; } - elseif(array_key_exists('mimeType',$vurl) && $vurl['mimeType'] === 'text/html') { + elseif (array_key_exists('mimeType', $vurl) && $vurl['mimeType'] === 'text/html') { $purl = $vurl['href']; break; } } } - elseif(is_string($act->obj['url'])) { + elseif (is_string($act->obj['url'])) { $purl = $act->obj['url']; } - if($purl) { + if ($purl) { $li = z_fetch_url(z_root() . '/linkinfo?binurl=' . bin2hex($purl)); - if($li['success'] && $li['body']) { + if ($li['success'] && $li['body']) { $s['body'] .= "\n" . $li['body']; } else { @@ -2418,32 +2419,31 @@ class Activity { } - - if(in_array($act->obj['type'],[ 'Note','Article','Page' ])) { + if (in_array($act->obj['type'], ['Note', 'Article', 'Page'])) { $ptr = null; - if(array_key_exists('url',$act->obj)) { - if(is_array($act->obj['url'])) { - if(array_key_exists(0,$act->obj['url'])) { + if (array_key_exists('url', $act->obj)) { + if (is_array($act->obj['url'])) { + if (array_key_exists(0, $act->obj['url'])) { $ptr = $act->obj['url']; } else { - $ptr = [ $act->obj['url'] ]; + $ptr = [$act->obj['url']]; } - foreach($ptr as $vurl) { - if(array_key_exists('mediaType',$vurl) && $vurl['mediaType'] === 'text/html') { + foreach ($ptr as $vurl) { + if (array_key_exists('mediaType', $vurl) && $vurl['mediaType'] === 'text/html') { $s['plink'] = $vurl['href']; break; } } } - elseif(is_string($act->obj['url'])) { + elseif (is_string($act->obj['url'])) { $s['plink'] = $act->obj['url']; } } } - if(! $s['plink']) { + if (!$s['plink']) { $s['plink'] = $s['mid']; } @@ -2456,24 +2456,24 @@ class Activity { } if (is_array($act->obj)) { - if (array_key_exists('directMessage',$act->obj) && intval($act->obj['directMessage'])) { + if (array_key_exists('directMessage', $act->obj) && intval($act->obj['directMessage'])) { $s['item_private'] = 2; } } - set_iconfig($s,'activitypub','recips',$act->raw_recips); + set_iconfig($s, 'activitypub', 'recips', $act->raw_recips); $parent = (($s['parent_mid'] && $s['parent_mid'] === $s['mid']) ? true : false); - if($parent) { - set_iconfig($s,'activitypub','rawmsg',$act->raw,1); + if ($parent) { + set_iconfig($s, 'activitypub', 'rawmsg', $act->raw, 1); } $hookinfo = [ 'act' => $act, - 's' => $s + 's' => $s ]; - call_hooks('decode_note',$hookinfo); + call_hooks('decode_note', $hookinfo); $s = $hookinfo['s']; @@ -2481,7 +2481,7 @@ class Activity { } - static function store($channel,$observer_hash,$act,$item,$fetch_parents = true) { + static function store($channel, $observer_hash, $act, $item, $fetch_parents = true) { $is_sys_channel = is_sys_channel($channel['channel_id']); @@ -2492,15 +2492,15 @@ class Activity { $pubstream = ((is_array($act->obj) && array_key_exists('to', $act->obj) && in_array(ACTIVITY_PUBLIC_INBOX, $act->obj['to'])) ? true : false); $is_parent = (($item['parent_mid'] && $item['parent_mid'] === $item['mid']) ? true : false); - if($is_parent && (! perm_is_allowed($channel['channel_id'],$observer_hash,'send_stream') && ! ($is_sys_channel && $pubstream))) { + if ($is_parent && (!perm_is_allowed($channel['channel_id'], $observer_hash, 'send_stream') && !($is_sys_channel && $pubstream))) { logger('no permission'); return; } - if(is_array($act->obj)) { + if (is_array($act->obj)) { $content = self::get_content($act->obj); } - if(! $content) { + if (!$content) { logger('no content'); return; } @@ -2513,19 +2513,19 @@ class Activity { $item['author_xchan'] = self::find_best_identity($item['author_xchan']); $item['owner_xchan'] = self::find_best_identity($item['owner_xchan']); - if(!$item['author_xchan']) { + if (!$item['author_xchan']) { logger('No author: ' . print_r($act, true)); } - if(!$item['owner_xchan']) { + if (!$item['owner_xchan']) { logger('No owner: ' . print_r($act, true)); } - if(!$item['author_xchan'] || !$item['owner_xchan']) + if (!$item['author_xchan'] || !$item['owner_xchan']) return; - if($channel['channel_system']) { - if(! MessageFilter::evaluate($item,get_config('system','pubstream_incl'),get_config('system','pubstream_excl'))) { + if ($channel['channel_system']) { + if (!MessageFilter::evaluate($item, get_config('system', 'pubstream_incl'), get_config('system', 'pubstream_excl'))) { logger('post is filtered'); return; } @@ -2536,32 +2536,32 @@ class Activity { intval($channel['channel_id']) ); - if($abook) { - if(! post_is_importable($item,$abook[0])) { + if ($abook) { + if (!post_is_importable($item, $abook[0])) { logger('post is filtered'); return; } } - if($act->obj['conversation']) { - set_iconfig($item,'ostatus','conversation',$act->obj['conversation'],1); + if ($act->obj['conversation']) { + set_iconfig($item, 'ostatus', 'conversation', $act->obj['conversation'], 1); } // This isn't perfect but the best we can do for now. $item['comment_policy'] = 'authenticated'; - set_iconfig($item,'activitypub','recips',$act->raw_recips); + set_iconfig($item, 'activitypub', 'recips', $act->raw_recips); - if(! $is_parent) { + if (!$is_parent) { $p = q("select parent_mid, id, obj_type from item where mid = '%s' and uid = %d limit 1", dbesc($item['parent_mid']), intval($item['uid']) ); - if(! $p) { - $a = (($fetch_parents) ? self::fetch_and_store_parents($channel,$act,$item) : false); - if($a) { + if (!$p) { + $a = (($fetch_parents) ? self::fetch_and_store_parents($channel, $item) : false); + if ($a) { $p = q("select parent_mid from item where mid = '%s' and uid = %d limit 1", dbesc($item['parent_mid']), intval($item['uid']) @@ -2588,13 +2588,13 @@ class Activity { if ($p[0]['obj_type'] === 'Question') { - if ($item['obj_type'] === ACTIVITY_OBJ_NOTE && $item['title'] && (! $item['content'])) { + if ($item['obj_type'] === ACTIVITY_OBJ_NOTE && $item['title'] && (!$item['content'])) { $item['obj_type'] = 'Answer'; } } - if($p[0]['parent_mid'] !== $item['parent_mid']) { + if ($p[0]['parent_mid'] !== $item['parent_mid']) { $item['thr_parent'] = $item['parent_mid']; } else { @@ -2607,10 +2607,10 @@ class Activity { dbesc($item['mid']), intval($item['uid']) ); - if($r) { - if($item['edited'] > $r[0]['edited']) { + if ($r) { + if ($item['edited'] > $r[0]['edited']) { $item['id'] = $r[0]['id']; - $x = item_store_update($item); + $x = item_store_update($item); } else { return; @@ -2620,52 +2620,51 @@ class Activity { $x = item_store($item); } - if(is_array($x) && $x['item_id']) { - if($is_parent) { - if($item['owner_xchan'] === $channel['channel_hash']) { + if (is_array($x) && $x['item_id']) { + if ($is_parent) { + if ($item['owner_xchan'] === $channel['channel_hash']) { // We are the owner of this conversation, so send all received comments back downstream - Master::Summon(array('Notifier','comment-import',$x['item_id'])); + Master::Summon(['Notifier', 'comment-import', $x['item_id']]); } $r = q("select * from item where id = %d limit 1", intval($x['item_id']) ); - if($r) { - send_status_notifications($x['item_id'],$r[0]); + if ($r) { + send_status_notifications($x['item_id'], $r[0]); } } - sync_an_item($channel['channel_id'],$x['item_id']); + sync_an_item($channel['channel_id'], $x['item_id']); } } - static public function fetch_and_store_parents($channel,$act,$item) { + static public function fetch_and_store_parents($channel, $item) { logger('fetching parents'); $p = []; - $current_act = $act; $current_item = $item; - while($current_item['parent_mid'] !== $current_item['mid']) { + while ($current_item['parent_mid'] !== $current_item['mid']) { $n = self::fetch($current_item['parent_mid'], $channel); - if(! $n) { + if (!$n) { break; } $a = new ActivityStreams($n); //logger($a->debug()); - if(! $a->is_valid()) { + if (!$a->is_valid()) { break; } - if (is_array($a->actor) && array_key_exists('id',$a->actor)) { - self::actor_store($a->actor['id'],$a->actor); + if (is_array($a->actor) && array_key_exists('id', $a->actor)) { + self::actor_store($a->actor['id'], $a->actor); } $replies = null; - if(isset($a->obj['replies']['first']['items'])) { + if (isset($a->obj['replies']['first']['items'])) { $replies = $a->obj['replies']['first']['items']; // we already have this one array_diff($replies, [$current_item['mid']]); @@ -2673,11 +2672,11 @@ class Activity { $item = null; - switch($a->type) { + switch ($a->type) { case 'Create': case 'Update': - //case 'Like': - //case 'Dislike': + //case 'Like': + //case 'Dislike': case 'Announce': $item = self::decode_note($a); break; @@ -2687,31 +2686,30 @@ class Activity { } $hookinfo = [ - 'a' => $a, + 'a' => $a, 'item' => $item ]; - call_hooks('fetch_and_store',$hookinfo); + call_hooks('fetch_and_store', $hookinfo); $item = $hookinfo['item']; - if($item) { + if ($item) { - array_unshift($p,[ $a, $item, $replies]); - - if($item['parent_mid'] === $item['mid'] || count($p) > 20) { + array_unshift($p, [$a, $item, $replies]); + + if ($item['parent_mid'] === $item['mid'] || count($p) > 20) { break; } } - $current_act = $a; $current_item = $item; } - if($p) { - foreach($p as $pv) { - self::store($channel,$pv[0]->actor['id'],$pv[0],$pv[1],false); - if($pv[2]) + if ($p) { + foreach ($p as $pv) { + self::store($channel, $pv[0]->actor['id'], $pv[0], $pv[1], false); + if ($pv[2]) self::fetch_and_store_replies($channel, $pv[2]); } return true; @@ -2723,26 +2721,26 @@ class Activity { static public function fetch_and_store_replies($channel, $arr) { logger('fetching replies'); - logger(print_r($arr,true)); + logger(print_r($arr, true)); $p = []; - foreach($arr as $url) { + foreach ($arr as $url) { $n = self::fetch($url, $channel); - if(! $n) { + if (!$n) { break; } $a = new ActivityStreams($n); - if(! $a->is_valid()) { + if (!$a->is_valid()) { break; } $item = null; - switch($a->type) { + switch ($a->type) { case 'Create': case 'Update': case 'Like': @@ -2755,29 +2753,29 @@ class Activity { } $hookinfo = [ - 'a' => $a, + 'a' => $a, 'item' => $item ]; - call_hooks('fetch_and_store',$hookinfo); + call_hooks('fetch_and_store', $hookinfo); $item = $hookinfo['item']; - if($item) { - array_unshift($p,[ $a, $item ]); + if ($item) { + array_unshift($p, [$a, $item]); } } - if($p) { - foreach($p as $pv) { - self::store($channel,$pv[0]->actor['id'],$pv[0],$pv[1],false); + if ($p) { + foreach ($p as $pv) { + self::store($channel, $pv[0]->actor['id'], $pv[0], $pv[1], false); } } } - static function announce_note($channel,$observer_hash,$act) { + static function announce_note($channel, $observer_hash, $act) { $s = []; @@ -2788,29 +2786,29 @@ class Activity { // This is not part of the activitypub protocol - we might change this to show all public posts in pubstream at some point. $pubstream = ((is_array($act->obj) && array_key_exists('to', $act->obj) && in_array(ACTIVITY_PUBLIC_INBOX, $act->obj['to'])) ? true : false); - if(! perm_is_allowed($channel['channel_id'],$observer_hash,'send_stream') && ! ($is_sys_channel && $pubstream)) { + if (!perm_is_allowed($channel['channel_id'], $observer_hash, 'send_stream') && !($is_sys_channel && $pubstream)) { logger('no permission'); return; } $content = self::get_content($act->obj); - if(! $content) { + if (!$content) { logger('no content'); return; } $s['owner_xchan'] = $s['author_xchan'] = $observer_hash; - $s['aid'] = $channel['channel_account_id']; - $s['uid'] = $channel['channel_id']; - $s['mid'] = urldecode($act->obj['id']); + $s['aid'] = $channel['channel_account_id']; + $s['uid'] = $channel['channel_id']; + $s['mid'] = urldecode($act->obj['id']); $s['plink'] = urldecode($act->obj['id']); - if(! $s['created']) + if (!$s['created']) $s['created'] = datetime_convert(); - if(! $s['edited']) + if (!$s['edited']) $s['edited'] = $s['created']; @@ -2820,8 +2818,8 @@ class Activity { $s['obj_type'] = ACTIVITY_OBJ_NOTE; $s['app'] = t('ActivityPub'); - if($channel['channel_system']) { - if(! \Zotlabs\Lib\MessageFilter::evaluate($s,get_config('system','pubstream_incl'),get_config('system','pubstream_excl'))) { + if ($channel['channel_system']) { + if (!MessageFilter::evaluate($s, get_config('system', 'pubstream_incl'), get_config('system', 'pubstream_excl'))) { logger('post is filtered'); return; } @@ -2832,61 +2830,61 @@ class Activity { intval($channel['channel_id']) ); - if($abook) { - if(! post_is_importable($s,$abook[0])) { + if ($abook) { + if (!post_is_importable($s, $abook[0])) { logger('post is filtered'); return; } } - if($act->obj['conversation']) { - set_iconfig($s,'ostatus','conversation',$act->obj['conversation'],1); + if ($act->obj['conversation']) { + set_iconfig($s, 'ostatus', 'conversation', $act->obj['conversation'], 1); } $a = self::decode_taxonomy($act->obj); - if($a) { + if ($a) { $s['term'] = $a; } $a = self::decode_attachment($act->obj); - if($a) { + if ($a) { $s['attach'] = $a; } - $body = "[share author='" . urlencode($act->sharee['name']) . - "' profile='" . $act->sharee['url'] . - "' avatar='" . $act->sharee['photo_s'] . - "' link='" . ((is_array($act->obj['url'])) ? $act->obj['url']['href'] : $act->obj['url']) . - "' auth='" . ((is_matrix_url($act->obj['url'])) ? 'true' : 'false' ) . - "' posted='" . $act->obj['published'] . - "' message_id='" . $act->obj['id'] . - "']"; + $body = "[share author='" . urlencode($act->sharee['name']) . + "' profile='" . $act->sharee['url'] . + "' avatar='" . $act->sharee['photo_s'] . + "' link='" . ((is_array($act->obj['url'])) ? $act->obj['url']['href'] : $act->obj['url']) . + "' auth='" . ((is_matrix_url($act->obj['url'])) ? 'true' : 'false') . + "' posted='" . $act->obj['published'] . + "' message_id='" . $act->obj['id'] . + "']"; - if($content['name']) - $body .= self::bb_content($content,'name') . "\r\n"; + if ($content['name']) + $body .= self::bb_content($content, 'name') . "\r\n"; - $body .= self::bb_content($content,'content'); + $body .= self::bb_content($content, 'content'); - if($act->obj['type'] === 'Note' && $s['attach']) { - $body .= self::bb_attach($s['attach'],$body); + if ($act->obj['type'] === 'Note' && $s['attach']) { + $body .= self::bb_attach($s['attach'], $body); } $body .= "[/share]"; - $s['title'] = self::bb_content($content,'name'); - $s['body'] = $body; + $s['title'] = self::bb_content($content, 'name'); + $s['body'] = $body; - if($act->recips && (! in_array(ACTIVITY_PUBLIC_INBOX,$act->recips))) + if ($act->recips && (!in_array(ACTIVITY_PUBLIC_INBOX, $act->recips))) $s['item_private'] = 1; - set_iconfig($s,'activitypub','recips',$act->raw_recips); + set_iconfig($s, 'activitypub', 'recips', $act->raw_recips); $r = q("select created, edited from item where mid = '%s' and uid = %d limit 1", dbesc($s['mid']), intval($s['uid']) ); - if($r) { - if($s['edited'] > $r[0]['edited']) { + if ($r) { + if ($s['edited'] > $r[0]['edited']) { $x = item_store_update($s); } else { @@ -2897,35 +2895,35 @@ class Activity { $x = item_store($s); } - if(is_array($x) && $x['item_id']) { - if($s['owner_xchan'] === $channel['channel_hash']) { + if (is_array($x) && $x['item_id']) { + if ($s['owner_xchan'] === $channel['channel_hash']) { // We are the owner of this conversation, so send all received comments back downstream - Master::Summon(array('Notifier','comment-import',$x['item_id'])); + Master::Summon(['Notifier', 'comment-import', $x['item_id']]); } $r = q("select * from item where id = %d limit 1", intval($x['item_id']) ); - if($r) { - send_status_notifications($x['item_id'],$r[0]); + if ($r) { + send_status_notifications($x['item_id'], $r[0]); } - sync_an_item($channel['channel_id'],$x['item_id']); + sync_an_item($channel['channel_id'], $x['item_id']); } } - static function like_note($channel,$observer_hash,$act) { + static function like_note($channel, $observer_hash, $act) { $s = []; $parent = $act->obj['id']; - - if($act->type === 'Like') + + if ($act->type === 'Like') $s['verb'] = ACTIVITY_LIKE; - if($act->type === 'Dislike') + if ($act->type === 'Dislike') $s['verb'] = ACTIVITY_DISLIKE; - if(! $parent) + if (!$parent) return; $r = q("select * from item where uid = %d and ( mid = '%s' or mid = '%s' ) limit 1", @@ -2934,7 +2932,7 @@ class Activity { dbesc(urldecode(basename($parent))) ); - if(! $r) { + if (!$r) { logger('parent not found.'); return; } @@ -2942,14 +2940,14 @@ class Activity { xchan_query($r); $parent_item = $r[0]; - if($parent_item['owner_xchan'] === $channel['channel_hash']) { - if(! perm_is_allowed($channel['channel_id'],$observer_hash,'post_comments')) { + if ($parent_item['owner_xchan'] === $channel['channel_hash']) { + if (!perm_is_allowed($channel['channel_id'], $observer_hash, 'post_comments')) { logger('no comment permission.'); return; } } - if($parent_item['mid'] === $parent_item['parent_mid']) { + if ($parent_item['mid'] === $parent_item['parent_mid']) { $s['parent_mid'] = $parent_item['mid']; } else { @@ -2957,31 +2955,29 @@ class Activity { $s['parent_mid'] = $parent_item['parent_mid']; } - $s['owner_xchan'] = $parent_item['owner_xchan']; + $s['owner_xchan'] = $parent_item['owner_xchan']; $s['author_xchan'] = $observer_hash; - + $s['aid'] = $channel['channel_account_id']; $s['uid'] = $channel['channel_id']; $s['mid'] = $act->id; - if(! $s['parent_mid']) + if (!$s['parent_mid']) $s['parent_mid'] = $s['mid']; - - $post_type = (($parent_item['resource_type'] === 'photo') ? t('photo') : t('post')); - $links = array(array('rel' => 'alternate','type' => 'text/html', 'href' => $parent_item['plink'])); - $objtype = (($parent_item['resource_type'] === 'photo') ? ACTIVITY_OBJ_PHOTO : ACTIVITY_OBJ_NOTE ); + $post_type = (($parent_item['resource_type'] === 'photo') ? t('photo') : t('post')); - $body = $parent_item['body']; + $links = [['rel' => 'alternate', 'type' => 'text/html', 'href' => $parent_item['plink']]]; + $objtype = (($parent_item['resource_type'] === 'photo') ? ACTIVITY_OBJ_PHOTO : ACTIVITY_OBJ_NOTE); $z = q("select * from xchan where xchan_hash = '%s' limit 1", dbesc($parent_item['author_xchan']) ); - if($z) - $item_author = $z[0]; + if ($z) + $item_author = $z[0]; - $object = json_encode(array( + $object = json_encode([ 'type' => $post_type, 'id' => $parent_item['mid'], 'parent' => (($parent_item['thr_parent']) ? $parent_item['thr_parent'] : $parent_item['parent_mid']), @@ -2990,77 +2986,76 @@ class Activity { 'content' => $parent_item['body'], 'created' => $parent_item['created'], 'edited' => $parent_item['edited'], - 'author' => array( + 'author' => [ 'name' => $item_author['xchan_name'], 'address' => $item_author['xchan_addr'], 'guid' => $item_author['xchan_guid'], 'guid_sig' => $item_author['xchan_guid_sig'], - 'link' => array( - array('rel' => 'alternate', 'type' => 'text/html', 'href' => $item_author['xchan_url']), - array('rel' => 'photo', 'type' => $item_author['xchan_photo_mimetype'], 'href' => $item_author['xchan_photo_m'])), - ), - ), JSON_UNESCAPED_SLASHES + 'link' => [ + ['rel' => 'alternate', 'type' => 'text/html', 'href' => $item_author['xchan_url']], + ['rel' => 'photo', 'type' => $item_author['xchan_photo_mimetype'], 'href' => $item_author['xchan_photo_m']]], + ], + ], JSON_UNESCAPED_SLASHES ); - if($act->type === 'Like') + if ($act->type === 'Like') $bodyverb = t('%1$s likes %2$s\'s %3$s'); - if($act->type === 'Dislike') + if ($act->type === 'Dislike') $bodyverb = t('%1$s doesn\'t like %2$s\'s %3$s'); - $ulink = '[url=' . $item_author['xchan_url'] . ']' . $item_author['xchan_name'] . '[/url]'; - $alink = '[url=' . $parent_item['author']['xchan_url'] . ']' . $parent_item['author']['xchan_name'] . '[/url]'; - $plink = '[url='. z_root() . '/display/' . urlencode($act->id) . ']' . $post_type . '[/url]'; - $s['body'] = sprintf( $bodyverb, $ulink, $alink, $plink ); + $ulink = '[url=' . $item_author['xchan_url'] . ']' . $item_author['xchan_name'] . '[/url]'; + $alink = '[url=' . $parent_item['author']['xchan_url'] . ']' . $parent_item['author']['xchan_name'] . '[/url]'; + $plink = '[url=' . z_root() . '/display/' . urlencode($act->id) . ']' . $post_type . '[/url]'; + $s['body'] = sprintf($bodyverb, $ulink, $alink, $plink); - $s['app'] = t('ActivityPub'); + $s['app'] = t('ActivityPub'); // set the route to that of the parent so downstream hubs won't reject it. - $s['route'] = $parent_item['route']; + $s['route'] = $parent_item['route']; $s['item_private'] = $parent_item['item_private']; - $s['obj_type'] = $objtype; - $s['obj'] = $object; + $s['obj_type'] = $objtype; + $s['obj'] = $object; - if($act->obj['conversation']) { - set_iconfig($s,'ostatus','conversation',$act->obj['conversation'],1); + if ($act->obj['conversation']) { + set_iconfig($s, 'ostatus', 'conversation', $act->obj['conversation'], 1); } - if($act->recips && (! in_array(ACTIVITY_PUBLIC_INBOX,$act->recips))) + if ($act->recips && (!in_array(ACTIVITY_PUBLIC_INBOX, $act->recips))) $s['item_private'] = 1; - set_iconfig($s,'activitypub','recips',$act->raw_recips); + set_iconfig($s, 'activitypub', 'recips', $act->raw_recips); $result = item_store($s); - if($result['success']) { + if ($result['success']) { // if the message isn't already being relayed, notify others - if(intval($parent_item['item_origin'])) - Master::Summon(array('Notifier','comment-import',$result['item_id'])); - sync_an_item($channel['channel_id'],$result['item_id']); + if (intval($parent_item['item_origin'])) + Master::Summon(['Notifier', 'comment-import', $result['item_id']]); + sync_an_item($channel['channel_id'], $result['item_id']); } return; } - - static function bb_attach($attach,$body) { + static function bb_attach($attach, $body) { $ret = false; - foreach($attach as $a) { - if(strpos($a['type'],'image') !== false) { - if(self::media_not_in_body($a['href'],$body)) { + foreach ($attach as $a) { + if (strpos($a['type'], 'image') !== false) { + if (self::media_not_in_body($a['href'], $body)) { $ret .= "\n\n" . '[img]' . $a['href'] . '[/img]'; } } - if(array_key_exists('type',$a) && strpos($a['type'], 'video') === 0) { - if(self::media_not_in_body($a['href'],$body)) { + if (array_key_exists('type', $a) && strpos($a['type'], 'video') === 0) { + if (self::media_not_in_body($a['href'], $body)) { $ret .= "\n\n" . '[video]' . $a['href'] . '[/video]'; } } - if(array_key_exists('type',$a) && strpos($a['type'], 'audio') === 0) { - if(self::media_not_in_body($a['href'],$body)) { + if (array_key_exists('type', $a) && strpos($a['type'], 'audio') === 0) { + if (self::media_not_in_body($a['href'], $body)) { $ret .= "\n\n" . '[audio]' . $a['href'] . '[/audio]'; } } @@ -3072,40 +3067,40 @@ class Activity { // check for the existence of existing media link in body - static function media_not_in_body($s,$body) { - - if((strpos($body,']' . $s . '[/img]') === false) && - (strpos($body,']' . $s . '[/zmg]') === false) && - (strpos($body,']' . $s . '[/video]') === false) && - (strpos($body,']' . $s . '[/audio]') === false)) { + static function media_not_in_body($s, $body) { + + if ((strpos($body, ']' . $s . '[/img]') === false) && + (strpos($body, ']' . $s . '[/zmg]') === false) && + (strpos($body, ']' . $s . '[/video]') === false) && + (strpos($body, ']' . $s . '[/audio]') === false)) { return true; } return false; } - static function bb_content($content,$field) { + static function bb_content($content, $field) { require_once('include/html2bbcode.php'); require_once('include/event.php'); $ret = false; - if(is_array($content[$field])) { - foreach($content[$field] as $k => $v) { + if (is_array($content[$field])) { + foreach ($content[$field] as $k => $v) { $ret .= html2bbcode($v); // save this for auto-translate or dynamic filtering // $ret .= '[language=' . $k . ']' . html2bbcode($v) . '[/language]'; } } else { - if($field === 'bbcode' && array_key_exists('bbcode',$content)) { + if ($field === 'bbcode' && array_key_exists('bbcode', $content)) { $ret = $content[$field]; } else { $ret = html2bbcode($content[$field]); } } - if($field === 'content' && $content['event'] && (! strpos($ret,'[event'))) { + if ($field === 'content' && $content['event'] && (!strpos($ret, '[event'))) { $ret .= format_event_bbcode($content['event']); } @@ -3116,69 +3111,67 @@ class Activity { static function get_content($act) { $content = []; - $event = null; + $event = null; - if ((! $act) || (! is_array($act))) { + if ((!$act) || (!is_array($act))) { return $content; } - if($act['type'] === 'Event') { - $adjust = false; - $event = []; - $event['event_hash'] = $act['id']; - if(array_key_exists('startTime',$act) && strpos($act['startTime'],-1,1) === 'Z') { - $adjust = true; - $event['adjust'] = 1; - $event['dtstart'] = datetime_convert('UTC','UTC',$event['startTime'] . (($adjust) ? '' : 'Z')); - } - if(array_key_exists('endTime',$act)) { - $event['dtend'] = datetime_convert('UTC','UTC',$event['endTime'] . (($adjust) ? '' : 'Z')); - } - else { - $event['nofinish'] = true; - } - } - - foreach ([ 'name', 'summary', 'content' ] as $a) { - if (($x = self::get_textfield($act,$a)) !== false) { + if ($act['type'] === 'Event') { + $adjust = false; + $event = []; + $event['event_hash'] = $act['id']; + if (array_key_exists('startTime', $act) && strpos($act['startTime'], -1, 1) === 'Z') { + $adjust = true; + $event['adjust'] = 1; + $event['dtstart'] = datetime_convert('UTC', 'UTC', $event['startTime'] . (($adjust) ? '' : 'Z')); + } + if (array_key_exists('endTime', $act)) { + $event['dtend'] = datetime_convert('UTC', 'UTC', $event['endTime'] . (($adjust) ? '' : 'Z')); + } + else { + $event['nofinish'] = true; + } + } + + foreach (['name', 'summary', 'content'] as $a) { + if (($x = self::get_textfield($act, $a)) !== false) { $content[$a] = $x; } } - if($event) { + if ($event) { $event['summary'] = $content['name']; - if(! $event['summary']) { - if($content['summary']) { + if (!$event['summary']) { + if ($content['summary']) { $event['summary'] = html2plain($content['summary']); } } $event['description'] = html2bbcode($content['content']); - if($event['summary'] && $event['dtstart']) { + if ($event['summary'] && $event['dtstart']) { $content['event'] = $event; } } - if (array_path_exists('source/mediaType',$act) && array_path_exists('source/content',$act)) { + if (array_path_exists('source/mediaType', $act) && array_path_exists('source/content', $act)) { if ($act['source']['mediaType'] === 'text/bbcode') { $content['bbcode'] = purify_html($act['source']['content']); } } - - return $content; } - static function get_textfield($act,$field) { - + static function get_textfield($act, $field) { + $content = false; - if(array_key_exists($field,$act) && $act[$field]) + if (array_key_exists($field, $act) && $act[$field]) $content = purify_html($act[$field]); - elseif(array_key_exists($field . 'Map',$act) && $act[$field . 'Map']) { - foreach($act[$field . 'Map'] as $k => $v) { + elseif (array_key_exists($field . 'Map', $act) && $act[$field . 'Map']) { + foreach ($act[$field . 'Map'] as $k => $v) { $content[escape_tags($k)] = purify_html($v); } } @@ -3190,8 +3183,8 @@ class Activity { static function token_from_request() { - foreach ( [ 'REDIRECT_REMOTE_USER', 'HTTP_AUTHORIZATION' ] as $s ) { - $auth = ((array_key_exists($s,$_SERVER) && strpos($_SERVER[$s],'Bearer ') === 0) + foreach (['REDIRECT_REMOTE_USER', 'HTTP_AUTHORIZATION'] as $s) { + $auth = ((array_key_exists($s, $_SERVER) && strpos($_SERVER[$s], 'Bearer ') === 0) ? str_replace('Bearer ', EMPTY_STR, $_SERVER[$s]) : EMPTY_STR ); @@ -3200,8 +3193,8 @@ class Activity { } } - if (! $auth) { - if (array_key_exists('token',$_REQUEST) && $_REQUEST['token']) { + if (!$auth) { + if (array_key_exists('token', $_REQUEST) && $_REQUEST['token']) { $auth = $_REQUEST['token']; } } @@ -3211,7 +3204,7 @@ class Activity { static function find_best_identity($xchan) { - if(filter_var($xchan, FILTER_VALIDATE_URL)) { + if (filter_var($xchan, FILTER_VALIDATE_URL)) { $r = q("select hubloc_hash, hubloc_network from hubloc where hubloc_id_url = '%s' and hubloc_network in ('zot6', 'zot') and hubloc_deleted = 0", dbesc($xchan) ); diff --git a/Zotlabs/Lib/Libzot.php b/Zotlabs/Lib/Libzot.php index cde4c0145..8847f0975 100644 --- a/Zotlabs/Lib/Libzot.php +++ b/Zotlabs/Lib/Libzot.php @@ -34,7 +34,7 @@ class Libzot { */ static function new_uid($channel_nick) { $rawstr = z_root() . '/' . $channel_nick . '.' . mt_rand(); - return(base64url_encode(hash('whirlpool', $rawstr, true), true)); + return (base64url_encode(hash('whirlpool', $rawstr, true), true)); } @@ -100,13 +100,13 @@ class Libzot { */ static function build_packet($channel, $type = 'activity', $recipients = null, $msg = [], $encoding = 'activitystreams', $remote_key = null, $methods = '') { - $sig_method = get_config('system','signature_algorithm','sha256'); + $sig_method = get_config('system', 'signature_algorithm', 'sha256'); $data = [ 'type' => $type, 'encoding' => $encoding, 'sender' => $channel['channel_hash'], - 'site_id' => self::make_xchan_hash(z_root(), get_config('system','pubkey')), + 'site_id' => self::make_xchan_hash(z_root(), get_config('system', 'pubkey')), 'version' => System::get_zot_revision(), ]; @@ -116,8 +116,8 @@ class Libzot { if ($msg) { $actor = channel_url($channel); - if ($encoding === 'activitystreams' && array_key_exists('actor',$msg) && is_string($msg['actor']) && $actor === $msg['actor']) { - $msg = JSalmon::sign($msg,$actor,$channel['channel_prvkey']); + if ($encoding === 'activitystreams' && array_key_exists('actor', $msg) && is_string($msg['actor']) && $actor === $msg['actor']) { + $msg = JSalmon::sign($msg, $actor, $channel['channel_prvkey']); } $data['data'] = $msg; } @@ -125,12 +125,12 @@ class Libzot { unset($data['encoding']); } - logger('packet: ' . print_r($data,true), LOGGER_DATA, LOG_DEBUG); + logger('packet: ' . print_r($data, true), LOGGER_DATA, LOG_DEBUG); if ($remote_key) { $algorithm = self::best_algorithm($methods); if ($algorithm) { - $data = crypto_encapsulate(json_encode($data),$remote_key, $algorithm); + $data = crypto_encapsulate(json_encode($data), $remote_key, $algorithm); } } @@ -150,7 +150,7 @@ class Libzot { $x = [ 'methods' => $methods, - 'result' => '' + 'result' => '' ]; /** @@ -161,18 +161,18 @@ class Libzot { */ call_hooks('zot_best_algorithm', $x); - if($x['result']) + if ($x['result']) return $x['result']; - if($methods) { + if ($methods) { $x = explode(',', $methods); - if($x) { + if ($x) { $y = crypto_methods(); - if($y) { - foreach($y as $yv) { + if ($y) { + foreach ($y as $yv) { $yv = trim($yv); - if(in_array($yv, $x)) { - return($yv); + if (in_array($yv, $x)) { + return ($yv); } } } @@ -186,17 +186,17 @@ class Libzot { /** * @brief Send a zot message. * - * @see z_post_url() - * * @param string $url * @param string $data * @param array $channel (required if using zot6 delivery) * @param array $crypto (required if encrypted httpsig, requires hubloc_sitekey and site_crypto elements) * @return array see z_post_url() for returned data format + * @see z_post_url() + * */ - static function zot($url, $data, $channel = null,$crypto = null) { + static function zot($url, $data, $channel = null, $crypto = null) { - if($channel) { + if ($channel) { $headers = [ 'X-Zot-Token' => random_string(), 'Digest' => HTTPSig::generate_digest_header($data), @@ -204,8 +204,8 @@ class Libzot { '(request-target)' => 'post ' . get_request_string($url) ]; - $h = HTTPSig::create_sig($headers,$channel['channel_prvkey'],channel_url($channel),false,'sha512', - (($crypto) ? [ 'key' => $crypto['hubloc_sitekey'], 'algorithm' => self::best_algorithm($crypto['site_crypto']) ] : false)); + $h = HTTPSig::create_sig($headers, $channel['channel_prvkey'], channel_url($channel), false, 'sha512', + (($crypto) ? ['key' => $crypto['hubloc_sitekey'], 'algorithm' => self::best_algorithm($crypto['site_crypto'])] : false)); } else { $h = []; @@ -213,7 +213,7 @@ class Libzot { $redirects = 0; - return z_post_url($url,$data,$redirects,((empty($h)) ? [] : [ 'headers' => $h ])); + return z_post_url($url, $data, $redirects, ((empty($h)) ? [] : ['headers' => $h])); } @@ -245,9 +245,9 @@ class Libzot { */ static function refresh($them, $channel = null, $force = false) { - logger('them: ' . print_r($them,true), LOGGER_DATA, LOG_DEBUG); + logger('them: ' . print_r($them, true), LOGGER_DATA, LOG_DEBUG); if ($channel) - logger('channel: ' . print_r($channel,true), LOGGER_DATA, LOG_DEBUG); + logger('channel: ' . print_r($channel, true), LOGGER_DATA, LOG_DEBUG); $url = null; @@ -261,12 +261,12 @@ class Libzot { // We'll order by reverse id to try and pick off the newest one first and hopefully end up with the // correct hubloc. If this doesn't work we may have to re-write this section to try them all. - if(array_key_exists('xchan_addr',$them) && $them['xchan_addr']) { + if (array_key_exists('xchan_addr', $them) && $them['xchan_addr']) { $r = q("select hubloc_id_url, hubloc_primary from hubloc where hubloc_addr = '%s' and hubloc_network = 'zot6' order by hubloc_id desc", dbesc($them['xchan_addr']) ); } - if(! $r) { + if (!$r) { $r = q("select hubloc_id_url, hubloc_primary from hubloc where hubloc_hash = '%s' order by hubloc_id desc", dbesc($them['xchan_hash']) ); @@ -275,16 +275,16 @@ class Libzot { if ($r) { foreach ($r as $rr) { if (intval($rr['hubloc_primary'])) { - $url = $rr['hubloc_id_url']; + $url = $rr['hubloc_id_url']; $record = $rr; } } - if (! $url) { + if (!$url) { $url = $r[0]['hubloc_id_url']; } } } - if (! $url) { + if (!$url) { logger('zot_refresh: no url'); return false; } @@ -293,64 +293,64 @@ class Libzot { dbesc($url) ); - if($s && intval($s[0]['site_dead']) && (! $force)) { + if ($s && intval($s[0]['site_dead']) && (!$force)) { logger('zot_refresh: site ' . $url . ' is marked dead and force flag is not set. Cancelling operation.'); return false; } - $record = Zotfinger::exec($url,$channel); + $record = Zotfinger::exec($url, $channel); // Check the HTTP signature $hsig = $record['signature']; - if($hsig && $hsig['signer'] === $url && $hsig['header_valid'] === true && $hsig['content_valid'] === true) + if ($hsig && $hsig['signer'] === $url && $hsig['header_valid'] === true && $hsig['content_valid'] === true) $hsig_valid = true; - if(! $hsig_valid) { - logger('http signature not valid: ' . print_r($hsig,true)); + if (!$hsig_valid) { + logger('http signature not valid: ' . print_r($hsig, true)); return false; } - logger('zot-info: ' . print_r($record,true), LOGGER_DATA, LOG_DEBUG); + logger('zot-info: ' . print_r($record, true), LOGGER_DATA, LOG_DEBUG); $x = self::import_xchan($record['data'], (($force) ? UPDATE_FLAGS_FORCED : UPDATE_FLAGS_UPDATED)); - if(! $x['success']) + if (!$x['success']) return false; - if($channel && $record['data']['permissions']) { - $permissions = explode(',',$record['data']['permissions']); + if ($channel && $record['data']['permissions']) { + $permissions = explode(',', $record['data']['permissions']); - if($permissions && is_array($permissions)) { - $old_read_stream_perm = get_abconfig($channel['channel_id'],$x['hash'],'their_perms','view_stream'); + if ($permissions && is_array($permissions)) { + $old_read_stream_perm = get_abconfig($channel['channel_id'], $x['hash'], 'their_perms', 'view_stream'); $permissions = Permissions::FilledPerms($permissions); - foreach($permissions as $k => $v) { - set_abconfig($channel['channel_id'],$x['hash'],'their_perms',$k,$v); + foreach ($permissions as $k => $v) { + set_abconfig($channel['channel_id'], $x['hash'], 'their_perms', $k, $v); } } - if(array_key_exists('profile',$record['data']) && array_key_exists('next_birthday',$record['data']['profile'])) { - $next_birthday = datetime_convert('UTC','UTC',$record['data']['profile']['next_birthday']); + if (array_key_exists('profile', $record['data']) && array_key_exists('next_birthday', $record['data']['profile'])) { + $next_birthday = datetime_convert('UTC', 'UTC', $record['data']['profile']['next_birthday']); } else { $next_birthday = NULL_DATE; } - $profile_assign = get_pconfig($channel['channel_id'],'system','profile_assign',''); + $profile_assign = get_pconfig($channel['channel_id'], 'system', 'profile_assign', ''); // Keep original perms to check if we need to notify them - $previous_perms = get_all_perms($channel['channel_id'],$x['hash']); + $previous_perms = get_all_perms($channel['channel_id'], $x['hash']); $r = q("select * from abook where abook_xchan = '%s' and abook_channel = %d and abook_self = 0 limit 1", dbesc($x['hash']), intval($channel['channel_id']) ); - if($r) { + if ($r) { // connection exists @@ -358,7 +358,7 @@ class Libzot { // we have as we may have updated the year after sending a notification; and resetting // to the one we just received would cause us to create duplicated events. - if(substr($r[0]['abook_dob'],5) == substr($next_birthday,5)) + if (substr($r[0]['abook_dob'], 5) == substr($next_birthday, 5)) $next_birthday = $r[0]['abook_dob']; $y = q("update abook set abook_dob = '%s' @@ -369,30 +369,30 @@ class Libzot { intval($channel['channel_id']) ); - if(! $y) + if (!$y) logger('abook update failed'); else { // if we were just granted read stream permission and didn't have it before, try to pull in some posts - if((! $old_read_stream_perm) && (intval($permissions['view_stream']))) - Master::Summon([ 'Onepoll', $r[0]['abook_id'] ]); + if ((!$old_read_stream_perm) && (intval($permissions['view_stream']))) + Master::Summon(['Onepoll', $r[0]['abook_id']]); } } else { - $p = Permissions::connect_perms($channel['channel_id']); + $p = Permissions::connect_perms($channel['channel_id']); $my_perms = $p['perms']; $automatic = $p['automatic']; // new connection - if($my_perms) { - foreach($my_perms as $k => $v) { - set_abconfig($channel['channel_id'],$x['hash'],'my_perms',$k,$v); + if ($my_perms) { + foreach ($my_perms as $k => $v) { + set_abconfig($channel['channel_id'], $x['hash'], 'my_perms', $k, $v); } } - $closeness = get_pconfig($channel['channel_id'],'system','new_abook_closeness',80); + $closeness = get_pconfig($channel['channel_id'], 'system', 'new_abook_closeness', 80); $y = abook_store_lowlevel( [ @@ -408,9 +408,9 @@ class Libzot { ] ); - if($y) { + if ($y) { logger("New introduction received for {$channel['channel_name']}"); - $new_perms = get_all_perms($channel['channel_id'],$x['hash'],false); + $new_perms = get_all_perms($channel['channel_id'], $x['hash'], false); // Send a clone sync packet and a permissions update if permissions have changed @@ -419,45 +419,45 @@ class Libzot { intval($channel['channel_id']) ); - if($new_connection) { - if(! Permissions::PermsCompare($new_perms,$previous_perms)) - Master::Summon([ 'Notifier', 'permission_create', $new_connection[0]['abook_id'] ]); + if ($new_connection) { + if (!Permissions::PermsCompare($new_perms, $previous_perms)) + Master::Summon(['Notifier', 'permission_create', $new_connection[0]['abook_id']]); Enotify::submit( [ - 'type' => NOTIFY_INTRO, - 'from_xchan' => $x['hash'], - 'to_xchan' => $channel['channel_hash'], - 'link' => z_root() . '/connedit/' . $new_connection[0]['abook_id'] + 'type' => NOTIFY_INTRO, + 'from_xchan' => $x['hash'], + 'to_xchan' => $channel['channel_hash'], + 'link' => z_root() . '/connedit/' . $new_connection[0]['abook_id'] ] ); - if(intval($permissions['view_stream'])) { - if(intval(get_pconfig($channel['channel_id'],'perm_limits','send_stream') & PERMS_PENDING) - || (! intval($new_connection[0]['abook_pending']))) - Master::Summon([ 'Onepoll', $new_connection[0]['abook_id'] ]); + if (intval($permissions['view_stream'])) { + if (intval(get_pconfig($channel['channel_id'], 'perm_limits', 'send_stream') & PERMS_PENDING) + || (!intval($new_connection[0]['abook_pending']))) + Master::Summon(['Onepoll', $new_connection[0]['abook_id']]); } // If there is a default group for this channel, add this connection to it // for pending connections this will happens at acceptance time. - if(! intval($new_connection[0]['abook_pending'])) { + if (!intval($new_connection[0]['abook_pending'])) { $default_group = $channel['channel_default_group']; - if($default_group) { - $g = Group::rec_byhash($channel['channel_id'],$default_group); - if($g) - Group::member_add($channel['channel_id'],'',$x['hash'],$g['id']); + if ($default_group) { + $g = Group::rec_byhash($channel['channel_id'], $default_group); + if ($g) + Group::member_add($channel['channel_id'], '', $x['hash'], $g['id']); } } unset($new_connection[0]['abook_id']); unset($new_connection[0]['abook_account']); unset($new_connection[0]['abook_channel']); - $abconfig = load_abconfig($channel['channel_id'],$new_connection['abook_xchan']); - if($abconfig) + $abconfig = load_abconfig($channel['channel_id'], $new_connection['abook_xchan']); + if ($abconfig) $new_connection['abconfig'] = $abconfig; - Libsync::build_sync_packet($channel['channel_id'], array('abook' => $new_connection)); + Libsync::build_sync_packet($channel['channel_id'], ['abook' => $new_connection]); } } @@ -489,9 +489,9 @@ class Libzot { static function gethub($arr, $multiple = false) { - if($arr['id'] && $arr['id_sig'] && $arr['location'] && $arr['location_sig']) { + if ($arr['id'] && $arr['id_sig'] && $arr['location'] && $arr['location_sig']) { - if(! check_siteallowed($arr['location'])) { + if (!check_siteallowed($arr['location'])) { logger('blacklisted site: ' . $arr['location']); return null; } @@ -509,12 +509,12 @@ class Libzot { dbesc($arr['location_sig']), dbesc($arr['site_id']) ); - if($r) { + if ($r) { logger('Found', LOGGER_DEBUG); return (($multiple) ? $r : $r[0]); } } - logger('Not found: ' . print_r($arr,true), LOGGER_DEBUG); + logger('Not found: ' . print_r($arr, true), LOGGER_DEBUG); return false; } @@ -532,16 +532,16 @@ class Libzot { dbesc($sender), dbesc($site_id) ); - if(! $r) { + if (!$r) { return null; } - if(! check_siteallowed($r[0]['hubloc_url'])) { + if (!check_siteallowed($r[0]['hubloc_url'])) { logger('blacklisted site: ' . $r[0]['hubloc_url']); return null; } - if(! check_channelallowed($r[0]['hubloc_hash'])) { + if (!check_channelallowed($r[0]['hubloc_hash'])) { logger('blacklisted channel: ' . $r[0]['hubloc_hash']); return null; } @@ -567,9 +567,9 @@ class Libzot { $hsig_valid = false; - $result = [ 'success' => false ]; + $result = ['success' => false]; - if(! $id) { + if (!$id) { return $result; } @@ -578,16 +578,16 @@ class Libzot { // Check the HTTP signature $hsig = $record['signature']; - if($hsig['signer'] === $id && $hsig['header_valid'] === true && $hsig['content_valid'] === true) { + if ($hsig['signer'] === $id && $hsig['header_valid'] === true && $hsig['content_valid'] === true) { $hsig_valid = true; } - if(! $hsig_valid) { - logger('http signature not valid: ' . print_r($hsig,true)); + if (!$hsig_valid) { + logger('http signature not valid: ' . print_r($hsig, true)); return $result; } $c = self::import_xchan($record['data']); - if($c['success']) { + if ($c['success']) { $result['success'] = true; } else { @@ -625,26 +625,26 @@ class Libzot { */ call_hooks('import_xchan', $arr); - $ret = array('success' => false); - $dirmode = intval(get_config('system','directory_mode')); + $ret = ['success' => false]; + $dirmode = intval(get_config('system', 'directory_mode')); $changed = false; - $what = ''; + $what = ''; - if(! ($arr['id'] && $arr['id_sig'])) { - logger('No identity information provided. ' . print_r($arr,true)); + if (!($arr['id'] && $arr['id_sig'])) { + logger('No identity information provided. ' . print_r($arr, true)); return $ret; } - $xchan_hash = self::make_xchan_hash($arr['id'],$arr['public_key']); + $xchan_hash = self::make_xchan_hash($arr['id'], $arr['public_key']); $arr['hash'] = $xchan_hash; $import_photos = false; - $sig_methods = ((array_key_exists('signing',$arr) && is_array($arr['signing'])) ? $arr['signing'] : [ 'sha256' ]); - $verified = false; + $sig_methods = ((array_key_exists('signing', $arr) && is_array($arr['signing'])) ? $arr['signing'] : ['sha256']); + $verified = false; - if(! self::verify($arr['id'],$arr['id_sig'],$arr['public_key'])) { + if (!self::verify($arr['id'], $arr['id_sig'], $arr['public_key'])) { logger('Unable to verify channel signature for ' . $arr['address']); return $ret; } @@ -652,7 +652,7 @@ class Libzot { $verified = true; } - if(! $verified) { + if (!$verified) { $ret['message'] = t('Unable to verify channel signature'); return $ret; } @@ -663,40 +663,40 @@ class Libzot { dbesc($xchan_hash) ); - if(! array_key_exists('connect_url', $arr)) + if (!array_key_exists('connect_url', $arr)) $arr['connect_url'] = ''; - if($r) { - if($arr['photo'] && array_key_exists('updated',$arr['photo']) && $r[0]['xchan_photo_date'] != $arr['photo']['updated']) { + if ($r) { + if ($arr['photo'] && array_key_exists('updated', $arr['photo']) && $r[0]['xchan_photo_date'] != $arr['photo']['updated']) { $import_photos = true; } // if we import an entry from a site that's not ours and either or both of us is off the grid - hide the entry. /** @TODO: check if we're the same directory realm, which would mean we are allowed to see it */ - $dirmode = get_config('system','directory_mode'); + $dirmode = get_config('system', 'directory_mode'); - if((($arr['site']['directory_mode'] === 'standalone') || ($dirmode & DIRECTORY_MODE_STANDALONE)) && ($arr['site']['url'] != z_root())) + if ((($arr['site']['directory_mode'] === 'standalone') || ($dirmode & DIRECTORY_MODE_STANDALONE)) && ($arr['site']['url'] != z_root())) $arr['searchable'] = false; $hidden = (1 - intval($arr['searchable'])); $hidden_changed = $adult_changed = $deleted_changed = $pubforum_changed = 0; - if(intval($r[0]['xchan_hidden']) != (1 - intval($arr['searchable']))) + if (intval($r[0]['xchan_hidden']) != (1 - intval($arr['searchable']))) $hidden_changed = 1; - if(intval($r[0]['xchan_selfcensored']) != intval($arr['adult_content'])) + if (intval($r[0]['xchan_selfcensored']) != intval($arr['adult_content'])) $adult_changed = 1; - if(intval($r[0]['xchan_deleted']) != intval($arr['deleted'])) + if (intval($r[0]['xchan_deleted']) != intval($arr['deleted'])) $deleted_changed = 1; // new style 6-MAR-2019 - if(array_key_exists('channel_type',$arr)) { - if($arr['channel_type'] === 'collection') { + if (array_key_exists('channel_type', $arr)) { + if ($arr['channel_type'] === 'collection') { // do nothing at this time. } - elseif($arr['channel_type'] === 'group') { + elseif ($arr['channel_type'] === 'group') { $arr['public_forum'] = 1; } else { @@ -706,27 +706,27 @@ class Libzot { // old style - if(intval($r[0]['xchan_pubforum']) != intval($arr['public_forum'])) + if (intval($r[0]['xchan_pubforum']) != intval($arr['public_forum'])) $pubforum_changed = 1; - if($arr['protocols']) { - $protocols = implode(',',$arr['protocols']); - if($protocols !== 'zot6') { - set_xconfig($xchan_hash,'system','protocols',$protocols); + if ($arr['protocols']) { + $protocols = implode(',', $arr['protocols']); + if ($protocols !== 'zot6') { + set_xconfig($xchan_hash, 'system', 'protocols', $protocols); } else { - del_xconfig($xchan_hash,'system','protocols'); + del_xconfig($xchan_hash, 'system', 'protocols'); } } - if(($r[0]['xchan_name_date'] != $arr['name_updated']) + if (($r[0]['xchan_name_date'] != $arr['name_updated']) || ($r[0]['xchan_connurl'] != $arr['primary_location']['connections_url']) || ($r[0]['xchan_addr'] != $arr['primary_location']['address']) || ($r[0]['xchan_follow'] != $arr['primary_location']['follow_url']) || ($r[0]['xchan_connpage'] != $arr['connect_url']) || ($r[0]['xchan_url'] != $arr['primary_location']['url']) - || $hidden_changed || $adult_changed || $deleted_changed || $pubforum_changed ) { + || $hidden_changed || $adult_changed || $deleted_changed || $pubforum_changed) { $rup = q("update xchan set xchan_name = '%s', xchan_name_date = '%s', xchan_connurl = '%s', xchan_follow = '%s', xchan_connpage = '%s', xchan_hidden = %d, xchan_selfcensored = %d, xchan_deleted = %d, xchan_pubforum = %d, xchan_addr = '%s', xchan_url = '%s' where xchan_hash = '%s'", @@ -744,18 +744,18 @@ class Libzot { dbesc($xchan_hash) ); - logger('Update: existing: ' . print_r($r[0],true), LOGGER_DATA, LOG_DEBUG); - logger('Update: new: ' . print_r($arr,true), LOGGER_DATA, LOG_DEBUG); - $what .= 'xchan '; + logger('Update: existing: ' . print_r($r[0], true), LOGGER_DATA, LOG_DEBUG); + logger('Update: new: ' . print_r($arr, true), LOGGER_DATA, LOG_DEBUG); + $what .= 'xchan '; $changed = true; } } else { $import_photos = true; - if((($arr['site']['directory_mode'] === 'standalone') + if ((($arr['site']['directory_mode'] === 'standalone') || ($dirmode & DIRECTORY_MODE_STANDALONE)) - && ($arr['site']['url'] != z_root())) + && ($arr['site']['url'] != z_root())) $arr['searchable'] = false; $x = xchan_store_lowlevel( @@ -782,11 +782,11 @@ class Libzot { ] ); - $what .= 'new_xchan'; + $what .= 'new_xchan'; $changed = true; } - if($import_photos) { + if ($import_photos) { require_once('include/photo/photo_driver.php'); @@ -795,13 +795,13 @@ class Libzot { $local = q("select channel_account_id, channel_id from channel where channel_hash = '%s' limit 1", dbesc($xchan_hash) ); - if($local) { + if ($local) { $ph = z_fetch_url($arr['photo']['url'], true); - if($ph['success']) { + if ($ph['success']) { $hash = import_channel_photo($ph['body'], $arr['photo']['type'], $local[0]['channel_account_id'], $local[0]['channel_id']); - if($hash) { + if ($hash) { // unless proven otherwise $is_default_profile = 1; @@ -809,13 +809,13 @@ class Libzot { intval($local[0]['channel_account_id']), intval($local[0]['channel_id']) ); - if($profile) { - if(! intval($profile[0]['is_default'])) + if ($profile) { + if (!intval($profile[0]['is_default'])) $is_default_profile = 0; } // If setting for the default profile, unset the profile photo flag from any other photos I own - if($is_default_profile) { + if ($is_default_profile) { q("UPDATE photo SET photo_usage = %d WHERE photo_usage = %d AND resource_id != '%s' AND aid = %d AND uid = %d", intval(PHOTO_NORMAL), intval(PHOTO_PROFILE), @@ -827,20 +827,20 @@ class Libzot { } // reset the names in case they got messed up when we had a bug in this function - $photos = array( + $photos = [ z_root() . '/photo/profile/l/' . $local[0]['channel_id'], z_root() . '/photo/profile/m/' . $local[0]['channel_id'], z_root() . '/photo/profile/s/' . $local[0]['channel_id'], $arr['photo_mimetype'], false - ); + ]; } } else { $photos = import_xchan_photo($arr['photo']['url'], $xchan_hash); } - if($photos) { - if($photos[4]) { + if ($photos) { + if ($photos[4]) { // importing the photo failed somehow. Leave the photo_date alone so we can try again at a later date. // This often happens when somebody joins the matrix with a bad cert. $r = q("update xchan set xchan_photo_l = '%s', xchan_photo_m = '%s', xchan_photo_s = '%s', xchan_photo_mimetype = '%s' @@ -855,7 +855,7 @@ class Libzot { else { $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'", - dbescdate(datetime_convert('UTC','UTC',$arr['photo_updated'])), + dbescdate(datetime_convert('UTC', 'UTC', $arr['photo_updated'])), dbesc($photos[0]), dbesc($photos[1]), dbesc($photos[2]), @@ -863,7 +863,7 @@ class Libzot { dbesc($xchan_hash) ); } - $what .= 'photo '; + $what .= 'photo '; $changed = true; } } @@ -873,12 +873,12 @@ class Libzot { $s = Libsync::sync_locations($arr, $arr); - if($s) { - if($s['change_message']) + if ($s) { + if ($s['change_message']) $what .= $s['change_message']; - if($s['changed']) + if ($s['changed']) $changed = $s['changed']; - if($s['message']) + if ($s['message']) $ret['message'] .= $s['message']; } @@ -890,24 +890,24 @@ class Libzot { // Are we a directory server of some kind? $other_realm = false; - $realm = get_directory_realm(); - if(array_key_exists('site',$arr) - && array_key_exists('realm',$arr['site']) - && (strpos($arr['site']['realm'],$realm) === false)) + $realm = get_directory_realm(); + if (array_key_exists('site', $arr) + && array_key_exists('realm', $arr['site']) + && (strpos($arr['site']['realm'], $realm) === false)) $other_realm = true; - if($dirmode != DIRECTORY_MODE_NORMAL) { + if ($dirmode != DIRECTORY_MODE_NORMAL) { // We're some kind of directory server. However we can only add directory information // if the entry is in the same realm (or is a sub-realm). Sub-realms are denoted by // including the parent realm in the name. e.g. 'RED_GLOBAL:foo' would allow an entry to // be in directories for the local realm (foo) and also the RED_GLOBAL realm. - if(array_key_exists('profile',$arr) && is_array($arr['profile']) && (! $other_realm)) { - $profile_changed = Libzotdir::import_directory_profile($xchan_hash,$arr['profile'],$address,$ud_flags, 1); - if($profile_changed) { - $what .= 'profile '; + if (array_key_exists('profile', $arr) && is_array($arr['profile']) && (!$other_realm)) { + $profile_changed = Libzotdir::import_directory_profile($xchan_hash, $arr['profile'], $address, $ud_flags, 1); + if ($profile_changed) { + $what .= 'profile '; $changed = true; } } @@ -923,20 +923,20 @@ class Libzot { } } - if(array_key_exists('site',$arr) && is_array($arr['site'])) { + if (array_key_exists('site', $arr) && is_array($arr['site'])) { $profile_changed = self::import_site($arr['site']); - if($profile_changed) { - $what .= 'site '; + if ($profile_changed) { + $what .= 'site '; $changed = true; } } - if(($changed) || ($ud_flags == UPDATE_FLAGS_FORCED)) { + if (($changed) || ($ud_flags == UPDATE_FLAGS_FORCED)) { $guid = random_string() . '@' . \App::get_hostname(); - Libzotdir::update_modtime($xchan_hash,$guid,$address,$ud_flags); - logger('Changed: ' . $what,LOGGER_DEBUG); + Libzotdir::update_modtime($xchan_hash, $guid, $address, $ud_flags); + logger('Changed: ' . $what, LOGGER_DEBUG); } - elseif(! $ud_flags) { + elseif (!$ud_flags) { // nothing changed but we still need to update the updates record q("update updates set ud_flags = ( ud_flags | %d ) where ud_addr = '%s' and not (ud_flags & %d) > 0 ", intval(UPDATE_FLAGS_UPDATED), @@ -945,12 +945,12 @@ class Libzot { ); } - if(! x($ret,'message')) { + if (!x($ret, 'message')) { $ret['success'] = true; - $ret['hash'] = $xchan_hash; + $ret['hash'] = $xchan_hash; } - logger('Result: ' . print_r($ret,true), LOGGER_DATA, LOG_DEBUG); + logger('Result: ' . print_r($ret, true), LOGGER_DATA, LOG_DEBUG); return $ret; } @@ -967,32 +967,32 @@ class Libzot { */ static function process_response($hub, $arr, $outq) { - logger('remote: ' . print_r($arr,true),LOGGER_DATA); + logger('remote: ' . print_r($arr, true), LOGGER_DATA); - if(! $arr['success']) { + if (!$arr['success']) { logger('Failed: ' . $hub); return; } $x = json_decode($arr['body'], true); - if(! $x) { + if (!$x) { logger('No json from ' . $hub); logger('Headers: ' . print_r($arr['header'], true), LOGGER_DATA, LOG_DEBUG); } - $x = crypto_unencapsulate($x, get_config('system','prvkey')); + $x = crypto_unencapsulate($x, get_config('system', 'prvkey')); - if(! is_array($x)) { - $x = json_decode($x,true); + if (!is_array($x)) { + $x = json_decode($x, true); } - if(! is_array($x)) { + if (!is_array($x)) { btlogger('failed communication - no response'); } - if($x) { - if(! $x['success']) { + if ($x) { + if (!$x['success']) { // handle remote validation issues @@ -1003,18 +1003,18 @@ class Libzot { ); } - if(is_array($x) && array_key_exists('delivery_report',$x) && is_array($x['delivery_report'])) { + if (is_array($x) && array_key_exists('delivery_report', $x) && is_array($x['delivery_report'])) { - foreach($x['delivery_report'] as $xx) { - call_hooks('dreport_process',$xx); - if(is_array($xx) && array_key_exists('message_id',$xx) && DReport::is_storable($xx)) { + foreach ($x['delivery_report'] as $xx) { + call_hooks('dreport_process', $xx); + if (is_array($xx) && array_key_exists('message_id', $xx) && DReport::is_storable($xx)) { // legacy recipients add a space and their name to the xchan. split those if true. $legacy_recipient = strpos($xx['recipient'], ' '); - if($legacy_recipient !== false) { + if ($legacy_recipient !== false) { $legacy_recipient_parts = explode(' ', $xx['recipient'], 2); - $xx['recipient'] = $legacy_recipient_parts[0]; - $xx['name'] = $legacy_recipient_parts[1]; + $xx['recipient'] = $legacy_recipient_parts[0]; + $xx['name'] = $legacy_recipient_parts[1]; } q("insert into dreport ( dreport_mid, dreport_site, dreport_recip, dreport_name, dreport_result, dreport_time, dreport_xchan ) values ( '%s', '%s', '%s','%s','%s','%s','%s' ) ", @@ -1023,7 +1023,7 @@ class Libzot { dbesc($xx['recipient']), dbesc($xx['name']), dbesc($xx['status']), - dbesc(datetime_convert('UTC','UTC',$xx['date'])), + dbesc(datetime_convert('UTC', 'UTC', $xx['date'])), dbesc($xx['sender']) ); } @@ -1046,10 +1046,10 @@ class Libzot { // synchronous message types are handled immediately // async messages remain in the queue until processed. - if(intval($outq['outq_async'])) - Queue::remove($outq['outq_hash'],$outq['outq_channel']); + if (intval($outq['outq_async'])) + Queue::remove($outq['outq_hash'], $outq['outq_channel']); - logger('zot_process_response: ' . print_r($x,true), LOGGER_DEBUG); + logger('zot_process_response: ' . print_r($x, true), LOGGER_DEBUG); } /** @@ -1067,16 +1067,16 @@ class Libzot { * If everything checks out on the remote end, we will receive back a packet containing one or more messages, * which will be processed and delivered before this function ultimately returns. * - * @see zot_import() - * * @param array $arr * decrypted and json decoded notify packet from remote site * @return array from zot_import() + * @see zot_import() + * */ static function fetch($arr) { - logger('zot_fetch: ' . print_r($arr,true), LOGGER_DATA, LOG_DEBUG); + logger('zot_fetch: ' . print_r($arr, true), LOGGER_DATA, LOG_DEBUG); return self::import($arr); @@ -1101,15 +1101,15 @@ class Libzot { */ static function import($arr) { - $env = $arr; + $env = $arr; $private = false; - $return = []; + $return = []; $result = null; - logger('Notify: ' . print_r($env,true), LOGGER_DATA, LOG_DEBUG); + logger('Notify: ' . print_r($env, true), LOGGER_DATA, LOG_DEBUG); - if(! is_array($env)) { + if (!is_array($env)) { logger('decode error'); return; } @@ -1117,59 +1117,59 @@ class Libzot { $message_request = false; - $has_data = array_key_exists('data',$env) && $env['data']; - $data = (($has_data) ? $env['data'] : false); + $has_data = array_key_exists('data', $env) && $env['data']; + $data = (($has_data) ? $env['data'] : false); $AS = null; - if($env['encoding'] === 'activitystreams') { + if ($env['encoding'] === 'activitystreams') { - $AS = new ActivityStreams($data); - if(! $AS->is_valid()) { - logger('Activity rejected: ' . print_r($data,true)); - return; - } - if (is_array($AS->obj)) { - $arr = Activity::decode_note($AS); - } - else { - $arr = []; - } + $AS = new ActivityStreams($data); + if (!$AS->is_valid()) { + logger('Activity rejected: ' . print_r($data, true)); + return; + } + if (is_array($AS->obj)) { + $arr = Activity::decode_note($AS); + } + else { + $arr = []; + } - logger($AS->debug(),LOGGER_DATA); + logger($AS->debug(), LOGGER_DATA); } $deliveries = null; - if(array_key_exists('recipients',$env) && count($env['recipients'])) { + if (array_key_exists('recipients', $env) && count($env['recipients'])) { logger('specific recipients'); - logger('recipients: ' . print_r($env['recipients'],true),LOGGER_DEBUG); + logger('recipients: ' . print_r($env['recipients'], true), LOGGER_DEBUG); $recip_arr = []; - foreach($env['recipients'] as $recip) { - $recip_arr[] = $recip; + foreach ($env['recipients'] as $recip) { + $recip_arr[] = $recip; } $r = false; - if($recip_arr) { - stringify_array_elms($recip_arr,true); - $recips = implode(',',$recip_arr); - $r = q("select channel_hash as hash from channel where channel_hash in ( " . $recips . " ) and channel_removed = 0 "); + if ($recip_arr) { + stringify_array_elms($recip_arr, true); + $recips = implode(',', $recip_arr); + $r = q("select channel_hash as hash from channel where channel_hash in ( " . $recips . " ) and channel_removed = 0 "); } - if(! $r) { + if (!$r) { logger('recips: no recipients on this site'); return; } // Response messages will inherit the privacy of the parent - if($env['type'] !== 'response') + if ($env['type'] !== 'response') $private = true; - $deliveries = ids_to_array($r,'hash'); + $deliveries = ids_to_array($r, 'hash'); // We found somebody on this site that's in the recipient list. } @@ -1182,33 +1182,33 @@ class Libzot { // and who are allowed to see them based on the sender's permissions // @fixme; - $deliveries = self::public_recips($env,$AS); + $deliveries = self::public_recips($env, $AS); } $deliveries = array_unique($deliveries); - if(! $deliveries) { + if (!$deliveries) { logger('No deliveries on this site'); return; } - if($has_data) { + if ($has_data) { - if(in_array($env['type'],['activity','response'])) { + if (in_array($env['type'], ['activity', 'response'])) { $r = q("select hubloc_hash, hubloc_network from hubloc where hubloc_id_url = '%s' ", dbesc($AS->actor['id']) ); - if($r) { + if ($r) { // selects a zot6 hash if available, otherwise use whatever we have - $r = self::zot_record_preferred($r); + $r = self::zot_record_preferred($r); $arr['author_xchan'] = $r['hubloc_hash']; } - if (! $arr['author_xchan']) { + if (!$arr['author_xchan']) { logger('No author!'); return; } @@ -1218,43 +1218,43 @@ class Libzot { ); // in individual delivery, change owner if needed - if($s) { + if ($s) { $arr['owner_xchan'] = $s[0]['hubloc_hash']; } else { $arr['owner_xchan'] = $env['sender']; } - if ($private && (! intval($arr['item_private']))) { + if ($private && (!intval($arr['item_private']))) { $arr['item_private'] = 1; } if ($arr['mid'] === $arr['parent_mid']) { - if (is_array($AS->obj) && array_key_exists('commentPolicy',$AS->obj)) { - $p = strstr($AS->obj['commentPolicy'],'until='); - if($p !== false) { - $arr['comments_closed'] = datetime_convert('UTC','UTC', substr($p,6)); - $arr['comment_policy'] = trim(str_replace($p,'',$AS->obj['commentPolicy'])); + if (is_array($AS->obj) && array_key_exists('commentPolicy', $AS->obj)) { + $p = strstr($AS->obj['commentPolicy'], 'until='); + if ($p !== false) { + $arr['comments_closed'] = datetime_convert('UTC', 'UTC', substr($p, 6)); + $arr['comment_policy'] = trim(str_replace($p, '', $AS->obj['commentPolicy'])); } else { - $arr['comment_policy'] = $AS->obj['commentPolicy']; + $arr['comment_policy'] = $AS->obj['commentPolicy']; } } } /// @FIXME - spoofable - if($AS->data['hubloc']) { + if ($AS->data['hubloc']) { $arr['item_verified'] = true; - if (! array_key_exists('comment_policy',$arr)) { + if (!array_key_exists('comment_policy', $arr)) { // set comment policy depending on source hub. Unknown or osada is ActivityPub. // Anything else we'll say is zot - which could have a range of project names $s = q("select site_project from site where site_url = '%s' limit 1", dbesc($r[0]['hubloc_url']) ); - if ((! $s) || (in_array($s[0]['site_project'],[ '', 'osada' ]))) { + if ((!$s) || (in_array($s[0]['site_project'], ['', 'osada']))) { $arr['comment_policy'] = 'authenticated'; } else { @@ -1262,28 +1262,28 @@ class Libzot { } } } - if($AS->data['signed_data']) { - IConfig::Set($arr,'activitystreams','signed_data',$AS->data['signed_data'],false); + if ($AS->data['signed_data']) { + IConfig::Set($arr, 'activitystreams', 'signed_data', $AS->data['signed_data'], false); } - logger('Activity received: ' . print_r($arr,true), LOGGER_DATA, LOG_DEBUG); - logger('Activity recipients: ' . print_r($deliveries,true), LOGGER_DATA, LOG_DEBUG); + logger('Activity received: ' . print_r($arr, true), LOGGER_DATA, LOG_DEBUG); + logger('Activity recipients: ' . print_r($deliveries, true), LOGGER_DATA, LOG_DEBUG); - $relay = (($env['type'] === 'response') ? true : false ); + $relay = (($env['type'] === 'response') ? true : false); - $result = self::process_delivery($env['sender'],$AS,$arr,$deliveries,$relay,false,$message_request); + $result = self::process_delivery($env['sender'], $AS, $arr, $deliveries, $relay, false, $message_request); } - elseif($env['type'] === 'sync') { + elseif ($env['type'] === 'sync') { // $arr = get_channelsync_elements($data); - $arr = json_decode($data,true); + $arr = json_decode($data, true); - logger('Channel sync received: ' . print_r($arr,true), LOGGER_DATA, LOG_DEBUG); - logger('Channel sync recipients: ' . print_r($deliveries,true), LOGGER_DATA, LOG_DEBUG); + logger('Channel sync received: ' . print_r($arr, true), LOGGER_DATA, LOG_DEBUG); + logger('Channel sync recipients: ' . print_r($deliveries, true), LOGGER_DATA, LOG_DEBUG); if ($env['encoding'] === 'hz') { - $result = Libsync::process_channel_sync_delivery($env['sender'],$arr,$deliveries); + $result = Libsync::process_channel_sync_delivery($env['sender'], $arr, $deliveries); } else { logger('sync packet type not supported.'); @@ -1305,15 +1305,15 @@ class Libzot { * @return boolean */ static function is_top_level($env, $act) { - if($env['encoding'] === 'zot' && array_key_exists('flags',$env) && in_array('thread_parent', $env['flags'])) { + if ($env['encoding'] === 'zot' && array_key_exists('flags', $env) && in_array('thread_parent', $env['flags'])) { return true; } - if($act) { - if(in_array($act->type, ['Like','Dislike'])) { + if ($act) { + if (in_array($act->type, ['Like', 'Dislike'])) { return false; } - $x = self::find_parent($env,$act); - if($x === $act->id || $x === $act->obj['id']) { + $x = self::find_parent($env, $act); + if ($x === $act->id || $x === $act->obj['id']) { return true; } } @@ -1321,12 +1321,12 @@ class Libzot { } - static function find_parent($env,$act) { - if($act) { - if(in_array($act->type, ['Like','Dislike'])) { + static function find_parent($env, $act) { + if ($act) { + if (in_array($act->type, ['Like', 'Dislike'])) { return $act->obj['id']; } - if($act->parent_id) { + if ($act->parent_id) { return $act->parent_id; } } @@ -1355,58 +1355,57 @@ class Libzot { require_once('include/channel.php'); $check_mentions = false; - $include_sys = false; + $include_sys = false; - if($msg['type'] === 'activity') { - $disable_discover_tab = get_config('system','disable_discover_tab') || get_config('system','disable_discover_tab') === false; - if(! $disable_discover_tab) + if ($msg['type'] === 'activity') { + $disable_discover_tab = get_config('system', 'disable_discover_tab') || get_config('system', 'disable_discover_tab') === false; + if (!$disable_discover_tab) $include_sys = true; $perm = 'send_stream'; - if(self::is_top_level($msg,$act)) { + if (self::is_top_level($msg, $act)) { $check_mentions = true; } } - elseif($msg['type'] === 'mail') + elseif ($msg['type'] === 'mail') $perm = 'post_mail'; $r = []; $c = q("select channel_id, channel_hash from channel where channel_removed = 0"); - if($c) { - foreach($c as $cc) { - if(perm_is_allowed($cc['channel_id'],$msg['sender'],$perm)) { + if ($c) { + foreach ($c as $cc) { + if (perm_is_allowed($cc['channel_id'], $msg['sender'], $perm)) { $r[] = $cc['channel_hash']; } } } - if($include_sys) { + if ($include_sys) { $sys = get_sys_channel(); - if($sys) + if ($sys) $r[] = $sys['channel_hash']; } - // look for any public mentions on this site // They will get filtered by tgroup_check() so we don't need to check permissions now - if($check_mentions) { + if ($check_mentions) { // It's a top level post. Look at the tags. See if any of them are mentions and are on this hub. - if($act && $act->obj) { - if(is_array($act->obj['tag']) && $act->obj['tag']) { - foreach($act->obj['tag'] as $tag) { - if($tag['type'] === 'Mention' && (strpos($tag['href'],z_root()) !== false)) { + if ($act && $act->obj) { + if (is_array($act->obj['tag']) && $act->obj['tag']) { + foreach ($act->obj['tag'] as $tag) { + if ($tag['type'] === 'Mention' && (strpos($tag['href'], z_root()) !== false)) { $address = basename($tag['href']); - if($address) { + if ($address) { $z = q("select channel_hash as hash from channel where channel_address = '%s' and channel_removed = 0 limit 1", dbesc($address) ); - if($z) { + if ($z) { $r[] = $z[0]['hash']; } } @@ -1420,15 +1419,15 @@ class Libzot { // everybody that stored a copy of the parent. This way we know we're covered. We'll check the // comment permissions when we deliver them. - $thread_parent = self::find_parent($msg,$act); + $thread_parent = self::find_parent($msg, $act); - if($thread_parent) { + if ($thread_parent) { $z = q("select channel_hash as hash from channel left join item on channel.channel_id = item.uid where ( item.thr_parent = '%s' OR item.parent_mid = '%s' ) ", dbesc($thread_parent), dbesc($thread_parent) ); - if($z) { - foreach($z as $zv) { + if ($z) { + foreach ($z as $zv) { $r[] = $zv['hash']; } } @@ -1438,11 +1437,11 @@ class Libzot { // There are probably a lot of duplicates in $r at this point. We need to filter those out. // It's a bit of work since it's a multi-dimensional array - if($r) { + if ($r) { $r = array_values(array_unique($r)); } - logger('public_recips: ' . print_r($r,true), LOGGER_DATA, LOG_DEBUG); + logger('public_recips: ' . print_r($r, true), LOGGER_DATA, LOG_DEBUG); return $r; } @@ -1465,22 +1464,22 @@ class Libzot { // We've validated the sender. Now make sure that the sender is the owner or author - if(! $public) { - if($sender != $arr['owner_xchan'] && $sender != $arr['author_xchan']) { + if (!$public) { + if ($sender != $arr['owner_xchan'] && $sender != $arr['author_xchan']) { logger("Sender $sender is not owner {$arr['owner_xchan']} or author {$arr['author_xchan']} - mid {$arr['mid']}"); return; } } - foreach($deliveries as $d) { + foreach ($deliveries as $d) { $local_public = $public; - $DR = new DReport(z_root(),$sender,$d,$arr['mid']); + $DR = new DReport(z_root(), $sender, $d, $arr['mid']); $channel = channelx_by_hash($d); - if (! $channel) { + if (!$channel) { $DR->update('recipient not found'); $result[] = $DR->get(); continue; @@ -1488,16 +1487,16 @@ class Libzot { $DR->set_name($channel['channel_name'] . ' <' . channel_reddress($channel) . '>'); - if(($act) && ($act->obj) && (! is_array($act->obj))) { + if (($act) && ($act->obj) && (!is_array($act->obj))) { // The initial object fetch failed using the sys channel credentials. // Try again using the delivery channel credentials. // We will also need to re-parse the $item array, // but preserve any values that were set during anonymous parsing. - $o = Activity::fetch($act->obj,$channel); - if($o) { + $o = Activity::fetch($act->obj, $channel); + if ($o) { $act->obj = $o; - $arr = array_merge(Activity::decode_note($act),$arr); + $arr = array_merge(Activity::decode_note($act), $arr); } else { @@ -1516,7 +1515,7 @@ class Libzot { * access checks. */ - if($sender === $channel['channel_hash'] && $arr['author_xchan'] === $channel['channel_hash'] && $arr['mid'] === $arr['parent_mid']) { + if ($sender === $channel['channel_hash'] && $arr['author_xchan'] === $channel['channel_hash'] && $arr['mid'] === $arr['parent_mid']) { $DR->update('self delivery ignored'); $result[] = $DR->get(); continue; @@ -1526,32 +1525,32 @@ class Libzot { // for comments travelling upstream. Wait and catch them on the way down. // They may have been blocked by the owner. - if(intval($channel['channel_system']) && (! $arr['item_private']) && (! $relay)) { + if (intval($channel['channel_system']) && (!$arr['item_private']) && (!$relay)) { $local_public = true; $r = q("select xchan_selfcensored from xchan where xchan_hash = '%s' limit 1", dbesc($sender) ); // don't import sys channel posts from selfcensored authors - if($r && (intval($r[0]['xchan_selfcensored']))) { + if ($r && (intval($r[0]['xchan_selfcensored']))) { $local_public = false; continue; } - if(! MessageFilter::evaluate($arr,get_config('system','pubstream_incl'),get_config('system','pubstream_excl'))) { + if (!MessageFilter::evaluate($arr, get_config('system', 'pubstream_incl'), get_config('system', 'pubstream_excl'))) { $local_public = false; continue; } } - $tag_delivery = tgroup_check($channel['channel_id'],$arr); + $tag_delivery = tgroup_check($channel['channel_id'], $arr); $perm = 'send_stream'; - if(($arr['mid'] !== $arr['parent_mid']) && ($relay)) + if (($arr['mid'] !== $arr['parent_mid']) && ($relay)) $perm = 'post_comments'; // This is our own post, possibly coming from a channel clone - if($arr['owner_xchan'] == $d) { + if ($arr['owner_xchan'] == $d) { $arr['item_wall'] = 1; } else { @@ -1560,15 +1559,15 @@ class Libzot { $friendofriend = false; - if ((! $tag_delivery) && (! $local_public)) { - $allowed = (perm_is_allowed($channel['channel_id'],$sender,$perm)); - if((! $allowed) && $perm === 'post_comments') { + if ((!$tag_delivery) && (!$local_public)) { + $allowed = (perm_is_allowed($channel['channel_id'], $sender, $perm)); + if ((!$allowed) && $perm === 'post_comments') { $parent = q("select * from item where mid = '%s' and uid = %d limit 1", dbesc($arr['parent_mid']), intval($channel['channel_id']) ); if ($parent) { - $allowed = can_comment_on_post($sender,$parent[0]); + $allowed = can_comment_on_post($sender, $parent[0]); } } @@ -1588,7 +1587,7 @@ class Libzot { // doesn't exist. if ($perm === 'send_stream') { - if (get_pconfig($channel['channel_id'],'system','hyperdrive',false) || $arr['verb'] === ACTIVITY_SHARE) { + if (get_pconfig($channel['channel_id'], 'system', 'hyperdrive', false) || $arr['verb'] === ACTIVITY_SHARE) { $allowed = true; } } @@ -1599,7 +1598,7 @@ class Libzot { $friendofriend = true; } - if (! $allowed) { + if (!$allowed) { logger("permission denied for delivery to channel {$channel['channel_id']} {$channel['channel_address']}"); $DR->update('permission denied'); $result[] = $DR->get(); @@ -1609,7 +1608,7 @@ class Libzot { // logger('item: ' . print_r($arr,true), LOGGER_DATA); - if($arr['mid'] !== $arr['parent_mid']) { + if ($arr['mid'] !== $arr['parent_mid']) { logger('checking source: "' . $arr['mid'] . '" != "' . $arr['parent_mid'] . '"'); @@ -1624,7 +1623,7 @@ class Libzot { intval($channel['channel_id']) ); - if(! $r) { + if (!$r) { $DR->update('comment parent not found'); $result[] = $DR->get(); @@ -1639,9 +1638,9 @@ class Libzot { // the top level post is unlikely to be imported and // this is just an exercise in futility. - if((! $relay) && (! $request) && (! $local_public) - && perm_is_allowed($channel['channel_id'],$sender,'send_stream')) { - self::fetch_conversation($channel,$arr['parent_mid']); + if ((!$relay) && (!$request) && (!$local_public) + && perm_is_allowed($channel['channel_id'], $sender, 'send_stream')) { + self::fetch_conversation($channel, $arr['parent_mid']); } continue; } @@ -1650,13 +1649,13 @@ class Libzot { // route checking doesn't work correctly here because we've changed the privacy $r[0]['route'] = EMPTY_STR; // If this is a poll response, convert the obj_type to our (internal-only) "Answer" type - if ($arr['obj_type'] === ACTIVITY_OBJ_COMMENT && $arr['title'] && (! $arr['body'])) { + if ($arr['obj_type'] === ACTIVITY_OBJ_COMMENT && $arr['title'] && (!$arr['body'])) { $arr['obj_type'] = 'Answer'; } } - if($relay || $friendofriend || (intval($r[0]['item_private']) === 0 && intval($arr['item_private']) === 0)) { + if ($relay || $friendofriend || (intval($r[0]['item_private']) === 0 && intval($arr['item_private']) === 0)) { // reset the route in case it travelled a great distance upstream // use our parent's route so when we go back downstream we'll match // with whatever route our parent has. @@ -1664,7 +1663,7 @@ class Libzot { // but we are now getting comments via listener delivery // and if there is no privacy on this or the parent, we don't care about the route, // so just set the owner and route accordingly. - $arr['route'] = $r[0]['route']; + $arr['route'] = $r[0]['route']; $arr['owner_xchan'] = $r[0]['owner_xchan']; } else { @@ -1676,24 +1675,24 @@ class Libzot { // Always accept empty routes and firehose items (route contains 'undefined') . $existing_route = explode(',', $r[0]['route']); - $routes = count($existing_route); - if($routes) { - $last_hop = array_pop($existing_route); - $last_prior_route = implode(',',$existing_route); + $routes = count($existing_route); + if ($routes) { + $last_hop = array_pop($existing_route); + $last_prior_route = implode(',', $existing_route); } else { - $last_hop = ''; + $last_hop = ''; $last_prior_route = ''; } - if(in_array('undefined',$existing_route) || $last_hop == 'undefined' || $sender == 'undefined') + if (in_array('undefined', $existing_route) || $last_hop == 'undefined' || $sender == 'undefined') $last_hop = ''; $current_route = (($arr['route']) ? $arr['route'] . ',' : '') . $sender; - if($last_hop && $last_hop != $sender) { + if ($last_hop && $last_hop != $sender) { logger('comment route mismatch: parent route = ' . $r[0]['route'] . ' expected = ' . $current_route, LOGGER_DEBUG); - logger('comment route mismatch: parent msg = ' . $r[0]['id'],LOGGER_DEBUG); + logger('comment route mismatch: parent msg = ' . $r[0]['id'], LOGGER_DEBUG); $DR->update('comment route mismatch'); $result[] = $DR->get(); continue; @@ -1706,16 +1705,16 @@ class Libzot { } } - $ab = q("select * from abook where abook_channel = %d and abook_xchan = '%s'", + $ab = q("select * from abook where abook_channel = %d and abook_xchan = '%s'", intval($channel['channel_id']), dbesc($arr['owner_xchan']) ); $abook = (($ab) ? $ab[0] : null); - if(intval($arr['item_deleted'])) { + if (intval($arr['item_deleted'])) { // remove_community_tag is a no-op if this isn't a community tag activity - self::remove_community_tag($sender,$arr,$channel['channel_id']); + self::remove_community_tag($sender, $arr, $channel['channel_id']); // set these just in case we need to store a fresh copy of the deleted post. // This could happen if the delete got here before the original post did. @@ -1723,13 +1722,13 @@ class Libzot { $arr['aid'] = $channel['channel_account_id']; $arr['uid'] = $channel['channel_id']; - $item_id = self::delete_imported_item($sender,$act,$arr,$channel['channel_id'],$relay); + $item_id = self::delete_imported_item($sender, $act, $arr, $channel['channel_id'], $relay); $DR->update(($item_id) ? 'deleted' : 'delete_failed'); $result[] = $DR->get(); - if($relay && $item_id) { + if ($relay && $item_id) { logger('process_delivery: invoking relay'); - Master::Summon([ 'Notifier', 'relay', intval($item_id) ]); + Master::Summon(['Notifier', 'relay', intval($item_id)]); $DR->update('relayed'); $result[] = $DR->get(); } @@ -1746,11 +1745,11 @@ class Libzot { intval($channel['channel_id']) ); - if($r) { + if ($r) { // We already have this post. $item_id = $r[0]['id']; - if(intval($r[0]['item_deleted'])) { + if (intval($r[0]['item_deleted'])) { // It was deleted locally. $DR->update('update ignored'); $result[] = $DR->get(); @@ -1758,19 +1757,19 @@ class Libzot { continue; } // Maybe it has been edited? - elseif($arr['edited'] > $r[0]['edited']) { - $arr['id'] = $r[0]['id']; + elseif ($arr['edited'] > $r[0]['edited']) { + $arr['id'] = $r[0]['id']; $arr['uid'] = $channel['channel_id']; - if(($arr['mid'] == $arr['parent_mid']) && (! post_is_importable($arr,$abook))) { + if (($arr['mid'] == $arr['parent_mid']) && (!post_is_importable($arr, $abook))) { $DR->update('update ignored'); $result[] = $DR->get(); } else { - $item_result = self::update_imported_item($sender,$arr,$r[0],$channel['channel_id'],$tag_delivery); + $item_result = self::update_imported_item($sender, $arr, $r[0], $channel['channel_id'], $tag_delivery); $DR->update('updated'); $result[] = $DR->get(); - if(! $relay) - add_source_route($item_id,$sender); + if (!$relay) + add_source_route($item_id, $sender); } } else { @@ -1779,7 +1778,7 @@ class Libzot { // We need this line to ensure wall-to-wall comments are relayed (by falling through to the relay bit), // and at the same time not relay any other relayable posts more than once, because to do so is very wasteful. - if(! intval($r[0]['item_origin'])) + if (!intval($r[0]['item_origin'])) continue; } } @@ -1790,7 +1789,7 @@ class Libzot { // if it's a sourced post, call the post_local hooks as if it were // posted locally so that crosspost connectors will be triggered. - if(check_item_source($arr['uid'], $arr) || ($channel['xchan_pubforum'] == 1)) { + if (check_item_source($arr['uid'], $arr) || ($channel['xchan_pubforum'] == 1)) { /** * @hooks post_local * Called when an item has been posted on this machine via mod/item.php (also via API). @@ -1801,19 +1800,19 @@ class Libzot { $item_id = 0; - if(($arr['mid'] == $arr['parent_mid']) && (! post_is_importable($arr,$abook))) { + if (($arr['mid'] == $arr['parent_mid']) && (!post_is_importable($arr, $abook))) { $DR->update('post ignored'); $result[] = $DR->get(); } else { $item_result = item_store($arr); - if($item_result['success']) { + if ($item_result['success']) { $item_id = $item_result['item_id']; - $parr = [ - 'item_id' => $item_id, - 'item' => $arr, - 'sender' => $sender, - 'channel' => $channel + $parr = [ + 'item_id' => $item_id, + 'item' => $arr, + 'sender' => $sender, + 'channel' => $channel ]; /** * @hooks activity_received @@ -1825,8 +1824,8 @@ class Libzot { */ call_hooks('activity_received', $parr); // don't add a source route if it's a relay or later recipients will get a route mismatch - if(! $relay) - add_source_route($item_id,$sender); + if (!$relay) + add_source_route($item_id, $sender); } $DR->update(($item_id) ? 'posted' : 'storage failed: ' . $item_result['message']); $result[] = $DR->get(); @@ -1836,40 +1835,40 @@ class Libzot { // preserve conversations with which you are involved from expiration $stored = (($item_result && $item_result['item']) ? $item_result['item'] : false); - if((is_array($stored)) && ($stored['id'] != $stored['parent']) + if ((is_array($stored)) && ($stored['id'] != $stored['parent']) && ($stored['author_xchan'] === $channel['channel_hash'] || $stored['author_xchan'] === $channel['channel_hash'])) { retain_item($stored['item']['parent']); } - if($relay && $item_id) { + if ($relay && $item_id) { logger('Invoking relay'); - Master::Summon([ 'Notifier', 'relay', intval($item_id) ]); + Master::Summon(['Notifier', 'relay', intval($item_id)]); $DR->addto_update('relayed'); $result[] = $DR->get(); } } - if(! $deliveries) - $result[] = array('', 'no recipients', '', $arr['mid']); + if (!$deliveries) + $result[] = ['', 'no recipients', '', $arr['mid']]; logger('Local results: ' . print_r($result, true), LOGGER_DEBUG); return $result; } - static public function fetch_conversation($channel,$mid) { + static public function fetch_conversation($channel, $mid) { // Use Zotfinger to create a signed request - $a = Zotfinger::exec($mid,$channel); + $a = Zotfinger::exec($mid, $channel); - logger('received conversation: ' . print_r($a,true), LOGGER_DATA); + logger('received conversation: ' . print_r($a, true), LOGGER_DATA); - if($a['data']['type'] !== 'OrderedCollection') { + if ($a['data']['type'] !== 'OrderedCollection') { return; } - if(! intval($a['data']['totalItems'])) { + if (!intval($a['data']['totalItems'])) { return; } @@ -1879,45 +1878,44 @@ class Libzot { dbesc($a['signature']['signer']) ); - foreach($a['data']['orderedItems'] as $activity) { + foreach ($a['data']['orderedItems'] as $activity) { $AS = new ActivityStreams($activity); - if(! $AS->is_valid()) { - logger('FOF Activity rejected: ' . print_r($activity,true)); + if (!$AS->is_valid()) { + logger('FOF Activity rejected: ' . print_r($activity, true)); continue; } $arr = Activity::decode_note($AS); logger($AS->debug()); - $r = q("select hubloc_hash from hubloc where hubloc_id_url = '%s' and hubloc_network = 'zot6' limit 1", dbesc($AS->actor['id']) ); - if(! $r) { - $y = import_author_xchan([ 'url' => $AS->actor['id'] ]); - if($y) { + if (!$r) { + $y = import_author_xchan(['url' => $AS->actor['id']]); + if ($y) { $r = q("select hubloc_hash from hubloc where hubloc_id_url = '%s' and hubloc_network = 'zot6' limit 1", dbesc($AS->actor['id']) ); } - if(! $r) { + if (!$r) { logger('FOF Activity: no actor'); continue; } } - if($AS->obj['actor'] && $AS->obj['actor']['id'] && $AS->obj['actor']['id'] !== $AS->actor['id']) { - $y = import_author_xchan([ 'url' => $AS->obj['actor']['id'] ]); - if(! $y) { + if ($AS->obj['actor'] && $AS->obj['actor']['id'] && $AS->obj['actor']['id'] !== $AS->actor['id']) { + $y = import_author_xchan(['url' => $AS->obj['actor']['id']]); + if (!$y) { logger('FOF Activity: no object actor'); continue; } } - if($r) { + if ($r) { $arr['author_xchan'] = $r[0]['hubloc_hash']; } @@ -1925,7 +1923,7 @@ class Libzot { dbesc($a['signature']['signer']) ); - if($s) { + if ($s) { $arr['owner_xchan'] = $s[0]['hubloc_hash']; } else { @@ -1934,7 +1932,7 @@ class Libzot { /// @FIXME - spoofable - if($AS->data['hubloc']) { + if ($AS->data['hubloc']) { $arr['item_verified'] = true; } @@ -1945,7 +1943,7 @@ class Libzot { $s = q("select site_project from site where site_url = '%s' limit 1", dbesc($signer[0]['hubloc_url']) ); - if ((! $s) || (in_array($s[0]['site_project'],[ '', 'osada' ]))) { + if ((!$s) || (in_array($s[0]['site_project'], ['', 'osada']))) { $arr['comment_policy'] = 'authenticated'; } else { @@ -1954,14 +1952,14 @@ class Libzot { } - if($AS->data['signed_data']) { - IConfig::Set($arr,'activitystreams','signed_data',$AS->data['signed_data'],false); + if ($AS->data['signed_data']) { + IConfig::Set($arr, 'activitystreams', 'signed_data', $AS->data['signed_data'], false); } - logger('FOF Activity received: ' . print_r($arr,true), LOGGER_DATA, LOG_DEBUG); + logger('FOF Activity received: ' . print_r($arr, true), LOGGER_DATA, LOG_DEBUG); logger('FOF Activity recipient: ' . $channel['channel_hash'], LOGGER_DATA, LOG_DEBUG); - $result = self::process_delivery($arr['owner_xchan'],$AS, $arr, [ $channel['channel_hash'] ],false,false,true); + $result = self::process_delivery($arr['owner_xchan'], $AS, $arr, [$channel['channel_hash']], false, false, true); if ($result) { $ret = array_merge($ret, $result); } @@ -1984,12 +1982,12 @@ class Libzot { */ static function remove_community_tag($sender, $arr, $uid) { - if(! (activity_match($arr['verb'], ACTIVITY_TAG) && ($arr['obj_type'] == ACTIVITY_OBJ_TAGTERM))) + if (!(activity_match($arr['verb'], ACTIVITY_TAG) && ($arr['obj_type'] == ACTIVITY_OBJ_TAGTERM))) return; logger('remove_community_tag: invoked'); - if(! get_pconfig($uid,'system','blocktags')) { + if (!get_pconfig($uid, 'system', 'blocktags')) { logger('Permission denied.'); return; } @@ -1998,24 +1996,24 @@ class Libzot { dbesc($arr['mid']), intval($uid) ); - if(! $r) { + if (!$r) { logger('No item'); return; } - if(($sender != $r[0]['owner_xchan']) && ($sender != $r[0]['author_xchan'])) { + if (($sender != $r[0]['owner_xchan']) && ($sender != $r[0]['author_xchan'])) { logger('Sender not authorised.'); return; } $i = $r[0]; - if($i['target']) - $i['target'] = json_decode($i['target'],true); - if($i['object']) - $i['object'] = json_decode($i['object'],true); + if ($i['target']) + $i['target'] = json_decode($i['target'], true); + if ($i['object']) + $i['object'] = json_decode($i['object'], true); - if(! ($i['target'] && $i['object'])) { + if (!($i['target'] && $i['object'])) { logger('No target/object'); return; } @@ -2026,7 +2024,7 @@ class Libzot { dbesc($message_id), intval($uid) ); - if(! $r) { + if (!$r) { logger('No parent message'); return; } @@ -2038,28 +2036,28 @@ class Libzot { intval(TERM_HASHTAG), intval(TERM_COMMUNITYTAG), dbesc($i['object']['title']), - dbesc(get_rel_link($i['object']['link'],'alternate')) + dbesc(get_rel_link($i['object']['link'], 'alternate')) ); } /** * @brief Updates an imported item. * - * @see item_store_update() - * * @param string $sender * @param array $item * @param array $orig * @param int $uid * @param boolean $tag_delivery * @return void|array + * @see item_store_update() + * */ static function update_imported_item($sender, $item, $orig, $uid, $tag_delivery) { // If this is a comment being updated, remove any privacy information // so that item_store_update will set it from the original. - if($item['mid'] !== $item['parent_mid']) { + if ($item['mid'] !== $item['parent_mid']) { unset($item['allow_cid']); unset($item['allow_gid']); unset($item['deny_cid']); @@ -2070,7 +2068,7 @@ class Libzot { // we need the tag_delivery check for downstream flowing posts as the stored post // may have a different owner than the one being transmitted. - if(($sender != $orig['owner_xchan'] && $sender != $orig['author_xchan']) && (! $tag_delivery)) { + if (($sender != $orig['owner_xchan'] && $sender != $orig['author_xchan']) && (!$tag_delivery)) { logger('sender is not owner or author'); return; } @@ -2081,13 +2079,13 @@ class Libzot { // If we're updating an event that we've saved locally, we store the item info first // because event_addtocal will parse the body to get the 'new' event details - if($orig['resource_type'] === 'event') { + if ($orig['resource_type'] === 'event') { $res = event_addtocal($orig['id'], $uid); - if(! $res) + if (!$res) logger('update event: failed'); } - if(! $x['item_id']) + if (!$x['item_id']) logger('update_imported_item: failed: ' . $x['message']); else logger('update_imported_item'); @@ -2111,8 +2109,8 @@ class Libzot { logger('invoked', LOGGER_DEBUG); $ownership_valid = false; - $item_found = false; - $post_id = 0; + $item_found = false; + $post_id = 0; if ($item['verb'] === 'Tombstone') { // The id of the deleted thing is the item mid (activity id) @@ -2131,17 +2129,17 @@ class Libzot { dbesc($sender), dbesc($sender), dbesc($mid), - dbesc(str_replace('/activity/','/item/',$mid)), + dbesc(str_replace('/activity/', '/item/', $mid)), intval($uid) ); - if($r) { + if ($r) { $stored = $r[0]; // we proved ownership in the sql query $ownership_valid = true; - $post_id = $stored['id']; + $post_id = $stored['id']; $item_found = true; } else { @@ -2149,7 +2147,7 @@ class Libzot { logger('delete received for non-existent item or not owned by sender - ignoring.'); } - if($ownership_valid === false) { + if ($ownership_valid === false) { logger('delete_imported_item: failed: ownership issue'); return false; } @@ -2173,10 +2171,10 @@ class Libzot { } } - if($item_found) { - if(intval($stored['item_deleted'])) { + if ($item_found) { + if (intval($stored['item_deleted'])) { logger('delete_imported_item: item was already deleted'); - if(! $relay) + if (!$relay) return false; // This is a bit hackish, but may have to suffice until the notification/delivery loop is optimised @@ -2207,22 +2205,22 @@ class Libzot { static function process_mail_delivery($sender, $arr, $deliveries) { - $result = array(); + $result = []; - if($sender != $arr['from_xchan']) { + if ($sender != $arr['from_xchan']) { logger('process_mail_delivery: sender is not mail author'); return; } - foreach($deliveries as $d) { + foreach ($deliveries as $d) { - $DR = new DReport(z_root(),$sender,$d,$arr['mid']); + $DR = new DReport(z_root(), $sender, $d, $arr['mid']); $r = q("select * from channel where channel_hash = '%s' limit 1", dbesc($d['hash']) ); - if(! $r) { + if (!$r) { $DR->update('recipient not found'); $result[] = $DR->get(); continue; @@ -2232,7 +2230,7 @@ class Libzot { $DR->set_name($channel['channel_name'] . ' <' . channel_reddress($channel) . '>'); - if(! perm_is_allowed($channel['channel_id'],$sender,'post_mail')) { + if (!perm_is_allowed($channel['channel_id'], $sender, 'post_mail')) { /* * Always allow somebody to reply if you initiated the conversation. It's anti-social @@ -2241,13 +2239,13 @@ class Libzot { */ $return = false; - if($arr['parent_mid']) { + if ($arr['parent_mid']) { $return = q("select * from mail where mid = '%s' and channel_id = %d limit 1", dbesc($arr['parent_mid']), intval($channel['channel_id']) ); } - if(! $return) { + if (!$return) { logger("permission denied for mail delivery {$channel['channel_id']}"); $DR->update('permission denied'); $result[] = $DR->get(); @@ -2260,8 +2258,8 @@ class Libzot { dbesc($arr['mid']), intval($channel['channel_id']) ); - if($r) { - if(intval($arr['mail_recalled'])) { + if ($r) { + if (intval($arr['mail_recalled'])) { $x = q("delete from mail where id = %d and channel_id = %d", intval($r[0]['id']), intval($channel['channel_id']) @@ -2280,7 +2278,7 @@ class Libzot { else { $arr['account_id'] = $channel['channel_account_id']; $arr['channel_id'] = $channel['channel_id']; - $item_id = mail_store($arr); + $item_id = mail_store($arr); $DR->update('mail delivered'); $result[] = $DR->get(); } @@ -2293,12 +2291,12 @@ class Libzot { /** * @brief Processes delivery of profile. * - * @see import_directory_profile() - * * @param string $sender * @param array $arr * @param array $deliveries (unused) * @return void + * @see import_directory_profile() + * */ static function process_profile_delivery($sender, $arr, $deliveries) { @@ -2307,7 +2305,7 @@ class Libzot { $r = q("select xchan_addr from xchan where xchan_hash = '%s' limit 1", dbesc($sender) ); - if($r) { + if ($r) { Libzotdir::import_directory_profile($sender, $arr, $r[0]['xchan_addr'], UPDATE_FLAGS_UPDATED, 0); } } @@ -2329,16 +2327,16 @@ class Libzot { $r = q("select * from xchan where xchan_hash = '%s' limit 1", dbesc($sender) ); - if($r) { - $xchan = [ 'id' => $r[0]['xchan_guid'], 'id_sig' => $r[0]['xchan_guid_sig'], - 'hash' => $r[0]['xchan_hash'], 'public_key' => $r[0]['xchan_pubkey'] ]; - } - if(array_key_exists('locations',$arr) && $arr['locations']) { - $x = Libsync::sync_locations($xchan,$arr,true); - logger('results: ' . print_r($x,true), LOGGER_DEBUG); - if($x['changed']) { + if ($r) { + $xchan = ['id' => $r[0]['xchan_guid'], 'id_sig' => $r[0]['xchan_guid_sig'], + 'hash' => $r[0]['xchan_hash'], 'public_key' => $r[0]['xchan_pubkey']]; + } + if (array_key_exists('locations', $arr) && $arr['locations']) { + $x = Libsync::sync_locations($xchan, $arr, true); + logger('results: ' . print_r($x, true), LOGGER_DEBUG); + if ($x['changed']) { //$guid = random_string() . '@' . App::get_hostname(); - Libzotdir::update_modtime($sender,$r[0]['xchan_guid'],$arr['locations'][0]['address'],UPDATE_FLAGS_UPDATED); + Libzotdir::update_modtime($sender, $r[0]['xchan_guid'], $arr['locations'][0]['address'], UPDATE_FLAGS_UPDATED); } } } @@ -2365,10 +2363,10 @@ class Libzot { */ static function check_location_move($sender_hash, $locations) { - if(! $locations) + if (!$locations) return; - if(count($locations) != 1) + if (count($locations) != 1) return; $loc = $locations[0]; @@ -2377,10 +2375,10 @@ class Libzot { dbesc($sender_hash) ); - if(! $r) + if (!$r) return; - if($loc['url'] !== z_root()) { + if ($loc['url'] !== z_root()) { $x = q("update channel set channel_moved = '%s' where channel_hash = '%s' limit 1", dbesc($loc['url']), dbesc($sender_hash) @@ -2390,7 +2388,7 @@ class Libzot { // of the move on singleton networks $arr = [ - 'channel' => $r[0], + 'channel' => $r[0], 'locations' => $locations ]; /** @@ -2407,23 +2405,23 @@ class Libzot { /** * @brief Returns an array with all known distinct hubs for this channel. * - * @see self::get_hublocs() * @param array $channel an associative array which must contain * * \e string \b channel_hash the hash of the channel * @return array an array with associative arrays + * @see self::get_hublocs() */ static function encode_locations($channel) { $ret = []; $x = self::get_hublocs($channel['channel_hash']); - if($x && count($x)) { - foreach($x as $hub) { + if ($x && count($x)) { + foreach ($x as $hub) { // if this is a local channel that has been deleted, the hubloc is no good - make sure it is marked deleted // so that nobody tries to use it. - if(intval($channel['channel_removed']) && $hub['hubloc_url'] === z_root()) + if (intval($channel['channel_removed']) && $hub['hubloc_url'] === z_root()) $hub['hubloc_deleted'] = 1; @@ -2442,15 +2440,15 @@ class Libzot { // version compatibility tweaks - if(! strpos($z['url_sig'],'.')) { + if (!strpos($z['url_sig'], '.')) { $z['url_sig'] = 'sha256.' . $z['url_sig']; } - if(! $z['id_url']) { - $z['id_url'] = $z['url'] . '/channel/' . substr($z['address'],0,strpos($z['address'],'@')); + if (!$z['id_url']) { + $z['id_url'] = $z['url'] . '/channel/' . substr($z['address'], 0, strpos($z['address'], '@')); } - if(! $z['site_id']) { - $z['site_id'] = Libzot::make_xchan_hash($z['url'],$z['sitekey']); + if (!$z['site_id']) { + $z['site_id'] = Libzot::make_xchan_hash($z['url'], $z['sitekey']); } $ret[] = $z; @@ -2469,10 +2467,10 @@ class Libzot { */ static function import_site($arr) { - if( (! is_array($arr)) || (! $arr['url']) || (! $arr['site_sig'])) + if ((!is_array($arr)) || (!$arr['url']) || (!$arr['site_sig'])) return false; - if(! self::verify($arr['url'], $arr['site_sig'], $arr['sitekey'])) { + if (!self::verify($arr['url'], $arr['site_sig'], $arr['sitekey'])) { logger('Bad url_sig'); return false; } @@ -2483,66 +2481,66 @@ class Libzot { $r = q("select * from site where site_url = '%s' limit 1", dbesc($arr['url']) ); - if($r) { - $exists = true; + if ($r) { + $exists = true; $siterecord = $r[0]; } $site_directory = 0; - if($arr['directory_mode'] == 'normal') + if ($arr['directory_mode'] == 'normal') $site_directory = DIRECTORY_MODE_NORMAL; - if($arr['directory_mode'] == 'primary') + if ($arr['directory_mode'] == 'primary') $site_directory = DIRECTORY_MODE_PRIMARY; - if($arr['directory_mode'] == 'secondary') + if ($arr['directory_mode'] == 'secondary') $site_directory = DIRECTORY_MODE_SECONDARY; - if($arr['directory_mode'] == 'standalone') + if ($arr['directory_mode'] == 'standalone') $site_directory = DIRECTORY_MODE_STANDALONE; $register_policy = 0; - if($arr['register_policy'] == 'closed') + if ($arr['register_policy'] == 'closed') $register_policy = REGISTER_CLOSED; - if($arr['register_policy'] == 'open') + if ($arr['register_policy'] == 'open') $register_policy = REGISTER_OPEN; - if($arr['register_policy'] == 'approve') + if ($arr['register_policy'] == 'approve') $register_policy = REGISTER_APPROVE; $access_policy = 0; - if(array_key_exists('access_policy',$arr)) { - if($arr['access_policy'] === 'private') + if (array_key_exists('access_policy', $arr)) { + if ($arr['access_policy'] === 'private') $access_policy = ACCESS_PRIVATE; - if($arr['access_policy'] === 'paid') + if ($arr['access_policy'] === 'paid') $access_policy = ACCESS_PAID; - if($arr['access_policy'] === 'free') + if ($arr['access_policy'] === 'free') $access_policy = ACCESS_FREE; - if($arr['access_policy'] === 'tiered') + if ($arr['access_policy'] === 'tiered') $access_policy = ACCESS_TIERED; } // don't let insecure sites register as public hubs - if(strpos($arr['url'],'https://') === false) + if (strpos($arr['url'], 'https://') === false) $access_policy = ACCESS_PRIVATE; - if($access_policy != ACCESS_PRIVATE) { + if ($access_policy != ACCESS_PRIVATE) { $x = z_fetch_url($arr['url'] . '/siteinfo.json'); - if(! $x['success']) + if (!$x['success']) $access_policy = ACCESS_PRIVATE; } - $directory_url = htmlspecialchars($arr['directory_url'],ENT_COMPAT,'UTF-8',false); - $url = htmlspecialchars(strtolower($arr['url']),ENT_COMPAT,'UTF-8',false); - $sellpage = htmlspecialchars($arr['sellpage'],ENT_COMPAT,'UTF-8',false); - $site_location = htmlspecialchars($arr['location'],ENT_COMPAT,'UTF-8',false); - $site_realm = htmlspecialchars($arr['realm'],ENT_COMPAT,'UTF-8',false); - $site_project = htmlspecialchars($arr['project'],ENT_COMPAT,'UTF-8',false); - $site_crypto = ((array_key_exists('encryption',$arr) && is_array($arr['encryption'])) ? htmlspecialchars(implode(',',$arr['encryption']),ENT_COMPAT,'UTF-8',false) : ''); - $site_version = ((array_key_exists('version',$arr)) ? htmlspecialchars($arr['version'],ENT_COMPAT,'UTF-8',false) : ''); + $directory_url = htmlspecialchars($arr['directory_url'], ENT_COMPAT, 'UTF-8', false); + $url = htmlspecialchars(strtolower($arr['url']), ENT_COMPAT, 'UTF-8', false); + $sellpage = htmlspecialchars($arr['sellpage'], ENT_COMPAT, 'UTF-8', false); + $site_location = htmlspecialchars($arr['location'], ENT_COMPAT, 'UTF-8', false); + $site_realm = htmlspecialchars($arr['realm'], ENT_COMPAT, 'UTF-8', false); + $site_project = htmlspecialchars($arr['project'], ENT_COMPAT, 'UTF-8', false); + $site_crypto = ((array_key_exists('encryption', $arr) && is_array($arr['encryption'])) ? htmlspecialchars(implode(',', $arr['encryption']), ENT_COMPAT, 'UTF-8', false) : ''); + $site_version = ((array_key_exists('version', $arr)) ? htmlspecialchars($arr['version'], ENT_COMPAT, 'UTF-8', false) : ''); // You can have one and only one primary directory per realm. // Downgrade any others claiming to be primary. As they have // flubbed up this badly already, don't let them be directory servers at all. - if(($site_directory === DIRECTORY_MODE_PRIMARY) + if (($site_directory === DIRECTORY_MODE_PRIMARY) && ($site_realm === get_directory_realm()) && ($arr['url'] != get_directory_primary())) { $site_directory = DIRECTORY_MODE_NORMAL; @@ -2550,12 +2548,12 @@ class Libzot { $site_flags = $site_directory; - if(array_key_exists('zot',$arr)) { - set_sconfig($arr['url'],'system','zot_version',$arr['zot']); + if (array_key_exists('zot', $arr)) { + set_sconfig($arr['url'], 'system', 'zot_version', $arr['zot']); } - if($exists) { - if(($siterecord['site_flags'] != $site_flags) + if ($exists) { + if (($siterecord['site_flags'] != $site_flags) || ($siterecord['site_access'] != $access_policy) || ($siterecord['site_directory'] != $directory_url) || ($siterecord['site_sellpage'] != $sellpage) @@ -2564,12 +2562,12 @@ class Libzot { || ($siterecord['site_project'] != $site_project) || ($siterecord['site_realm'] != $site_realm) || ($siterecord['site_crypto'] != $site_crypto) - || ($siterecord['site_version'] != $site_version) ) { + || ($siterecord['site_version'] != $site_version)) { $update = true; - // logger('import_site: input: ' . print_r($arr,true)); - // logger('import_site: stored: ' . print_r($siterecord,true)); + // logger('import_site: input: ' . print_r($arr,true)); + // logger('import_site: stored: ' . print_r($siterecord,true)); $r = q("update site set site_dead = 0, site_location = '%s', site_flags = %d, site_access = %d, site_directory = '%s', site_register = %d, site_update = '%s', site_sellpage = '%s', site_realm = '%s', site_type = %d, site_project = '%s', site_version = '%s', site_crypto = '%s' where site_url = '%s'", @@ -2587,8 +2585,8 @@ class Libzot { dbesc($site_crypto), dbesc($url) ); - if(! $r) { - logger('Update failed. ' . print_r($arr,true)); + if (!$r) { + logger('Update failed. ' . print_r($arr, true)); } } else { @@ -2620,8 +2618,8 @@ class Libzot { ] ); - if(! $r) { - logger('Record create failed. ' . print_r($arr,true)); + if (!$r) { + logger('Record create failed. ' . print_r($arr, true)); } } @@ -2631,14 +2629,14 @@ class Libzot { /** * @brief Returns path to /rpost * - * @todo We probably should make rpost discoverable. - * * @param array $observer * * \e string \b xchan_url * @return string + * @todo We probably should make rpost discoverable. + * */ static function get_rpost_path($observer) { - if(! $observer) + if (!$observer) return ''; $parsed = parse_url($observer['xchan_url']); @@ -2659,11 +2657,11 @@ class Libzot { // we may only end up with one; which results in posts with no author name or photo and are a bit // of a hassle to repair. If either or both are missing, do a full discovery probe. - if(! array_key_exists('id',$x)) { + if (!array_key_exists('id', $x)) { return import_author_activitypub($x); } - $hash = self::make_xchan_hash($x['id'],$x['key']); + $hash = self::make_xchan_hash($x['id'], $x['key']); $desturl = $x['url']; @@ -2680,18 +2678,18 @@ class Libzot { $site_dead = false; - if($r1 && intval($r1[0]['site_dead'])) { + if ($r1 && intval($r1[0]['site_dead'])) { $site_dead = true; } // We have valid and somewhat fresh information. Always true if it is our own site. - if($r1 && $r2 && ( $r1[0]['hubloc_updated'] > datetime_convert('UTC','UTC','now - 1 week') || $r1[0]['hubloc_url'] === z_root() ) ) { + if ($r1 && $r2 && ($r1[0]['hubloc_updated'] > datetime_convert('UTC', 'UTC', 'now - 1 week') || $r1[0]['hubloc_url'] === z_root())) { logger('in cache', LOGGER_DEBUG); return $hash; } - logger('not in cache or cache stale - probing: ' . print_r($x,true), LOGGER_DEBUG,LOG_INFO); + logger('not in cache or cache stale - probing: ' . print_r($x, true), LOGGER_DEBUG, LOG_INFO); // The primary hub may be dead. Try to find another one associated with this identity that is // still alive. If we find one, use that url for the discovery/refresh probe. Otherwise, the dead site @@ -2699,15 +2697,15 @@ class Libzot { // cached entry and the identity is valid. It's just unreachable until they bring back their // server from the grave or create another clone elsewhere. - if($site_dead) { - logger('dead site - ignoring', LOGGER_DEBUG,LOG_INFO); + if ($site_dead) { + logger('dead site - ignoring', LOGGER_DEBUG, LOG_INFO); $r = q("select hubloc_id_url from hubloc left join site on hubloc_url = site_url where hubloc_hash = '%s' and site_dead = 0", dbesc($hash) ); - if($r) { - logger('found another site that is not dead: ' . $r[0]['hubloc_url'], LOGGER_DEBUG,LOG_INFO); + if ($r) { + logger('found another site that is not dead: ' . $r[0]['hubloc_url'], LOGGER_DEBUG, LOG_INFO); $desturl = $r[0]['hubloc_url']; } else { @@ -2715,8 +2713,8 @@ class Libzot { } } - $them = [ 'hubloc_id_url' => $desturl ]; - if(self::refresh($them)) + $them = ['hubloc_id_url' => $desturl]; + if (self::refresh($them)) return $hash; return false; @@ -2724,27 +2722,27 @@ class Libzot { static function zotinfo($arr) { - logger('arr: ' . print_r($arr,true)); + logger('arr: ' . print_r($arr, true)); $ret = []; - $zhash = ((x($arr,'guid_hash')) ? $arr['guid_hash'] : ''); - $zguid = ((x($arr,'guid')) ? $arr['guid'] : ''); - $zguid_sig = ((x($arr,'guid_sig')) ? $arr['guid_sig'] : ''); - $zaddr = ((x($arr,'address')) ? $arr['address'] : ''); - $ztarget = ((x($arr,'target_url')) ? $arr['target_url'] : ''); - $zsig = ((x($arr,'target_sig')) ? $arr['target_sig'] : ''); - $zkey = ((x($arr,'key')) ? $arr['key'] : ''); - $mindate = ((x($arr,'mindate')) ? $arr['mindate'] : ''); - $token = ((x($arr,'token')) ? $arr['token'] : ''); - $feed = ((x($arr,'feed')) ? intval($arr['feed']) : 0); - - if($ztarget) { + $zhash = ((x($arr, 'guid_hash')) ? $arr['guid_hash'] : ''); + $zguid = ((x($arr, 'guid')) ? $arr['guid'] : ''); + $zguid_sig = ((x($arr, 'guid_sig')) ? $arr['guid_sig'] : ''); + $zaddr = ((x($arr, 'address')) ? $arr['address'] : ''); + $ztarget = ((x($arr, 'target_url')) ? $arr['target_url'] : ''); + $zsig = ((x($arr, 'target_sig')) ? $arr['target_sig'] : ''); + $zkey = ((x($arr, 'key')) ? $arr['key'] : ''); + $mindate = ((x($arr, 'mindate')) ? $arr['mindate'] : ''); + $token = ((x($arr, 'token')) ? $arr['token'] : ''); + $feed = ((x($arr, 'feed')) ? intval($arr['feed']) : 0); + + if ($ztarget) { $t = q("select * from hubloc where hubloc_id_url = '%s' and hubloc_network = 'zot6' limit 1", dbesc($ztarget) ); - if($t) { + if ($t) { $ztarget_hash = $t[0]['hubloc_hash']; @@ -2762,21 +2760,21 @@ class Libzot { $r = null; - if(strlen($zhash)) { + if (strlen($zhash)) { $r = q("select channel.*, xchan.* from channel left join xchan on channel_hash = xchan_hash where channel_hash = '%s' limit 1", dbesc($zhash) ); } - elseif(strlen($zguid) && strlen($zguid_sig)) { + elseif (strlen($zguid) && strlen($zguid_sig)) { $r = q("select channel.*, xchan.* from channel left join xchan on channel_hash = xchan_hash where channel_guid = '%s' and channel_guid_sig = '%s' limit 1", dbesc($zguid), dbesc($zguid_sig) ); } - elseif(strlen($zaddr)) { - if(strpos($zaddr,'[system]') === false) { /* normal address lookup */ + elseif (strlen($zaddr)) { + if (strpos($zaddr, '[system]') === false) { /* normal address lookup */ $r = q("select channel.*, xchan.* from channel left join xchan on channel_hash = xchan_hash where ( channel_address = '%s' or xchan_addr = '%s' ) limit 1", dbesc($zaddr), @@ -2799,7 +2797,7 @@ class Libzot { $r = q("select channel.*, xchan.* from channel left join xchan on channel_hash = xchan_hash where channel_system = 1 order by channel_id limit 1"); - if(! $r) { + if (!$r) { $r = q("select channel.*, xchan.* from channel left join xchan on channel_hash = xchan_hash where channel_removed = 0 order by channel_id limit 1"); } @@ -2807,45 +2805,45 @@ class Libzot { } else { $ret['message'] = 'Invalid request'; - return($ret); + return ($ret); } - if(! $r) { + if (!$r) { $ret['message'] = 'Item not found.'; - return($ret); + return ($ret); } $e = $r[0]; $id = $e['channel_id']; - $sys_channel = (intval($e['channel_system']) ? true : false); - $special_channel = (($e['channel_pageflags'] & PAGE_PREMIUM) ? true : false); - $adult_channel = (($e['channel_pageflags'] & PAGE_ADULT) ? true : false); + $sys_channel = (intval($e['channel_system']) ? true : false); + $special_channel = (($e['channel_pageflags'] & PAGE_PREMIUM) ? true : false); + $adult_channel = (($e['channel_pageflags'] & PAGE_ADULT) ? true : false); $censored = (($e['channel_pageflags'] & PAGE_CENSORED) ? true : false); - $searchable = (($e['channel_pageflags'] & PAGE_HIDDEN) ? false : true); + $searchable = (($e['channel_pageflags'] & PAGE_HIDDEN) ? false : true); $deleted = (intval($e['xchan_deleted']) ? true : false); - if($deleted || $censored || $sys_channel) + if ($deleted || $censored || $sys_channel) $searchable = false; $public_forum = false; - $role = get_pconfig($e['channel_id'],'system','permissions_role'); - if($role === 'forum' || $role === 'repository') { + $role = get_pconfig($e['channel_id'], 'system', 'permissions_role'); + if ($role === 'forum' || $role === 'repository') { $public_forum = true; } else { // check if it has characteristics of a public forum based on custom permissions. $m = Permissions::FilledAutoperms($e['channel_id']); - if($m) { - foreach($m as $k => $v) { - if($k == 'tag_deliver' && intval($v) == 1) - $ch ++; - if($k == 'send_stream' && intval($v) == 0) - $ch ++; - } - if($ch == 2) + if ($m) { + foreach ($m as $k => $v) { + if ($k == 'tag_deliver' && intval($v) == 1) + $ch++; + if ($k == 'send_stream' && intval($v) == 0) + $ch++; + } + if ($ch == 2) $public_forum = true; } } @@ -2856,128 +2854,128 @@ class Libzot { intval($e['channel_id']) ); - $profile = array(); + $profile = []; - if($p) { + if ($p) { - if(! intval($p[0]['publish'])) + if (!intval($p[0]['publish'])) $searchable = false; - $profile['description'] = $p[0]['pdesc']; - $profile['birthday'] = $p[0]['dob']; - if(($profile['birthday'] != '0000-00-00') && (($bd = z_birthday($p[0]['dob'],'UTC')) !== '')) + $profile['description'] = $p[0]['pdesc']; + $profile['birthday'] = $p[0]['dob']; + if (($profile['birthday'] != '0000-00-00') && (($bd = z_birthday($p[0]['dob'], 'UTC')) !== '')) $profile['next_birthday'] = $bd; - if($age = age($p[0]['dob'],$e['channel_timezone'],'')) + if ($age = age($p[0]['dob'], $e['channel_timezone'], '')) $profile['age'] = $age; - $profile['gender'] = $p[0]['gender']; - $profile['marital'] = $p[0]['marital']; - $profile['sexual'] = $p[0]['sexual']; - $profile['locale'] = $p[0]['locality']; - $profile['region'] = $p[0]['region']; - $profile['postcode'] = $p[0]['postal_code']; - $profile['country'] = $p[0]['country_name']; - $profile['about'] = $p[0]['about']; - $profile['homepage'] = $p[0]['homepage']; - $profile['hometown'] = $p[0]['hometown']; - - if($p[0]['keywords']) { - $tags = array(); - $k = explode(' ',$p[0]['keywords']); - if($k) { - foreach($k as $kk) { - if(trim($kk," \t\n\r\0\x0B,")) { - $tags[] = trim($kk," \t\n\r\0\x0B,"); + $profile['gender'] = $p[0]['gender']; + $profile['marital'] = $p[0]['marital']; + $profile['sexual'] = $p[0]['sexual']; + $profile['locale'] = $p[0]['locality']; + $profile['region'] = $p[0]['region']; + $profile['postcode'] = $p[0]['postal_code']; + $profile['country'] = $p[0]['country_name']; + $profile['about'] = $p[0]['about']; + $profile['homepage'] = $p[0]['homepage']; + $profile['hometown'] = $p[0]['hometown']; + + if ($p[0]['keywords']) { + $tags = []; + $k = explode(' ', $p[0]['keywords']); + if ($k) { + foreach ($k as $kk) { + if (trim($kk, " \t\n\r\0\x0B,")) { + $tags[] = trim($kk, " \t\n\r\0\x0B,"); } } } - if($tags) + if ($tags) $profile['keywords'] = $tags; } } // Communication details - $ret['id'] = $e['xchan_guid']; - $ret['id_sig'] = self::sign($e['xchan_guid'], $e['channel_prvkey']); + $ret['id'] = $e['xchan_guid']; + $ret['id_sig'] = self::sign($e['xchan_guid'], $e['channel_prvkey']); $ret['primary_location'] = [ - 'address' => $e['xchan_addr'], - 'url' => $e['xchan_url'], - 'connections_url' => $e['xchan_connurl'], - 'follow_url' => $e['xchan_follow'], + 'address' => $e['xchan_addr'], + 'url' => $e['xchan_url'], + 'connections_url' => $e['xchan_connurl'], + 'follow_url' => $e['xchan_follow'], ]; - $ret['public_key'] = $e['xchan_pubkey']; - $ret['username'] = $e['channel_address']; - $ret['name'] = $e['xchan_name']; - $ret['name_updated'] = $e['xchan_name_date']; - $ret['photo'] = [ + $ret['public_key'] = $e['xchan_pubkey']; + $ret['username'] = $e['channel_address']; + $ret['name'] = $e['xchan_name']; + $ret['name_updated'] = $e['xchan_name_date']; + $ret['photo'] = [ 'url' => $e['xchan_photo_l'], 'type' => $e['xchan_photo_mimetype'], 'updated' => $e['xchan_photo_date'] ]; - $ret['channel_role'] = get_pconfig($e['channel_id'],'system','permissions_role','custom'); - $ret['protocols'] = [ 'zot6', 'zot' ]; - $ret['searchable'] = $searchable; - $ret['adult_content'] = $adult_channel; - $ret['public_forum'] = $public_forum; + $ret['channel_role'] = get_pconfig($e['channel_id'], 'system', 'permissions_role', 'custom'); + $ret['protocols'] = ['zot6', 'zot']; + $ret['searchable'] = $searchable; + $ret['adult_content'] = $adult_channel; + $ret['public_forum'] = $public_forum; - $ret['comments'] = map_scope(PermissionLimits::Get($e['channel_id'],'post_comments')); - $ret['mail'] = map_scope(PermissionLimits::Get($e['channel_id'],'post_mail')); + $ret['comments'] = map_scope(PermissionLimits::Get($e['channel_id'], 'post_comments')); + $ret['mail'] = map_scope(PermissionLimits::Get($e['channel_id'], 'post_mail')); - if($deleted) - $ret['deleted'] = $deleted; + if ($deleted) + $ret['deleted'] = $deleted; - if(intval($e['channel_removed'])) + if (intval($e['channel_removed'])) $ret['deleted_locally'] = true; // premium or other channel desiring some contact with potential followers before connecting. // This is a template - %s will be replaced with the follow_url we discover for the return channel. - if($special_channel) { + if ($special_channel) { $ret['connect_url'] = (($e['xchan_connpage']) ? $e['xchan_connpage'] : z_root() . '/connect/' . $e['channel_address']); } // This is a template for our follow url, %s will be replaced with a webbie - if(! $ret['follow_url']) + if (!$ret['follow_url']) $ret['follow_url'] = z_root() . '/follow?f=&url=%s'; - $permissions = get_all_perms($e['channel_id'],$ztarget_hash,false,false); + $permissions = get_all_perms($e['channel_id'], $ztarget_hash, false, false); - if($ztarget_hash) { + if ($ztarget_hash) { $permissions['connected'] = false; - $b = q("select * from abook where abook_xchan = '%s' and abook_channel = %d limit 1", + $b = q("select * from abook where abook_xchan = '%s' and abook_channel = %d limit 1", dbesc($ztarget_hash), intval($e['channel_id']) ); - if($b) + if ($b) $permissions['connected'] = true; } - if($permissions['view_profile']) - $ret['profile'] = $profile; + if ($permissions['view_profile']) + $ret['profile'] = $profile; $concise_perms = []; - if($permissions) { - foreach($permissions as $k => $v) { - if($v) { + if ($permissions) { + foreach ($permissions as $k => $v) { + if ($v) { $concise_perms[] = $k; } } - $permissions = implode(',',$concise_perms); + $permissions = implode(',', $concise_perms); } - $ret['permissions'] = $permissions; - $ret['permissions_for'] = $ztarget; + $ret['permissions'] = $permissions; + $ret['permissions_for'] = $ztarget; // array of (verified) hubs this channel uses $x = self::encode_locations($e); - if($x) + if ($x) $ret['locations'] = $x; $ret['site'] = self::site_info(); @@ -2997,58 +2995,58 @@ class Libzot { */ static function site_info() { - $signing_key = get_config('system','prvkey'); - $sig_method = get_config('system','signature_algorithm','sha256'); + $signing_key = get_config('system', 'prvkey'); + $sig_method = get_config('system', 'signature_algorithm', 'sha256'); - $ret = []; - $ret['site'] = []; - $ret['site']['url'] = z_root(); - $ret['site']['site_sig'] = self::sign(z_root(), $signing_key); - $ret['site']['post'] = z_root() . '/zot'; + $ret = []; + $ret['site'] = []; + $ret['site']['url'] = z_root(); + $ret['site']['site_sig'] = self::sign(z_root(), $signing_key); + $ret['site']['post'] = z_root() . '/zot'; $ret['site']['openWebAuth'] = z_root() . '/owa'; $ret['site']['authRedirect'] = z_root() . '/magic'; - $ret['site']['sitekey'] = get_config('system','pubkey'); + $ret['site']['sitekey'] = get_config('system', 'pubkey'); - $dirmode = get_config('system','directory_mode'); - if(($dirmode === false) || ($dirmode == DIRECTORY_MODE_NORMAL)) + $dirmode = get_config('system', 'directory_mode'); + if (($dirmode === false) || ($dirmode == DIRECTORY_MODE_NORMAL)) $ret['site']['directory_mode'] = 'normal'; - if($dirmode == DIRECTORY_MODE_PRIMARY) + if ($dirmode == DIRECTORY_MODE_PRIMARY) $ret['site']['directory_mode'] = 'primary'; - elseif($dirmode == DIRECTORY_MODE_SECONDARY) + elseif ($dirmode == DIRECTORY_MODE_SECONDARY) $ret['site']['directory_mode'] = 'secondary'; - elseif($dirmode == DIRECTORY_MODE_STANDALONE) + elseif ($dirmode == DIRECTORY_MODE_STANDALONE) $ret['site']['directory_mode'] = 'standalone'; - if($dirmode != DIRECTORY_MODE_NORMAL) + if ($dirmode != DIRECTORY_MODE_NORMAL) $ret['site']['directory_url'] = z_root() . '/dirsearch'; $ret['site']['encryption'] = crypto_methods(); - $ret['site']['zot'] = System::get_zot_revision(); + $ret['site']['zot'] = System::get_zot_revision(); // hide detailed site information if you're off the grid - if($dirmode != DIRECTORY_MODE_STANDALONE) { + if ($dirmode != DIRECTORY_MODE_STANDALONE) { - $register_policy = intval(get_config('system','register_policy')); + $register_policy = intval(get_config('system', 'register_policy')); - if($register_policy == REGISTER_CLOSED) + if ($register_policy == REGISTER_CLOSED) $ret['site']['register_policy'] = 'closed'; - if($register_policy == REGISTER_APPROVE) + if ($register_policy == REGISTER_APPROVE) $ret['site']['register_policy'] = 'approve'; - if($register_policy == REGISTER_OPEN) + if ($register_policy == REGISTER_OPEN) $ret['site']['register_policy'] = 'open'; - $access_policy = intval(get_config('system','access_policy')); + $access_policy = intval(get_config('system', 'access_policy')); - if($access_policy == ACCESS_PRIVATE) + if ($access_policy == ACCESS_PRIVATE) $ret['site']['access_policy'] = 'private'; - if($access_policy == ACCESS_PAID) + if ($access_policy == ACCESS_PAID) $ret['site']['access_policy'] = 'paid'; - if($access_policy == ACCESS_FREE) + if ($access_policy == ACCESS_FREE) $ret['site']['access_policy'] = 'free'; - if($access_policy == ACCESS_TIERED) + if ($access_policy == ACCESS_TIERED) $ret['site']['access_policy'] = 'tiered'; $ret['site']['accounts'] = account_total(); @@ -3056,24 +3054,24 @@ class Libzot { require_once('include/channel.php'); $ret['site']['channels'] = channel_total(); - $ret['site']['admin'] = get_config('system','admin_email'); + $ret['site']['admin'] = get_config('system', 'admin_email'); - $visible_plugins = array(); - if(is_array(\App::$plugins) && count(\App::$plugins)) { + $visible_plugins = []; + if (is_array(\App::$plugins) && count(\App::$plugins)) { $r = q("select * from addon where hidden = 0"); - if($r) - foreach($r as $rr) + if ($r) + foreach ($r as $rr) $visible_plugins[] = $rr['aname']; } - $ret['site']['plugins'] = $visible_plugins; - $ret['site']['sitehash'] = get_config('system','location_hash'); - $ret['site']['sitename'] = get_config('system','sitename'); - $ret['site']['sellpage'] = get_config('system','sellpage'); - $ret['site']['location'] = get_config('system','site_location'); - $ret['site']['realm'] = get_directory_realm(); - $ret['site']['project'] = System::get_platform_name(); - $ret['site']['version'] = System::get_project_version(); + $ret['site']['plugins'] = $visible_plugins; + $ret['site']['sitehash'] = get_config('system', 'location_hash'); + $ret['site']['sitename'] = get_config('system', 'sitename'); + $ret['site']['sellpage'] = get_config('system', 'sellpage'); + $ret['site']['location'] = get_config('system', 'site_location'); + $ret['site']['realm'] = get_directory_realm(); + $ret['site']['project'] = System::get_platform_name(); + $ret['site']['version'] = System::get_project_version(); } @@ -3154,36 +3152,36 @@ class Libzot { * @param string $alg (optional) default 'sha256' * @return string */ - static function sign($data,$key,$alg = 'sha256') { - if(! $key) + static function sign($data, $key, $alg = 'sha256') { + if (!$key) return 'no key'; $sig = ''; - openssl_sign($data,$sig,$key,$alg); + openssl_sign($data, $sig, $key, $alg); return $alg . '.' . base64url_encode($sig); } - static function verify($data,$sig,$key) { + static function verify($data, $sig, $key) { $verify = 0; - $x = explode('.',$sig,2); + $x = explode('.', $sig, 2); if ($key && count($x) === 2) { - $alg = $x[0]; + $alg = $x[0]; $signature = base64url_decode($x[1]); - $verify = @openssl_verify($data,$signature,$key,$alg); + $verify = @openssl_verify($data, $signature, $key, $alg); if ($verify === (-1)) { while ($msg = openssl_error_string()) { - logger('openssl_verify: ' . $msg,LOGGER_NORMAL,LOG_ERR); + logger('openssl_verify: ' . $msg, LOGGER_NORMAL, LOG_ERR); } btlogger('openssl_verify: key: ' . $key, LOGGER_DEBUG, LOG_ERR); } } - return(($verify > 0) ? true : false); + return (($verify > 0) ? true : false); } /** @@ -3192,25 +3190,25 @@ class Libzot { * @return boolean */ static function is_zot_request() { - $x = getBestSupportedMimeType([ 'application/x-zot+json' ]); + $x = getBestSupportedMimeType(['application/x-zot+json']); - return(($x) ? true : false); + return (($x) ? true : false); } static public function zot_record_preferred($arr, $check = 'hubloc_network') { - if(! $arr) { + if (!$arr) { return $arr; } - foreach($arr as $v) { - if($v[$check] === 'zot6') { + foreach ($arr as $v) { + if ($v[$check] === 'zot6') { return $v; } } - foreach($arr as $v) { - if($v[$check] === 'zot') { + foreach ($arr as $v) { + if ($v[$check] === 'zot') { return $v; } } diff --git a/Zotlabs/Lib/ZotURL.php b/Zotlabs/Lib/ZotURL.php index 98d1febe5..fa3959f69 100644 --- a/Zotlabs/Lib/ZotURL.php +++ b/Zotlabs/Lib/ZotURL.php @@ -23,9 +23,10 @@ class ZotURL { $portable_url = substr($url,6); $u = explode('/',$portable_url); $portable_id = $u[0]; + hz_syslog(print_r($u,true)); $hosts = self::lookup($portable_id); - + hz_syslog(print_r($hosts,true)); if(! $hosts) { return $ret; } diff --git a/Zotlabs/Module/Zotfeed.php b/Zotlabs/Module/Zotfeed.php index 8c13682b4..6f4cd9fc4 100644 --- a/Zotlabs/Module/Zotfeed.php +++ b/Zotlabs/Module/Zotfeed.php @@ -1,29 +1,127 @@ <?php -namespace Zotlabs\Module; -require_once('include/items.php'); -require_once('include/zot.php'); +namespace Zotlabs\Module; +use App; +use Zotlabs\Lib\Activity; +use Zotlabs\Lib\ActivityStreams; +use Zotlabs\Lib\Config; +use Zotlabs\Web\Controller; +use Zotlabs\Web\HTTPSig; -class Zotfeed extends \Zotlabs\Web\Controller { +class Zotfeed extends Controller { function init() { - + + if (ActivityStreams::is_as_request()) { + + if (observer_prohibited(true)) { + killme(); + } + + if (argc() < 2) { + killme(); + } + + $channel = channelx_by_nick(argv(1)); + if (!$channel) { + killme(); + } + + if (intval($channel['channel_system'])) { + killme(); + } + + $sigdata = HTTPSig::verify(($_SERVER['REQUEST_METHOD'] === 'POST') ? file_get_contents('php://input') : EMPTY_STR); + if ($sigdata['portable_id'] && $sigdata['header_valid']) { + $portable_id = $sigdata['portable_id']; + if (!check_channelallowed($portable_id)) { + http_status_exit(403, 'Permission denied'); + } + if (!check_siteallowed($sigdata['signer'])) { + http_status_exit(403, 'Permission denied'); + } + observer_auth($portable_id); + } + elseif (Config::get('system', 'require_authenticated_fetch', false)) { + http_status_exit(403, 'Permission denied'); + } + + $observer_hash = get_observer_hash(); + + $params = []; + + $params['begin'] = ((x($_REQUEST, 'date_begin')) ? $_REQUEST['date_begin'] : NULL_DATE); + $params['end'] = ((x($_REQUEST, 'date_end')) ? $_REQUEST['date_end'] : ''); + $params['type'] = 'json'; + $params['pages'] = ((x($_REQUEST, 'pages')) ? intval($_REQUEST['pages']) : 0); + $params['top'] = ((x($_REQUEST, 'top')) ? intval($_REQUEST['top']) : 0); + $params['direction'] = ((x($_REQUEST, 'direction')) ? dbesc($_REQUEST['direction']) : 'desc'); // unimplemented + $params['cat'] = ((x($_REQUEST, 'cat')) ? escape_tags($_REQUEST['cat']) : ''); + $params['compat'] = 1; + + $total = items_fetch( + [ + 'total' => true, + 'wall' => '1', + 'datequery' => $params['end'], + 'datequery2' => $params['begin'], + 'direction' => dbesc($params['direction']), + 'pages' => $params['pages'], + 'order' => dbesc('post'), + 'top' => $params['top'], + 'cat' => $params['cat'], + 'compat' => $params['compat'] + ], $channel, $observer_hash, CLIENT_MODE_NORMAL, App::$module + ); + + if ($total) { + App::set_pager_total($total); + App::set_pager_itemspage(100); + } + + if (App::$pager['unset'] && $total > 100) { + $ret = Activity::paged_collection_init($total, App::$query_string); + } + else { + $items = items_fetch( + [ + 'wall' => '1', + 'datequery' => $params['end'], + 'datequery2' => $params['begin'], + 'records' => intval(App::$pager['itemspage']), + 'start' => intval(App::$pager['start']), + 'direction' => dbesc($params['direction']), + 'pages' => $params['pages'], + 'order' => dbesc('post'), + 'top' => $params['top'], + 'cat' => $params['cat'], + 'compat' => $params['compat'] + ], $channel, $observer_hash, CLIENT_MODE_NORMAL, App::$module + ); + + $ret = Activity::encode_item_collection($items, App::$query_string, 'OrderedCollection', $total); + } + + as_return_and_die($ret, $channel); + } + + /* $result = array('success' => false); - + $mindate = (($_REQUEST['mindate']) ? datetime_convert('UTC','UTC',$_REQUEST['mindate']) : ''); if(! $mindate) $mindate = datetime_convert('UTC','UTC', 'now - 14 days'); - + if(observer_prohibited()) { $result['message'] = 'Public access denied'; json_return_and_die($result); } - - $observer = \App::get_observer(); - + + $observer = App::get_observer(); + logger('observer: ' . get_observer_hash(), LOGGER_DEBUG); - + $channel_address = ((argc() > 1) ? argv(1) : ''); if($channel_address) { $r = q("select channel_id, channel_name from channel where channel_address = '%s' and channel_removed = 0 limit 1", @@ -40,12 +138,12 @@ class Zotfeed extends \Zotlabs\Web\Controller { $result['message'] = 'Channel not found.'; json_return_and_die($result); } - + logger('zotfeed request: ' . $r[0]['channel_name'], LOGGER_DEBUG); - $result['project'] = 'Hubzilla'; + $result['project'] = 'Hubzilla'; $result['messages'] = zot_feed($r[0]['channel_id'],$observer['xchan_hash'],array('mindate' => $mindate)); $result['success'] = true; json_return_and_die($result); + */ } - } diff --git a/include/items.php b/include/items.php index bfca354d1..5b9bbd1f9 100755 --- a/include/items.php +++ b/include/items.php @@ -4562,9 +4562,11 @@ function items_fetch($arr,$channel = null,$observer_hash = null,$client_mode = C // only setup pagination on initial page view $pager_sql = ''; } else { - $itemspage = (($channel) ? get_pconfig($uid,'system','itemspage') : 10); - App::set_pager_itemspage(((intval($itemspage)) ? $itemspage : 10)); - $pager_sql = sprintf(" LIMIT %d OFFSET %d ", intval(App::$pager['itemspage']), intval(App::$pager['start'])); + if(! $arr['total']) { + $itemspage = (($channel) ? get_pconfig($uid,'system','itemspage') : 20); + App::set_pager_itemspage(((intval($itemspage)) ? $itemspage : 20)); + $pager_sql = sprintf(" LIMIT %d OFFSET %d ", intval(App::$pager['itemspage']), intval(App::$pager['start'])); + } } if (isset($arr['start']) && isset($arr['records'])) @@ -4613,6 +4615,18 @@ function items_fetch($arr,$channel = null,$observer_hash = null,$client_mode = C // "New Item View" - show all items unthreaded in reverse created date order + if ($arr['total']) { + $items = q("SELECT count(item.id) AS total FROM item + WHERE $item_uids $item_restrict + $simple_update + $sql_extra $sql_nets $sql_extra3" + ); + if ($items) { + return intval($items[0]['total']); + } + return 0; + } + $items = q("SELECT item.*, item.id AS item_id FROM item WHERE $item_uids $item_restrict $simple_update diff --git a/include/network.php b/include/network.php index 324a99eba..f5ff48fce 100644 --- a/include/network.php +++ b/include/network.php @@ -1,8 +1,10 @@ <?php +use Zotlabs\Lib\LDSignatures; use Zotlabs\Lib\Zotfinger; use Zotlabs\Lib\Libzot; use Zotlabs\Lib\Queue; +use Zotlabs\Web\HTTPSig; /** * @file include/network.php @@ -404,6 +406,31 @@ function json_return_and_die($x, $content_type = 'application/json') { killme(); } +function as_return_and_die($obj,$channel) { + + $x = array_merge(['@context' => [ + ACTIVITYSTREAMS_JSONLD_REV, + 'https://w3id.org/security/v1', + z_root() . ZOT_APSCHEMA_REV + ]], $obj ); + + $headers = []; + $headers['Content-Type'] = 'application/ld+json; profile="https://www.w3.org/ns/activitystreams"' ; + $x['signature'] = LDSignatures::sign($x,$channel); + $ret = json_encode($x, JSON_UNESCAPED_SLASHES); + logger('data: ' . jindent($ret), LOGGER_DATA); + $headers['Date'] = datetime_convert('UTC','UTC', 'now', 'D, d M Y H:i:s \\G\\M\\T'); + $headers['Digest'] = HTTPSig::generate_digest_header($ret); + $headers['(request-target)'] = strtolower($_SERVER['REQUEST_METHOD']) . ' ' . $_SERVER['REQUEST_URI']; + + $h = HTTPSig::create_sig($headers,$channel['channel_prvkey'],channel_url($channel)); + HTTPSig::set_headers($h); + + echo $ret; + killme(); + +} + /** * @brief Send HTTP status header. * @@ -1978,7 +2005,7 @@ function getBestSupportedMimeType($mimeTypes = null, $acceptedTypes = false) { // check if there is a different quality if (strpos($a, ';q=')) { // divide "mime/type;q=X" into two parts: "mime/type" i "X" - list($a, $q) = explode(';q=', $a); + [$a, $q] = explode(';q=', $a); } // mime-type $a is accepted with the quality $q // WARNING: $q == 0 means, that mime-type isn’t supported! |