]> git.mxchange.org Git - friendica.git/blob - src/Model/Item.php
Merge pull request #12243 from annando/remote-self
[friendica.git] / src / Model / Item.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2010-2022, the Friendica project
4  *
5  * @license GNU AGPL version 3 or any later version
6  *
7  * This program is free software: you can redistribute it and/or modify
8  * it under the terms of the GNU Affero General Public License as
9  * published by the Free Software Foundation, either version 3 of the
10  * License, or (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU Affero General Public License for more details.
16  *
17  * You should have received a copy of the GNU Affero General Public License
18  * along with this program.  If not, see <https://www.gnu.org/licenses/>.
19  *
20  */
21
22 namespace Friendica\Model;
23
24 use Friendica\Content\Text\BBCode;
25 use Friendica\Content\Text\HTML;
26 use Friendica\Core\Hook;
27 use Friendica\Core\Logger;
28 use Friendica\Core\Protocol;
29 use Friendica\Core\Renderer;
30 use Friendica\Core\System;
31 use Friendica\Model\Tag;
32 use Friendica\Core\Worker;
33 use Friendica\Database\DBA;
34 use Friendica\DI;
35 use Friendica\Protocol\Activity;
36 use Friendica\Protocol\ActivityPub;
37 use Friendica\Protocol\Diaspora;
38 use Friendica\Util\DateTimeFormat;
39 use Friendica\Util\Map;
40 use Friendica\Util\Network;
41 use Friendica\Util\Proxy;
42 use Friendica\Util\Strings;
43 use Friendica\Util\Temporal;
44 use Friendica\Worker\Delivery;
45 use GuzzleHttp\Psr7\Uri;
46 use LanguageDetection\Language;
47
48 class Item
49 {
50         // Posting types, inspired by https://www.w3.org/TR/activitystreams-vocabulary/#object-types
51         const PT_ARTICLE = 0;
52         const PT_NOTE = 1;
53         const PT_PAGE = 2;
54         const PT_IMAGE = 16;
55         const PT_AUDIO = 17;
56         const PT_VIDEO = 18;
57         const PT_DOCUMENT = 19;
58         const PT_EVENT = 32;
59         const PT_POLL = 33;
60         const PT_PERSONAL_NOTE = 128;
61
62         // Posting reasons (Why had a post been stored for a user?)
63         const PR_NONE = 0;
64         const PR_TAG = 64;
65         const PR_TO = 65;
66         const PR_CC = 66;
67         const PR_BTO = 67;
68         const PR_BCC = 68;
69         const PR_FOLLOWER = 69;
70         const PR_ANNOUNCEMENT = 70;
71         const PR_COMMENT = 71;
72         const PR_STORED = 72;
73         const PR_GLOBAL = 73;
74         const PR_RELAY = 74;
75         const PR_FETCHED = 75;
76         const PR_COMPLETION = 76;
77         const PR_DIRECT = 77;
78         const PR_ACTIVITY = 78;
79         const PR_DISTRIBUTE = 79;
80         const PR_PUSHED = 80;
81         const PR_LOCAL = 81;
82
83         // system.accept_only_sharer setting values
84         const COMPLETION_NONE    = 1;
85         const COMPLETION_COMMENT = 0;
86         const COMPLETION_LIKE    = 2;
87
88         // Field list that is used to display the items
89         const DISPLAY_FIELDLIST = [
90                 'uid', 'id', 'parent', 'guid', 'network', 'gravity',
91                 'uri-id', 'uri', 'thr-parent-id', 'thr-parent', 'parent-uri-id', 'parent-uri', 'conversation',
92                 'commented', 'created', 'edited', 'received', 'verb', 'object-type', 'postopts', 'plink',
93                 'wall', 'private', 'starred', 'origin', 'parent-origin', 'title', 'body', 'language',
94                 'content-warning', 'location', 'coord', 'app', 'rendered-hash', 'rendered-html', 'object',
95                 'quote-uri', 'quote-uri-id', 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid', 'mention', 'global',
96                 'author-id', 'author-link', 'author-name', 'author-avatar', 'author-network', 'author-updated', 'author-gsid', 'author-addr', 'author-uri-id',
97                 'owner-id', 'owner-link', 'owner-name', 'owner-avatar', 'owner-network', 'owner-contact-type', 'owner-updated',
98                 'causer-id', 'causer-link', 'causer-name', 'causer-avatar', 'causer-contact-type', 'causer-network',
99                 'contact-id', 'contact-uid', 'contact-link', 'contact-name', 'contact-avatar',
100                 'writable', 'self', 'cid', 'alias',
101                 'event-created', 'event-edited', 'event-start', 'event-finish',
102                 'event-summary', 'event-desc', 'event-location', 'event-type',
103                 'event-nofinish', 'event-ignore', 'event-id',
104                 'question-id', 'question-multiple', 'question-voters', 'question-end-time',
105                 'has-categories', 'has-media',
106                 'delivery_queue_count', 'delivery_queue_done', 'delivery_queue_failed'
107         ];
108
109         // Field list that is used to deliver items via the protocols
110         const DELIVER_FIELDLIST = ['uid', 'id', 'parent', 'uri-id', 'uri', 'thr-parent', 'parent-uri', 'guid',
111                         'parent-guid', 'conversation', 'received', 'created', 'edited', 'verb', 'object-type', 'object', 'target',
112                         'private', 'title', 'body', 'raw-body', 'location', 'coord', 'app',
113                         'inform', 'deleted', 'extid', 'post-type', 'post-reason', 'gravity',
114                         'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid',
115                         'author-id', 'author-addr', 'author-link', 'author-name', 'author-avatar', 'owner-id', 'owner-link', 'contact-uid',
116                         'signed_text', 'network', 'wall', 'contact-id', 'plink', 'origin',
117                         'thr-parent-id', 'parent-uri-id', 'quote-uri', 'quote-uri-id', 'postopts', 'pubmail',
118                         'event-created', 'event-edited', 'event-start', 'event-finish',
119                         'event-summary', 'event-desc', 'event-location', 'event-type',
120                         'event-nofinish', 'event-ignore', 'event-id'];
121
122         // All fields in the item table
123         const ITEM_FIELDLIST = ['id', 'uid', 'parent', 'uri', 'parent-uri', 'thr-parent',
124                         'guid', 'uri-id', 'parent-uri-id', 'thr-parent-id', 'conversation', 'vid',
125                         'quote-uri', 'quote-uri-id', 'contact-id', 'wall', 'gravity', 'extid', 'psid',
126                         'created', 'edited', 'commented', 'received', 'changed', 'verb',
127                         'postopts', 'plink', 'resource-id', 'event-id', 'inform',
128                         'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid', 'post-type', 'post-reason',
129                         'private', 'pubmail', 'visible', 'starred',
130                         'unseen', 'deleted', 'origin', 'mention', 'global', 'network',
131                         'title', 'content-warning', 'body', 'location', 'coord', 'app',
132                         'rendered-hash', 'rendered-html', 'object-type', 'object', 'target-type', 'target',
133                         'author-id', 'author-link', 'author-name', 'author-avatar', 'author-network',
134                         'owner-id', 'owner-link', 'owner-name', 'owner-avatar', 'causer-id'];
135
136         // List of all verbs that don't need additional content data.
137         // Never reorder or remove entries from this list. Just add new ones at the end, if needed.
138         const ACTIVITIES = [
139                 Activity::LIKE, Activity::DISLIKE,
140                 Activity::ATTEND, Activity::ATTENDNO, Activity::ATTENDMAYBE,
141                 Activity::FOLLOW,
142                 Activity::ANNOUNCE];
143
144         // Privacy levels
145         const PUBLIC = 0;
146         const PRIVATE = 1;
147         const UNLISTED = 2;
148
149         // Item weight for query ordering
150         const GRAVITY_PARENT   = 0;
151         const GRAVITY_ACTIVITY = 3;
152         const GRAVITY_COMMENT  = 6;
153         const GRAVITY_UNKNOWN  = 9;
154
155         /**
156          * Update existing item entries
157          *
158          * @param array $fields    The fields that are to be changed
159          * @param array $condition The condition for finding the item entries
160          *
161          * In the future we may have to change permissions as well.
162          * Then we had to add the user id as third parameter.
163          *
164          * A return value of "0" doesn't mean an error - but that 0 rows had been changed.
165          *
166          * @return integer|boolean number of affected rows - or "false" if there was an error
167          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
168          */
169         public static function update(array $fields, array $condition)
170         {
171                 if (empty($condition) || empty($fields)) {
172                         return false;
173                 }
174
175                 if (isset($fields['extid'])) {
176                         $fields['external-id'] = ItemURI::getIdByURI($fields['extid']);
177                 }
178
179                 if (!empty($fields['verb'])) {
180                         $fields['vid'] = Verb::getID($fields['verb']);
181                 }
182
183                 if (!empty($fields['edited'])) {
184                         $previous = Post::selectFirst(['edited'], $condition);
185                 }
186
187                 $rows = Post::update($fields, $condition);
188                 if (is_bool($rows)) {
189                         return $rows;
190                 }
191
192                 // We only need to call the line by line update for specific fields
193                 if (empty($fields['body']) && empty($fields['file']) &&
194                         empty($fields['attach']) && empty($fields['edited'])) {
195                         return $rows;
196                 }
197
198                 Logger::info('Updating per single row method', ['fields' => $fields, 'condition' => $condition]);
199
200                 $items = Post::select(['id', 'origin', 'uri-id', 'uid', 'author-network', 'quote-uri-id'], $condition);
201
202                 $notify_items = [];
203
204                 while ($item = DBA::fetch($items)) {
205                         if (!empty($fields['body'])) {
206                                 if (!empty($item['quote-uri-id'])) {
207                                         $fields['body'] = BBCode::removeSharedData($fields['body']);
208
209                                         if (!empty($fields['raw-body'])) {
210                                                 $fields['raw-body'] = BBCode::removeSharedData($fields['raw-body']);
211                                         }
212                                 }
213
214                                 Post\Media::insertFromAttachmentData($item['uri-id'], $fields['body']);
215
216                                 $content_fields = ['raw-body' => trim($fields['raw-body'] ?? $fields['body'])];
217
218                                 // Remove all media attachments from the body and store them in the post-media table
219                                 // @todo On shared postings (Diaspora style and commented reshare) don't fetch content from the shared part
220                                 $content_fields['raw-body'] = Post\Media::insertFromBody($item['uri-id'], $content_fields['raw-body']);
221                                 $content_fields['raw-body'] = self::setHashtags($content_fields['raw-body']);
222
223                                 Post\Media::insertFromRelevantUrl($item['uri-id'], $content_fields['raw-body']);
224                                 Post\Content::update($item['uri-id'], $content_fields);
225                         }
226
227                         if (!empty($fields['file'])) {
228                                 Post\Category::storeTextByURIId($item['uri-id'], $item['uid'], $fields['file']);
229                         }
230
231                         if (!empty($fields['attach'])) {
232                                 Post\Media::insertFromAttachment($item['uri-id'], $fields['attach']);
233                         }
234
235                         // We only need to notfiy others when it is an original entry from us.
236                         // Only call the notifier when the item had been edited and records had been changed.
237                         if ($item['origin'] && !empty($fields['edited']) && ($previous['edited'] != $fields['edited'])) {
238                                 $notify_items[] = $item['id'];
239                         }
240                 }
241
242                 DBA::close($items);
243
244                 foreach ($notify_items as $notify_item) {
245                         $post = Post::selectFirst(['uri-id', 'uid'], ['id' => $notify_item]);
246                         Worker::add(Worker::PRIORITY_HIGH, 'Notifier', Delivery::POST, (int)$post['uri-id'], (int)$post['uid']);
247                 }
248
249                 return $rows;
250         }
251
252         /**
253          * Delete an item and notify others about it - if it was ours
254          *
255          * @param array   $condition The condition for finding the item entries
256          * @param integer $priority  Priority for the notification
257          * @return void
258          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
259          */
260         public static function markForDeletion(array $condition, int $priority = Worker::PRIORITY_HIGH)
261         {
262                 $items = Post::select(['id'], $condition);
263                 while ($item = Post::fetch($items)) {
264                         self::markForDeletionById($item['id'], $priority);
265                 }
266                 DBA::close($items);
267         }
268
269         /**
270          * Delete an item for an user and notify others about it - if it was ours
271          *
272          * @param array   $condition The condition for finding the item entries
273          * @param integer $uid       User who wants to delete this item
274          * @return void
275          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
276          */
277         public static function deleteForUser(array $condition, int $uid)
278         {
279                 if ($uid == 0) {
280                         return;
281                 }
282
283                 $items = Post::select(['id', 'uid', 'uri-id'], $condition);
284                 while ($item = Post::fetch($items)) {
285                         if (in_array($item['uid'], [$uid, 0])) {
286                                 Post\User::update($item['uri-id'], $uid, ['hidden' => true], true);
287                                 Post\ThreadUser::update($item['uri-id'], $uid, ['hidden' => true], true);
288                         }
289
290                         if ($item['uid'] == $uid) {
291                                 self::markForDeletionById($item['id'], Worker::PRIORITY_HIGH);
292                         } elseif ($item['uid'] != 0) {
293                                 Logger::warning('Wrong ownership. Not deleting item', ['id' => $item['id']]);
294                         }
295                 }
296                 DBA::close($items);
297         }
298
299         /**
300          * Mark an item for deletion, delete related data and notify others about it - if it was ours
301          *
302          * @param integer $item_id
303          * @param integer $priority Priority for the notification
304          * @return boolean success
305          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
306          */
307         public static function markForDeletionById(int $item_id, int $priority = Worker::PRIORITY_HIGH): bool
308         {
309                 Logger::info('Mark item for deletion by id', ['id' => $item_id, 'callstack' => System::callstack()]);
310                 // locate item to be deleted
311                 $fields = ['id', 'uri', 'uri-id', 'uid', 'parent', 'parent-uri-id', 'origin',
312                         'deleted', 'resource-id', 'event-id',
313                         'verb', 'object-type', 'object', 'target', 'contact-id', 'psid', 'gravity'];
314                 $item = Post::selectFirst($fields, ['id' => $item_id]);
315                 if (!DBA::isResult($item)) {
316                         Logger::info('Item not found.', ['id' => $item_id]);
317                         return false;
318                 }
319
320                 if ($item['deleted']) {
321                         Logger::info('Item has already been marked for deletion.', ['id' => $item_id]);
322                         return false;
323                 }
324
325                 $parent = Post::selectFirst(['origin'], ['id' => $item['parent']]);
326                 if (!DBA::isResult($parent)) {
327                         $parent = ['origin' => false];
328                 }
329
330                 // clean up categories and tags so they don't end up as orphans
331                 Post\Category::deleteByURIId($item['uri-id'], $item['uid']);
332
333                 /*
334                  * If item is a link to a photo resource, nuke all the associated photos
335                  * (visitors will not have photo resources)
336                  * This only applies to photos uploaded from the photos page. Photos inserted into a post do not
337                  * generate a resource-id and therefore aren't intimately linked to the item.
338                  */
339                 /// @TODO: this should first check if photo is used elsewhere
340                 if ($item['resource-id']) {
341                         Photo::delete(['resource-id' => $item['resource-id'], 'uid' => $item['uid']]);
342                 }
343
344                 // If item is a link to an event, delete the event.
345                 if (intval($item['event-id'])) {
346                         Event::delete($item['event-id']);
347                 }
348
349                 // If item has attachments, drop them
350                 $attachments = Post\Media::getByURIId($item['uri-id'], [Post\Media::DOCUMENT]);
351                 foreach($attachments as $attachment) {
352                         if (preg_match('|attach/(\d+)|', $attachment['url'], $matches)) {
353                                 Attach::delete(['id' => $matches[1], 'uid' => $item['uid']]);
354                         }
355                 }
356
357                 // Set the item to "deleted"
358                 $item_fields = ['deleted' => true, 'edited' => DateTimeFormat::utcNow(), 'changed' => DateTimeFormat::utcNow()];
359                 Post::update($item_fields, ['id' => $item['id']]);
360
361                 Post\Category::storeTextByURIId($item['uri-id'], $item['uid'], '');
362
363                 if (!Post::exists(["`uri-id` = ? AND `uid` != 0 AND NOT `deleted`", $item['uri-id']])) {
364                         self::markForDeletion(['uri-id' => $item['uri-id'], 'uid' => 0, 'deleted' => false], $priority);
365                 }
366
367                 Post\DeliveryData::delete($item['uri-id']);
368
369                 // If it's the parent of a comment thread, kill all the kids
370                 if ($item['gravity'] == self::GRAVITY_PARENT) {
371                         self::markForDeletion(['parent' => $item['parent'], 'deleted' => false], $priority);
372                 }
373
374                 // Is it our comment and/or our thread?
375                 if (($item['origin'] || $parent['origin']) && ($item['uid'] != 0)) {
376                         // When we delete the original post we will delete all existing copies on the server as well
377                         self::markForDeletion(['uri-id' => $item['uri-id'], 'deleted' => false], $priority);
378
379                         // send the notification upstream/downstream
380                         if ($priority) {
381                                 Worker::add(['priority' => $priority, 'dont_fork' => true], 'Notifier', Delivery::DELETION, (int)$item['uri-id'], (int)$item['uid']);
382                         }
383                 } elseif ($item['uid'] != 0) {
384                         Post\User::update($item['uri-id'], $item['uid'], ['hidden' => true]);
385                         Post\ThreadUser::update($item['uri-id'], $item['uid'], ['hidden' => true]);
386                 }
387
388                 Logger::info('Item has been marked for deletion.', ['id' => $item_id]);
389
390                 return true;
391         }
392
393         /**
394          * Get guid from given item record
395          *
396          * @param array $item Item record
397          * @param bool Whether to notify (?)
398          * @return string Guid
399          */
400         public static function guid(array $item, bool $notify): string
401         {
402                 if (!empty($item['guid'])) {
403                         return trim($item['guid']);
404                 }
405
406                 if ($notify) {
407                         // We have to avoid duplicates. So we create the GUID in form of a hash of the plink or uri.
408                         // We add the hash of our own host because our host is the original creator of the post.
409                         $prefix_host = DI::baseUrl()->getHostname();
410                 } else {
411                         $prefix_host = '';
412
413                         // We are only storing the post so we create a GUID from the original hostname.
414                         if (!empty($item['author-link'])) {
415                                 $parsed = parse_url($item['author-link']);
416                                 if (!empty($parsed['host'])) {
417                                         $prefix_host = $parsed['host'];
418                                 }
419                         }
420
421                         if (empty($prefix_host) && !empty($item['plink'])) {
422                                 $parsed = parse_url($item['plink']);
423                                 if (!empty($parsed['host'])) {
424                                         $prefix_host = $parsed['host'];
425                                 }
426                         }
427
428                         if (empty($prefix_host) && !empty($item['uri'])) {
429                                 $parsed = parse_url($item['uri']);
430                                 if (!empty($parsed['host'])) {
431                                         $prefix_host = $parsed['host'];
432                                 }
433                         }
434
435                         // Is it in the format data@host.tld? - Used for mail contacts
436                         if (empty($prefix_host) && !empty($item['author-link']) && strstr($item['author-link'], '@')) {
437                                 $mailparts = explode('@', $item['author-link']);
438                                 $prefix_host = array_pop($mailparts);
439                         }
440                 }
441
442                 if (!empty($item['plink'])) {
443                         $guid = self::guidFromUri($item['plink'], $prefix_host);
444                 } elseif (!empty($item['uri'])) {
445                         $guid = self::guidFromUri($item['uri'], $prefix_host);
446                 } else {
447                         $guid = System::createUUID(hash('crc32', $prefix_host));
448                 }
449
450                 return $guid;
451         }
452
453         /**
454          * Returns contact id from given item record
455          *
456          * @param array $item Item record
457          * @return int Contact id
458          */
459         private static function contactId(array $item): int
460         {
461                 if ($item['uid'] == 0) {
462                         return $item['author-id'];
463                 }
464
465                 if ($item['origin']) {
466                         $owner = User::getOwnerDataById($item['uid']);
467                         return $owner['id'];
468                 }
469
470                 if (!empty($item['causer-id']) && Contact::isSharing($item['causer-id'], $item['uid'], true)) {
471                         $cdata = Contact::getPublicAndUserContactID($item['causer-id'], $item['uid']);
472                         if (!empty($cdata['user'])) {
473                                 return $cdata['user'];
474                         }
475                 }
476
477                 if ($item['gravity'] == self::GRAVITY_PARENT) {
478                         if (Contact::isSharingByURL($item['owner-link'], $item['uid'], true)) {
479                                 $contact_id = Contact::getIdForURL($item['owner-link'], $item['uid']);
480                         } else {
481                                 $contact_id = Contact::getIdForURL($item['owner-link']);
482                         }
483                         if (!empty($contact_id)) {
484                                 return $contact_id;
485                         }
486                 }
487
488                 if (Contact::isSharingByURL($item['author-link'], $item['uid'], true)) {
489                         $contact_id = Contact::getIdForURL($item['author-link'], $item['uid']);
490                 } else {
491                         $contact_id = Contact::getIdForURL($item['author-link']);
492                 }
493
494                 if (!empty($contact_id)) {
495                         return $contact_id;
496                 }
497
498                 Logger::warning('contact-id could not be fetched, using self contact instead.', ['uid' => $item['uid'], 'item' => $item]);
499                 $self = Contact::selectFirst(['id'], ['self' => true, 'uid' => $item['uid']]);
500                 return $self['id'];
501         }
502
503         /**
504          * Write an item array into a spool file to be inserted later.
505          * This command is called whenever there are issues storing an item.
506          *
507          * @param array $item The item fields that are to be inserted
508          * @throws \Exception
509          */
510         private static function spool(array $item)
511         {
512                 // Now we store the data in the spool directory
513                 // We use "microtime" to keep the arrival order and "mt_rand" to avoid duplicates
514                 $file = 'item-' . round(microtime(true) * 10000) . '-' . mt_rand() . '.msg';
515
516                 $spoolpath = System::getSpoolPath();
517                 if ($spoolpath != '') {
518                         $spool = $spoolpath . '/' . $file;
519
520                         file_put_contents($spool, json_encode($item));
521                         Logger::warning("Item wasn't stored - Item was spooled into file", ['file' => $file]);
522                 }
523         }
524
525         /**
526          * Check if the item array is a duplicate
527          *
528          * @param array $item Item record
529          * @return boolean is it a duplicate?
530          */
531         private static function isDuplicate(array $item): bool
532         {
533                 // Checking if there is already an item with the same guid
534                 $condition = ['guid' => $item['guid'], 'network' => $item['network'], 'uid' => $item['uid']];
535                 if (Post::exists($condition)) {
536                         Logger::notice('Found already existing item', $condition);
537                         return true;
538                 }
539
540                 $condition = ['uri-id' => $item['uri-id'], 'uid' => $item['uid'],
541                         'network' => [$item['network'], Protocol::DFRN]];
542                 if (Post::exists($condition)) {
543                         Logger::notice('duplicated item with the same uri found.', $condition);
544                         return true;
545                 }
546
547                 // On Friendica and Diaspora the GUID is unique
548                 if (in_array($item['network'], [Protocol::DFRN, Protocol::DIASPORA])) {
549                         $condition = ['guid' => $item['guid'], 'uid' => $item['uid']];
550                         if (Post::exists($condition)) {
551                                 Logger::notice('duplicated item with the same guid found.', $condition);
552                                 return true;
553                         }
554                 } elseif ($item['network'] == Protocol::OSTATUS) {
555                         // Check for an existing post with the same content. There seems to be a problem with OStatus.
556                         $condition = ["`body` = ? AND `network` = ? AND `created` = ? AND `contact-id` = ? AND `uid` = ?",
557                                         $item['body'], $item['network'], $item['created'], $item['contact-id'], $item['uid']];
558                         if (Post::exists($condition)) {
559                                 Logger::notice('duplicated item with the same body found.', $item);
560                                 return true;
561                         }
562                 }
563
564                 /*
565                  * Check for already added items.
566                  * There is a timing issue here that sometimes creates double postings.
567                  * An unique index would help - but the limitations of MySQL (maximum size of index values) prevent this.
568                  */
569                 if (($item['uid'] == 0) && Post::exists(['uri-id' => $item['uri-id'], 'uid' => 0])) {
570                         Logger::notice('Global item already stored.', ['uri-id' => $item['uri-id'], 'network' => $item['network']]);
571                         return true;
572                 }
573
574                 return false;
575         }
576
577         /**
578          * Check if the item array is valid
579          *
580          * @param array $item Item record
581          * @return boolean item is valid
582          */
583         public static function isValid(array $item): bool
584         {
585                 // When there is no content then we don't post it
586                 if (($item['body'] . $item['title'] == '') && empty($item['quote-uri-id']) && (empty($item['uri-id']) || !Post\Media::existsByURIId($item['uri-id']))) {
587                         Logger::notice('No body, no title.');
588                         return false;
589                 }
590
591                 if (!empty($item['uid'])) {
592                         $owner = User::getOwnerDataById($item['uid'], false);
593                         if (!$owner) {
594                                 Logger::warning('Missing item user owner data', ['uid' => $item['uid']]);
595                                 return false;
596                         }
597
598                         if ($owner['account_expired'] || $owner['account_removed']) {
599                                 Logger::notice('Item user has been deleted/expired/removed', ['uid' => $item['uid'], 'deleted' => $owner['deleted'], 'account_expired' => $owner['account_expired'], 'account_removed' => $owner['account_removed']]);
600                                 return false;
601                         }
602                 }
603
604                 if (!empty($item['author-id']) && Contact::isBlocked($item['author-id'])) {
605                         Logger::notice('Author is blocked node-wide', ['author-link' => $item['author-link'], 'item-uri' => $item['uri']]);
606                         return false;
607                 }
608
609                 if (!empty($item['author-link']) && Network::isUrlBlocked($item['author-link'])) {
610                         Logger::notice('Author server is blocked', ['author-link' => $item['author-link'], 'item-uri' => $item['uri']]);
611                         return false;
612                 }
613
614                 if (!empty($item['owner-id']) && Contact::isBlocked($item['owner-id'])) {
615                         Logger::notice('Owner is blocked node-wide', ['owner-link' => $item['owner-link'], 'item-uri' => $item['uri']]);
616                         return false;
617                 }
618
619                 if (!empty($item['owner-link']) && Network::isUrlBlocked($item['owner-link'])) {
620                         Logger::notice('Owner server is blocked', ['owner-link' => $item['owner-link'], 'item-uri' => $item['uri']]);
621                         return false;
622                 }
623
624                 if (!empty($item['uid']) && !self::isAllowedByUser($item, $item['uid'])) {
625                         return false;
626                 }
627
628                 if ($item['verb'] == Activity::FOLLOW) {
629                         if (!$item['origin'] && ($item['author-id'] == Contact::getPublicIdByUserId($item['uid']))) {
630                                 // Our own follow request can be relayed to us. We don't store it to avoid notification chaos.
631                                 Logger::info("Follow: Don't store not origin follow request", ['parent-uri' => $item['parent-uri']]);
632                                 return false;
633                         }
634
635                         $condition = ['verb' => Activity::FOLLOW, 'uid' => $item['uid'],
636                                 'parent-uri' => $item['parent-uri'], 'author-id' => $item['author-id']];
637                         if (Post::exists($condition)) {
638                                 // It happens that we receive multiple follow requests by the same author - we only store one.
639                                 Logger::info('Follow: Found existing follow request from author', ['author-id' => $item['author-id'], 'parent-uri' => $item['parent-uri']]);
640                                 return false;
641                         }
642                 }
643
644                 return true;
645         }
646
647         /**
648          * Check if the item array is too old
649          *
650          * @param array $item Item record
651          * @return boolean item is too old
652          */
653         public static function isTooOld(array $item): bool
654         {
655                 // check for create date and expire time
656                 $expire_interval = DI::config()->get('system', 'dbclean-expire-days', 0);
657
658                 $user = DBA::selectFirst('user', ['expire'], ['uid' => $item['uid']]);
659                 if (DBA::isResult($user) && ($user['expire'] > 0) && (($user['expire'] < $expire_interval) || ($expire_interval == 0))) {
660                         $expire_interval = $user['expire'];
661                 }
662
663                 if (($expire_interval > 0) && !empty($item['created'])) {
664                         $expire_date = time() - ($expire_interval * 86400);
665                         $created_date = strtotime($item['created']);
666                         if ($created_date < $expire_date) {
667                                 Logger::notice('Item created before expiration interval.', [
668                                         'created' => date('c', $created_date),
669                                         'expired' => date('c', $expire_date),
670                                         '$item' => $item
671                                 ]);
672                                 return true;
673                         }
674                 }
675
676                 return false;
677         }
678
679         /**
680          * Return the id of the given item array if it has been stored before
681          *
682          * @param array $item Item record
683          * @return integer Item id or zero on error
684          */
685         private static function getDuplicateID(array $item): int
686         {
687                 if (empty($item['network']) || in_array($item['network'], Protocol::FEDERATED)) {
688                         $condition = ['`uri-id` = ? AND `uid` = ? AND `network` IN (?, ?, ?, ?)',
689                                 $item['uri-id'],
690                                 $item['uid'],
691                                 Protocol::ACTIVITYPUB,
692                                 Protocol::DIASPORA,
693                                 Protocol::DFRN,
694                                 Protocol::OSTATUS
695                         ];
696                         $existing = Post::selectFirst(['id', 'network'], $condition);
697                         if (DBA::isResult($existing)) {
698                                 // We only log the entries with a different user id than 0. Otherwise we would have too many false positives
699                                 if ($item['uid'] != 0) {
700                                         Logger::notice('Item already existed for user', [
701                                                 'uri-id' => $item['uri-id'],
702                                                 'uid' => $item['uid'],
703                                                 'network' => $item['network'],
704                                                 'existing_id' => $existing['id'],
705                                                 'existing_network' => $existing['network']
706                                         ]);
707                                 }
708
709                                 return $existing['id'];
710                         }
711                 }
712                 return 0;
713         }
714
715         /**
716          * Fetch the uri-id of the parent for the given uri-id
717          *
718          * @param integer $uriid
719          * @return integer
720          */
721         public static function getParent(int $uriid): int
722         {
723                 $thread_parent = Post::selectFirstPost(['thr-parent-id', 'gravity'], ['uri-id' => $uriid]);
724                 if (empty($thread_parent)) {
725                         return 0;
726                 }
727
728                 if ($thread_parent['gravity'] == Item::GRAVITY_PARENT) {
729                         return $uriid;
730                 }
731
732                 return self::getParent($thread_parent['thr-parent-id']);
733         }
734
735         /**
736          * Fetch top-level parent data for the given item array
737          *
738          * @param array $item
739          * @return array item array with parent data
740          * @throws \Exception
741          */
742         private static function getTopLevelParent(array $item): array
743         {
744                 $fields = ['uid', 'uri', 'parent-uri', 'id', 'deleted',
745                         'uri-id', 'parent-uri-id',
746                         'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid',
747                         'wall', 'private', 'origin', 'author-id'];
748                 $condition = ['uri-id' => [$item['thr-parent-id'], $item['parent-uri-id']], 'uid' => $item['uid']];
749                 $params = ['order' => ['id' => false]];
750                 $parent = Post::selectFirst($fields, $condition, $params);
751
752                 if (!DBA::isResult($parent) && Post::exists(['uri-id' => [$item['thr-parent-id'], $item['parent-uri-id']], 'uid' => 0])) {
753                         $stored = Item::storeForUserByUriId($item['thr-parent-id'], $item['uid'], ['post-reason' => Item::PR_COMPLETION]);
754                         if (!$stored && ($item['thr-parent-id'] != $item['parent-uri-id'])) {
755                                 $stored = Item::storeForUserByUriId($item['parent-uri-id'], $item['uid'], ['post-reason' => Item::PR_COMPLETION]);
756                         }
757                         if ($stored) {
758                                 Logger::info('Stored thread parent item for user', ['uri-id' => $item['thr-parent-id'], 'uid' => $item['uid'], 'stored' => $stored]);
759                                 $parent = Post::selectFirst($fields, $condition, $params);
760                         }
761                 }
762
763                 if (!DBA::isResult($parent)) {
764                         Logger::notice('item parent was not found - ignoring item', ['uri-id' => $item['uri-id'], 'thr-parent-id' => $item['thr-parent-id'], 'uid' => $item['uid'], 'callstack' => System::callstack(20)]);
765                         return [];
766                 }
767
768                 if ($parent['uri-id'] == $parent['parent-uri-id']) {
769                         return $parent;
770                 }
771
772                 $condition = ['uri-id' => $parent['parent-uri-id'],
773                         'parent-uri-id' => $parent['parent-uri-id'],
774                         'uid' => $parent['uid']];
775                 $params = ['order' => ['id' => false]];
776                 $toplevel_parent = Post::selectFirst($fields, $condition, $params);
777
778                 if (!DBA::isResult($toplevel_parent) && $item['origin']) {
779                         $stored = Item::storeForUserByUriId($item['parent-uri-id'], $item['uid'], ['post-reason' => Item::PR_COMPLETION]);
780                         Logger::info('Stored parent item for user', ['uri-id' => $item['parent-uri-id'], 'uid' => $item['uid'], 'stored' => $stored]);
781                         $toplevel_parent = Post::selectFirst($fields, $condition, $params);
782                 }
783
784                 if (!DBA::isResult($toplevel_parent)) {
785                         Logger::notice('item top level parent was not found - ignoring item', ['parent-uri-id' => $parent['parent-uri-id'], 'uid' => $parent['uid']]);
786                         return [];
787                 }
788
789                 return $toplevel_parent;
790         }
791
792         /**
793          * Get the gravity for the given item array
794          *
795          * @param array $item
796          * @return integer gravity
797          */
798         private static function getGravity(array $item): int
799         {
800                 $activity = DI::activity();
801
802                 if (isset($item['gravity'])) {
803                         return intval($item['gravity']);
804                 } elseif ($item['parent-uri-id'] === $item['uri-id']) {
805                         return self::GRAVITY_PARENT;
806                 } elseif ($activity->match($item['verb'], Activity::POST)) {
807                         return self::GRAVITY_COMMENT;
808                 } elseif ($activity->match($item['verb'], Activity::FOLLOW)) {
809                         return self::GRAVITY_ACTIVITY;
810                 } elseif ($activity->match($item['verb'], Activity::ANNOUNCE)) {
811                         return self::GRAVITY_ACTIVITY;
812                 }
813
814                 Logger::info('Unknown gravity for verb', ['verb' => $item['verb']]);
815                 return self::GRAVITY_UNKNOWN;   // Should not happen
816         }
817
818         private static function prepareOriginPost(array $item): array
819         {
820                 $item['wall'] = 1;
821                 $item['origin'] = 1;
822                 $item['network'] = Protocol::DFRN;
823                 $item['protocol'] = Conversation::PARCEL_DIRECT;
824                 $item['direction'] = Conversation::PUSH;
825
826                 $owner = User::getOwnerDataById($item['uid']);
827
828                 if (empty($item['contact-id'])) {
829                         $item['contact-id'] = $owner['id'];
830                 }
831
832                 if (empty($item['author-link']) && empty($item['author-id'])) {
833                         $item['author-link']   = $owner['url'];
834                         $item['author-name']   = $owner['name'];
835                         $item['author-avatar'] = $owner['thumb'];
836                 }
837
838                 if (empty($item['owner-link']) && empty($item['owner-id'])) {
839                         $item['owner-link']   = $item['author-link'];
840                         $item['owner-name']   = $item['author-name'];
841                         $item['owner-avatar'] = $item['author-avatar'];
842                 }
843
844                 // Setting the object type if not defined before
845                 if (empty($item['object-type'])) {
846                         $item['object-type'] = Activity\ObjectType::NOTE; // Default value
847                         $objectdata = BBCode::getAttachedData($item['body']);
848
849                         if ($objectdata['type'] == 'link') {
850                                 $item['object-type'] = Activity\ObjectType::BOOKMARK;
851                         } elseif ($objectdata['type'] == 'video') {
852                                 $item['object-type'] = Activity\ObjectType::VIDEO;
853                         } elseif ($objectdata['type'] == 'photo') {
854                                 $item['object-type'] = Activity\ObjectType::IMAGE;
855                         }
856                 }
857
858                 return $item;
859         }
860
861         /**
862          * Inserts item record
863          *
864          * @param array $item Item array to be inserted
865          * @param int   $notify Notification (type?)
866          * @param bool  $post_local (???)
867          * @return int Zero means error, otherwise primary key (id) is being returned
868          */
869         public static function insert(array $item, int $notify = 0, bool $post_local = true): int
870         {
871                 $orig_item = $item;
872
873                 $priority = Worker::PRIORITY_HIGH;
874
875                 // If it is a posting where users should get notifications, then define it as wall posting
876                 if ($notify) {
877                         $item = self::prepareOriginPost($item);
878
879                         if (is_int($notify) && in_array($notify, Worker::PRIORITIES)) {
880                                 $priority = $notify;
881                         }
882                 } else {
883                         $item['network'] = trim(($item['network'] ?? '') ?: Protocol::PHANTOM);
884                 }
885
886                 $uid = intval($item['uid']);
887
888                 $item['guid'] = self::guid($item, $notify);
889                 $item['uri'] = substr(trim($item['uri'] ?? '') ?: self::newURI($item['guid']), 0, 255);
890
891                 // Store URI data
892                 $item['uri-id'] = ItemURI::insert(['uri' => $item['uri'], 'guid' => $item['guid']]);
893
894                 // Backward compatibility: parent-uri used to be the direct parent uri.
895                 // If it is provided without a thr-parent, it probably is the old behavior.
896                 if (empty($item['thr-parent']) || empty($item['parent-uri'])) {
897                         $item['thr-parent'] = trim($item['thr-parent'] ?? $item['parent-uri'] ?? $item['uri']);
898                         $item['parent-uri'] = $item['thr-parent'];
899                 }
900
901                 $item['thr-parent-id'] = ItemURI::getIdByURI($item['thr-parent']);
902                 $item['parent-uri-id'] = ItemURI::getIdByURI($item['parent-uri']);
903
904                 // Store conversation data
905                 $source = $item['source'] ?? '';
906                 unset($item['conversation-uri']);
907                 unset($item['conversation-href']);
908                 unset($item['source']);
909
910                 /*
911                  * Do we already have this item?
912                  * We have to check several networks since Friendica posts could be repeated
913                  * via OStatus (maybe Diasporsa as well)
914                  */
915                 $duplicate = self::getDuplicateID($item);
916                 if ($duplicate) {
917                         return $duplicate;
918                 }
919
920                 // Additional duplicate checks
921                 /// @todo Check why the first duplication check returns the item number and the second a 0
922                 if (self::isDuplicate($item)) {
923                         return 0;
924                 }
925
926                 if (!isset($item['post-type'])) {
927                         $item['post-type'] = empty($item['title']) ? self::PT_NOTE : self::PT_ARTICLE;
928                 }
929
930                 $item['wall']          = intval($item['wall'] ?? 0);
931                 $item['extid']         = trim($item['extid'] ?? '');
932                 $item['author-name']   = trim($item['author-name'] ?? '');
933                 $item['author-link']   = trim($item['author-link'] ?? '');
934                 $item['author-avatar'] = trim($item['author-avatar'] ?? '');
935                 $item['owner-name']    = trim($item['owner-name'] ?? '');
936                 $item['owner-link']    = trim($item['owner-link'] ?? '');
937                 $item['owner-avatar']  = trim($item['owner-avatar'] ?? '');
938                 $item['received']      = (isset($item['received'])  ? DateTimeFormat::utc($item['received'])  : DateTimeFormat::utcNow());
939                 $item['created']       = (isset($item['created'])   ? DateTimeFormat::utc($item['created'])   : $item['received']);
940                 $item['edited']        = (isset($item['edited'])    ? DateTimeFormat::utc($item['edited'])    : $item['created']);
941                 $item['changed']       = (isset($item['changed'])   ? DateTimeFormat::utc($item['changed'])   : $item['created']);
942                 $item['commented']     = (isset($item['commented']) ? DateTimeFormat::utc($item['commented']) : $item['created']);
943                 $item['title']         = substr(trim($item['title'] ?? ''), 0, 255);
944                 $item['location']      = trim($item['location'] ?? '');
945                 $item['coord']         = trim($item['coord'] ?? '');
946                 $item['visible']       = (isset($item['visible']) ? intval($item['visible']) : 1);
947                 $item['deleted']       = 0;
948                 $item['verb']          = trim($item['verb'] ?? '');
949                 $item['object-type']   = trim($item['object-type'] ?? '');
950                 $item['object']        = trim($item['object'] ?? '');
951                 $item['target-type']   = trim($item['target-type'] ?? '');
952                 $item['target']        = trim($item['target'] ?? '');
953                 $item['plink']         = substr(trim($item['plink'] ?? ''), 0, 255);
954                 $item['allow_cid']     = trim($item['allow_cid'] ?? '');
955                 $item['allow_gid']     = trim($item['allow_gid'] ?? '');
956                 $item['deny_cid']      = trim($item['deny_cid'] ?? '');
957                 $item['deny_gid']      = trim($item['deny_gid'] ?? '');
958                 $item['private']       = intval($item['private'] ?? self::PUBLIC);
959                 $item['body']          = trim($item['body'] ?? '');
960                 $item['raw-body']      = trim($item['raw-body'] ?? $item['body']);
961                 $item['app']           = trim($item['app'] ?? '');
962                 $item['origin']        = intval($item['origin'] ?? 0);
963                 $item['postopts']      = trim($item['postopts'] ?? '');
964                 $item['resource-id']   = trim($item['resource-id'] ?? '');
965                 $item['event-id']      = intval($item['event-id'] ?? 0);
966                 $item['inform']        = trim($item['inform'] ?? '');
967                 $item['file']          = trim($item['file'] ?? '');
968
969                 // Communities aren't working with the Diaspora protoccol
970                 if (($uid != 0) && ($item['network'] == Protocol::DIASPORA)) {
971                         $user = User::getById($uid, ['account-type']);
972                         if ($user['account-type'] == Contact::TYPE_COMMUNITY) {
973                                 Logger::info('Community posts are not supported via Diaspora');
974                                 return 0;
975                         }
976                 }
977
978                 // Items cannot be stored before they happen ...
979                 if ($item['created'] > DateTimeFormat::utcNow()) {
980                         $item['created'] = DateTimeFormat::utcNow();
981                 }
982
983                 // We haven't invented time travel by now.
984                 if ($item['edited'] > DateTimeFormat::utcNow()) {
985                         $item['edited'] = DateTimeFormat::utcNow();
986                 }
987
988                 $item['plink'] = ($item['plink'] ?? '') ?: DI::baseUrl() . '/display/' . urlencode($item['guid']);
989
990                 $item['gravity'] = self::getGravity($item);
991
992                 $default = ['url' => $item['author-link'], 'name' => $item['author-name'],
993                         'photo' => $item['author-avatar'], 'network' => $item['network']];
994                 $item['author-id'] = ($item['author-id'] ?? 0) ?: Contact::getIdForURL($item['author-link'], 0, null, $default);
995
996                 $default = ['url' => $item['owner-link'], 'name' => $item['owner-name'],
997                         'photo' => $item['owner-avatar'], 'network' => $item['network']];
998                 $item['owner-id'] = ($item['owner-id'] ?? 0) ?: Contact::getIdForURL($item['owner-link'], 0, null, $default);
999
1000                 $item['post-reason'] = self::getPostReason($item);
1001
1002                 // Ensure that there is an avatar cache
1003                 Contact::checkAvatarCache($item['author-id']);
1004                 Contact::checkAvatarCache($item['owner-id']);
1005
1006                 $item['contact-id'] = self::contactId($item);
1007
1008                 if (!empty($item['direction']) && in_array($item['direction'], [Conversation::PUSH, Conversation::RELAY]) &&
1009                         empty($item['origin']) && self::isTooOld($item)) {
1010                         Logger::info('Item is too old', ['item' => $item]);
1011                         return 0;
1012                 }
1013
1014                 if (!self::isValid($item)) {
1015                         return 0;
1016                 }
1017
1018                 if ($item['gravity'] !== self::GRAVITY_PARENT) {
1019                         $toplevel_parent = self::getTopLevelParent($item);
1020                         if (empty($toplevel_parent)) {
1021                                 return 0;
1022                         }
1023
1024                         // If the thread originated from this node, we check the permission against the thread starter
1025                         $condition = ['uri-id' => $toplevel_parent['uri-id'], 'wall' => true];
1026                         $localTopLevelParent = Post::selectFirst(['uid'], $condition);
1027                         if (!empty($localTopLevelParent['uid']) && !self::isAllowedByUser($item, $localTopLevelParent['uid'])) {
1028                                 return 0;
1029                         }
1030
1031                         $parent_id             = $toplevel_parent['id'];
1032                         $item['parent-uri']    = $toplevel_parent['uri'];
1033                         $item['parent-uri-id'] = $toplevel_parent['uri-id'];
1034                         $item['deleted']       = $toplevel_parent['deleted'];
1035                         $item['wall']          = $toplevel_parent['wall'];
1036
1037                         // Reshares have to keep their permissions to allow forums to work
1038                         if (!$item['origin'] || ($item['verb'] != Activity::ANNOUNCE)) {
1039                                 $item['allow_cid']     = $toplevel_parent['allow_cid'];
1040                                 $item['allow_gid']     = $toplevel_parent['allow_gid'];
1041                                 $item['deny_cid']      = $toplevel_parent['deny_cid'];
1042                                 $item['deny_gid']      = $toplevel_parent['deny_gid'];
1043                         }
1044
1045                         $parent_origin         = $toplevel_parent['origin'];
1046
1047                         // Don't federate received participation messages
1048                         if ($item['verb'] != Activity::FOLLOW) {
1049                                 $item['wall'] = $toplevel_parent['wall'];
1050                         } else {
1051                                 $item['wall'] = false;
1052                                 // Participations are technical messages, so they are set to "seen" automatically
1053                                 $item['unseen'] = false;
1054                         }
1055
1056                         /*
1057                          * If the parent is private, force privacy for the entire conversation
1058                          * This differs from the above settings as it subtly allows comments from
1059                          * email correspondents to be private even if the overall thread is not.
1060                          */
1061                         if ($toplevel_parent['private']) {
1062                                 $item['private'] = $toplevel_parent['private'];
1063                         }
1064
1065                         // If its a post that originated here then tag the thread as "mention"
1066                         if ($item['origin'] && $item['uid']) {
1067                                 DBA::update('post-thread-user', ['mention' => true], ['uri-id' => $item['parent-uri-id'], 'uid' => $item['uid']]);
1068                                 Logger::info('tagged thread as mention', ['parent' => $parent_id, 'parent-uri-id' => $item['parent-uri-id'], 'uid' => $item['uid']]);
1069                         }
1070
1071                         // Update the contact relations
1072                         Contact\Relation::store($toplevel_parent['author-id'], $item['author-id'], $item['created']);
1073                 } else {
1074                         $parent_id = 0;
1075                         $parent_origin = $item['origin'];
1076
1077                         if ($item['wall'] && empty($item['conversation'])) {
1078                                 $item['conversation'] = $item['parent-uri'] . '#context';
1079                         }
1080                 }
1081
1082                 $item['parent-uri-id'] = ItemURI::getIdByURI($item['parent-uri']);
1083                 $item['thr-parent-id'] = ItemURI::getIdByURI($item['thr-parent']);
1084
1085                 if (!empty($item['conversation']) && empty($item['conversation-id'])) {
1086                         $item['conversation-id'] = ItemURI::getIdByURI($item['conversation']);
1087                 }
1088
1089                 // Is this item available in the global items (with uid=0)?
1090                 if ($item['uid'] == 0) {
1091                         $item['global'] = true;
1092
1093                         // Set the global flag on all items if this was a global item entry
1094                         Post::update(['global' => true], ['uri-id' => $item['uri-id']]);
1095                 } else {
1096                         $item['global'] = Post::exists(['uid' => 0, 'uri-id' => $item['uri-id']]);
1097                 }
1098
1099                 // ACL settings
1100                 if (!empty($item['allow_cid'] . $item['allow_gid'] . $item['deny_cid'] . $item['deny_gid'])) {
1101                         $item['private'] = self::PRIVATE;
1102                 }
1103
1104                 if ($notify && $post_local) {
1105                         $item['edit'] = false;
1106                         $item['parent'] = $parent_id;
1107
1108                         // Trigger automatic reactions for addons
1109                         if (!isset($item['api_source'])) {
1110                                 $item['api_source'] = true;
1111                         }
1112
1113                         // We have to tell the hooks who we are - this really should be improved
1114                         if (!DI::userSession()->getLocalUserId()) {
1115                                 $_SESSION['authenticated'] = true;
1116                                 $_SESSION['uid'] = $uid;
1117                                 $dummy_session = true;
1118                         } else {
1119                                 $dummy_session = false;
1120                         }
1121
1122                         Hook::callAll('post_local', $item);
1123
1124                         if ($dummy_session) {
1125                                 unset($_SESSION['authenticated']);
1126                                 unset($_SESSION['uid']);
1127                         }
1128                 } elseif (!$notify) {
1129                         Hook::callAll('post_remote', $item);
1130                 }
1131
1132                 if (!empty($item['cancel'])) {
1133                         Logger::notice('post cancelled by addon.');
1134                         return 0;
1135                 }
1136
1137                 if (empty($item['vid']) && !empty($item['verb'])) {
1138                         $item['vid'] = Verb::getID($item['verb']);
1139                 }
1140
1141                 // Creates or assigns the permission set
1142                 $item['psid'] = DI::permissionSet()->selectOrCreate(
1143                         DI::permissionSetFactory()->createFromString(
1144                                 $item['uid'],
1145                                 $item['allow_cid'],
1146                                 $item['allow_gid'],
1147                                 $item['deny_cid'],
1148                                 $item['deny_gid']
1149                 ))->id;
1150
1151                 if (!empty($item['extid'])) {
1152                         $item['external-id'] = ItemURI::getIdByURI($item['extid']);
1153                 }
1154
1155                 if ($item['verb'] == Activity::ANNOUNCE) {
1156                         self::setOwnerforResharedItem($item);
1157                 }
1158
1159                 if (isset($item['attachments'])) {
1160                         foreach ($item['attachments'] as $attachment) {
1161                                 $attachment['uri-id'] = $item['uri-id'];
1162                                 Post\Media::insert($attachment);
1163                         }
1164                         unset($item['attachments']);
1165                 }
1166
1167                 if (empty($item['quote-uri-id'])) {
1168                         $quote_id = self::getQuoteUriId($item['body']);
1169                         if (!empty($quote_id)) {
1170                                 // This is one of these "should not happen" situations.
1171                                 // The protocol implementations should already have done this job.
1172                                 Logger::notice('Quote-uri-id detected in post', ['id' => $quote_id, 'guid' => $item['guid'], 'uri-id' => $item['uri-id'], 'callstack' => System::callstack(20)]);
1173                                 $item['quote-uri-id'] = $quote_id;
1174                         }
1175                 }
1176
1177                 if (!empty($item['quote-uri-id'])) {
1178                         $item['raw-body'] = BBCode::removeSharedData($item['raw-body']);
1179                         $item['body']     = BBCode::removeSharedData($item['body']);
1180                 }
1181
1182                 Post\Media::insertFromAttachmentData($item['uri-id'], $item['body']);
1183
1184                 // Remove all media attachments from the body and store them in the post-media table
1185                 $item['raw-body'] = Post\Media::insertFromBody($item['uri-id'], $item['raw-body']);
1186                 $item['raw-body'] = self::setHashtags($item['raw-body']);
1187
1188                 Post\Media::insertFromRelevantUrl($item['uri-id'], $item['raw-body']);
1189
1190                 // Check for hashtags in the body and repair or add hashtag links
1191                 $item['body'] = self::setHashtags($item['body']);
1192
1193                 $item['language'] = self::getLanguage($item);
1194
1195                 $notify_type = Delivery::POST;
1196
1197                 // Filling item related side tables
1198                 if (!empty($item['attach'])) {
1199                         Post\Media::insertFromAttachment($item['uri-id'], $item['attach']);
1200                 }
1201
1202                 if (empty($item['event-id'])) {
1203                         unset($item['event-id']);
1204
1205                         $ev = Event::fromBBCode($item['body']);
1206                         if ((!empty($ev['desc']) || !empty($ev['summary'])) && !empty($ev['start'])) {
1207                                 Logger::info('Event found.');
1208                                 $ev['cid']       = $item['contact-id'];
1209                                 $ev['uid']       = $item['uid'];
1210                                 $ev['uri']       = $item['uri'];
1211                                 $ev['edited']    = $item['edited'];
1212                                 $ev['private']   = $item['private'];
1213                                 $ev['guid']      = $item['guid'];
1214                                 $ev['plink']     = $item['plink'];
1215                                 $ev['network']   = $item['network'];
1216                                 $ev['protocol']  = $item['protocol'] ?? Conversation::PARCEL_UNKNOWN;
1217                                 $ev['direction'] = $item['direction'] ?? Conversation::UNKNOWN;
1218                                 $ev['source']    = $item['source'] ?? '';
1219
1220                                 $event = DBA::selectFirst('event', ['id'], ['uri' => $item['uri'], 'uid' => $item['uid']]);
1221                                 if (DBA::isResult($event)) {
1222                                         $ev['id'] = $event['id'];
1223                                 }
1224
1225                                 $event_id = Event::store($ev);
1226                                 $item = Event::getItemArrayForImportedId($event_id, $item);
1227
1228                                 Logger::info('Event was stored', ['id' => $event_id]);
1229                         }
1230                 }
1231
1232                 if (empty($item['causer-id'])) {
1233                         unset($item['causer-id']);
1234                 }
1235
1236                 if (in_array($item['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN])) {
1237                         $content_warning = BBCode::getAbstract($item['body'], Protocol::ACTIVITYPUB);
1238                         if (!empty($content_warning) && empty($item['content-warning'])) {
1239                                 $item['content-warning'] = BBCode::toPlaintext($content_warning);
1240                         }
1241                 }
1242
1243                 Post::insert($item['uri-id'], $item);
1244
1245                 if ($item['gravity'] == self::GRAVITY_PARENT) {
1246                         Post\Thread::insert($item['uri-id'], $item);
1247                 }
1248
1249                 if (!in_array($item['verb'], self::ACTIVITIES)) {
1250                         Post\Content::insert($item['uri-id'], $item);
1251                 }
1252
1253                 // Create Diaspora signature
1254                 if ($item['origin'] && empty($item['diaspora_signed_text']) && ($item['gravity'] != self::GRAVITY_PARENT)) {
1255                         $signed = Diaspora::createCommentSignature($item);
1256                         if (!empty($signed)) {
1257                                 $item['diaspora_signed_text'] = json_encode($signed);
1258                         }
1259                 }
1260
1261                 if (!empty($item['diaspora_signed_text'])) {
1262                         DBA::replace('diaspora-interaction', ['uri-id' => $item['uri-id'], 'interaction' => $item['diaspora_signed_text']]);
1263                 }
1264
1265                 // Attached file links
1266                 if (!empty($item['file'])) {
1267                         Post\Category::storeTextByURIId($item['uri-id'], $item['uid'], $item['file']);
1268                 }
1269
1270                 // Delivery relevant data
1271                 $delivery_data = Post\DeliveryData::extractFields($item);
1272
1273                 if (!empty($item['origin']) || !empty($item['wall']) || !empty($delivery_data['postopts']) || !empty($delivery_data['inform'])) {
1274                         Post\DeliveryData::insert($item['uri-id'], $delivery_data);
1275                 }
1276
1277                 // Store tags from the body if this hadn't been handled previously in the protocol classes
1278                 if (!Tag::existsForPost($item['uri-id'])) {
1279                         Tag::storeFromBody($item['uri-id'], $item['body']);
1280                 }
1281
1282                 $condition = ['uri-id' => $item['uri-id'], 'uid' => $item['uid']];
1283                 if (Post::exists($condition)) {
1284                         Logger::notice('Item is already inserted - aborting', $condition);
1285                         return 0;
1286                 }
1287
1288                 $post_user_id = Post\User::insert($item['uri-id'], $item['uid'], $item);
1289                 if (!$post_user_id) {
1290                         Logger::notice('Post-User is already inserted - aborting', ['uid' => $item['uid'], 'uri-id' => $item['uri-id']]);
1291                         return 0;
1292                 }
1293
1294                 if ($item['gravity'] == self::GRAVITY_PARENT) {
1295                         $item['post-user-id'] = $post_user_id;
1296                         Post\ThreadUser::insert($item['uri-id'], $item['uid'], $item);
1297                 }
1298
1299                 Logger::notice('created item', ['post-id' => $post_user_id, 'uid' => $item['uid'], 'network' => $item['network'], 'uri-id' => $item['uri-id'], 'guid' => $item['guid']]);
1300
1301                 $posted_item = Post::selectFirst(self::ITEM_FIELDLIST, ['post-user-id' => $post_user_id]);
1302                 if (!DBA::isResult($posted_item)) {
1303                         // On failure store the data into a spool file so that the "SpoolPost" worker can try again later.
1304                         Logger::warning('Could not store item. it will be spooled', ['id' => $post_user_id]);
1305                         self::spool($orig_item);
1306                         return 0;
1307                 }
1308
1309                 // update the commented timestamp on the parent
1310                 if (DI::config()->get('system', 'like_no_comment')) {
1311                         // Update when it is a comment
1312                         $update_commented = in_array($posted_item['gravity'], [self::GRAVITY_PARENT, self::GRAVITY_COMMENT]);
1313                 } else {
1314                         // Update when it isn't a follow or tag verb
1315                         $update_commented = !in_array($posted_item['verb'], [Activity::FOLLOW, Activity::TAG]);
1316                 }
1317
1318                 if ($update_commented) {
1319                         $fields = ['commented' => DateTimeFormat::utcNow(), 'changed' => DateTimeFormat::utcNow()];
1320                 } else {
1321                         $fields = ['changed' => DateTimeFormat::utcNow()];
1322                 }
1323
1324                 Post::update($fields, ['uri-id' => $posted_item['parent-uri-id'], 'uid' => $posted_item['uid']]);
1325
1326                 // In that function we check if this is a forum post. Additionally we delete the item under certain circumstances
1327                 if (self::tagDeliver($posted_item['uid'], $post_user_id)) {
1328                         // Get the user information for the logging
1329                         $user = User::getById($uid);
1330
1331                         Logger::notice('Item had been deleted', ['id' => $post_user_id, 'user' => $uid, 'account-type' => $user['account-type']]);
1332                         return 0;
1333                 }
1334
1335                 if ($notify) {
1336                         if (!\Friendica\Content\Feature::isEnabled($posted_item['uid'], 'explicit_mentions') && ($posted_item['gravity'] == self::GRAVITY_COMMENT)) {
1337                                 Tag::createImplicitMentions($posted_item['uri-id'], $posted_item['thr-parent-id']);
1338                         }
1339                         Hook::callAll('post_local_end', $posted_item);
1340                 } else {
1341                         Hook::callAll('post_remote_end', $posted_item);
1342                 }
1343
1344                 if ($posted_item['gravity'] === self::GRAVITY_PARENT) {
1345                         self::addShadow($post_user_id);
1346                 } else {
1347                         self::addShadowPost($post_user_id);
1348                 }
1349
1350                 self::updateContact($posted_item);
1351
1352                 Post\UserNotification::setNotification($posted_item['uri-id'], $posted_item['uid']);
1353
1354                 // Distribute items to users who subscribed to their tags
1355                 self::distributeByTags($posted_item);
1356
1357                 // Automatically reshare the item if the "remote_self" option is selected
1358                 self::autoReshare($posted_item);
1359
1360                 $transmit = $notify || ($posted_item['visible'] && ($parent_origin || $posted_item['origin']));
1361
1362                 if ($transmit) {
1363                         // Don't relay participation messages
1364                         if (($posted_item['verb'] == Activity::FOLLOW) &&
1365                                 (!$posted_item['origin'] || ($posted_item['author-id'] != Contact::getPublicIdByUserId($uid)))) {
1366                                 Logger::info('Participation messages will not be relayed', ['item' => $posted_item['id'], 'uri' => $posted_item['uri'], 'verb' => $posted_item['verb']]);
1367                                 $transmit = false;
1368                         }
1369                 }
1370
1371                 if (!empty($source) && ($transmit || DI::config()->get('debug', 'store_source'))) {
1372                         Post\Activity::insert($item['uri-id'], $source);
1373                 }
1374
1375                 if ($transmit) {
1376                         Worker::add(['priority' => $priority, 'dont_fork' => true], 'Notifier', $notify_type, (int)$posted_item['uri-id'], (int)$posted_item['uid']);
1377                 }
1378
1379                 // Fill the cache with the rendered content.
1380                 if (in_array($posted_item['gravity'], [self::GRAVITY_PARENT, self::GRAVITY_COMMENT]) && ($posted_item['uid'] == 0)) {
1381                         self::updateDisplayCache($posted_item['uri-id']);
1382                 }
1383
1384                 return $post_user_id;
1385         }
1386
1387         /**
1388          * Fetch the post reason for a given item array
1389          *
1390          * @param array $item
1391          *
1392          * @return integer
1393          */
1394         public static function getPostReason(array $item): int
1395         {
1396                 $actor = ($item['gravity'] == self::GRAVITY_PARENT) ? $item['owner-id'] : $item['author-id'];
1397                 if (empty($item['origin']) && ($item['uid'] != 0) && Contact::isSharing($actor, $item['uid'])) {
1398                         return self::PR_FOLLOWER;
1399                 }
1400
1401                 if (!empty($item['origin']) && empty($item['post-reason'])) {
1402                         return self::PR_LOCAL;
1403                 }
1404
1405                 return $item['post-reason'] ?? self::PR_NONE;
1406         }
1407
1408         /**
1409          * Update the display cache
1410          *
1411          * @param integer $uri_id
1412          * @return void
1413          */
1414         public static function updateDisplayCache(int $uri_id)
1415         {
1416                 $item = Post::selectFirst(self::DISPLAY_FIELDLIST, ['uri-id' => $uri_id]);
1417                 self::prepareBody($item, false, false, true);
1418         }
1419
1420         /**
1421          * Change the owner of a parent item if it had been shared by a forum
1422          *
1423          * (public) forum posts in the new format consist of the regular post by the author
1424          * followed by an announce message sent from the forum account.
1425          * Changing the owner helps in grouping forum posts.
1426          *
1427          * @param array $item
1428          * @return void
1429          */
1430         private static function setOwnerforResharedItem(array $item)
1431         {
1432                 $parent = Post::selectFirst(['id', 'causer-id', 'owner-id', 'author-id', 'author-link', 'origin', 'post-reason'],
1433                         ['uri-id' => $item['thr-parent-id'], 'uid' => $item['uid']]);
1434                 if (!DBA::isResult($parent)) {
1435                         Logger::error('Parent not found', ['uri-id' => $item['thr-parent-id'], 'uid' => $item['uid']]);
1436                         return;
1437                 }
1438
1439                 $author = Contact::selectFirst(['url', 'contact-type', 'network'], ['id' => $item['author-id']]);
1440                 if (!DBA::isResult($author)) {
1441                         Logger::error('Author not found', ['id' => $item['author-id']]);
1442                         return;
1443                 }
1444
1445                 $self_contact = Contact::selectFirst(['id'], ['uid' => $item['uid'], 'self' => true]);
1446                 $self = !empty($self_contact) ? $self_contact['id'] : 0;
1447
1448                 $cid = Contact::getIdForURL($author['url'], $item['uid']);
1449                 if (empty($cid) || (!Contact::isSharing($cid, $item['uid']) && ($cid != $self))) {
1450                         Logger::info('The resharer is not a following contact: quit', ['resharer' => $author['url'], 'uid' => $item['uid'], 'cid' => $cid]);
1451                         return;
1452                 }
1453
1454                 if ($author['contact-type'] != Contact::TYPE_COMMUNITY) {
1455                         if ($parent['post-reason'] == self::PR_ANNOUNCEMENT) {
1456                                 Logger::info('The parent is already marked as announced: quit', ['causer' => $parent['causer-id'], 'owner' => $parent['owner-id'], 'author' => $parent['author-id'], 'uid' => $item['uid']]);
1457                                 return;
1458                         }
1459
1460                         if (Contact::isSharing($parent['owner-id'], $item['uid'])) {
1461                                 Logger::info('The resharer is no forum: quit', ['resharer' => $item['author-id'], 'owner' => $parent['owner-id'], 'author' => $parent['author-id'], 'uid' => $item['uid']]);
1462                                 return;
1463                         }
1464                 }
1465
1466                 self::update(['post-reason' => self::PR_ANNOUNCEMENT, 'causer-id' => $item['author-id']], ['id' => $parent['id']]);
1467                 Logger::info('Set announcement post-reason', ['uri-id' => $item['uri-id'], 'thr-parent-id' => $item['thr-parent-id'], 'uid' => $item['uid']]);
1468         }
1469
1470         /**
1471          * Distribute the given item to users who subscribed to their tags
1472          *
1473          * @param array $item     Processed item
1474          */
1475         private static function distributeByTags(array $item)
1476         {
1477                 if (($item['uid'] != 0) || ($item['gravity'] != self::GRAVITY_PARENT) || !in_array($item['network'], Protocol::FEDERATED)) {
1478                         return;
1479                 }
1480
1481                 $uids = Tag::getUIDListByURIId($item['uri-id']);
1482                 foreach ($uids as $uid) {
1483                         $stored = self::storeForUserByUriId($item['uri-id'], $uid, ['post-reason' => self::PR_TAG]);
1484                         Logger::info('Stored item for users', ['uri-id' => $item['uri-id'], 'uid' => $uid, 'stored' => $stored]);
1485                 }
1486         }
1487
1488         /**
1489          * Distributes public items to the receivers
1490          *
1491          * @param integer $itemid      Item ID that should be added
1492          * @param string  $signed_text Original text (for Diaspora signatures), JSON encoded.
1493          * @throws \Exception
1494          */
1495         public static function distribute(int $itemid, string $signed_text = '')
1496         {
1497                 $condition = ["`id` IN (SELECT `parent` FROM `post-user-view` WHERE `id` = ?)", $itemid];
1498                 $parent = Post::selectFirst(['owner-id'], $condition);
1499                 if (!DBA::isResult($parent)) {
1500                         Logger::warning('Item not found', ['condition' => $condition]);
1501                         return;
1502                 }
1503
1504                 // Only distribute public items from native networks
1505                 $condition = ['id' => $itemid, 'uid' => 0,
1506                         'network' => array_merge(Protocol::FEDERATED ,['']),
1507                         'visible' => true, 'deleted' => false, 'private' => [self::PUBLIC, self::UNLISTED]];
1508                 $item = Post::selectFirst(array_merge(self::ITEM_FIELDLIST, ['protocol']), $condition);
1509                 if (!DBA::isResult($item)) {
1510                         Logger::warning('Item not found', ['condition' => $condition]);
1511                         return;
1512                 }
1513
1514                 $origin = $item['origin'];
1515
1516                 $users = [];
1517
1518                 /// @todo add a field "pcid" in the contact table that referrs to the public contact id.
1519                 $owner = DBA::selectFirst('contact', ['url', 'nurl', 'alias'], ['id' => $parent['owner-id']]);
1520                 if (!DBA::isResult($owner)) {
1521                         return;
1522                 }
1523
1524                 $condition = ['nurl' => $owner['nurl'], 'rel' => [Contact::SHARING, Contact::FRIEND]];
1525                 $contacts = DBA::select('contact', ['uid'], $condition);
1526                 while ($contact = DBA::fetch($contacts)) {
1527                         if ($contact['uid'] == 0) {
1528                                 continue;
1529                         }
1530
1531                         $users[$contact['uid']] = $contact['uid'];
1532                 }
1533                 DBA::close($contacts);
1534
1535                 $condition = ['alias' => $owner['url'], 'rel' => [Contact::SHARING, Contact::FRIEND]];
1536                 $contacts = DBA::select('contact', ['uid'], $condition);
1537                 while ($contact = DBA::fetch($contacts)) {
1538                         if ($contact['uid'] == 0) {
1539                                 continue;
1540                         }
1541
1542                         $users[$contact['uid']] = $contact['uid'];
1543                 }
1544                 DBA::close($contacts);
1545
1546                 if (!empty($owner['alias'])) {
1547                         $condition = ['nurl' => Strings::normaliseLink($owner['alias']), 'rel' => [Contact::SHARING, Contact::FRIEND]];
1548                         $contacts = DBA::select('contact', ['uid'], $condition);
1549                         while ($contact = DBA::fetch($contacts)) {
1550                                 if ($contact['uid'] == 0) {
1551                                         continue;
1552                                 }
1553
1554                                 $users[$contact['uid']] = $contact['uid'];
1555                         }
1556                         DBA::close($contacts);
1557                 }
1558
1559                 $origin_uid = 0;
1560
1561                 if ($item['uri-id'] != $item['parent-uri-id']) {
1562                         $parents = Post::select(['uid', 'origin'], ["`uri-id` = ? AND `uid` != 0", $item['parent-uri-id']]);
1563                         while ($parent = Post::fetch($parents)) {
1564                                 $users[$parent['uid']] = $parent['uid'];
1565                                 if ($parent['origin'] && !$origin) {
1566                                         $origin_uid = $parent['uid'];
1567                                 }
1568                         }
1569                         DBA::close($parents);
1570                 }
1571
1572                 foreach ($users as $uid) {
1573                         if ($origin_uid == $uid) {
1574                                 $item['diaspora_signed_text'] = $signed_text;
1575                         }
1576                         $item['post-reason'] = self::PR_DISTRIBUTE;
1577                         self::storeForUser($item, $uid);
1578                 }
1579         }
1580
1581         /**
1582          * Store a public item defined by their URI-ID for the given users
1583          *
1584          * @param integer $uri_id     URI-ID of the given item
1585          * @param integer $uid        The user that will receive the item entry
1586          * @param array   $fields     Additional fields to be stored
1587          * @param integer $source_uid User id of the source post
1588          * @return integer stored item id
1589          */
1590         public static function storeForUserByUriId(int $uri_id, int $uid, array $fields = [], int $source_uid = 0): int
1591         {
1592                 if ($uid == $source_uid) {
1593                         Logger::warning('target UID must not be be equal to the source UID', ['uri-id' => $uri_id, 'uid' => $uid]);
1594                         return 0;
1595                 }
1596
1597                 $item = Post::selectFirst(array_merge(self::ITEM_FIELDLIST, ['protocol']), ['uri-id' => $uri_id, 'uid' => $source_uid]);
1598                 if (!DBA::isResult($item)) {
1599                         Logger::warning('Item could not be fetched', ['uri-id' => $uri_id, 'uid' => $source_uid]);
1600                         return 0;
1601                 }
1602
1603                 if (($uid != 0) && ($item['gravity'] == self::GRAVITY_PARENT)) {
1604                         $owner = User::getOwnerDataById($uid);
1605                         if (($owner['contact-type'] == User::ACCOUNT_TYPE_COMMUNITY) && !Tag::isMentioned($uri_id, $owner['url'])) {
1606                                 Logger::info('Target user is a forum but is not mentioned here, thread will not be stored', ['uid' => $uid, 'uri-id' => $uri_id]);
1607                                 return 0;
1608                         }
1609                 }
1610
1611                 if (($source_uid == 0) && (($item['private'] == self::PRIVATE) || !in_array($item['network'], Protocol::FEDERATED))) {
1612                         Logger::notice('Item is private or not from a federated network. It will not be stored for the user.', ['uri-id' => $uri_id, 'uid' => $uid, 'private' => $item['private'], 'network' => $item['network']]);
1613                         return 0;
1614                 }
1615
1616                 $item['post-reason'] = self::PR_STORED;
1617
1618                 $item = array_merge($item, $fields);
1619
1620                 if (($uid != 0) && Contact::isSharing(($item['gravity'] == Item::GRAVITY_PARENT) ? $item['owner-id'] : $item['author-id'], $uid)) {
1621                         $item['post-reason'] = self::PR_FOLLOWER;
1622                 }
1623
1624                 $is_reshare = ($item['gravity'] == self::GRAVITY_ACTIVITY) && ($item['verb'] == Activity::ANNOUNCE);
1625
1626                 if (($uid != 0) && (($item['gravity'] == self::GRAVITY_PARENT) || $is_reshare) &&
1627                         DI::pConfig()->get($uid, 'system', 'accept_only_sharer') == self::COMPLETION_NONE &&
1628                         !in_array($item['post-reason'], [self::PR_FOLLOWER, self::PR_TAG, self::PR_TO, self::PR_CC])) {
1629                         Logger::info('Contact is not a follower, thread will not be stored', ['author' => $item['author-link'], 'uid' => $uid, 'uri-id' => $uri_id, 'post-reason' => $item['post-reason']]);
1630                         return 0;
1631                 }
1632
1633                 $causer = $item['causer-id'] ?: $item['author-id'];
1634
1635                 if (($uri_id != $item['parent-uri-id']) && ($item['gravity'] == self::GRAVITY_COMMENT) && !Post::exists(['uri-id' => $item['parent-uri-id'], 'uid' => $uid])) {
1636                         if (!self::fetchParent($item['parent-uri-id'], $uid, $causer)) {
1637                                 Logger::info('Parent post had not been added', ['uri-id' => $item['parent-uri-id'], 'uid' => $uid, 'causer' => $causer]);
1638                                 return 0;
1639                         }
1640                         Logger::info('Fetched parent post', ['uri-id' => $item['parent-uri-id'], 'uid' => $uid, 'causer' => $causer]);
1641                 } elseif (($uri_id != $item['thr-parent-id']) && $is_reshare && !Post::exists(['uri-id' => $item['thr-parent-id'], 'uid' => $uid])) {
1642                         if (!self::fetchParent($item['thr-parent-id'], $uid, $causer)) {
1643                                 Logger::info('Thread parent had not been added', ['uri-id' => $item['thr-parent-id'], 'uid' => $uid, 'causer' => $causer]);
1644                                 return 0;
1645                         }
1646                         Logger::info('Fetched thread parent', ['uri-id' => $item['thr-parent-id'], 'uid' => $uid, 'causer' => $causer]);
1647                 }
1648
1649                 $stored = self::storeForUser($item, $uid);
1650                 Logger::info('Item stored for user', ['uri-id' => $item['uri-id'], 'uid' => $uid, 'causer' => $causer, 'source-uid' => $source_uid, 'stored' => $stored]);
1651                 return $stored;
1652         }
1653
1654         /**
1655          * Fetch the parent with the given uri-id
1656          *
1657          * @param integer $uri_id
1658          * @param integer $uid
1659          * @param integer $causer
1660          *
1661          * @return integer
1662          */
1663         private static function fetchParent(int $uri_id, int $uid, int $causer): int
1664         {
1665                 // Fetch the origin user for the post
1666                 $origin_uid = self::GetOriginUidForUriId($uri_id, $uid);
1667                 if (is_null($origin_uid)) {
1668                         Logger::info('Origin item was not found', ['uid' => $uid, 'uri-id' => $uri_id]);
1669                         return 0;
1670                 }
1671
1672                 return self::storeForUserByUriId($uri_id, $uid, ['causer-id' => $causer, 'post-reason' => self::PR_FETCHED], $origin_uid);
1673         }
1674
1675         /**
1676          * Returns the origin uid of a post if the given user is allowed to see it.
1677          *
1678          * @param int $uriid
1679          * @param int $uid
1680          * @return int
1681          */
1682         private static function GetOriginUidForUriId(int $uriid, int $uid)
1683         {
1684                 if (Post::exists(['uri-id' => $uriid, 'uid' => $uid])) {
1685                         return $uid;
1686                 }
1687
1688                 $post = Post::selectFirst(['uid', 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid', 'private'], ['uri-id' => $uriid, 'origin' => true]);
1689                 if (!empty($post)) {
1690                         if (in_array($post['private'], [Item::PUBLIC, Item::UNLISTED])) {
1691                                 return $post['uid'];
1692                         }
1693
1694                         $pcid = Contact::getPublicIdByUserId($uid);
1695                         if (empty($pcid)) {
1696                                 return null;
1697                         }
1698
1699                         foreach (Item::enumeratePermissions($post, true) as $receiver) {
1700                                 if ($receiver == $pcid) {
1701                                         return $post['uid'];
1702                                 }
1703                         }
1704
1705                         return null;
1706                 }
1707
1708                 if (Post::exists(['uri-id' => $uriid, 'uid' => 0])) {
1709                         return 0;
1710                 }
1711
1712                 // When the post belongs to a a forum then all forum users are allowed to access it
1713                 foreach (Tag::getByURIId($uriid, [Tag::MENTION, Tag::EXCLUSIVE_MENTION]) as $tag) {
1714                         if (DBA::exists('contact', ['uid' => $uid, 'nurl' => Strings::normaliseLink($tag['url']), 'contact-type' => Contact::TYPE_COMMUNITY])) {
1715                                 $target_uid = User::getIdForURL($tag['url']);
1716                                 if (!empty($target_uid)) {
1717                                         return $target_uid;
1718                                 }
1719                         }
1720                 }
1721
1722                 return null;
1723         }
1724
1725         /**
1726          * Store a public item array for the given users
1727          *
1728          * @param array   $item   The item entry that will be stored
1729          * @param integer $uid    The user that will receive the item entry
1730          * @return integer stored item id
1731          * @throws \Exception
1732          */
1733         private static function storeForUser(array $item, int $uid): int
1734         {
1735                 $post = Post::selectFirst(['id'], ['uri-id' => $item['uri-id'], 'uid' => $uid]);
1736                 if (!empty($post['id'])) {
1737                         if (!empty($item['event-id'])) {
1738                                 $event_post = Post::selectFirst(['event-id'], ['uri-id' => $item['uri-id'], 'uid' => $uid]);
1739                                 if (!empty($event_post['event-id'])) {
1740                                         $event = DBA::selectFirst('event', ['edited', 'start', 'finish', 'summary', 'desc', 'location', 'nofinish', 'adjust'], ['id' => $item['event-id']]);
1741                                         if (!empty($event)) {
1742                                                 // We aren't using "Event::store" here, since we don't want to trigger any further action
1743                                                 $ret = DBA::update('event', $event, ['id' => $event_post['event-id']]);
1744                                                 Logger::info('Event updated', ['uid' => $uid, 'source-event' => $item['event-id'], 'target-event' => $event_post['event-id'], 'ret' => $ret]);
1745                                         }
1746                                 }
1747                         }
1748                         Logger::info('Item already exists', ['uri-id' => $item['uri-id'], 'uid' => $uid, 'id' => $post['id']]);
1749                         return $post['id'];
1750                 }
1751
1752                 // Data from the "post-user" table
1753                 unset($item['id']);
1754                 unset($item['mention']);
1755                 unset($item['starred']);
1756                 unset($item['unseen']);
1757                 unset($item['psid']);
1758                 unset($item['pinned']);
1759                 unset($item['ignored']);
1760                 unset($item['pubmail']);
1761                 unset($item['event-id']);
1762                 unset($item['hidden']);
1763                 unset($item['notification-type']);
1764
1765                 // Data from the "post-delivery-data" table
1766                 unset($item['postopts']);
1767                 unset($item['inform']);
1768
1769                 $item['uid'] = $uid;
1770                 $item['origin'] = 0;
1771                 $item['wall'] = 0;
1772
1773                 $item['contact-id'] = self::contactId($item);
1774
1775                 $notify = false;
1776                 if ($item['gravity'] == self::GRAVITY_PARENT) {
1777                         $contact = DBA::selectFirst('contact', [], ['id' => $item['contact-id'], 'self' => false]);
1778                         if (DBA::isResult($contact)) {
1779                                 $notify = self::isRemoteSelf($contact, $item);
1780                         }
1781                 }
1782
1783                 $distributed = self::insert($item, $notify);
1784
1785                 if (!$distributed) {
1786                         Logger::info("Distributed item wasn't stored", ['uri-id' => $item['uri-id'], 'user' => $uid]);
1787                 } else {
1788                         Logger::info('Distributed item was stored', ['uri-id' => $item['uri-id'], 'user' => $uid, 'stored' => $distributed]);
1789                 }
1790                 return $distributed;
1791         }
1792
1793         /**
1794          * Add a shadow entry for a given item id that is a thread starter
1795          *
1796          * We store every public item entry additionally with the user id "0".
1797          * This is used for the community page and for the search.
1798          * It is planned that in the future we will store public item entries only once.
1799          *
1800          * @param integer $itemid Item ID that should be added
1801          * @throws \Exception
1802          */
1803         private static function addShadow(int $itemid)
1804         {
1805                 $fields = ['uid', 'private', 'visible', 'deleted', 'network', 'uri-id'];
1806                 $condition = ['id' => $itemid, 'gravity' => self::GRAVITY_PARENT];
1807                 $item = Post::selectFirst($fields, $condition);
1808
1809                 if (!DBA::isResult($item)) {
1810                         return;
1811                 }
1812
1813                 // is it already a copy?
1814                 if (($itemid == 0) || ($item['uid'] == 0)) {
1815                         return;
1816                 }
1817
1818                 // Is it a visible public post?
1819                 if (!$item["visible"] || $item["deleted"]  || ($item["private"] == self::PRIVATE)) {
1820                         return;
1821                 }
1822
1823                 // is it an entry from a connector? Only add an entry for natively connected networks
1824                 if (!in_array($item["network"], array_merge(Protocol::FEDERATED ,['']))) {
1825                         return;
1826                 }
1827
1828                 if (Post::exists(['uri-id' => $item['uri-id'], 'uid' => 0])) {
1829                         return;
1830                 }
1831
1832                 $item = Post::selectFirst(array_merge(self::ITEM_FIELDLIST, ['protocol']), ['id' => $itemid]);
1833
1834                 if (DBA::isResult($item)) {
1835                         // Preparing public shadow (removing user specific data)
1836                         $item['uid'] = 0;
1837                         unset($item['id']);
1838                         unset($item['parent']);
1839                         unset($item['wall']);
1840                         unset($item['mention']);
1841                         unset($item['origin']);
1842                         unset($item['starred']);
1843                         unset($item['postopts']);
1844                         unset($item['inform']);
1845                         unset($item['post-reason']);
1846                         if ($item['uri-id'] == $item['parent-uri-id']) {
1847                                 $item['contact-id'] = $item['owner-id'];
1848                         } else {
1849                                 $item['contact-id'] = $item['author-id'];
1850                         }
1851
1852                         $public_shadow = self::insert($item);
1853
1854                         Logger::info('Stored public shadow', ['thread' => $itemid, 'id' => $public_shadow]);
1855                 }
1856         }
1857
1858         /**
1859          * Add a shadow entry for a given item id that is a comment
1860          *
1861          * This function does the same like the function above - but for comments
1862          *
1863          * @param integer $itemid Item ID that should be added
1864          * @throws \Exception
1865          */
1866         private static function addShadowPost(int $itemid)
1867         {
1868                 $item = Post::selectFirst(array_merge(self::ITEM_FIELDLIST, ['protocol']), ['id' => $itemid]);
1869                 if (!DBA::isResult($item)) {
1870                         return;
1871                 }
1872
1873                 // Is it a toplevel post?
1874                 if ($item['gravity'] == self::GRAVITY_PARENT) {
1875                         self::addShadow($itemid);
1876                         return;
1877                 }
1878
1879                 // Is this a shadow entry?
1880                 if ($item['uid'] == 0) {
1881                         return;
1882                 }
1883
1884                 // Is there a shadow parent?
1885                 if (!Post::exists(['uri-id' => $item['parent-uri-id'], 'uid' => 0])) {
1886                         return;
1887                 }
1888
1889                 // Is there already a shadow entry?
1890                 if (Post::exists(['uri-id' => $item['uri-id'], 'uid' => 0])) {
1891                         return;
1892                 }
1893
1894                 // Save "origin" and "parent" state
1895                 $origin = $item['origin'];
1896                 $parent = $item['parent'];
1897
1898                 // Preparing public shadow (removing user specific data)
1899                 $item['uid'] = 0;
1900                 unset($item['id']);
1901                 unset($item['parent']);
1902                 unset($item['wall']);
1903                 unset($item['mention']);
1904                 unset($item['origin']);
1905                 unset($item['starred']);
1906                 unset($item['postopts']);
1907                 unset($item['inform']);
1908                 unset($item['post-reason']);
1909                 $item['contact-id'] = Contact::getIdForURL($item['author-link']);
1910
1911                 $public_shadow = self::insert($item);
1912
1913                 Logger::info('Stored public shadow', ['uri-id' => $item['uri-id'], 'id' => $public_shadow]);
1914
1915                 // If this was a comment to a Diaspora post we don't get our comment back.
1916                 // This means that we have to distribute the comment by ourselves.
1917                 if ($origin && Post::exists(['id' => $parent, 'network' => Protocol::DIASPORA])) {
1918                         self::distribute($public_shadow);
1919                 }
1920         }
1921
1922         /**
1923          * Adds a language specification in a "language" element of given $arr.
1924          * Expects "body" element to exist in $arr.
1925          *
1926          * @param array $item
1927          * @return string detected language
1928          * @throws \Text_LanguageDetect_Exception
1929          */
1930         private static function getLanguage(array $item): string
1931         {
1932                 if (!empty($item['language'])) {
1933                         return $item['language'];
1934                 }
1935
1936                 if (!in_array($item['gravity'], [self::GRAVITY_PARENT, self::GRAVITY_COMMENT]) || empty($item['body'])) {
1937                         return '';
1938                 }
1939
1940                 $languages = self::getLanguageArray(trim($item['title'] . "\n" . $item['body']), 3);
1941                 if (empty($languages)) {
1942                         return '';
1943                 }
1944
1945                 return json_encode($languages);
1946         }
1947
1948         /**
1949          * Get a language array from a given text
1950          *
1951          * @param string  $body
1952          * @param integer $count
1953          * @return array
1954          */
1955         public static function getLanguageArray(string $body, int $count): array
1956         {
1957                 // Convert attachments to links
1958                 $naked_body = BBCode::removeAttachment($body);
1959                 if (empty($naked_body)) {
1960                         return [];
1961                 }
1962
1963                 // Remove links and pictures
1964                 $naked_body = BBCode::removeLinks($naked_body);
1965
1966                 // Convert the title and the body to plain text
1967                 $naked_body = BBCode::toPlaintext($naked_body);
1968
1969                 // Remove possibly remaining links
1970                 $naked_body = preg_replace(Strings::autoLinkRegEx(), '', $naked_body);
1971
1972                 if (empty($naked_body)) {
1973                         return [];
1974                 }
1975
1976                 $naked_body = self::getDominantLanguage($naked_body);
1977
1978                 $availableLanguages = DI::l10n()->getAvailableLanguages();
1979                 // See https://github.com/friendica/friendica/issues/10511
1980                 // Persian is manually added to language detection until a persian translation is provided for the interface, at
1981                 // which point it will be automatically available through `getAvailableLanguages()` and this should be removed.
1982                 $availableLanguages['fa'] = 'fa';
1983
1984                 $ld = new Language(array_keys($availableLanguages));
1985                 return $ld->detect($naked_body)->limit(0, $count)->close() ?: [];
1986         }
1987
1988         /**
1989          * Check if latin or non latin are dominant in the body and only return the dominant one
1990          *
1991          * @param string $body
1992          * @return string
1993          */
1994         private static function getDominantLanguage(string $body): string
1995         {
1996                 $latin = '';
1997                 $non_latin = '';
1998                 for ($i = 0; $i < mb_strlen($body); $i++) {
1999                         $character = mb_substr($body, $i, 1);
2000                         $ord = mb_ord($character);
2001
2002                         // We add the most common characters to both strings.
2003                         if (($ord <= 64) || ($ord >= 91 && $ord <= 96) || ($ord >= 123 && $ord <= 191) || in_array($ord, [215, 247]) || ($ord >= 697 && $ord <= 735) || ($ord > 65535)) {
2004                                 $latin .= $character;
2005                                 $non_latin .= $character;
2006                         } elseif ($ord < 768) {
2007                                 $latin .= $character;
2008                         } else {
2009                                 $non_latin .= $character;
2010                         }
2011                 }
2012                 return (mb_strlen($latin) > mb_strlen($non_latin)) ? $latin : $non_latin;
2013         }
2014
2015         public static function getLanguageMessage(array $item): string
2016         {
2017                 $iso639 = new \Matriphe\ISO639\ISO639;
2018
2019                 $used_languages = '';
2020                 foreach (json_decode($item['language'], true) as $language => $reliability) {
2021                         $used_languages .= $iso639->languageByCode1($language) . ' (' . $language . "): " . number_format($reliability, 5) . '\n';
2022                 }
2023                 $used_languages = DI::l10n()->t('Detected languages in this post:\n%s', $used_languages);
2024                 return $used_languages;
2025         }
2026
2027         /**
2028          * Creates an unique guid out of a given uri.
2029          * This function is used for messages outside the fediverse (Connector posts, feeds, Mails, ...)
2030          * Posts that are created on this system are using System::createUUID.
2031          * Received ActivityPub posts are using Processor::getGUIDByURL.
2032          *
2033          * @param string      $uri uri of an item entry
2034          * @param string|null $host hostname for the GUID prefix
2035          * @return string Unique guid
2036          */
2037         public static function guidFromUri(string $uri, string $host = null): string
2038         {
2039                 // Our regular guid routine is using this kind of prefix as well
2040                 // We have to avoid that different routines could accidentally create the same value
2041                 $parsed = parse_url($uri);
2042
2043                 // Remove the scheme to make sure that "https" and "http" doesn't make a difference
2044                 unset($parsed['scheme']);
2045
2046                 // Glue it together to be able to make a hash from it
2047                 $host_id = implode('/', $parsed);
2048
2049                 // Use a mixture of several hashes to provide some GUID like experience
2050                 return hash('crc32', $host) . '-'. hash('joaat', $host_id) . '-'. hash('fnv164', $host_id);
2051         }
2052
2053         /**
2054          * generate an unique URI
2055          *
2056          * @param string $guid An existing GUID (Otherwise it will be generated)
2057          *
2058          * @return string
2059          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2060          */
2061         public static function newURI(string $guid = ''): string
2062         {
2063                 if ($guid == '') {
2064                         $guid = System::createUUID();
2065                 }
2066
2067                 return DI::baseUrl()->get() . '/objects/' . $guid;
2068         }
2069
2070         /**
2071          * Set "success_update" and "last-item" to the date of the last time we heard from this contact
2072          *
2073          * This can be used to filter for inactive contacts.
2074          * Only do this for public postings to avoid privacy problems, since poco data is public.
2075          * Don't set this value if it isn't from the owner (could be an author that we don't know)
2076          *
2077          * @param array $arr Contains the just posted item record
2078          * @throws \Exception
2079          */
2080         private static function updateContact(array $arr)
2081         {
2082                 // Unarchive the author
2083                 $contact = DBA::selectFirst('contact', [], ['id' => $arr["author-id"]]);
2084                 if (DBA::isResult($contact)) {
2085                         Contact::unmarkForArchival($contact);
2086                 }
2087
2088                 // Unarchive the contact if it's not our own contact
2089                 $contact = DBA::selectFirst('contact', [], ['id' => $arr["contact-id"], 'self' => false]);
2090                 if (DBA::isResult($contact)) {
2091                         Contact::unmarkForArchival($contact);
2092                 }
2093
2094                 /// @todo On private posts we could obfuscate the date
2095                 $update = ($arr['private'] != self::PRIVATE) || in_array($arr['network'], Protocol::FEDERATED);
2096
2097                 // Is it a forum? Then we don't care about the rules from above
2098                 if (!$update && in_array($arr["network"], [Protocol::ACTIVITYPUB, Protocol::DFRN]) && ($arr["parent-uri-id"] === $arr["uri-id"])) {
2099                         if (DBA::exists('contact', ['id' => $arr['contact-id'], 'forum' => true])) {
2100                                 $update = true;
2101                         }
2102                 }
2103
2104                 if ($update) {
2105                         // The "self" contact id is used (for example in the connectors) when the contact is unknown
2106                         // So we have to ensure to only update the last item when it had been our own post,
2107                         // or it had been done by a "regular" contact.
2108                         if (!empty($arr['wall'])) {
2109                                 $condition = ['id' => $arr['contact-id']];
2110                         } else {
2111                                 $condition = ['id' => $arr['contact-id'], 'self' => false];
2112                         }
2113                         Contact::update(['failed' => false, 'local-data' => true, 'success_update' => $arr['received'], 'last-item' => $arr['received']], $condition);
2114                 }
2115                 // Now do the same for the system wide contacts with uid=0
2116                 if ($arr['private'] != self::PRIVATE) {
2117                         Contact::update(['failed' => false, 'local-data' => true, 'success_update' => $arr['received'], 'last-item' => $arr['received']],
2118                                 ['id' => $arr['owner-id']]);
2119
2120                         if ($arr['owner-id'] != $arr['author-id']) {
2121                                 Contact::update(['failed' => false, 'local-data' => true, 'success_update' => $arr['received'], 'last-item' => $arr['received']],
2122                                         ['id' => $arr['author-id']]);
2123                         }
2124                 }
2125         }
2126
2127         public static function setHashtags(string $body): string
2128         {
2129                 $body = BBCode::performWithEscapedTags($body, ['noparse', 'pre', 'code', 'img'], function ($body) {
2130                         $tags = BBCode::getTags($body);
2131
2132                         // No hashtags?
2133                         if (!count($tags)) {
2134                                 return $body;
2135                         }
2136
2137                         // This sorting is important when there are hashtags that are part of other hashtags
2138                         // Otherwise there could be problems with hashtags like #test and #test2
2139                         // Because of this we are sorting from the longest to the shortest tag.
2140                         usort($tags, function ($a, $b) {
2141                                 return strlen($b) <=> strlen($a);
2142                         });
2143
2144                         $URLSearchString = "^\[\]";
2145
2146                         // All hashtags should point to the home server if "local_tags" is activated
2147                         if (DI::config()->get('system', 'local_tags')) {
2148                                 $body = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
2149                                         "#[url=" . DI::baseUrl() . "/search?tag=$2]$2[/url]", $body);
2150                         }
2151
2152                         // mask hashtags inside of url, bookmarks and attachments to avoid urls in urls
2153                         $body = preg_replace_callback("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
2154                                 function ($match) {
2155                                         return ("[url=" . str_replace("#", "&num;", $match[1]) . "]" . str_replace("#", "&num;", $match[2]) . "[/url]");
2156                                 }, $body);
2157
2158                         $body = preg_replace_callback("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism",
2159                                 function ($match) {
2160                                         return ("[bookmark=" . str_replace("#", "&num;", $match[1]) . "]" . str_replace("#", "&num;", $match[2]) . "[/bookmark]");
2161                                 }, $body);
2162
2163                         $body = preg_replace_callback("/\[attachment (.*?)\](.*?)\[\/attachment\]/ism",
2164                                 function ($match) {
2165                                         return ("[attachment " . str_replace("#", "&num;", $match[1]) . "]" . $match[2] . "[/attachment]");
2166                                 }, $body);
2167
2168                         // Repair recursive urls
2169                         $body = preg_replace("/&num;\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
2170                                 "&num;$2", $body);
2171
2172                         foreach ($tags as $tag) {
2173                                 if ((strpos($tag, '#') !== 0) || strpos($tag, '[url=') || strlen($tag) < 2 || $tag[1] == '#') {
2174                                         continue;
2175                                 }
2176
2177                                 $basetag = str_replace('_', ' ', substr($tag, 1));
2178                                 $newtag = '#[url=' . DI::baseUrl() . '/search?tag=' . $basetag . ']' . $basetag . '[/url]';
2179
2180                                 $body = str_replace($tag, $newtag, $body);
2181                         }
2182
2183                         // Convert back the masked hashtags
2184                         $body = str_replace("&num;", "#", $body);
2185
2186                         return $body;
2187                 });
2188
2189                 return $body;
2190         }
2191
2192         /**
2193          * look for mention tags and setup a second delivery chain for forum/community posts if appropriate
2194          *
2195          * @param int $uid
2196          * @param int $item_id
2197          * @return boolean true if item was deleted, else false
2198          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2199          * @throws \ImagickException
2200          */
2201         private static function tagDeliver(int $uid, int $item_id): bool
2202         {
2203                 $mention = false;
2204
2205                 $owner = User::getOwnerDataById($uid);
2206                 if (!DBA::isResult($owner)) {
2207                         Logger::warning('User not found, quitting here.', ['uid' => $uid]);
2208                         return false;
2209                 }
2210
2211                 if ($owner['contact-type'] != User::ACCOUNT_TYPE_COMMUNITY) {
2212                         Logger::debug('Owner is no community, quitting here.', ['uid' => $uid, 'id' => $item_id]);
2213                         return false;
2214                 }
2215
2216                 $item = Post::selectFirst(self::ITEM_FIELDLIST, ['id' => $item_id, 'gravity' => [self::GRAVITY_PARENT, self::GRAVITY_COMMENT], 'origin' => false]);
2217                 if (!DBA::isResult($item)) {
2218                         Logger::debug('Post is an activity or origin or not found at all, quitting here.', ['id' => $item_id]);
2219                         return false;
2220                 }
2221
2222                 if ($item['gravity'] == self::GRAVITY_PARENT) {
2223                         if (Tag::isMentioned($item['uri-id'], $owner['url'])) {
2224                                 Logger::info('Mention found in tag.', ['uri' => $item['uri'], 'uid' => $uid, 'id' => $item_id, 'uri-id' => $item['uri-id'], 'guid' => $item['guid']]);
2225                         } else {
2226                                 Logger::info('Top-level post without mention is deleted.', ['uri' => $item['uri'], $uid, 'id' => $item_id, 'uri-id' => $item['uri-id'], 'guid' => $item['guid']]);
2227                                 Post\User::delete(['uri-id' => $item['uri-id'], 'uid' => $item['uid']]);
2228                                 return true;
2229                         }
2230
2231                         $arr = ['item' => $item, 'user' => $owner];
2232
2233                         Hook::callAll('tagged', $arr);
2234                 } else {
2235                         if (Tag::isMentioned($item['parent-uri-id'], $owner['url'])) {
2236                                 Logger::info('Mention found in parent tag.', ['uri' => $item['uri'], 'uid' => $uid, 'id' => $item_id, 'uri-id' => $item['uri-id'], 'guid' => $item['guid']]);
2237                         } else {
2238                                 Logger::debug('No mentions found in parent, quitting here.', ['id' => $item_id, 'uri-id' => $item['uri-id'], 'guid' => $item['guid']]);
2239                                 return false;
2240                         }
2241                 }
2242
2243                 Logger::info('Community post will be distributed', ['uri' => $item['uri'], 'uid' => $uid, 'id' => $item_id, 'uri-id' => $item['uri-id'], 'guid' => $item['guid']]);
2244
2245                 if ($owner['page-flags'] == User::PAGE_FLAGS_PRVGROUP) {
2246                         $allow_cid = '';
2247                         $allow_gid = '<' . Group::FOLLOWERS . '>';
2248                         $deny_cid  = '';
2249                         $deny_gid  = '';
2250                         self::performActivity($item['id'], 'announce', $uid, $allow_cid, $allow_gid, $deny_cid, $deny_gid);
2251                 } else {
2252                         self::performActivity($item['id'], 'announce', $uid);
2253                 }
2254
2255                 Logger::info('Community post had been distributed', ['uri' => $item['uri'], 'uid' => $uid, 'id' => $item_id, 'uri-id' => $item['uri-id'], 'guid' => $item['guid']]);
2256                 return false;
2257         }
2258
2259         /**
2260          * Automatically reshare the item if the "remote_self" option is selected
2261          *
2262          * @param array $item
2263          * @return void
2264          */
2265         private static function autoReshare(array $item)
2266         {
2267                 if ($item['gravity'] != self::GRAVITY_PARENT) {
2268                         return;
2269                 }
2270
2271                 if (!DBA::exists('contact', ['id' => $item['contact-id'], 'remote_self' => Contact::MIRROR_NATIVE_RESHARE])) {
2272                         return;
2273                 }
2274
2275                 if (!in_array($item['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN])) {
2276                         return;
2277                 }
2278
2279                 Logger::info('Automatically reshare item', ['uid' => $item['uid'], 'id' => $item['id'], 'guid' => $item['guid'], 'uri-id' => $item['uri-id']]);
2280
2281                 self::performActivity($item['id'], 'announce', $item['uid']);
2282         }
2283
2284         public static function isRemoteSelf(array $contact, array &$datarray): bool
2285         {
2286                 if (!$contact['remote_self']) {
2287                         return false;
2288                 }
2289
2290                 // Prevent the forwarding of posts that are forwarded
2291                 if (!empty($datarray["extid"]) && ($datarray["extid"] == Protocol::DFRN)) {
2292                         Logger::info('Already forwarded');
2293                         return false;
2294                 }
2295
2296                 // Prevent to forward already forwarded posts
2297                 if ($datarray["app"] == DI::baseUrl()->getHostname()) {
2298                         Logger::info('Already forwarded (second test)');
2299                         return false;
2300                 }
2301
2302                 // Only forward posts
2303                 if ($datarray["verb"] != Activity::POST) {
2304                         Logger::info('No post');
2305                         return false;
2306                 }
2307
2308                 if (($contact['network'] != Protocol::FEED) && ($datarray['private'] == self::PRIVATE)) {
2309                         Logger::info('Not public');
2310                         return false;
2311                 }
2312
2313                 $datarray2 = $datarray;
2314                 Logger::info('remote-self start', ['contact' => $contact['url'], 'remote_self'=> $contact['remote_self'], 'item' => $datarray]);
2315                 if ($contact['remote_self'] == Contact::MIRROR_OWN_POST) {
2316                         $self = DBA::selectFirst('contact', ['id', 'name', 'url', 'thumb'],
2317                                         ['uid' => $contact['uid'], 'self' => true]);
2318                         if (DBA::isResult($self)) {
2319                                 $datarray['contact-id'] = $self["id"];
2320
2321                                 $datarray['owner-name'] = $self["name"];
2322                                 $datarray['owner-link'] = $self["url"];
2323                                 $datarray['owner-avatar'] = $self["thumb"];
2324
2325                                 $datarray['author-name']   = $datarray['owner-name'];
2326                                 $datarray['author-link']   = $datarray['owner-link'];
2327                                 $datarray['author-avatar'] = $datarray['owner-avatar'];
2328
2329                                 unset($datarray['edited']);
2330
2331                                 unset($datarray['network']);
2332                                 unset($datarray['owner-id']);
2333                                 unset($datarray['author-id']);
2334                         }
2335
2336                         if ($contact['network'] != Protocol::FEED) {
2337                                 $old_uri_id = $datarray["uri-id"] ?? 0;
2338                                 $datarray["guid"] = System::createUUID();
2339                                 unset($datarray["plink"]);
2340                                 $datarray["uri"] = self::newURI($datarray["guid"]);
2341                                 $datarray["uri-id"] = ItemURI::getIdByURI($datarray["uri"]);
2342                                 $datarray["extid"] = Protocol::DFRN;
2343                                 $urlpart = parse_url($datarray2['author-link']);
2344                                 $datarray["app"] = $urlpart["host"];
2345                                 if (!empty($old_uri_id)) {
2346                                         Post\Media::copy($old_uri_id, $datarray["uri-id"]);
2347                                 }
2348
2349                                 unset($datarray["parent-uri"]);
2350                                 unset($datarray["thr-parent"]);
2351                         } else {
2352                                 $datarray['private'] = self::PUBLIC;
2353                         }
2354                 }
2355
2356                 if ($contact['network'] != Protocol::FEED) {
2357                         // Store the original post
2358                         $result = self::insert($datarray2);
2359                         Logger::info('remote-self post original item', ['contact' => $contact['url'], 'result'=> $result, 'item' => $datarray2]);
2360                 } else {
2361                         $datarray["app"] = "Feed";
2362                         $result = true;
2363                 }
2364
2365                 return (bool)$result;
2366         }
2367
2368         /**
2369          *
2370          * @param string $s
2371          * @param int    $uid
2372          * @param array  $item
2373          * @param int    $cid
2374          * @return string
2375          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2376          * @throws \ImagickException
2377          */
2378         public static function fixPrivatePhotos(string $s, int $uid, array $item = null, int $cid = 0): string
2379         {
2380                 if (DI::config()->get('system', 'disable_embedded')) {
2381                         return $s;
2382                 }
2383
2384                 Logger::info('check for photos');
2385                 $site = substr(DI::baseUrl(), strpos(DI::baseUrl(), '://'));
2386
2387                 $orig_body = $s;
2388                 $new_body = '';
2389
2390                 $img_start = strpos($orig_body, '[img');
2391                 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
2392                 $img_len = ($img_start !== false ? strpos(substr($orig_body, $img_start + $img_st_close + 1), '[/img]') : false);
2393
2394                 while (($img_st_close !== false) && ($img_len !== false)) {
2395                         $img_st_close++; // make it point to AFTER the closing bracket
2396                         $image = substr($orig_body, $img_start + $img_st_close, $img_len);
2397
2398                         Logger::info('found photo', ['image' => $image]);
2399
2400                         if (stristr($image, $site . '/photo/')) {
2401                                 // Only embed locally hosted photos
2402                                 $replace = false;
2403                                 $i = basename($image);
2404                                 $i = str_replace(['.jpg', '.png', '.gif'], ['', '', ''], $i);
2405                                 $x = strpos($i, '-');
2406
2407                                 if ($x) {
2408                                         $res = substr($i, $x + 1);
2409                                         $i = substr($i, 0, $x);
2410                                         $photo = Photo::getPhotoForUser($uid, $i, $res);
2411                                         if (DBA::isResult($photo)) {
2412                                                 /*
2413                                                  * Check to see if we should replace this photo link with an embedded image
2414                                                  * 1. No need to do so if the photo is public
2415                                                  * 2. If there's a contact-id provided, see if they're in the access list
2416                                                  *    for the photo. If so, embed it.
2417                                                  * 3. Otherwise, if we have an item, see if the item permissions match the photo
2418                                                  *    permissions, regardless of order but first check to see if they're an exact
2419                                                  *    match to save some processing overhead.
2420                                                  */
2421                                                 if (self::hasPermissions($photo)) {
2422                                                         if ($cid) {
2423                                                                 $recips = self::enumeratePermissions($photo);
2424                                                                 if (in_array($cid, $recips)) {
2425                                                                         $replace = true;
2426                                                                 }
2427                                                         } elseif ($item) {
2428                                                                 if (self::samePermissions($uid, $item, $photo)) {
2429                                                                         $replace = true;
2430                                                                 }
2431                                                         }
2432                                                 }
2433                                                 if ($replace) {
2434                                                         $photo_img = Photo::getImageForPhoto($photo);
2435                                                         // If a custom width and height were specified, apply before embedding
2436                                                         if (preg_match("/\[img\=([0-9]*)x([0-9]*)\]/is", substr($orig_body, $img_start, $img_st_close), $match)) {
2437                                                                 Logger::info('scaling photo');
2438
2439                                                                 $width = intval($match[1]);
2440                                                                 $height = intval($match[2]);
2441
2442                                                                 $photo_img->scaleDown(max($width, $height));
2443                                                         }
2444
2445                                                         $data = $photo_img->asString();
2446                                                         $type = $photo_img->getType();
2447
2448                                                         Logger::info('replacing photo');
2449                                                         $image = 'data:' . $type . ';base64,' . base64_encode($data);
2450                                                         Logger::debug('replaced', ['image' => $image]);
2451                                                 }
2452                                         }
2453                                 }
2454                         }
2455
2456                         $new_body = $new_body . substr($orig_body, 0, $img_start + $img_st_close) . $image . '[/img]';
2457                         $orig_body = substr($orig_body, $img_start + $img_st_close + $img_len + strlen('[/img]'));
2458                         if ($orig_body === false) {
2459                                 $orig_body = '';
2460                         }
2461
2462                         $img_start = strpos($orig_body, '[img');
2463                         $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
2464                         $img_len = ($img_start !== false ? strpos(substr($orig_body, $img_start + $img_st_close + 1), '[/img]') : false);
2465                 }
2466
2467                 $new_body = $new_body . $orig_body;
2468
2469                 return $new_body;
2470         }
2471
2472         private static function hasPermissions(array $obj)
2473         {
2474                 return !empty($obj['allow_cid']) || !empty($obj['allow_gid']) ||
2475                         !empty($obj['deny_cid']) || !empty($obj['deny_gid']);
2476         }
2477
2478         // @TODO $uid is unused parameter
2479         private static function samePermissions($uid, array $obj1, array $obj2): bool
2480         {
2481                 // first part is easy. Check that these are exactly the same.
2482                 if (($obj1['allow_cid'] == $obj2['allow_cid'])
2483                         && ($obj1['allow_gid'] == $obj2['allow_gid'])
2484                         && ($obj1['deny_cid'] == $obj2['deny_cid'])
2485                         && ($obj1['deny_gid'] == $obj2['deny_gid'])) {
2486                         return true;
2487                 }
2488
2489                 // This is harder. Parse all the permissions and compare the resulting set.
2490                 $recipients1 = self::enumeratePermissions($obj1);
2491                 $recipients2 = self::enumeratePermissions($obj2);
2492                 sort($recipients1);
2493                 sort($recipients2);
2494
2495                 /// @TODO Comparison of arrays, maybe use array_diff_assoc() here?
2496                 return ($recipients1 == $recipients2);
2497         }
2498
2499         /**
2500          * Returns an array of contact-ids that are allowed to see this object
2501          *
2502          * @param array $obj        Item array with at least uid, allow_cid, allow_gid, deny_cid and deny_gid
2503          * @param bool  $check_dead Prunes unavailable contacts from the result
2504          * @return array
2505          * @throws \Exception
2506          */
2507         public static function enumeratePermissions(array $obj, bool $check_dead = false): array
2508         {
2509                 $aclFormater = DI::aclFormatter();
2510
2511                 $allow_people = $aclFormater->expand($obj['allow_cid']);
2512                 $allow_groups = Group::expand($obj['uid'], $aclFormater->expand($obj['allow_gid']), $check_dead);
2513                 $deny_people  = $aclFormater->expand($obj['deny_cid']);
2514                 $deny_groups  = Group::expand($obj['uid'], $aclFormater->expand($obj['deny_gid']), $check_dead);
2515                 $recipients   = array_unique(array_merge($allow_people, $allow_groups));
2516                 $deny         = array_unique(array_merge($deny_people, $deny_groups));
2517                 $recipients   = array_diff($recipients, $deny);
2518                 return $recipients;
2519         }
2520
2521         public static function expire(int $uid, int $days, string $network = "", bool $force = false)
2522         {
2523                 if (!$uid || ($days < 1)) {
2524                         return;
2525                 }
2526
2527                 $condition = ["`uid` = ? AND NOT `deleted` AND `gravity` = ?",
2528                         $uid, self::GRAVITY_PARENT];
2529
2530                 /*
2531                  * $expire_network_only = save your own wall posts
2532                  * and just expire conversations started by others
2533                  */
2534                 $expire_network_only = DI::pConfig()->get($uid, 'expire', 'network_only', false);
2535
2536                 if ($expire_network_only) {
2537                         $condition[0] .= " AND NOT `wall`";
2538                 }
2539
2540                 if ($network != "") {
2541                         $condition[0] .= " AND `network` = ?";
2542                         $condition[] = $network;
2543                 }
2544
2545                 $condition[0] .= " AND `received` < ?";
2546                 $condition[] = DateTimeFormat::utc('now - ' . $days . ' day');
2547
2548                 $items = Post::select(['resource-id', 'starred', 'id', 'post-type', 'uid', 'uri-id'], $condition);
2549
2550                 if (!DBA::isResult($items)) {
2551                         return;
2552                 }
2553
2554                 $expire_items = (bool)DI::pConfig()->get($uid, 'expire', 'items', true);
2555
2556                 // Forcing expiring of items - but not notes and marked items
2557                 if ($force) {
2558                         $expire_items = true;
2559                 }
2560
2561                 $expire_notes = (bool)DI::pConfig()->get($uid, 'expire', 'notes', true);
2562                 $expire_starred = (bool)DI::pConfig()->get($uid, 'expire', 'starred', true);
2563                 $expire_photos = (bool)DI::pConfig()->get($uid, 'expire', 'photos', false);
2564
2565                 $expired = 0;
2566
2567                 $priority = DI::config()->get('system', 'expire-notify-priority');
2568
2569                 while ($item = Post::fetch($items)) {
2570                         // don't expire filed items
2571                         if (DBA::exists('post-category', ['uri-id' => $item['uri-id'], 'uid' => $item['uid'], 'type' => Post\Category::FILE])) {
2572                                 continue;
2573                         }
2574
2575                         // Only expire posts, not photos and photo comments
2576
2577                         if (!$expire_photos && !empty($item['resource-id'])) {
2578                                 continue;
2579                         } elseif (!$expire_starred && intval($item['starred'])) {
2580                                 continue;
2581                         } elseif (!$expire_notes && ($item['post-type'] == self::PT_PERSONAL_NOTE)) {
2582                                 continue;
2583                         } elseif (!$expire_items && ($item['post-type'] != self::PT_PERSONAL_NOTE)) {
2584                                 continue;
2585                         }
2586
2587                         self::markForDeletionById($item['id'], $priority);
2588
2589                         ++$expired;
2590                 }
2591                 DBA::close($items);
2592                 Logger::notice('Expired', ['user' => $uid, 'days' => $days, 'network' => $network, 'force' => $force, 'expired' => $expired, 'expire items' => $expire_items, 'expire notes' => $expire_notes, 'expire starred' => $expire_starred, 'expire photos' => $expire_photos, 'condition' => $condition]);
2593         }
2594
2595         public static function firstPostDate(int $uid, bool $wall = false)
2596         {
2597                 $user = User::getById($uid, ['register_date']);
2598                 if (empty($user)) {
2599                         return false;
2600                 }
2601
2602                 $condition = ["`uid` = ? AND `wall` = ? AND NOT `deleted` AND `visible` AND `received` >= ?",
2603                         $uid, $wall, $user['register_date']];
2604                 $params = ['order' => ['received' => false]];
2605                 $thread = Post::selectFirstThread(['received'], $condition, $params);
2606                 if (DBA::isResult($thread)) {
2607                         $postdate = substr(DateTimeFormat::local($thread['received']), 0, 10);
2608                         return $postdate;
2609                 }
2610                 return false;
2611         }
2612
2613         /**
2614          * add/remove activity to an item
2615          *
2616          * Toggle activities as like,dislike,attend of an item
2617          *
2618          * @param int    $item_id
2619          * @param string $verb
2620          *            Activity verb. One of
2621          *            like, unlike, dislike, undislike, attendyes, unattendyes,
2622          *            attendno, unattendno, attendmaybe, unattendmaybe,
2623          *            announce, unannouce
2624          * @param int    $uid
2625          * @param string $allow_cid
2626          * @param string $allow_gid
2627          * @param string $deny_cid
2628          * @param string $deny_gid
2629          * @return bool
2630          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2631          * @throws \ImagickException
2632          * @hook  'post_local_end'
2633          *            array $arr
2634          *            'post_id' => ID of posted item
2635          */
2636         public static function performActivity(int $item_id, string $verb, int $uid, string $allow_cid = null, string $allow_gid = null, string $deny_cid = null, string $deny_gid = null): bool
2637         {
2638                 if (empty($uid)) {
2639                         return false;
2640                 }
2641
2642                 Logger::notice('Start create activity', ['verb' => $verb, 'item' => $item_id, 'user' => $uid]);
2643
2644                 $item = Post::selectFirst(self::ITEM_FIELDLIST, ['id' => $item_id]);
2645                 if (!DBA::isResult($item)) {
2646                         Logger::warning('Post had not been fetched', ['id' => $item_id]);
2647                         return false;
2648                 }
2649
2650                 $uri_id = $item['uri-id'];
2651
2652                 if (!in_array($item['uid'], [0, $uid])) {
2653                         return false;
2654                 }
2655
2656                 if (!Post::exists(['uri-id' => $item['parent-uri-id'], 'uid' => $uid])) {
2657                         $stored = self::storeForUserByUriId($item['parent-uri-id'], $uid, ['post-reason' => Item::PR_ACTIVITY]);
2658                         if (($item['parent-uri-id'] == $item['uri-id']) && !empty($stored)) {
2659                                 $item = Post::selectFirst(self::ITEM_FIELDLIST, ['id' => $stored]);
2660                                 if (!DBA::isResult($item)) {
2661                                         Logger::info('Could not fetch just created item - should not happen', ['stored' => $stored, 'uid' => $uid, 'uri-id' => $uri_id]);
2662                                         return false;
2663                                 }
2664                         }
2665                 }
2666
2667                 // Retrieves the local post owner
2668                 $owner = User::getOwnerDataById($uid);
2669                 if (empty($owner)) {
2670                         Logger::info('Empty owner for user', ['uid' => $uid]);
2671                         return false;
2672                 }
2673
2674                 // Retrieve the current logged in user's public contact
2675                 $author_id = Contact::getPublicIdByUserId($uid);
2676                 if (empty($author_id)) {
2677                         Logger::info('Empty public contact');
2678                         return false;
2679                 }
2680
2681                 $activity = null;
2682                 switch ($verb) {
2683                         case 'like':
2684                         case 'unlike':
2685                                 $activity = Activity::LIKE;
2686                                 break;
2687                         case 'dislike':
2688                         case 'undislike':
2689                                 $activity = Activity::DISLIKE;
2690                                 break;
2691                         case 'attendyes':
2692                         case 'unattendyes':
2693                                 $activity = Activity::ATTEND;
2694                                 break;
2695                         case 'attendno':
2696                         case 'unattendno':
2697                                 $activity = Activity::ATTENDNO;
2698                                 break;
2699                         case 'attendmaybe':
2700                         case 'unattendmaybe':
2701                                 $activity = Activity::ATTENDMAYBE;
2702                                 break;
2703                         case 'follow':
2704                         case 'unfollow':
2705                                 $activity = Activity::FOLLOW;
2706                                 break;
2707                         case 'announce':
2708                         case 'unannounce':
2709                                 $activity = Activity::ANNOUNCE;
2710                                 break;
2711                         default:
2712                                 Logger::warning('unknown verb', ['verb' => $verb, 'item' => $item_id]);
2713                                 return false;
2714                 }
2715
2716                 $mode = Strings::startsWith($verb, 'un') ? 'delete' : 'create';
2717
2718                 // Enable activity toggling instead of on/off
2719                 $event_verb_flag = $activity === Activity::ATTEND || $activity === Activity::ATTENDNO || $activity === Activity::ATTENDMAYBE;
2720
2721                 // Look for an existing verb row
2722                 // Event participation activities are mutually exclusive, only one of them can exist at all times.
2723                 if ($event_verb_flag) {
2724                         $verbs = [Activity::ATTEND, Activity::ATTENDNO, Activity::ATTENDMAYBE];
2725
2726                         // Translate to the index based activity index
2727                         $vids = [];
2728                         foreach ($verbs as $verb) {
2729                                 $vids[] = Verb::getID($verb);
2730                         }
2731                 } else {
2732                         $vids = Verb::getID($activity);
2733                 }
2734
2735                 $condition = ['vid' => $vids, 'deleted' => false, 'gravity' => self::GRAVITY_ACTIVITY,
2736                         'author-id' => $author_id, 'uid' => $uid, 'thr-parent-id' => $uri_id];
2737                 $like_item = Post::selectFirst(['id', 'guid', 'verb'], $condition);
2738
2739                 if (DBA::isResult($like_item)) {
2740                         /**
2741                          * Truth table for existing activities
2742                          *
2743                          * |          Inputs            ||      Outputs      |
2744                          * |----------------------------||-------------------|
2745                          * |  Mode  | Event | Same verb || Delete? | Return? |
2746                          * |--------|-------|-----------||---------|---------|
2747                          * | create |  Yes  |    Yes    ||   No    |   Yes   |
2748                          * | create |  Yes  |    No     ||   Yes   |   No    |
2749                          * | create |  No   |    Yes    ||   No    |   Yes   |
2750                          * | create |  No   |    No     ||        N/A†       |
2751                          * | delete |  Yes  |    Yes    ||   Yes   |   N/A‡  |
2752                          * | delete |  Yes  |    No     ||   No    |   N/A‡  |
2753                          * | delete |  No   |    Yes    ||   Yes   |   N/A‡  |
2754                          * | delete |  No   |    No     ||        N/A†       |
2755                          * |--------|-------|-----------||---------|---------|
2756                          * |   A    |   B   |     C     || A xor C | !B or C |
2757                          *
2758                          * â€  Can't happen: It's impossible to find an existing non-event activity without
2759                          *                 the same verb because we are only looking for this single verb.
2760                          *
2761                          * â€¡ The "mode = delete" is returning early whether an existing activity was found or not.
2762                          */
2763                         if ($mode == 'create' xor $like_item['verb'] == $activity) {
2764                                 self::markForDeletionById($like_item['id']);
2765                         }
2766
2767                         if (!$event_verb_flag || $like_item['verb'] == $activity) {
2768                                 return true;
2769                         }
2770                 }
2771
2772                 // No need to go further if we aren't creating anything
2773                 if ($mode == 'delete') {
2774                         return true;
2775                 }
2776
2777                 $objtype = $item['resource-id'] ? Activity\ObjectType::IMAGE : Activity\ObjectType::NOTE;
2778
2779                 $new_item = [
2780                         'guid'          => System::createUUID(),
2781                         'uri'           => self::newURI(),
2782                         'uid'           => $uid,
2783                         'contact-id'    => $owner['id'],
2784                         'wall'          => $item['wall'],
2785                         'origin'        => 1,
2786                         'network'       => Protocol::DFRN,
2787                         'protocol'      => Conversation::PARCEL_DIRECT,
2788                         'direction'     => Conversation::PUSH,
2789                         'gravity'       => self::GRAVITY_ACTIVITY,
2790                         'parent'        => $item['id'],
2791                         'thr-parent'    => $item['uri'],
2792                         'owner-id'      => $author_id,
2793                         'author-id'     => $author_id,
2794                         'body'          => $activity,
2795                         'verb'          => $activity,
2796                         'object-type'   => $objtype,
2797                         'allow_cid'     => $allow_cid ?? $item['allow_cid'],
2798                         'allow_gid'     => $allow_gid ?? $item['allow_gid'],
2799                         'deny_cid'      => $deny_cid ?? $item['deny_cid'],
2800                         'deny_gid'      => $deny_gid ?? $item['deny_gid'],
2801                         'visible'       => 1,
2802                         'unseen'        => 1,
2803                 ];
2804
2805                 if (in_array($activity, [Activity::LIKE, Activity::DISLIKE])) {
2806                         $signed = Diaspora::createLikeSignature($uid, $new_item);
2807                         if (!empty($signed)) {
2808                                 $new_item['diaspora_signed_text'] = json_encode($signed);
2809                         }
2810                 }
2811
2812                 self::insert($new_item, true);
2813
2814                 // If the parent item isn't visible then set it to visible
2815                 // @todo Check if this is still needed
2816                 if (!$item['visible']) {
2817                         self::update(['visible' => true], ['id' => $item['id']]);
2818                 }
2819                 return true;
2820         }
2821
2822         /**
2823          * Fetch the SQL condition for the given user id
2824          *
2825          * @param integer $owner_id User ID for which the permissions should be fetched
2826          * @return array condition
2827          */
2828         public static function getPermissionsConditionArrayByUserId(int $owner_id): array
2829         {
2830                 $local_user = DI::userSession()->getLocalUserId();
2831                 $remote_user = DI::userSession()->getRemoteContactID($owner_id);
2832
2833                 // default permissions - anonymous user
2834                 $condition = ["`private` != ?", self::PRIVATE];
2835
2836                 if ($local_user && ($local_user == $owner_id)) {
2837                         // Profile owner - everything is visible
2838                         $condition = [];
2839                 } elseif ($remote_user) {
2840                          // Authenticated visitor - fetch the matching permissionsets
2841                         $permissionSets = DI::permissionSet()->selectByContactId($remote_user, $owner_id);
2842                         if (!empty($set)) {
2843                                 $condition = ["(`private` != ? OR (`private` = ? AND `wall`
2844                                         AND `psid` IN (" . implode(', ', array_fill(0, count($set), '?')) . ")))",
2845                                         self::PRIVATE, self::PRIVATE];
2846                                 $condition = array_merge($condition, $permissionSets->column('id'));
2847                         }
2848                 }
2849
2850                 return $condition;
2851         }
2852
2853         /**
2854          * Get a permission SQL string for the given user
2855          *
2856          * @param int $owner_id
2857          * @param string $table
2858          * @return string
2859          */
2860         public static function getPermissionsSQLByUserId(int $owner_id, string $table = ''): string
2861         {
2862                 $local_user = DI::userSession()->getLocalUserId();
2863                 $remote_user = DI::userSession()->getRemoteContactID($owner_id);
2864
2865                 if (!empty($table)) {
2866                         $table = DBA::quoteIdentifier($table) . '.';
2867                 }
2868
2869                 /*
2870                  * Construct permissions
2871                  *
2872                  * default permissions - anonymous user
2873                  */
2874                 $sql = sprintf(" AND " . $table . "`private` != %d", self::PRIVATE);
2875
2876                 // Profile owner - everything is visible
2877                 if ($local_user && ($local_user == $owner_id)) {
2878                         $sql = '';
2879                 } elseif ($remote_user) {
2880                         /*
2881                          * Authenticated visitor. Unless pre-verified,
2882                          * check that the contact belongs to this $owner_id
2883                          * and load the groups the visitor belongs to.
2884                          * If pre-verified, the caller is expected to have already
2885                          * done this and passed the groups into this function.
2886                          */
2887                         $permissionSets = DI::permissionSet()->selectByContactId($remote_user, $owner_id);
2888
2889                         if (!empty($set)) {
2890                                 $sql_set = sprintf(" OR (" . $table . "`private` = %d AND " . $table . "`wall` AND " . $table . "`psid` IN (", self::PRIVATE) . implode(',', $permissionSets->column('id')) . "))";
2891                         } else {
2892                                 $sql_set = '';
2893                         }
2894
2895                         $sql = sprintf(" AND (" . $table . "`private` != %d", self::PRIVATE) . $sql_set . ")";
2896                 }
2897
2898                 return $sql;
2899         }
2900
2901         /**
2902          * get translated item type
2903          *
2904          * @param array                $item
2905          * @param \Friendica\Core\L10n $l10n
2906          * @return string
2907          */
2908         public static function postType(array $item, \Friendica\Core\L10n $l10n): string
2909         {
2910                 if (!empty($item['event-id'])) {
2911                         return $l10n->t('event');
2912                 } elseif (!empty($item['resource-id'])) {
2913                         return $l10n->t('photo');
2914                 } elseif ($item['gravity'] == self::GRAVITY_ACTIVITY) {
2915                         return $l10n->t('activity');
2916                 } elseif ($item['gravity'] == self::GRAVITY_COMMENT) {
2917                         return $l10n->t('comment');
2918                 }
2919
2920                 return $l10n->t('post');
2921         }
2922
2923         /**
2924          * Sets the "rendered-html" field of the provided item
2925          *
2926          * Body is preserved to avoid side-effects as we modify it just-in-time for spoilers and private image links
2927          *
2928          * @param array $item
2929          *
2930          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2931          * @todo Remove reference, simply return "rendered-html" and "rendered-hash"
2932          */
2933         private static function putInCache(&$item)
2934         {
2935                 // Save original body to prevent addons to modify it
2936                 $body = $item['body'];
2937
2938                 $rendered_hash = $item['rendered-hash'] ?? '';
2939                 $rendered_html = $item['rendered-html'] ?? '';
2940
2941                 if ($rendered_hash == ''
2942                         || $rendered_html == ''
2943                         || $rendered_hash != hash('md5', BBCode::VERSION . '::' . $body)
2944                         || DI::config()->get('system', 'ignore_cache')
2945                 ) {
2946                         $item['rendered-html'] = BBCode::convertForUriId($item['uri-id'], $item['body']);
2947                         $item['rendered-hash'] = hash('md5', BBCode::VERSION . '::' . $body);
2948
2949                         $hook_data = ['item' => $item, 'rendered-html' => $item['rendered-html'], 'rendered-hash' => $item['rendered-hash']];
2950                         Hook::callAll('put_item_in_cache', $hook_data);
2951                         $item['rendered-html'] = $hook_data['rendered-html'];
2952                         $item['rendered-hash'] = $hook_data['rendered-hash'];
2953                         unset($hook_data);
2954
2955                         // Update if the generated values differ from the existing ones
2956                         if ((($rendered_hash != $item['rendered-hash']) || ($rendered_html != $item['rendered-html'])) && !empty($item['id'])) {
2957                                 self::update(
2958                                         [
2959                                                 'rendered-html' => $item['rendered-html'],
2960                                                 'rendered-hash' => $item['rendered-hash']
2961                                         ],
2962                                         ['id' => $item['id']]
2963                                 );
2964                         }
2965                 }
2966
2967                 $item['body'] = $body;
2968         }
2969
2970         /**
2971          * Given an item array, convert the body element from bbcode to html and add smilie icons.
2972          * If attach is true, also add icons for item attachments.
2973          *
2974          * @param array   $item Record from item table
2975          * @param boolean $attach If true, add icons for item attachments as well
2976          * @param boolean $is_preview Whether this is a preview
2977          * @param boolean $only_cache Whether only cached HTML should be updated
2978          * @return string item body html
2979          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2980          * @throws \ImagickException
2981          * @hook  prepare_body_init item array before any work
2982          * @hook  prepare_body_content_filter ('item'=>item array, 'filter_reasons'=>string array) before first bbcode to html
2983          * @hook  prepare_body ('item'=>item array, 'html'=>body string, 'is_preview'=>boolean, 'filter_reasons'=>string array) after first bbcode to html
2984          * @hook  prepare_body_final ('item'=>item array, 'html'=>body string) after attach icons and blockquote special case handling (spoiler, author)
2985          */
2986         public static function prepareBody(array &$item, bool $attach = false, bool $is_preview = false, bool $only_cache = false): string
2987         {
2988                 $a = DI::app();
2989                 Hook::callAll('prepare_body_init', $item);
2990
2991                 // In order to provide theme developers more possibilities, event items
2992                 // are treated differently.
2993                 if ($item['object-type'] === Activity\ObjectType::EVENT && isset($item['event-id'])) {
2994                         $ev = Event::getItemHTML($item);
2995                         return $ev;
2996                 }
2997
2998                 $tags = Tag::populateFromItem($item);
2999
3000                 $item['tags'] = $tags['tags'];
3001                 $item['hashtags'] = $tags['hashtags'];
3002                 $item['mentions'] = $tags['mentions'];
3003
3004                 $body = $item['body'] ?? '';
3005
3006                 $fields = ['uri-id', 'uri', 'body', 'title', 'author-name', 'author-link', 'author-avatar', 'guid', 'created', 'plink', 'network', 'has-media', 'quote-uri-id', 'post-type'];
3007
3008                 $shared_uri_id = 0;
3009                 $shared_links  = [];
3010
3011                 $shared = DI::contentItem()->getSharedPost($item, $fields);
3012                 if (!empty($shared['post'])) {
3013                         $shared_item  = $shared['post'];
3014                         $quote_uri_id = $shared['post']['uri-id'];
3015                         $shared_links[] = strtolower($shared['post']['uri']);
3016                         $item['body'] = BBCode::removeSharedData($item['body']);
3017                 } elseif (empty($shared_item['uri-id']) && empty($item['quote-uri-id']) && ($item['network'] != Protocol::DIASPORA)) {
3018                         $media = Post\Media::getByURIId($item['uri-id'], [Post\Media::ACTIVITY]);
3019                         if (!empty($media)) {
3020                                 $shared_item = Post::selectFirst($fields, ['plink' => $media[0]['url'], 'uid' => [$item['uid'], 0]]);
3021
3022                                 if (empty($shared_item['uri-id'])) {
3023                                         $shared_item = Post::selectFirst($fields, ['uri' => $media[0]['url'], 'uid' => [$item['uid'], 0]]);
3024                                         $shared_links[] = strtolower($media[0]['url']);
3025                                 }
3026
3027                                 $quote_uri_id = $shared_item['uri-id'] ?? 0;
3028                         }
3029                 }
3030
3031                 if (!empty($quote_uri_id)) {
3032                         $item['body'] .= "\n" . DI::contentItem()->createSharedBlockByArray($shared_item);
3033                 }
3034
3035                 if (!empty($shared_item['uri-id'])) {
3036                         $shared_uri_id = $shared_item['uri-id'];
3037                         $shared_links[] = strtolower($shared_item['plink']);
3038                         $shared_attachments = Post\Media::splitAttachments($shared_uri_id, [], $shared_item['has-media']);
3039                         $shared_links = array_merge($shared_links, array_column($shared_attachments['visual'], 'url'));
3040                         $shared_links = array_merge($shared_links, array_column($shared_attachments['link'], 'url'));
3041                         $shared_links = array_merge($shared_links, array_column($shared_attachments['additional'], 'url'));
3042                         $item['body'] = self::replaceVisualAttachments($shared_attachments, $item['body']);
3043                 }
3044
3045                 $attachments = Post\Media::splitAttachments($item['uri-id'], $shared_links, $item['has-media'] ?? false);
3046                 $item['body'] = self::replaceVisualAttachments($attachments, $item['body'] ?? '');
3047
3048                 $item['body'] = preg_replace("/\s*\[attachment .*?\].*?\[\/attachment\]\s*/ism", "\n", $item['body']);
3049                 self::putInCache($item);
3050                 $item['body'] = $body;
3051                 $s = $item["rendered-html"];
3052
3053                 if ($only_cache) {
3054                         return '';
3055                 }
3056
3057                 // Compile eventual content filter reasons
3058                 $filter_reasons = [];
3059                 if (!$is_preview && DI::userSession()->getPublicContactId() != $item['author-id']) {
3060                         if (!empty($item['content-warning']) && (!DI::userSession()->getLocalUserId() || !DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'system', 'disable_cw', false))) {
3061                                 $filter_reasons[] = DI::l10n()->t('Content warning: %s', $item['content-warning']);
3062                         }
3063
3064                         $item['attachments'] = $attachments;
3065
3066                         $hook_data = [
3067                                 'item' => $item,
3068                                 'filter_reasons' => $filter_reasons
3069                         ];
3070                         Hook::callAll('prepare_body_content_filter', $hook_data);
3071                         $filter_reasons = $hook_data['filter_reasons'];
3072                         unset($hook_data);
3073                 }
3074
3075                 $hook_data = [
3076                         'item' => $item,
3077                         'html' => $s,
3078                         'preview' => $is_preview,
3079                         'filter_reasons' => $filter_reasons
3080                 ];
3081                 Hook::callAll('prepare_body', $hook_data);
3082                 $s = $hook_data['html'];
3083                 unset($hook_data);
3084
3085                 if (!$attach) {
3086                         // Replace the blockquotes with quotes that are used in mails.
3087                         $mailquote = '<blockquote type="cite" class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex;">';
3088                         $s = str_replace(['<blockquote>', '<blockquote class="spoiler">', '<blockquote class="author">'], [$mailquote, $mailquote, $mailquote], $s);
3089                         return $s;
3090                 }
3091
3092                 if (!empty($shared_attachments)) {
3093                         $s = self::addVisualAttachments($shared_attachments, $shared_item, $s, true);
3094                         $s = self::addLinkAttachment($shared_uri_id ?: $item['uri-id'], $shared_attachments, $body, $s, true, []);
3095                         $s = self::addNonVisualAttachments($shared_attachments, $item, $s, true);
3096                         $body = BBCode::removeSharedData($body);
3097                 }
3098
3099                 $s = self::addVisualAttachments($attachments, $item, $s, false);
3100                 $s = self::addLinkAttachment($item['uri-id'], $attachments, $body, $s, false, $shared_links);
3101                 $s = self::addNonVisualAttachments($attachments, $item, $s, false);
3102                 $s = self::addQuestions($item, $s);
3103
3104                 // Map.
3105                 if (strpos($s, '<div class="map">') !== false && !empty($item['coord'])) {
3106                         $x = Map::byCoordinates(trim($item['coord']));
3107                         if ($x) {
3108                                 $s = preg_replace('/\<div class\=\"map\"\>/', '$0' . $x, $s);
3109                         }
3110                 }
3111
3112                 // Replace friendica image url size with theme preference.
3113                 if (!empty($a->getThemeInfoValue('item_image_size'))) {
3114                         $ps = $a->getThemeInfoValue('item_image_size');
3115                         $s = preg_replace('|(<img[^>]+src="[^"]+/photo/[0-9a-f]+)-[0-9]|', "$1-" . $ps, $s);
3116                 }
3117
3118                 $s = HTML::applyContentFilter($s, $filter_reasons);
3119
3120                 $hook_data = ['item' => $item, 'html' => $s];
3121                 Hook::callAll('prepare_body_final', $hook_data);
3122
3123                 return $hook_data['html'];
3124         }
3125
3126         /**
3127          * Check if the body contains a link
3128          *
3129          * @param string $body
3130          * @param string $url
3131          * @param int    $type
3132          * @return bool
3133          */
3134         public static function containsLink(string $body, string $url, int $type = 0): bool
3135         {
3136                 // Make sure that for example site parameters aren't used when testing if the link is contained in the body
3137                 $urlparts = parse_url($url);
3138                 if (empty($urlparts)) {
3139                         return false;
3140                 }
3141
3142                 unset($urlparts['query']);
3143                 unset($urlparts['fragment']);
3144
3145                 try {
3146                         $url = (string)Uri::fromParts($urlparts);
3147                 } catch (\InvalidArgumentException $e) {
3148                         DI::logger()->notice('Invalid URL', ['$url' => $url, '$urlparts' => $urlparts]);
3149                         /* See https://github.com/friendica/friendica/issues/12113
3150                          * Malformed URLs will result in a Fatal Error
3151                          */
3152                         return false;
3153                 }
3154
3155                 // Remove media links to only search in embedded content
3156                 // @todo Check images for image link, audio for audio links, ...
3157                 if (in_array($type, [Post\Media::AUDIO, Post\Media::VIDEO, Post\Media::IMAGE])) {
3158                         $body = preg_replace("/\[url=[^\[\]]*\](.*)\[\/url\]/Usi", ' $1 ', $body);
3159                 }
3160
3161                 if (strpos($body, $url)) {
3162                         return true;
3163                 }
3164
3165                 foreach ([0, 1, 2] as $size) {
3166                         if (preg_match('#/photo/.*-' . $size . '\.#ism', $url) &&
3167                                 strpos(preg_replace('#(/photo/.*)-[012]\.#ism', '$1-' . $size . '.', $body), $url)) {
3168                                 return true;
3169                         }
3170                 }
3171
3172                 return false;
3173         }
3174
3175         /**
3176          * Replace visual attachments in the body
3177          *
3178          * @param array $attachments
3179          * @param string $body
3180          * @return string modified body
3181          */
3182         private static function replaceVisualAttachments(array $attachments, string $body): string
3183         {
3184                 DI::profiler()->startRecording('rendering');
3185
3186                 foreach ($attachments['visual'] as $attachment) {
3187                         if (!empty($attachment['preview'])) {
3188                                 $proxy   = Post\Media::getPreviewUrlForId($attachment['id'], Proxy::SIZE_LARGE);
3189                                 $search  = ['[img=' . $attachment['preview'] . ']', ']' . $attachment['preview'] . '[/img]'];
3190                                 $replace = ['[img=' . $proxy . ']', ']' . $proxy . '[/img]'];
3191
3192                                 $body = str_replace($search, $replace, $body);
3193                         } elseif ($attachment['filetype'] == 'image') {
3194                                 $proxy   = Post\Media::getUrlForId($attachment['id']);
3195                                 $search  = ['[img=' . $attachment['url'] . ']', ']' . $attachment['url'] . '[/img]'];
3196                                 $replace = ['[img=' . $proxy . ']', ']' . $proxy . '[/img]'];
3197
3198                                 $body = str_replace($search, $replace, $body);
3199                         }
3200                 }
3201                 DI::profiler()->stopRecording();
3202                 return $body;
3203         }
3204
3205         /**
3206          * Add visual attachments to the content
3207          *
3208          * @param array $attachments
3209          * @param array $item
3210          * @param string $content
3211          * @return string modified content
3212          */
3213         private static function addVisualAttachments(array $attachments, array $item, string $content, bool $shared): string
3214         {
3215                 DI::profiler()->startRecording('rendering');
3216                 $leading = '';
3217                 $trailing = '';
3218
3219                 // @todo In the future we should make a single for the template engine with all media in it. This allows more flexibilty.
3220                 foreach ($attachments['visual'] as $attachment) {
3221                         if (self::containsLink($item['body'], $attachment['preview'] ?? $attachment['url'], $attachment['type'])) {
3222                                 continue;
3223                         }
3224
3225                         if ($attachment['filetype'] == 'image') {
3226                                 $preview_url = Post\Media::getPreviewUrlForId($attachment['id'], ($attachment['width'] > $attachment['height']) ? Proxy::SIZE_MEDIUM : Proxy::SIZE_LARGE);
3227                         } elseif (!empty($attachment['preview'])) {
3228                                 $preview_url = Post\Media::getPreviewUrlForId($attachment['id'], Proxy::SIZE_LARGE);
3229                         } else {
3230                                 $preview_url = '';
3231                         }
3232
3233                         if ($preview_url && self::containsLink($item['body'], $preview_url)) {
3234                                 continue;
3235                         }
3236
3237                         if (($attachment['filetype'] == 'video')) {
3238                                 /// @todo Move the template to /content as well
3239                                 $media = Renderer::replaceMacros(Renderer::getMarkupTemplate('video_top.tpl'), [
3240                                         '$video' => [
3241                                                 'id'      => $attachment['id'],
3242                                                 'src'     => $attachment['url'],
3243                                                 'name'    => $attachment['name'] ?: $attachment['url'],
3244                                                 'preview' => $preview_url,
3245                                                 'mime'    => $attachment['mimetype'],
3246                                         ],
3247                                 ]);
3248                                 if (($item['post-type'] ?? null) == Item::PT_VIDEO) {
3249                                         $leading .= $media;
3250                                 } else {
3251                                         $trailing .= $media;
3252                                 }
3253                         } elseif ($attachment['filetype'] == 'audio') {
3254                                 $media = Renderer::replaceMacros(Renderer::getMarkupTemplate('content/audio.tpl'), [
3255                                         '$audio' => [
3256                                                 'id'     => $attachment['id'],
3257                                                 'src'    => $attachment['url'],
3258                                                 'name'   => $attachment['name'] ?: $attachment['url'],
3259                                                 'mime'   => $attachment['mimetype'],
3260                                         ],
3261                                 ]);
3262                                 if (($item['post-type'] ?? null) == Item::PT_AUDIO) {
3263                                         $leading .= $media;
3264                                 } else {
3265                                         $trailing .= $media;
3266                                 }
3267                         } elseif ($attachment['filetype'] == 'image') {
3268                                 $src_url = Post\Media::getUrlForId($attachment['id']);
3269                                 if (self::containsLink($item['body'], $src_url)) {
3270                                         continue;
3271                                 }
3272                                 $media = Renderer::replaceMacros(Renderer::getMarkupTemplate('content/image.tpl'), [
3273                                         '$image' => [
3274                                                 'src'        => $src_url,
3275                                                 'preview'    => $preview_url,
3276                                                 'attachment' => $attachment,
3277                                         ],
3278                                 ]);
3279                                 // On Diaspora posts the attached pictures are leading
3280                                 if ($item['network'] == Protocol::DIASPORA) {
3281                                         $leading .= $media;
3282                                 } else {
3283                                         $trailing .= $media;
3284                                 }
3285                         }
3286                 }
3287
3288                 if ($shared) {
3289                         $content = str_replace(BBCode::TOP_ANCHOR, '<div class="body-attach">' . $leading . '<div class="clear"></div></div>' . BBCode::TOP_ANCHOR, $content);
3290                         $content = str_replace(BBCode::BOTTOM_ANCHOR, '<div class="body-attach">' . $trailing . '<div class="clear"></div></div>' . BBCode::BOTTOM_ANCHOR, $content);
3291                 } else {
3292                         if ($leading != '') {
3293                                 $content = '<div class="body-attach">' . $leading . '<div class="clear"></div></div>' . $content;
3294                         }
3295
3296                         if ($trailing != '') {
3297                                 $content .= '<div class="body-attach">' . $trailing . '<div class="clear"></div></div>';
3298                         }
3299                 }
3300
3301                 DI::profiler()->stopRecording();
3302                 return $content;
3303         }
3304
3305         /**
3306          * Add link attachment to the content
3307          *
3308          * @param array  $attachments
3309          * @param string $body
3310          * @param string $content
3311          * @param bool   $shared
3312          * @param array  $ignore_links A list of URLs to ignore
3313          * @return string modified content
3314          */
3315         private static function addLinkAttachment(int $uriid, array $attachments, string $body, string $content, bool $shared, array $ignore_links): string
3316         {
3317                 DI::profiler()->startRecording('rendering');
3318                 // Don't show a preview when there is a visual attachment (audio or video)
3319                 $types = array_column($attachments['visual'], 'type');
3320                 $preview = !in_array(Post\Media::IMAGE, $types) && !in_array(Post\Media::VIDEO, $types);
3321
3322                 if (!empty($attachments['link'])) {
3323                         foreach ($attachments['link'] as $link) {
3324                                 $found = false;
3325                                 foreach ($ignore_links as $ignore_link) {
3326                                         if (Strings::compareLink($link['url'], $ignore_link)) {
3327                                                 $found = true;
3328                                         }
3329                                 }
3330                                 // @todo Judge between the links to use the one with most information
3331                                 if (!$found && (empty($attachment) || !empty($link['author-name']) ||
3332                                         (empty($attachment['name']) && !empty($link['name'])) ||
3333                                         (empty($attachment['description']) && !empty($link['description'])) ||
3334                                         (empty($attachment['preview']) && !empty($link['preview'])))) {
3335                                         $attachment = $link;
3336                                 }
3337                         }
3338                 }
3339
3340                 if (!empty($attachment)) {
3341                         $data = [
3342                                 'after' => '',
3343                                 'author_name' => $attachment['author-name'] ?? '',
3344                                 'author_url' =>  $attachment['author-url'] ?? '',
3345                                 'description' => $attachment['description'] ?? '',
3346                                 'image' => '',
3347                                 'preview' => '',
3348                                 'provider_name' => $attachment['publisher-name'] ?? '',
3349                                 'provider_url' => $attachment['publisher-url'] ?? '',
3350                                 'text' => '',
3351                                 'title' => $attachment['name'] ?? '',
3352                                 'type' => 'link',
3353                                 'url' => $attachment['url']];
3354
3355                         if ($preview && !empty($attachment['preview'])) {
3356                                 if ($attachment['preview-width'] >= 500) {
3357                                         $data['image'] = Post\Media::getPreviewUrlForId($attachment['id'], Proxy::SIZE_MEDIUM);
3358                                 } else {
3359                                         $data['preview'] = Post\Media::getPreviewUrlForId($attachment['id'], Proxy::SIZE_MEDIUM);
3360                                 }
3361                         }
3362
3363                         if (!empty($data['description']) && !empty($content)) {
3364                                 similar_text($data['description'], $content, $percent);
3365                         } else {
3366                                 $percent = 0;
3367                         }
3368
3369                         if (!empty($data['description']) && (($data['title'] == $data['description']) || ($percent > 95) || (strpos($content, $data['description']) !== false))) {
3370                                 $data['description'] = '';
3371                         }
3372
3373                         if (($data['author_name'] ?? '') == ($data['provider_name'] ?? '')) {
3374                                 $data['author_name'] = '';
3375                         }
3376
3377                         if (($data['author_url'] ?? '') == ($data['provider_url'] ?? '')) {
3378                                 $data['author_url'] = '';
3379                         }
3380                 } elseif (preg_match("/.*(\[attachment.*?\].*?\[\/attachment\]).*/ism", $body, $match)) {
3381                         $data = BBCode::getAttachmentData($match[1]);
3382                 }
3383                 DI::profiler()->stopRecording();
3384
3385                 if (isset($data['url']) && !in_array(strtolower($data['url']), $ignore_links)) {
3386                         if (!empty($data['description']) || !empty($data['image']) || !empty($data['preview'])) {
3387                                 $parts = parse_url($data['url']);
3388                                 if (!empty($parts['scheme']) && !empty($parts['host'])) {
3389                                         if (empty($data['provider_name'])) {
3390                                                 $data['provider_name'] = $parts['host'];
3391                                         }
3392                                         if (empty($data['provider_url']) || empty(parse_url($data['provider_url'], PHP_URL_SCHEME))) {
3393                                                 $data['provider_url'] = $parts['scheme'] . '://' . $parts['host'];
3394
3395                                                 if (!empty($parts['port'])) {
3396                                                         $data['provider_url'] .= ':' . $parts['port'];
3397                                                 }
3398                                         }
3399                                 }
3400
3401                                 // @todo Use a template
3402                                 $rendered = BBCode::convertAttachment('', BBCode::INTERNAL, false, $data, $uriid);
3403                         } elseif (!self::containsLink($content, $data['url'], Post\Media::HTML)) {
3404                                 $rendered = Renderer::replaceMacros(Renderer::getMarkupTemplate('content/link.tpl'), [
3405                                         '$url'  => $data['url'],
3406                                         '$title' => $data['title'],
3407                                 ]);
3408                         } else {
3409                                 return $content;
3410                         }
3411
3412                         if ($shared) {
3413                                 return str_replace(BBCode::BOTTOM_ANCHOR, BBCode::BOTTOM_ANCHOR . $rendered, $content);
3414                         } else {
3415                                 return $content . $rendered;
3416                         }
3417                 }
3418                 return $content;
3419         }
3420
3421         /**
3422          * Add non visual attachments to the content
3423          *
3424          * @param array $attachments
3425          * @param array $item
3426          * @param string $content
3427          * @return string modified content
3428          */
3429         private static function addNonVisualAttachments(array $attachments, array $item, string $content): string
3430         {
3431                 DI::profiler()->startRecording('rendering');
3432                 $trailing = '';
3433                 foreach ($attachments['additional'] as $attachment) {
3434                         if (strpos($item['body'], $attachment['url'])) {
3435                                 continue;
3436                         }
3437
3438                         $author = ['uid' => 0, 'id' => $item['author-id'],
3439                                 'network' => $item['author-network'], 'url' => $item['author-link']];
3440                         $the_url = Contact::magicLinkByContact($author, $attachment['url']);
3441
3442                         $title = Strings::escapeHtml(trim(($attachment['description'] ?? '') ?: $attachment['url']));
3443
3444                         if (!empty($attachment['size'])) {
3445                                 $title .= ' ' . $attachment['size'] . ' ' . DI::l10n()->t('bytes');
3446                         }
3447
3448                         /// @todo Use a template
3449                         $icon = '<div class="attachtype icon s22 type-' . $attachment['filetype'] . ' subtype-' . $attachment['subtype'] . '"></div>';
3450                         $trailing .= '<a href="' . strip_tags($the_url) . '" title="' . $title . '" class="attachlink" target="_blank" rel="noopener noreferrer" >' . $icon . '</a>';
3451                 }
3452
3453                 if ($trailing != '') {
3454                         $content .= '<div class="body-attach">' . $trailing . '<div class="clear"></div></div>';
3455                 }
3456
3457                 DI::profiler()->stopRecording();
3458                 return $content;
3459         }
3460
3461         private static function addQuestions(array $item, string $content): string
3462         {
3463                 DI::profiler()->startRecording('rendering');
3464                 if (!empty($item['question-id'])) {
3465                         $question = [
3466                                 'id'       => $item['question-id'],
3467                                 'multiple' => $item['question-multiple'],
3468                                 'voters'   => $item['question-voters'],
3469                                 'endtime'  => $item['question-end-time']
3470                         ];
3471
3472                         $options = Post\QuestionOption::getByURIId($item['uri-id']);
3473                         foreach ($options as $key => $option) {
3474                                 if ($question['voters'] > 0) {
3475                                         $percent = $option['replies'] / $question['voters'] * 100;
3476                                         $options[$key]['vote'] = DI::l10n()->tt('%2$s (%3$d%%, %1$d vote)', '%2$s (%3$d%%, %1$d votes)', $option['replies'], $option['name'], round($percent, 1));
3477                                 } else {
3478                                         $options[$key]['vote'] = DI::l10n()->tt('%2$s (%1$d vote)', '%2$s (%1$d votes)', $option['replies'], $option['name']);
3479                                 }
3480                         }
3481
3482                         if (!empty($question['voters']) && !empty($question['endtime'])) {
3483                                 $summary = DI::l10n()->tt('%d voter. Poll end: %s', '%d voters. Poll end: %s', $question['voters'], Temporal::getRelativeDate($question['endtime']));
3484                         } elseif (!empty($question['voters'])) {
3485                                 $summary = DI::l10n()->tt('%d voter.', '%d voters.', $question['voters']);
3486                         } elseif (!empty($question['endtime'])) {
3487                                 $summary = DI::l10n()->t('Poll end: %s', Temporal::getRelativeDate($question['endtime']));
3488                         } else {
3489                                 $summary = '';
3490                         }
3491
3492                         $content .= Renderer::replaceMacros(Renderer::getMarkupTemplate('content/question.tpl'), [
3493                                 '$question' => $question,
3494                                 '$options'  => $options,
3495                                 '$summary'  => $summary,
3496                         ]);
3497         }
3498                 DI::profiler()->stopRecording();
3499                 return $content;
3500         }
3501
3502         /**
3503          * get private link for item
3504          *
3505          * @param array $item
3506          * @return boolean|array False if item has not plink, otherwise array('href'=>plink url, 'title'=>translated title)
3507          * @throws \Exception
3508          */
3509         public static function getPlink(array $item)
3510         {
3511                 if (!empty($item['plink']) && Network::isValidHttpUrl($item['plink'])) {
3512                         $plink = $item['plink'];
3513                 } elseif (!empty($item['uri']) && Network::isValidHttpUrl($item['uri']) && !Network::isLocalLink($item['uri'])) {
3514                         $plink = $item['uri'];
3515                 }
3516
3517                 if (DI::userSession()->getLocalUserId()) {
3518                         $ret = [
3519                                 'href' => "display/" . $item['guid'],
3520                                 'orig' => "display/" . $item['guid'],
3521                                 'title' => DI::l10n()->t('View on separate page'),
3522                                 'orig_title' => DI::l10n()->t('View on separate page'),
3523                         ];
3524
3525                         if (!empty($plink) && ($item['private'] == self::PRIVATE)) {
3526                                 $author = ['uid' => 0, 'id' => $item['author-id'],
3527                                         'network' => $item['author-network'], 'url' => $item['author-link']];
3528                                 $plink = Contact::magicLinkByContact($author, $plink);
3529                         }
3530
3531                         if (!empty($plink)) {
3532                                 $ret['href'] = DI::baseUrl()->remove($plink);
3533                                 $ret['title'] = DI::l10n()->t('Link to source');
3534                         }
3535                 } elseif (!empty($plink) && ($item['private'] != self::PRIVATE)) {
3536                         $ret = [
3537                                 'href' => $plink,
3538                                 'orig' => $plink,
3539                                 'title' => DI::l10n()->t('Link to source'),
3540                                 'orig_title' => DI::l10n()->t('Link to source'),
3541                         ];
3542                 } else {
3543                         $ret = [];
3544                 }
3545
3546                 return $ret;
3547         }
3548
3549         /**
3550          * Does the given uri-id belongs to a post that is sent as starting post to a forum?
3551          *
3552          * @param int $uri_id
3553          *
3554          * @return boolean "true" when it is a forum post
3555          */
3556         public static function isForumPost(int $uri_id): bool
3557         {
3558                 foreach (Tag::getByURIId($uri_id, [Tag::EXCLUSIVE_MENTION]) as $tag) {
3559                         if (DBA::exists('contact', ['uid' => 0, 'nurl' => Strings::normaliseLink($tag['url']), 'contact-type' => Contact::TYPE_COMMUNITY])) {
3560                                 return true;
3561                         }
3562                 }
3563                 return false;
3564         }
3565
3566         /**
3567          * Search item id for given URI or plink
3568          *
3569          * @param string $uri
3570          * @param integer $uid
3571          *
3572          * @return integer item id
3573          */
3574         public static function searchByLink(string $uri, int $uid = 0): int
3575         {
3576                 $ssl_uri = str_replace('http://', 'https://', $uri);
3577                 $uris = [$uri, $ssl_uri, Strings::normaliseLink($uri)];
3578
3579                 $item = Post::selectFirst(['id'], ['uri' => $uris, 'uid' => $uid]);
3580                 if (DBA::isResult($item)) {
3581                         return $item['id'];
3582                 }
3583
3584                 $item = Post::selectFirst(['id'], ['plink' => $uris, 'uid' => $uid]);
3585                 if (DBA::isResult($item)) {
3586                         return $item['id'];
3587                 }
3588
3589                 return 0;
3590         }
3591
3592         /**
3593          * Return the URI for a link to the post
3594          *
3595          * @param string $uri URI or link to post
3596          *
3597          * @return string URI
3598          */
3599         public static function getURIByLink(string $uri): string
3600         {
3601                 $ssl_uri = str_replace('http://', 'https://', $uri);
3602                 $uris = [$uri, $ssl_uri, Strings::normaliseLink($uri)];
3603
3604                 $item = Post::selectFirst(['uri'], ['uri' => $uris]);
3605                 if (DBA::isResult($item)) {
3606                         return $item['uri'];
3607                 }
3608
3609                 $item = Post::selectFirst(['uri'], ['plink' => $uris]);
3610                 if (DBA::isResult($item)) {
3611                         return $item['uri'];
3612                 }
3613
3614                 return '';
3615         }
3616
3617         /**
3618          * Fetches item for given URI or plink
3619          *
3620          * @param string $uri
3621          * @param integer $uid
3622          *
3623          * @return integer item id
3624          */
3625         public static function fetchByLink(string $uri, int $uid = 0): int
3626         {
3627                 Logger::info('Trying to fetch link', ['uid' => $uid, 'uri' => $uri]);
3628                 $item_id = self::searchByLink($uri, $uid);
3629                 if (!empty($item_id)) {
3630                         Logger::info('Link found', ['uid' => $uid, 'uri' => $uri, 'id' => $item_id]);
3631                         return $item_id;
3632                 }
3633
3634                 $hookData = [
3635                         'uri'     => $uri,
3636                         'uid'     => $uid,
3637                         'item_id' => null,
3638                 ];
3639
3640                 Hook::callAll('item_by_link', $hookData);
3641
3642                 if (isset($hookData['item_id'])) {
3643                         return is_numeric($hookData['item_id']) ? $hookData['item_id'] : 0;
3644                 }
3645
3646                 $fetched_uri = ActivityPub\Processor::fetchMissingActivity($uri);
3647
3648                 if ($fetched_uri) {
3649                         $item_id = self::searchByLink($fetched_uri, $uid);
3650                 } else {
3651                         $item_id = Diaspora::fetchByURL($uri);
3652                 }
3653
3654                 if (!empty($item_id)) {
3655                         Logger::info('Link fetched', ['uid' => $uid, 'uri' => $uri, 'id' => $item_id]);
3656                         return $item_id;
3657                 }
3658
3659                 Logger::info('Link not found', ['uid' => $uid, 'uri' => $uri]);
3660                 return 0;
3661         }
3662
3663         /**
3664          * Check a prospective item array against user-level permissions
3665          *
3666          * @param array $item Expected keys: uri, gravity, and
3667          *                    author-link if is author-id is set,
3668          *                    owner-link if is owner-id is set,
3669          *                    causer-link if is causer-id is set.
3670          * @param int   $user_id Local user ID
3671          * @return bool
3672          * @throws \Exception
3673          */
3674         protected static function isAllowedByUser(array $item, int $user_id): bool
3675         {
3676                 if (!empty($item['author-id']) && Contact\User::isBlocked($item['author-id'], $user_id)) {
3677                         Logger::notice('Author is blocked by user', ['author-link' => $item['author-link'], 'uid' => $user_id, 'item-uri' => $item['uri']]);
3678                         return false;
3679                 }
3680
3681                 if (!empty($item['owner-id']) && Contact\User::isBlocked($item['owner-id'], $user_id)) {
3682                         Logger::notice('Owner is blocked by user', ['owner-link' => $item['owner-link'], 'uid' => $user_id, 'item-uri' => $item['uri']]);
3683                         return false;
3684                 }
3685
3686                 // The causer is set during a thread completion, for example because of a reshare. It countains the responsible actor.
3687                 if (!empty($item['causer-id']) && Contact\User::isBlocked($item['causer-id'], $user_id)) {
3688                         Logger::notice('Causer is blocked by user', ['causer-link' => $item['causer-link'] ?? $item['causer-id'], 'uid' => $user_id, 'item-uri' => $item['uri']]);
3689                         return false;
3690                 }
3691
3692                 if (!empty($item['causer-id']) && ($item['gravity'] === self::GRAVITY_PARENT) && Contact\User::isIgnored($item['causer-id'], $user_id)) {
3693                         Logger::notice('Causer is ignored by user', ['causer-link' => $item['causer-link'] ?? $item['causer-id'], 'uid' => $user_id, 'item-uri' => $item['uri']]);
3694                         return false;
3695                 }
3696
3697                 return true;
3698         }
3699
3700         /**
3701          * Fetch the uri-id of a quote
3702          *
3703          * @param string $body
3704          * @return integer
3705          */
3706         public static function getQuoteUriId(string $body, int $uid = 0): int
3707         {
3708                 $shared = BBCode::fetchShareAttributes($body);
3709                 if (empty($shared['guid']) && empty($shared['message_id'])) {
3710                         return 0;
3711                 }
3712
3713                 if (empty($shared['link']) && empty($shared['message_id'])) {
3714                         Logger::notice('Invalid share block.', ['share' => $shared]);
3715                         return 0;
3716                 }
3717
3718                 if (!empty($shared['guid'])) {
3719                         $shared_item = Post::selectFirst(['uri-id'], ['guid' => $shared['guid'], 'uid' => [0, $uid]]);
3720                         if (!empty($shared_item['uri-id'])) {
3721                                 Logger::debug('Found post by guid', ['guid' => $shared['guid'], 'uid' => $uid]);
3722                                 return $shared_item['uri-id'];
3723                         }
3724                 }
3725
3726                 if (!empty($shared['message_id'])) {
3727                         $shared_item = Post::selectFirst(['uri-id'], ['uri' => $shared['message_id'], 'uid' => [0, $uid]]);
3728                         if (!empty($shared_item['uri-id'])) {
3729                                 Logger::debug('Found post by message_id', ['message_id' => $shared['message_id'], 'uid' => $uid]);
3730                                 return $shared_item['uri-id'];
3731                         }
3732                 }
3733
3734                 if (!empty($shared['link'])) {
3735                         $shared_item = Post::selectFirst(['uri-id'], ['plink' => $shared['link'], 'uid' => [0, $uid]]);
3736                         if (!empty($shared_item['uri-id'])) {
3737                                 Logger::debug('Found post by link', ['link' => $shared['link'], 'uid' => $uid]);
3738                                 return $shared_item['uri-id'];
3739                         }
3740                 }
3741
3742                 $url = $shared['message_id'] ?: $shared['link'];
3743                 $id = self::fetchByLink($url);
3744                 if (!$id) {
3745                         Logger::notice('Post could not be fetched.', ['url' => $url, 'uid' => $uid]);
3746                         return 0;
3747                 }
3748
3749                 $shared_item = Post::selectFirst(['uri-id'], ['id' => $id]);
3750                 if (!empty($shared_item['uri-id'])) {
3751                         Logger::debug('Fetched shared post', ['id' => $id, 'url' => $url, 'uid' => $uid]);
3752                         return $shared_item['uri-id'];
3753                 }
3754
3755                 Logger::warning('Post does not exist although it was supposed to had been fetched.', ['id' => $id, 'url' => $url, 'uid' => $uid]);
3756                 return 0;
3757         }
3758 }