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