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