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