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