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