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