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