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