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;
if ($this->supported_ext($event->type)) {
if($event->force) {
if ($event->force) {
$result = $this->create_thumb($event->hash);
} else {
$outname = warehouse_path("thumbs", $event->hash);
if(file_exists($outname)) {
if (file_exists($outname)) {
return;
}
$result = $this->create_thumb($event->hash);
}
}
if($result) {
if ($result) {
$event->generated = true;
}
}

View file

@ -70,9 +70,9 @@ function get_extension_from_mime(String $file_path): ?String
{
global $config;
$mime = mime_content_type($file_path);
if(!empty($mime)) {
if (!empty($mime)) {
$ext = get_extension($mime);
if(!empty($ext)) {
if (!empty($ext)) {
return $ext;
}
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");
$convert = $config->get_string("thumb_convert_path");
if($convert==null||$convert=="")
{
if ($convert==null||$convert=="") {
return false;
}
@ -202,7 +201,7 @@ function create_thumbnail_convert($hash): bool
}
$bg = "black";
if($type=="webp") {
if ($type=="webp") {
$bg = "none";
}
$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;
$ffmpeg = $config->get_string("thumb_ffmpeg_path");
if($ffmpeg==null||$ffmpeg=="") {
if ($ffmpeg==null||$ffmpeg=="") {
return false;
}
@ -237,12 +236,12 @@ function create_thumbnail_ffmpeg($hash): bool
$codec = "mjpeg";
$quality = $config->get_int("thumb_quality");
if($config->get_string("thumb_type")=="webp") {
if ($config->get_string("thumb_type")=="webp") {
$codec = "libwebp";
} else {
// mjpeg quality ranges from 2-31, with 2 being the best quality.
$quality = floor(31 - (31 * ($quality/100)));
if($quality<2) {
if ($quality<2) {
$quality = 2;
}
}
@ -321,13 +320,19 @@ function calc_memory_use(array $info): int
return (int)$memory_use;
}
function image_resize_gd(String $image_filename, array $info, int $new_width, int $new_height,
string $output_filename=null, string $output_type=null, int $output_quality = 80)
{
function image_resize_gd(
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];
$height = $info[1];
if($output_type==null) {
if ($output_type==null) {
/* If not specified, output to the same format as the original image */
switch ($info[2]) {
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_resized = imagecreatetruecolor($new_width, $new_height);
try {
if($image===false) {
if ($image===false) {
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 ");
}
// Handle transparent images
switch($info[2]) {
switch ($info[2]) {
case IMAGETYPE_GIF:
$transparency = imagecolortransparent($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
$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");
}
// 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");
}
@ -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
//
if(imagealphablending($image_resized, false)===false) {
if (imagealphablending($image_resized, false)===false) {
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");
}
$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");
}
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");
}
break;
}
// Actually resize the image.
if(imagecopyresampled(
if (imagecopyresampled(
$image_resized,
$image,
0,
@ -419,7 +424,7 @@ function image_resize_gd(String $image_filename, array $info, int $new_width, in
}
$result = false;
switch($output_type) {
switch ($output_type) {
case "bmp":
$result = imagebmp($image_resized, $output_filename, true);
break;
@ -439,7 +444,7 @@ function image_resize_gd(String $image_filename, array $info, int $new_width, in
default:
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");
}
} 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;
if (($fh = @fopen($image_filename, 'rb'))) {
//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
{
/** @var array */
public $actions = array();
public $actions = [];
public function add_action(String $action, string $button_text, String $confirmation_message = "", String $block = "", int $position = 40)
{
if ($block == null)
if ($block == null) {
$block = "";
}
array_push(
$this->actions,
array(
[
"block" => $block,
"confirmation_message" => $confirmation_message,
"action" => $action,
"button_text" => $button_text,
"position" => $position
)
]
);
}
}
@ -41,7 +42,7 @@ class BulkActionEvent extends Event
/** @var PageRequestEvent */
public $page_request;
function __construct(String $action, PageRequestEvent $pageRequestEvent, array $items)
public function __construct(String $action, PageRequestEvent $pageRequestEvent, array $items)
{
$this->action = $action;
$this->page_request = $pageRequestEvent;
@ -59,10 +60,11 @@ class BulkActions extends Extension
$babbe = new BulkActionBlockBuildingEvent();
send_event($babbe);
if (sizeof($babbe->actions) == 0)
if (sizeof($babbe->actions) == 0) {
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));
}
@ -73,15 +75,15 @@ class BulkActions extends Extension
global $user;
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")) {
$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")) {
$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'];
if ($query != null && $query != "") {
$n = 0;
@ -188,7 +190,7 @@ class BulkActions extends Extension
foreach ($items as $id) {
try {
$image = Image::by_id($id);
if($image==null) {
if ($image==null) {
continue;
}
@ -219,7 +221,7 @@ class BulkActions extends Extension
if ($replace) {
foreach ($items as $id) {
$image = Image::by_id($id);
if($image==null) {
if ($image==null) {
continue;
}
@ -229,7 +231,7 @@ class BulkActions extends Extension
} else {
foreach ($items as $id) {
$image = Image::by_id($id);
if($image==null) {
if ($image==null) {
continue;
}
@ -254,7 +256,7 @@ class BulkActions extends Extension
foreach ($items as $id) {
try {
$image = Image::by_id($id);
if($image==null) {
if ($image==null) {
continue;
}

View file

@ -2,8 +2,6 @@
class BulkActionsTheme extends Themelet
{
public function display_selector(Page $page, $actions, $query)
{
global $user;
@ -33,7 +31,7 @@ class BulkActionsTheme extends Themelet
}
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_selected_ids' />" .
"<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]);
$database->commit();
$this->move_uploaded($img[0], $img[1], $output_subdir, false);
if($result==null) {
if ($result==null) {
$merged++;
} else {
$added++;
@ -299,7 +299,8 @@ class CronUploader extends Extension
}
try {
$database->rollback();
} catch (Exception $e) {}
} catch (Exception $e) {
}
}
}
@ -330,12 +331,11 @@ class CronUploader extends Extension
// Move to corrupt dir
$newDir .= "/failed_to_upload/".$output_subdir.$relativeDir;
$info = "ERROR: Image was not uploaded.";
}
else {
} else {
$newDir .= "/uploaded/".$output_subdir.$relativeDir;
$info = "Image successfully uploaded. ";
}
$newDir = str_replace ( "//", "/", $newDir."/" );
$newDir = str_replace("//", "/", $newDir."/");
if (!is_dir($newDir)) {
mkdir($newDir, 0775, true);
@ -369,7 +369,7 @@ class CronUploader extends Extension
$infomsg = ""; // Will contain info message
if ($event->image_id == -1) {
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}";
} else {
$infomsg = "Image uploaded. ID: {$event->image_id} - Filename: {$filename}";

View file

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

View file

@ -97,19 +97,26 @@ class PixelFileHandler extends DataHandlerExtension
try {
$info = getimagesize($inname);
$tsize = get_thumbnail_size_scaled($info[0], $info[1]);
$image = image_resize_gd($inname, $info, $tsize[0], $tsize[1],
$outname, $config->get_string('thumb_type'),$config->get_int('thumb_quality'));
} catch(InsufficientMemoryException $e) {
$image = image_resize_gd(
$inname,
$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();
$thumb = imagecreatetruecolor($tsize[0], min($tsize[1], 64));
$white = imagecolorallocate($thumb, 255, 255, 255);
$black = imagecolorallocate($thumb, 0, 0, 0);
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);
return true;
} catch(Exception $e) {
log_error("handle_pixel","Error while creating thumbnail: ".$e->getMessage());
} catch (Exception $e) {
log_error("handle_pixel", "Error while creating thumbnail: ".$e->getMessage());
return false;
}

View file

@ -34,7 +34,7 @@ class SVGFileHandler extends DataHandlerExtension
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));
}
return true;

View file

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

View file

@ -46,7 +46,8 @@ class RatingsTheme extends Themelet
$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."'>
<option value='s'>Safe</option>
<option value='q'>Questionable</option>

View file

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

View file

@ -38,7 +38,8 @@ class RegenThumbTheme extends Themelet
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>";
}
@ -49,7 +50,7 @@ class RegenThumbTheme extends Themelet
$types = [];
$results = $database->get_all("SELECT ext, count(*) count FROM images group by ext");
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 = "
@ -67,7 +68,7 @@ class RegenThumbTheme extends Themelet
<tr><td colspan='2'><input type='submit' value='Regenerate Thumbnails'></td></tr>
</table>
</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'>
<tr><th><label for='delete_thumb_type'>Type</label></th><td>
<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);
$memory_use =calc_memory_use ($info);
$memory_use =calc_memory_use($info);
$memory_limit = get_memory_limit();
if ($memory_use > $memory_limit) {
@ -164,18 +164,18 @@ class RotateImage extends Extension
*/
$background_color = 0;
switch($info[2]){
switch ($info[2]) {
case IMAGETYPE_PNG:
case IMAGETYPE_WEBP:
$background_color = imagecolorallocatealpha($image, 0, 0, 0, 127);
break;
}
if($background_color===false) {
if ($background_color===false) {
throw new ImageRotateException("Unable to allocate transparent color");
}
$image_rotated = imagerotate($image, $deg, $background_color);
if($image_rotated===false) {
if ($image_rotated===false) {
throw new ImageRotateException("Image rotate failed");
}
@ -190,14 +190,14 @@ class RotateImage extends Extension
switch ($info[2]) {
case IMAGETYPE_GIF: $result = imagegif($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_BMP: $result = imagebmp($image_rotated, $tmp_filename,true); break;
case IMAGETYPE_BMP: $result = imagebmp($image_rotated, $tmp_filename, true); break;
default:
throw new ImageRotateException("Unsupported image type.");
}
if($result===false) {
if ($result===false) {
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
*/
class ImageTranscodeException extends SCoreException{ }
class ImageTranscodeException extends SCoreException
{
}
class TranscodeImage extends Extension
@ -103,7 +105,7 @@ class TranscodeImage extends Extension
$config->set_default_string('transcode_engine', "gd");
$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, "");
}
}
@ -114,7 +116,7 @@ class TranscodeImage extends Extension
if ($user->is_admin() && $config->get_bool("resize_enabled")) {
$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);
$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->add_bool_option("transcode_enabled", "Allow transcoding images: ");
$sb->add_bool_option("transcode_upload", "<br>Transcode on upload: ");
$sb->add_choice_option('transcode_engine',self::CONVERSION_ENGINES,"<br />Transcode engine: ");
foreach(self::INPUT_FORMATS as $display=>$format) {
if(in_array($format, self::ENGINE_INPUT_SUPPORT[$engine])) {
$sb->add_choice_option('transcode_engine', self::CONVERSION_ENGINES, "<br />Transcode engine: ");
foreach (self::INPUT_FORMATS as $display=>$format) {
if (in_array($format, self::ENGINE_INPUT_SUPPORT[$engine])) {
$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: ");
@ -151,21 +153,21 @@ class TranscodeImage extends Extension
$ext = $this->clean_format($ext);
if($event->type=="gif"&&is_animated_gif($event->tmpname)) {
if ($event->type=="gif"&&is_animated_gif($event->tmpname)) {
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);
if(empty($target_format)) {
if (empty($target_format)) {
return;
}
try {
$new_image = $this->transcode_image($event->tmpname, $ext, $target_format);
$event->set_type($this->determine_ext($target_format));
$event->set_tmpname($new_image);
} catch(Exception $e) {
log_error("transcode","Error while performing upload transcode: ".$e->getMessage());
} catch (Exception $e) {
log_error("transcode", "Error while performing upload transcode: ".$e->getMessage());
// We don't want to interfere with the upload process,
// 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");
} else {
if (isset($_POST['transcode_format'])) {
try {
$this->transcode_and_replace_image($image_obj, $_POST['transcode_format']);
$page->set_mode("redirect");
@ -214,16 +215,15 @@ class TranscodeImage extends Extension
$engine = $config->get_string("transcode_engine");
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)
{
global $user, $database;
switch($event->action) {
switch ($event->action) {
case "bulk_transcode":
if (!isset($_POST['transcode_format'])) {
return;
@ -235,7 +235,7 @@ class TranscodeImage extends Extension
try {
$database->beginTransaction();
$image = Image::by_id($id);
if($image==null) {
if ($image==null) {
continue;
}
@ -244,22 +244,23 @@ class TranscodeImage extends Extension
// otherwise the image entries will be stuck pointing to missing image files
$database->commit();
$total++;
} catch(Exception $e) {
} catch (Exception $e) {
log_error("transcode", "Error while bulk transcode on item $id to $format: ".$e->getMessage());
try {
$database->rollback();
} catch (Exception $e) {}
} catch (Exception $e) {
}
}
}
flash_message("Transcoded $total items");
}
break;
}
}
private function clean_format($format): ?string {
if(array_key_exists($format, self::FORMAT_ALIASES)) {
private function clean_format($format): ?string
{
if (array_key_exists($format, self::FORMAT_ALIASES)) {
return self::FORMAT_ALIASES[$format];
}
return $format;
@ -268,7 +269,7 @@ class TranscodeImage extends Extension
private function can_convert_format($engine, $format): bool
{
$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 true;
@ -278,12 +279,12 @@ class TranscodeImage extends Extension
{
$omit_format = $this->clean_format($omit_format);
$output = [];
foreach(self::OUTPUT_FORMATS as $key=>$value) {
if($value=="") {
foreach (self::OUTPUT_FORMATS as $key=>$value) {
if ($value=="") {
$output[$key] = $value;
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))) {
$output[$key] = $value;
}
@ -293,7 +294,7 @@ class TranscodeImage extends Extension
private function determine_ext(String $format): String
{
switch($format) {
switch ($format) {
case "webp-lossless":
case "webp-lossy":
return "webp";
@ -327,7 +328,6 @@ class TranscodeImage extends Extension
@unlink($tmp_filename);
send_event(new ImageReplaceEvent($image_obj->id, $new_image));
}
@ -335,7 +335,7 @@ class TranscodeImage extends Extension
{
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);
}
@ -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");
}
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");
}
switch($engine) {
switch ($engine) {
case "gd":
return $this->transcode_image_gd($source_name, $source_format, $target_format);
case "convert":
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
@ -370,7 +369,7 @@ class TranscodeImage extends Extension
$image = imagecreatefromstring(file_get_contents($source_name));
try {
$result = false;
switch($target_format) {
switch ($target_format) {
case "webp-lossy":
$result = imagewebp($image, $tmp_name, $q);
break;
@ -382,18 +381,18 @@ class TranscodeImage extends Extension
$width = imagesx($image);
$height = imagesy($image);
$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");
}
try{
try {
$black = imagecolorallocate($new_image, 0, 0, 0);
if($black===false) {
if ($black===false) {
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");
}
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");
}
$result = imagejpeg($new_image, $tmp_name, $q);
@ -402,7 +401,7 @@ class TranscodeImage extends Extension
}
break;
}
if($result===false) {
if ($result===false) {
throw new ImageTranscodeException("Error while transcoding ".$source_name." to ".$target_format);
}
return $tmp_name;
@ -418,15 +417,14 @@ class TranscodeImage extends Extension
$q = $config->get_int("transcode_quality");
$convert = $config->get_string("thumb_convert_path");
if($convert==null||$convert=="")
{
if ($convert==null||$convert=="") {
throw new ImageTranscodeException("ImageMagick path not configured");
}
$ext = $this->determine_ext($target_format);
$args = " -flatten ";
$bg = "none";
switch($target_format) {
switch ($target_format) {
case "webp-lossless":
$args .= '-define webp:lossless=true';
break;
@ -449,11 +447,10 @@ class TranscodeImage extends Extension
log_debug('transcode', "Transcoding with command `$cmd`, returns $ret");
if($ret!==0) {
if ($ret!==0) {
throw new ImageTranscodeException("Transcoding failed with command ".$cmd);
}
return $tmp_name;
}
}

View file

@ -20,14 +20,14 @@ class TranscodeImageTheme extends Themelet
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' >";
foreach($options as $display=>$value) {
foreach ($options as $display=>$value) {
$html .= "<option value='$value'>$display</option>";
}
return $html."</select>";
}
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 Block($title, $message));
}
}

View file

@ -46,10 +46,10 @@ class DataUploadEvent extends Event
$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));
} else {
if(array_key_exists('extension',$metadata)&&!empty($metadata['extension'])) {
if (array_key_exists('extension', $metadata)&&!empty($metadata['extension'])) {
$this->type = strtolower($metadata['extension']);
} else {
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->metadata["extension"] = $this->type;
}
public function set_tmpname(String $tmpname) {
public function set_tmpname(String $tmpname)
{
$this->tmpname = $tmpname;
$this->metadata['hash'] = md5_file($tmpname);
$this->metadata['size'] = filesize($tmpname);