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