get_cdf.php 1.99 KB
<?php

/**
* Look for a NetCDF file in the local base dir, then convert it using the NetCDF to CDF Python converter.
*/

$converterPath = './nc2cdf.py';
$tmpDir = '/tmp/';
$log_path = $tmpDir . 'get_cdf.log';

if (!$_GET['id']) {
	exit('INPUT ERROR');
}

require_once './DDserverWeb_ini.php';

$name = preg_replace('/\..*/', '', $_GET['id']); // ie. ACE/SW/sw19980204
$inputFilePath = baseDir . $name . '.nc.gz'; // ie. /data/DDBASE/DATA/ACE/SW/sw19980204.nc.gz
$outputFilePath = $tmpDir . str_replace('/', '_', $name) . '.cdf'; // ie. /tmp/ACE_SW_sw19980204.cdf

function send_file($mime_type, $send_file_path) {
	header('Content-Description: File Transfer');
	header('Content-Type: ' . $mime_type);
	header('Content-Disposition: attachment; filename="' . basename($send_file_path) . '"');
	header('Expires: 0');
	header('Cache-Control: must-revalidate');
	header('Pragma: public');
	header('Content-Length: ' . filesize($send_file_path));
	readfile($send_file_path);
}

function error($log_msg) {
	global $inputFilePath, $log_path;
	file_put_contents($log_path, date("Y-m-d H:i:s") . " with id='" . $_GET['id'] . "': $log_msg\n", FILE_APPEND);
	// If the file can not be converted, return the NetCDF file.
	send_file('application/x-gzip', basename($inputFilePath));
	exit;
}

if (!file_exists($inputFilePath)) {
	exit('NO SUCH FILE');
}

if (!is_dir(pathinfo($outputFilePath, PATHINFO_DIRNAME))) {
	error("Can not create $outputFilePath because the folder does not exist.");
}

try {
	$res = shell_exec("$converterPath $inputFilePath $outputFilePath");
} catch (Exception $e) {
	error("Error on shell_exec():\n$e");
}


// The converter is not supposed to output something if the file has been successfully converted
if(trim($res) != '') {
	error("The converter said:\n$res");
}

if(! file_exists($outputFilePath)) {
	error("The output file $outputFilePath has not been created.");
}

send_file('application/x-cdf', $outputFilePath);

sleep(600); // Wait 10 minutes before to delete the converted file.
unlink($outputFilePath);

exit;
?>