]> git.mxchange.org Git - friendica.git/blob - include/onepoll.php
Issue 2122: Make sure to always return the correct number of entries
[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                 if (!poco_reachable($contact['url'])) {
173                         logger("Skipping probably dead contact ".$contact['url']);
174                         return;
175                 }
176
177                 if (!update_contact($contact["id"])) {
178                         mark_for_death($contact);
179                         return;
180                 } else
181                         unmark_for_death($contact);
182         }
183
184         if($contact['network'] === NETWORK_DFRN) {
185
186
187                 $idtosend = $orig_id = (($contact['dfrn-id']) ? $contact['dfrn-id'] : $contact['issued-id']);
188                 if(intval($contact['duplex']) && $contact['dfrn-id'])
189                         $idtosend = '0:' . $orig_id;
190                 if(intval($contact['duplex']) && $contact['issued-id'])
191                         $idtosend = '1:' . $orig_id;
192
193                 // they have permission to write to us. We already filtered this in the contact query.
194                 $perm = 'rw';
195
196                 // But this may be our first communication, so set the writable flag if it isn't set already.
197
198                 if(! intval($contact['writable']))
199                         q("update contact set writable = 1 where id = %d", intval($contact['id']));
200
201
202                 $url = $contact['poll'] . '?dfrn_id=' . $idtosend
203                         . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
204                         . '&type=data&last_update=' . $last_update
205                         . '&perm=' . $perm ;
206
207                 $handshake_xml = fetch_url($url);
208                 $html_code = $a->get_curl_code();
209
210                 logger('onepoll: handshake with url ' . $url . ' returns xml: ' . $handshake_xml, LOGGER_DATA);
211
212
213                 if((! strlen($handshake_xml)) || ($html_code >= 400) || (! $html_code)) {
214                         logger("poller: $url appears to be dead - marking for death ");
215
216                         // dead connection - might be a transient event, or this might
217                         // mean the software was uninstalled or the domain expired.
218                         // Will keep trying for one month.
219
220                         mark_for_death($contact);
221
222                         // set the last-update so we don't keep polling
223                         $r = q("UPDATE `contact` SET `last-update` = '%s', `failure_update` = '%s' WHERE `id` = %d",
224                                 dbesc(datetime_convert()),
225                                 dbesc(datetime_convert()),
226                                 intval($contact['id'])
227                         );
228
229                         return;
230                 }
231
232                 if(! strstr($handshake_xml,'<')) {
233                         logger('poller: response from ' . $url . ' did not contain XML.');
234
235                         mark_for_death($contact);
236
237                         $r = q("UPDATE `contact` SET `last-update` = '%s', `failure_update` = '%s' WHERE `id` = %d",
238                                 dbesc(datetime_convert()),
239                                 dbesc(datetime_convert()),
240                                 intval($contact['id'])
241                         );
242                         return;
243                 }
244
245
246                 $res = parse_xml_string($handshake_xml);
247
248                 if(intval($res->status) == 1) {
249                         logger("poller: $url replied status 1 - marking for death ");
250
251                         // we may not be friends anymore. Will keep trying for one month.
252                         // set the last-update so we don't keep polling
253
254
255                         $r = q("UPDATE `contact` SET `last-update` = '%s', `failure_update` = '%s' WHERE `id` = %d",
256                                 dbesc(datetime_convert()),
257                                 dbesc(datetime_convert()),
258                                 intval($contact['id'])
259                         );
260                         mark_for_death($contact);
261                 }
262                 else {
263                         if($contact['term-date'] != '0000-00-00 00:00:00') {
264                                 logger("poller: $url back from the dead - removing mark for death");
265                                 unmark_for_death($contact);
266                         }
267                 }
268
269                 if((intval($res->status) != 0) || (! strlen($res->challenge)) || (! strlen($res->dfrn_id)))
270                         return;
271
272                 if(((float) $res->dfrn_version > 2.21) && ($contact['poco'] == '')) {
273                         q("update contact set poco = '%s' where id = %d",
274                                 dbesc(str_replace('/profile/','/poco/', $contact['url'])),
275                                 intval($contact['id'])
276                         );
277                 }
278
279                 $postvars = array();
280
281                 $sent_dfrn_id = hex2bin((string) $res->dfrn_id);
282                 $challenge    = hex2bin((string) $res->challenge);
283
284                 $final_dfrn_id = '';
285
286                 if(($contact['duplex']) && strlen($contact['prvkey'])) {
287                         openssl_private_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['prvkey']);
288                         openssl_private_decrypt($challenge,$postvars['challenge'],$contact['prvkey']);
289                 }
290                 else {
291                         openssl_public_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['pubkey']);
292                         openssl_public_decrypt($challenge,$postvars['challenge'],$contact['pubkey']);
293                 }
294
295                 $final_dfrn_id = substr($final_dfrn_id, 0, strpos($final_dfrn_id, '.'));
296
297                 if(strpos($final_dfrn_id,':') == 1)
298                         $final_dfrn_id = substr($final_dfrn_id,2);
299
300                 if($final_dfrn_id != $orig_id) {
301                         logger('poller: ID did not decode: ' . $contact['id'] . ' orig: ' . $orig_id . ' final: ' . $final_dfrn_id);
302                         // did not decode properly - cannot trust this site
303                         return;
304                 }
305
306                 $postvars['dfrn_id'] = $idtosend;
307                 $postvars['dfrn_version'] = DFRN_PROTOCOL_VERSION;
308                 $postvars['perm'] = 'rw';
309
310                 $xml = post_url($contact['poll'],$postvars);
311
312         }
313         elseif(($contact['network'] === NETWORK_OSTATUS)
314                 || ($contact['network'] === NETWORK_DIASPORA)
315                 || ($contact['network'] === NETWORK_FEED) ) {
316
317                 // Upgrading DB fields from an older Friendica version
318                 // Will only do this once per notify-enabled OStatus contact
319                 // or if relationship changes
320
321                 $stat_writeable = ((($contact['notify']) && ($contact['rel'] == CONTACT_IS_FOLLOWER || $contact['rel'] == CONTACT_IS_FRIEND)) ? 1 : 0);
322
323                 // Contacts from OStatus are always writable
324                 if($contact['network'] === NETWORK_OSTATUS)
325                         $stat_writeable = 1;
326
327                 if($stat_writeable != $contact['writable']) {
328                         q("UPDATE `contact` SET `writable` = %d WHERE `id` = %d",
329                                 intval($stat_writeable),
330                                 intval($contact['id'])
331                         );
332                 }
333
334                 // Are we allowed to import from this person?
335
336                 if($contact['rel'] == CONTACT_IS_FOLLOWER || $contact['blocked'] || $contact['readonly'])
337                         return;
338
339                 $xml = fetch_url($contact['poll']);
340         }
341         elseif($contact['network'] === NETWORK_MAIL || $contact['network'] === NETWORK_MAIL2) {
342
343                 logger("Mail: Fetching", LOGGER_DEBUG);
344
345                 $mail_disabled = ((function_exists('imap_open') && (! get_config('system','imap_disabled'))) ? 0 : 1);
346                 if($mail_disabled)
347                         return;
348
349                 logger("Mail: Enabled", LOGGER_DEBUG);
350
351                 $mbox = null;
352                 $x = q("SELECT `prvkey` FROM `user` WHERE `uid` = %d LIMIT 1",
353                         intval($importer_uid)
354                 );
355                 $mailconf = q("SELECT * FROM `mailacct` WHERE `server` != '' AND `uid` = %d LIMIT 1",
356                         intval($importer_uid)
357                 );
358                 if(count($x) && count($mailconf)) {
359                     $mailbox = construct_mailbox_name($mailconf[0]);
360                         $password = '';
361                         openssl_private_decrypt(hex2bin($mailconf[0]['pass']),$password,$x[0]['prvkey']);
362                         $mbox = email_connect($mailbox,$mailconf[0]['user'],$password);
363                         unset($password);
364                         logger("Mail: Connect to " . $mailconf[0]['user']);
365                         if($mbox) {
366                                 q("UPDATE `mailacct` SET `last_check` = '%s' WHERE `id` = %d AND `uid` = %d",
367                                         dbesc(datetime_convert()),
368                                         intval($mailconf[0]['id']),
369                                         intval($importer_uid)
370                                 );
371                                 logger("Mail: Connected to " . $mailconf[0]['user']);
372                         } else
373                                 logger("Mail: Connection error ".$mailconf[0]['user']." ".print_r(imap_errors(), true));
374                 }
375                 if($mbox) {
376
377                         $msgs = email_poll($mbox,$contact['addr']);
378
379                         if(count($msgs)) {
380                                 logger("Mail: Parsing ".count($msgs)." mails for ".$mailconf[0]['user'], LOGGER_DEBUG);
381
382                                 $metas = email_msg_meta($mbox,implode(',',$msgs));
383                                 if(count($metas) != count($msgs)) {
384                                         logger("onepoll: for " . $mailconf[0]['user'] . " there are ". count($msgs) . " messages but received " . count($metas) . " metas", LOGGER_DEBUG);
385                                 }
386                                 else {
387                                         $msgs = array_combine($msgs, $metas);
388
389                                         foreach($msgs as $msg_uid => $meta) {
390                                                 logger("Mail: Parsing mail ".$msg_uid, LOGGER_DATA);
391
392                                                 $datarray = array();
393                                                 $datarray['verb'] = ACTIVITY_POST;
394                                                 $datarray['object-type'] = ACTIVITY_OBJ_NOTE;
395         //                                      $meta = email_msg_meta($mbox,$msg_uid);
396         //                                      $headers = email_msg_headers($mbox,$msg_uid);
397
398                                                 $datarray['uri'] = msgid2iri(trim($meta->message_id,'<>'));
399
400                                                 // Have we seen it before?
401                                                 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `uri` = '%s' LIMIT 1",
402                                                         intval($importer_uid),
403                                                         dbesc($datarray['uri'])
404                                                 );
405
406                                                 if(count($r)) {
407                                                         logger("Mail: Seen before ".$msg_uid." for ".$mailconf[0]['user']." UID: ".$importer_uid." URI: ".$datarray['uri'],LOGGER_DEBUG);
408
409                                                         // Only delete when mails aren't automatically moved or deleted
410                                                         if (($mailconf[0]['action'] != 1) AND ($mailconf[0]['action'] != 3))
411                                                                 if($meta->deleted && ! $r[0]['deleted']) {
412                                                                         q("UPDATE `item` SET `deleted` = 1, `changed` = '%s' WHERE `id` = %d",
413                                                                                 dbesc(datetime_convert()),
414                                                                                 intval($r[0]['id'])
415                                                                         );
416                                                                 }
417
418                                                         switch ($mailconf[0]['action']) {
419                                                                 case 0:
420                                                                         logger("Mail: Seen before ".$msg_uid." for ".$mailconf[0]['user'].". Doing nothing.", LOGGER_DEBUG);
421                                                                         break;
422                                                                 case 1:
423                                                                         logger("Mail: Deleting ".$msg_uid." for ".$mailconf[0]['user']);
424                                                                         imap_delete($mbox, $msg_uid, FT_UID);
425                                                                         break;
426                                                                 case 2:
427                                                                         logger("Mail: Mark as seen ".$msg_uid." for ".$mailconf[0]['user']);
428                                                                         imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
429                                                                         break;
430                                                                 case 3:
431                                                                         logger("Mail: Moving ".$msg_uid." to ".$mailconf[0]['movetofolder']." for ".$mailconf[0]['user']);
432                                                                         imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
433                                                                         if ($mailconf[0]['movetofolder'] != "")
434                                                                                 imap_mail_move($mbox, $msg_uid, $mailconf[0]['movetofolder'], FT_UID);
435                                                                         break;
436                                                         }
437                                                         continue;
438                                                 }
439
440
441                                                 // look for a 'references' or an 'in-reply-to' header and try to match with a parent item we have locally.
442
443         //                                      $raw_refs = ((x($headers,'references')) ? str_replace("\t",'',$headers['references']) : '');
444                                                 $raw_refs = ((property_exists($meta,'references')) ? str_replace("\t",'',$meta->references) : '');
445                                                 if(! trim($raw_refs))
446                                                         $raw_refs = ((property_exists($meta,'in_reply_to')) ? str_replace("\t",'',$meta->in_reply_to) : '');
447                                                 $raw_refs = trim($raw_refs);  // Don't allow a blank reference in $refs_arr
448
449                                                 if($raw_refs) {
450                                                         $refs_arr = explode(' ', $raw_refs);
451                                                         if(count($refs_arr)) {
452                                                                 for($x = 0; $x < count($refs_arr); $x ++)
453                                                                         $refs_arr[$x] = "'" . msgid2iri(str_replace(array('<','>',' '),array('','',''),dbesc($refs_arr[$x]))) . "'";
454                                                         }
455                                                         $qstr = implode(',',$refs_arr);
456                                                         $r = q("SELECT `uri` , `parent-uri` FROM `item` WHERE `uri` IN ( $qstr ) AND `uid` = %d LIMIT 1",
457                                                                 intval($importer_uid)
458                                                         );
459                                                         if(count($r))
460                                                                 $datarray['parent-uri'] = $r[0]['parent-uri'];  // Set the parent as the top-level item
461         //                                                      $datarray['parent-uri'] = $r[0]['uri'];
462                                                 }
463
464                                                 // Decoding the header
465                                                 $subject = imap_mime_header_decode($meta->subject);
466                                                 $datarray['title'] = "";
467                                                 foreach($subject as $subpart)
468                                                         if ($subpart->charset != "default")
469                                                                 $datarray['title'] .= iconv($subpart->charset, 'UTF-8//IGNORE', $subpart->text);
470                                                         else
471                                                                 $datarray['title'] .= $subpart->text;
472
473                                                 $datarray['title'] = notags(trim($datarray['title']));
474
475                                                 //$datarray['title'] = notags(trim($meta->subject));
476                                                 $datarray['created'] = datetime_convert('UTC','UTC',$meta->date);
477
478                                                 // Is it a reply?
479                                                 $reply = ((substr(strtolower($datarray['title']), 0, 3) == "re:") or
480                                                         (substr(strtolower($datarray['title']), 0, 3) == "re-") or
481                                                         ($raw_refs != ""));
482
483                                                 // Remove Reply-signs in the subject
484                                                 $datarray['title'] = RemoveReply($datarray['title']);
485
486                                                 // If it seems to be a reply but a header couldn't be found take the last message with matching subject
487                                                 if(!x($datarray,'parent-uri') and $reply) {
488                                                         $r = q("SELECT `uri` , `parent-uri` FROM `item` WHERE `title` = \"%s\" AND `uid` = %d ORDER BY `created` DESC LIMIT 1",
489                                                                 dbesc(protect_sprintf($datarray['title'])),
490                                                                 intval($importer_uid));
491                                                         if(count($r))
492                                                                 $datarray['parent-uri'] = $r[0]['parent-uri'];
493                                                 }
494
495                                                 if(! x($datarray,'parent-uri'))
496                                                         $datarray['parent-uri'] = $datarray['uri'];
497
498
499                                                 $r = email_get_msg($mbox,$msg_uid, $reply);
500                                                 if(! $r) {
501                                                         logger("Mail: can't fetch msg ".$msg_uid." for ".$mailconf[0]['user']);
502                                                         continue;
503                                                 }
504                                                 $datarray['body'] = escape_tags($r['body']);
505                                                 $datarray['body'] = limit_body_size($datarray['body']);
506
507                                                 logger("Mail: Importing ".$msg_uid." for ".$mailconf[0]['user']);
508
509                                                 // some mailing lists have the original author as 'from' - add this sender info to msg body.
510                                                 // todo: adding a gravatar for the original author would be cool
511
512                                                 if(! stristr($meta->from,$contact['addr'])) {
513                                                         $from = imap_mime_header_decode($meta->from);
514                                                         $fromdecoded = "";
515                                                         foreach($from as $frompart)
516                                                                 if ($frompart->charset != "default")
517                                                                         $fromdecoded .= iconv($frompart->charset, 'UTF-8//IGNORE', $frompart->text);
518                                                                 else
519                                                                         $fromdecoded .= $frompart->text;
520
521                                                         $fromarr = imap_rfc822_parse_adrlist($fromdecoded, $a->get_hostname());
522
523                                                         $frommail = $fromarr[0]->mailbox."@".$fromarr[0]->host;
524
525                                                         if (isset($fromarr[0]->personal))
526                                                                 $fromname = $fromarr[0]->personal;
527                                                         else
528                                                                 $fromname = $frommail;
529
530                                                         //$datarray['body'] = "[b]".t('From: ') . escape_tags($fromdecoded) . "[/b]\n\n" . $datarray['body'];
531
532                                                         $datarray['author-name'] = $fromname;
533                                                         $datarray['author-link'] = "mailto:".$frommail;
534                                                         $datarray['author-avatar'] = $contact['photo'];
535
536                                                         $datarray['owner-name'] = $contact['name'];
537                                                         $datarray['owner-link'] = "mailto:".$contact['addr'];
538                                                         $datarray['owner-avatar'] = $contact['photo'];
539
540                                                 } else {
541                                                         $datarray['author-name'] = $contact['name'];
542                                                         $datarray['author-link'] = 'mailbox';
543                                                         $datarray['author-avatar'] = $contact['photo'];
544                                                 }
545
546                                                 $datarray['uid'] = $importer_uid;
547                                                 $datarray['contact-id'] = $contact['id'];
548                                                 if($datarray['parent-uri'] === $datarray['uri'])
549                                                         $datarray['private'] = 1;
550                                                 if(($contact['network'] === NETWORK_MAIL) && (! get_pconfig($importer_uid,'system','allow_public_email_replies'))) {
551                                                         $datarray['private'] = 1;
552                                                         $datarray['allow_cid'] = '<' . $contact['id'] . '>';
553                                                 }
554
555                                                 $stored_item = item_store($datarray);
556                                                 q("UPDATE `item` SET `last-child` = 0 WHERE `parent-uri` = '%s' AND `uid` = %d",
557                                                         dbesc($datarray['parent-uri']),
558                                                         intval($importer_uid)
559                                                 );
560                                                 q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d",
561                                                         intval($stored_item)
562                                                 );
563                                                 switch ($mailconf[0]['action']) {
564                                                         case 0:
565                                                                 logger("Mail: Seen before ".$msg_uid." for ".$mailconf[0]['user'].". Doing nothing.", LOGGER_DEBUG);
566                                                                 break;
567                                                         case 1:
568                                                                 logger("Mail: Deleting ".$msg_uid." for ".$mailconf[0]['user']);
569                                                                 imap_delete($mbox, $msg_uid, FT_UID);
570                                                                 break;
571                                                         case 2:
572                                                                 logger("Mail: Mark as seen ".$msg_uid." for ".$mailconf[0]['user']);
573                                                                 imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
574                                                                 break;
575                                                         case 3:
576                                                                 logger("Mail: Moving ".$msg_uid." to ".$mailconf[0]['movetofolder']." for ".$mailconf[0]['user']);
577                                                                 imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
578                                                                 if ($mailconf[0]['movetofolder'] != "")
579                                                                         imap_mail_move($mbox, $msg_uid, $mailconf[0]['movetofolder'], FT_UID);
580                                                                 break;
581                                                 }
582                                         }
583                                 }
584                         } else
585                                 logger("Mail: no mails for ".$mailconf[0]['user']);
586
587                         logger("Mail: closing connection for ".$mailconf[0]['user']);
588                         imap_close($mbox);
589                 }
590         }
591         elseif($contact['network'] === NETWORK_FACEBOOK) {
592                 // This is picked up by the Facebook plugin on a cron hook.
593                 // Ignored here.
594         } elseif($contact['network'] === NETWORK_PUMPIO) {
595                 // This is picked up by the pump.io plugin on a cron hook.
596                 // Ignored here.
597         }
598
599         if($xml) {
600                 logger('poller: received xml : ' . $xml, LOGGER_DATA);
601                 if(! strstr($xml,'<')) {
602                         logger('poller: post_handshake: response from ' . $url . ' did not contain XML.');
603                         $r = q("UPDATE `contact` SET `last-update` = '%s',  `failure_update` = '%s' WHERE `id` = %d",
604                                 dbesc(datetime_convert()),
605                                 dbesc(datetime_convert()),
606                                 intval($contact['id'])
607                         );
608                         return;
609                 }
610
611
612                 logger("Consume feed of contact ".$contact['id']);
613
614                 consume_feed($xml,$importer,$contact,$hub,1,1);
615
616                 // do it twice. Ensures that children of parents which may be later in the stream aren't tossed
617
618                 consume_feed($xml,$importer,$contact,$hub,1,2);
619
620                 $hubmode = 'subscribe';
621                 if($contact['network'] === NETWORK_DFRN || $contact['blocked'] || $contact['readonly'])
622                         $hubmode = 'unsubscribe';
623
624                 if(($contact['network'] === NETWORK_OSTATUS ||  $contact['network'] == NETWORK_FEED) && (! $contact['hub-verify']))
625                         $hub_update = true;
626
627                 if ($force)
628                         $hub_update = true;
629
630                 logger("Contact ".$contact['id']." returned hub: ".$hub." Network: ".$contact['network']." Relation: ".$contact['rel']." Update: ".$hub_update);
631
632                 if((strlen($hub)) && ($hub_update) && (($contact['rel'] != CONTACT_IS_FOLLOWER) || $contact['network'] == NETWORK_FEED) ) {
633                         logger('poller: hub ' . $hubmode . ' : ' . $hub . ' contact name : ' . $contact['name'] . ' local user : ' . $importer['name']);
634                         $hubs = explode(',', $hub);
635                         if(count($hubs)) {
636                                 foreach($hubs as $h) {
637                                         $h = trim($h);
638                                         if(! strlen($h))
639                                                 continue;
640                                         subscribe_to_hub($h,$importer,$contact,$hubmode);
641                                 }
642                         }
643                 }
644
645                 $updated = datetime_convert();
646
647                 $r = q("UPDATE `contact` SET `last-update` = '%s', `success_update` = '%s' WHERE `id` = %d",
648                         dbesc($updated),
649                         dbesc($updated),
650                         intval($contact['id'])
651                 );
652
653                 q("UPDATE `gcontact` SET `last_contact` = '%s' WHERE `nurl` = '%s'",
654                         dbesc($updated),
655                         dbesc($contact['nurl'])
656                 );
657
658         } elseif (in_array($contact["network"], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS, NETWORK_FEED))) {
659                 $updated = datetime_convert();
660
661                 $r = q("UPDATE `contact` SET `last-update` = '%s', `failure_update` = '%s' WHERE `id` = %d",
662                         dbesc($updated),
663                         dbesc($updated),
664                         intval($contact['id'])
665                 );
666
667                 q("UPDATE `gcontact` SET `last_failure` = '%s' WHERE `nurl` = '%s'",
668                         dbesc($updated),
669                         dbesc($contact['nurl'])
670                 );
671         } else {
672                 $r = q("UPDATE `contact` SET `last-update` = '%s' WHERE `id` = %d",
673                         dbesc($updated),
674                         intval($contact['id'])
675                 );
676         }
677
678         return;
679 }
680
681 if (array_search(__file__,get_included_files())===0){
682         onepoll_run($_SERVER["argv"],$_SERVER["argc"]);
683         killme();
684 }