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