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