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