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