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