]> git.mxchange.org Git - friendica.git/blob - src/Worker/OnePoll.php
377bda85f4c4ebd94b3eea0c47f2d1329c7ffab8
[friendica.git] / src / Worker / OnePoll.php
1 <?php
2 /**
3  * @file src/Worker/OnePoll.php
4  */
5 namespace Friendica\Worker;
6
7 use Friendica\Content\Text\BBCode;
8 use Friendica\Core\Config;
9 use Friendica\Core\PConfig;
10 use Friendica\Database\DBM;
11 use Friendica\Model\Contact;
12 use Friendica\Model\Item;
13 use Friendica\Protocol\Email;
14 use Friendica\Protocol\PortableContact;
15 use Friendica\Util\DateTimeFormat;
16 use Friendica\Util\Network;
17 use Friendica\Util\XML;
18 use dba;
19
20 require_once 'include/dba.php';
21
22 class OnePoll
23 {
24         public static function execute($contact_id = 0, $command = '') {
25                 global $a;
26
27                 require_once 'include/items.php';
28
29                 logger('start');
30
31                 $manual_id  = 0;
32                 $generation = 0;
33                 $hub_update = false;
34                 $force      = false;
35                 $restart    = false;
36
37                 if ($command == "force") {
38                         $force = true;
39                 }
40
41                 if (!$contact_id) {
42                         logger('no contact');
43                         return;
44                 }
45
46                 $d = DateTimeFormat::utcNow();
47
48                 $contact = dba::selectFirst('contact', [], ['id' => $contact_id]);
49                 if (!DBM::is_result($contact)) {
50                         logger('Contact not found or cannot be used.');
51                         return;
52                 }
53
54                 $importer_uid = $contact['uid'];
55
56                 // load current friends if possible.
57                 if (($contact['poco'] != "") && ($contact['success_update'] > $contact['failure_update'])) {
58                         $r = q("SELECT count(*) AS total FROM glink
59                                 WHERE `cid` = %d AND updated > UTC_TIMESTAMP() - INTERVAL 1 DAY",
60                                 intval($contact['id'])
61                         );
62                         if (DBM::is_result($r)) {
63                                 if (!$r[0]['total']) {
64                                         PortableContact::loadWorker($contact['id'], $importer_uid, 0, $contact['poco']);
65                                 }
66                         }
67                 }
68
69                 // Diaspora users, archived users and followers are only checked if they still exist.
70                 if ($contact['archive'] || ($contact["network"] == NETWORK_DIASPORA) || ($contact["rel"] == CONTACT_IS_FOLLOWER)) {
71                         $last_updated = PortableContact::lastUpdated($contact["url"], true);
72                         $updated = DateTimeFormat::utcNow();
73                         if ($last_updated) {
74                                 logger('Contact '.$contact['id'].' had last update on '.$last_updated, LOGGER_DEBUG);
75
76                                 // The last public item can be older than the last item we got
77                                 if ($last_updated < $contact['last-item']) {
78                                         $last_updated = $contact['last-item'];
79                                 }
80
81                                 $fields = ['last-item' => $last_updated, 'last-update' => $updated, 'success_update' => $updated];
82                                 self::updateContact($contact, $fields);
83                                 Contact::unmarkForArchival($contact);
84                         } else {
85                                 self::updateContact($contact, ['last-update' => $updated, 'failure_update' => $updated]);
86                                 Contact::markForArchival($contact);
87                                 logger('Contact '.$contact['id'].' is marked for archival', LOGGER_DEBUG);
88                         }
89                         return;
90                 }
91
92                 $xml = false;
93
94                 $t = $contact['last-update'];
95
96                 if ($contact['subhub']) {
97                         $poll_interval = Config::get('system', 'pushpoll_frequency', 3);
98                         $contact['priority'] = intval($poll_interval);
99                         $hub_update = false;
100
101                         if (DateTimeFormat::utcNow() > DateTimeFormat::utc($t . " + 1 day")) {
102                                 $hub_update = true;
103                         }
104                 } else {
105                         $hub_update = false;
106                 }
107
108                 $last_update = (($contact['last-update'] <= NULL_DATE)
109                         ? DateTimeFormat::utc('now - 7 days', DateTimeFormat::ATOM)
110                         : DateTimeFormat::utc($contact['last-update'], DateTimeFormat::ATOM)
111                 );
112
113                 // Update the contact entry
114                 if (($contact['network'] === NETWORK_OSTATUS) || ($contact['network'] === NETWORK_DIASPORA) || ($contact['network'] === NETWORK_DFRN)) {
115                         if (!PortableContact::reachable($contact['url'])) {
116                                 logger("Skipping probably dead contact ".$contact['url']);
117
118                                 // set the last-update so we don't keep polling
119                                 dba::update('contact', ['last-update' => DateTimeFormat::utcNow()], ['id' => $contact['id']]);
120                                 return;
121                         }
122
123                         if (!Contact::updateFromProbe($contact["id"])) {
124                                 Contact::markForArchival($contact);
125                                 logger('Contact is marked dead');
126
127                                 // set the last-update so we don't keep polling
128                                 dba::update('contact', ['last-update' => DateTimeFormat::utcNow()], ['id' => $contact['id']]);
129                                 return;
130                         } else {
131                                 Contact::unmarkForArchival($contact);
132                         }
133                 }
134
135                 if ($importer_uid == 0) {
136                         logger('Ignore public contacts');
137
138                         // set the last-update so we don't keep polling
139                         dba::update('contact', ['last-update' => DateTimeFormat::utcNow()], ['id' => $contact['id']]);
140                         return;
141                 }
142
143                 $r = q("SELECT `contact`.*, `user`.`page-flags` FROM `contact` INNER JOIN `user` on `contact`.`uid` = `user`.`uid` WHERE `user`.`uid` = %d AND `contact`.`self` = 1 LIMIT 1",
144                         intval($importer_uid)
145                 );
146
147                 if (!DBM::is_result($r)) {
148                         logger('No self contact for user '.$importer_uid);
149
150                         // set the last-update so we don't keep polling
151                         dba::update('contact', ['last-update' => DateTimeFormat::utcNow()], ['id' => $contact['id']]);
152                         return;
153                 }
154
155                 $importer = $r[0];
156
157                 logger("poll: ({$contact['network']}-{$contact['id']}) IMPORTER: {$importer['name']}, CONTACT: {$contact['name']}");
158
159                 if ($contact['network'] === NETWORK_DFRN) {
160                         $idtosend = $orig_id = (($contact['dfrn-id']) ? $contact['dfrn-id'] : $contact['issued-id']);
161                         if (intval($contact['duplex']) && $contact['dfrn-id']) {
162                                 $idtosend = '0:' . $orig_id;
163                         }
164                         if (intval($contact['duplex']) && $contact['issued-id']) {
165                                 $idtosend = '1:' . $orig_id;
166                         }
167
168                         // they have permission to write to us. We already filtered this in the contact query.
169                         $perm = 'rw';
170
171                         // But this may be our first communication, so set the writable flag if it isn't set already.
172
173                         if (!intval($contact['writable'])) {
174                                 $fields = ['writable' => true];
175                                 dba::update('contact', $fields, ['id' => $contact['id']]);
176                         }
177
178                         $url = $contact['poll'] . '?dfrn_id=' . $idtosend
179                                 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
180                                 . '&type=data&last_update=' . $last_update
181                                 . '&perm=' . $perm ;
182
183                         $ret = Network::curl($url);
184
185                         if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
186                                 // set the last-update so we don't keep polling
187                                 dba::update('contact', ['last-update' => DateTimeFormat::utcNow()], ['id' => $contact['id']]);
188                                 Contact::markForArchival($contact);
189                                 return;
190                         }
191
192                         $handshake_xml = $ret['body'];
193
194                         $html_code = $a->get_curl_code();
195
196                         logger('handshake with url ' . $url . ' returns xml: ' . $handshake_xml, LOGGER_DATA);
197
198
199                         if (!strlen($handshake_xml) || ($html_code >= 400) || !$html_code) {
200                                 logger("$url appears to be dead - marking for death ");
201
202                                 // dead connection - might be a transient event, or this might
203                                 // mean the software was uninstalled or the domain expired.
204                                 // Will keep trying for one month.
205
206                                 Contact::markForArchival($contact);
207
208                                 // set the last-update so we don't keep polling
209                                 $fields = ['last-update' => DateTimeFormat::utcNow(), 'failure_update' => DateTimeFormat::utcNow()];
210                                 self::updateContact($contact, $fields);
211                                 return;
212                         }
213
214                         if (!strstr($handshake_xml, '<')) {
215                                 logger('response from ' . $url . ' did not contain XML.');
216
217                                 Contact::markForArchival($contact);
218
219                                 $fields = ['last-update' => DateTimeFormat::utcNow(), 'failure_update' => DateTimeFormat::utcNow()];
220                                 self::updateContact($contact, $fields);
221                                 return;
222                         }
223
224
225                         $res = XML::parseString($handshake_xml);
226
227                         if (intval($res->status) == 1) {
228                                 logger("$url replied status 1 - marking for death ");
229
230                                 // we may not be friends anymore. Will keep trying for one month.
231                                 // set the last-update so we don't keep polling
232                                 $fields = ['last-update' => DateTimeFormat::utcNow(), 'failure_update' => DateTimeFormat::utcNow()];
233                                 self::updateContact($contact, $fields);
234
235                                 Contact::markForArchival($contact);
236                         } elseif ($contact['term-date'] > NULL_DATE) {
237                                 logger("$url back from the dead - removing mark for death");
238                                 Contact::unmarkForArchival($contact);
239                         }
240
241                         if ((intval($res->status) != 0) || !strlen($res->challenge) || !strlen($res->dfrn_id)) {
242                                 // set the last-update so we don't keep polling
243                                 dba::update('contact', ['last-update' => DateTimeFormat::utcNow()], ['id' => $contact['id']]);
244                                 return;
245                         }
246
247                         if (((float)$res->dfrn_version > 2.21) && ($contact['poco'] == '')) {
248                                 $fields = ['poco' => str_replace('/profile/', '/poco/', $contact['url'])];
249                                 dba::update('contact', $fields, ['id' => $contact['id']]);
250                         }
251
252                         $postvars = [];
253
254                         $sent_dfrn_id = hex2bin((string) $res->dfrn_id);
255                         $challenge    = hex2bin((string) $res->challenge);
256
257                         $final_dfrn_id = '';
258
259                         if ($contact['duplex'] && strlen($contact['prvkey'])) {
260                                 openssl_private_decrypt($sent_dfrn_id, $final_dfrn_id, $contact['prvkey']);
261                                 openssl_private_decrypt($challenge, $postvars['challenge'], $contact['prvkey']);
262                         } else {
263                                 openssl_public_decrypt($sent_dfrn_id, $final_dfrn_id, $contact['pubkey']);
264                                 openssl_public_decrypt($challenge, $postvars['challenge'], $contact['pubkey']);
265                         }
266
267                         $final_dfrn_id = substr($final_dfrn_id, 0, strpos($final_dfrn_id, '.'));
268
269                         if (strpos($final_dfrn_id, ':') == 1) {
270                                 $final_dfrn_id = substr($final_dfrn_id, 2);
271                         }
272
273                         if ($final_dfrn_id != $orig_id) {
274                                 // did not decode properly - cannot trust this site
275                                 logger('ID did not decode: ' . $contact['id'] . ' orig: ' . $orig_id . ' final: ' . $final_dfrn_id);
276
277                                 // set the last-update so we don't keep polling
278                                 dba::update('contact', ['last-update' => DateTimeFormat::utcNow()], ['id' => $contact['id']]);
279                                 Contact::markForArchival($contact);
280                                 return;
281                         }
282
283                         $postvars['dfrn_id'] = $idtosend;
284                         $postvars['dfrn_version'] = DFRN_PROTOCOL_VERSION;
285                         $postvars['perm'] = 'rw';
286
287                         $xml = Network::post($contact['poll'], $postvars);
288
289                 } elseif (($contact['network'] === NETWORK_OSTATUS)
290                         || ($contact['network'] === NETWORK_DIASPORA)
291                         || ($contact['network'] === NETWORK_FEED)) {
292
293                         // Upgrading DB fields from an older Friendica version
294                         // Will only do this once per notify-enabled OStatus contact
295                         // or if relationship changes
296
297                         $stat_writeable = ((($contact['notify']) && ($contact['rel'] == CONTACT_IS_FOLLOWER || $contact['rel'] == CONTACT_IS_FRIEND)) ? 1 : 0);
298
299                         // Contacts from OStatus are always writable
300                         if ($contact['network'] === NETWORK_OSTATUS) {
301                                 $stat_writeable = 1;
302                         }
303
304                         if ($stat_writeable != $contact['writable']) {
305                                 $fields = ['writable' => $stat_writeable];
306                                 dba::update('contact', $fields, ['id' => $contact['id']]);
307                         }
308
309                         // Are we allowed to import from this person?
310
311                         if ($contact['rel'] == CONTACT_IS_FOLLOWER || $contact['blocked'] || $contact['readonly']) {
312                                 // set the last-update so we don't keep polling
313                                 dba::update('contact', ['last-update' => DateTimeFormat::utcNow()], ['id' => $contact['id']]);
314                                 return;
315                         }
316
317                         $cookiejar = tempnam(get_temppath(), 'cookiejar-onepoll-');
318                         $ret = Network::curl($contact['poll'], false, $redirects, ['cookiejar' => $cookiejar]);
319                         unlink($cookiejar);
320
321                         if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
322                                 // set the last-update so we don't keep polling
323                                 dba::update('contact', ['last-update' => DateTimeFormat::utcNow()], ['id' => $contact['id']]);
324                                 Contact::markForArchival($contact);
325                                 return;
326                         }
327
328                         $xml = $ret['body'];
329
330                 } elseif ($contact['network'] === NETWORK_MAIL) {
331
332                         logger("Mail: Fetching for ".$contact['addr'], LOGGER_DEBUG);
333
334                         $mail_disabled = ((function_exists('imap_open') && (! Config::get('system', 'imap_disabled'))) ? 0 : 1);
335                         if ($mail_disabled) {
336                                 // set the last-update so we don't keep polling
337                                 dba::update('contact', ['last-update' => DateTimeFormat::utcNow()], ['id' => $contact['id']]);
338                                 Contact::markForArchival($contact);
339                                 return;
340                         }
341
342                         logger("Mail: Enabled", LOGGER_DEBUG);
343
344                         $mbox = null;
345                         $user = dba::selectFirst('user', ['prvkey'], ['uid' => $importer_uid]);
346
347                         $condition = ["`server` != '' AND `uid` = ?", $importer_uid];
348                         $mailconf = dba::selectFirst('mailacct', [], $condition);
349                         if (DBM::is_result($user) && DBM::is_result($mailconf)) {
350                                 $mailbox = Email::constructMailboxName($mailconf);
351                                 $password = '';
352                                 openssl_private_decrypt(hex2bin($mailconf['pass']), $password, $user['prvkey']);
353                                 $mbox = Email::connect($mailbox, $mailconf['user'], $password);
354                                 unset($password);
355                                 logger("Mail: Connect to " . $mailconf['user']);
356                                 if ($mbox) {
357                                         $fields = ['last_check' => DateTimeFormat::utcNow()];
358                                         dba::update('mailacct', $fields, ['id' => $mailconf['id']]);
359                                         logger("Mail: Connected to " . $mailconf['user']);
360                                 } else {
361                                         logger("Mail: Connection error ".$mailconf['user']." ".print_r(imap_errors(), true));
362                                 }
363                         }
364
365                         if ($mbox) {
366                                 $msgs = Email::poll($mbox, $contact['addr']);
367
368                                 if (count($msgs)) {
369                                         logger("Mail: Parsing ".count($msgs)." mails from ".$contact['addr']." for ".$mailconf['user'], LOGGER_DEBUG);
370
371                                         $metas = Email::messageMeta($mbox, implode(',', $msgs));
372                                         if (count($metas) != count($msgs)) {
373                                                 logger("for " . $mailconf['user'] . " there are ". count($msgs) . " messages but received " . count($metas) . " metas", LOGGER_DEBUG);
374                                         } else {
375                                                 $msgs = array_combine($msgs, $metas);
376
377                                                 foreach ($msgs as $msg_uid => $meta) {
378                                                         logger("Mail: Parsing mail ".$msg_uid, LOGGER_DATA);
379
380                                                         $datarray = [];
381                                                         $datarray['verb'] = ACTIVITY_POST;
382                                                         $datarray['object-type'] = ACTIVITY_OBJ_NOTE;
383                                                         // $meta = Email::messageMeta($mbox, $msg_uid);
384
385                                                         $datarray['uri'] = Email::msgid2iri(trim($meta->message_id, '<>'));
386
387                                                         // Have we seen it before?
388                                                         $fields = ['deleted', 'id'];
389                                                         $condition = ['uid' => $importer_uid, 'uri' => $datarray['uri']];
390                                                         $item = dba::selectFirst('item', $fields, $condition);
391                                                         if (DBM::is_result($item)) {
392                                                                 logger("Mail: Seen before ".$msg_uid." for ".$mailconf['user']." UID: ".$importer_uid." URI: ".$datarray['uri'],LOGGER_DEBUG);
393
394                                                                 // Only delete when mails aren't automatically moved or deleted
395                                                                 if (($mailconf['action'] != 1) && ($mailconf['action'] != 3))
396                                                                         if ($meta->deleted && ! $item['deleted']) {
397                                                                                 $fields = ['deleted' => true, 'changed' => DateTimeFormat::utcNow()];
398                                                                                 Item::update($fields, ['id' => $item['id']]);
399                                                                         }
400
401                                                                 switch ($mailconf['action']) {
402                                                                         case 0:
403                                                                                 logger("Mail: Seen before ".$msg_uid." for ".$mailconf['user'].". Doing nothing.", LOGGER_DEBUG);
404                                                                                 break;
405                                                                         case 1:
406                                                                                 logger("Mail: Deleting ".$msg_uid." for ".$mailconf['user']);
407                                                                                 imap_delete($mbox, $msg_uid, FT_UID);
408                                                                                 break;
409                                                                         case 2:
410                                                                                 logger("Mail: Mark as seen ".$msg_uid." for ".$mailconf['user']);
411                                                                                 imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
412                                                                                 break;
413                                                                         case 3:
414                                                                                 logger("Mail: Moving ".$msg_uid." to ".$mailconf['movetofolder']." for ".$mailconf['user']);
415                                                                                 imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
416                                                                                 if ($mailconf['movetofolder'] != "") {
417                                                                                         imap_mail_move($mbox, $msg_uid, $mailconf['movetofolder'], FT_UID);
418                                                                                 }
419                                                                                 break;
420                                                                 }
421                                                                 continue;
422                                                         }
423
424
425                                                         // look for a 'references' or an 'in-reply-to' header and try to match with a parent item we have locally.
426                                                         $raw_refs = ((property_exists($meta, 'references')) ? str_replace("\t", '', $meta->references) : '');
427                                                         if (!trim($raw_refs)) {
428                                                                 $raw_refs = ((property_exists($meta, 'in_reply_to')) ? str_replace("\t", '', $meta->in_reply_to) : '');
429                                                         }
430                                                         $raw_refs = trim($raw_refs);  // Don't allow a blank reference in $refs_arr
431
432                                                         if ($raw_refs) {
433                                                                 $refs_arr = explode(' ', $raw_refs);
434                                                                 if (count($refs_arr)) {
435                                                                         for ($x = 0; $x < count($refs_arr); $x ++) {
436                                                                                 $refs_arr[$x] = "'" . Email::msgid2iri(str_replace(['<', '>', ' '],['', '', ''],dbesc($refs_arr[$x]))) . "'";
437                                                                         }
438                                                                 }
439                                                                 $qstr = implode(',', $refs_arr);
440                                                                 $r = q("SELECT `parent-uri` FROM `item` USE INDEX (`uid_uri`) WHERE `uri` IN ($qstr) AND `uid` = %d LIMIT 1",
441                                                                         intval($importer_uid)
442                                                                 );
443                                                                 if (DBM::is_result($r)) {
444                                                                         $datarray['parent-uri'] = $r[0]['parent-uri'];  // Set the parent as the top-level item
445                                                                 }
446                                                         }
447
448                                                         // Decoding the header
449                                                         $subject = imap_mime_header_decode($meta->subject);
450                                                         $datarray['title'] = "";
451                                                         foreach ($subject as $subpart) {
452                                                                 if ($subpart->charset != "default") {
453                                                                         $datarray['title'] .= iconv($subpart->charset, 'UTF-8//IGNORE', $subpart->text);
454                                                                 } else {
455                                                                         $datarray['title'] .= $subpart->text;
456                                                                 }
457                                                         }
458                                                         $datarray['title'] = notags(trim($datarray['title']));
459
460                                                         //$datarray['title'] = notags(trim($meta->subject));
461                                                         $datarray['created'] = DateTimeFormat::utc($meta->date);
462
463                                                         // Is it a reply?
464                                                         $reply = ((substr(strtolower($datarray['title']), 0, 3) == "re:") ||
465                                                                 (substr(strtolower($datarray['title']), 0, 3) == "re-") ||
466                                                                 ($raw_refs != ""));
467
468                                                         // Remove Reply-signs in the subject
469                                                         $datarray['title'] = self::RemoveReply($datarray['title']);
470
471                                                         // If it seems to be a reply but a header couldn't be found take the last message with matching subject
472                                                         if (empty($datarray['parent-uri']) && $reply) {
473                                                                 $r = q("SELECT `parent-uri` FROM `item` WHERE `title` = \"%s\" AND `uid` = %d AND `network` = '%s' ORDER BY `created` DESC LIMIT 1",
474                                                                         dbesc(protect_sprintf($datarray['title'])),
475                                                                         intval($importer_uid),
476                                                                         dbesc(NETWORK_MAIL));
477                                                                 if (DBM::is_result($r)) {
478                                                                         $datarray['parent-uri'] = $r[0]['parent-uri'];
479                                                                 }
480                                                         }
481
482                                                         if (empty($datarray['parent-uri'])) {
483                                                                 $datarray['parent-uri'] = $datarray['uri'];
484                                                         }
485
486                                                         $r = Email::getMessage($mbox, $msg_uid, $reply);
487                                                         if (!$r) {
488                                                                 logger("Mail: can't fetch msg ".$msg_uid." for ".$mailconf['user']);
489                                                                 continue;
490                                                         }
491                                                         $datarray['body'] = escape_tags($r['body']);
492                                                         $datarray['body'] = BBCode::limitBodySize($datarray['body']);
493
494                                                         logger("Mail: Importing ".$msg_uid." for ".$mailconf['user']);
495
496                                                         /// @TODO Adding a gravatar for the original author would be cool
497
498                                                         $from = imap_mime_header_decode($meta->from);
499                                                         $fromdecoded = "";
500                                                         foreach ($from as $frompart) {
501                                                                 if ($frompart->charset != "default") {
502                                                                         $fromdecoded .= iconv($frompart->charset, 'UTF-8//IGNORE', $frompart->text);
503                                                                 } else {
504                                                                         $fromdecoded .= $frompart->text;
505                                                                 }
506                                                         }
507
508                                                         $fromarr = imap_rfc822_parse_adrlist($fromdecoded, $a->get_hostname());
509
510                                                         $frommail = $fromarr[0]->mailbox."@".$fromarr[0]->host;
511
512                                                         if (isset($fromarr[0]->personal)) {
513                                                                 $fromname = $fromarr[0]->personal;
514                                                         } else {
515                                                                 $fromname = $frommail;
516                                                         }
517
518                                                         $datarray['author-name'] = $fromname;
519                                                         $datarray['author-link'] = "mailto:".$frommail;
520                                                         $datarray['author-avatar'] = $contact['photo'];
521
522                                                         $datarray['owner-name'] = $contact['name'];
523                                                         $datarray['owner-link'] = "mailto:".$contact['addr'];
524                                                         $datarray['owner-avatar'] = $contact['photo'];
525
526                                                         $datarray['uid'] = $importer_uid;
527                                                         $datarray['contact-id'] = $contact['id'];
528                                                         if ($datarray['parent-uri'] === $datarray['uri']) {
529                                                                 $datarray['private'] = 1;
530                                                         }
531                                                         if (($contact['network'] === NETWORK_MAIL) && (!PConfig::get($importer_uid, 'system', 'allow_public_email_replies'))) {
532                                                                 $datarray['private'] = 1;
533                                                                 $datarray['allow_cid'] = '<' . $contact['id'] . '>';
534                                                         }
535
536                                                         $stored_item = Item::insert($datarray);
537
538                                                         switch ($mailconf['action']) {
539                                                                 case 0:
540                                                                         logger("Mail: Seen before ".$msg_uid." for ".$mailconf['user'].". Doing nothing.", LOGGER_DEBUG);
541                                                                         break;
542                                                                 case 1:
543                                                                         logger("Mail: Deleting ".$msg_uid." for ".$mailconf['user']);
544                                                                         imap_delete($mbox, $msg_uid, FT_UID);
545                                                                         break;
546                                                                 case 2:
547                                                                         logger("Mail: Mark as seen ".$msg_uid." for ".$mailconf['user']);
548                                                                         imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
549                                                                         break;
550                                                                 case 3:
551                                                                         logger("Mail: Moving ".$msg_uid." to ".$mailconf['movetofolder']." for ".$mailconf['user']);
552                                                                         imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
553                                                                         if ($mailconf['movetofolder'] != "") {
554                                                                                 imap_mail_move($mbox, $msg_uid, $mailconf['movetofolder'], FT_UID);
555                                                                         }
556                                                                         break;
557                                                         }
558                                                 }
559                                         }
560                                 } else {
561                                         logger("Mail: no mails for ".$mailconf['user']);
562                                 }
563
564                                 logger("Mail: closing connection for ".$mailconf['user']);
565                                 imap_close($mbox);
566                         }
567                 }
568
569                 if ($xml) {
570                         logger('received xml : ' . $xml, LOGGER_DATA);
571                         if (!strstr($xml, '<')) {
572                                 logger('post_handshake: response from ' . $url . ' did not contain XML.');
573
574                                 $fields = ['last-update' => DateTimeFormat::utcNow(), 'failure_update' => DateTimeFormat::utcNow()];
575                                 self::updateContact($contact, $fields);
576                                 Contact::markForArchival($contact);
577                                 return;
578                         }
579
580
581                         logger("Consume feed of contact ".$contact['id']);
582
583                         consume_feed($xml, $importer, $contact, $hub, 1, 1);
584
585                         // do it twice. Ensures that children of parents which may be later in the stream aren't tossed
586
587                         consume_feed($xml, $importer, $contact, $hub, 1, 2);
588
589                         $hubmode = 'subscribe';
590                         if ($contact['network'] === NETWORK_DFRN || $contact['blocked'] || $contact['readonly']) {
591                                 $hubmode = 'unsubscribe';
592                         }
593
594                         if (($contact['network'] === NETWORK_OSTATUS ||  $contact['network'] == NETWORK_FEED) && (! $contact['hub-verify'])) {
595                                 $hub_update = true;
596                         }
597
598                         if ($force) {
599                                 $hub_update = true;
600                         }
601
602                         logger("Contact ".$contact['id']." returned hub: ".$hub." Network: ".$contact['network']." Relation: ".$contact['rel']." Update: ".$hub_update);
603
604                         if (strlen($hub) && $hub_update && (($contact['rel'] != CONTACT_IS_FOLLOWER) || $contact['network'] == NETWORK_FEED)) {
605                                 logger('hub ' . $hubmode . ' : ' . $hub . ' contact name : ' . $contact['name'] . ' local user : ' . $importer['name']);
606                                 $hubs = explode(',', $hub);
607                                 if (count($hubs)) {
608                                         foreach ($hubs as $h) {
609                                                 $h = trim($h);
610                                                 if (!strlen($h)) {
611                                                         continue;
612                                                 }
613                                                 subscribe_to_hub($h, $importer, $contact, $hubmode);
614                                         }
615                                 }
616                         }
617
618                         $updated = DateTimeFormat::utcNow();
619
620                         self::updateContact($contact, ['last-update' => $updated, 'success_update' => $updated]);
621                         dba::update('gcontact', ['last_contact' => $updated], ['nurl' => $contact['nurl']]);
622                         Contact::unmarkForArchival($contact);
623                 } elseif (in_array($contact["network"], [NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS, NETWORK_FEED])) {
624                         $updated = DateTimeFormat::utcNow();
625
626                         self::updateContact($contact, ['last-update' => $updated, 'failure_update' => $updated]);
627                         dba::update('gcontact', ['last_failure' => $updated], ['nurl' => $contact['nurl']]);
628                         Contact::markForArchival($contact);
629                 } else {
630                         $updated = DateTimeFormat::utcNow();
631                         dba::update('contact', ['last-update' => $updated], ['id' => $contact['id']]);
632                 }
633
634                 return;
635         }
636
637         private static function RemoveReply($subject) {
638                 while (in_array(strtolower(substr($subject, 0, 3)), ["re:", "aw:"])) {
639                         $subject = trim(substr($subject, 4));
640                 }
641
642                 return $subject;
643         }
644
645         /**
646          * @brief Updates a personal contact entry and the public contact entry
647          *
648          * @param array $contact The personal contact entry
649          * @param array $fields The fields that are updated
650          */
651         private static function updateContact($contact, $fields) {
652                 dba::update('contact', $fields, ['id' => $contact['id']]);
653                 dba::update('contact', $fields, ['uid' => 0, 'nurl' => $contact['nurl']]);
654         }
655 }