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