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