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