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