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