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