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