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