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