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