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