formatting pass

This commit is contained in:
Shish 2019-06-14 13:47:50 +01:00
parent d1102cd635
commit 064b24ffc1
18 changed files with 265 additions and 255 deletions

View file

@ -221,17 +221,17 @@ abstract class DataHandlerExtension extends Extension
{ {
$result = false; $result = false;
if ($this->supported_ext($event->type)) { if ($this->supported_ext($event->type)) {
if($event->force) { if ($event->force) {
$result = $this->create_thumb($event->hash); $result = $this->create_thumb($event->hash);
} else { } else {
$outname = warehouse_path("thumbs", $event->hash); $outname = warehouse_path("thumbs", $event->hash);
if(file_exists($outname)) { if (file_exists($outname)) {
return; return;
} }
$result = $this->create_thumb($event->hash); $result = $this->create_thumb($event->hash);
} }
} }
if($result) { if ($result) {
$event->generated = true; $event->generated = true;
} }
} }

View file

@ -70,9 +70,9 @@ function get_extension_from_mime(String $file_path): ?String
{ {
global $config; global $config;
$mime = mime_content_type($file_path); $mime = mime_content_type($file_path);
if(!empty($mime)) { if (!empty($mime)) {
$ext = get_extension($mime); $ext = get_extension($mime);
if(!empty($ext)) { if (!empty($ext)) {
return $ext; return $ext;
} }
throw new UploadException("Could not determine extension for mimetype ".$mime); throw new UploadException("Could not determine extension for mimetype ".$mime);
@ -178,8 +178,7 @@ function create_thumbnail_convert($hash): bool
$q = $config->get_int("thumb_quality"); $q = $config->get_int("thumb_quality");
$convert = $config->get_string("thumb_convert_path"); $convert = $config->get_string("thumb_convert_path");
if($convert==null||$convert=="") if ($convert==null||$convert=="") {
{
return false; return false;
} }
@ -202,7 +201,7 @@ function create_thumbnail_convert($hash): bool
} }
$bg = "black"; $bg = "black";
if($type=="webp") { if ($type=="webp") {
$bg = "none"; $bg = "none";
} }
$format = '"%s" -flatten -strip -thumbnail %ux%u%s -quality %u -background %s "%s[0]" %s:"%s"'; $format = '"%s" -flatten -strip -thumbnail %ux%u%s -quality %u -background %s "%s[0]" %s:"%s"';
@ -225,7 +224,7 @@ function create_thumbnail_ffmpeg($hash): bool
global $config; global $config;
$ffmpeg = $config->get_string("thumb_ffmpeg_path"); $ffmpeg = $config->get_string("thumb_ffmpeg_path");
if($ffmpeg==null||$ffmpeg=="") { if ($ffmpeg==null||$ffmpeg=="") {
return false; return false;
} }
@ -237,12 +236,12 @@ function create_thumbnail_ffmpeg($hash): bool
$codec = "mjpeg"; $codec = "mjpeg";
$quality = $config->get_int("thumb_quality"); $quality = $config->get_int("thumb_quality");
if($config->get_string("thumb_type")=="webp") { if ($config->get_string("thumb_type")=="webp") {
$codec = "libwebp"; $codec = "libwebp";
} else { } else {
// mjpeg quality ranges from 2-31, with 2 being the best quality. // mjpeg quality ranges from 2-31, with 2 being the best quality.
$quality = floor(31 - (31 * ($quality/100))); $quality = floor(31 - (31 * ($quality/100)));
if($quality<2) { if ($quality<2) {
$quality = 2; $quality = 2;
} }
} }
@ -321,13 +320,19 @@ function calc_memory_use(array $info): int
return (int)$memory_use; return (int)$memory_use;
} }
function image_resize_gd(String $image_filename, array $info, int $new_width, int $new_height, function image_resize_gd(
string $output_filename=null, string $output_type=null, int $output_quality = 80) String $image_filename,
{ array $info,
int $new_width,
int $new_height,
string $output_filename=null,
string $output_type=null,
int $output_quality = 80
) {
$width = $info[0]; $width = $info[0];
$height = $info[1]; $height = $info[1];
if($output_type==null) { if ($output_type==null) {
/* If not specified, output to the same format as the original image */ /* If not specified, output to the same format as the original image */
switch ($info[2]) { switch ($info[2]) {
case IMAGETYPE_GIF: $output_type = "gif"; break; case IMAGETYPE_GIF: $output_type = "gif"; break;
@ -348,15 +353,15 @@ function image_resize_gd(String $image_filename, array $info, int $new_width, in
$image = imagecreatefromstring(file_get_contents($image_filename)); $image = imagecreatefromstring(file_get_contents($image_filename));
$image_resized = imagecreatetruecolor($new_width, $new_height); $image_resized = imagecreatetruecolor($new_width, $new_height);
try { try {
if($image===false) { if ($image===false) {
throw new ImageResizeException("Could not load image: ".$image_filename); throw new ImageResizeException("Could not load image: ".$image_filename);
} }
if($image_resized===false) { if ($image_resized===false) {
throw new ImageResizeException("Could not create output image with dimensions $new_width c $new_height "); throw new ImageResizeException("Could not create output image with dimensions $new_width c $new_height ");
} }
// Handle transparent images // Handle transparent images
switch($info[2]) { switch ($info[2]) {
case IMAGETYPE_GIF: case IMAGETYPE_GIF:
$transparency = imagecolortransparent($image); $transparency = imagecolortransparent($image);
$palletsize = imagecolorstotal($image); $palletsize = imagecolorstotal($image);
@ -368,12 +373,12 @@ function image_resize_gd(String $image_filename, array $info, int $new_width, in
// Allocate the same color in the new image resource // Allocate the same color in the new image resource
$transparency = imagecolorallocate($image_resized, $transparent_color['red'], $transparent_color['green'], $transparent_color['blue']); $transparency = imagecolorallocate($image_resized, $transparent_color['red'], $transparent_color['green'], $transparent_color['blue']);
if($transparency===false) { if ($transparency===false) {
throw new ImageResizeException("Unable to allocate transparent color"); throw new ImageResizeException("Unable to allocate transparent color");
} }
// Completely fill the background of the new image with allocated color. // Completely fill the background of the new image with allocated color.
if(imagefill($image_resized, 0, 0, $transparency)===false) { if (imagefill($image_resized, 0, 0, $transparency)===false) {
throw new ImageResizeException("Unable to fill new image with transparent color"); throw new ImageResizeException("Unable to fill new image with transparent color");
} }
@ -386,24 +391,24 @@ function image_resize_gd(String $image_filename, array $info, int $new_width, in
// //
// More info here: http://stackoverflow.com/questions/279236/how-do-i-resize-pngs-with-transparency-in-php // More info here: http://stackoverflow.com/questions/279236/how-do-i-resize-pngs-with-transparency-in-php
// //
if(imagealphablending($image_resized, false)===false) { if (imagealphablending($image_resized, false)===false) {
throw new ImageResizeException("Unable to disable image alpha blending"); throw new ImageResizeException("Unable to disable image alpha blending");
} }
if(imagesavealpha($image_resized, true)===false) { if (imagesavealpha($image_resized, true)===false) {
throw new ImageResizeException("Unable to enable image save alpha"); throw new ImageResizeException("Unable to enable image save alpha");
} }
$transparent_color = imagecolorallocatealpha($image_resized, 255, 255, 255, 127); $transparent_color = imagecolorallocatealpha($image_resized, 255, 255, 255, 127);
if($transparent_color===false) { if ($transparent_color===false) {
throw new ImageResizeException("Unable to allocate transparent color"); throw new ImageResizeException("Unable to allocate transparent color");
} }
if(imagefilledrectangle($image_resized, 0, 0, $new_width, $new_height, $transparent_color)===false) { if (imagefilledrectangle($image_resized, 0, 0, $new_width, $new_height, $transparent_color)===false) {
throw new ImageResizeException("Unable to fill new image with transparent color"); throw new ImageResizeException("Unable to fill new image with transparent color");
} }
break; break;
} }
// Actually resize the image. // Actually resize the image.
if(imagecopyresampled( if (imagecopyresampled(
$image_resized, $image_resized,
$image, $image,
0, 0,
@ -419,7 +424,7 @@ function image_resize_gd(String $image_filename, array $info, int $new_width, in
} }
$result = false; $result = false;
switch($output_type) { switch ($output_type) {
case "bmp": case "bmp":
$result = imagebmp($image_resized, $output_filename, true); $result = imagebmp($image_resized, $output_filename, true);
break; break;
@ -439,7 +444,7 @@ function image_resize_gd(String $image_filename, array $info, int $new_width, in
default: default:
throw new ImageResizeException("Failed to save the new image - Unsupported image type: $output_type"); throw new ImageResizeException("Failed to save the new image - Unsupported image type: $output_type");
} }
if($result==false) { if ($result==false) {
throw new ImageResizeException("Failed to save the new image, function returned false when saving type: $output_type"); throw new ImageResizeException("Failed to save the new image, function returned false when saving type: $output_type");
} }
} finally { } finally {
@ -448,7 +453,8 @@ function image_resize_gd(String $image_filename, array $info, int $new_width, in
} }
} }
function is_animated_gif(String $image_filename) { function is_animated_gif(String $image_filename)
{
$isanigif = 0; $isanigif = 0;
if (($fh = @fopen($image_filename, 'rb'))) { if (($fh = @fopen($image_filename, 'rb'))) {
//check if gif is animated (via http://www.php.net/manual/en/function.imagecreatefromgif.php#104473) //check if gif is animated (via http://www.php.net/manual/en/function.imagecreatefromgif.php#104473)

View file

@ -12,22 +12,23 @@
class BulkActionBlockBuildingEvent extends Event class BulkActionBlockBuildingEvent extends Event
{ {
/** @var array */ /** @var array */
public $actions = array(); public $actions = [];
public function add_action(String $action, string $button_text, String $confirmation_message = "", String $block = "", int $position = 40) public function add_action(String $action, string $button_text, String $confirmation_message = "", String $block = "", int $position = 40)
{ {
if ($block == null) if ($block == null) {
$block = ""; $block = "";
}
array_push( array_push(
$this->actions, $this->actions,
array( [
"block" => $block, "block" => $block,
"confirmation_message" => $confirmation_message, "confirmation_message" => $confirmation_message,
"action" => $action, "action" => $action,
"button_text" => $button_text, "button_text" => $button_text,
"position" => $position "position" => $position
) ]
); );
} }
} }
@ -41,7 +42,7 @@ class BulkActionEvent extends Event
/** @var PageRequestEvent */ /** @var PageRequestEvent */
public $page_request; public $page_request;
function __construct(String $action, PageRequestEvent $pageRequestEvent, array $items) public function __construct(String $action, PageRequestEvent $pageRequestEvent, array $items)
{ {
$this->action = $action; $this->action = $action;
$this->page_request = $pageRequestEvent; $this->page_request = $pageRequestEvent;
@ -59,10 +60,11 @@ class BulkActions extends Extension
$babbe = new BulkActionBlockBuildingEvent(); $babbe = new BulkActionBlockBuildingEvent();
send_event($babbe); send_event($babbe);
if (sizeof($babbe->actions) == 0) if (sizeof($babbe->actions) == 0) {
return; return;
}
usort($babbe->actions, array($this, "sort_blocks")); usort($babbe->actions, [$this, "sort_blocks"]);
$this->theme->display_selector($page, $babbe->actions, Tag::implode($event->search_terms)); $this->theme->display_selector($page, $babbe->actions, Tag::implode($event->search_terms));
} }
@ -73,15 +75,15 @@ class BulkActions extends Extension
global $user; global $user;
if ($user->can("delete_image")) { if ($user->can("delete_image")) {
$event->add_action("bulk_delete","Delete", "Delete selected images?", "", 10); $event->add_action("bulk_delete", "Delete", "Delete selected images?", "", 10);
} }
if ($user->can("bulk_edit_image_tag")) { if ($user->can("bulk_edit_image_tag")) {
$event->add_action("bulk_tag","Tag", "", $this->theme->render_tag_input(), 10); $event->add_action("bulk_tag", "Tag", "", $this->theme->render_tag_input(), 10);
} }
if ($user->can("bulk_edit_image_source")) { if ($user->can("bulk_edit_image_source")) {
$event->add_action("bulk_source","Set Source", "", $this->theme->render_source_input(), 10); $event->add_action("bulk_source", "Set Source", "", $this->theme->render_source_input(), 10);
} }
} }
@ -144,7 +146,7 @@ class BulkActions extends Extension
} }
} }
} }
} else if (isset($_POST['bulk_query']) && $_POST['bulk_query'] != "") { } elseif (isset($_POST['bulk_query']) && $_POST['bulk_query'] != "") {
$query = $_POST['bulk_query']; $query = $_POST['bulk_query'];
if ($query != null && $query != "") { if ($query != null && $query != "") {
$n = 0; $n = 0;
@ -188,7 +190,7 @@ class BulkActions extends Extension
foreach ($items as $id) { foreach ($items as $id) {
try { try {
$image = Image::by_id($id); $image = Image::by_id($id);
if($image==null) { if ($image==null) {
continue; continue;
} }
@ -219,7 +221,7 @@ class BulkActions extends Extension
if ($replace) { if ($replace) {
foreach ($items as $id) { foreach ($items as $id) {
$image = Image::by_id($id); $image = Image::by_id($id);
if($image==null) { if ($image==null) {
continue; continue;
} }
@ -229,7 +231,7 @@ class BulkActions extends Extension
} else { } else {
foreach ($items as $id) { foreach ($items as $id) {
$image = Image::by_id($id); $image = Image::by_id($id);
if($image==null) { if ($image==null) {
continue; continue;
} }
@ -254,7 +256,7 @@ class BulkActions extends Extension
foreach ($items as $id) { foreach ($items as $id) {
try { try {
$image = Image::by_id($id); $image = Image::by_id($id);
if($image==null) { if ($image==null) {
continue; continue;
} }

View file

@ -2,8 +2,6 @@
class BulkActionsTheme extends Themelet class BulkActionsTheme extends Themelet
{ {
public function display_selector(Page $page, $actions, $query) public function display_selector(Page $page, $actions, $query)
{ {
global $user; global $user;
@ -33,7 +31,7 @@ class BulkActionsTheme extends Themelet
} }
foreach ($actions as $action) { foreach ($actions as $action) {
$body .= "<div class='bulk_action'>" . make_form(make_link("bulk_action"), "POST", False, "", "return validate_selections(this,'" . html_escape($action["confirmation_message"]) . "');") . $body .= "<div class='bulk_action'>" . make_form(make_link("bulk_action"), "POST", false, "", "return validate_selections(this,'" . html_escape($action["confirmation_message"]) . "');") .
"<input type='hidden' name='bulk_query' value='" . html_escape($query) . "'>" . "<input type='hidden' name='bulk_query' value='" . html_escape($query) . "'>" .
"<input type='hidden' name='bulk_selected_ids' />" . "<input type='hidden' name='bulk_selected_ids' />" .
"<input type='hidden' name='bulk_action' value='" . $action["action"] . "' />" . "<input type='hidden' name='bulk_action' value='" . $action["action"] . "' />" .

View file

@ -282,7 +282,7 @@ class CronUploader extends Extension
$result = $this->add_image($img[0], $img[1], $img[2]); $result = $this->add_image($img[0], $img[1], $img[2]);
$database->commit(); $database->commit();
$this->move_uploaded($img[0], $img[1], $output_subdir, false); $this->move_uploaded($img[0], $img[1], $output_subdir, false);
if($result==null) { if ($result==null) {
$merged++; $merged++;
} else { } else {
$added++; $added++;
@ -299,7 +299,8 @@ class CronUploader extends Extension
} }
try { try {
$database->rollback(); $database->rollback();
} catch (Exception $e) {} } catch (Exception $e) {
}
} }
} }
@ -330,12 +331,11 @@ class CronUploader extends Extension
// Move to corrupt dir // Move to corrupt dir
$newDir .= "/failed_to_upload/".$output_subdir.$relativeDir; $newDir .= "/failed_to_upload/".$output_subdir.$relativeDir;
$info = "ERROR: Image was not uploaded."; $info = "ERROR: Image was not uploaded.";
} } else {
else {
$newDir .= "/uploaded/".$output_subdir.$relativeDir; $newDir .= "/uploaded/".$output_subdir.$relativeDir;
$info = "Image successfully uploaded. "; $info = "Image successfully uploaded. ";
} }
$newDir = str_replace ( "//", "/", $newDir."/" ); $newDir = str_replace("//", "/", $newDir."/");
if (!is_dir($newDir)) { if (!is_dir($newDir)) {
mkdir($newDir, 0775, true); mkdir($newDir, 0775, true);
@ -369,7 +369,7 @@ class CronUploader extends Extension
$infomsg = ""; // Will contain info message $infomsg = ""; // Will contain info message
if ($event->image_id == -1) { if ($event->image_id == -1) {
throw new Exception("File type not recognised. Filename: {$filename}"); throw new Exception("File type not recognised. Filename: {$filename}");
} else if ($event->image_id == null) { } elseif ($event->image_id == null) {
$infomsg = "Image merged. Filename: {$filename}"; $infomsg = "Image merged. Filename: {$filename}";
} else { } else {
$infomsg = "Image uploaded. ID: {$event->image_id} - Filename: {$filename}"; $infomsg = "Image uploaded. ID: {$event->image_id} - Filename: {$filename}";

View file

@ -12,7 +12,7 @@ class FlashFileHandler extends DataHandlerExtension
{ {
global $config; global $config;
if(!create_thumbnail_ffmpeg($hash)) { if (!create_thumbnail_ffmpeg($hash)) {
copy("ext/handle_flash/thumb.jpg", warehouse_path("thumbs", $hash)); copy("ext/handle_flash/thumb.jpg", warehouse_path("thumbs", $hash));
} }
return true; return true;

View file

@ -97,19 +97,26 @@ class PixelFileHandler extends DataHandlerExtension
try { try {
$info = getimagesize($inname); $info = getimagesize($inname);
$tsize = get_thumbnail_size_scaled($info[0], $info[1]); $tsize = get_thumbnail_size_scaled($info[0], $info[1]);
$image = image_resize_gd($inname, $info, $tsize[0], $tsize[1], $image = image_resize_gd(
$outname, $config->get_string('thumb_type'),$config->get_int('thumb_quality')); $inname,
} catch(InsufficientMemoryException $e) { $info,
$tsize[0],
$tsize[1],
$outname,
$config->get_string('thumb_type'),
$config->get_int('thumb_quality')
);
} catch (InsufficientMemoryException $e) {
$tsize = get_thumbnail_max_size_scaled(); $tsize = get_thumbnail_max_size_scaled();
$thumb = imagecreatetruecolor($tsize[0], min($tsize[1], 64)); $thumb = imagecreatetruecolor($tsize[0], min($tsize[1], 64));
$white = imagecolorallocate($thumb, 255, 255, 255); $white = imagecolorallocate($thumb, 255, 255, 255);
$black = imagecolorallocate($thumb, 0, 0, 0); $black = imagecolorallocate($thumb, 0, 0, 0);
imagefill($thumb, 0, 0, $white); imagefill($thumb, 0, 0, $white);
log_warning("handle_pixel","Insufficient memory while creating thumbnail: ".$e->getMessage()); log_warning("handle_pixel", "Insufficient memory while creating thumbnail: ".$e->getMessage());
imagestring($thumb, 5, 10, 24, "Image Too Large :(", $black); imagestring($thumb, 5, 10, 24, "Image Too Large :(", $black);
return true; return true;
} catch(Exception $e) { } catch (Exception $e) {
log_error("handle_pixel","Error while creating thumbnail: ".$e->getMessage()); log_error("handle_pixel", "Error while creating thumbnail: ".$e->getMessage());
return false; return false;
} }

View file

@ -34,7 +34,7 @@ class SVGFileHandler extends DataHandlerExtension
protected function create_thumb(string $hash): bool protected function create_thumb(string $hash): bool
{ {
if(!create_thumbnail_convert($hash)) { if (!create_thumbnail_convert($hash)) {
copy("ext/handle_svg/thumb.jpg", warehouse_path("thumbs", $hash)); copy("ext/handle_svg/thumb.jpg", warehouse_path("thumbs", $hash));
} }
return true; return true;

View file

@ -170,16 +170,15 @@ class Ratings extends Extension
global $user; global $user;
if ($user->is_admin()) { if ($user->is_admin()) {
$event->add_action("bulk_rate","Set Rating","",$this->theme->get_selection_rater_html("bulk_rating")); $event->add_action("bulk_rate", "Set Rating", "", $this->theme->get_selection_rater_html("bulk_rating"));
} }
} }
public function onBulkAction(BulkActionEvent $event) public function onBulkAction(BulkActionEvent $event)
{ {
global $user; global $user;
switch($event->action) { switch ($event->action) {
case "bulk_rate": case "bulk_rate":
if (!isset($_POST['bulk_rating'])) { if (!isset($_POST['bulk_rating'])) {
return; return;
@ -189,7 +188,7 @@ class Ratings extends Extension
$total = 0; $total = 0;
foreach ($event->items as $id) { foreach ($event->items as $id) {
$image = Image::by_id($id); $image = Image::by_id($id);
if($image==null) { if ($image==null) {
continue; continue;
} }
@ -331,7 +330,7 @@ class Ratings extends Extension
if ($config->get_int("ext_ratings2_version") < 3) { if ($config->get_int("ext_ratings2_version") < 3) {
$database->Execute("UPDATE images SET rating = 'u' WHERE rating is null"); $database->Execute("UPDATE images SET rating = 'u' WHERE rating is null");
switch($database->get_driver_name()) { switch ($database->get_driver_name()) {
case "mysql": case "mysql":
$database->Execute("ALTER TABLE images CHANGE rating rating CHAR(1) NOT NULL DEFAULT 'u'"); $database->Execute("ALTER TABLE images CHANGE rating rating CHAR(1) NOT NULL DEFAULT 'u'");
break; break;

View file

@ -46,7 +46,8 @@ class RatingsTheme extends Themelet
$page->add_block(new Block("List Controls", $html, "left")); $page->add_block(new Block("List Controls", $html, "left"));
} }
public function get_selection_rater_html(String $id = "select_rating") { public function get_selection_rater_html(String $id = "select_rating")
{
return "<select name='".$id."'> return "<select name='".$id."'>
<option value='s'>Safe</option> <option value='s'>Safe</option>
<option value='q'>Questionable</option> <option value='q'>Questionable</option>

View file

@ -69,33 +69,31 @@ class RegenThumb extends Extension
global $user; global $user;
if ($user->can("delete_image")) { if ($user->can("delete_image")) {
$event->add_action("bulk_regen","Regen Thumbnails","",$this->theme->bulk_html()); $event->add_action("bulk_regen", "Regen Thumbnails", "", $this->theme->bulk_html());
} }
} }
public function onBulkAction(BulkActionEvent $event) public function onBulkAction(BulkActionEvent $event)
{ {
global $user; global $user;
switch($event->action) { switch ($event->action) {
case "bulk_regen": case "bulk_regen":
if ($user->can("delete_image")) { if ($user->can("delete_image")) {
$force = true; $force = true;
if(isset($_POST["bulk_regen_thumb_missing_only"]) if (isset($_POST["bulk_regen_thumb_missing_only"])
&&$_POST["bulk_regen_thumb_missing_only"]=="true") &&$_POST["bulk_regen_thumb_missing_only"]=="true") {
{
$force=false; $force=false;
} }
$total = 0; $total = 0;
foreach ($event->items as $id) { foreach ($event->items as $id) {
$image = Image::by_id($id); $image = Image::by_id($id);
if($image==null) { if ($image==null) {
continue; continue;
} }
if($this->regenerate_thumbnail($image, $force)) { if ($this->regenerate_thumbnail($image, $force)) {
$total++; $total++;
} }
} }
@ -110,41 +108,42 @@ class RegenThumb extends Extension
$this->theme->display_admin_block(); $this->theme->display_admin_block();
} }
public function onAdminAction(AdminActionEvent $event) { public function onAdminAction(AdminActionEvent $event)
{
global $database; global $database;
switch($event->action) { switch ($event->action) {
case "regen_thumbs": case "regen_thumbs":
$event->redirect = true; $event->redirect = true;
$force = false; $force = false;
if(isset($_POST["regen_thumb_force"])&&$_POST["regen_thumb_force"]=="true") { if (isset($_POST["regen_thumb_force"])&&$_POST["regen_thumb_force"]=="true") {
$force=true; $force=true;
} }
$limit = 1000; $limit = 1000;
if(isset($_POST["regen_thumb_limit"])&&is_numeric($_POST["regen_thumb_limit"])) { if (isset($_POST["regen_thumb_limit"])&&is_numeric($_POST["regen_thumb_limit"])) {
$limit=intval($_POST["regen_thumb_limit"]); $limit=intval($_POST["regen_thumb_limit"]);
} }
$type = ""; $type = "";
if(isset($_POST["regen_thumb_limit"])) { if (isset($_POST["regen_thumb_limit"])) {
$type = $_POST["regen_thumb_type"]; $type = $_POST["regen_thumb_type"];
} }
$images = $this->get_images($type); $images = $this->get_images($type);
$i = 0; $i = 0;
foreach ($images as $image) { foreach ($images as $image) {
if(!$force) { if (!$force) {
$path = warehouse_path("thumbs", $image["hash"], false); $path = warehouse_path("thumbs", $image["hash"], false);
if(file_exists($path)) { if (file_exists($path)) {
continue; continue;
} }
} }
$event = new ThumbnailGenerationEvent($image["hash"], $image["ext"], $force); $event = new ThumbnailGenerationEvent($image["hash"], $image["ext"], $force);
send_event($event); send_event($event);
if($event->generated) { if ($event->generated) {
$i++; $i++;
} }
if($i>=$limit) { if ($i>=$limit) {
break; break;
} }
} }
@ -153,13 +152,13 @@ class RegenThumb extends Extension
case "delete_thumbs": case "delete_thumbs":
$event->redirect = true; $event->redirect = true;
if(isset($_POST["delete_thumb_type"])&&$_POST["delete_thumb_type"]!="") { if (isset($_POST["delete_thumb_type"])&&$_POST["delete_thumb_type"]!="") {
$images = $this->get_images($_POST["delete_thumb_type"]); $images = $this->get_images($_POST["delete_thumb_type"]);
$i = 0; $i = 0;
foreach ($images as $image) { foreach ($images as $image) {
$outname = warehouse_path("thumbs", $image["hash"]); $outname = warehouse_path("thumbs", $image["hash"]);
if(file_exists($outname)) { if (file_exists($outname)) {
unlink($outname); unlink($outname);
$i++; $i++;
} }
@ -176,13 +175,13 @@ class RegenThumb extends Extension
} }
} }
function get_images(String $ext = null) public function get_images(String $ext = null)
{ {
global $database; global $database;
$query = "SELECT hash, ext FROM images"; $query = "SELECT hash, ext FROM images";
$args = []; $args = [];
if($ext!=null&&$ext!="") { if ($ext!=null&&$ext!="") {
$query .= " WHERE ext = :ext"; $query .= " WHERE ext = :ext";
$args["ext"] = $ext; $args["ext"] = $ext;
} }
@ -190,7 +189,7 @@ class RegenThumb extends Extension
return $database->get_all($query, $args); return $database->get_all($query, $args);
} }
function remove_dir_recursively($dir) public function remove_dir_recursively($dir)
{ {
if (is_dir($dir)) { if (is_dir($dir)) {
$objects = scandir($dir); $objects = scandir($dir);
@ -199,7 +198,7 @@ class RegenThumb extends Extension
if (filetype($dir."/".$object) == "dir") { if (filetype($dir."/".$object) == "dir") {
$this->remove_dir_recursively($dir."/".$object); $this->remove_dir_recursively($dir."/".$object);
} else { } else {
unlink ($dir."/".$object); unlink($dir."/".$object);
} }
} }
} }
@ -207,5 +206,4 @@ class RegenThumb extends Extension
rmdir($dir); rmdir($dir);
} }
} }
} }

View file

@ -38,7 +38,8 @@ class RegenThumbTheme extends Themelet
return $html; return $html;
} }
public function bulk_html() { public function bulk_html()
{
return "<label><input type='checkbox' name='bulk_regen_thumb_missing_only' id='bulk_regen_thumb_missing_only' style='width:13px' value='true' />Only missing thumbs</label>"; return "<label><input type='checkbox' name='bulk_regen_thumb_missing_only' id='bulk_regen_thumb_missing_only' style='width:13px' value='true' />Only missing thumbs</label>";
} }
@ -49,7 +50,7 @@ class RegenThumbTheme extends Themelet
$types = []; $types = [];
$results = $database->get_all("SELECT ext, count(*) count FROM images group by ext"); $results = $database->get_all("SELECT ext, count(*) count FROM images group by ext");
foreach ($results as $result) { foreach ($results as $result) {
array_push($types,"<option value='".$result["ext"]."'>".$result["ext"]." (".$result["count"].")</option>"); array_push($types, "<option value='".$result["ext"]."'>".$result["ext"]." (".$result["count"].")</option>");
} }
$html = " $html = "
@ -67,7 +68,7 @@ class RegenThumbTheme extends Themelet
<tr><td colspan='2'><input type='submit' value='Regenerate Thumbnails'></td></tr> <tr><td colspan='2'><input type='submit' value='Regenerate Thumbnails'></td></tr>
</table> </table>
</form></p> </form></p>
<p>".make_form(make_link("admin/delete_thumbs"),"POST",False, "","return confirm('Are you sure you want to delete all thumbnails?')")." <p>".make_form(make_link("admin/delete_thumbs"), "POST", false, "", "return confirm('Are you sure you want to delete all thumbnails?')")."
<table class='form'> <table class='form'>
<tr><th><label for='delete_thumb_type'>Type</label></th><td> <tr><th><label for='delete_thumb_type'>Type</label></th><td>
<select name='delete_thumb_type' id='delete_thumb_type' value='1000'> <select name='delete_thumb_type' id='delete_thumb_type' value='1000'>

View file

@ -127,7 +127,7 @@ class RotateImage extends Extension
$info = getimagesize($image_filename); $info = getimagesize($image_filename);
$memory_use =calc_memory_use ($info); $memory_use =calc_memory_use($info);
$memory_limit = get_memory_limit(); $memory_limit = get_memory_limit();
if ($memory_use > $memory_limit) { if ($memory_use > $memory_limit) {
@ -164,18 +164,18 @@ class RotateImage extends Extension
*/ */
$background_color = 0; $background_color = 0;
switch($info[2]){ switch ($info[2]) {
case IMAGETYPE_PNG: case IMAGETYPE_PNG:
case IMAGETYPE_WEBP: case IMAGETYPE_WEBP:
$background_color = imagecolorallocatealpha($image, 0, 0, 0, 127); $background_color = imagecolorallocatealpha($image, 0, 0, 0, 127);
break; break;
} }
if($background_color===false) { if ($background_color===false) {
throw new ImageRotateException("Unable to allocate transparent color"); throw new ImageRotateException("Unable to allocate transparent color");
} }
$image_rotated = imagerotate($image, $deg, $background_color); $image_rotated = imagerotate($image, $deg, $background_color);
if($image_rotated===false) { if ($image_rotated===false) {
throw new ImageRotateException("Image rotate failed"); throw new ImageRotateException("Image rotate failed");
} }
@ -190,14 +190,14 @@ class RotateImage extends Extension
switch ($info[2]) { switch ($info[2]) {
case IMAGETYPE_GIF: $result = imagegif($image_rotated, $tmp_filename); break; case IMAGETYPE_GIF: $result = imagegif($image_rotated, $tmp_filename); break;
case IMAGETYPE_JPEG: $result = imagejpeg($image_rotated, $tmp_filename); break; case IMAGETYPE_JPEG: $result = imagejpeg($image_rotated, $tmp_filename); break;
case IMAGETYPE_PNG: $result = imagepng($image_rotated, $tmp_filename,9); break; case IMAGETYPE_PNG: $result = imagepng($image_rotated, $tmp_filename, 9); break;
case IMAGETYPE_WEBP: $result = imagewebp($image_rotated, $tmp_filename); break; case IMAGETYPE_WEBP: $result = imagewebp($image_rotated, $tmp_filename); break;
case IMAGETYPE_BMP: $result = imagebmp($image_rotated, $tmp_filename,true); break; case IMAGETYPE_BMP: $result = imagebmp($image_rotated, $tmp_filename, true); break;
default: default:
throw new ImageRotateException("Unsupported image type."); throw new ImageRotateException("Unsupported image type.");
} }
if($result===false) { if ($result===false) {
throw new ImageRotateException("Could not save image: ".$tmp_filename); throw new ImageRotateException("Could not save image: ".$tmp_filename);
} }

View file

@ -15,7 +15,9 @@
/* /*
* This is used by the image transcoding code when there is an error while transcoding * This is used by the image transcoding code when there is an error while transcoding
*/ */
class ImageTranscodeException extends SCoreException{ } class ImageTranscodeException extends SCoreException
{
}
class TranscodeImage extends Extension class TranscodeImage extends Extension
@ -103,7 +105,7 @@ class TranscodeImage extends Extension
$config->set_default_string('transcode_engine', "gd"); $config->set_default_string('transcode_engine', "gd");
$config->set_default_int('transcode_quality', 80); $config->set_default_int('transcode_quality', 80);
foreach(array_values(self::INPUT_FORMATS) as $format) { foreach (array_values(self::INPUT_FORMATS) as $format) {
$config->set_default_string('transcode_upload_'.$format, ""); $config->set_default_string('transcode_upload_'.$format, "");
} }
} }
@ -114,7 +116,7 @@ class TranscodeImage extends Extension
if ($user->is_admin() && $config->get_bool("resize_enabled")) { if ($user->is_admin() && $config->get_bool("resize_enabled")) {
$engine = $config->get_string("transcode_engine"); $engine = $config->get_string("transcode_engine");
if($this->can_convert_format($engine,$event->image->ext)) { if ($this->can_convert_format($engine, $event->image->ext)) {
$options = $this->get_supported_output_formats($engine, $event->image->ext); $options = $this->get_supported_output_formats($engine, $event->image->ext);
$event->add_part($this->theme->get_transcode_html($event->image, $options)); $event->add_part($this->theme->get_transcode_html($event->image, $options));
} }
@ -131,11 +133,11 @@ class TranscodeImage extends Extension
$sb = new SetupBlock("Image Transcode"); $sb = new SetupBlock("Image Transcode");
$sb->add_bool_option("transcode_enabled", "Allow transcoding images: "); $sb->add_bool_option("transcode_enabled", "Allow transcoding images: ");
$sb->add_bool_option("transcode_upload", "<br>Transcode on upload: "); $sb->add_bool_option("transcode_upload", "<br>Transcode on upload: ");
$sb->add_choice_option('transcode_engine',self::CONVERSION_ENGINES,"<br />Transcode engine: "); $sb->add_choice_option('transcode_engine', self::CONVERSION_ENGINES, "<br />Transcode engine: ");
foreach(self::INPUT_FORMATS as $display=>$format) { foreach (self::INPUT_FORMATS as $display=>$format) {
if(in_array($format, self::ENGINE_INPUT_SUPPORT[$engine])) { if (in_array($format, self::ENGINE_INPUT_SUPPORT[$engine])) {
$outputs = $this->get_supported_output_formats($engine, $format); $outputs = $this->get_supported_output_formats($engine, $format);
$sb->add_choice_option('transcode_upload_'.$format,$outputs,"<br />$display to: "); $sb->add_choice_option('transcode_upload_'.$format, $outputs, "<br />$display to: ");
} }
} }
$sb->add_int_option("transcode_quality", "<br/>Lossy format quality: "); $sb->add_int_option("transcode_quality", "<br/>Lossy format quality: ");
@ -151,21 +153,21 @@ class TranscodeImage extends Extension
$ext = $this->clean_format($ext); $ext = $this->clean_format($ext);
if($event->type=="gif"&&is_animated_gif($event->tmpname)) { if ($event->type=="gif"&&is_animated_gif($event->tmpname)) {
return; return;
} }
if(in_array($ext, array_values(self::INPUT_FORMATS))) { if (in_array($ext, array_values(self::INPUT_FORMATS))) {
$target_format = $config->get_string("transcode_upload_".$ext); $target_format = $config->get_string("transcode_upload_".$ext);
if(empty($target_format)) { if (empty($target_format)) {
return; return;
} }
try { try {
$new_image = $this->transcode_image($event->tmpname, $ext, $target_format); $new_image = $this->transcode_image($event->tmpname, $ext, $target_format);
$event->set_type($this->determine_ext($target_format)); $event->set_type($this->determine_ext($target_format));
$event->set_tmpname($new_image); $event->set_tmpname($new_image);
} catch(Exception $e) { } catch (Exception $e) {
log_error("transcode","Error while performing upload transcode: ".$e->getMessage()); log_error("transcode", "Error while performing upload transcode: ".$e->getMessage());
// We don't want to interfere with the upload process, // We don't want to interfere with the upload process,
// so if something goes wrong the untranscoded image jsut continues // so if something goes wrong the untranscoded image jsut continues
} }
@ -193,7 +195,6 @@ class TranscodeImage extends Extension
$this->theme->display_error(404, "Image not found", "No image in the database has the ID #$image_id"); $this->theme->display_error(404, "Image not found", "No image in the database has the ID #$image_id");
} else { } else {
if (isset($_POST['transcode_format'])) { if (isset($_POST['transcode_format'])) {
try { try {
$this->transcode_and_replace_image($image_obj, $_POST['transcode_format']); $this->transcode_and_replace_image($image_obj, $_POST['transcode_format']);
$page->set_mode("redirect"); $page->set_mode("redirect");
@ -214,16 +215,15 @@ class TranscodeImage extends Extension
$engine = $config->get_string("transcode_engine"); $engine = $config->get_string("transcode_engine");
if ($user->is_admin()) { if ($user->is_admin()) {
$event->add_action("bulk_transcode","Transcode","",$this->theme->get_transcode_picker_html($this->get_supported_output_formats($engine))); $event->add_action("bulk_transcode", "Transcode", "", $this->theme->get_transcode_picker_html($this->get_supported_output_formats($engine)));
} }
} }
public function onBulkAction(BulkActionEvent $event) public function onBulkAction(BulkActionEvent $event)
{ {
global $user, $database; global $user, $database;
switch($event->action) { switch ($event->action) {
case "bulk_transcode": case "bulk_transcode":
if (!isset($_POST['transcode_format'])) { if (!isset($_POST['transcode_format'])) {
return; return;
@ -235,7 +235,7 @@ class TranscodeImage extends Extension
try { try {
$database->beginTransaction(); $database->beginTransaction();
$image = Image::by_id($id); $image = Image::by_id($id);
if($image==null) { if ($image==null) {
continue; continue;
} }
@ -244,22 +244,23 @@ class TranscodeImage extends Extension
// otherwise the image entries will be stuck pointing to missing image files // otherwise the image entries will be stuck pointing to missing image files
$database->commit(); $database->commit();
$total++; $total++;
} catch(Exception $e) { } catch (Exception $e) {
log_error("transcode", "Error while bulk transcode on item $id to $format: ".$e->getMessage()); log_error("transcode", "Error while bulk transcode on item $id to $format: ".$e->getMessage());
try { try {
$database->rollback(); $database->rollback();
} catch (Exception $e) {} } catch (Exception $e) {
}
} }
} }
flash_message("Transcoded $total items"); flash_message("Transcoded $total items");
} }
break; break;
} }
} }
private function clean_format($format): ?string { private function clean_format($format): ?string
if(array_key_exists($format, self::FORMAT_ALIASES)) { {
if (array_key_exists($format, self::FORMAT_ALIASES)) {
return self::FORMAT_ALIASES[$format]; return self::FORMAT_ALIASES[$format];
} }
return $format; return $format;
@ -268,7 +269,7 @@ class TranscodeImage extends Extension
private function can_convert_format($engine, $format): bool private function can_convert_format($engine, $format): bool
{ {
$format = $this->clean_format($format); $format = $this->clean_format($format);
if(!in_array($format, self::ENGINE_INPUT_SUPPORT[$engine])) { if (!in_array($format, self::ENGINE_INPUT_SUPPORT[$engine])) {
return false; return false;
} }
return true; return true;
@ -278,12 +279,12 @@ class TranscodeImage extends Extension
{ {
$omit_format = $this->clean_format($omit_format); $omit_format = $this->clean_format($omit_format);
$output = []; $output = [];
foreach(self::OUTPUT_FORMATS as $key=>$value) { foreach (self::OUTPUT_FORMATS as $key=>$value) {
if($value=="") { if ($value=="") {
$output[$key] = $value; $output[$key] = $value;
continue; continue;
} }
if(in_array($value, self::ENGINE_OUTPUT_SUPPORT[$engine]) if (in_array($value, self::ENGINE_OUTPUT_SUPPORT[$engine])
&&(empty($omit_format)||$omit_format!=$this->determine_ext($value))) { &&(empty($omit_format)||$omit_format!=$this->determine_ext($value))) {
$output[$key] = $value; $output[$key] = $value;
} }
@ -293,7 +294,7 @@ class TranscodeImage extends Extension
private function determine_ext(String $format): String private function determine_ext(String $format): String
{ {
switch($format) { switch ($format) {
case "webp-lossless": case "webp-lossless":
case "webp-lossy": case "webp-lossy":
return "webp"; return "webp";
@ -327,7 +328,6 @@ class TranscodeImage extends Extension
@unlink($tmp_filename); @unlink($tmp_filename);
send_event(new ImageReplaceEvent($image_obj->id, $new_image)); send_event(new ImageReplaceEvent($image_obj->id, $new_image));
} }
@ -335,7 +335,7 @@ class TranscodeImage extends Extension
{ {
global $config; global $config;
if($source_format==$this->determine_ext($target_format)) { if ($source_format==$this->determine_ext($target_format)) {
throw new ImageTranscodeException("Source and target formats are the same: ".$source_format); throw new ImageTranscodeException("Source and target formats are the same: ".$source_format);
} }
@ -343,20 +343,19 @@ class TranscodeImage extends Extension
if(!$this->can_convert_format($engine,$source_format)) { if (!$this->can_convert_format($engine, $source_format)) {
throw new ImageTranscodeException("Engine $engine does not support input format $source_format"); throw new ImageTranscodeException("Engine $engine does not support input format $source_format");
} }
if(!in_array($target_format, self::ENGINE_OUTPUT_SUPPORT[$engine])) { if (!in_array($target_format, self::ENGINE_OUTPUT_SUPPORT[$engine])) {
throw new ImageTranscodeException("Engine $engine does not support output format $target_format"); throw new ImageTranscodeException("Engine $engine does not support output format $target_format");
} }
switch($engine) { switch ($engine) {
case "gd": case "gd":
return $this->transcode_image_gd($source_name, $source_format, $target_format); return $this->transcode_image_gd($source_name, $source_format, $target_format);
case "convert": case "convert":
return $this->transcode_image_convert($source_name, $source_format, $target_format); return $this->transcode_image_convert($source_name, $source_format, $target_format);
} }
} }
private function transcode_image_gd(String $source_name, String $source_format, string $target_format): string private function transcode_image_gd(String $source_name, String $source_format, string $target_format): string
@ -370,7 +369,7 @@ class TranscodeImage extends Extension
$image = imagecreatefromstring(file_get_contents($source_name)); $image = imagecreatefromstring(file_get_contents($source_name));
try { try {
$result = false; $result = false;
switch($target_format) { switch ($target_format) {
case "webp-lossy": case "webp-lossy":
$result = imagewebp($image, $tmp_name, $q); $result = imagewebp($image, $tmp_name, $q);
break; break;
@ -382,18 +381,18 @@ class TranscodeImage extends Extension
$width = imagesx($image); $width = imagesx($image);
$height = imagesy($image); $height = imagesy($image);
$new_image = imagecreatetruecolor($width, $height); $new_image = imagecreatetruecolor($width, $height);
if($new_image===false) { if ($new_image===false) {
throw new ImageTranscodeException("Could not create image with dimensions $width x $height"); throw new ImageTranscodeException("Could not create image with dimensions $width x $height");
} }
try{ try {
$black = imagecolorallocate($new_image, 0, 0, 0); $black = imagecolorallocate($new_image, 0, 0, 0);
if($black===false) { if ($black===false) {
throw new ImageTranscodeException("Could not allocate background color"); throw new ImageTranscodeException("Could not allocate background color");
} }
if(imagefilledrectangle($new_image, 0, 0, $width, $height, $black)===false) { if (imagefilledrectangle($new_image, 0, 0, $width, $height, $black)===false) {
throw new ImageTranscodeException("Could not fill background color"); throw new ImageTranscodeException("Could not fill background color");
} }
if(imagecopy($new_image, $image, 0, 0, 0, 0, $width, $height)===false) { if (imagecopy($new_image, $image, 0, 0, 0, 0, $width, $height)===false) {
throw new ImageTranscodeException("Could not copy source image to new image"); throw new ImageTranscodeException("Could not copy source image to new image");
} }
$result = imagejpeg($new_image, $tmp_name, $q); $result = imagejpeg($new_image, $tmp_name, $q);
@ -402,7 +401,7 @@ class TranscodeImage extends Extension
} }
break; break;
} }
if($result===false) { if ($result===false) {
throw new ImageTranscodeException("Error while transcoding ".$source_name." to ".$target_format); throw new ImageTranscodeException("Error while transcoding ".$source_name." to ".$target_format);
} }
return $tmp_name; return $tmp_name;
@ -418,15 +417,14 @@ class TranscodeImage extends Extension
$q = $config->get_int("transcode_quality"); $q = $config->get_int("transcode_quality");
$convert = $config->get_string("thumb_convert_path"); $convert = $config->get_string("thumb_convert_path");
if($convert==null||$convert=="") if ($convert==null||$convert=="") {
{
throw new ImageTranscodeException("ImageMagick path not configured"); throw new ImageTranscodeException("ImageMagick path not configured");
} }
$ext = $this->determine_ext($target_format); $ext = $this->determine_ext($target_format);
$args = " -flatten "; $args = " -flatten ";
$bg = "none"; $bg = "none";
switch($target_format) { switch ($target_format) {
case "webp-lossless": case "webp-lossless":
$args .= '-define webp:lossless=true'; $args .= '-define webp:lossless=true';
break; break;
@ -449,11 +447,10 @@ class TranscodeImage extends Extension
log_debug('transcode', "Transcoding with command `$cmd`, returns $ret"); log_debug('transcode', "Transcoding with command `$cmd`, returns $ret");
if($ret!==0) { if ($ret!==0) {
throw new ImageTranscodeException("Transcoding failed with command ".$cmd); throw new ImageTranscodeException("Transcoding failed with command ".$cmd);
} }
return $tmp_name; return $tmp_name;
} }
} }

View file

@ -20,14 +20,14 @@ class TranscodeImageTheme extends Themelet
return $html; return $html;
} }
public function get_transcode_picker_html(array $options) { public function get_transcode_picker_html(array $options)
{
$html = "<select id='transcode_format' name='transcode_format' required='required' >"; $html = "<select id='transcode_format' name='transcode_format' required='required' >";
foreach($options as $display=>$value) { foreach ($options as $display=>$value) {
$html .= "<option value='$value'>$display</option>"; $html .= "<option value='$value'>$display</option>";
} }
return $html."</select>"; return $html."</select>";
} }
public function display_transcode_error(Page $page, string $title, string $message) public function display_transcode_error(Page $page, string $title, string $message)
@ -37,5 +37,4 @@ class TranscodeImageTheme extends Themelet
$page->add_block(new NavBlock()); $page->add_block(new NavBlock());
$page->add_block(new Block($title, $message)); $page->add_block(new Block($title, $message));
} }
} }

View file

@ -46,10 +46,10 @@ class DataUploadEvent extends Event
$this->set_tmpname($tmpname); $this->set_tmpname($tmpname);
if($config->get_bool("upload_use_mime")) { if ($config->get_bool("upload_use_mime")) {
$this->set_type(get_extension_from_mime($tmpname)); $this->set_type(get_extension_from_mime($tmpname));
} else { } else {
if(array_key_exists('extension',$metadata)&&!empty($metadata['extension'])) { if (array_key_exists('extension', $metadata)&&!empty($metadata['extension'])) {
$this->type = strtolower($metadata['extension']); $this->type = strtolower($metadata['extension']);
} else { } else {
throw new UploadException("Could not determine extension for file ".$metadata["filename"]); throw new UploadException("Could not determine extension for file ".$metadata["filename"]);
@ -57,12 +57,14 @@ class DataUploadEvent extends Event
} }
} }
public function set_type(String $type) { public function set_type(String $type)
{
$this->type = strtolower($type); $this->type = strtolower($type);
$this->metadata["extension"] = $this->type; $this->metadata["extension"] = $this->type;
} }
public function set_tmpname(String $tmpname) { public function set_tmpname(String $tmpname)
{
$this->tmpname = $tmpname; $this->tmpname = $tmpname;
$this->metadata['hash'] = md5_file($tmpname); $this->metadata['hash'] = md5_file($tmpname);
$this->metadata['size'] = filesize($tmpname); $this->metadata['size'] = filesize($tmpname);