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