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