expmail/File.class.php
Klaus-Uwe Mitterer 730ad8c0e1 Move response to own class
Implement warning output
Implement warning when URL and string provided for HTML/plain
Turn allowempty to config key
Add option to prefer URL over string for HTML/plain
Add user agent to curl requests
Update OpenAPI
Bump version to 0.5
2020-09-05 09:12:28 +02:00

87 lines
No EOL
2.9 KiB
PHP

<?php
class File {
public $url;
function __construct($url) {
$this->url = $url;
}
function get_headers($follow=true) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $this->url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, $follow);
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (compatible; KumiSystemsMailer/0.5; +https://expmail.kumi.systems/doc/)");
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_NOBODY, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
$output = curl_exec($ch);
curl_close($ch);
$headers = [];
$output = rtrim($output);
$data = explode("\n", $output);
$headers['status'] = $data[0];
array_shift($data);
foreach($data as $part) {
$middle = explode(":",$part,2);
if ( !isset($middle[1]) ) { $middle[1] = null; }
$headers[trim($middle[0])] = trim($middle[1]);
}
return $headers;
}
function get_status($follow=true, $throw=true) {
if ($status=$this->get_headers($follow)["status"] >= 400) {
throw new Exception("Error downloading " . $this->url . " - Status: " . $status);
}
return $status;
}
function get_filename($follow=true) {
$content = $this->get_headers($follow);
$content = array_change_key_case($content, CASE_LOWER);
if ($content['content-disposition']) {
$tmp_name = explode('=', $content['content-disposition']);
if ($tmp_name[1]) $realfilename = trim($tmp_name[1],'";\'');
};
if (!$realfilename) {
$stripped_url = preg_replace('/\\?.*/', '', $this->url);
$stripped_url = preg_replace('/\\/$/', '', $stripped_url);
$realfilename = basename($stripped_url);
}
return $realfilename;
}
function fetch_file($write=false, $path=null, $follow=true) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $this->url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, $follow);
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (compatible; KumiSystemsMailer/0.5; +https://expmail.kumi.systems/doc/)");
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_NOBODY, false);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
$output = curl_exec($ch);
if(curl_errno($ch)) throw new Exception('Error downloading file. ' . curl_error($ch));
curl_close($ch);
if ($write) {
if (!$path) $path = tempnam(sys_get_temp_dir(), "EXPMAIL_");
if (!file_put_contents($path, $output)) throw new Exception('Error saving file to ' . $path);
}
return ($write ? $path : $output);
}
}