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