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