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