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