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