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