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