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