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