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