expmail/File.class.php
Kumi 2eed78b83e Complete refactor: Moving stuff to classes, making sender tiny
Adding two config options to modify behavior
Allow messages with empty body to be sent
Automatically convert HTML to plain if none provided
Version bump to 0.4
2020-09-04 22:01:34 +02:00

85 lines
2.6 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_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_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);
}
}