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