3 require_once("boot.php");
5 function poller_run($argv, $argc){
13 @include(".htconfig.php");
14 require_once("dba.php");
15 $db = new dba($db_host, $db_user, $db_pass, $db_data);
16 unset($db_host, $db_user, $db_pass, $db_data);
21 require_once('session.php');
22 require_once('datetime.php');
23 require_once('simplepie/simplepie.inc');
24 require_once('include/items.php');
25 require_once('include/Contact.php');
26 require_once('include/email.php');
28 $a->set_baseurl(get_config('system','url'));
30 logger('poller: start');
32 // run queue delivery process in the background
34 proc_run('php',"include/queue.php");
36 // once daily run expire in background
38 $d1 = get_config('system','last_expire_day');
39 $d2 = intval(datetime_convert('UTC','UTC','now','d'));
41 if($d2 != intval($d1)) {
42 set_config('system','last_expire_day',$d2);
43 proc_run('php','include/expire.php');
48 q("DELETE FROM `cache` WHERE `updated` < '%s'",
49 dbesc(datetime_convert('UTC','UTC',"now - 30 days")));
55 if(($argc > 1) && ($argv[1] == 'force'))
58 if(($argc > 1) && intval($argv[1])) {
59 $manual_id = intval($argv[1]);
63 $sql_extra = (($manual_id) ? " AND `id` = $manual_id " : "");
65 $d = datetime_convert();
66 call_hooks('cron', $d);
70 $contacts = q("SELECT `id` FROM `contact`
71 WHERE ( `rel` = %d OR `rel` = %d ) AND `poll` != ''
73 AND `self` = 0 AND `blocked` = 0 AND `readonly` = 0 ORDER BY RAND()",
78 if(! count($contacts)) {
82 foreach($contacts as $c) {
84 $res = q("SELECT * FROM `contact` WHERE `id` = %d LIMIT 1",
91 foreach($res as $contact) {
96 $contact['last-update'] = '0000-00-00 00:00:00';
98 if($contact['priority'] || $contact['subhub']) {
103 $t = $contact['last-update'];
105 // We should be getting everything via a hub. But just to be sure, let's check once a day.
106 // (You can make this more or less frequent if desired by setting 'pushpoll_frequency' appropriately)
107 // This also lets us update our subscription to the hub, and add or replace hubs in case it
108 // changed. We will only update hubs once a day, regardless of 'pushpoll_frequency'.
111 if($contact['subhub']) {
112 $interval = get_config('system','pushpoll_frequency');
113 $contact['priority'] = (($interval !== false) ? intval($interval) : 3);
116 if((datetime_convert('UTC','UTC', 'now') > datetime_convert('UTC','UTC', $t . " + 1 day")) || $force)
121 * Based on $contact['priority'], should we poll this site now? Or later?
124 switch ($contact['priority']) {
126 if(datetime_convert('UTC','UTC', 'now') > datetime_convert('UTC','UTC', $t . " + 1 month"))
130 if(datetime_convert('UTC','UTC', 'now') > datetime_convert('UTC','UTC', $t . " + 1 week"))
134 if(datetime_convert('UTC','UTC', 'now') > datetime_convert('UTC','UTC', $t . " + 1 day"))
138 if(datetime_convert('UTC','UTC', 'now') > datetime_convert('UTC','UTC', $t . " + 12 hour"))
143 if(datetime_convert('UTC','UTC', 'now') > datetime_convert('UTC','UTC', $t . " + 1 hour"))
147 if((! $update) && (! $force))
151 $importer_uid = $contact['uid'];
153 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `self` = 1 LIMIT 1",
154 intval($importer_uid)
161 logger("poller: poll: IMPORTER: {$importer['name']}, CONTACT: {$contact['name']}");
163 $last_update = (($contact['last-update'] === '0000-00-00 00:00:00')
164 ? datetime_convert('UTC','UTC','now - 30 days', ATOM_TIME)
165 : datetime_convert('UTC','UTC',$contact['last-update'], ATOM_TIME)
168 if($contact['network'] === NETWORK_DFRN) {
170 $idtosend = $orig_id = (($contact['dfrn-id']) ? $contact['dfrn-id'] : $contact['issued-id']);
172 if(intval($contact['duplex']) && $contact['dfrn-id'])
173 $idtosend = '0:' . $orig_id;
174 if(intval($contact['duplex']) && $contact['issued-id'])
175 $idtosend = '1:' . $orig_id;
177 // they have permission to write to us. We already filtered this in the contact query.
180 $url = $contact['poll'] . '?dfrn_id=' . $idtosend
181 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
182 . '&type=data&last_update=' . $last_update
185 $handshake_xml = fetch_url($url);
187 logger('poller: handshake with url ' . $url . ' returns xml: ' . $handshake_xml, LOGGER_DATA);
190 if(! $handshake_xml) {
191 logger("poller: $url appears to be dead - marking for death ");
192 // dead connection - might be a transient event, or this might
193 // mean the software was uninstalled or the domain expired.
194 // Will keep trying for one month.
195 mark_for_death($contact);
197 // set the last-update so we don't keep polling
199 $r = q("UPDATE `contact` SET `last-update` = '%s' WHERE `id` = %d LIMIT 1",
200 dbesc(datetime_convert()),
201 intval($contact['id'])
207 if(! strstr($handshake_xml,'<?xml')) {
208 logger('poller: response from ' . $url . ' did not contain XML.');
209 $r = q("UPDATE `contact` SET `last-update` = '%s' WHERE `id` = %d LIMIT 1",
210 dbesc(datetime_convert()),
211 intval($contact['id'])
217 $res = parse_xml_string($handshake_xml);
219 if(intval($res->status) == 1) {
220 logger("poller: $url replied status 1 - marking for death ");
222 // we may not be friends anymore. Will keep trying for one month.
223 // set the last-update so we don't keep polling
225 $r = q("UPDATE `contact` SET `last-update` = '%s' WHERE `id` = %d LIMIT 1",
226 dbesc(datetime_convert()),
227 intval($contact['id'])
230 mark_for_death($contact);
233 if($contact['term-date'] != '0000-00-00 00:00:00') {
234 logger("poller: $url back from the dead - removing mark for death");
235 unmark_for_death($contact);
239 if((intval($res->status) != 0) || (! strlen($res->challenge)) || (! strlen($res->dfrn_id)))
244 $sent_dfrn_id = hex2bin((string) $res->dfrn_id);
245 $challenge = hex2bin((string) $res->challenge);
249 if(($contact['duplex']) && strlen($contact['prvkey'])) {
250 openssl_private_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['prvkey']);
251 openssl_private_decrypt($challenge,$postvars['challenge'],$contact['prvkey']);
254 openssl_public_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['pubkey']);
255 openssl_public_decrypt($challenge,$postvars['challenge'],$contact['pubkey']);
258 $final_dfrn_id = substr($final_dfrn_id, 0, strpos($final_dfrn_id, '.'));
260 if(strpos($final_dfrn_id,':') == 1)
261 $final_dfrn_id = substr($final_dfrn_id,2);
263 if($final_dfrn_id != $orig_id) {
264 logger('poller: ID did not decode: ' . $contact['id'] . ' orig: ' . $orig_id . ' final: ' . $final_dfrn_id);
265 // did not decode properly - cannot trust this site
269 $postvars['dfrn_id'] = $idtosend;
270 $postvars['dfrn_version'] = DFRN_PROTOCOL_VERSION;
271 $postvars['perm'] = 'rw';
273 $xml = post_url($contact['poll'],$postvars);
275 elseif(($contact['network'] === NETWORK_OSTATUS)
276 || ($contact['network'] === NETWORK_DIASPORA)
277 || ($contact['network'] === NETWORK_FEED) ) {
279 // Upgrading DB fields from an older Friendika version
280 // Will only do this once per notify-enabled OStatus contact
282 if(($contact['notify']) && (! $contact['writable'])) {
283 q("UPDATE `contact` SET `writable` = 1 WHERE `id` = %d LIMIT 1",
284 intval($contact['id'])
288 $xml = fetch_url($contact['poll']);
290 elseif($contact['network'] === NETWORK_MAIL) {
292 $x = q("SELECT `prvkey` FROM `user` WHERE `uid` = %d LIMIT 1",
293 intval($importer_uid)
295 $mailconf = q("SELECT * FROM `mailacct` WHERE `server` != '' AND `uid` = %d LIMIT 1",
296 intval($importer_uid)
298 if(count($x) && count($mailconf)) {
299 $mailbox = construct_mailbox_name($mailconf[0]);
301 openssl_private_decrypt(hex2bin($mailconf[0]['pass']),$password,$x[0]['prvkey']);
302 $mbox = email_connect($mailbox,$mailconf[0]['user'],$password);
305 q("UPDATE `mailacct` SET `last_check` = '%s' WHERE `id` = %d AND `uid` = %d LIMIT 1",
306 dbesc(datetime_convert()),
307 intval($mailconf[0]['id']),
308 intval($importer_uid)
315 $msgs = email_poll($mbox,$contact['addr']);
318 foreach($msgs as $msg_uid) {
320 $meta = email_msg_meta($mbox,$msg_uid);
321 $headers = email_msg_headers($mbox,$msg_uid);
323 // look for a 'references' header and try and match with a parent item we have locally.
325 $raw_refs = ((x($headers,'references')) ? str_replace("\t",'',$headers['references']) : '');
326 $datarray['uri'] = trim($meta->message_id,'<>');
329 $refs_arr = explode(' ', $raw_refs);
330 if(count($refs_arr)) {
331 for($x = 0; $x < count($refs_arr); $x ++)
332 $refs_arr[$x] = "'" . str_replace(array('<','>',' '),array('','',''),dbesc($refs_arr[$x])) . "'";
334 $qstr = implode(',',$refs_arr);
335 $r = q("SELECT `uri` , `parent-uri` FROM `item` WHERE `uri` IN ( $qstr ) AND `uid` = %d LIMIT 1",
336 intval($importer_uid)
339 $datarray['parent-uri'] = $r[0]['uri'];
343 if(! x($datarray,'parent-uri'))
344 $datarray['parent-uri'] = $datarray['uri'];
346 // Have we seen it before?
347 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `uri` = '%s' LIMIT 1",
348 intval($importer_uid),
349 dbesc($datarray['uri'])
353 if($meta->deleted && ! $r[0]['deleted']) {
354 q("UPDATE `item` SET `deleted` = `, `changed` = '%s' WHERE `id` = %d LIMIT 1",
355 dbesc(datetime_convert()),
361 $datarray['title'] = notags(trim($meta->subject));
362 $datarray['created'] = datetime_convert('UTC','UTC',$meta->date);
364 $r = email_get_msg($mbox,$msg_uid);
367 $datarray['body'] = escape_tags($r['body']);
368 $datarray['uid'] = $importer_uid;
369 $datarray['contact-id'] = $contact['id'];
370 if($datarray['parent-uri'] === $datarray['uri'])
371 $datarray['private'] = 1;
372 $datarray['author-name'] = $contact['name'];
373 $datarray['author-link'] = 'mailbox';
374 $datarray['author-avatar'] = $contact['photo'];
376 $stored_item = item_store($datarray);
377 q("UPDATE `item` SET `last-child` = 0 WHERE `parent-uri` = '%s' AND `uid` = %d",
378 dbesc($datarray['parent-uri']),
379 intval($importer_uid)
381 q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d LIMIT 1",
388 elseif($contact['network'] === NETWORK_FACEBOOK) {
389 // TODO: work in progress
393 logger('poller: received xml : ' . $xml, LOGGER_DATA);
395 if(! strstr($xml,'<?xml')) {
396 logger('poller: post_handshake: response from ' . $url . ' did not contain XML.');
397 $r = q("UPDATE `contact` SET `last-update` = '%s' WHERE `id` = %d LIMIT 1",
398 dbesc(datetime_convert()),
399 intval($contact['id'])
405 consume_feed($xml,$importer,$contact,$hub,1, true);
407 // do it twice. Ensures that children of parents which may be later in the stream aren't tossed
409 consume_feed($xml,$importer,$contact,$hub,1);
412 if((strlen($hub)) && ($hub_update) && (($contact['rel'] == REL_BUD) || (($contact['network'] === NETWORK_OSTATUS) && (! $contact['readonly'])))) {
413 logger('poller: subscribing to hub(s) : ' . $hub . ' contact name : ' . $contact['name'] . ' local user : ' . $importer['name']);
414 $hubs = explode(',', $hub);
416 foreach($hubs as $h) {
420 subscribe_to_hub($h,$importer,$contact);
426 $updated = datetime_convert();
428 $r = q("UPDATE `contact` SET `last-update` = '%s', `success_update` = '%s' WHERE `id` = %d LIMIT 1",
431 intval($contact['id'])
434 // loop - next contact
438 if($mbox && function_exists('imap_close'))
444 if (array_search(__file__,get_included_files())===0){
445 poller_run($argv,$argc);