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('include/session.php');
21 require_once('include/datetime.php');
22 require_once('library/simplepie/simplepie.inc');
23 require_once('include/items.php');
24 require_once('include/Contact.php');
25 require_once('include/email.php');
27 load_config('config');
28 load_config('system');
30 $a->set_baseurl(get_config('system','url'));
34 logger('poller: start');
36 // run queue delivery process in the background
38 proc_run('php',"include/queue.php");
40 // once daily run expire in background
42 $d1 = get_config('system','last_expire_day');
43 $d2 = intval(datetime_convert('UTC','UTC','now','d'));
45 if($d2 != intval($d1)) {
46 set_config('system','last_expire_day',$d2);
47 proc_run('php','include/expire.php');
52 q("DELETE FROM `cache` WHERE `updated` < '%s'",
53 dbesc(datetime_convert('UTC','UTC',"now - 30 days")));
59 if(($argc > 1) && ($argv[1] == 'force'))
62 if(($argc > 1) && intval($argv[1])) {
63 $manual_id = intval($argv[1]);
67 $sql_extra = (($manual_id) ? " AND `id` = $manual_id " : "");
71 $d = datetime_convert();
73 call_hooks('cron', $d);
76 $contacts = q("SELECT `id` FROM `contact`
77 WHERE ( `rel` = %d OR `rel` = %d ) AND `poll` != ''
79 AND `self` = 0 AND `blocked` = 0 AND `readonly` = 0 ORDER BY RAND()",
84 if(! count($contacts)) {
88 foreach($contacts as $c) {
90 $res = q("SELECT * FROM `contact` WHERE `id` = %d LIMIT 1",
97 foreach($res as $contact) {
102 $contact['last-update'] = '0000-00-00 00:00:00';
104 if($contact['priority'] || $contact['subhub']) {
109 $t = $contact['last-update'];
111 // We should be getting everything via a hub. But just to be sure, let's check once a day.
112 // (You can make this more or less frequent if desired by setting 'pushpoll_frequency' appropriately)
113 // This also lets us update our subscription to the hub, and add or replace hubs in case it
114 // changed. We will only update hubs once a day, regardless of 'pushpoll_frequency'.
117 if($contact['subhub']) {
118 $interval = get_config('system','pushpoll_frequency');
119 $contact['priority'] = (($interval !== false) ? intval($interval) : 3);
122 if((datetime_convert('UTC','UTC', 'now') > datetime_convert('UTC','UTC', $t . " + 1 day")) || $force)
127 * Based on $contact['priority'], should we poll this site now? Or later?
130 switch ($contact['priority']) {
132 if(datetime_convert('UTC','UTC', 'now') > datetime_convert('UTC','UTC', $t . " + 1 month"))
136 if(datetime_convert('UTC','UTC', 'now') > datetime_convert('UTC','UTC', $t . " + 1 week"))
140 if(datetime_convert('UTC','UTC', 'now') > datetime_convert('UTC','UTC', $t . " + 1 day"))
144 if(datetime_convert('UTC','UTC', 'now') > datetime_convert('UTC','UTC', $t . " + 12 hour"))
149 if(datetime_convert('UTC','UTC', 'now') > datetime_convert('UTC','UTC', $t . " + 1 hour"))
153 if((! $update) && (! $force))
157 $importer_uid = $contact['uid'];
159 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `self` = 1 LIMIT 1",
160 intval($importer_uid)
167 logger("poller: poll: IMPORTER: {$importer['name']}, CONTACT: {$contact['name']}");
169 $last_update = (($contact['last-update'] === '0000-00-00 00:00:00')
170 ? datetime_convert('UTC','UTC','now - 30 days', ATOM_TIME)
171 : datetime_convert('UTC','UTC',$contact['last-update'], ATOM_TIME)
174 if($contact['network'] === NETWORK_DFRN) {
176 $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;
183 // they have permission to write to us. We already filtered this in the contact query.
186 $url = $contact['poll'] . '?dfrn_id=' . $idtosend
187 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
188 . '&type=data&last_update=' . $last_update
191 $handshake_xml = fetch_url($url);
193 logger('poller: handshake with url ' . $url . ' returns xml: ' . $handshake_xml, LOGGER_DATA);
196 if(! $handshake_xml) {
197 logger("poller: $url appears to be dead - marking for death ");
198 // dead connection - might be a transient event, or this might
199 // mean the software was uninstalled or the domain expired.
200 // Will keep trying for one month.
201 mark_for_death($contact);
203 // set the last-update so we don't keep polling
205 $r = q("UPDATE `contact` SET `last-update` = '%s' WHERE `id` = %d LIMIT 1",
206 dbesc(datetime_convert()),
207 intval($contact['id'])
213 if(! strstr($handshake_xml,'<?xml')) {
214 logger('poller: response from ' . $url . ' did not contain XML.');
215 $r = q("UPDATE `contact` SET `last-update` = '%s' WHERE `id` = %d LIMIT 1",
216 dbesc(datetime_convert()),
217 intval($contact['id'])
223 $res = parse_xml_string($handshake_xml);
225 if(intval($res->status) == 1) {
226 logger("poller: $url replied status 1 - marking for death ");
228 // we may not be friends anymore. Will keep trying for one month.
229 // set the last-update so we don't keep polling
231 $r = q("UPDATE `contact` SET `last-update` = '%s' WHERE `id` = %d LIMIT 1",
232 dbesc(datetime_convert()),
233 intval($contact['id'])
236 mark_for_death($contact);
239 if($contact['term-date'] != '0000-00-00 00:00:00') {
240 logger("poller: $url back from the dead - removing mark for death");
241 unmark_for_death($contact);
245 if((intval($res->status) != 0) || (! strlen($res->challenge)) || (! strlen($res->dfrn_id)))
250 $sent_dfrn_id = hex2bin((string) $res->dfrn_id);
251 $challenge = hex2bin((string) $res->challenge);
255 if(($contact['duplex']) && strlen($contact['prvkey'])) {
256 openssl_private_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['prvkey']);
257 openssl_private_decrypt($challenge,$postvars['challenge'],$contact['prvkey']);
260 openssl_public_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['pubkey']);
261 openssl_public_decrypt($challenge,$postvars['challenge'],$contact['pubkey']);
264 $final_dfrn_id = substr($final_dfrn_id, 0, strpos($final_dfrn_id, '.'));
266 if(strpos($final_dfrn_id,':') == 1)
267 $final_dfrn_id = substr($final_dfrn_id,2);
269 if($final_dfrn_id != $orig_id) {
270 logger('poller: ID did not decode: ' . $contact['id'] . ' orig: ' . $orig_id . ' final: ' . $final_dfrn_id);
271 // did not decode properly - cannot trust this site
275 $postvars['dfrn_id'] = $idtosend;
276 $postvars['dfrn_version'] = DFRN_PROTOCOL_VERSION;
277 $postvars['perm'] = 'rw';
279 $xml = post_url($contact['poll'],$postvars);
281 elseif(($contact['network'] === NETWORK_OSTATUS)
282 || ($contact['network'] === NETWORK_DIASPORA)
283 || ($contact['network'] === NETWORK_FEED) ) {
285 // Upgrading DB fields from an older Friendika version
286 // Will only do this once per notify-enabled OStatus contact
288 if(($contact['notify']) && (! $contact['writable'])) {
289 q("UPDATE `contact` SET `writable` = 1 WHERE `id` = %d LIMIT 1",
290 intval($contact['id'])
294 $xml = fetch_url($contact['poll']);
296 elseif($contact['network'] === NETWORK_MAIL) {
298 $mail_disabled = ((function_exists('imap_open') && (! get_config('system','imap_disabled'))) ? 0 : 1);
303 $x = q("SELECT `prvkey` FROM `user` WHERE `uid` = %d LIMIT 1",
304 intval($importer_uid)
306 $mailconf = q("SELECT * FROM `mailacct` WHERE `server` != '' AND `uid` = %d LIMIT 1",
307 intval($importer_uid)
309 if(count($x) && count($mailconf)) {
310 $mailbox = construct_mailbox_name($mailconf[0]);
312 openssl_private_decrypt(hex2bin($mailconf[0]['pass']),$password,$x[0]['prvkey']);
313 $mbox = email_connect($mailbox,$mailconf[0]['user'],$password);
316 q("UPDATE `mailacct` SET `last_check` = '%s' WHERE `id` = %d AND `uid` = %d LIMIT 1",
317 dbesc(datetime_convert()),
318 intval($mailconf[0]['id']),
319 intval($importer_uid)
325 $msgs = email_poll($mbox,$contact['addr']);
328 foreach($msgs as $msg_uid) {
330 $meta = email_msg_meta($mbox,$msg_uid);
331 $headers = email_msg_headers($mbox,$msg_uid);
333 // look for a 'references' header and try and match with a parent item we have locally.
335 $raw_refs = ((x($headers,'references')) ? str_replace("\t",'',$headers['references']) : '');
336 $datarray['uri'] = trim($meta->message_id,'<>');
339 $refs_arr = explode(' ', $raw_refs);
340 if(count($refs_arr)) {
341 for($x = 0; $x < count($refs_arr); $x ++)
342 $refs_arr[$x] = "'" . str_replace(array('<','>',' '),array('','',''),dbesc($refs_arr[$x])) . "'";
344 $qstr = implode(',',$refs_arr);
345 $r = q("SELECT `uri` , `parent-uri` FROM `item` WHERE `uri` IN ( $qstr ) AND `uid` = %d LIMIT 1",
346 intval($importer_uid)
349 $datarray['parent-uri'] = $r[0]['uri'];
353 if(! x($datarray,'parent-uri'))
354 $datarray['parent-uri'] = $datarray['uri'];
356 // Have we seen it before?
357 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `uri` = '%s' LIMIT 1",
358 intval($importer_uid),
359 dbesc($datarray['uri'])
363 if($meta->deleted && ! $r[0]['deleted']) {
364 q("UPDATE `item` SET `deleted` = 1, `changed` = '%s' WHERE `id` = %d LIMIT 1",
365 dbesc(datetime_convert()),
371 $datarray['title'] = notags(trim($meta->subject));
372 $datarray['created'] = datetime_convert('UTC','UTC',$meta->date);
374 $r = email_get_msg($mbox,$msg_uid);
377 $datarray['body'] = escape_tags($r['body']);
379 // some mailing lists have the original author as 'from' - add this sender info to msg body.
380 // todo: adding a gravatar for the original author would be cool
382 if(! stristr($meta->from,$contact['addr']))
383 $datarray['body'] = t('From: ') . escape_tags($meta->from) . "\n\n" . $datarray['body'];
385 $datarray['uid'] = $importer_uid;
386 $datarray['contact-id'] = $contact['id'];
387 if($datarray['parent-uri'] === $datarray['uri'])
388 $datarray['private'] = 1;
389 $datarray['author-name'] = $contact['name'];
390 $datarray['author-link'] = 'mailbox';
391 $datarray['author-avatar'] = $contact['photo'];
393 $stored_item = item_store($datarray);
394 q("UPDATE `item` SET `last-child` = 0 WHERE `parent-uri` = '%s' AND `uid` = %d",
395 dbesc($datarray['parent-uri']),
396 intval($importer_uid)
398 q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d LIMIT 1",
407 elseif($contact['network'] === NETWORK_FACEBOOK) {
408 // TODO: work in progress
412 logger('poller: received xml : ' . $xml, LOGGER_DATA);
414 if(! strstr($xml,'<?xml')) {
415 logger('poller: post_handshake: response from ' . $url . ' did not contain XML.');
416 $r = q("UPDATE `contact` SET `last-update` = '%s' WHERE `id` = %d LIMIT 1",
417 dbesc(datetime_convert()),
418 intval($contact['id'])
424 consume_feed($xml,$importer,$contact,$hub,1, true);
426 // do it twice. Ensures that children of parents which may be later in the stream aren't tossed
428 consume_feed($xml,$importer,$contact,$hub,1);
431 if((strlen($hub)) && ($hub_update) && (($contact['rel'] == REL_BUD) || (($contact['network'] === NETWORK_OSTATUS) && (! $contact['readonly'])))) {
432 logger('poller: subscribing to hub(s) : ' . $hub . ' contact name : ' . $contact['name'] . ' local user : ' . $importer['name']);
433 $hubs = explode(',', $hub);
435 foreach($hubs as $h) {
439 subscribe_to_hub($h,$importer,$contact);
445 $updated = datetime_convert();
447 $r = q("UPDATE `contact` SET `last-update` = '%s', `success_update` = '%s' WHERE `id` = %d LIMIT 1",
450 intval($contact['id'])
453 // loop - next contact
461 if (array_search(__file__,get_included_files())===0){
462 poller_run($argv,$argc);