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