streams/Zotlabs/Lib/Img_cache.php

76 lines
1.5 KiB
PHP
Raw Normal View History

2020-03-05 02:55:25 +00:00
<?php
namespace Zotlabs\Lib;
2020-08-18 06:35:05 +00:00
use Zotlabs\Lib\Hashpath;
use Zotlabs\Daemon\Run;
2020-03-05 02:55:25 +00:00
class Img_cache {
static $cache_life = 18600 * 7;
2020-08-18 06:35:05 +00:00
static function get_filename($url, $prefix = '.') {
2020-08-18 06:38:57 +00:00
return Hashpath::path($url,$prefix);
2020-03-05 02:55:25 +00:00
}
2020-08-18 06:35:05 +00:00
static function check($url, $prefix = '.') {
2020-03-05 02:55:25 +00:00
if (strpos($url,z_root()) !== false) {
return false;
}
2020-08-17 04:55:59 +00:00
2020-03-05 02:55:25 +00:00
$path = self::get_filename($url,$prefix);
if (file_exists($path)) {
$t = filemtime($path);
2020-03-05 02:55:25 +00:00
if ($t && time() - $t >= self::$cache_life) {
Run::Summon( [ 'Cache_image', $url, $path ] );
return false;
}
else {
return ((filesize($path)) ? true : false);
2020-03-05 02:55:25 +00:00
}
}
Run::Summon( [ 'Cache_image', $url, $path ] );
return false;
2020-03-05 02:55:25 +00:00
}
static function url_to_cache($url,$file) {
2020-03-05 04:51:20 +00:00
$fp = fopen($file,'wb');
2020-03-05 02:55:25 +00:00
if (! $fp) {
logger('failed to open storage file: ' . $file,LOGGER_NORMAL,LOG_ERR);
2020-03-05 02:55:25 +00:00
return false;
}
$redirects = 0;
$x = z_fetch_url($url,true,$redirects,[ 'filep' => $fp, 'novalidate' => true ]);
fclose($fp);
2020-08-27 10:18:54 +00:00
2020-08-26 06:10:25 +00:00
if ($x['success'] && file_exists($file)) {
$i = @getimagesize($file);
if ($i && $i[2]) { // looking for non-zero imagetype
Run::Summon( [ 'CacheThumb' , basename($file) ] );
return true;
}
2020-03-05 02:55:25 +00:00
}
// We could not cache the image for some reason. Leave an empty file here
// to provide a record of the attempt. We'll use this as a flag to avoid
// doing it again repeatedly.
file_put_contents($file, EMPTY_STR);
logger('cache failed ' . $file);
2020-03-05 02:55:25 +00:00
return false;
}
}