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