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