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