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