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