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