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 $x = q("SELECT `prvkey` FROM `user` WHERE `uid` = %d LIMIT 1",
292 intval($importer_uid)
294 $mailconf = q("SELECT * FROM `mailacct` WHERE `server` != '' AND `uid` = %d LIMIT 1",
295 intval($importer_uid)
297 if(count($x) && count($mailconf)) {
298 $mailbox = construct_mailbox_name($mailconf[0]);
300 openssl_private_decrypt(hex2bin($mailconf[0]['pass']),$password,$x[0]['prvkey']);
301 $mbox = email_connect($mailbox,$mailconf[0]['user'],$password);
304 q("UPDATE `mailacct` SET `last_check` = '%s' WHERE `id` = %d AND `uid` = %d LIMIT 1",
305 dbesc(datetime_convert()),
306 intval($mailconf[0]['id']),
307 intval($importer_uid)
313 $msgs = email_poll($mbox,$contact['addr']);
316 foreach($msgs as $msg_uid) {
318 $meta = email_msg_meta($mbox,$msg_uid);
319 $headers = email_msg_headers($mbox,$msg_uid);
321 // look for a 'references' header and try and match with a parent item we have locally.
323 $raw_refs = ((x($headers,'references')) ? str_replace("\t",'',$headers['references']) : '');
324 $datarray['uri'] = trim($meta->message_id,'<>');
327 $refs_arr = explode(' ', $raw_refs);
328 if(count($refs_arr)) {
329 for($x = 0; $x < count($refs_arr); $x ++)
330 $refs_arr[$x] = "'" . str_replace(array('<','>',' '),array('','',''),dbesc($refs_arr[$x])) . "'";
332 $qstr = implode(',',$refs_arr);
333 $r = q("SELECT `uri` , `parent-uri` FROM `item` WHERE `uri` IN ( $qstr ) AND `uid` = %d LIMIT 1",
334 intval($importer_uid)
337 $datarray['parent-uri'] = $r[0]['uri'];
341 if(! x($datarray,'parent-uri'))
342 $datarray['parent-uri'] = $datarray['uri'];
344 // Have we seen it before?
345 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `uri` = '%s' LIMIT 1",
346 intval($importer_uid),
347 dbesc($datarray['uri'])
351 if($meta->deleted && ! $r[0]['deleted']) {
352 q("UPDATE `item` SET `deleted` = `, `changed` = '%s' WHERE `id` = %d LIMIT 1",
353 dbesc(datetime_convert()),
359 $datarray['title'] = notags(trim($meta->subject));
360 $datarray['created'] = datetime_convert('UTC','UTC',$meta->date);
362 $r = email_get_msg($mbox,$msg_uid);
365 $datarray['body'] = escape_tags($r['body']);
366 $datarray['uid'] = $importer_uid;
367 $datarray['contact-id'] = $contact['id'];
368 if($datarray['parent-uri'] === $datarray['uri'])
369 $datarray['private'] = 1;
370 $datarray['author-name'] = $contact['name'];
371 $datarray['author-link'] = 'mailbox';
372 $datarray['author-avatar'] = $contact['photo'];
374 $stored_item = item_store($datarray);
375 q("UPDATE `item` SET `last-child` = 0 WHERE `parent-uri` = '%s' AND `uid` = %d",
376 dbesc($datarray['parent-uri']),
377 intval($importer_uid)
379 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
442 if (array_search(__file__,get_included_files())===0){
443 poller_run($argv,$argc);