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