]> git.mxchange.org Git - friendica.git/blob - include/onepoll.php
Define the lowest possible datetime string as "0001-01-01 00:00:00"
[friendica.git] / include / onepoll.php
1 <?php
2
3 use \Friendica\Core\Config;
4
5 require_once("boot.php");
6 require_once("include/follow.php");
7
8 function RemoveReply($subject) {
9         while (in_array(strtolower(substr($subject, 0, 3)), array("re:", "aw:")))
10                 $subject = trim(substr($subject, 4));
11
12         return($subject);
13 }
14
15 function onepoll_run(&$argv, &$argc){
16         global $a, $db;
17
18         if(is_null($a)) {
19                 $a = new App;
20         }
21
22         if(is_null($db)) {
23                 @include(".htconfig.php");
24                 require_once("include/dba.php");
25                 $db = new dba($db_host, $db_user, $db_pass, $db_data);
26                 unset($db_host, $db_user, $db_pass, $db_data);
27         };
28
29         require_once('include/session.php');
30         require_once('include/datetime.php');
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/queue_fn.php');
36
37         Config::load();
38
39         $a->set_baseurl(get_config('system','url'));
40
41         load_hooks();
42
43         logger('onepoll: start');
44
45         $manual_id  = 0;
46         $generation = 0;
47         $hub_update = false;
48         $force      = false;
49         $restart    = false;
50
51         if(($argc > 1) && (intval($argv[1])))
52                 $contact_id = intval($argv[1]);
53
54         if(($argc > 2) && ($argv[2] == "force"))
55                 $force = true;
56
57         if(! $contact_id) {
58                 logger('onepoll: no contact');
59                 return;
60         }
61
62         // Don't check this stuff if the function is called by the poller
63         if (App::callstack() != "poller_run")
64                 if (App::is_already_running('onepoll'.$contact_id, '', 540))
65                         return;
66
67         $d = datetime_convert();
68
69         // Only poll from those with suitable relationships,
70         // and which have a polling address and ignore Diaspora since
71         // we are unable to match those posts with a Diaspora GUID and prevent duplicates.
72
73         $contacts = q("SELECT `contact`.* FROM `contact`
74                 WHERE ( `rel` = %d OR `rel` = %d ) AND `poll` != ''
75                 AND NOT `network` IN ( '%s', '%s' )
76                 AND `contact`.`id` = %d
77                 AND `self` = 0 AND `contact`.`blocked` = 0 AND `contact`.`readonly` = 0
78                 AND `contact`.`archive` = 0 LIMIT 1",
79                 intval(CONTACT_IS_SHARING),
80                 intval(CONTACT_IS_FRIEND),
81                 dbesc(NETWORK_FACEBOOK),
82                 dbesc(NETWORK_PUMPIO),
83                 intval($contact_id)
84         );
85
86         if(! count($contacts))
87                 return;
88
89         $contact = $contacts[0];
90
91         // load current friends if possible.
92         if (($contact['poco'] != "") AND ($contact['success_update'] > $contact['failure_update'])) {
93                 $r = q("SELECT count(*) as total from glink
94                         where `cid` = %d and updated > UTC_TIMESTAMP() - INTERVAL 1 DAY",
95                         intval($contact['id'])
96                 );
97                 if (dbm::is_result($r))
98                         if (!$r[0]['total'])
99                                 poco_load($contact['id'],$importer_uid,0,$contact['poco']);
100         }
101
102         /// @TODO Check why we don't poll the Diaspora feed at the moment (some guid problem in the items?)
103         /// @TODO Check whether this is possible with Redmatrix
104         if ($contact["network"] == NETWORK_DIASPORA) {
105                 if (poco_do_update($contact["created"], $contact["last-item"], $contact["failure_update"], $contact["success_update"])) {
106                         $last_updated = poco_last_updated($contact["url"]);
107                         $updated = datetime_convert();
108                         if ($last_updated) {
109                                 q("UPDATE `contact` SET `last-item` = '%s', `last-update` = '%s', `success_update` = '%s' WHERE `id` = %d",
110                                         dbesc($last_updated),
111                                         dbesc($updated),
112                                         dbesc($updated),
113                                         intval($contact['id'])
114                                 );
115                         } else {
116                                 q("UPDATE `contact` SET `last-update` = '%s', `failure_update` = '%s' WHERE `id` = %d",
117                                         dbesc($updated),
118                                         dbesc($updated),
119                                         intval($contact['id'])
120                                 );
121                         }
122                 }
123                 return;
124         }
125
126         $xml = false;
127
128         $t = $contact['last-update'];
129
130         if($contact['subhub']) {
131                 $poll_interval = get_config('system','pushpoll_frequency');
132                 $contact['priority'] = (($poll_interval !== false) ? intval($poll_interval) : 3);
133                 $hub_update = false;
134
135                 if(datetime_convert('UTC','UTC', 'now') > datetime_convert('UTC','UTC', $t . " + 1 day"))
136                                 $hub_update = true;
137         }
138         else
139                 $hub_update = false;
140
141
142         $importer_uid = $contact['uid'];
143
144         $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",
145                 intval($importer_uid)
146         );
147         if (! dbm::is_result($r)) {
148                 return;
149         }
150
151         $importer = $r[0];
152
153         logger("onepoll: poll: ({$contact['id']}) IMPORTER: {$importer['name']}, CONTACT: {$contact['name']}");
154
155         $last_update = (($contact['last-update'] === '0000-00-00 00:00:00')
156                 ? datetime_convert('UTC','UTC','now - 7 days', ATOM_TIME)
157                 : datetime_convert('UTC','UTC',$contact['last-update'], ATOM_TIME)
158         );
159
160         // Update the contact entry
161         if(($contact['network'] === NETWORK_OSTATUS) || ($contact['network'] === NETWORK_DIASPORA) || ($contact['network'] === NETWORK_DFRN)) {
162                 if (!poco_reachable($contact['url'])) {
163                         logger("Skipping probably dead contact ".$contact['url']);
164                         return;
165                 }
166
167                 if (!update_contact($contact["id"])) {
168                         mark_for_death($contact);
169                         return;
170                 } else
171                         unmark_for_death($contact);
172         }
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                 $cookiejar = tempnam(get_temppath(), 'cookiejar-onepoll-');
330                 $xml = fetch_url($contact['poll'], false, $redirects, 0, Null, $cookiejar);
331                 unlink($cookiejar);
332         }
333         elseif($contact['network'] === NETWORK_MAIL || $contact['network'] === NETWORK_MAIL2) {
334
335                 logger("Mail: Fetching", LOGGER_DEBUG);
336
337                 $mail_disabled = ((function_exists('imap_open') && (! get_config('system','imap_disabled'))) ? 0 : 1);
338                 if($mail_disabled)
339                         return;
340
341                 logger("Mail: Enabled", LOGGER_DEBUG);
342
343                 $mbox = null;
344                 $x = q("SELECT `prvkey` FROM `user` WHERE `uid` = %d LIMIT 1",
345                         intval($importer_uid)
346                 );
347                 $mailconf = q("SELECT * FROM `mailacct` WHERE `server` != '' AND `uid` = %d LIMIT 1",
348                         intval($importer_uid)
349                 );
350                 if(count($x) && count($mailconf)) {
351                     $mailbox = construct_mailbox_name($mailconf[0]);
352                         $password = '';
353                         openssl_private_decrypt(hex2bin($mailconf[0]['pass']),$password,$x[0]['prvkey']);
354                         $mbox = email_connect($mailbox,$mailconf[0]['user'],$password);
355                         unset($password);
356                         logger("Mail: Connect to " . $mailconf[0]['user']);
357                         if($mbox) {
358                                 q("UPDATE `mailacct` SET `last_check` = '%s' WHERE `id` = %d AND `uid` = %d",
359                                         dbesc(datetime_convert()),
360                                         intval($mailconf[0]['id']),
361                                         intval($importer_uid)
362                                 );
363                                 logger("Mail: Connected to " . $mailconf[0]['user']);
364                         } else
365                                 logger("Mail: Connection error ".$mailconf[0]['user']." ".print_r(imap_errors(), true));
366                 }
367                 if($mbox) {
368
369                         $msgs = email_poll($mbox,$contact['addr']);
370
371                         if(count($msgs)) {
372                                 logger("Mail: Parsing ".count($msgs)." mails for ".$mailconf[0]['user'], LOGGER_DEBUG);
373
374                                 $metas = email_msg_meta($mbox,implode(',',$msgs));
375                                 if(count($metas) != count($msgs)) {
376                                         logger("onepoll: for " . $mailconf[0]['user'] . " there are ". count($msgs) . " messages but received " . count($metas) . " metas", LOGGER_DEBUG);
377                                 }
378                                 else {
379                                         $msgs = array_combine($msgs, $metas);
380
381                                         foreach($msgs as $msg_uid => $meta) {
382                                                 logger("Mail: Parsing mail ".$msg_uid, LOGGER_DATA);
383
384                                                 $datarray = array();
385                                                 $datarray['verb'] = ACTIVITY_POST;
386                                                 $datarray['object-type'] = ACTIVITY_OBJ_NOTE;
387         //                                      $meta = email_msg_meta($mbox,$msg_uid);
388         //                                      $headers = email_msg_headers($mbox,$msg_uid);
389
390                                                 $datarray['uri'] = msgid2iri(trim($meta->message_id,'<>'));
391
392                                                 // Have we seen it before?
393                                                 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `uri` = '%s' LIMIT 1",
394                                                         intval($importer_uid),
395                                                         dbesc($datarray['uri'])
396                                                 );
397
398                                                 if (dbm::is_result($r)) {
399                                                         logger("Mail: Seen before ".$msg_uid." for ".$mailconf[0]['user']." UID: ".$importer_uid." URI: ".$datarray['uri'],LOGGER_DEBUG);
400
401                                                         // Only delete when mails aren't automatically moved or deleted
402                                                         if (($mailconf[0]['action'] != 1) AND ($mailconf[0]['action'] != 3))
403                                                                 if($meta->deleted && ! $r[0]['deleted']) {
404                                                                         q("UPDATE `item` SET `deleted` = 1, `changed` = '%s' WHERE `id` = %d",
405                                                                                 dbesc(datetime_convert()),
406                                                                                 intval($r[0]['id'])
407                                                                         );
408                                                                 }
409
410                                                         switch ($mailconf[0]['action']) {
411                                                                 case 0:
412                                                                         logger("Mail: Seen before ".$msg_uid." for ".$mailconf[0]['user'].". Doing nothing.", LOGGER_DEBUG);
413                                                                         break;
414                                                                 case 1:
415                                                                         logger("Mail: Deleting ".$msg_uid." for ".$mailconf[0]['user']);
416                                                                         imap_delete($mbox, $msg_uid, FT_UID);
417                                                                         break;
418                                                                 case 2:
419                                                                         logger("Mail: Mark as seen ".$msg_uid." for ".$mailconf[0]['user']);
420                                                                         imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
421                                                                         break;
422                                                                 case 3:
423                                                                         logger("Mail: Moving ".$msg_uid." to ".$mailconf[0]['movetofolder']." for ".$mailconf[0]['user']);
424                                                                         imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
425                                                                         if ($mailconf[0]['movetofolder'] != "")
426                                                                                 imap_mail_move($mbox, $msg_uid, $mailconf[0]['movetofolder'], FT_UID);
427                                                                         break;
428                                                         }
429                                                         continue;
430                                                 }
431
432
433                                                 // look for a 'references' or an 'in-reply-to' header and try to match with a parent item we have locally.
434
435         //                                      $raw_refs = ((x($headers,'references')) ? str_replace("\t",'',$headers['references']) : '');
436                                                 $raw_refs = ((property_exists($meta,'references')) ? str_replace("\t",'',$meta->references) : '');
437                                                 if(! trim($raw_refs))
438                                                         $raw_refs = ((property_exists($meta,'in_reply_to')) ? str_replace("\t",'',$meta->in_reply_to) : '');
439                                                 $raw_refs = trim($raw_refs);  // Don't allow a blank reference in $refs_arr
440
441                                                 if($raw_refs) {
442                                                         $refs_arr = explode(' ', $raw_refs);
443                                                         if(count($refs_arr)) {
444                                                                 for($x = 0; $x < count($refs_arr); $x ++)
445                                                                         $refs_arr[$x] = "'" . msgid2iri(str_replace(array('<','>',' '),array('','',''),dbesc($refs_arr[$x]))) . "'";
446                                                         }
447                                                         $qstr = implode(',',$refs_arr);
448                                                         $r = q("SELECT `uri` , `parent-uri` FROM `item` USE INDEX (`uid_uri`) WHERE `uri` IN ($qstr) AND `uid` = %d LIMIT 1",
449                                                                 intval($importer_uid)
450                                                         );
451                                                         if (dbm::is_result($r))
452                                                                 $datarray['parent-uri'] = $r[0]['parent-uri'];  // Set the parent as the top-level item
453         //                                                      $datarray['parent-uri'] = $r[0]['uri'];
454                                                 }
455
456                                                 // Decoding the header
457                                                 $subject = imap_mime_header_decode($meta->subject);
458                                                 $datarray['title'] = "";
459                                                 foreach($subject as $subpart)
460                                                         if ($subpart->charset != "default")
461                                                                 $datarray['title'] .= iconv($subpart->charset, 'UTF-8//IGNORE', $subpart->text);
462                                                         else
463                                                                 $datarray['title'] .= $subpart->text;
464
465                                                 $datarray['title'] = notags(trim($datarray['title']));
466
467                                                 //$datarray['title'] = notags(trim($meta->subject));
468                                                 $datarray['created'] = datetime_convert('UTC','UTC',$meta->date);
469
470                                                 // Is it a reply?
471                                                 $reply = ((substr(strtolower($datarray['title']), 0, 3) == "re:") or
472                                                         (substr(strtolower($datarray['title']), 0, 3) == "re-") or
473                                                         ($raw_refs != ""));
474
475                                                 // Remove Reply-signs in the subject
476                                                 $datarray['title'] = RemoveReply($datarray['title']);
477
478                                                 // If it seems to be a reply but a header couldn't be found take the last message with matching subject
479                                                 if(!x($datarray,'parent-uri') and $reply) {
480                                                         $r = q("SELECT `uri` , `parent-uri` FROM `item` WHERE `title` = \"%s\" AND `uid` = %d AND `network` = '%s' ORDER BY `created` DESC LIMIT 1",
481                                                                 dbesc(protect_sprintf($datarray['title'])),
482                                                                 intval($importer_uid),
483                                                                 dbesc(NETWORK_MAIL));
484                                                         if (dbm::is_result($r))
485                                                                 $datarray['parent-uri'] = $r[0]['parent-uri'];
486                                                 }
487
488                                                 if(! x($datarray,'parent-uri'))
489                                                         $datarray['parent-uri'] = $datarray['uri'];
490
491
492                                                 $r = email_get_msg($mbox,$msg_uid, $reply);
493                                                 if(! $r) {
494                                                         logger("Mail: can't fetch msg ".$msg_uid." for ".$mailconf[0]['user']);
495                                                         continue;
496                                                 }
497                                                 $datarray['body'] = escape_tags($r['body']);
498                                                 $datarray['body'] = limit_body_size($datarray['body']);
499
500                                                 logger("Mail: Importing ".$msg_uid." for ".$mailconf[0]['user']);
501
502                                                 // some mailing lists have the original author as 'from' - add this sender info to msg body.
503                                                 /// @TODO Adding a gravatar for the original author would be cool
504
505                                                 if(! stristr($meta->from,$contact['addr'])) {
506                                                         $from = imap_mime_header_decode($meta->from);
507                                                         $fromdecoded = "";
508                                                         foreach($from as $frompart)
509                                                                 if ($frompart->charset != "default")
510                                                                         $fromdecoded .= iconv($frompart->charset, 'UTF-8//IGNORE', $frompart->text);
511                                                                 else
512                                                                         $fromdecoded .= $frompart->text;
513
514                                                         $fromarr = imap_rfc822_parse_adrlist($fromdecoded, $a->get_hostname());
515
516                                                         $frommail = $fromarr[0]->mailbox."@".$fromarr[0]->host;
517
518                                                         if (isset($fromarr[0]->personal))
519                                                                 $fromname = $fromarr[0]->personal;
520                                                         else
521                                                                 $fromname = $frommail;
522
523                                                         //$datarray['body'] = "[b]".t('From: ') . escape_tags($fromdecoded) . "[/b]\n\n" . $datarray['body'];
524
525                                                         $datarray['author-name'] = $fromname;
526                                                         $datarray['author-link'] = "mailto:".$frommail;
527                                                         $datarray['author-avatar'] = $contact['photo'];
528
529                                                         $datarray['owner-name'] = $contact['name'];
530                                                         $datarray['owner-link'] = "mailto:".$contact['addr'];
531                                                         $datarray['owner-avatar'] = $contact['photo'];
532
533                                                 } else {
534                                                         $datarray['author-name'] = $contact['name'];
535                                                         $datarray['author-link'] = 'mailbox';
536                                                         $datarray['author-avatar'] = $contact['photo'];
537                                                 }
538
539                                                 $datarray['uid'] = $importer_uid;
540                                                 $datarray['contact-id'] = $contact['id'];
541                                                 if($datarray['parent-uri'] === $datarray['uri'])
542                                                         $datarray['private'] = 1;
543                                                 if(($contact['network'] === NETWORK_MAIL) && (! get_pconfig($importer_uid,'system','allow_public_email_replies'))) {
544                                                         $datarray['private'] = 1;
545                                                         $datarray['allow_cid'] = '<' . $contact['id'] . '>';
546                                                 }
547
548                                                 $stored_item = item_store($datarray);
549                                                 q("UPDATE `item` SET `last-child` = 0 WHERE `parent-uri` = '%s' AND `uid` = %d",
550                                                         dbesc($datarray['parent-uri']),
551                                                         intval($importer_uid)
552                                                 );
553                                                 q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d",
554                                                         intval($stored_item)
555                                                 );
556                                                 switch ($mailconf[0]['action']) {
557                                                         case 0:
558                                                                 logger("Mail: Seen before ".$msg_uid." for ".$mailconf[0]['user'].". Doing nothing.", LOGGER_DEBUG);
559                                                                 break;
560                                                         case 1:
561                                                                 logger("Mail: Deleting ".$msg_uid." for ".$mailconf[0]['user']);
562                                                                 imap_delete($mbox, $msg_uid, FT_UID);
563                                                                 break;
564                                                         case 2:
565                                                                 logger("Mail: Mark as seen ".$msg_uid." for ".$mailconf[0]['user']);
566                                                                 imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
567                                                                 break;
568                                                         case 3:
569                                                                 logger("Mail: Moving ".$msg_uid." to ".$mailconf[0]['movetofolder']." for ".$mailconf[0]['user']);
570                                                                 imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
571                                                                 if ($mailconf[0]['movetofolder'] != "")
572                                                                         imap_mail_move($mbox, $msg_uid, $mailconf[0]['movetofolder'], FT_UID);
573                                                                 break;
574                                                 }
575                                         }
576                                 }
577                         } else
578                                 logger("Mail: no mails for ".$mailconf[0]['user']);
579
580                         logger("Mail: closing connection for ".$mailconf[0]['user']);
581                         imap_close($mbox);
582                 }
583         }
584         elseif($contact['network'] === NETWORK_FACEBOOK) {
585                 // This is picked up by the Facebook plugin on a cron hook.
586                 // Ignored here.
587         } elseif($contact['network'] === NETWORK_PUMPIO) {
588                 // This is picked up by the pump.io plugin on a cron hook.
589                 // Ignored here.
590         }
591
592         if($xml) {
593                 logger('poller: received xml : ' . $xml, LOGGER_DATA);
594                 if(! strstr($xml,'<')) {
595                         logger('poller: post_handshake: response from ' . $url . ' did not contain XML.');
596                         $r = q("UPDATE `contact` SET `last-update` = '%s',  `failure_update` = '%s' WHERE `id` = %d",
597                                 dbesc(datetime_convert()),
598                                 dbesc(datetime_convert()),
599                                 intval($contact['id'])
600                         );
601                         return;
602                 }
603
604
605                 logger("Consume feed of contact ".$contact['id']);
606
607                 consume_feed($xml,$importer,$contact,$hub,1,1);
608
609                 // do it twice. Ensures that children of parents which may be later in the stream aren't tossed
610
611                 consume_feed($xml,$importer,$contact,$hub,1,2);
612
613                 $hubmode = 'subscribe';
614                 if($contact['network'] === NETWORK_DFRN || $contact['blocked'] || $contact['readonly'])
615                         $hubmode = 'unsubscribe';
616
617                 if(($contact['network'] === NETWORK_OSTATUS ||  $contact['network'] == NETWORK_FEED) && (! $contact['hub-verify']))
618                         $hub_update = true;
619
620                 if ($force)
621                         $hub_update = true;
622
623                 logger("Contact ".$contact['id']." returned hub: ".$hub." Network: ".$contact['network']." Relation: ".$contact['rel']." Update: ".$hub_update);
624
625                 if((strlen($hub)) && ($hub_update) && (($contact['rel'] != CONTACT_IS_FOLLOWER) || $contact['network'] == NETWORK_FEED) ) {
626                         logger('poller: hub ' . $hubmode . ' : ' . $hub . ' contact name : ' . $contact['name'] . ' local user : ' . $importer['name']);
627                         $hubs = explode(',', $hub);
628                         if(count($hubs)) {
629                                 foreach($hubs as $h) {
630                                         $h = trim($h);
631                                         if(! strlen($h))
632                                                 continue;
633                                         subscribe_to_hub($h,$importer,$contact,$hubmode);
634                                 }
635                         }
636                 }
637
638                 $updated = datetime_convert();
639
640                 $r = q("UPDATE `contact` SET `last-update` = '%s', `success_update` = '%s' WHERE `id` = %d",
641                         dbesc($updated),
642                         dbesc($updated),
643                         intval($contact['id'])
644                 );
645
646                 q("UPDATE `gcontact` SET `last_contact` = '%s' WHERE `nurl` = '%s'",
647                         dbesc($updated),
648                         dbesc($contact['nurl'])
649                 );
650
651         } elseif (in_array($contact["network"], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS, NETWORK_FEED))) {
652                 $updated = datetime_convert();
653
654                 $r = q("UPDATE `contact` SET `last-update` = '%s', `failure_update` = '%s' WHERE `id` = %d",
655                         dbesc($updated),
656                         dbesc($updated),
657                         intval($contact['id'])
658                 );
659
660                 q("UPDATE `gcontact` SET `last_failure` = '%s' WHERE `nurl` = '%s'",
661                         dbesc($updated),
662                         dbesc($contact['nurl'])
663                 );
664         } else {
665                 $r = q("UPDATE `contact` SET `last-update` = '%s' WHERE `id` = %d",
666                         dbesc($updated),
667                         intval($contact['id'])
668                 );
669         }
670
671         return;
672 }
673
674 if (array_search(__file__,get_included_files())===0){
675         onepoll_run($_SERVER["argv"],$_SERVER["argc"]);
676         killme();
677 }