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