3 require_once("boot.php");
6 function poller_run($argv, $argc){
14 @include(".htconfig.php");
15 require_once("dba.php");
16 $db = new dba($db_host, $db_user, $db_pass, $db_data);
17 unset($db_host, $db_user, $db_pass, $db_data);
21 require_once('include/session.php');
22 require_once('include/datetime.php');
23 require_once('library/simplepie/simplepie.inc');
24 require_once('include/items.php');
25 require_once('include/Contact.php');
26 require_once('include/email.php');
27 require_once('include/socgraph.php');
29 load_config('config');
30 load_config('system');
32 $a->set_baseurl(get_config('system','url'));
36 logger('poller: start');
38 // run queue delivery process in the background
40 proc_run('php',"include/queue.php");
42 // expire any expired accounts
44 q("UPDATE user SET `account_expired` = 1 where `account_expired` = 0
45 AND `account_expires_on` != '0000-00-00 00:00:00'
46 AND `account_expires_on` < UTC_TIMESTAMP() ");
48 $abandon_days = intval(get_config('system','account_abandon_days'));
54 // once daily run birthday_updates and then expire in background
56 $d1 = get_config('system','last_expire_day');
57 $d2 = intval(datetime_convert('UTC','UTC','now','d'));
59 if($d2 != intval($d1)) {
61 update_contact_birthdays();
63 set_config('system','last_expire_day',$d2);
64 proc_run('php','include/expire.php');
76 if(($argc > 1) && ($argv[1] == 'force'))
79 if(($argc > 1) && ($argv[1] == 'restart')) {
81 $generation = intval($argv[2]);
86 if(($argc > 1) && intval($argv[1])) {
87 $manual_id = intval($argv[1]);
91 $sql_extra = (($manual_id) ? " AND `id` = $manual_id " : "");
95 $d = datetime_convert();
98 proc_run('php','include/cronhooks.php');
100 // Only poll from those with suitable relationships,
101 // and which have a polling address and ignore Diaspora since
102 // we are unable to match those posts with a Diaspora GUID and prevent duplicates.
104 $abandon_sql = (($abandon_days)
105 ? sprintf(" AND `user`.`login_date` > UTC_TIMESTAMP() - INTERVAL %d DAY ", intval($abandon_days))
109 $contacts = q("SELECT `contact`.`id` FROM `contact` LEFT JOIN `user` ON `user`.`uid` = `contact`.`uid`
110 WHERE ( `rel` = %d OR `rel` = %d ) AND `poll` != ''
111 AND `network` != '%s'
113 AND `self` = 0 AND `contact`.`blocked` = 0 AND `contact`.`readonly` = 0
114 AND `user`.`account_expired` = 0 $abandon_sql ORDER BY RAND()",
115 intval(CONTACT_IS_SHARING),
116 intval(CONTACT_IS_FRIEND),
117 dbesc(NETWORK_DIASPORA)
120 if(! count($contacts)) {
124 foreach($contacts as $c) {
126 $res = q("SELECT * FROM `contact` WHERE `id` = %d LIMIT 1",
130 if((! $res) || (! count($res)))
133 foreach($res as $contact) {
138 $contact['last-update'] = '0000-00-00 00:00:00';
140 if($contact['priority'] || $contact['subhub']) {
145 $t = $contact['last-update'];
147 // We should be getting everything via a hub. But just to be sure, let's check once a day.
148 // (You can make this more or less frequent if desired by setting 'pushpoll_frequency' appropriately)
149 // This also lets us update our subscription to the hub, and add or replace hubs in case it
150 // changed. We will only update hubs once a day, regardless of 'pushpoll_frequency'.
153 if($contact['subhub']) {
154 $interval = get_config('system','pushpoll_frequency');
155 $contact['priority'] = (($interval !== false) ? intval($interval) : 3);
158 if((datetime_convert('UTC','UTC', 'now') > datetime_convert('UTC','UTC', $t . " + 1 day")) || $force)
165 * Based on $contact['priority'], should we poll this site now? Or later?
168 switch ($contact['priority']) {
170 if(datetime_convert('UTC','UTC', 'now') > datetime_convert('UTC','UTC', $t . " + 1 month"))
174 if(datetime_convert('UTC','UTC', 'now') > datetime_convert('UTC','UTC', $t . " + 1 week"))
178 if(datetime_convert('UTC','UTC', 'now') > datetime_convert('UTC','UTC', $t . " + 1 day"))
182 if(datetime_convert('UTC','UTC', 'now') > datetime_convert('UTC','UTC', $t . " + 12 hour"))
187 if(datetime_convert('UTC','UTC', 'now') > datetime_convert('UTC','UTC', $t . " + 1 hour"))
191 if((! $update) && (! $force))
195 // Check to see if we are running out of memory - if so spawn a new process and kill this one
197 $avail_memory = return_bytes(ini_get('memory_limit'));
198 $memused = memory_get_peak_usage(true);
199 if(intval($avail_memory)) {
200 if(($memused / $avail_memory) > 0.95) {
201 if($generation + 1 > 10) {
202 logger('poller: maximum number of spawns exceeded. Terminating.');
205 logger('poller: memory exceeded. ' . $memused . ' bytes used. Spawning new poll.');
206 proc_run('php', 'include/poller.php', 'restart', (string) $generation + 1);
211 $importer_uid = $contact['uid'];
213 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `self` = 1 LIMIT 1",
214 intval($importer_uid)
221 logger("poller: poll: IMPORTER: {$importer['name']}, CONTACT: {$contact['name']}");
223 $last_update = (($contact['last-update'] === '0000-00-00 00:00:00')
224 ? datetime_convert('UTC','UTC','now - 30 days', ATOM_TIME)
225 : datetime_convert('UTC','UTC',$contact['last-update'], ATOM_TIME)
228 if($contact['network'] === NETWORK_DFRN) {
230 $idtosend = $orig_id = (($contact['dfrn-id']) ? $contact['dfrn-id'] : $contact['issued-id']);
232 if(intval($contact['duplex']) && $contact['dfrn-id'])
233 $idtosend = '0:' . $orig_id;
234 if(intval($contact['duplex']) && $contact['issued-id'])
235 $idtosend = '1:' . $orig_id;
237 // they have permission to write to us. We already filtered this in the contact query.
240 $url = $contact['poll'] . '?dfrn_id=' . $idtosend
241 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
242 . '&type=data&last_update=' . $last_update
245 $handshake_xml = fetch_url($url);
247 logger('poller: handshake with url ' . $url . ' returns xml: ' . $handshake_xml, LOGGER_DATA);
250 if(! $handshake_xml) {
251 logger("poller: $url appears to be dead - marking for death ");
252 // dead connection - might be a transient event, or this might
253 // mean the software was uninstalled or the domain expired.
254 // Will keep trying for one month.
255 mark_for_death($contact);
257 // set the last-update so we don't keep polling
259 $r = q("UPDATE `contact` SET `last-update` = '%s' WHERE `id` = %d LIMIT 1",
260 dbesc(datetime_convert()),
261 intval($contact['id'])
267 if(! strstr($handshake_xml,'<?xml')) {
268 logger('poller: response from ' . $url . ' did not contain XML.');
269 $r = q("UPDATE `contact` SET `last-update` = '%s' WHERE `id` = %d LIMIT 1",
270 dbesc(datetime_convert()),
271 intval($contact['id'])
277 $res = parse_xml_string($handshake_xml);
279 if(intval($res->status) == 1) {
280 logger("poller: $url replied status 1 - marking for death ");
282 // we may not be friends anymore. Will keep trying for one month.
283 // set the last-update so we don't keep polling
285 $r = q("UPDATE `contact` SET `last-update` = '%s' WHERE `id` = %d LIMIT 1",
286 dbesc(datetime_convert()),
287 intval($contact['id'])
290 mark_for_death($contact);
293 if($contact['term-date'] != '0000-00-00 00:00:00') {
294 logger("poller: $url back from the dead - removing mark for death");
295 unmark_for_death($contact);
299 if((intval($res->status) != 0) || (! strlen($res->challenge)) || (! strlen($res->dfrn_id)))
302 if(((float) $res->dfrn_version > 2.21) && ($contact['poco'] == '')) {
303 q("update contact set poco = '%s' where id = %d limit 1",
304 dbesc(str_replace('/profile/','/poco/', $contact['url'])),
305 intval($contact['id'])
311 $sent_dfrn_id = hex2bin((string) $res->dfrn_id);
312 $challenge = hex2bin((string) $res->challenge);
316 if(($contact['duplex']) && strlen($contact['prvkey'])) {
317 openssl_private_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['prvkey']);
318 openssl_private_decrypt($challenge,$postvars['challenge'],$contact['prvkey']);
321 openssl_public_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['pubkey']);
322 openssl_public_decrypt($challenge,$postvars['challenge'],$contact['pubkey']);
325 $final_dfrn_id = substr($final_dfrn_id, 0, strpos($final_dfrn_id, '.'));
327 if(strpos($final_dfrn_id,':') == 1)
328 $final_dfrn_id = substr($final_dfrn_id,2);
330 if($final_dfrn_id != $orig_id) {
331 logger('poller: ID did not decode: ' . $contact['id'] . ' orig: ' . $orig_id . ' final: ' . $final_dfrn_id);
332 // did not decode properly - cannot trust this site
336 $postvars['dfrn_id'] = $idtosend;
337 $postvars['dfrn_version'] = DFRN_PROTOCOL_VERSION;
338 $postvars['perm'] = 'rw';
340 $xml = post_url($contact['poll'],$postvars);
342 elseif(($contact['network'] === NETWORK_OSTATUS)
343 || ($contact['network'] === NETWORK_DIASPORA)
344 || ($contact['network'] === NETWORK_FEED) ) {
346 // Upgrading DB fields from an older Friendika version
347 // Will only do this once per notify-enabled OStatus contact
348 // or if relationship changes
350 $stat_writeable = ((($contact['notify']) && ($contact['rel'] == CONTACT_IS_FOLLOWER || $contact['rel'] == CONTACT_IS_FRIEND)) ? 1 : 0);
352 if($stat_writeable != $contact['writable']) {
353 q("UPDATE `contact` SET `writable` = %d WHERE `id` = %d LIMIT 1",
354 intval($stat_writeable),
355 intval($contact['id'])
359 // Are we allowed to import from this person?
361 if($contact['rel'] == CONTACT_IS_FOLLOWER || $contact['blocked'] || $contact['readonly'])
364 $xml = fetch_url($contact['poll']);
366 elseif($contact['network'] === NETWORK_MAIL) {
368 $mail_disabled = ((function_exists('imap_open') && (! get_config('system','imap_disabled'))) ? 0 : 1);
373 $x = q("SELECT `prvkey` FROM `user` WHERE `uid` = %d LIMIT 1",
374 intval($importer_uid)
376 $mailconf = q("SELECT * FROM `mailacct` WHERE `server` != '' AND `uid` = %d LIMIT 1",
377 intval($importer_uid)
379 if(count($x) && count($mailconf)) {
380 $mailbox = construct_mailbox_name($mailconf[0]);
382 openssl_private_decrypt(hex2bin($mailconf[0]['pass']),$password,$x[0]['prvkey']);
383 $mbox = email_connect($mailbox,$mailconf[0]['user'],$password);
386 q("UPDATE `mailacct` SET `last_check` = '%s' WHERE `id` = %d AND `uid` = %d LIMIT 1",
387 dbesc(datetime_convert()),
388 intval($mailconf[0]['id']),
389 intval($importer_uid)
395 $msgs = email_poll($mbox,$contact['addr']);
398 foreach($msgs as $msg_uid) {
400 $meta = email_msg_meta($mbox,$msg_uid);
401 $headers = email_msg_headers($mbox,$msg_uid);
403 // look for a 'references' header and try and match with a parent item we have locally.
405 $raw_refs = ((x($headers,'references')) ? str_replace("\t",'',$headers['references']) : '');
406 $datarray['uri'] = trim($meta->message_id,'<>');
409 $refs_arr = explode(' ', $raw_refs);
410 if(count($refs_arr)) {
411 for($x = 0; $x < count($refs_arr); $x ++)
412 $refs_arr[$x] = "'" . str_replace(array('<','>',' '),array('','',''),dbesc($refs_arr[$x])) . "'";
414 $qstr = implode(',',$refs_arr);
415 $r = q("SELECT `uri` , `parent-uri` FROM `item` WHERE `uri` IN ( $qstr ) AND `uid` = %d LIMIT 1",
416 intval($importer_uid)
419 $datarray['parent-uri'] = $r[0]['uri'];
423 if(! x($datarray,'parent-uri'))
424 $datarray['parent-uri'] = $datarray['uri'];
426 // Have we seen it before?
427 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `uri` = '%s' LIMIT 1",
428 intval($importer_uid),
429 dbesc($datarray['uri'])
433 if($meta->deleted && ! $r[0]['deleted']) {
434 q("UPDATE `item` SET `deleted` = 1, `changed` = '%s' WHERE `id` = %d LIMIT 1",
435 dbesc(datetime_convert()),
441 $datarray['title'] = notags(trim($meta->subject));
442 $datarray['created'] = datetime_convert('UTC','UTC',$meta->date);
444 $r = email_get_msg($mbox,$msg_uid);
447 $datarray['body'] = escape_tags($r['body']);
449 // some mailing lists have the original author as 'from' - add this sender info to msg body.
450 // todo: adding a gravatar for the original author would be cool
452 if(! stristr($meta->from,$contact['addr']))
453 $datarray['body'] = t('From: ') . escape_tags($meta->from) . "\n\n" . $datarray['body'];
455 $datarray['uid'] = $importer_uid;
456 $datarray['contact-id'] = $contact['id'];
457 if($datarray['parent-uri'] === $datarray['uri'])
458 $datarray['private'] = 1;
459 if(! get_pconfig($importer_uid,'system','allow_public_email_replies')) {
460 $datarray['private'] = 1;
461 $datarray['allow_cid'] = '<' . $contact['id'] . '>';
463 $datarray['author-name'] = $contact['name'];
464 $datarray['author-link'] = 'mailbox';
465 $datarray['author-avatar'] = $contact['photo'];
467 $stored_item = item_store($datarray);
468 q("UPDATE `item` SET `last-child` = 0 WHERE `parent-uri` = '%s' AND `uid` = %d",
469 dbesc($datarray['parent-uri']),
470 intval($importer_uid)
472 q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d LIMIT 1",
481 elseif($contact['network'] === NETWORK_FACEBOOK) {
482 // This is picked up by the Facebook plugin on a cron hook.
487 logger('poller: received xml : ' . $xml, LOGGER_DATA);
489 if(! strstr($xml,'<?xml')) {
490 logger('poller: post_handshake: response from ' . $url . ' did not contain XML.');
491 $r = q("UPDATE `contact` SET `last-update` = '%s' WHERE `id` = %d LIMIT 1",
492 dbesc(datetime_convert()),
493 intval($contact['id'])
499 consume_feed($xml,$importer,$contact,$hub,1,1);
501 // do it twice. Ensures that children of parents which may be later in the stream aren't tossed
503 consume_feed($xml,$importer,$contact,$hub,1,2);
505 $hubmode = 'subscribe';
506 if($contact['network'] === NETWORK_DFRN || $contact['blocked'] || $contact['readonly'])
507 $hubmode = 'unsubscribe';
509 if((strlen($hub)) && ($hub_update) && ($contact['rel'] != CONTACT_IS_FOLLOWER)) {
510 logger('poller: hub ' . $hubmode . ' : ' . $hub . ' contact name : ' . $contact['name'] . ' local user : ' . $importer['name']);
511 $hubs = explode(',', $hub);
513 foreach($hubs as $h) {
517 subscribe_to_hub($h,$importer,$contact,$hubmode);
524 $updated = datetime_convert();
526 $r = q("UPDATE `contact` SET `last-update` = '%s', `success_update` = '%s' WHERE `id` = %d LIMIT 1",
529 intval($contact['id'])
533 // load current friends if possible.
535 if($contact['poco']) {
536 $r = q("SELECT count(*) as total from glink
537 where `cid` = %d and updated > UTC_TIMESTAMP() - INTERVAL 1 DAY",
538 intval($contact['id'])
543 poco_load($contact['id'],$importer_uid,$contact['poco']);
546 // loop - next contact
554 if (array_search(__file__,get_included_files())===0){
555 poller_run($argv,$argc);