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