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