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