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