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