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