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