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'));
31 logger('poller: start');
33 // run queue delivery process in the background
35 proc_run('php',"include/queue.php");
37 // once daily run expire in background
39 $d1 = get_config('system','last_expire_day');
40 $d2 = intval(datetime_convert('UTC','UTC','now','d'));
42 if($d2 != intval($d1)) {
43 set_config('system','last_expire_day',$d2);
44 proc_run('php','include/expire.php');
49 q("DELETE FROM `cache` WHERE `updated` < '%s'",
50 dbesc(datetime_convert('UTC','UTC',"now - 30 days")));
56 if(($argc > 1) && ($argv[1] == 'force'))
59 if(($argc > 1) && intval($argv[1])) {
60 $manual_id = intval($argv[1]);
64 $sql_extra = (($manual_id) ? " AND `id` = $manual_id " : "");
68 $d = datetime_convert();
70 call_hooks('cron', $d);
73 $contacts = q("SELECT `id` FROM `contact`
74 WHERE ( `rel` = %d OR `rel` = %d ) AND `poll` != ''
76 AND `self` = 0 AND `blocked` = 0 AND `readonly` = 0 ORDER BY RAND()",
81 if(! count($contacts)) {
85 foreach($contacts as $c) {
87 $res = q("SELECT * FROM `contact` WHERE `id` = %d LIMIT 1",
94 foreach($res as $contact) {
99 $contact['last-update'] = '0000-00-00 00:00:00';
101 if($contact['priority'] || $contact['subhub']) {
106 $t = $contact['last-update'];
108 // We should be getting everything via a hub. But just to be sure, let's check once a day.
109 // (You can make this more or less frequent if desired by setting 'pushpoll_frequency' appropriately)
110 // This also lets us update our subscription to the hub, and add or replace hubs in case it
111 // changed. We will only update hubs once a day, regardless of 'pushpoll_frequency'.
114 if($contact['subhub']) {
115 $interval = get_config('system','pushpoll_frequency');
116 $contact['priority'] = (($interval !== false) ? intval($interval) : 3);
119 if((datetime_convert('UTC','UTC', 'now') > datetime_convert('UTC','UTC', $t . " + 1 day")) || $force)
124 * Based on $contact['priority'], should we poll this site now? Or later?
127 switch ($contact['priority']) {
129 if(datetime_convert('UTC','UTC', 'now') > datetime_convert('UTC','UTC', $t . " + 1 month"))
133 if(datetime_convert('UTC','UTC', 'now') > datetime_convert('UTC','UTC', $t . " + 1 week"))
137 if(datetime_convert('UTC','UTC', 'now') > datetime_convert('UTC','UTC', $t . " + 1 day"))
141 if(datetime_convert('UTC','UTC', 'now') > datetime_convert('UTC','UTC', $t . " + 12 hour"))
146 if(datetime_convert('UTC','UTC', 'now') > datetime_convert('UTC','UTC', $t . " + 1 hour"))
150 if((! $update) && (! $force))
154 $importer_uid = $contact['uid'];
156 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `self` = 1 LIMIT 1",
157 intval($importer_uid)
164 logger("poller: poll: IMPORTER: {$importer['name']}, CONTACT: {$contact['name']}");
166 $last_update = (($contact['last-update'] === '0000-00-00 00:00:00')
167 ? datetime_convert('UTC','UTC','now - 30 days', ATOM_TIME)
168 : datetime_convert('UTC','UTC',$contact['last-update'], ATOM_TIME)
171 if($contact['network'] === NETWORK_DFRN) {
173 $idtosend = $orig_id = (($contact['dfrn-id']) ? $contact['dfrn-id'] : $contact['issued-id']);
175 if(intval($contact['duplex']) && $contact['dfrn-id'])
176 $idtosend = '0:' . $orig_id;
177 if(intval($contact['duplex']) && $contact['issued-id'])
178 $idtosend = '1:' . $orig_id;
180 // they have permission to write to us. We already filtered this in the contact query.
183 $url = $contact['poll'] . '?dfrn_id=' . $idtosend
184 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
185 . '&type=data&last_update=' . $last_update
188 $handshake_xml = fetch_url($url);
190 logger('poller: handshake with url ' . $url . ' returns xml: ' . $handshake_xml, LOGGER_DATA);
193 if(! $handshake_xml) {
194 logger("poller: $url appears to be dead - marking for death ");
195 // dead connection - might be a transient event, or this might
196 // mean the software was uninstalled or the domain expired.
197 // Will keep trying for one month.
198 mark_for_death($contact);
200 // set the last-update so we don't keep polling
202 $r = q("UPDATE `contact` SET `last-update` = '%s' WHERE `id` = %d LIMIT 1",
203 dbesc(datetime_convert()),
204 intval($contact['id'])
210 if(! strstr($handshake_xml,'<?xml')) {
211 logger('poller: response from ' . $url . ' did not contain XML.');
212 $r = q("UPDATE `contact` SET `last-update` = '%s' WHERE `id` = %d LIMIT 1",
213 dbesc(datetime_convert()),
214 intval($contact['id'])
220 $res = parse_xml_string($handshake_xml);
222 if(intval($res->status) == 1) {
223 logger("poller: $url replied status 1 - marking for death ");
225 // we may not be friends anymore. Will keep trying for one month.
226 // set the last-update so we don't keep polling
228 $r = q("UPDATE `contact` SET `last-update` = '%s' WHERE `id` = %d LIMIT 1",
229 dbesc(datetime_convert()),
230 intval($contact['id'])
233 mark_for_death($contact);
236 if($contact['term-date'] != '0000-00-00 00:00:00') {
237 logger("poller: $url back from the dead - removing mark for death");
238 unmark_for_death($contact);
242 if((intval($res->status) != 0) || (! strlen($res->challenge)) || (! strlen($res->dfrn_id)))
247 $sent_dfrn_id = hex2bin((string) $res->dfrn_id);
248 $challenge = hex2bin((string) $res->challenge);
252 if(($contact['duplex']) && strlen($contact['prvkey'])) {
253 openssl_private_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['prvkey']);
254 openssl_private_decrypt($challenge,$postvars['challenge'],$contact['prvkey']);
257 openssl_public_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['pubkey']);
258 openssl_public_decrypt($challenge,$postvars['challenge'],$contact['pubkey']);
261 $final_dfrn_id = substr($final_dfrn_id, 0, strpos($final_dfrn_id, '.'));
263 if(strpos($final_dfrn_id,':') == 1)
264 $final_dfrn_id = substr($final_dfrn_id,2);
266 if($final_dfrn_id != $orig_id) {
267 logger('poller: ID did not decode: ' . $contact['id'] . ' orig: ' . $orig_id . ' final: ' . $final_dfrn_id);
268 // did not decode properly - cannot trust this site
272 $postvars['dfrn_id'] = $idtosend;
273 $postvars['dfrn_version'] = DFRN_PROTOCOL_VERSION;
274 $postvars['perm'] = 'rw';
276 $xml = post_url($contact['poll'],$postvars);
278 elseif(($contact['network'] === NETWORK_OSTATUS)
279 || ($contact['network'] === NETWORK_DIASPORA)
280 || ($contact['network'] === NETWORK_FEED) ) {
282 // Upgrading DB fields from an older Friendika version
283 // Will only do this once per notify-enabled OStatus contact
285 if(($contact['notify']) && (! $contact['writable'])) {
286 q("UPDATE `contact` SET `writable` = 1 WHERE `id` = %d LIMIT 1",
287 intval($contact['id'])
291 $xml = fetch_url($contact['poll']);
293 elseif($contact['network'] === NETWORK_MAIL) {
295 $mail_disabled = ((function_exists('imap_open') && (! get_config('system','imap_disabled'))) ? 0 : 1);
300 $x = q("SELECT `prvkey` FROM `user` WHERE `uid` = %d LIMIT 1",
301 intval($importer_uid)
303 $mailconf = q("SELECT * FROM `mailacct` WHERE `server` != '' AND `uid` = %d LIMIT 1",
304 intval($importer_uid)
306 if(count($x) && count($mailconf)) {
307 $mailbox = construct_mailbox_name($mailconf[0]);
309 openssl_private_decrypt(hex2bin($mailconf[0]['pass']),$password,$x[0]['prvkey']);
310 $mbox = email_connect($mailbox,$mailconf[0]['user'],$password);
313 q("UPDATE `mailacct` SET `last_check` = '%s' WHERE `id` = %d AND `uid` = %d LIMIT 1",
314 dbesc(datetime_convert()),
315 intval($mailconf[0]['id']),
316 intval($importer_uid)
322 $msgs = email_poll($mbox,$contact['addr']);
325 foreach($msgs as $msg_uid) {
327 $meta = email_msg_meta($mbox,$msg_uid);
328 $headers = email_msg_headers($mbox,$msg_uid);
330 // look for a 'references' header and try and match with a parent item we have locally.
332 $raw_refs = ((x($headers,'references')) ? str_replace("\t",'',$headers['references']) : '');
333 $datarray['uri'] = trim($meta->message_id,'<>');
336 $refs_arr = explode(' ', $raw_refs);
337 if(count($refs_arr)) {
338 for($x = 0; $x < count($refs_arr); $x ++)
339 $refs_arr[$x] = "'" . str_replace(array('<','>',' '),array('','',''),dbesc($refs_arr[$x])) . "'";
341 $qstr = implode(',',$refs_arr);
342 $r = q("SELECT `uri` , `parent-uri` FROM `item` WHERE `uri` IN ( $qstr ) AND `uid` = %d LIMIT 1",
343 intval($importer_uid)
346 $datarray['parent-uri'] = $r[0]['uri'];
350 if(! x($datarray,'parent-uri'))
351 $datarray['parent-uri'] = $datarray['uri'];
353 // Have we seen it before?
354 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `uri` = '%s' LIMIT 1",
355 intval($importer_uid),
356 dbesc($datarray['uri'])
360 if($meta->deleted && ! $r[0]['deleted']) {
361 q("UPDATE `item` SET `deleted` = 1, `changed` = '%s' WHERE `id` = %d LIMIT 1",
362 dbesc(datetime_convert()),
368 $datarray['title'] = notags(trim($meta->subject));
369 $datarray['created'] = datetime_convert('UTC','UTC',$meta->date);
371 $r = email_get_msg($mbox,$msg_uid);
374 $datarray['body'] = escape_tags($r['body']);
376 // some mailing lists have the original author as 'from' - add this sender info to msg body.
377 // todo: adding a gravatar for the original author would be cool
379 if(! stristr($meta->from,$contact['addr']))
380 $datarray['body'] = t('From: ') . escape_tags($meta->from) . "\n\n" . $datarray['body'];
382 $datarray['uid'] = $importer_uid;
383 $datarray['contact-id'] = $contact['id'];
384 if($datarray['parent-uri'] === $datarray['uri'])
385 $datarray['private'] = 1;
386 $datarray['author-name'] = $contact['name'];
387 $datarray['author-link'] = 'mailbox';
388 $datarray['author-avatar'] = $contact['photo'];
390 $stored_item = item_store($datarray);
391 q("UPDATE `item` SET `last-child` = 0 WHERE `parent-uri` = '%s' AND `uid` = %d",
392 dbesc($datarray['parent-uri']),
393 intval($importer_uid)
395 q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d LIMIT 1",
404 elseif($contact['network'] === NETWORK_FACEBOOK) {
405 // TODO: work in progress
409 logger('poller: received xml : ' . $xml, LOGGER_DATA);
411 if(! strstr($xml,'<?xml')) {
412 logger('poller: post_handshake: response from ' . $url . ' did not contain XML.');
413 $r = q("UPDATE `contact` SET `last-update` = '%s' WHERE `id` = %d LIMIT 1",
414 dbesc(datetime_convert()),
415 intval($contact['id'])
421 consume_feed($xml,$importer,$contact,$hub,1, true);
423 // do it twice. Ensures that children of parents which may be later in the stream aren't tossed
425 consume_feed($xml,$importer,$contact,$hub,1);
428 if((strlen($hub)) && ($hub_update) && (($contact['rel'] == REL_BUD) || (($contact['network'] === NETWORK_OSTATUS) && (! $contact['readonly'])))) {
429 logger('poller: subscribing to hub(s) : ' . $hub . ' contact name : ' . $contact['name'] . ' local user : ' . $importer['name']);
430 $hubs = explode(',', $hub);
432 foreach($hubs as $h) {
436 subscribe_to_hub($h,$importer,$contact);
442 $updated = datetime_convert();
444 $r = q("UPDATE `contact` SET `last-update` = '%s', `success_update` = '%s' WHERE `id` = %d LIMIT 1",
447 intval($contact['id'])
450 // loop - next contact
458 if (array_search(__file__,get_included_files())===0){
459 poller_run($argv,$argc);