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