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