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