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