]> git.mxchange.org Git - friendica.git/blob - src/Worker/OnePoll.php
NETWORK_MAIL2 was never finished, so remove it as well
[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\Email;
12 use Friendica\Protocol\PortableContact;
13 use dba;
14
15 require_once 'include/follow.php';
16
17 Class OnePoll
18 {
19         public static function execute($contact_id = 0, $command = '') {
20                 global $a;
21
22                 require_once 'include/datetime.php';
23                 require_once 'include/items.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) {
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 = Email::constructMailboxName($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::messageMeta($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::messageMeta($mbox, $msg_uid);
365
366                                                         $datarray['uri'] = Email::msgid2iri(trim($meta->message_id, '<>'));
367
368                                                         // Have we seen it before?
369                                                         $fields = array('deleted', 'id');
370                                                         $condition = array('uid' => $importer_uid, 'uri' => $datarray['uri']);
371                                                         $r = dba::select('item', $fields, $condition, array('limit' => 1));
372
373                                                         if (DBM::is_result($r)) {
374                                                                 logger("Mail: Seen before ".$msg_uid." for ".$mailconf['user']." UID: ".$importer_uid." URI: ".$datarray['uri'],LOGGER_DEBUG);
375
376                                                                 // Only delete when mails aren't automatically moved or deleted
377                                                                 if (($mailconf['action'] != 1) && ($mailconf['action'] != 3))
378                                                                         if ($meta->deleted && ! $r['deleted']) {
379                                                                                 $fields = array('deleted' => true, 'changed' => datetime_convert());
380                                                                                 dba::update('item', $fields, array('id' => $r['id']));
381                                                                         }
382
383                                                                 switch ($mailconf['action']) {
384                                                                         case 0:
385                                                                                 logger("Mail: Seen before ".$msg_uid." for ".$mailconf['user'].". Doing nothing.", LOGGER_DEBUG);
386                                                                                 break;
387                                                                         case 1:
388                                                                                 logger("Mail: Deleting ".$msg_uid." for ".$mailconf['user']);
389                                                                                 imap_delete($mbox, $msg_uid, FT_UID);
390                                                                                 break;
391                                                                         case 2:
392                                                                                 logger("Mail: Mark as seen ".$msg_uid." for ".$mailconf['user']);
393                                                                                 imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
394                                                                                 break;
395                                                                         case 3:
396                                                                                 logger("Mail: Moving ".$msg_uid." to ".$mailconf['movetofolder']." for ".$mailconf['user']);
397                                                                                 imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
398                                                                                 if ($mailconf['movetofolder'] != "") {
399                                                                                         imap_mail_move($mbox, $msg_uid, $mailconf['movetofolder'], FT_UID);
400                                                                                 }
401                                                                                 break;
402                                                                 }
403                                                                 continue;
404                                                         }
405
406
407                                                         // look for a 'references' or an 'in-reply-to' header and try to match with a parent item we have locally.
408                                                         $raw_refs = ((property_exists($meta, 'references')) ? str_replace("\t", '', $meta->references) : '');
409                                                         if (!trim($raw_refs)) {
410                                                                 $raw_refs = ((property_exists($meta, 'in_reply_to')) ? str_replace("\t", '', $meta->in_reply_to) : '');
411                                                         }
412                                                         $raw_refs = trim($raw_refs);  // Don't allow a blank reference in $refs_arr
413
414                                                         if ($raw_refs) {
415                                                                 $refs_arr = explode(' ', $raw_refs);
416                                                                 if (count($refs_arr)) {
417                                                                         for ($x = 0; $x < count($refs_arr); $x ++) {
418                                                                                 $refs_arr[$x] = "'" . Email::msgid2iri(str_replace(array('<', '>', ' '),array('', '', ''),dbesc($refs_arr[$x]))) . "'";
419                                                                         }
420                                                                 }
421                                                                 $qstr = implode(',', $refs_arr);
422                                                                 $r = q("SELECT `parent-uri` FROM `item` USE INDEX (`uid_uri`) WHERE `uri` IN ($qstr) AND `uid` = %d LIMIT 1",
423                                                                         intval($importer_uid)
424                                                                 );
425                                                                 if (DBM::is_result($r)) {
426                                                                         $datarray['parent-uri'] = $r[0]['parent-uri'];  // Set the parent as the top-level item
427                                                                 }
428                                                         }
429
430                                                         // Decoding the header
431                                                         $subject = imap_mime_header_decode($meta->subject);
432                                                         $datarray['title'] = "";
433                                                         foreach ($subject as $subpart) {
434                                                                 if ($subpart->charset != "default") {
435                                                                         $datarray['title'] .= iconv($subpart->charset, 'UTF-8//IGNORE', $subpart->text);
436                                                                 } else {
437                                                                         $datarray['title'] .= $subpart->text;
438                                                                 }
439                                                         }
440                                                         $datarray['title'] = notags(trim($datarray['title']));
441
442                                                         //$datarray['title'] = notags(trim($meta->subject));
443                                                         $datarray['created'] = datetime_convert('UTC', 'UTC', $meta->date);
444
445                                                         // Is it a reply?
446                                                         $reply = ((substr(strtolower($datarray['title']), 0, 3) == "re:") ||
447                                                                 (substr(strtolower($datarray['title']), 0, 3) == "re-") ||
448                                                                 ($raw_refs != ""));
449
450                                                         // Remove Reply-signs in the subject
451                                                         $datarray['title'] = self::RemoveReply($datarray['title']);
452
453                                                         // If it seems to be a reply but a header couldn't be found take the last message with matching subject
454                                                         if (empty($datarray['parent-uri']) && $reply) {
455                                                                 $r = q("SELECT `parent-uri` FROM `item` WHERE `title` = \"%s\" AND `uid` = %d AND `network` = '%s' ORDER BY `created` DESC LIMIT 1",
456                                                                         dbesc(protect_sprintf($datarray['title'])),
457                                                                         intval($importer_uid),
458                                                                         dbesc(NETWORK_MAIL));
459                                                                 if (DBM::is_result($r)) {
460                                                                         $datarray['parent-uri'] = $r[0]['parent-uri'];
461                                                                 }
462                                                         }
463
464                                                         if (empty($datarray['parent-uri'])) {
465                                                                 $datarray['parent-uri'] = $datarray['uri'];
466                                                         }
467
468                                                         $r = Email::getMessage($mbox, $msg_uid, $reply);
469                                                         if (!$r) {
470                                                                 logger("Mail: can't fetch msg ".$msg_uid." for ".$mailconf['user']);
471                                                                 continue;
472                                                         }
473                                                         $datarray['body'] = escape_tags($r['body']);
474                                                         $datarray['body'] = limit_body_size($datarray['body']);
475
476                                                         logger("Mail: Importing ".$msg_uid." for ".$mailconf['user']);
477
478                                                         /// @TODO Adding a gravatar for the original author would be cool
479
480                                                         $from = imap_mime_header_decode($meta->from);
481                                                         $fromdecoded = "";
482                                                         foreach ($from as $frompart) {
483                                                                 if ($frompart->charset != "default") {
484                                                                         $fromdecoded .= iconv($frompart->charset, 'UTF-8//IGNORE', $frompart->text);
485                                                                 } else {
486                                                                         $fromdecoded .= $frompart->text;
487                                                                 }
488                                                         }
489
490                                                         $fromarr = imap_rfc822_parse_adrlist($fromdecoded, $a->get_hostname());
491
492                                                         $frommail = $fromarr[0]->mailbox."@".$fromarr[0]->host;
493
494                                                         if (isset($fromarr[0]->personal)) {
495                                                                 $fromname = $fromarr[0]->personal;
496                                                         } else {
497                                                                 $fromname = $frommail;
498                                                         }
499
500                                                         $datarray['author-name'] = $fromname;
501                                                         $datarray['author-link'] = "mailto:".$frommail;
502                                                         $datarray['author-avatar'] = $contact['photo'];
503
504                                                         $datarray['owner-name'] = $contact['name'];
505                                                         $datarray['owner-link'] = "mailto:".$contact['addr'];
506                                                         $datarray['owner-avatar'] = $contact['photo'];
507
508                                                         $datarray['uid'] = $importer_uid;
509                                                         $datarray['contact-id'] = $contact['id'];
510                                                         if ($datarray['parent-uri'] === $datarray['uri']) {
511                                                                 $datarray['private'] = 1;
512                                                         }
513                                                         if (($contact['network'] === NETWORK_MAIL) && (!PConfig::get($importer_uid, 'system', 'allow_public_email_replies'))) {
514                                                                 $datarray['private'] = 1;
515                                                                 $datarray['allow_cid'] = '<' . $contact['id'] . '>';
516                                                         }
517
518                                                         $stored_item = item_store($datarray);
519
520                                                         $condition = array('parent-uri' => $datarray['parent-uri'], 'uid' => $importer_uid);
521                                                         dba::update('item', array('last-child' => false), $condition);
522
523                                                         dba::update('item', array('last-child' => true), array('id' => $stored_item));
524
525                                                         switch ($mailconf['action']) {
526                                                                 case 0:
527                                                                         logger("Mail: Seen before ".$msg_uid." for ".$mailconf['user'].". Doing nothing.", LOGGER_DEBUG);
528                                                                         break;
529                                                                 case 1:
530                                                                         logger("Mail: Deleting ".$msg_uid." for ".$mailconf['user']);
531                                                                         imap_delete($mbox, $msg_uid, FT_UID);
532                                                                         break;
533                                                                 case 2:
534                                                                         logger("Mail: Mark as seen ".$msg_uid." for ".$mailconf['user']);
535                                                                         imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
536                                                                         break;
537                                                                 case 3:
538                                                                         logger("Mail: Moving ".$msg_uid." to ".$mailconf['movetofolder']." for ".$mailconf['user']);
539                                                                         imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
540                                                                         if ($mailconf['movetofolder'] != "") {
541                                                                                 imap_mail_move($mbox, $msg_uid, $mailconf['movetofolder'], FT_UID);
542                                                                         }
543                                                                         break;
544                                                         }
545                                                 }
546                                         }
547                                 } else {
548                                         logger("Mail: no mails for ".$mailconf['user']);
549                                 }
550
551                                 logger("Mail: closing connection for ".$mailconf['user']);
552                                 imap_close($mbox);
553                         }
554                 }
555
556                 if ($xml) {
557                         logger('received xml : ' . $xml, LOGGER_DATA);
558                         if (!strstr($xml, '<')) {
559                                 logger('post_handshake: response from ' . $url . ' did not contain XML.');
560
561                                 $fields = array('last-update' => datetime_convert(), 'failure_update' => datetime_convert());
562                                 dba::update('contact', $fields, array('id' => $contact['id']));
563
564                                 return;
565                         }
566
567
568                         logger("Consume feed of contact ".$contact['id']);
569
570                         consume_feed($xml, $importer, $contact, $hub, 1, 1);
571
572                         // do it twice. Ensures that children of parents which may be later in the stream aren't tossed
573
574                         consume_feed($xml, $importer, $contact, $hub, 1, 2);
575
576                         $hubmode = 'subscribe';
577                         if ($contact['network'] === NETWORK_DFRN || $contact['blocked'] || $contact['readonly']) {
578                                 $hubmode = 'unsubscribe';
579                         }
580
581                         if (($contact['network'] === NETWORK_OSTATUS ||  $contact['network'] == NETWORK_FEED) && (! $contact['hub-verify'])) {
582                                 $hub_update = true;
583                         }
584
585                         if ($force) {
586                                 $hub_update = true;
587                         }
588
589                         logger("Contact ".$contact['id']." returned hub: ".$hub." Network: ".$contact['network']." Relation: ".$contact['rel']." Update: ".$hub_update);
590
591                         if (strlen($hub) && $hub_update && (($contact['rel'] != CONTACT_IS_FOLLOWER) || $contact['network'] == NETWORK_FEED)) {
592                                 logger('hub ' . $hubmode . ' : ' . $hub . ' contact name : ' . $contact['name'] . ' local user : ' . $importer['name']);
593                                 $hubs = explode(',', $hub);
594                                 if (count($hubs)) {
595                                         foreach ($hubs as $h) {
596                                                 $h = trim($h);
597                                                 if (!strlen($h)) {
598                                                         continue;
599                                                 }
600                                                 subscribe_to_hub($h, $importer, $contact, $hubmode);
601                                         }
602                                 }
603                         }
604
605                         $updated = datetime_convert();
606
607                         dba::update('contact', array('last-update' => $updated, 'success_update' => $updated), array('id' => $contact['id']));
608                         dba::update('gcontact', array('last_contact' => $updated), array('nurl' => $contact['nurl']));
609                 } elseif (in_array($contact["network"], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS, NETWORK_FEED))) {
610                         $updated = datetime_convert();
611
612                         dba::update('contact', array('last-update' => $updated, 'failure_update' => $updated), array('id' => $contact['id']));
613                         dba::update('gcontact', array('last_failure' => $updated), array('nurl' => $contact['nurl']));
614                 } else {
615                         dba::update('contact', array('last-update' => $updated), array('id' => $contact['id']));
616                 }
617
618                 return;
619         }
620
621         private static function RemoveReply($subject) {
622                 while (in_array(strtolower(substr($subject, 0, 3)), array("re:", "aw:"))) {
623                         $subject = trim(substr($subject, 4));
624                 }
625
626                 return $subject;
627         }
628 }