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');
28 load_config('config');
29 load_config('system');
31 $a->set_baseurl(get_config('system','url'));
35 logger('poller: start');
37 // run queue delivery process in the background
39 proc_run('php',"include/queue.php");
41 // expire any expired accounts
43 q("UPDATE user SET `account_expired` = 1 where `account_expired` = 0
44 AND `account_expires_on` != '0000-00-00 00:00:00'
45 AND `account_expires_on` < UTC_TIMESTAMP() ");
47 $abandon_days = intval(get_config('system','account_abandon_days'));
53 // once daily run birthday_updates and then expire in background
55 $d1 = get_config('system','last_expire_day');
56 $d2 = intval(datetime_convert('UTC','UTC','now','d'));
58 if($d2 != intval($d1)) {
60 update_contact_birthdays();
62 set_config('system','last_expire_day',$d2);
63 proc_run('php','include/expire.php');
75 if(($argc > 1) && ($argv[1] == 'force'))
78 if(($argc > 1) && ($argv[1] == 'restart')) {
80 $generation = intval($argv[2]);
85 if(($argc > 1) && intval($argv[1])) {
86 $manual_id = intval($argv[1]);
90 $sql_extra = (($manual_id) ? " AND `id` = $manual_id " : "");
94 $d = datetime_convert();
97 proc_run('php','include/cronhooks.php');
99 // Only poll from those with suitable relationships,
100 // and which have a polling address and ignore Diaspora since
101 // we are unable to match those posts with a Diaspora GUID and prevent duplicates.
103 $abandon_sql = (($abandon_days)
104 ? sprintf(" AND `user`.`login_date` > UTC_TIMESTAMP() - INTERVAL %d DAY ", intval($abandon_days))
108 $contacts = q("SELECT `contact`.`id` FROM `contact` LEFT JOIN `user` ON `user`.`uid` = `contact`.`uid`
109 WHERE ( `rel` = %d OR `rel` = %d ) AND `poll` != ''
110 AND `network` != '%s'
112 AND `self` = 0 AND `contact`.`blocked` = 0 AND `contact`.`readonly` = 0
113 AND `user`.`account_expired` = 0 $abandon_sql ORDER BY RAND()",
114 intval(CONTACT_IS_SHARING),
115 intval(CONTACT_IS_FRIEND),
116 dbesc(NETWORK_DIASPORA)
119 if(! count($contacts)) {
123 foreach($contacts as $c) {
125 $res = q("SELECT * FROM `contact` WHERE `id` = %d LIMIT 1",
129 if((! $res) || (! count($res)))
132 foreach($res as $contact) {
137 $contact['last-update'] = '0000-00-00 00:00:00';
139 if($contact['priority'] || $contact['subhub']) {
144 $t = $contact['last-update'];
146 // We should be getting everything via a hub. But just to be sure, let's check once a day.
147 // (You can make this more or less frequent if desired by setting 'pushpoll_frequency' appropriately)
148 // This also lets us update our subscription to the hub, and add or replace hubs in case it
149 // changed. We will only update hubs once a day, regardless of 'pushpoll_frequency'.
152 if($contact['subhub']) {
153 $interval = get_config('system','pushpoll_frequency');
154 $contact['priority'] = (($interval !== false) ? intval($interval) : 3);
157 if((datetime_convert('UTC','UTC', 'now') > datetime_convert('UTC','UTC', $t . " + 1 day")) || $force)
164 * Based on $contact['priority'], should we poll this site now? Or later?
167 switch ($contact['priority']) {
169 if(datetime_convert('UTC','UTC', 'now') > datetime_convert('UTC','UTC', $t . " + 1 month"))
173 if(datetime_convert('UTC','UTC', 'now') > datetime_convert('UTC','UTC', $t . " + 1 week"))
177 if(datetime_convert('UTC','UTC', 'now') > datetime_convert('UTC','UTC', $t . " + 1 day"))
181 if(datetime_convert('UTC','UTC', 'now') > datetime_convert('UTC','UTC', $t . " + 12 hour"))
186 if(datetime_convert('UTC','UTC', 'now') > datetime_convert('UTC','UTC', $t . " + 1 hour"))
190 if((! $update) && (! $force))
194 // Check to see if we are running out of memory - if so spawn a new process and kill this one
196 $avail_memory = return_bytes(ini_get('memory_limit'));
197 $memused = memory_get_peak_usage(true);
198 if(intval($avail_memory)) {
199 if(($memused / $avail_memory) > 0.95) {
200 if($generation + 1 > 10) {
201 logger('poller: maximum number of spawns exceeded. Terminating.');
204 logger('poller: memory exceeded. ' . $memused . ' bytes used. Spawning new poll.');
205 proc_run('php', 'include/poller.php', 'restart', (string) $generation + 1);
210 $importer_uid = $contact['uid'];
212 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `self` = 1 LIMIT 1",
213 intval($importer_uid)
220 logger("poller: poll: IMPORTER: {$importer['name']}, CONTACT: {$contact['name']}");
222 $last_update = (($contact['last-update'] === '0000-00-00 00:00:00')
223 ? datetime_convert('UTC','UTC','now - 30 days', ATOM_TIME)
224 : datetime_convert('UTC','UTC',$contact['last-update'], ATOM_TIME)
227 if($contact['network'] === NETWORK_DFRN) {
229 $idtosend = $orig_id = (($contact['dfrn-id']) ? $contact['dfrn-id'] : $contact['issued-id']);
231 if(intval($contact['duplex']) && $contact['dfrn-id'])
232 $idtosend = '0:' . $orig_id;
233 if(intval($contact['duplex']) && $contact['issued-id'])
234 $idtosend = '1:' . $orig_id;
236 // they have permission to write to us. We already filtered this in the contact query.
239 $url = $contact['poll'] . '?dfrn_id=' . $idtosend
240 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
241 . '&type=data&last_update=' . $last_update
244 $handshake_xml = fetch_url($url);
246 logger('poller: handshake with url ' . $url . ' returns xml: ' . $handshake_xml, LOGGER_DATA);
249 if(! $handshake_xml) {
250 logger("poller: $url appears to be dead - marking for death ");
251 // dead connection - might be a transient event, or this might
252 // mean the software was uninstalled or the domain expired.
253 // Will keep trying for one month.
254 mark_for_death($contact);
256 // set the last-update so we don't keep polling
258 $r = q("UPDATE `contact` SET `last-update` = '%s' WHERE `id` = %d LIMIT 1",
259 dbesc(datetime_convert()),
260 intval($contact['id'])
266 if(! strstr($handshake_xml,'<?xml')) {
267 logger('poller: response from ' . $url . ' did not contain XML.');
268 $r = q("UPDATE `contact` SET `last-update` = '%s' WHERE `id` = %d LIMIT 1",
269 dbesc(datetime_convert()),
270 intval($contact['id'])
276 $res = parse_xml_string($handshake_xml);
278 if(intval($res->status) == 1) {
279 logger("poller: $url replied status 1 - marking for death ");
281 // we may not be friends anymore. Will keep trying for one month.
282 // set the last-update so we don't keep polling
284 $r = q("UPDATE `contact` SET `last-update` = '%s' WHERE `id` = %d LIMIT 1",
285 dbesc(datetime_convert()),
286 intval($contact['id'])
289 mark_for_death($contact);
292 if($contact['term-date'] != '0000-00-00 00:00:00') {
293 logger("poller: $url back from the dead - removing mark for death");
294 unmark_for_death($contact);
298 if((intval($res->status) != 0) || (! strlen($res->challenge)) || (! strlen($res->dfrn_id)))
303 $sent_dfrn_id = hex2bin((string) $res->dfrn_id);
304 $challenge = hex2bin((string) $res->challenge);
308 if(($contact['duplex']) && strlen($contact['prvkey'])) {
309 openssl_private_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['prvkey']);
310 openssl_private_decrypt($challenge,$postvars['challenge'],$contact['prvkey']);
313 openssl_public_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['pubkey']);
314 openssl_public_decrypt($challenge,$postvars['challenge'],$contact['pubkey']);
317 $final_dfrn_id = substr($final_dfrn_id, 0, strpos($final_dfrn_id, '.'));
319 if(strpos($final_dfrn_id,':') == 1)
320 $final_dfrn_id = substr($final_dfrn_id,2);
322 if($final_dfrn_id != $orig_id) {
323 logger('poller: ID did not decode: ' . $contact['id'] . ' orig: ' . $orig_id . ' final: ' . $final_dfrn_id);
324 // did not decode properly - cannot trust this site
328 $postvars['dfrn_id'] = $idtosend;
329 $postvars['dfrn_version'] = DFRN_PROTOCOL_VERSION;
330 $postvars['perm'] = 'rw';
332 $xml = post_url($contact['poll'],$postvars);
334 elseif(($contact['network'] === NETWORK_OSTATUS)
335 || ($contact['network'] === NETWORK_DIASPORA)
336 || ($contact['network'] === NETWORK_FEED) ) {
338 // Upgrading DB fields from an older Friendika version
339 // Will only do this once per notify-enabled OStatus contact
340 // or if relationship changes
342 $stat_writeable = ((($contact['notify']) && ($contact['rel'] == CONTACT_IS_FOLLOWER || $contact['rel'] == CONTACT_IS_FRIEND)) ? 1 : 0);
344 if($stat_writeable != $contact['writable']) {
345 q("UPDATE `contact` SET `writable` = %d WHERE `id` = %d LIMIT 1",
346 intval($stat_writeable),
347 intval($contact['id'])
351 // Are we allowed to import from this person?
353 if($contact['rel'] == CONTACT_IS_FOLLOWER || $contact['blocked'] || $contact['readonly'])
356 $xml = fetch_url($contact['poll']);
358 elseif($contact['network'] === NETWORK_MAIL) {
360 $mail_disabled = ((function_exists('imap_open') && (! get_config('system','imap_disabled'))) ? 0 : 1);
365 $x = q("SELECT `prvkey` FROM `user` WHERE `uid` = %d LIMIT 1",
366 intval($importer_uid)
368 $mailconf = q("SELECT * FROM `mailacct` WHERE `server` != '' AND `uid` = %d LIMIT 1",
369 intval($importer_uid)
371 if(count($x) && count($mailconf)) {
372 $mailbox = construct_mailbox_name($mailconf[0]);
374 openssl_private_decrypt(hex2bin($mailconf[0]['pass']),$password,$x[0]['prvkey']);
375 $mbox = email_connect($mailbox,$mailconf[0]['user'],$password);
378 q("UPDATE `mailacct` SET `last_check` = '%s' WHERE `id` = %d AND `uid` = %d LIMIT 1",
379 dbesc(datetime_convert()),
380 intval($mailconf[0]['id']),
381 intval($importer_uid)
387 $msgs = email_poll($mbox,$contact['addr']);
390 foreach($msgs as $msg_uid) {
392 $meta = email_msg_meta($mbox,$msg_uid);
393 $headers = email_msg_headers($mbox,$msg_uid);
395 // look for a 'references' header and try and match with a parent item we have locally.
397 $raw_refs = ((x($headers,'references')) ? str_replace("\t",'',$headers['references']) : '');
398 $datarray['uri'] = trim($meta->message_id,'<>');
401 $refs_arr = explode(' ', $raw_refs);
402 if(count($refs_arr)) {
403 for($x = 0; $x < count($refs_arr); $x ++)
404 $refs_arr[$x] = "'" . str_replace(array('<','>',' '),array('','',''),dbesc($refs_arr[$x])) . "'";
406 $qstr = implode(',',$refs_arr);
407 $r = q("SELECT `uri` , `parent-uri` FROM `item` WHERE `uri` IN ( $qstr ) AND `uid` = %d LIMIT 1",
408 intval($importer_uid)
411 $datarray['parent-uri'] = $r[0]['uri'];
415 if(! x($datarray,'parent-uri'))
416 $datarray['parent-uri'] = $datarray['uri'];
418 // Have we seen it before?
419 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `uri` = '%s' LIMIT 1",
420 intval($importer_uid),
421 dbesc($datarray['uri'])
425 if($meta->deleted && ! $r[0]['deleted']) {
426 q("UPDATE `item` SET `deleted` = 1, `changed` = '%s' WHERE `id` = %d LIMIT 1",
427 dbesc(datetime_convert()),
433 $datarray['title'] = notags(trim($meta->subject));
434 $datarray['created'] = datetime_convert('UTC','UTC',$meta->date);
436 $r = email_get_msg($mbox,$msg_uid);
439 $datarray['body'] = escape_tags($r['body']);
441 // some mailing lists have the original author as 'from' - add this sender info to msg body.
442 // todo: adding a gravatar for the original author would be cool
444 if(! stristr($meta->from,$contact['addr']))
445 $datarray['body'] = t('From: ') . escape_tags($meta->from) . "\n\n" . $datarray['body'];
447 $datarray['uid'] = $importer_uid;
448 $datarray['contact-id'] = $contact['id'];
449 if($datarray['parent-uri'] === $datarray['uri'])
450 $datarray['private'] = 1;
451 if(! get_pconfig($importer_uid,'system','allow_public_email_replies')) {
452 $datarray['private'] = 1;
453 $datarray['allow_cid'] = '<' . $contact['id'] . '>';
455 $datarray['author-name'] = $contact['name'];
456 $datarray['author-link'] = 'mailbox';
457 $datarray['author-avatar'] = $contact['photo'];
459 $stored_item = item_store($datarray);
460 q("UPDATE `item` SET `last-child` = 0 WHERE `parent-uri` = '%s' AND `uid` = %d",
461 dbesc($datarray['parent-uri']),
462 intval($importer_uid)
464 q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d LIMIT 1",
473 elseif($contact['network'] === NETWORK_FACEBOOK) {
474 // This is picked up by the Facebook plugin on a cron hook.
479 logger('poller: received xml : ' . $xml, LOGGER_DATA);
481 if(! strstr($xml,'<?xml')) {
482 logger('poller: post_handshake: response from ' . $url . ' did not contain XML.');
483 $r = q("UPDATE `contact` SET `last-update` = '%s' WHERE `id` = %d LIMIT 1",
484 dbesc(datetime_convert()),
485 intval($contact['id'])
491 consume_feed($xml,$importer,$contact,$hub,1,1);
493 // do it twice. Ensures that children of parents which may be later in the stream aren't tossed
495 consume_feed($xml,$importer,$contact,$hub,1,2);
497 $hubmode = 'subscribe';
498 if($contact['network'] === NETWORK_DFRN || $contact['blocked'] || $contact['readonly'])
499 $hubmode = 'unsubscribe';
501 if((strlen($hub)) && ($hub_update) && ($contact['rel'] != CONTACT_IS_FOLLOWER)) {
502 logger('poller: hub ' . $hubmode . ' : ' . $hub . ' contact name : ' . $contact['name'] . ' local user : ' . $importer['name']);
503 $hubs = explode(',', $hub);
505 foreach($hubs as $h) {
509 subscribe_to_hub($h,$importer,$contact,$hubmode);
516 $updated = datetime_convert();
518 $r = q("UPDATE `contact` SET `last-update` = '%s', `success_update` = '%s' WHERE `id` = %d LIMIT 1",
521 intval($contact['id'])
524 // loop - next contact
532 if (array_search(__file__,get_included_files())===0){
533 poller_run($argv,$argc);