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