#! /usr/bin/php -q
<?php

// Code refactored / debugged by KB4FXC, 11/06/2018.
// Fixed issue where error conditions were always generated by private nodes.

// Updated to check for strictly private nodes
// and change load order - private first
// WA3DSP 2/2016
// $Id $

// Original code by WD6AWP
// Modified to run immediately when called directly
// and load randomly within  30 minute window when 
// called by cron

// Refactor to use CURL --- KB4FXC 11/19/2018

$retries = 0;
$maxRetries = 3;
$Pcontents = '';
$privatefile = "/etc/asterisk/local/privatenodes.txt";

// Load private nodes if any
// Private nodes are less than 2000 and loaded first
// to ensure proper order of file

if (file_exists($privatefile)) {
    $Pcontents .= file_get_contents($privatefile);
}

$contents = '';
$contents2 = '';

// Check if ONLY private nodes
// In that case do not read Allstar database
// Maintains compatibility with pre 1.3 versions
// assumes public in environment variable

$private = getenv('PRIVATE_NODE');
if (is_null($private) || !$private) {	// If not a private node...

	// If called by cron wait between 0 and 30 min

	if (isset($argv[1])) {
    		if ($argv[1] == 'cron') {
                        $seconds = mt_rand(0, 1800);
                        print "Waiting for $seconds seconds...\n";
                        while ($seconds > 0) {
                                if ($seconds > 60) {
                                        print "sleeping for $seconds seconds...\n";
                                        sleep(60);
                                        $seconds = $seconds - 60;
                                }
                                else {
                                        print "sleeping for $seconds seconds...\n";
                                        sleep($seconds);
                                        $seconds = 0;
                                }
                        }
    		}
	}

// Open AllStar db URL and retrieve file.

	$url = "https://frostygmrs.com/astdb.txt";
	$url2 = "https://frostygmrs.com/astdb.txt";
	$retries = 0;
	while (true) {

		$ch = curl_init();				// Initiate CURL 
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);	// Return all data retrieved as a string
		curl_setopt($ch, CURLOPT_ENCODING, 'gzip'); 	// Use gzip compression if supported by host
		curl_setopt($ch, CURLOPT_TIMEOUT, 20);	 	// Give up after 20 seconds
		curl_setopt($ch, CURLOPT_URL, $url);		// Set the url 
		$contents2=curl_exec($ch);			// Execute
		curl_close($ch);				// Close CURL

		$size = strlen($contents2);
		if ($size < 0) {

			if ($retries >= 2)
    				$url = $url2;

			if ($retries >= 5)
    				die ("astdb.txt: Retries exceeded!!  $size bytes - Invalid: file too small, bailing out.\n");

			$retries++;
			sleep (5);
			continue;
		}
       		break;
	}

} // End private node check

$contents = $Pcontents;
$contents .= $contents2;

// Added to strip non printing characters.
$contents = preg_replace('/[\x00-\x09\x0B-\x0C\x0E-\x1F\x7F-\xFF]/', '', $contents);

// Save the data
$db = "/var/log/asterisk/astdb.txt";
if (! ($fh = fopen($db, 'w'))) {
    die("Cannot open $db.");
}
if (!flock($fh, LOCK_EX))  {
    echo 'Unable to obtain lock.';
    exit(-1); 
}
if (fwrite($fh, $contents) === FALSE) {
    die ("Cannot write $db.");
}
fclose($fh);

$size = strlen($contents);
print "astdb.txt: $size bytes";

?>

