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