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