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