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