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