]> git.mxchange.org Git - friendica.git/blob - src/Model/Item.php
Bugfix - `author-network` (adding to unset list during insert)
[friendica.git] / src / Model / Item.php
1 <?php
2
3 /**
4  * @file src/Model/Item.php
5  */
6
7 namespace Friendica\Model;
8
9 use Friendica\BaseObject;
10 use Friendica\Content\Text\BBCode;
11 use Friendica\Content\Text\HTML;
12 use Friendica\Core\Config;
13 use Friendica\Core\Hook;
14 use Friendica\Core\L10n;
15 use Friendica\Core\Lock;
16 use Friendica\Core\Logger;
17 use Friendica\Core\PConfig;
18 use Friendica\Core\Protocol;
19 use Friendica\Core\Renderer;
20 use Friendica\Core\System;
21 use Friendica\Core\Worker;
22 use Friendica\Database\DBA;
23 use Friendica\Protocol\Diaspora;
24 use Friendica\Protocol\OStatus;
25 use Friendica\Util\DateTimeFormat;
26 use Friendica\Util\Map;
27 use Friendica\Util\Network;
28 use Friendica\Util\Security;
29 use Friendica\Util\Strings;
30 use Friendica\Util\XML;
31 use 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', 'gravity',
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-uid', '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                         'parent-guid', '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', 'author-network',
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                 unset($item['author-network']);
1725
1726                 unset($item['owner-link']);
1727                 unset($item['owner-name']);
1728                 unset($item['owner-avatar']);
1729
1730                 DBA::transaction();
1731                 $ret = DBA::insert('item', $item);
1732
1733                 // When the item was successfully stored we fetch the ID of the item.
1734                 if (DBA::isResult($ret)) {
1735                         $current_post = DBA::lastInsertId();
1736                 } else {
1737                         // This can happen - for example - if there are locking timeouts.
1738                         DBA::rollback();
1739
1740                         // Store the data into a spool file so that we can try again later.
1741
1742                         // At first we restore the Diaspora signature that we removed above.
1743                         if (isset($encoded_signature)) {
1744                                 $item['dsprsig'] = $encoded_signature;
1745                         }
1746
1747                         // Now we store the data in the spool directory
1748                         // We use "microtime" to keep the arrival order and "mt_rand" to avoid duplicates
1749                         $file = 'item-'.round(microtime(true) * 10000).'-'.mt_rand().'.msg';
1750
1751                         $spoolpath = get_spoolpath();
1752                         if ($spoolpath != "") {
1753                                 $spool = $spoolpath.'/'.$file;
1754
1755                                 file_put_contents($spool, json_encode($orig_item));
1756                                 Logger::log("Item wasn't stored - Item was spooled into file ".$file, Logger::DEBUG);
1757                         }
1758                         return 0;
1759                 }
1760
1761                 if ($current_post == 0) {
1762                         // This is one of these error messages that never should occur.
1763                         Logger::log("couldn't find created item - we better quit now.");
1764                         DBA::rollback();
1765                         return 0;
1766                 }
1767
1768                 // How much entries have we created?
1769                 // We wouldn't need this query when we could use an unique index - but MySQL has length problems with them.
1770                 $entries = DBA::count('item', ['uri' => $item['uri'], 'uid' => $item['uid'], 'network' => $item['network']]);
1771
1772                 if ($entries > 1) {
1773                         // There are duplicates. We delete our just created entry.
1774                         Logger::log('Duplicated post occurred. uri = ' . $item['uri'] . ' uid = ' . $item['uid']);
1775
1776                         // Yes, we could do a rollback here - but we are having many users with MyISAM.
1777                         DBA::delete('item', ['id' => $current_post]);
1778                         DBA::commit();
1779                         return 0;
1780                 } elseif ($entries == 0) {
1781                         // This really should never happen since we quit earlier if there were problems.
1782                         Logger::log("Something is terribly wrong. We haven't found our created entry.");
1783                         DBA::rollback();
1784                         return 0;
1785                 }
1786
1787                 Logger::log('created item '.$current_post);
1788                 self::updateContact($item);
1789
1790                 if (!$parent_id || ($item['parent-uri'] === $item['uri'])) {
1791                         $parent_id = $current_post;
1792                 }
1793
1794                 // Set parent id
1795                 DBA::update('item', ['parent' => $parent_id], ['id' => $current_post]);
1796
1797                 $item['id'] = $current_post;
1798                 $item['parent'] = $parent_id;
1799
1800                 // update the commented timestamp on the parent
1801                 // Only update "commented" if it is really a comment
1802                 if (($item['gravity'] != GRAVITY_ACTIVITY) || !Config::get("system", "like_no_comment")) {
1803                         DBA::update('item', ['commented' => DateTimeFormat::utcNow(), 'changed' => DateTimeFormat::utcNow()], ['id' => $parent_id]);
1804                 } else {
1805                         DBA::update('item', ['changed' => DateTimeFormat::utcNow()], ['id' => $parent_id]);
1806                 }
1807
1808                 if ($dsprsig) {
1809                         /*
1810                          * Friendica servers lower than 3.4.3-2 had double encoded the signature ...
1811                          * We can check for this condition when we decode and encode the stuff again.
1812                          */
1813                         if (base64_encode(base64_decode(base64_decode($dsprsig->signature))) == base64_decode($dsprsig->signature)) {
1814                                 $dsprsig->signature = base64_decode($dsprsig->signature);
1815                                 Logger::log("Repaired double encoded signature from handle ".$dsprsig->signer, Logger::DEBUG);
1816                         }
1817
1818                         if (!empty($dsprsig->signed_text) && empty($dsprsig->signature) && empty($dsprsig->signer)) {
1819                                 DBA::insert('diaspora-interaction', ['uri-id' => $item['uri-id'], 'interaction' => $dsprsig->signed_text], true);
1820                         } else {
1821                                 // The other fields are used by very old Friendica servers, so we currently store them differently
1822                                 DBA::insert('sign', ['iid' => $current_post, 'signed_text' => $dsprsig->signed_text,
1823                                         'signature' => $dsprsig->signature, 'signer' => $dsprsig->signer]);
1824                         }
1825                 }
1826
1827                 if (!empty($diaspora_signed_text)) {
1828                         DBA::insert('diaspora-interaction', ['uri-id' => $item['uri-id'], 'interaction' => $diaspora_signed_text], true);
1829                 }
1830
1831                 self::tagDeliver($item['uid'], $current_post);
1832
1833                 /*
1834                  * current post can be deleted if is for a community page and no mention are
1835                  * in it.
1836                  */
1837                 if (!$dontcache) {
1838                         $posted_item = self::selectFirst(self::ITEM_FIELDLIST, ['id' => $current_post]);
1839                         if (DBA::isResult($posted_item)) {
1840                                 if ($notify) {
1841                                         Hook::callAll('post_local_end', $posted_item);
1842                                 } else {
1843                                         Hook::callAll('post_remote_end', $posted_item);
1844                                 }
1845                         } else {
1846                                 Logger::log('new item not found in DB, id ' . $current_post);
1847                         }
1848                 }
1849
1850                 if ($item['parent-uri'] === $item['uri']) {
1851                         self::addThread($current_post);
1852                 } else {
1853                         self::updateThread($parent_id);
1854                 }
1855
1856                 ItemDeliveryData::insert($current_post, $delivery_data);
1857
1858                 DBA::commit();
1859
1860                 /*
1861                  * Due to deadlock issues with the "term" table we are doing these steps after the commit.
1862                  * This is not perfect - but a workable solution until we found the reason for the problem.
1863                  */
1864                 if (!empty($tags)) {
1865                         Term::insertFromTagFieldByItemId($current_post, $tags);
1866                 }
1867
1868                 if (!empty($files)) {
1869                         Term::insertFromFileFieldByItemId($current_post, $files);
1870                 }
1871
1872                 if ($item['parent-uri'] === $item['uri']) {
1873                         self::addShadow($current_post);
1874                 } else {
1875                         self::addShadowPost($current_post);
1876                 }
1877
1878                 check_user_notification($current_post);
1879
1880                 if ($notify) {
1881                         Worker::add(['priority' => $priority, 'dont_fork' => true], 'Notifier', $notify_type, $current_post);
1882                 } elseif ($item['visible'] && ((!empty($parent) && $parent['origin']) || $item['origin'])) {
1883                         if ($item['gravity'] == GRAVITY_ACTIVITY) {
1884                                 $cmd = $item['origin'] ? 'activity-new' : 'activity-import';
1885                         } elseif ($item['gravity'] == GRAVITY_COMMENT) {
1886                                 $cmd = $item['origin'] ? 'comment-new' : 'comment-import';
1887                         } else {
1888                                 $cmd = 'wall-new';
1889                         }
1890
1891                         Worker::add(['priority' => $priority, 'dont_fork' => true], 'Notifier', $cmd, $current_post);
1892                 }
1893
1894                 return $current_post;
1895         }
1896
1897         /**
1898          * @brief Insert a new item content entry
1899          *
1900          * @param array $item The item fields that are to be inserted
1901          * @return bool
1902          * @throws \Exception
1903          */
1904         private static function insertActivity(&$item)
1905         {
1906                 $activity_index = self::activityToIndex($item['verb']);
1907
1908                 if ($activity_index < 0) {
1909                         return false;
1910                 }
1911
1912                 $fields = ['activity' => $activity_index, 'uri-hash' => (string)$item['uri-id'], 'uri-id' => $item['uri-id']];
1913
1914                 // We just remove everything that is content
1915                 foreach (array_merge(self::CONTENT_FIELDLIST, self::MIXED_CONTENT_FIELDLIST) as $field) {
1916                         unset($item[$field]);
1917                 }
1918
1919                 // To avoid timing problems, we are using locks.
1920                 $locked = Lock::acquire('item_insert_activity');
1921                 if (!$locked) {
1922                         Logger::log("Couldn't acquire lock for URI " . $item['uri'] . " - proceeding anyway.");
1923                 }
1924
1925                 // Do we already have this content?
1926                 $item_activity = DBA::selectFirst('item-activity', ['id'], ['uri-id' => $item['uri-id']]);
1927                 if (DBA::isResult($item_activity)) {
1928                         $item['iaid'] = $item_activity['id'];
1929                         Logger::log('Fetched activity for URI ' . $item['uri'] . ' (' . $item['iaid'] . ')');
1930                 } elseif (DBA::insert('item-activity', $fields)) {
1931                         $item['iaid'] = DBA::lastInsertId();
1932                         Logger::log('Inserted activity for URI ' . $item['uri'] . ' (' . $item['iaid'] . ')');
1933                 } else {
1934                         // This shouldn't happen.
1935                         Logger::log('Could not insert activity for URI ' . $item['uri'] . ' - should not happen');
1936                         Lock::release('item_insert_activity');
1937                         return false;
1938                 }
1939                 if ($locked) {
1940                         Lock::release('item_insert_activity');
1941                 }
1942                 return true;
1943         }
1944
1945         /**
1946          * @brief Insert a new item content entry
1947          *
1948          * @param array $item The item fields that are to be inserted
1949          * @throws \Exception
1950          */
1951         private static function insertContent(&$item)
1952         {
1953                 $fields = ['uri-plink-hash' => (string)$item['uri-id'], 'uri-id' => $item['uri-id']];
1954
1955                 foreach (array_merge(self::CONTENT_FIELDLIST, self::MIXED_CONTENT_FIELDLIST) as $field) {
1956                         if (isset($item[$field])) {
1957                                 $fields[$field] = $item[$field];
1958                                 unset($item[$field]);
1959                         }
1960                 }
1961
1962                 // To avoid timing problems, we are using locks.
1963                 $locked = Lock::acquire('item_insert_content');
1964                 if (!$locked) {
1965                         Logger::log("Couldn't acquire lock for URI " . $item['uri'] . " - proceeding anyway.");
1966                 }
1967
1968                 // Do we already have this content?
1969                 $item_content = DBA::selectFirst('item-content', ['id'], ['uri-id' => $item['uri-id']]);
1970                 if (DBA::isResult($item_content)) {
1971                         $item['icid'] = $item_content['id'];
1972                         Logger::log('Fetched content for URI ' . $item['uri'] . ' (' . $item['icid'] . ')');
1973                 } elseif (DBA::insert('item-content', $fields)) {
1974                         $item['icid'] = DBA::lastInsertId();
1975                         Logger::log('Inserted content for URI ' . $item['uri'] . ' (' . $item['icid'] . ')');
1976                 } else {
1977                         // This shouldn't happen.
1978                         Logger::log('Could not insert content for URI ' . $item['uri'] . ' - should not happen');
1979                 }
1980                 if ($locked) {
1981                         Lock::release('item_insert_content');
1982                 }
1983         }
1984
1985         /**
1986          * @brief Update existing item content entries
1987          *
1988          * @param array $item      The item fields that are to be changed
1989          * @param array $condition The condition for finding the item content entries
1990          * @return bool
1991          * @throws \Exception
1992          */
1993         private static function updateActivity($item, $condition)
1994         {
1995                 if (empty($item['verb'])) {
1996                         return false;
1997                 }
1998                 $activity_index = self::activityToIndex($item['verb']);
1999
2000                 if ($activity_index < 0) {
2001                         return false;
2002                 }
2003
2004                 $fields = ['activity' => $activity_index];
2005
2006                 Logger::log('Update activity for ' . json_encode($condition));
2007
2008                 DBA::update('item-activity', $fields, $condition, true);
2009
2010                 return true;
2011         }
2012
2013         /**
2014          * @brief Update existing item content entries
2015          *
2016          * @param array $item      The item fields that are to be changed
2017          * @param array $condition The condition for finding the item content entries
2018          * @throws \Exception
2019          */
2020         private static function updateContent($item, $condition)
2021         {
2022                 // We have to select only the fields from the "item-content" table
2023                 $fields = [];
2024                 foreach (array_merge(self::CONTENT_FIELDLIST, self::MIXED_CONTENT_FIELDLIST) as $field) {
2025                         if (isset($item[$field])) {
2026                                 $fields[$field] = $item[$field];
2027                         }
2028                 }
2029
2030                 if (empty($fields)) {
2031                         // when there are no fields at all, just use the condition
2032                         // This is to ensure that we always store content.
2033                         $fields = $condition;
2034                 }
2035
2036                 Logger::log('Update content for ' . json_encode($condition));
2037
2038                 DBA::update('item-content', $fields, $condition, true);
2039         }
2040
2041         /**
2042          * @brief Distributes public items to the receivers
2043          *
2044          * @param integer $itemid      Item ID that should be added
2045          * @param string  $signed_text Original text (for Diaspora signatures), JSON encoded.
2046          * @throws \Exception
2047          */
2048         public static function distribute($itemid, $signed_text = '')
2049         {
2050                 $condition = ["`id` IN (SELECT `parent` FROM `item` WHERE `id` = ?)", $itemid];
2051                 $parent = self::selectFirst(['owner-id'], $condition);
2052                 if (!DBA::isResult($parent)) {
2053                         return;
2054                 }
2055
2056                 // Only distribute public items from native networks
2057                 $condition = ['id' => $itemid, 'uid' => 0,
2058                         'network' => [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS, ""],
2059                         'visible' => true, 'deleted' => false, 'moderated' => false, 'private' => false];
2060                 $item = self::selectFirst(self::ITEM_FIELDLIST, $condition);
2061                 if (!DBA::isResult($item)) {
2062                         return;
2063                 }
2064
2065                 $origin = $item['origin'];
2066
2067                 unset($item['id']);
2068                 unset($item['parent']);
2069                 unset($item['mention']);
2070                 unset($item['wall']);
2071                 unset($item['origin']);
2072                 unset($item['starred']);
2073
2074                 $users = [];
2075
2076                 /// @todo add a field "pcid" in the contact table that referrs to the public contact id.
2077                 $owner = DBA::selectFirst('contact', ['url', 'nurl', 'alias'], ['id' => $parent['owner-id']]);
2078                 if (!DBA::isResult($owner)) {
2079                         return;
2080                 }
2081
2082                 $condition = ['nurl' => $owner['nurl'], 'rel' => [Contact::SHARING, Contact::FRIEND]];
2083                 $contacts = DBA::select('contact', ['uid'], $condition);
2084                 while ($contact = DBA::fetch($contacts)) {
2085                         if ($contact['uid'] == 0) {
2086                                 continue;
2087                         }
2088
2089                         $users[$contact['uid']] = $contact['uid'];
2090                 }
2091                 DBA::close($contacts);
2092
2093                 $condition = ['alias' => $owner['url'], 'rel' => [Contact::SHARING, Contact::FRIEND]];
2094                 $contacts = DBA::select('contact', ['uid'], $condition);
2095                 while ($contact = DBA::fetch($contacts)) {
2096                         if ($contact['uid'] == 0) {
2097                                 continue;
2098                         }
2099
2100                         $users[$contact['uid']] = $contact['uid'];
2101                 }
2102                 DBA::close($contacts);
2103
2104                 if (!empty($owner['alias'])) {
2105                         $condition = ['url' => $owner['alias'], 'rel' => [Contact::SHARING, Contact::FRIEND]];
2106                         $contacts = DBA::select('contact', ['uid'], $condition);
2107                         while ($contact = DBA::fetch($contacts)) {
2108                                 if ($contact['uid'] == 0) {
2109                                         continue;
2110                                 }
2111
2112                                 $users[$contact['uid']] = $contact['uid'];
2113                         }
2114                         DBA::close($contacts);
2115                 }
2116
2117                 $origin_uid = 0;
2118
2119                 if ($item['uri'] != $item['parent-uri']) {
2120                         $parents = self::select(['uid', 'origin'], ["`uri` = ? AND `uid` != 0", $item['parent-uri']]);
2121                         while ($parent = self::fetch($parents)) {
2122                                 $users[$parent['uid']] = $parent['uid'];
2123                                 if ($parent['origin'] && !$origin) {
2124                                         $origin_uid = $parent['uid'];
2125                                 }
2126                         }
2127                 }
2128
2129                 foreach ($users as $uid) {
2130                         if ($origin_uid == $uid) {
2131                                 $item['diaspora_signed_text'] = $signed_text;
2132                         }
2133                         self::storeForUser($itemid, $item, $uid);
2134                 }
2135         }
2136
2137         /**
2138          * @brief Store public items for the receivers
2139          *
2140          * @param integer $itemid Item ID that should be added
2141          * @param array   $item   The item entry that will be stored
2142          * @param integer $uid    The user that will receive the item entry
2143          * @throws \Exception
2144          */
2145         private static function storeForUser($itemid, $item, $uid)
2146         {
2147                 $item['uid'] = $uid;
2148                 $item['origin'] = 0;
2149                 $item['wall'] = 0;
2150                 if ($item['uri'] == $item['parent-uri']) {
2151                         $item['contact-id'] = Contact::getIdForURL($item['owner-link'], $uid);
2152                 } else {
2153                         $item['contact-id'] = Contact::getIdForURL($item['author-link'], $uid);
2154                 }
2155
2156                 if (empty($item['contact-id'])) {
2157                         $self = DBA::selectFirst('contact', ['id'], ['self' => true, 'uid' => $uid]);
2158                         if (!DBA::isResult($self)) {
2159                                 return;
2160                         }
2161                         $item['contact-id'] = $self['id'];
2162                 }
2163
2164                 /// @todo Handling of "event-id"
2165
2166                 $notify = false;
2167                 if ($item['uri'] == $item['parent-uri']) {
2168                         $contact = DBA::selectFirst('contact', [], ['id' => $item['contact-id'], 'self' => false]);
2169                         if (DBA::isResult($contact)) {
2170                                 $notify = self::isRemoteSelf($contact, $item);
2171                         }
2172                 }
2173
2174                 $distributed = self::insert($item, false, $notify, true);
2175
2176                 if (!$distributed) {
2177                         Logger::log("Distributed public item " . $itemid . " for user " . $uid . " wasn't stored", Logger::DEBUG);
2178                 } else {
2179                         Logger::log("Distributed public item " . $itemid . " for user " . $uid . " with id " . $distributed, Logger::DEBUG);
2180                 }
2181         }
2182
2183         /**
2184          * @brief Add a shadow entry for a given item id that is a thread starter
2185          *
2186          * We store every public item entry additionally with the user id "0".
2187          * This is used for the community page and for the search.
2188          * It is planned that in the future we will store public item entries only once.
2189          *
2190          * @param integer $itemid Item ID that should be added
2191          * @throws \Exception
2192          */
2193         public static function addShadow($itemid)
2194         {
2195                 $fields = ['uid', 'private', 'moderated', 'visible', 'deleted', 'network', 'uri'];
2196                 $condition = ['id' => $itemid, 'parent' => [0, $itemid]];
2197                 $item = self::selectFirst($fields, $condition);
2198
2199                 if (!DBA::isResult($item)) {
2200                         return;
2201                 }
2202
2203                 // is it already a copy?
2204                 if (($itemid == 0) || ($item['uid'] == 0)) {
2205                         return;
2206                 }
2207
2208                 // Is it a visible public post?
2209                 if (!$item["visible"] || $item["deleted"] || $item["moderated"] || $item["private"]) {
2210                         return;
2211                 }
2212
2213                 // is it an entry from a connector? Only add an entry for natively connected networks
2214                 if (!in_array($item["network"], [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS, ""])) {
2215                         return;
2216                 }
2217
2218                 if (self::exists(['uri' => $item['uri'], 'uid' => 0])) {
2219                         return;
2220                 }
2221
2222                 $item = self::selectFirst(self::ITEM_FIELDLIST, ['id' => $itemid]);
2223
2224                 if (DBA::isResult($item)) {
2225                         // Preparing public shadow (removing user specific data)
2226                         $item['uid'] = 0;
2227                         unset($item['id']);
2228                         unset($item['parent']);
2229                         unset($item['wall']);
2230                         unset($item['mention']);
2231                         unset($item['origin']);
2232                         unset($item['starred']);
2233                         unset($item['postopts']);
2234                         unset($item['inform']);
2235                         if ($item['uri'] == $item['parent-uri']) {
2236                                 $item['contact-id'] = $item['owner-id'];
2237                         } else {
2238                                 $item['contact-id'] = $item['author-id'];
2239                         }
2240
2241                         $public_shadow = self::insert($item, false, false, true);
2242
2243                         Logger::log("Stored public shadow for thread ".$itemid." under id ".$public_shadow, Logger::DEBUG);
2244                 }
2245         }
2246
2247         /**
2248          * @brief Add a shadow entry for a given item id that is a comment
2249          *
2250          * This function does the same like the function above - but for comments
2251          *
2252          * @param integer $itemid Item ID that should be added
2253          * @throws \Exception
2254          */
2255         public static function addShadowPost($itemid)
2256         {
2257                 $item = self::selectFirst(self::ITEM_FIELDLIST, ['id' => $itemid]);
2258                 if (!DBA::isResult($item)) {
2259                         return;
2260                 }
2261
2262                 // Is it a toplevel post?
2263                 if ($item['id'] == $item['parent']) {
2264                         self::addShadow($itemid);
2265                         return;
2266                 }
2267
2268                 // Is this a shadow entry?
2269                 if ($item['uid'] == 0) {
2270                         return;
2271                 }
2272
2273                 // Is there a shadow parent?
2274                 if (!self::exists(['uri' => $item['parent-uri'], 'uid' => 0])) {
2275                         return;
2276                 }
2277
2278                 // Is there already a shadow entry?
2279                 if (self::exists(['uri' => $item['uri'], 'uid' => 0])) {
2280                         return;
2281                 }
2282
2283                 // Save "origin" and "parent" state
2284                 $origin = $item['origin'];
2285                 $parent = $item['parent'];
2286
2287                 // Preparing public shadow (removing user specific data)
2288                 $item['uid'] = 0;
2289                 unset($item['id']);
2290                 unset($item['parent']);
2291                 unset($item['wall']);
2292                 unset($item['mention']);
2293                 unset($item['origin']);
2294                 unset($item['starred']);
2295                 unset($item['postopts']);
2296                 unset($item['inform']);
2297                 $item['contact-id'] = Contact::getIdForURL($item['author-link']);
2298
2299                 $public_shadow = self::insert($item, false, false, true);
2300
2301                 Logger::log("Stored public shadow for comment ".$item['uri']." under id ".$public_shadow, Logger::DEBUG);
2302
2303                 // If this was a comment to a Diaspora post we don't get our comment back.
2304                 // This means that we have to distribute the comment by ourselves.
2305                 if ($origin && self::exists(['id' => $parent, 'network' => Protocol::DIASPORA])) {
2306                         self::distribute($public_shadow);
2307                 }
2308         }
2309
2310         /**
2311          * Adds a language specification in a "language" element of given $arr.
2312          * Expects "body" element to exist in $arr.
2313          *
2314          * @param $item
2315          * @throws \Text_LanguageDetect_Exception
2316          */
2317         private static function addLanguageToItemArray(&$item)
2318         {
2319                 $naked_body = BBCode::toPlaintext($item['body'], false);
2320
2321                 $ld = new Text_LanguageDetect();
2322                 $ld->setNameMode(2);
2323                 $languages = $ld->detect($naked_body, 3);
2324
2325                 if (is_array($languages)) {
2326                         $item['language'] = json_encode($languages);
2327                 }
2328         }
2329
2330         /**
2331          * @brief Creates an unique guid out of a given uri
2332          *
2333          * @param string $uri uri of an item entry
2334          * @param string $host hostname for the GUID prefix
2335          * @return string unique guid
2336          */
2337         public static function guidFromUri($uri, $host)
2338         {
2339                 // Our regular guid routine is using this kind of prefix as well
2340                 // We have to avoid that different routines could accidentally create the same value
2341                 $parsed = parse_url($uri);
2342
2343                 // We use a hash of the hostname as prefix for the guid
2344                 $guid_prefix = hash("crc32", $host);
2345
2346                 // Remove the scheme to make sure that "https" and "http" doesn't make a difference
2347                 unset($parsed["scheme"]);
2348
2349                 // Glue it together to be able to make a hash from it
2350                 $host_id = implode("/", $parsed);
2351
2352                 // We could use any hash algorithm since it isn't a security issue
2353                 $host_hash = hash("ripemd128", $host_id);
2354
2355                 return $guid_prefix.$host_hash;
2356         }
2357
2358         /**
2359          * generate an unique URI
2360          *
2361          * @param integer $uid  User id
2362          * @param string  $guid An existing GUID (Otherwise it will be generated)
2363          *
2364          * @return string
2365          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2366          */
2367         public static function newURI($uid, $guid = "")
2368         {
2369                 if ($guid == "") {
2370                         $guid = System::createUUID();
2371                 }
2372
2373                 return self::getApp()->getBaseURL() . '/objects/' . $guid;
2374         }
2375
2376         /**
2377          * @brief Set "success_update" and "last-item" to the date of the last time we heard from this contact
2378          *
2379          * This can be used to filter for inactive contacts.
2380          * Only do this for public postings to avoid privacy problems, since poco data is public.
2381          * Don't set this value if it isn't from the owner (could be an author that we don't know)
2382          *
2383          * @param array $arr Contains the just posted item record
2384          * @throws \Exception
2385          */
2386         private static function updateContact($arr)
2387         {
2388                 // Unarchive the author
2389                 $contact = DBA::selectFirst('contact', [], ['id' => $arr["author-id"]]);
2390                 if (DBA::isResult($contact)) {
2391                         Contact::unmarkForArchival($contact);
2392                 }
2393
2394                 // Unarchive the contact if it's not our own contact
2395                 $contact = DBA::selectFirst('contact', [], ['id' => $arr["contact-id"], 'self' => false]);
2396                 if (DBA::isResult($contact)) {
2397                         Contact::unmarkForArchival($contact);
2398                 }
2399
2400                 $update = (!$arr['private'] && ((defaults($arr, 'author-link', '') === defaults($arr, 'owner-link', '')) || ($arr["parent-uri"] === $arr["uri"])));
2401
2402                 // Is it a forum? Then we don't care about the rules from above
2403                 if (!$update && in_array($arr["network"], [Protocol::ACTIVITYPUB, Protocol::DFRN]) && ($arr["parent-uri"] === $arr["uri"])) {
2404                         if (DBA::exists('contact', ['id' => $arr['contact-id'], 'forum' => true])) {
2405                                 $update = true;
2406                         }
2407                 }
2408
2409                 if ($update) {
2410                         DBA::update('contact', ['success_update' => $arr['received'], 'last-item' => $arr['received']],
2411                                 ['id' => $arr['contact-id']]);
2412                 }
2413                 // Now do the same for the system wide contacts with uid=0
2414                 if (!$arr['private']) {
2415                         DBA::update('contact', ['success_update' => $arr['received'], 'last-item' => $arr['received']],
2416                                 ['id' => $arr['owner-id']]);
2417
2418                         if ($arr['owner-id'] != $arr['author-id']) {
2419                                 DBA::update('contact', ['success_update' => $arr['received'], 'last-item' => $arr['received']],
2420                                         ['id' => $arr['author-id']]);
2421                         }
2422                 }
2423         }
2424
2425         public static function setHashtags(&$item)
2426         {
2427                 $tags = BBCode::getTags($item["body"]);
2428
2429                 // No hashtags?
2430                 if (!count($tags)) {
2431                         return false;
2432                 }
2433
2434                 // What happens in [code], stays in [code]!
2435                 // escape the # and the [
2436                 // hint: we will also get in trouble with #tags, when we want markdown in posts -> ### Headline 3
2437                 $item["body"] = preg_replace_callback("/\[code(.*?)\](.*?)\[\/code\]/ism",
2438                         function ($match) {
2439                                 // we truly ESCape all # and [ to prevent gettin weird tags in [code] blocks
2440                                 $find = ['#', '['];
2441                                 $replace = [chr(27).'sharp', chr(27).'leftsquarebracket'];
2442                                 return ("[code" . $match[1] . "]" . str_replace($find, $replace, $match[2]) . "[/code]");
2443                         }, $item["body"]);
2444
2445                 // This sorting is important when there are hashtags that are part of other hashtags
2446                 // Otherwise there could be problems with hashtags like #test and #test2
2447                 rsort($tags);
2448
2449                 $URLSearchString = "^\[\]";
2450
2451                 // All hashtags should point to the home server if "local_tags" is activated
2452                 if (Config::get('system', 'local_tags')) {
2453                         $item["body"] = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
2454                                         "#[url=".System::baseUrl()."/search?tag=$2]$2[/url]", $item["body"]);
2455
2456                         $item["tag"] = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
2457                                         "#[url=".System::baseUrl()."/search?tag=$2]$2[/url]", $item["tag"]);
2458                 }
2459
2460                 // mask hashtags inside of url, bookmarks and attachments to avoid urls in urls
2461                 $item["body"] = preg_replace_callback("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
2462                         function ($match) {
2463                                 return ("[url=" . str_replace("#", "&num;", $match[1]) . "]" . str_replace("#", "&num;", $match[2]) . "[/url]");
2464                         }, $item["body"]);
2465
2466                 $item["body"] = preg_replace_callback("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism",
2467                         function ($match) {
2468                                 return ("[bookmark=" . str_replace("#", "&num;", $match[1]) . "]" . str_replace("#", "&num;", $match[2]) . "[/bookmark]");
2469                         }, $item["body"]);
2470
2471                 $item["body"] = preg_replace_callback("/\[attachment (.*)\](.*?)\[\/attachment\]/ism",
2472                         function ($match) {
2473                                 return ("[attachment " . str_replace("#", "&num;", $match[1]) . "]" . $match[2] . "[/attachment]");
2474                         }, $item["body"]);
2475
2476                 // Repair recursive urls
2477                 $item["body"] = preg_replace("/&num;\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
2478                                 "&num;$2", $item["body"]);
2479
2480                 foreach ($tags as $tag) {
2481                         if ((strpos($tag, '#') !== 0) || strpos($tag, '[url=') || $tag[1] == '#') {
2482                                 continue;
2483                         }
2484
2485                         $basetag = str_replace('_',' ',substr($tag,1));
2486                         $newtag = '#[url=' . System::baseUrl() . '/search?tag=' . $basetag . ']' . $basetag . '[/url]';
2487
2488                         $item["body"] = str_replace($tag, $newtag, $item["body"]);
2489
2490                         if (!stristr($item["tag"], "/search?tag=" . $basetag . "]" . $basetag . "[/url]")) {
2491                                 if (strlen($item["tag"])) {
2492                                         $item["tag"] = ',' . $item["tag"];
2493                                 }
2494                                 $item["tag"] = $newtag . $item["tag"];
2495                         }
2496                 }
2497
2498                 // Convert back the masked hashtags
2499                 $item["body"] = str_replace("&num;", "#", $item["body"]);
2500
2501                 // Remember! What happens in [code], stays in [code]
2502                 // roleback the # and [
2503                 $item["body"] = preg_replace_callback("/\[code(.*?)\](.*?)\[\/code\]/ism",
2504                         function ($match) {
2505                                 // we truly unESCape all sharp and leftsquarebracket
2506                                 $find = [chr(27).'sharp', chr(27).'leftsquarebracket'];
2507                                 $replace = ['#', '['];
2508                                 return ("[code" . $match[1] . "]" . str_replace($find, $replace, $match[2]) . "[/code]");
2509                         }, $item["body"]);
2510         }
2511
2512         /**
2513          * look for mention tags and setup a second delivery chain for forum/community posts if appropriate
2514          *
2515          * @param int $uid
2516          * @param int $item_id
2517          * @return void true if item was deleted, else false
2518          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2519          * @throws \ImagickException
2520          */
2521         private static function tagDeliver($uid, $item_id)
2522         {
2523                 $mention = false;
2524
2525                 $user = DBA::selectFirst('user', [], ['uid' => $uid]);
2526                 if (!DBA::isResult($user)) {
2527                         return;
2528                 }
2529
2530                 $community_page = (($user['page-flags'] == User::PAGE_FLAGS_COMMUNITY) ? true : false);
2531                 $prvgroup = (($user['page-flags'] == User::PAGE_FLAGS_PRVGROUP) ? true : false);
2532
2533                 $item = self::selectFirst(self::ITEM_FIELDLIST, ['id' => $item_id]);
2534                 if (!DBA::isResult($item)) {
2535                         return;
2536                 }
2537
2538                 $link = Strings::normaliseLink(System::baseUrl() . '/profile/' . $user['nickname']);
2539
2540                 /*
2541                  * Diaspora uses their own hardwired link URL in @-tags
2542                  * instead of the one we supply with webfinger
2543                  */
2544                 $dlink = Strings::normaliseLink(System::baseUrl() . '/u/' . $user['nickname']);
2545
2546                 $cnt = preg_match_all('/[\@\!]\[url\=(.*?)\](.*?)\[\/url\]/ism', $item['body'], $matches, PREG_SET_ORDER);
2547                 if ($cnt) {
2548                         foreach ($matches as $mtch) {
2549                                 if (Strings::compareLink($link, $mtch[1]) || Strings::compareLink($dlink, $mtch[1])) {
2550                                         $mention = true;
2551                                         Logger::log('mention found: ' . $mtch[2]);
2552                                 }
2553                         }
2554                 }
2555
2556                 if (!$mention) {
2557                         if (($community_page || $prvgroup) &&
2558                                   !$item['wall'] && !$item['origin'] && ($item['id'] == $item['parent'])) {
2559                                 // mmh.. no mention.. community page or private group... no wall.. no origin.. top-post (not a comment)
2560                                 // delete it!
2561                                 Logger::log("no-mention top-level post to community or private group. delete.");
2562                                 DBA::delete('item', ['id' => $item_id]);
2563                                 return true;
2564                         }
2565                         return;
2566                 }
2567
2568                 $arr = ['item' => $item, 'user' => $user];
2569
2570                 Hook::callAll('tagged', $arr);
2571
2572                 if (!$community_page && !$prvgroup) {
2573                         return;
2574                 }
2575
2576                 /*
2577                  * tgroup delivery - setup a second delivery chain
2578                  * prevent delivery looping - only proceed
2579                  * if the message originated elsewhere and is a top-level post
2580                  */
2581                 if ($item['wall'] || $item['origin'] || ($item['id'] != $item['parent'])) {
2582                         return;
2583                 }
2584
2585                 // now change this copy of the post to a forum head message and deliver to all the tgroup members
2586                 $self = DBA::selectFirst('contact', ['id', 'name', 'url', 'thumb'], ['uid' => $uid, 'self' => true]);
2587                 if (!DBA::isResult($self)) {
2588                         return;
2589                 }
2590
2591                 $owner_id = Contact::getIdForURL($self['url']);
2592
2593                 // also reset all the privacy bits to the forum default permissions
2594
2595                 $private = ($user['allow_cid'] || $user['allow_gid'] || $user['deny_cid'] || $user['deny_gid']) ? 1 : 0;
2596
2597                 $psid = PermissionSet::fetchIDForPost($user);
2598
2599                 $forum_mode = ($prvgroup ? 2 : 1);
2600
2601                 $fields = ['wall' => true, 'origin' => true, 'forum_mode' => $forum_mode, 'contact-id' => $self['id'],
2602                         'owner-id' => $owner_id, 'private' => $private, 'psid' => $psid];
2603                 self::update($fields, ['id' => $item_id]);
2604
2605                 self::updateThread($item_id);
2606
2607                 Worker::add(['priority' => PRIORITY_HIGH, 'dont_fork' => true], 'Notifier', 'tgroup', $item_id);
2608         }
2609
2610         public static function isRemoteSelf($contact, &$datarray)
2611         {
2612                 $a = \get_app();
2613
2614                 if (!$contact['remote_self']) {
2615                         return false;
2616                 }
2617
2618                 // Prevent the forwarding of posts that are forwarded
2619                 if (!empty($datarray["extid"]) && ($datarray["extid"] == Protocol::DFRN)) {
2620                         Logger::log('Already forwarded', Logger::DEBUG);
2621                         return false;
2622                 }
2623
2624                 // Prevent to forward already forwarded posts
2625                 if ($datarray["app"] == $a->getHostName()) {
2626                         Logger::log('Already forwarded (second test)', Logger::DEBUG);
2627                         return false;
2628                 }
2629
2630                 // Only forward posts
2631                 if ($datarray["verb"] != ACTIVITY_POST) {
2632                         Logger::log('No post', Logger::DEBUG);
2633                         return false;
2634                 }
2635
2636                 if (($contact['network'] != Protocol::FEED) && $datarray['private']) {
2637                         Logger::log('Not public', Logger::DEBUG);
2638                         return false;
2639                 }
2640
2641                 $datarray2 = $datarray;
2642                 Logger::log('remote-self start - Contact '.$contact['url'].' - '.$contact['remote_self'].' Item '.print_r($datarray, true), Logger::DEBUG);
2643                 if ($contact['remote_self'] == 2) {
2644                         $self = DBA::selectFirst('contact', ['id', 'name', 'url', 'thumb'],
2645                                         ['uid' => $contact['uid'], 'self' => true]);
2646                         if (DBA::isResult($self)) {
2647                                 $datarray['contact-id'] = $self["id"];
2648
2649                                 $datarray['owner-name'] = $self["name"];
2650                                 $datarray['owner-link'] = $self["url"];
2651                                 $datarray['owner-avatar'] = $self["thumb"];
2652
2653                                 $datarray['author-name']   = $datarray['owner-name'];
2654                                 $datarray['author-link']   = $datarray['owner-link'];
2655                                 $datarray['author-avatar'] = $datarray['owner-avatar'];
2656
2657                                 unset($datarray['created']);
2658                                 unset($datarray['edited']);
2659
2660                                 unset($datarray['network']);
2661                                 unset($datarray['owner-id']);
2662                                 unset($datarray['author-id']);
2663                         }
2664
2665                         if ($contact['network'] != Protocol::FEED) {
2666                                 $datarray["guid"] = System::createUUID();
2667                                 unset($datarray["plink"]);
2668                                 $datarray["uri"] = self::newURI($contact['uid'], $datarray["guid"]);
2669                                 $datarray["parent-uri"] = $datarray["uri"];
2670                                 $datarray["thr-parent"] = $datarray["uri"];
2671                                 $datarray["extid"] = Protocol::DFRN;
2672                                 $urlpart = parse_url($datarray2['author-link']);
2673                                 $datarray["app"] = $urlpart["host"];
2674                         } else {
2675                                 $datarray['private'] = 0;
2676                         }
2677                 }
2678
2679                 if ($contact['network'] != Protocol::FEED) {
2680                         // Store the original post
2681                         $result = self::insert($datarray2, false, false);
2682                         Logger::log('remote-self post original item - Contact '.$contact['url'].' return '.$result.' Item '.print_r($datarray2, true), Logger::DEBUG);
2683                 } else {
2684                         $datarray["app"] = "Feed";
2685                         $result = true;
2686                 }
2687
2688                 // Trigger automatic reactions for addons
2689                 $datarray['api_source'] = true;
2690
2691                 // We have to tell the hooks who we are - this really should be improved
2692                 $_SESSION["authenticated"] = true;
2693                 $_SESSION["uid"] = $contact['uid'];
2694
2695                 return $result;
2696         }
2697
2698         /**
2699          *
2700          * @param string $s
2701          * @param int    $uid
2702          * @param array  $item
2703          * @param int    $cid
2704          * @return string
2705          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2706          * @throws \ImagickException
2707          */
2708         public static function fixPrivatePhotos($s, $uid, $item = null, $cid = 0)
2709         {
2710                 if (Config::get('system', 'disable_embedded')) {
2711                         return $s;
2712                 }
2713
2714                 Logger::log('check for photos', Logger::DEBUG);
2715                 $site = substr(System::baseUrl(), strpos(System::baseUrl(), '://'));
2716
2717                 $orig_body = $s;
2718                 $new_body = '';
2719
2720                 $img_start = strpos($orig_body, '[img');
2721                 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
2722                 $img_len = ($img_start !== false ? strpos(substr($orig_body, $img_start + $img_st_close + 1), '[/img]') : false);
2723
2724                 while (($img_st_close !== false) && ($img_len !== false)) {
2725                         $img_st_close++; // make it point to AFTER the closing bracket
2726                         $image = substr($orig_body, $img_start + $img_st_close, $img_len);
2727
2728                         Logger::log('found photo ' . $image, Logger::DEBUG);
2729
2730                         if (stristr($image, $site . '/photo/')) {
2731                                 // Only embed locally hosted photos
2732                                 $replace = false;
2733                                 $i = basename($image);
2734                                 $i = str_replace(['.jpg', '.png', '.gif'], ['', '', ''], $i);
2735                                 $x = strpos($i, '-');
2736
2737                                 if ($x) {
2738                                         $res = substr($i, $x + 1);
2739                                         $i = substr($i, 0, $x);
2740                                         $photo = Photo::getPhotoForUser($uid, $i, $res);
2741                                         if (DBA::isResult($photo)) {
2742                                                 /*
2743                                                  * Check to see if we should replace this photo link with an embedded image
2744                                                  * 1. No need to do so if the photo is public
2745                                                  * 2. If there's a contact-id provided, see if they're in the access list
2746                                                  *    for the photo. If so, embed it.
2747                                                  * 3. Otherwise, if we have an item, see if the item permissions match the photo
2748                                                  *    permissions, regardless of order but first check to see if they're an exact
2749                                                  *    match to save some processing overhead.
2750                                                  */
2751                                                 if (self::hasPermissions($photo)) {
2752                                                         if ($cid) {
2753                                                                 $recips = self::enumeratePermissions($photo);
2754                                                                 if (in_array($cid, $recips)) {
2755                                                                         $replace = true;
2756                                                                 }
2757                                                         } elseif ($item) {
2758                                                                 if (self::samePermissions($item, $photo)) {
2759                                                                         $replace = true;
2760                                                                 }
2761                                                         }
2762                                                 }
2763                                                 if ($replace) {
2764                                                         $photo_img = Photo::getImageForPhoto($photo);
2765                                                         // If a custom width and height were specified, apply before embedding
2766                                                         if (preg_match("/\[img\=([0-9]*)x([0-9]*)\]/is", substr($orig_body, $img_start, $img_st_close), $match)) {
2767                                                                 Logger::log('scaling photo', Logger::DEBUG);
2768
2769                                                                 $width = intval($match[1]);
2770                                                                 $height = intval($match[2]);
2771
2772                                                                 $photo_img->scaleDown(max($width, $height));
2773                                                         }
2774
2775                                                         $data = $photo_img->asString();
2776                                                         $type = $photo_img->getType();
2777
2778                                                         Logger::log('replacing photo', Logger::DEBUG);
2779                                                         $image = 'data:' . $type . ';base64,' . base64_encode($data);
2780                                                         Logger::log('replaced: ' . $image, Logger::DATA);
2781                                                 }
2782                                         }
2783                                 }
2784                         }
2785
2786                         $new_body = $new_body . substr($orig_body, 0, $img_start + $img_st_close) . $image . '[/img]';
2787                         $orig_body = substr($orig_body, $img_start + $img_st_close + $img_len + strlen('[/img]'));
2788                         if ($orig_body === false) {
2789                                 $orig_body = '';
2790                         }
2791
2792                         $img_start = strpos($orig_body, '[img');
2793                         $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
2794                         $img_len = ($img_start !== false ? strpos(substr($orig_body, $img_start + $img_st_close + 1), '[/img]') : false);
2795                 }
2796
2797                 $new_body = $new_body . $orig_body;
2798
2799                 return $new_body;
2800         }
2801
2802         private static function hasPermissions($obj)
2803         {
2804                 return !empty($obj['allow_cid']) || !empty($obj['allow_gid']) ||
2805                         !empty($obj['deny_cid']) || !empty($obj['deny_gid']);
2806         }
2807
2808         private static function samePermissions($obj1, $obj2)
2809         {
2810                 // first part is easy. Check that these are exactly the same.
2811                 if (($obj1['allow_cid'] == $obj2['allow_cid'])
2812                         && ($obj1['allow_gid'] == $obj2['allow_gid'])
2813                         && ($obj1['deny_cid'] == $obj2['deny_cid'])
2814                         && ($obj1['deny_gid'] == $obj2['deny_gid'])) {
2815                         return true;
2816                 }
2817
2818                 // This is harder. Parse all the permissions and compare the resulting set.
2819                 $recipients1 = self::enumeratePermissions($obj1);
2820                 $recipients2 = self::enumeratePermissions($obj2);
2821                 sort($recipients1);
2822                 sort($recipients2);
2823
2824                 /// @TODO Comparison of arrays, maybe use array_diff_assoc() here?
2825                 return ($recipients1 == $recipients2);
2826         }
2827
2828         // returns an array of contact-ids that are allowed to see this object
2829         public static function enumeratePermissions($obj)
2830         {
2831                 $allow_people = expand_acl($obj['allow_cid']);
2832                 $allow_groups = Group::expand(expand_acl($obj['allow_gid']));
2833                 $deny_people  = expand_acl($obj['deny_cid']);
2834                 $deny_groups  = Group::expand(expand_acl($obj['deny_gid']));
2835                 $recipients   = array_unique(array_merge($allow_people, $allow_groups));
2836                 $deny         = array_unique(array_merge($deny_people, $deny_groups));
2837                 $recipients   = array_diff($recipients, $deny);
2838                 return $recipients;
2839         }
2840
2841         public static function getFeedTags($item)
2842         {
2843                 $ret = [];
2844                 $matches = false;
2845                 $cnt = preg_match_all('|\#\[url\=(.*?)\](.*?)\[\/url\]|', $item['tag'], $matches);
2846                 if ($cnt) {
2847                         for ($x = 0; $x < $cnt; $x ++) {
2848                                 if ($matches[1][$x]) {
2849                                         $ret[$matches[2][$x]] = ['#', $matches[1][$x], $matches[2][$x]];
2850                                 }
2851                         }
2852                 }
2853                 $matches = false;
2854                 $cnt = preg_match_all('|\@\[url\=(.*?)\](.*?)\[\/url\]|', $item['tag'], $matches);
2855                 if ($cnt) {
2856                         for ($x = 0; $x < $cnt; $x ++) {
2857                                 if ($matches[1][$x]) {
2858                                         $ret[] = ['@', $matches[1][$x], $matches[2][$x]];
2859                                 }
2860                         }
2861                 }
2862                 return $ret;
2863         }
2864
2865         public static function expire($uid, $days, $network = "", $force = false)
2866         {
2867                 if (!$uid || ($days < 1)) {
2868                         return;
2869                 }
2870
2871                 $condition = ["`uid` = ? AND NOT `deleted` AND `id` = `parent` AND `gravity` = ?",
2872                         $uid, GRAVITY_PARENT];
2873
2874                 /*
2875                  * $expire_network_only = save your own wall posts
2876                  * and just expire conversations started by others
2877                  */
2878                 $expire_network_only = PConfig::get($uid, 'expire', 'network_only', false);
2879
2880                 if ($expire_network_only) {
2881                         $condition[0] .= " AND NOT `wall`";
2882                 }
2883
2884                 if ($network != "") {
2885                         $condition[0] .= " AND `network` = ?";
2886                         $condition[] = $network;
2887
2888                         /*
2889                          * There is an index "uid_network_received" but not "uid_network_created"
2890                          * This avoids the creation of another index just for one purpose.
2891                          * And it doesn't really matter wether to look at "received" or "created"
2892                          */
2893                         $condition[0] .= " AND `received` < UTC_TIMESTAMP() - INTERVAL ? DAY";
2894                         $condition[] = $days;
2895                 } else {
2896                         $condition[0] .= " AND `created` < UTC_TIMESTAMP() - INTERVAL ? DAY";
2897                         $condition[] = $days;
2898                 }
2899
2900                 $items = self::select(['file', 'resource-id', 'starred', 'type', 'id', 'post-type'], $condition);
2901
2902                 if (!DBA::isResult($items)) {
2903                         return;
2904                 }
2905
2906                 $expire_items = PConfig::get($uid, 'expire', 'items', true);
2907
2908                 // Forcing expiring of items - but not notes and marked items
2909                 if ($force) {
2910                         $expire_items = true;
2911                 }
2912
2913                 $expire_notes = PConfig::get($uid, 'expire', 'notes', true);
2914                 $expire_starred = PConfig::get($uid, 'expire', 'starred', true);
2915                 $expire_photos = PConfig::get($uid, 'expire', 'photos', false);
2916
2917                 $expired = 0;
2918
2919                 while ($item = Item::fetch($items)) {
2920                         // don't expire filed items
2921
2922                         if (strpos($item['file'], '[') !== false) {
2923                                 continue;
2924                         }
2925
2926                         // Only expire posts, not photos and photo comments
2927
2928                         if (!$expire_photos && strlen($item['resource-id'])) {
2929                                 continue;
2930                         } elseif (!$expire_starred && intval($item['starred'])) {
2931                                 continue;
2932                         } elseif (!$expire_notes && (($item['type'] == 'note') || ($item['post-type'] == Item::PT_PERSONAL_NOTE))) {
2933                                 continue;
2934                         } elseif (!$expire_items && ($item['type'] != 'note') && ($item['post-type'] != Item::PT_PERSONAL_NOTE)) {
2935                                 continue;
2936                         }
2937
2938                         self::deleteById($item['id'], PRIORITY_LOW);
2939
2940                         ++$expired;
2941                 }
2942                 DBA::close($items);
2943                 Logger::log('User ' . $uid . ": expired $expired items; expire items: $expire_items, expire notes: $expire_notes, expire starred: $expire_starred, expire photos: $expire_photos");
2944         }
2945
2946         public static function firstPostDate($uid, $wall = false)
2947         {
2948                 $condition = ['uid' => $uid, 'wall' => $wall, 'deleted' => false, 'visible' => true, 'moderated' => false];
2949                 $params = ['order' => ['created' => false]];
2950                 $thread = DBA::selectFirst('thread', ['created'], $condition, $params);
2951                 if (DBA::isResult($thread)) {
2952                         return substr(DateTimeFormat::local($thread['created']), 0, 10);
2953                 }
2954                 return false;
2955         }
2956
2957         /**
2958          * @brief add/remove activity to an item
2959          *
2960          * Toggle activities as like,dislike,attend of an item
2961          *
2962          * @param string $item_id
2963          * @param string $verb
2964          *            Activity verb. One of
2965          *            like, unlike, dislike, undislike, attendyes, unattendyes,
2966          *            attendno, unattendno, attendmaybe, unattendmaybe
2967          * @return bool
2968          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2969          * @throws \ImagickException
2970          * @hook  'post_local_end'
2971          *            array $arr
2972          *            'post_id' => ID of posted item
2973          */
2974         public static function performLike($item_id, $verb)
2975         {
2976                 if (!local_user() && !remote_user()) {
2977                         return false;
2978                 }
2979
2980                 switch ($verb) {
2981                         case 'like':
2982                         case 'unlike':
2983                                 $activity = ACTIVITY_LIKE;
2984                                 break;
2985                         case 'dislike':
2986                         case 'undislike':
2987                                 $activity = ACTIVITY_DISLIKE;
2988                                 break;
2989                         case 'attendyes':
2990                         case 'unattendyes':
2991                                 $activity = ACTIVITY_ATTEND;
2992                                 break;
2993                         case 'attendno':
2994                         case 'unattendno':
2995                                 $activity = ACTIVITY_ATTENDNO;
2996                                 break;
2997                         case 'attendmaybe':
2998                         case 'unattendmaybe':
2999                                 $activity = ACTIVITY_ATTENDMAYBE;
3000                                 break;
3001                         default:
3002                                 Logger::log('like: unknown verb ' . $verb . ' for item ' . $item_id);
3003                                 return false;
3004                 }
3005
3006                 // Enable activity toggling instead of on/off
3007                 $event_verb_flag = $activity === ACTIVITY_ATTEND || $activity === ACTIVITY_ATTENDNO || $activity === ACTIVITY_ATTENDMAYBE;
3008
3009                 Logger::log('like: verb ' . $verb . ' item ' . $item_id);
3010
3011                 $item = self::selectFirst(self::ITEM_FIELDLIST, ['`id` = ? OR `uri` = ?', $item_id, $item_id]);
3012                 if (!DBA::isResult($item)) {
3013                         Logger::log('like: unknown item ' . $item_id);
3014                         return false;
3015                 }
3016
3017                 $item_uri = $item['uri'];
3018
3019                 $uid = $item['uid'];
3020                 if (($uid == 0) && local_user()) {
3021                         $uid = local_user();
3022                 }
3023
3024                 if (!Security::canWriteToUserWall($uid)) {
3025                         Logger::log('like: unable to write on wall ' . $uid);
3026                         return false;
3027                 }
3028
3029                 // Retrieves the local post owner
3030                 $owner_self_contact = DBA::selectFirst('contact', [], ['uid' => $uid, 'self' => true]);
3031                 if (!DBA::isResult($owner_self_contact)) {
3032                         Logger::log('like: unknown owner ' . $uid);
3033                         return false;
3034                 }
3035
3036                 // Retrieve the current logged in user's public contact
3037                 $author_id = public_contact();
3038
3039                 $author_contact = DBA::selectFirst('contact', ['url'], ['id' => $author_id]);
3040                 if (!DBA::isResult($author_contact)) {
3041                         Logger::log('like: unknown author ' . $author_id);
3042                         return false;
3043                 }
3044
3045                 // Contact-id is the uid-dependant author contact
3046                 if (local_user() == $uid) {
3047                         $item_contact_id = $owner_self_contact['id'];
3048                 } else {
3049                         $item_contact_id = Contact::getIdForURL($author_contact['url'], $uid, true);
3050                         $item_contact = DBA::selectFirst('contact', [], ['id' => $item_contact_id]);
3051                         if (!DBA::isResult($item_contact)) {
3052                                 Logger::log('like: unknown item contact ' . $item_contact_id);
3053                                 return false;
3054                         }
3055                 }
3056
3057                 // Look for an existing verb row
3058                 // event participation are essentially radio toggles. If you make a subsequent choice,
3059                 // we need to eradicate your first choice.
3060                 if ($event_verb_flag) {
3061                         $verbs = [ACTIVITY_ATTEND, ACTIVITY_ATTENDNO, ACTIVITY_ATTENDMAYBE];
3062
3063                         // Translate to the index based activity index
3064                         $activities = [];
3065                         foreach ($verbs as $verb) {
3066                                 $activities[] = self::activityToIndex($verb);
3067                         }
3068                 } else {
3069                         $activities = self::activityToIndex($activity);
3070                 }
3071
3072                 $condition = ['activity' => $activities, 'deleted' => false, 'gravity' => GRAVITY_ACTIVITY,
3073                         'author-id' => $author_id, 'uid' => $item['uid'], 'thr-parent' => $item_uri];
3074
3075                 $like_item = self::selectFirst(['id', 'guid', 'verb'], $condition);
3076
3077                 // If it exists, mark it as deleted
3078                 if (DBA::isResult($like_item)) {
3079                         self::deleteById($like_item['id']);
3080
3081                         if (!$event_verb_flag || $like_item['verb'] == $activity) {
3082                                 return true;
3083                         }
3084                 }
3085
3086                 // Verb is "un-something", just trying to delete existing entries
3087                 if (strpos($verb, 'un') === 0) {
3088                         return true;
3089                 }
3090
3091                 $objtype = $item['resource-id'] ? ACTIVITY_OBJ_IMAGE : ACTIVITY_OBJ_NOTE;
3092
3093                 $new_item = [
3094                         'guid'          => System::createUUID(),
3095                         'uri'           => self::newURI($item['uid']),
3096                         'uid'           => $item['uid'],
3097                         'contact-id'    => $item_contact_id,
3098                         'wall'          => $item['wall'],
3099                         'origin'        => 1,
3100                         'network'       => Protocol::DFRN,
3101                         'gravity'       => GRAVITY_ACTIVITY,
3102                         'parent'        => $item['id'],
3103                         'parent-uri'    => $item['uri'],
3104                         'thr-parent'    => $item['uri'],
3105                         'owner-id'      => $author_id,
3106                         'author-id'     => $author_id,
3107                         'body'          => $activity,
3108                         'verb'          => $activity,
3109                         'object-type'   => $objtype,
3110                         'allow_cid'     => $item['allow_cid'],
3111                         'allow_gid'     => $item['allow_gid'],
3112                         'deny_cid'      => $item['deny_cid'],
3113                         'deny_gid'      => $item['deny_gid'],
3114                         'visible'       => 1,
3115                         'unseen'        => 1,
3116                 ];
3117
3118                 $signed = Diaspora::createLikeSignature($uid, $new_item);
3119                 if (!empty($signed)) {
3120                         $new_item['diaspora_signed_text'] = json_encode($signed);
3121                 }
3122
3123                 $new_item_id = self::insert($new_item);
3124
3125                 // If the parent item isn't visible then set it to visible
3126                 if (!$item['visible']) {
3127                         self::update(['visible' => true], ['id' => $item['id']]);
3128                 }
3129
3130                 $new_item['id'] = $new_item_id;
3131
3132                 Hook::callAll('post_local_end', $new_item);
3133
3134                 return true;
3135         }
3136
3137         private static function addThread($itemid, $onlyshadow = false)
3138         {
3139                 $fields = ['uid', 'created', 'edited', 'commented', 'received', 'changed', 'wall', 'private', 'pubmail',
3140                         'moderated', 'visible', 'starred', 'contact-id', 'post-type',
3141                         'deleted', 'origin', 'forum_mode', 'mention', 'network', 'author-id', 'owner-id'];
3142                 $condition = ["`id` = ? AND (`parent` = ? OR `parent` = 0)", $itemid, $itemid];
3143                 $item = self::selectFirst($fields, $condition);
3144
3145                 if (!DBA::isResult($item)) {
3146                         return;
3147                 }
3148
3149                 $item['iid'] = $itemid;
3150
3151                 if (!$onlyshadow) {
3152                         $result = DBA::insert('thread', $item);
3153
3154                         Logger::log("Add thread for item ".$itemid." - ".print_r($result, true), Logger::DEBUG);
3155                 }
3156         }
3157
3158         private static function updateThread($itemid, $setmention = false)
3159         {
3160                 $fields = ['uid', 'guid', 'created', 'edited', 'commented', 'received', 'changed', 'post-type',
3161                         'wall', 'private', 'pubmail', 'moderated', 'visible', 'starred', 'contact-id',
3162                         'deleted', 'origin', 'forum_mode', 'network', 'author-id', 'owner-id'];
3163                 $condition = ["`id` = ? AND (`parent` = ? OR `parent` = 0)", $itemid, $itemid];
3164
3165                 $item = self::selectFirst($fields, $condition);
3166                 if (!DBA::isResult($item)) {
3167                         return;
3168                 }
3169
3170                 if ($setmention) {
3171                         $item["mention"] = 1;
3172                 }
3173
3174                 $fields = [];
3175
3176                 foreach ($item as $field => $data) {
3177                         if (!in_array($field, ["guid"])) {
3178                                 $fields[$field] = $data;
3179                         }
3180                 }
3181
3182                 $result = DBA::update('thread', $fields, ['iid' => $itemid]);
3183
3184                 Logger::log("Update thread for item ".$itemid." - guid ".$item["guid"]." - ".(int)$result, Logger::DEBUG);
3185         }
3186
3187         private static function deleteThread($itemid, $itemuri = "")
3188         {
3189                 $item = DBA::selectFirst('thread', ['uid'], ['iid' => $itemid]);
3190                 if (!DBA::isResult($item)) {
3191                         Logger::log('No thread found for id '.$itemid, Logger::DEBUG);
3192                         return;
3193                 }
3194
3195                 $result = DBA::delete('thread', ['iid' => $itemid], ['cascade' => false]);
3196
3197                 Logger::log("deleteThread: Deleted thread for item ".$itemid." - ".print_r($result, true), Logger::DEBUG);
3198
3199                 if ($itemuri != "") {
3200                         $condition = ["`uri` = ? AND NOT `deleted` AND NOT (`uid` IN (?, 0))", $itemuri, $item["uid"]];
3201                         if (!self::exists($condition)) {
3202                                 DBA::delete('item', ['uri' => $itemuri, 'uid' => 0]);
3203                                 Logger::log("deleteThread: Deleted shadow for item ".$itemuri, Logger::DEBUG);
3204                         }
3205                 }
3206         }
3207
3208         public static function getPermissionsSQLByUserId($owner_id, $remote_verified = false, $groups = null, $remote_cid = null)
3209         {
3210                 $local_user = local_user();
3211                 $remote_user = remote_user();
3212
3213                 /*
3214                  * Construct permissions
3215                  *
3216                  * default permissions - anonymous user
3217                  */
3218                 $sql = " AND NOT `item`.`private`";
3219
3220                 // Profile owner - everything is visible
3221                 if ($local_user && ($local_user == $owner_id)) {
3222                         $sql = '';
3223                 } elseif ($remote_user) {
3224                         /*
3225                          * Authenticated visitor. Unless pre-verified,
3226                          * check that the contact belongs to this $owner_id
3227                          * and load the groups the visitor belongs to.
3228                          * If pre-verified, the caller is expected to have already
3229                          * done this and passed the groups into this function.
3230                          */
3231                         $set = PermissionSet::get($owner_id, $remote_cid, $groups);
3232
3233                         if (!empty($set)) {
3234                                 $sql_set = " OR (`item`.`private` IN (1,2) AND `item`.`wall` AND `item`.`psid` IN (" . implode(',', $set) . "))";
3235                         } else {
3236                                 $sql_set = '';
3237                         }
3238
3239                         $sql = " AND (NOT `item`.`private`" . $sql_set . ")";
3240                 }
3241
3242                 return $sql;
3243         }
3244
3245         /**
3246          * get translated item type
3247          *
3248          * @param $item
3249          * @return string
3250          */
3251         public static function postType($item)
3252         {
3253                 if (!empty($item['event-id'])) {
3254                         return L10n::t('event');
3255                 } elseif (!empty($item['resource-id'])) {
3256                         return L10n::t('photo');
3257                 } elseif (!empty($item['verb']) && $item['verb'] !== ACTIVITY_POST) {
3258                         return L10n::t('activity');
3259                 } elseif ($item['id'] != $item['parent']) {
3260                         return L10n::t('comment');
3261                 }
3262
3263                 return L10n::t('post');
3264         }
3265
3266         /**
3267          * Sets the "rendered-html" field of the provided item
3268          *
3269          * Body is preserved to avoid side-effects as we modify it just-in-time for spoilers and private image links
3270          *
3271          * @param array $item
3272          * @param bool  $update
3273          *
3274          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3275          * @todo Remove reference, simply return "rendered-html" and "rendered-hash"
3276          */
3277         public static function putInCache(&$item, $update = false)
3278         {
3279                 $body = $item["body"];
3280
3281                 $rendered_hash = defaults($item, 'rendered-hash', '');
3282                 $rendered_html = defaults($item, 'rendered-html', '');
3283
3284                 if ($rendered_hash == ''
3285                         || $rendered_html == ""
3286                         || $rendered_hash != hash("md5", $item["body"])
3287                         || Config::get("system", "ignore_cache")
3288                 ) {
3289                         $a = self::getApp();
3290                         redir_private_images($a, $item);
3291
3292                         $item["rendered-html"] = prepare_text($item["body"]);
3293                         $item["rendered-hash"] = hash("md5", $item["body"]);
3294
3295                         $hook_data = ['item' => $item, 'rendered-html' => $item['rendered-html'], 'rendered-hash' => $item['rendered-hash']];
3296                         Hook::callAll('put_item_in_cache', $hook_data);
3297                         $item['rendered-html'] = $hook_data['rendered-html'];
3298                         $item['rendered-hash'] = $hook_data['rendered-hash'];
3299                         unset($hook_data);
3300
3301                         // Force an update if the generated values differ from the existing ones
3302                         if ($rendered_hash != $item["rendered-hash"]) {
3303                                 $update = true;
3304                         }
3305
3306                         // Only compare the HTML when we forcefully ignore the cache
3307                         if (Config::get("system", "ignore_cache") && ($rendered_html != $item["rendered-html"])) {
3308                                 $update = true;
3309                         }
3310
3311                         if ($update && !empty($item["id"])) {
3312                                 self::update(
3313                                         [
3314                                                 'rendered-html' => $item["rendered-html"],
3315                                                 'rendered-hash' => $item["rendered-hash"]
3316                                         ],
3317                                         ['id' => $item["id"]]
3318                                 );
3319                         }
3320                 }
3321
3322                 $item["body"] = $body;
3323         }
3324
3325         /**
3326          * @brief Given an item array, convert the body element from bbcode to html and add smilie icons.
3327          * If attach is true, also add icons for item attachments.
3328          *
3329          * @param array   $item
3330          * @param boolean $attach
3331          * @param boolean $is_preview
3332          * @return string item body html
3333          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3334          * @throws \ImagickException
3335          * @hook  prepare_body_init item array before any work
3336          * @hook  prepare_body_content_filter ('item'=>item array, 'filter_reasons'=>string array) before first bbcode to html
3337          * @hook  prepare_body ('item'=>item array, 'html'=>body string, 'is_preview'=>boolean, 'filter_reasons'=>string array) after first bbcode to html
3338          * @hook  prepare_body_final ('item'=>item array, 'html'=>body string) after attach icons and blockquote special case handling (spoiler, author)
3339          */
3340         public static function prepareBody(array &$item, $attach = false, $is_preview = false)
3341         {
3342                 $a = self::getApp();
3343                 Hook::callAll('prepare_body_init', $item);
3344
3345                 // In order to provide theme developers more possibilities, event items
3346                 // are treated differently.
3347                 if ($item['object-type'] === ACTIVITY_OBJ_EVENT && isset($item['event-id'])) {
3348                         $ev = Event::getItemHTML($item);
3349                         return $ev;
3350                 }
3351
3352                 $tags = Term::populateTagsFromItem($item);
3353
3354                 $item['tags'] = $tags['tags'];
3355                 $item['hashtags'] = $tags['hashtags'];
3356                 $item['mentions'] = $tags['mentions'];
3357
3358                 // Compile eventual content filter reasons
3359                 $filter_reasons = [];
3360                 if (!$is_preview && public_contact() != $item['author-id']) {
3361                         if (!empty($item['content-warning']) && (!local_user() || !PConfig::get(local_user(), 'system', 'disable_cw', false))) {
3362                                 $filter_reasons[] = L10n::t('Content warning: %s', $item['content-warning']);
3363                         }
3364
3365                         $hook_data = [
3366                                 'item' => $item,
3367                                 'filter_reasons' => $filter_reasons
3368                         ];
3369                         Hook::callAll('prepare_body_content_filter', $hook_data);
3370                         $filter_reasons = $hook_data['filter_reasons'];
3371                         unset($hook_data);
3372                 }
3373
3374                 // Update the cached values if there is no "zrl=..." on the links.
3375                 $update = (!local_user() && !remote_user() && ($item["uid"] == 0));
3376
3377                 // Or update it if the current viewer is the intented viewer.
3378                 if (($item["uid"] == local_user()) && ($item["uid"] != 0)) {
3379                         $update = true;
3380                 }
3381
3382                 self::putInCache($item, $update);
3383                 $s = $item["rendered-html"];
3384
3385                 $hook_data = [
3386                         'item' => $item,
3387                         'html' => $s,
3388                         'preview' => $is_preview,
3389                         'filter_reasons' => $filter_reasons
3390                 ];
3391                 Hook::callAll('prepare_body', $hook_data);
3392                 $s = $hook_data['html'];
3393                 unset($hook_data);
3394
3395                 if (!$attach) {
3396                         // Replace the blockquotes with quotes that are used in mails.
3397                         $mailquote = '<blockquote type="cite" class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex;">';
3398                         $s = str_replace(['<blockquote>', '<blockquote class="spoiler">', '<blockquote class="author">'], [$mailquote, $mailquote, $mailquote], $s);
3399                         return $s;
3400                 }
3401
3402                 $as = '';
3403                 $vhead = false;
3404                 $matches = [];
3405                 preg_match_all('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\"(?: title=\"(.*?)\")?|', $item['attach'], $matches, PREG_SET_ORDER);
3406                 foreach ($matches as $mtch) {
3407                         $mime = $mtch[3];
3408
3409                         $the_url = Contact::magicLinkById($item['author-id'], $mtch[1]);
3410
3411                         if (strpos($mime, 'video') !== false) {
3412                                 if (!$vhead) {
3413                                         $vhead = true;
3414                                         $a->page['htmlhead'] .= Renderer::replaceMacros(Renderer::getMarkupTemplate('videos_head.tpl'));
3415                                 }
3416
3417                                 $url_parts = explode('/', $the_url);
3418                                 $id = end($url_parts);
3419                                 $as .= Renderer::replaceMacros(Renderer::getMarkupTemplate('video_top.tpl'), [
3420                                         '$video' => [
3421                                                 'id'     => $id,
3422                                                 'title'  => L10n::t('View Video'),
3423                                                 'src'    => $the_url,
3424                                                 'mime'   => $mime,
3425                                         ],
3426                                 ]);
3427                         }
3428
3429                         $filetype = strtolower(substr($mime, 0, strpos($mime, '/')));
3430                         if ($filetype) {
3431                                 $filesubtype = strtolower(substr($mime, strpos($mime, '/') + 1));
3432                                 $filesubtype = str_replace('.', '-', $filesubtype);
3433                         } else {
3434                                 $filetype = 'unkn';
3435                                 $filesubtype = 'unkn';
3436                         }
3437
3438                         $title = Strings::escapeHtml(trim(defaults($mtch, 4, $mtch[1])));
3439                         $title .= ' ' . $mtch[2] . ' ' . L10n::t('bytes');
3440
3441                         $icon = '<div class="attachtype icon s22 type-' . $filetype . ' subtype-' . $filesubtype . '"></div>';
3442                         $as .= '<a href="' . strip_tags($the_url) . '" title="' . $title . '" class="attachlink" target="_blank" >' . $icon . '</a>';
3443                 }
3444
3445                 if ($as != '') {
3446                         $s .= '<div class="body-attach">'.$as.'<div class="clear"></div></div>';
3447                 }
3448
3449                 // Map.
3450                 if (strpos($s, '<div class="map">') !== false && !empty($item['coord'])) {
3451                         $x = Map::byCoordinates(trim($item['coord']));
3452                         if ($x) {
3453                                 $s = preg_replace('/\<div class\=\"map\"\>/', '$0' . $x, $s);
3454                         }
3455                 }
3456
3457
3458                 // Look for spoiler.
3459                 $spoilersearch = '<blockquote class="spoiler">';
3460
3461                 // Remove line breaks before the spoiler.
3462                 while ((strpos($s, "\n" . $spoilersearch) !== false)) {
3463                         $s = str_replace("\n" . $spoilersearch, $spoilersearch, $s);
3464                 }
3465                 while ((strpos($s, "<br />" . $spoilersearch) !== false)) {
3466                         $s = str_replace("<br />" . $spoilersearch, $spoilersearch, $s);
3467                 }
3468
3469                 while ((strpos($s, $spoilersearch) !== false)) {
3470                         $pos = strpos($s, $spoilersearch);
3471                         $rnd = Strings::getRandomHex(8);
3472                         $spoilerreplace = '<br /> <span id="spoiler-wrap-' . $rnd . '" class="spoiler-wrap fakelink" onclick="openClose(\'spoiler-' . $rnd . '\');">' . L10n::t('Click to open/close') . '</span>'.
3473                                                 '<blockquote class="spoiler" id="spoiler-' . $rnd . '" style="display: none;">';
3474                         $s = substr($s, 0, $pos) . $spoilerreplace . substr($s, $pos + strlen($spoilersearch));
3475                 }
3476
3477                 // Look for quote with author.
3478                 $authorsearch = '<blockquote class="author">';
3479
3480                 while ((strpos($s, $authorsearch) !== false)) {
3481                         $pos = strpos($s, $authorsearch);
3482                         $rnd = Strings::getRandomHex(8);
3483                         $authorreplace = '<br /> <span id="author-wrap-' . $rnd . '" class="author-wrap fakelink" onclick="openClose(\'author-' . $rnd . '\');">' . L10n::t('Click to open/close') . '</span>'.
3484                                                 '<blockquote class="author" id="author-' . $rnd . '" style="display: block;">';
3485                         $s = substr($s, 0, $pos) . $authorreplace . substr($s, $pos + strlen($authorsearch));
3486                 }
3487
3488                 // Replace friendica image url size with theme preference.
3489                 if (!empty($a->theme_info['item_image_size'])) {
3490                         $ps = $a->theme_info['item_image_size'];
3491                         $s = preg_replace('|(<img[^>]+src="[^"]+/photo/[0-9a-f]+)-[0-9]|', "$1-" . $ps, $s);
3492                 }
3493
3494                 $s = HTML::applyContentFilter($s, $filter_reasons);
3495
3496                 $hook_data = ['item' => $item, 'html' => $s];
3497                 Hook::callAll('prepare_body_final', $hook_data);
3498
3499                 return $hook_data['html'];
3500         }
3501
3502         /**
3503          * get private link for item
3504          *
3505          * @param array $item
3506          * @return boolean|array False if item has not plink, otherwise array('href'=>plink url, 'title'=>translated title)
3507          * @throws \Exception
3508          */
3509         public static function getPlink($item)
3510         {
3511                 $a = self::getApp();
3512
3513                 if ($a->user['nickname'] != "") {
3514                         $ret = [
3515                                 'href' => "display/" . $item['guid'],
3516                                 'orig' => "display/" . $item['guid'],
3517                                 'title' => L10n::t('View on separate page'),
3518                                 'orig_title' => L10n::t('view on separate page'),
3519                         ];
3520
3521                         if (!empty($item['plink'])) {
3522                                 $ret["href"] = $a->removeBaseURL($item['plink']);
3523                                 $ret["title"] = L10n::t('link to source');
3524                         }
3525
3526                 } elseif (!empty($item['plink']) && ($item['private'] != 1)) {
3527                         $ret = [
3528                                 'href' => $item['plink'],
3529                                 'orig' => $item['plink'],
3530                                 'title' => L10n::t('link to source'),
3531                         ];
3532                 } else {
3533                         $ret = [];
3534                 }
3535
3536                 return $ret;
3537         }
3538
3539         /**
3540          * Is the given item array a post that is sent as starting post to a forum?
3541          *
3542          * @param array $item
3543          * @param array $owner
3544          *
3545          * @return boolean "true" when it is a forum post
3546          */
3547         public static function isForumPost(array $item, array $owner = [])
3548         {
3549                 if (empty($owner)) {
3550                         $owner = User::getOwnerDataById($item['uid']);
3551                         if (empty($owner)) {
3552                                 return false;
3553                         }
3554                 }
3555
3556                 if (($item['author-id'] == $item['owner-id']) ||
3557                         ($owner['id'] == $item['contact-id']) ||
3558                         ($item['uri'] != $item['parent-uri']) ||
3559                         $item['origin']) {
3560                         return false;
3561                 }
3562
3563                 return Contact::isForum($item['contact-id']);
3564         }
3565 }