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