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