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