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);
20 require_once('session.php');
21 require_once('datetime.php');
22 require_once('simplepie/simplepie.inc');
23 require_once('include/items.php');
24 require_once('include/Contact.php');
25 require_once('include/email.php');
27 $a->set_baseurl(get_config('system','url'));
29 logger('poller: start');
31 // run queue delivery process in the background
33 proc_run('php',"include/queue.php");
35 // once daily run expire in background
37 $d1 = get_config('system','last_expire_day');
38 $d2 = intval(datetime_convert('UTC','UTC','now','d'));
40 if($d2 != intval($d1)) {
41 set_config('system','last_expire_day',$d2);
42 proc_run('php','include/expire.php');
47 q("DELETE FROM `cache` WHERE `updated` < '%s'",
48 dbesc(datetime_convert('UTC','UTC',"now - 30 days")));
54 if(($argc > 1) && ($argv[1] == 'force'))
57 if(($argc > 1) && intval($argv[1])) {
58 $manual_id = intval($argv[1]);
62 $sql_extra = (($manual_id) ? " AND `id` = $manual_id " : "");
64 $d = datetime_convert();
65 call_hooks('cron', $d);
69 $contacts = q("SELECT `id` FROM `contact`
70 WHERE ( `rel` = %d OR `rel` = %d ) AND `poll` != ''
72 AND `self` = 0 AND `blocked` = 0 AND `readonly` = 0 ORDER BY RAND()",
77 if(! count($contacts)) {
81 foreach($contacts as $c) {
83 $res = q("SELECT * FROM `contact` WHERE `id` = %d LIMIT 1",
90 foreach($res as $contact) {
95 $contact['last-update'] = '0000-00-00 00:00:00';
97 if($contact['priority'] || $contact['subhub']) {
102 $t = $contact['last-update'];
104 // We should be getting everything via a hub. But just to be sure, let's check once a day.
105 // (You can make this more or less frequent if desired by setting 'pushpoll_frequency' appropriately)
106 // This also lets us update our subscription to the hub, and add or replace hubs in case it
107 // changed. We will only update hubs once a day, regardless of 'pushpoll_frequency'.
110 if($contact['subhub']) {
111 $interval = get_config('system','pushpoll_frequency');
112 $contact['priority'] = (($interval !== false) ? intval($interval) : 3);
115 if((datetime_convert('UTC','UTC', 'now') > datetime_convert('UTC','UTC', $t . " + 1 day")) || $force)
120 * Based on $contact['priority'], should we poll this site now? Or later?
123 switch ($contact['priority']) {
125 if(datetime_convert('UTC','UTC', 'now') > datetime_convert('UTC','UTC', $t . " + 1 month"))
129 if(datetime_convert('UTC','UTC', 'now') > datetime_convert('UTC','UTC', $t . " + 1 week"))
133 if(datetime_convert('UTC','UTC', 'now') > datetime_convert('UTC','UTC', $t . " + 1 day"))
137 if(datetime_convert('UTC','UTC', 'now') > datetime_convert('UTC','UTC', $t . " + 12 hour"))
142 if(datetime_convert('UTC','UTC', 'now') > datetime_convert('UTC','UTC', $t . " + 1 hour"))
146 if((! $update) && (! $force))
150 $importer_uid = $contact['uid'];
152 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `self` = 1 LIMIT 1",
153 intval($importer_uid)
160 logger("poller: poll: IMPORTER: {$importer['name']}, CONTACT: {$contact['name']}");
162 $last_update = (($contact['last-update'] === '0000-00-00 00:00:00')
163 ? datetime_convert('UTC','UTC','now - 30 days', ATOM_TIME)
164 : datetime_convert('UTC','UTC',$contact['last-update'], ATOM_TIME)
167 if($contact['network'] === NETWORK_DFRN) {
169 $idtosend = $orig_id = (($contact['dfrn-id']) ? $contact['dfrn-id'] : $contact['issued-id']);
171 if(intval($contact['duplex']) && $contact['dfrn-id'])
172 $idtosend = '0:' . $orig_id;
173 if(intval($contact['duplex']) && $contact['issued-id'])
174 $idtosend = '1:' . $orig_id;
176 // they have permission to write to us. We already filtered this in the contact query.
179 $url = $contact['poll'] . '?dfrn_id=' . $idtosend
180 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
181 . '&type=data&last_update=' . $last_update
184 $handshake_xml = fetch_url($url);
186 logger('poller: handshake with url ' . $url . ' returns xml: ' . $handshake_xml, LOGGER_DATA);
189 if(! $handshake_xml) {
190 logger("poller: $url appears to be dead - marking for death ");
191 // dead connection - might be a transient event, or this might
192 // mean the software was uninstalled or the domain expired.
193 // Will keep trying for one month.
194 mark_for_death($contact);
196 // set the last-update so we don't keep polling
198 $r = q("UPDATE `contact` SET `last-update` = '%s' WHERE `id` = %d LIMIT 1",
199 dbesc(datetime_convert()),
200 intval($contact['id'])
206 if(! strstr($handshake_xml,'<?xml')) {
207 logger('poller: response from ' . $url . ' did not contain XML.');
208 $r = q("UPDATE `contact` SET `last-update` = '%s' WHERE `id` = %d LIMIT 1",
209 dbesc(datetime_convert()),
210 intval($contact['id'])
216 $res = parse_xml_string($handshake_xml);
218 if(intval($res->status) == 1) {
219 logger("poller: $url replied status 1 - marking for death ");
221 // we may not be friends anymore. Will keep trying for one month.
222 // set the last-update so we don't keep polling
224 $r = q("UPDATE `contact` SET `last-update` = '%s' WHERE `id` = %d LIMIT 1",
225 dbesc(datetime_convert()),
226 intval($contact['id'])
229 mark_for_death($contact);
232 if($contact['term-date'] != '0000-00-00 00:00:00') {
233 logger("poller: $url back from the dead - removing mark for death");
234 unmark_for_death($contact);
238 if((intval($res->status) != 0) || (! strlen($res->challenge)) || (! strlen($res->dfrn_id)))
243 $sent_dfrn_id = hex2bin((string) $res->dfrn_id);
244 $challenge = hex2bin((string) $res->challenge);
248 if(($contact['duplex']) && strlen($contact['prvkey'])) {
249 openssl_private_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['prvkey']);
250 openssl_private_decrypt($challenge,$postvars['challenge'],$contact['prvkey']);
253 openssl_public_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['pubkey']);
254 openssl_public_decrypt($challenge,$postvars['challenge'],$contact['pubkey']);
257 $final_dfrn_id = substr($final_dfrn_id, 0, strpos($final_dfrn_id, '.'));
259 if(strpos($final_dfrn_id,':') == 1)
260 $final_dfrn_id = substr($final_dfrn_id,2);
262 if($final_dfrn_id != $orig_id) {
263 logger('poller: ID did not decode: ' . $contact['id'] . ' orig: ' . $orig_id . ' final: ' . $final_dfrn_id);
264 // did not decode properly - cannot trust this site
268 $postvars['dfrn_id'] = $idtosend;
269 $postvars['dfrn_version'] = DFRN_PROTOCOL_VERSION;
270 $postvars['perm'] = 'rw';
272 $xml = post_url($contact['poll'],$postvars);
274 elseif(($contact['network'] === NETWORK_OSTATUS)
275 || ($contact['network'] === NETWORK_DIASPORA)
276 || ($contact['network'] === NETWORK_FEED) ) {
278 // Upgrading DB fields from an older Friendika version
279 // Will only do this once per notify-enabled OStatus contact
281 if(($contact['notify']) && (! $contact['writable'])) {
282 q("UPDATE `contact` SET `writable` = 1 WHERE `id` = %d LIMIT 1",
283 intval($contact['id'])
287 $xml = fetch_url($contact['poll']);
289 elseif($contact['network'] === NETWORK_MAIL) {
291 $mail_disabled = ((function_exists('imap_open') && (! get_config('system','imap_disabled'))) ? 0 : 1);
296 $x = q("SELECT `prvkey` FROM `user` WHERE `uid` = %d LIMIT 1",
297 intval($importer_uid)
299 $mailconf = q("SELECT * FROM `mailacct` WHERE `server` != '' AND `uid` = %d LIMIT 1",
300 intval($importer_uid)
302 if(count($x) && count($mailconf)) {
303 $mailbox = construct_mailbox_name($mailconf[0]);
305 openssl_private_decrypt(hex2bin($mailconf[0]['pass']),$password,$x[0]['prvkey']);
306 $mbox = email_connect($mailbox,$mailconf[0]['user'],$password);
309 q("UPDATE `mailacct` SET `last_check` = '%s' WHERE `id` = %d AND `uid` = %d LIMIT 1",
310 dbesc(datetime_convert()),
311 intval($mailconf[0]['id']),
312 intval($importer_uid)
318 $msgs = email_poll($mbox,$contact['addr']);
321 foreach($msgs as $msg_uid) {
323 $meta = email_msg_meta($mbox,$msg_uid);
324 $headers = email_msg_headers($mbox,$msg_uid);
326 // look for a 'references' header and try and match with a parent item we have locally.
328 $raw_refs = ((x($headers,'references')) ? str_replace("\t",'',$headers['references']) : '');
329 $datarray['uri'] = trim($meta->message_id,'<>');
332 $refs_arr = explode(' ', $raw_refs);
333 if(count($refs_arr)) {
334 for($x = 0; $x < count($refs_arr); $x ++)
335 $refs_arr[$x] = "'" . str_replace(array('<','>',' '),array('','',''),dbesc($refs_arr[$x])) . "'";
337 $qstr = implode(',',$refs_arr);
338 $r = q("SELECT `uri` , `parent-uri` FROM `item` WHERE `uri` IN ( $qstr ) AND `uid` = %d LIMIT 1",
339 intval($importer_uid)
342 $datarray['parent-uri'] = $r[0]['uri'];
346 if(! x($datarray,'parent-uri'))
347 $datarray['parent-uri'] = $datarray['uri'];
349 // Have we seen it before?
350 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `uri` = '%s' LIMIT 1",
351 intval($importer_uid),
352 dbesc($datarray['uri'])
356 if($meta->deleted && ! $r[0]['deleted']) {
357 q("UPDATE `item` SET `deleted` = `, `changed` = '%s' WHERE `id` = %d LIMIT 1",
358 dbesc(datetime_convert()),
364 $datarray['title'] = notags(trim($meta->subject));
365 $datarray['created'] = datetime_convert('UTC','UTC',$meta->date);
367 $r = email_get_msg($mbox,$msg_uid);
370 $datarray['body'] = escape_tags($r['body']);
371 $datarray['uid'] = $importer_uid;
372 $datarray['contact-id'] = $contact['id'];
373 if($datarray['parent-uri'] === $datarray['uri'])
374 $datarray['private'] = 1;
375 $datarray['author-name'] = $contact['name'];
376 $datarray['author-link'] = 'mailbox';
377 $datarray['author-avatar'] = $contact['photo'];
379 $stored_item = item_store($datarray);
380 q("UPDATE `item` SET `last-child` = 0 WHERE `parent-uri` = '%s' AND `uid` = %d",
381 dbesc($datarray['parent-uri']),
382 intval($importer_uid)
384 q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d LIMIT 1",
393 elseif($contact['network'] === NETWORK_FACEBOOK) {
394 // TODO: work in progress
398 logger('poller: received xml : ' . $xml, LOGGER_DATA);
400 if(! strstr($xml,'<?xml')) {
401 logger('poller: post_handshake: response from ' . $url . ' did not contain XML.');
402 $r = q("UPDATE `contact` SET `last-update` = '%s' WHERE `id` = %d LIMIT 1",
403 dbesc(datetime_convert()),
404 intval($contact['id'])
410 consume_feed($xml,$importer,$contact,$hub,1, true);
412 // do it twice. Ensures that children of parents which may be later in the stream aren't tossed
414 consume_feed($xml,$importer,$contact,$hub,1);
417 if((strlen($hub)) && ($hub_update) && (($contact['rel'] == REL_BUD) || (($contact['network'] === NETWORK_OSTATUS) && (! $contact['readonly'])))) {
418 logger('poller: subscribing to hub(s) : ' . $hub . ' contact name : ' . $contact['name'] . ' local user : ' . $importer['name']);
419 $hubs = explode(',', $hub);
421 foreach($hubs as $h) {
425 subscribe_to_hub($h,$importer,$contact);
431 $updated = datetime_convert();
433 $r = q("UPDATE `contact` SET `last-update` = '%s', `success_update` = '%s' WHERE `id` = %d LIMIT 1",
436 intval($contact['id'])
439 // loop - next contact
447 if (array_search(__file__,get_included_files())===0){
448 poller_run($argv,$argc);