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