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