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