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