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