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