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