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