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