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