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