]> git.mxchange.org Git - friendica.git/blob - src/Worker/OnePoll.php
Remove comment
[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' => DateTimeFormat::utc($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                 $url = '';
157
158                 logger("poll: ({$contact['network']}-{$contact['id']}) IMPORTER: {$importer['name']}, CONTACT: {$contact['name']}");
159
160                 if ($contact['network'] === NETWORK_DFRN) {
161                         $idtosend = $orig_id = (($contact['dfrn-id']) ? $contact['dfrn-id'] : $contact['issued-id']);
162                         if (intval($contact['duplex']) && $contact['dfrn-id']) {
163                                 $idtosend = '0:' . $orig_id;
164                         }
165                         if (intval($contact['duplex']) && $contact['issued-id']) {
166                                 $idtosend = '1:' . $orig_id;
167                         }
168
169                         // they have permission to write to us. We already filtered this in the contact query.
170                         $perm = 'rw';
171
172                         // But this may be our first communication, so set the writable flag if it isn't set already.
173
174                         if (!intval($contact['writable'])) {
175                                 $fields = ['writable' => true];
176                                 dba::update('contact', $fields, ['id' => $contact['id']]);
177                         }
178
179                         $url = $contact['poll'] . '?dfrn_id=' . $idtosend
180                                 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
181                                 . '&type=data&last_update=' . $last_update
182                                 . '&perm=' . $perm ;
183
184                         $ret = Network::curl($url);
185
186                         if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
187                                 // set the last-update so we don't keep polling
188                                 dba::update('contact', ['last-update' => DateTimeFormat::utcNow()], ['id' => $contact['id']]);
189                                 Contact::markForArchival($contact);
190                                 return;
191                         }
192
193                         $handshake_xml = $ret['body'];
194
195                         $html_code = $a->get_curl_code();
196
197                         logger('handshake with url ' . $url . ' returns xml: ' . $handshake_xml, LOGGER_DATA);
198
199
200                         if (!strlen($handshake_xml) || ($html_code >= 400) || !$html_code) {
201                                 logger("$url appears to be dead - marking for death ");
202
203                                 // dead connection - might be a transient event, or this might
204                                 // mean the software was uninstalled or the domain expired.
205                                 // Will keep trying for one month.
206
207                                 Contact::markForArchival($contact);
208
209                                 // set the last-update so we don't keep polling
210                                 $fields = ['last-update' => DateTimeFormat::utcNow(), 'failure_update' => DateTimeFormat::utcNow()];
211                                 self::updateContact($contact, $fields);
212                                 return;
213                         }
214
215                         if (!strstr($handshake_xml, '<')) {
216                                 logger('response from ' . $url . ' did not contain XML.');
217
218                                 Contact::markForArchival($contact);
219
220                                 $fields = ['last-update' => DateTimeFormat::utcNow(), 'failure_update' => DateTimeFormat::utcNow()];
221                                 self::updateContact($contact, $fields);
222                                 return;
223                         }
224
225
226                         $res = XML::parseString($handshake_xml);
227
228                         if (intval($res->status) == 1) {
229                                 logger("$url replied status 1 - marking for death ");
230
231                                 // we may not be friends anymore. Will keep trying for one month.
232                                 // set the last-update so we don't keep polling
233                                 $fields = ['last-update' => DateTimeFormat::utcNow(), 'failure_update' => DateTimeFormat::utcNow()];
234                                 self::updateContact($contact, $fields);
235
236                                 Contact::markForArchival($contact);
237                         } elseif ($contact['term-date'] > NULL_DATE) {
238                                 logger("$url back from the dead - removing mark for death");
239                                 Contact::unmarkForArchival($contact);
240                         }
241
242                         if ((intval($res->status) != 0) || !strlen($res->challenge) || !strlen($res->dfrn_id)) {
243                                 // set the last-update so we don't keep polling
244                                 dba::update('contact', ['last-update' => DateTimeFormat::utcNow()], ['id' => $contact['id']]);
245                                 return;
246                         }
247
248                         if (((float)$res->dfrn_version > 2.21) && ($contact['poco'] == '')) {
249                                 $fields = ['poco' => str_replace('/profile/', '/poco/', $contact['url'])];
250                                 dba::update('contact', $fields, ['id' => $contact['id']]);
251                         }
252
253                         $postvars = [];
254
255                         $sent_dfrn_id = hex2bin((string) $res->dfrn_id);
256                         $challenge    = hex2bin((string) $res->challenge);
257
258                         $final_dfrn_id = '';
259
260                         if ($contact['duplex'] && strlen($contact['prvkey'])) {
261                                 openssl_private_decrypt($sent_dfrn_id, $final_dfrn_id, $contact['prvkey']);
262                                 openssl_private_decrypt($challenge, $postvars['challenge'], $contact['prvkey']);
263                         } else {
264                                 openssl_public_decrypt($sent_dfrn_id, $final_dfrn_id, $contact['pubkey']);
265                                 openssl_public_decrypt($challenge, $postvars['challenge'], $contact['pubkey']);
266                         }
267
268                         $final_dfrn_id = substr($final_dfrn_id, 0, strpos($final_dfrn_id, '.'));
269
270                         if (strpos($final_dfrn_id, ':') == 1) {
271                                 $final_dfrn_id = substr($final_dfrn_id, 2);
272                         }
273
274                         if ($final_dfrn_id != $orig_id) {
275                                 // did not decode properly - cannot trust this site
276                                 logger('ID did not decode: ' . $contact['id'] . ' orig: ' . $orig_id . ' final: ' . $final_dfrn_id);
277
278                                 // set the last-update so we don't keep polling
279                                 dba::update('contact', ['last-update' => DateTimeFormat::utcNow()], ['id' => $contact['id']]);
280                                 Contact::markForArchival($contact);
281                                 return;
282                         }
283
284                         $postvars['dfrn_id'] = $idtosend;
285                         $postvars['dfrn_version'] = DFRN_PROTOCOL_VERSION;
286                         $postvars['perm'] = 'rw';
287
288                         $xml = Network::post($contact['poll'], $postvars);
289
290                 } elseif (($contact['network'] === NETWORK_OSTATUS)
291                         || ($contact['network'] === NETWORK_DIASPORA)
292                         || ($contact['network'] === NETWORK_FEED)) {
293
294                         // Upgrading DB fields from an older Friendica version
295                         // Will only do this once per notify-enabled OStatus contact
296                         // or if relationship changes
297
298                         $stat_writeable = ((($contact['notify']) && ($contact['rel'] == CONTACT_IS_FOLLOWER || $contact['rel'] == CONTACT_IS_FRIEND)) ? 1 : 0);
299
300                         // Contacts from OStatus are always writable
301                         if ($contact['network'] === NETWORK_OSTATUS) {
302                                 $stat_writeable = 1;
303                         }
304
305                         if ($stat_writeable != $contact['writable']) {
306                                 $fields = ['writable' => $stat_writeable];
307                                 dba::update('contact', $fields, ['id' => $contact['id']]);
308                         }
309
310                         // Are we allowed to import from this person?
311
312                         if ($contact['rel'] == CONTACT_IS_FOLLOWER || $contact['blocked']) {
313                                 // set the last-update so we don't keep polling
314                                 dba::update('contact', ['last-update' => DateTimeFormat::utcNow()], ['id' => $contact['id']]);
315                                 return;
316                         }
317
318                         $cookiejar = tempnam(get_temppath(), 'cookiejar-onepoll-');
319                         $ret = Network::curl($contact['poll'], false, $redirects, ['cookiejar' => $cookiejar]);
320                         unlink($cookiejar);
321
322                         if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
323                                 // set the last-update so we don't keep polling
324                                 dba::update('contact', ['last-update' => DateTimeFormat::utcNow()], ['id' => $contact['id']]);
325                                 Contact::markForArchival($contact);
326                                 return;
327                         }
328
329                         $xml = $ret['body'];
330
331                 } elseif ($contact['network'] === NETWORK_MAIL) {
332
333                         logger("Mail: Fetching for ".$contact['addr'], LOGGER_DEBUG);
334
335                         $mail_disabled = ((function_exists('imap_open') && (! Config::get('system', 'imap_disabled'))) ? 0 : 1);
336                         if ($mail_disabled) {
337                                 // set the last-update so we don't keep polling
338                                 dba::update('contact', ['last-update' => DateTimeFormat::utcNow()], ['id' => $contact['id']]);
339                                 Contact::markForArchival($contact);
340                                 return;
341                         }
342
343                         logger("Mail: Enabled", LOGGER_DEBUG);
344
345                         $mbox = null;
346                         $user = dba::selectFirst('user', ['prvkey'], ['uid' => $importer_uid]);
347
348                         $condition = ["`server` != '' AND `uid` = ?", $importer_uid];
349                         $mailconf = dba::selectFirst('mailacct', [], $condition);
350                         if (DBM::is_result($user) && DBM::is_result($mailconf)) {
351                                 $mailbox = Email::constructMailboxName($mailconf);
352                                 $password = '';
353                                 openssl_private_decrypt(hex2bin($mailconf['pass']), $password, $user['prvkey']);
354                                 $mbox = Email::connect($mailbox, $mailconf['user'], $password);
355                                 unset($password);
356                                 logger("Mail: Connect to " . $mailconf['user']);
357                                 if ($mbox) {
358                                         $fields = ['last_check' => DateTimeFormat::utcNow()];
359                                         dba::update('mailacct', $fields, ['id' => $mailconf['id']]);
360                                         logger("Mail: Connected to " . $mailconf['user']);
361                                 } else {
362                                         logger("Mail: Connection error ".$mailconf['user']." ".print_r(imap_errors(), true));
363                                 }
364                         }
365
366                         if ($mbox) {
367                                 $msgs = Email::poll($mbox, $contact['addr']);
368
369                                 if (count($msgs)) {
370                                         logger("Mail: Parsing ".count($msgs)." mails from ".$contact['addr']." for ".$mailconf['user'], LOGGER_DEBUG);
371
372                                         $metas = Email::messageMeta($mbox, implode(',', $msgs));
373                                         if (count($metas) != count($msgs)) {
374                                                 logger("for " . $mailconf['user'] . " there are ". count($msgs) . " messages but received " . count($metas) . " metas", LOGGER_DEBUG);
375                                         } else {
376                                                 $msgs = array_combine($msgs, $metas);
377
378                                                 foreach ($msgs as $msg_uid => $meta) {
379                                                         logger("Mail: Parsing mail ".$msg_uid, LOGGER_DATA);
380
381                                                         $datarray = [];
382                                                         $datarray['verb'] = ACTIVITY_POST;
383                                                         $datarray['object-type'] = ACTIVITY_OBJ_NOTE;
384                                                         $datarray['network'] = NETWORK_MAIL;
385                                                         // $meta = Email::messageMeta($mbox, $msg_uid);
386
387                                                         $datarray['uri'] = Email::msgid2iri(trim($meta->message_id, '<>'));
388
389                                                         // Have we seen it before?
390                                                         $fields = ['deleted', 'id'];
391                                                         $condition = ['uid' => $importer_uid, 'uri' => $datarray['uri']];
392                                                         $item = Item::selectFirst($fields, $condition);
393                                                         if (DBM::is_result($item)) {
394                                                                 logger("Mail: Seen before ".$msg_uid." for ".$mailconf['user']." UID: ".$importer_uid." URI: ".$datarray['uri'],LOGGER_DEBUG);
395
396                                                                 // Only delete when mails aren't automatically moved or deleted
397                                                                 if (($mailconf['action'] != 1) && ($mailconf['action'] != 3))
398                                                                         if ($meta->deleted && ! $item['deleted']) {
399                                                                                 $fields = ['deleted' => true, 'changed' => DateTimeFormat::utcNow()];
400                                                                                 Item::update($fields, ['id' => $item['id']]);
401                                                                         }
402
403                                                                 switch ($mailconf['action']) {
404                                                                         case 0:
405                                                                                 logger("Mail: Seen before ".$msg_uid." for ".$mailconf['user'].". Doing nothing.", LOGGER_DEBUG);
406                                                                                 break;
407                                                                         case 1:
408                                                                                 logger("Mail: Deleting ".$msg_uid." for ".$mailconf['user']);
409                                                                                 imap_delete($mbox, $msg_uid, FT_UID);
410                                                                                 break;
411                                                                         case 2:
412                                                                                 logger("Mail: Mark as seen ".$msg_uid." for ".$mailconf['user']);
413                                                                                 imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
414                                                                                 break;
415                                                                         case 3:
416                                                                                 logger("Mail: Moving ".$msg_uid." to ".$mailconf['movetofolder']." for ".$mailconf['user']);
417                                                                                 imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
418                                                                                 if ($mailconf['movetofolder'] != "") {
419                                                                                         imap_mail_move($mbox, $msg_uid, $mailconf['movetofolder'], FT_UID);
420                                                                                 }
421                                                                                 break;
422                                                                 }
423                                                                 continue;
424                                                         }
425
426
427                                                         // look for a 'references' or an 'in-reply-to' header and try to match with a parent item we have locally.
428                                                         $raw_refs = ((property_exists($meta, 'references')) ? str_replace("\t", '', $meta->references) : '');
429                                                         if (!trim($raw_refs)) {
430                                                                 $raw_refs = ((property_exists($meta, 'in_reply_to')) ? str_replace("\t", '', $meta->in_reply_to) : '');
431                                                         }
432                                                         $raw_refs = trim($raw_refs);  // Don't allow a blank reference in $refs_arr
433
434                                                         if ($raw_refs) {
435                                                                 $refs_arr = explode(' ', $raw_refs);
436                                                                 if (count($refs_arr)) {
437                                                                         for ($x = 0; $x < count($refs_arr); $x ++) {
438                                                                                 $refs_arr[$x] = Email::msgid2iri(str_replace(['<', '>', ' '],['', '', ''], $refs_arr[$x]));
439                                                                         }
440                                                                 }
441                                                                 $condition = ['uri' => $refs_arr, 'uid' => $importer_uid];
442                                                                 $parent = Item::selectFirst(['parent-uri'], $condition);
443                                                                 if (DBM::is_result($parent)) {
444                                                                         $datarray['parent-uri'] = $parent['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                                                                 $condition = ['title' => $datarray['title'], 'uid' => importer_uid, 'network' => NETWORK_MAIL];
474                                                                 $params = ['order' => ['created' => true]];
475                                                                 $parent = Item::selectFirst(['parent-uri'], $condition, $params);
476                                                                 if (DBM::is_result($parent)) {
477                                                                         $datarray['parent-uri'] = $parent['parent-uri'];
478                                                                 }
479                                                         }
480
481                                                         if (empty($datarray['parent-uri'])) {
482                                                                 $datarray['parent-uri'] = $datarray['uri'];
483                                                         }
484
485                                                         $r = Email::getMessage($mbox, $msg_uid, $reply);
486                                                         if (!$r) {
487                                                                 logger("Mail: can't fetch msg ".$msg_uid." for ".$mailconf['user']);
488                                                                 continue;
489                                                         }
490                                                         $datarray['body'] = escape_tags($r['body']);
491                                                         $datarray['body'] = BBCode::limitBodySize($datarray['body']);
492
493                                                         logger("Mail: Importing ".$msg_uid." for ".$mailconf['user']);
494
495                                                         /// @TODO Adding a gravatar for the original author would be cool
496
497                                                         $from = imap_mime_header_decode($meta->from);
498                                                         $fromdecoded = "";
499                                                         foreach ($from as $frompart) {
500                                                                 if ($frompart->charset != "default") {
501                                                                         $fromdecoded .= iconv($frompart->charset, 'UTF-8//IGNORE', $frompart->text);
502                                                                 } else {
503                                                                         $fromdecoded .= $frompart->text;
504                                                                 }
505                                                         }
506
507                                                         $fromarr = imap_rfc822_parse_adrlist($fromdecoded, $a->get_hostname());
508
509                                                         $frommail = $fromarr[0]->mailbox."@".$fromarr[0]->host;
510
511                                                         if (isset($fromarr[0]->personal)) {
512                                                                 $fromname = $fromarr[0]->personal;
513                                                         } else {
514                                                                 $fromname = $frommail;
515                                                         }
516
517                                                         $datarray['author-name'] = $fromname;
518                                                         $datarray['author-link'] = "mailto:".$frommail;
519                                                         $datarray['author-avatar'] = $contact['photo'];
520
521                                                         $datarray['owner-name'] = $contact['name'];
522                                                         $datarray['owner-link'] = "mailto:".$contact['addr'];
523                                                         $datarray['owner-avatar'] = $contact['photo'];
524
525                                                         $datarray['uid'] = $importer_uid;
526                                                         $datarray['contact-id'] = $contact['id'];
527                                                         if ($datarray['parent-uri'] === $datarray['uri']) {
528                                                                 $datarray['private'] = 1;
529                                                         }
530                                                         if (($contact['network'] === NETWORK_MAIL) && (!PConfig::get($importer_uid, 'system', 'allow_public_email_replies'))) {
531                                                                 $datarray['private'] = 1;
532                                                                 $datarray['allow_cid'] = '<' . $contact['id'] . '>';
533                                                         }
534
535                                                         $stored_item = Item::insert($datarray);
536
537                                                         switch ($mailconf['action']) {
538                                                                 case 0:
539                                                                         logger("Mail: Seen before ".$msg_uid." for ".$mailconf['user'].". Doing nothing.", LOGGER_DEBUG);
540                                                                         break;
541                                                                 case 1:
542                                                                         logger("Mail: Deleting ".$msg_uid." for ".$mailconf['user']);
543                                                                         imap_delete($mbox, $msg_uid, FT_UID);
544                                                                         break;
545                                                                 case 2:
546                                                                         logger("Mail: Mark as seen ".$msg_uid." for ".$mailconf['user']);
547                                                                         imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
548                                                                         break;
549                                                                 case 3:
550                                                                         logger("Mail: Moving ".$msg_uid." to ".$mailconf['movetofolder']." for ".$mailconf['user']);
551                                                                         imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
552                                                                         if ($mailconf['movetofolder'] != "") {
553                                                                                 imap_mail_move($mbox, $msg_uid, $mailconf['movetofolder'], FT_UID);
554                                                                         }
555                                                                         break;
556                                                         }
557                                                 }
558                                         }
559                                 } else {
560                                         logger("Mail: no mails for ".$mailconf['user']);
561                                 }
562
563                                 logger("Mail: closing connection for ".$mailconf['user']);
564                                 imap_close($mbox);
565                         }
566                 }
567
568                 if ($xml) {
569                         logger('received xml : ' . $xml, LOGGER_DATA);
570                         if (!strstr($xml, '<')) {
571                                 logger('post_handshake: response from ' . $url . ' did not contain XML.');
572
573                                 $fields = ['last-update' => DateTimeFormat::utcNow(), 'failure_update' => DateTimeFormat::utcNow()];
574                                 self::updateContact($contact, $fields);
575                                 Contact::markForArchival($contact);
576                                 return;
577                         }
578
579
580                         logger("Consume feed of contact ".$contact['id']);
581
582                         consume_feed($xml, $importer, $contact, $hub);
583
584                         // do it a second time for DFRN so that any children find their parents.
585                         if ($contact['network'] === NETWORK_DFRN) {
586                                 consume_feed($xml, $importer, $contact, $hub);
587                         }
588
589                         $hubmode = 'subscribe';
590                         if ($contact['network'] === NETWORK_DFRN || $contact['blocked']) {
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 }