public function download($url, $mixed_filename)
{
if (is_callable($mixed_filename)) {
$this->downloadCompleteFunction = $mixed_filename;
$fh = tmpfile();
} else {
$filename = $mixed_filename;
// Use a temporary file when downloading. Not using a temporary file can cause an error when an existing
// file has already fully completed downloading and a new download is started with the same destination save
// path. The download request will include header "Range: bytes=$filesize-" which is syntactically valid,
// but unsatisfiable.
$download_filename = $filename . '.pccdownload';
$mode = 'wb';
// Attempt to resume download only when a temporary download file exists and is not empty.
if (file_exists($download_filename) && ($filesize = filesize($download_filename))) {
$mode = 'ab';
$first_byte_position = $filesize;
$range = $first_byte_position . '-';
$this->setOpt(CURLOPT_RANGE, $range);
}
$fh = fopen($download_filename, $mode);
// Move the downloaded temporary file to the destination save path.
$this->downloadCompleteFunction = function ($fh) use($download_filename, $filename) {
rename($download_filename, $filename);
};
}
$this->setOpt(CURLOPT_FILE, $fh);
$this->get($url);
$this->downloadComplete($fh);
return !$this->error;
}
/** * Create user cache. * * @param string $user Twitter screen name * @return bool If successful true * @throws CacheException Any errors */ public function create($user) { try { $path = config("cache.path") . "/{$user}"; $json_file = "{$path}/data.json"; if (!$this->exists($user)) { mkdir($path); } if (!file_exists($json_file)) { touch($json_file); } $response = $this->twistOAuth->get("users/show", ["id" => $user]); $image_url = str_replace("_normal", "", $response->profile_image_url_https); $info = new SplFileInfo($image_url); $curl = new Curl(); $curl->setUserAgent(SaveTweet::APP_NAME . "/" . SaveTweet::APP_VERSION . " with PHP/" . PHP_VERSION); $curl->download($image_url, "{$path}/icon.{$info->getExtension()}"); $curl->close(); $data = ["name" => $response->name, "screen_name" => $response->screen_name, "id" => $response->id_str, "icon" => config("cache.http_path") . "/{$response->id_str}/icon.{$info->getExtension()}", "org_icon" => $image_url, "update_at" => time()]; $json = json_encode($data, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE); (new SplFileObject($json_file, "w"))->fwrite($json); return true; } catch (RuntimeException $e) { $this->_catch($e); } }