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