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