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