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