function HookImagestreamUpload_pluploadInitialuploadprocessing()
{
    #Support for uploading multi files as zip
    global $config_windows, $id, $targetDir, $resource_type, $imagestream_restypes, $imagestream_transitiontime, $zipcommand, $use_zip_extension, $userref, $session_hash, $filename, $filename_field, $collection_add, $archiver, $zipcommand, $ffmpeg_fullpath, $ffmpeg_preview_extension, $ffmpeg_preview_options, $ffmpeg_preview_min_height, $ffmpeg_preview_max_height, $ffmpeg_preview_min_width, $ffmpeg_preview_max_width, $lang, $collection_download_settings, $archiver_listfile_argument;
    $ffmpeg_fullpath = get_utility_path("ffmpeg");
    debug("DEBUG: Imagestream - checking restype: " . $resource_type . $imagestream_restypes);
    if (in_array($resource_type, $imagestream_restypes)) {
        debug("DEBUG: Imagestream - uploading file");
        #Check that we have an archiver configured
        $archiver_fullpath = get_utility_path("archiver");
        if (!isset($zipcommand) && !$use_zip_extension) {
            if ($archiver_fullpath == false) {
                exit($lang["archiver-utility-not-found"]);
            }
        }
        echo print_r($_POST) . print_r($_GET);
        if (getval("lastqueued", "")) {
            debug("DEBUG: Imagestream - last queued file");
            $ref = copy_resource(0 - $userref);
            # Copy from user template
            debug("DEBUG: Imagestream - creating resource: " . $ref);
            # Create the zip file
            $imagestreamzippath = get_resource_path($ref, true, "", true, "zip");
            if ($use_zip_extension) {
                $zip = new ZipArchive();
                $zip->open($imagestreamzippath, ZIPARCHIVE::CREATE);
            }
            $deletion_array = array();
            debug("DEBUG: opening directory: " . $targetDir);
            $imagestream_files = opendir($targetDir);
            $imagestream_workingfiles = get_temp_dir() . DIRECTORY_SEPARATOR . "plupload" . DIRECTORY_SEPARATOR . $session_hash . "workingfiles";
            if (!file_exists($imagestream_workingfiles)) {
                if ($config_windows) {
                    @mkdir($imagestream_workingfiles);
                } else {
                    @mkdir($imagestream_workingfiles, 0777, true);
                }
            }
            $filenumber = 00;
            $imagestream_filelist = array();
            while ($imagestream_filelist[] = readdir($imagestream_files)) {
                sort($imagestream_filelist);
            }
            closedir($imagestream_files);
            $imageindex = 1;
            foreach ($imagestream_filelist as $imagestream_file) {
                if ($imagestream_file != '.' && $imagestream_file != '..') {
                    $filenumber = sprintf("%03d", $filenumber);
                    $deletion_array[] = $targetDir . DIRECTORY_SEPARATOR . $imagestream_file;
                    if (!$use_zip_extension) {
                        $imagestreamcmd_file = get_temp_dir(false, $id) . "/imagestreamzipcmd" . $imagestream_file . ".txt";
                        $fh = fopen($imagestreamcmd_file, 'w') or die("can't open file");
                        fwrite($fh, $targetDir . DIRECTORY_SEPARATOR . $imagestream_file . "\r\n");
                        fclose($fh);
                        $deletion_array[] = $imagestreamcmd_file;
                    }
                    if ($use_zip_extension) {
                        debug("DEBUG: Imagestream - adding filename: " . $imagestream_file);
                        debug("DEBUG: using zip PHP extension, set up zip at : " . $imagestreamzippath);
                        $zip->addFile($imagestream_file);
                        debug(" Added files number : " . $zip->numFiles);
                        $wait = $zip->close();
                        debug("DEBUG: closed zip");
                    } else {
                        if ($archiver_fullpath) {
                            debug("DEBUG: using archiver, running command: \r\n" . $archiver_fullpath . " " . $collection_download_settings[0]["arguments"] . " " . escapeshellarg($imagestreamzippath) . " " . $archiver_listfile_argument . escapeshellarg($imagestream_file));
                            run_command($archiver_fullpath . " " . $collection_download_settings[0]["arguments"] . " " . escapeshellarg($imagestreamzippath) . " " . $archiver_listfile_argument . escapeshellarg($imagestreamcmd_file));
                        } else {
                            if (!$use_zip_extension) {
                                if ($config_windows) {
                                    debug("DEBUG: using zip command: . {$zipcommand} " . escapeshellarg($imagestreamzippath) . " @" . escapeshellarg($imagestreamcmd_file));
                                    exec("{$zipcommand} " . escapeshellarg($imagestreamzippath) . " @" . escapeshellarg($imagestreamcmd_file));
                                } else {
                                    # Pipe the command file, containing the filenames, to the executable.
                                    exec("{$zipcommand} " . escapeshellarg($imagestreamzippath) . " -@ < " . escapeshellarg($imagestreamcmd_file));
                                }
                            }
                        }
                    }
                    #Create a JPEG if not already in that format
                    $imagestream_file_parts = explode('.', $imagestream_file);
                    $imagestream_file_ext = $imagestream_file_parts[count($imagestream_file_parts) - 1];
                    $imagestream_file_noext = basename($imagestream_file, $imagestream_file_ext);
                    global $imagemagick_path, $imagemagick_quality;
                    $icc_transform_complete = false;
                    # Camera RAW images need prefix
                    if (preg_match('/^(dng|nef|x3f|cr2|crw|mrw|orf|raf|dcr)$/i', $imagestream_file_ext, $rawext)) {
                        $prefix = $rawext[0] . ':';
                    }
                    # Locate imagemagick.
                    $convert_fullpath = get_utility_path("im-convert");
                    if ($convert_fullpath == false) {
                        exit("Could not find ImageMagick 'convert' utility at location '{$imagemagick_path}'.");
                    }
                    $prefix = '';
                    if ($prefix == "cr2:" || $prefix == "nef:") {
                        $flatten = "";
                    } else {
                        $flatten = "-flatten";
                    }
                    $command = $convert_fullpath . ' ' . escapeshellarg($targetDir . DIRECTORY_SEPARATOR . $imagestream_file) . ' +matte ' . $flatten . ' -quality ' . $imagemagick_quality;
                    # EXPERIMENTAL CODE TO USE EXISTING ICC PROFILE IF PRESENT
                    global $icc_extraction, $icc_preview_profile, $icc_preview_options, $ffmpeg_supported_extensions;
                    if ($icc_extraction) {
                        $iccpath = $targetDir . DIRECTORY_SEPARATOR . $imagestream_file . '.icc';
                        if (!file_exists($iccpath) && !isset($iccfound) && $extension != "pdf" && !in_array($imagestream_file_ext, $ffmpeg_supported_extensions)) {
                            // extracted profile doesn't exist. Try extracting.
                            if (extract_icc_profile($ref, $imagestream_file_ext)) {
                                $iccfound = true;
                            } else {
                                $iccfound = false;
                            }
                        }
                    }
                    if ($icc_extraction && file_exists($iccpath) && !$icc_transform_complete) {
                        // we have an extracted ICC profile, so use it as source
                        $targetprofile = dirname(__FILE__) . '/../iccprofiles/' . $icc_preview_profile;
                        $profile = " +profile \"*\" -profile {$iccpath} {$icc_preview_options} -profile {$targetprofile} +profile \"*\" ";
                        $icc_transform_complete = true;
                    } else {
                        // use existing strategy for color profiles
                        # Preserve colour profiles? (omit for smaller sizes)
                        $profile = "+profile \"*\" -colorspace RGB";
                        # By default, strip the colour profiles ('+' is remove the profile, confusingly)
                        #if ($imagemagick_preserve_profiles && $id!="thm" && $id!="col" && $id!="pre" && $id!="scr") {$profile="";}
                    }
                    $runcommand = $command . " +matte {$profile} " . escapeshellarg($imagestream_workingfiles . DIRECTORY_SEPARATOR . "imagestream" . $filenumber . ".jpg");
                    $deletion_array[] = $imagestream_workingfiles . DIRECTORY_SEPARATOR . "imagestream" . $filenumber . ".jpg";
                    $output = run_command($runcommand);
                    debug("processed file" . $filenumber . ": " . $imagestream_file . "\r\n");
                    debug("Image index: " . $imageindex . ". file count: " . count($imagestream_filelist));
                    if ($filenumber == 00) {
                        $snapshotsize = getimagesize($imagestream_workingfiles . DIRECTORY_SEPARATOR . "imagestream" . $filenumber . ".jpg");
                        list($width, $height) = $snapshotsize;
                        # Frame size must be a multiple of two
                        if ($width % 2) {
                            $width++;
                        }
                        if ($height % 2) {
                            $height++;
                        }
                    }
                    if ($imageindex == count($imagestream_filelist) - 1) {
                        $additionalfile = $filenumber + 1;
                        $additionalfile = sprintf("%03d", $additionalfile);
                        copy($imagestream_workingfiles . DIRECTORY_SEPARATOR . "imagestream" . $filenumber . ".jpg", $imagestream_workingfiles . DIRECTORY_SEPARATOR . "imagestream" . $additionalfile . ".jpg");
                        $deletion_array[] = $imagestream_workingfiles . DIRECTORY_SEPARATOR . "imagestream" . $additionalfile . ".jpg";
                    }
                    $filenumber++;
                }
                #end of loop for each uploadedfile
                $imageindex++;
            }
            #Add the resource and move this zip file, set extension
            # Add to collection?
            if ($collection_add != "") {
                add_resource_to_collection($ref, $collection_add);
            }
            # Log this
            daily_stat("Resource upload", $ref);
            resource_log($ref, "u", 0);
            #Change this!!!!!!!!!!!
            #$status=upload_file($ref,true,false,false));
            if (!$config_windows) {
                @chmod($imagestreamzippath, 0777);
            }
            # Store extension in the database and update file modified time.
            sql_query("update resource set file_extension='zip',preview_extension='zip',file_modified=now(), has_image=0 where ref='{$ref}'");
            #update_field($ref,$filename_field,$filename);
            update_disk_usage($ref);
            # create the mp4 version
            # Add a new alternative file
            $aref = add_alternative_file($ref, "MP4 version");
            $imagestreamqtfile = get_resource_path($ref, true, "", false, "mp4", -1, 1, false, "", $aref);
            $shell_exec_cmd = $ffmpeg_fullpath . " -loglevel panic -y -r " . $imagestream_transitiontime . " -i " . $imagestream_workingfiles . DIRECTORY_SEPARATOR . "imagestream%3d.jpg -r " . $imagestream_transitiontime . " -s {$width}x{$height} " . $imagestreamqtfile;
            echo "Running command: " . $shell_exec_cmd;
            if ($config_windows) {
                $shell_exec_cmd = $ffmpeg_fullpath . " -loglevel panic -y -r " . $imagestream_transitiontime . " -i " . $imagestream_workingfiles . DIRECTORY_SEPARATOR . "imagestream%%3d.jpg -r " . $imagestream_transitiontime . " -s {$width}x{$height} " . $imagestreamqtfile;
                file_put_contents(get_temp_dir() . DIRECTORY_SEPARATOR . "imagestreammp4" . $session_hash . ".bat", $shell_exec_cmd);
                $shell_exec_cmd = get_temp_dir() . DIRECTORY_SEPARATOR . "imagestreammp4" . $session_hash . ".bat";
                $deletion_array[] = $shell_exec_cmd;
            }
            run_command($shell_exec_cmd);
            debug("DEBUG created slideshow MP4 video");
            if (!$config_windows) {
                @chmod($imagestreamqtfile, 0777);
            }
            $file_size = @filesize_unlimited($imagestreamqtfile);
            # Save alternative file data.
            sql_query("update resource_alt_files set file_name='quicktime.mp4',file_extension='mp4',file_size='" . $file_size . "',creation_date=now() where resource='{$ref}' and ref='{$aref}'");
            #create the FLV preview as per normal video processing if possible?
            if ($height < $ffmpeg_preview_min_height) {
                $height = $ffmpeg_preview_min_height;
            }
            if ($width < $ffmpeg_preview_min_width) {
                $width = $ffmpeg_preview_min_width;
            }
            if ($height > $ffmpeg_preview_max_height) {
                $width = ceil($width * ($ffmpeg_preview_max_height / $height));
                $height = $ffmpeg_preview_max_height;
            }
            if ($width > $ffmpeg_preview_max_width) {
                $height = ceil($height * ($ffmpeg_preview_max_width / $width));
                $width = $ffmpeg_preview_max_width;
            }
            $flvzippreviewfile = get_resource_path($ref, true, "pre", false, $ffmpeg_preview_extension);
            $shell_exec_cmd = $ffmpeg_fullpath . " -loglevel panic -y -i " . $imagestreamqtfile . " {$ffmpeg_preview_options} -s {$width}x{$height} " . $flvzippreviewfile;
            debug("Running command: " . $shell_exec_cmd);
            if ($config_windows) {
                file_put_contents(get_temp_dir() . DIRECTORY_SEPARATOR . "imagestreamflv" . $session_hash . ".bat", $shell_exec_cmd);
                $shell_exec_cmd = get_temp_dir() . DIRECTORY_SEPARATOR . "imagestreamflv" . $session_hash . ".bat";
                $deletion_array[] = $shell_exec_cmd;
            }
            run_command($shell_exec_cmd);
            debug("DEBUG created slideshow FLV video");
            if (!$config_windows) {
                @chmod($flvzippreviewfile, 0777);
            }
            #Tidy up
            rcRmdir($imagestream_workingfiles);
            rcRmdir($targetDir);
            foreach ($deletion_array as $tmpfile) {
                debug("\r\nDEBUG: Deleting: " . $tmpfile);
                delete_exif_tmpfile($tmpfile);
            }
            echo "SUCCESS";
            #return true;
            exit;
        } else {
            echo "SUCCESS";
            exit;
        }
        return true;
    } else {
        return false;
    }
}
function create_previews_using_im($ref, $thumbonly = false, $extension = "jpg", $previewonly = false, $previewbased = false, $alternative = -1, $ingested = false)
{
    global $keep_for_hpr, $imagemagick_path, $imagemagick_preserve_profiles, $imagemagick_quality, $imagemagick_colorspace, $default_icc_file, $autorotate_no_ingest, $always_make_previews, $lean_preview_generation;
    $icc_transform_complete = false;
    debug("create_previews_using_im(ref={$ref},thumbonly={$thumbonly},extension={$extension},previewonly={$previewonly},previewbased={$previewbased},alternative={$alternative},ingested={$ingested})");
    if (isset($imagemagick_path)) {
        # ----------------------------------------
        # Use ImageMagick to perform the resize
        # ----------------------------------------
        # For resource $ref, (re)create the various preview sizes listed in the table preview_sizes
        # Set thumbonly=true to (re)generate thumbnails only.
        if ($previewbased || $autorotate_no_ingest && !$ingested) {
            $file = get_resource_path($ref, true, "lpr", false, "jpg", -1, 1, false, "");
            if (!file_exists($file)) {
                $file = get_resource_path($ref, true, "scr", false, "jpg", -1, 1, false, "");
                if (!file_exists($file)) {
                    $file = get_resource_path($ref, true, "pre", false, "jpg", -1, 1, false, "");
                    /* staged, but not needed in testing
                    			if(!file_exists($file) && $autorotate_no_ingest && !$ingested)
                    				{
                    				$file=get_resource_path($ref,true,"",false,$extension,-1,1,false,"",$alternative);
                    				}*/
                }
            }
            if ($autorotate_no_ingest && !$ingested && !$previewonly) {
                # extra check for !previewonly should there also be ingested resources in the system
                $file = get_resource_path($ref, true, "", false, $extension, -1, 1, false, "", $alternative);
            }
        } else {
            if (!$previewonly) {
                $file = get_resource_path($ref, true, "", false, $extension, -1, 1, false, "", $alternative);
            } else {
                # We're generating based on a new preview (scr) image.
                $file = get_resource_path($ref, true, "tmp", false, "jpg");
            }
        }
        $hpr_path = get_resource_path($ref, true, "hpr", false, "jpg", -1, 1, false, "", $alternative);
        if (file_exists($hpr_path) && !$previewbased) {
            unlink($hpr_path);
        }
        $lpr_path = get_resource_path($ref, true, "lpr", false, "jpg", -1, 1, false, "", $alternative);
        if (file_exists($lpr_path) && !$previewbased) {
            unlink($lpr_path);
        }
        $scr_path = get_resource_path($ref, true, "scr", false, "jpg", -1, 1, false, "", $alternative);
        if (file_exists($scr_path) && !$previewbased) {
            unlink($scr_path);
        }
        $scr_wm_path = get_resource_path($ref, true, "scr", false, "jpg", -1, 1, true, "", $alternative);
        if (file_exists($scr_wm_path) && !$previewbased) {
            unlink($scr_wm_path);
        }
        $prefix = '';
        # Camera RAW images need prefix
        if (preg_match('/^(dng|nef|x3f|cr2|crw|mrw|orf|raf|dcr)$/i', $extension, $rawext)) {
            $prefix = $rawext[0] . ':';
        }
        # Locate imagemagick.
        $identify_fullpath = get_utility_path("im-identify");
        if ($identify_fullpath == false) {
            debug("ERROR: Could not find ImageMagick 'identify' utility at location '{$imagemagick_path}'.");
            return false;
        }
        # Get image's dimensions.
        $identcommand = $identify_fullpath . ' -format %wx%h ' . escapeshellarg($prefix . $file) . '[0]';
        $identoutput = run_command($identcommand);
        if ($lean_preview_generation) {
            $all_sizes = false;
            if (!$thumbonly && !$previewonly) {
                // seperate width and height
                $all_sizes = true;
                if (!empty($identoutput)) {
                    $wh = explode("x", $identoutput);
                    $o_width = $wh[0];
                    $o_height = $wh[1];
                }
            }
        }
        preg_match('/^([0-9]+)x([0-9]+)$/ims', $identoutput, $smatches);
        if (@(list(, $sw, $sh) = $smatches) === false) {
            return false;
        }
        $sizes = "";
        if ($thumbonly) {
            $sizes = " where id='thm' or id='col'";
        }
        if ($previewonly) {
            $sizes = " where id='thm' or id='col' or id='pre' or id='scr'";
        }
        $ps = sql_query("select * from preview_size {$sizes} order by width desc, height desc");
        if ($lean_preview_generation && $all_sizes) {
            $force_make = array("pre", "thm", "col");
            if ($extension != "jpg" || $extension != "jpeg") {
                array_push($force_make, "hpr", "scr");
            }
            $count = count($ps) - 1;
            $oversized = 0;
            for ($s = $count; $s > 0; $s--) {
                if (!in_array($ps[$s]['id'], $force_make) && !in_array($ps[$s]['id'], $always_make_previews) && (isset($o_width) && isset($o_height) && $ps[$s]['width'] > $o_width && $ps[$s]['height'] > $o_height)) {
                    $oversized++;
                }
                if ($oversized > 0) {
                    unset($ps[$s]);
                }
            }
            $ps = array_values($ps);
        }
        $created_count = 0;
        for ($n = 0; $n < count($ps); $n++) {
            # If this is just a jpg resource, we avoid the hpr size because the resource itself is an original sized jpg.
            # If preview_preprocessing indicates the intermediate jpg should be kept as the hpr image, do that.
            if ($keep_for_hpr && $ps[$n]['id'] == "hpr") {
                rename($file, $hpr_path);
                // $keep_for_hpr is switched to false below
            }
            # If we've already made the LPR or SCR then use those for the remaining previews.
            # As we start with the large and move to the small, this will speed things up.
            if ($extension != "png" && $extension != "gif") {
                if (file_exists($hpr_path)) {
                    $file = $hpr_path;
                }
                if (file_exists($lpr_path)) {
                    $file = $lpr_path;
                }
                if (file_exists($scr_path)) {
                    $file = $scr_path;
                }
            }
            # Locate imagemagick.
            $convert_fullpath = get_utility_path("im-convert");
            if ($convert_fullpath == false) {
                debug("ERROR: Could not find ImageMagick 'convert' utility at location '{$imagemagick_path}'.");
                return false;
            }
            if ($prefix == "cr2:" || $prefix == "nef:" || $extension == "png" || $extension == "gif") {
                $flatten = "";
            } else {
                $flatten = "-flatten";
            }
            $command = $convert_fullpath . ' ' . escapeshellarg($file) . ($extension != "png" && $extension != "gif" ? '[0] +matte ' : '') . $flatten . ' -quality ' . $imagemagick_quality;
            # fetch target width and height
            $tw = $ps[$n]["width"];
            $th = $ps[$n]["height"];
            $id = $ps[$n]["id"];
            # Debug
            debug("Contemplating " . $ps[$n]["id"] . " (sw={$sw}, tw={$tw}, sh={$sh}, th={$th}, extension={$extension})");
            # Find the target path
            if ($extension == "png" || $extension == "gif") {
                $target_ext = $extension;
            } else {
                $target_ext = "jpg";
            }
            $path = get_resource_path($ref, true, $ps[$n]["id"], false, $target_ext, -1, 1, false, "", $alternative);
            # Delete any file at the target path. Unless using the previewbased option, in which case we need it.
            if (!hook("imagepskipdel") && !$keep_for_hpr) {
                if (!$previewbased) {
                    if (file_exists($path)) {
                        unlink($path);
                    }
                }
            }
            if ($keep_for_hpr) {
                $keep_for_hpr = false;
            }
            # Also try the watermarked version.
            $wpath = get_resource_path($ref, true, $ps[$n]["id"], false, $target_ext, -1, 1, true, "", $alternative);
            if (file_exists($wpath)) {
                unlink($wpath);
            }
            # Always make a screen size for non-JPEG extensions regardless of actual image size
            # This is because the original file itself is not suitable for full screen preview, as it is with JPEG files.
            #
            # Always make preview sizes for smaller file sizes.
            #
            # Always make pre/thm/col sizes regardless of source image size.
            if ($id == "hpr" && !($extension == "jpg" || $extension == "jpeg") || $id == "scr" && !($extension == "jpg" || $extension == "jpeg") || $sw > $tw || $sh > $th || $id == "pre" || $id == "thm" || $id == "col" || in_array($id, $always_make_previews)) {
                # Debug
                debug("Generating preview size " . $ps[$n]["id"] . " to " . $path);
                # EXPERIMENTAL CODE TO USE EXISTING ICC PROFILE IF PRESENT
                global $icc_extraction, $icc_preview_profile, $icc_preview_options, $ffmpeg_supported_extensions;
                if ($icc_extraction) {
                    $iccpath = get_resource_path($ref, true, '', false, $extension) . '.icc';
                    if (!file_exists($iccpath) && !isset($iccfound) && $extension != "pdf" && !in_array($extension, $ffmpeg_supported_extensions)) {
                        // extracted profile doesn't exist. Try extracting.
                        if (extract_icc_profile($ref, $extension)) {
                            $iccfound = true;
                        } else {
                            $iccfound = false;
                        }
                    }
                }
                if ($icc_extraction && file_exists($iccpath) && !$icc_transform_complete) {
                    // we have an extracted ICC profile, so use it as source
                    $targetprofile = dirname(__FILE__) . '/../iccprofiles/' . $icc_preview_profile;
                    $profile = " -strip -profile {$iccpath} {$icc_preview_options} -profile {$targetprofile} -strip ";
                    // consider ICC transformation complete, if one of the sizes has been rendered that will be used for the smaller sizes
                    if ($id == 'hpr' || $id == 'lpr' || $id == 'scr') {
                        $icc_transform_complete = true;
                    }
                } else {
                    // use existing strategy for color profiles
                    # Preserve colour profiles? (omit for smaller sizes)
                    if ($imagemagick_preserve_profiles && $id != "thm" && $id != "col" && $id != "pre" && $id != "scr") {
                        $profile = "";
                    } else {
                        if (!empty($default_icc_file)) {
                            $profile = "-profile {$default_icc_file} ";
                        } else {
                            # By default, strip the colour profiles ('+' is remove the profile, confusingly)
                            $profile = "-strip -colorspace " . $imagemagick_colorspace;
                        }
                    }
                }
                $runcommand = $command . " " . ($extension != "png" && $extension != "gif" ? " +matte {$profile} " : "") . " -resize " . $tw . "x" . $th . "\">\" " . escapeshellarg($path);
                if (!hook("imagepskipthumb")) {
                    $output = run_command($runcommand);
                    $created_count++;
                    # if this is the first file generated for non-ingested resources check rotation
                    if ($autorotate_no_ingest && $created_count == 1 && !$ingested) {
                        # first preview created for non-ingested file...auto-rotate
                        if ($id == "thm" || $id == "col" || $id == "pre" || $id == "scr") {
                            AutoRotateImage($path, $ref);
                        } else {
                            AutoRotateImage($path);
                        }
                    }
                }
                // checkerboard
                if ($extension == "png" || $extension == "gif") {
                    global $transparency_background;
                    $transparencyreal = dirname(__FILE__) . "/../" . $transparency_background;
                    $wait = run_command(str_replace("identify", "composite", $identify_fullpath) . "  -compose Dst_Over -tile " . escapeshellarg($transparencyreal) . " " . escapeshellarg($path) . " " . escapeshellarg(str_replace($extension, "jpg", $path)), true);
                    unlink($path);
                    $path = str_replace($extension, "jpg", $path);
                }
                //echo $runcommand."<br /><br/>";
                # echo $runcommand."<br>\n";
                # Add a watermarked image too?
                global $watermark;
                if (!hook("replacewatermarkcreation", "", array($ref, $ps, $n, $alternative))) {
                    if ($alternative == -1 && isset($watermark) && ($ps[$n]["internal"] == 1 || $ps[$n]["allow_preview"] == 1)) {
                        $wmpath = get_resource_path($ref, true, $ps[$n]["id"], false, "jpg", -1, 1, true);
                        if (file_exists($wmpath)) {
                            unlink($wmpath);
                        }
                        $watermarkreal = dirname(__FILE__) . "/../" . $watermark;
                        $runcommand = $command . " +matte {$profile} -resize " . $tw . "x" . $th . "\">\" -tile " . escapeshellarg($watermarkreal) . " -draw \"rectangle 0,0 {$tw},{$th}\" " . escapeshellarg($wmpath);
                        // alternate command for png/gif using the path from above, and omitting resizing
                        if ($extension == "png" || $extension == "gif") {
                            $runcommand = $convert_fullpath . ' ' . escapeshellarg($path) . ($extension != "png" && $extension != "gif" ? '[0] +matte ' : '') . $flatten . ' -quality ' . $imagemagick_quality . " -tile " . escapeshellarg($watermarkreal) . " -draw \"rectangle 0,0 {$tw},{$th}\" " . escapeshellarg($wmpath);
                        }
                        #die($runcommand);
                        $output = run_command($runcommand);
                        //echo $runcommand."</br>";
                    }
                }
                // end hook replacewatermarkcreation
            }
        }
        # For the thumbnail image, call extract_mean_colour() to save the colour/size information
        $target = @imagecreatefromjpeg(get_resource_path($ref, true, "thm", false, "jpg", -1, 1, false, "", $alternative));
        if ($target && $alternative == -1) {
            extract_mean_colour($target, $ref);
            # flag database so a thumbnail appears on the site
            sql_query("update resource set has_image=1,preview_extension='jpg',preview_attempts=0,file_modified=now() where ref='{$ref}'");
        } else {
            if (!$target) {
                sql_query("update resource set preview_attempts=ifnull(preview_attempts,0) + 1 where ref='{$ref}'");
            }
        }
        return true;
    } else {
        return false;
    }
}
예제 #3
0
function create_previews_using_im($ref, $thumbonly = false, $extension = "jpg", $previewonly = false, $previewbased = false, $alternative = -1)
{
    global $imagemagick_path, $imagemagick_preserve_profiles, $imagemagick_quality;
    $icc_transform_complete = false;
    debug("create_previews_using_im(ref={$ref},thumbonly={$thumbonly},extension={$extension},previewonly={$previewonly},previewbased={$previewbased},alternative={$alternative})");
    if (isset($imagemagick_path)) {
        # ----------------------------------------
        # Use ImageMagick to perform the resize
        # ----------------------------------------
        # For resource $ref, (re)create the various preview sizes listed in the table preview_sizes
        # Set thumbonly=true to (re)generate thumbnails only.
        if ($previewbased) {
            $file = get_resource_path($ref, true, "lpr", false, "jpg", -1, 1, false, "");
            if (!file_exists($file)) {
                $file = get_resource_path($ref, true, "scr", false, "jpg", -1, 1, false, "");
                if (!file_exists($file)) {
                    $file = get_resource_path($ref, true, "pre", false, "jpg", -1, 1, false, "");
                }
            }
        } else {
            if (!$previewonly) {
                $file = get_resource_path($ref, true, "", false, $extension, -1, 1, false, "", $alternative);
            } else {
                # We're generating based on a new preview (scr) image.
                $file = get_resource_path($ref, true, "tmp", false, "jpg");
            }
        }
        $hpr_path = get_resource_path($ref, true, "hpr", false, "jpg", -1, 1, false, "", $alternative);
        if (file_exists($hpr_path) && !$previewbased) {
            unlink($hpr_path);
        }
        $lpr_path = get_resource_path($ref, true, "lpr", false, "jpg", -1, 1, false, "", $alternative);
        if (file_exists($lpr_path) && !$previewbased) {
            unlink($lpr_path);
        }
        $scr_path = get_resource_path($ref, true, "scr", false, "jpg", -1, 1, false, "", $alternative);
        if (file_exists($scr_path) && !$previewbased) {
            unlink($scr_path);
        }
        $scr_wm_path = get_resource_path($ref, true, "scr", false, "jpg", -1, 1, true, "", $alternative);
        if (file_exists($scr_wm_path) && !$previewbased) {
            unlink($scr_wm_path);
        }
        $prefix = '';
        # Camera RAW images need prefix
        if (preg_match('/^(dng|nef|x3f|cr2|crw|mrw|orf|raf|dcr)$/i', $extension, $rawext)) {
            $prefix = $rawext[0] . ':';
        }
        # Locate imagemagick.
        $identify_fullpath = get_utility_path("im-identify");
        if ($identify_fullpath == false) {
            exit("Could not find ImageMagick 'identify' utility at location '{$imagemagick_path}'.");
        }
        # Get image's dimensions.
        $identcommand = $identify_fullpath . ' -format %wx%h ' . escapeshellarg($prefix . $file) . '[0]';
        $identoutput = run_command($identcommand);
        preg_match('/^([0-9]+)x([0-9]+)$/ims', $identoutput, $smatches);
        if (@(list(, $sw, $sh) = $smatches) === false) {
            return false;
        }
        $sizes = "";
        if ($thumbonly) {
            $sizes = " where id='thm' or id='col'";
        }
        if ($previewonly) {
            $sizes = " where id='thm' or id='col' or id='pre' or id='scr'";
        }
        $ps = sql_query("select * from preview_size {$sizes} order by width desc, height desc");
        for ($n = 0; $n < count($ps); $n++) {
            # If we've already made the LPR or SCR then use those for the remaining previews.
            # As we start with the large and move to the small, this will speed things up.
            if (file_exists($hpr_path)) {
                $file = $hpr_path;
            }
            if (file_exists($lpr_path)) {
                $file = $lpr_path;
            }
            if (file_exists($scr_path)) {
                $file = $scr_path;
            }
            # Locate imagemagick.
            $convert_fullpath = get_utility_path("im-convert");
            if ($convert_fullpath == false) {
                exit("Could not find ImageMagick 'convert' utility at location '{$imagemagick_path}'.");
            }
            if ($prefix == "cr2:" || $prefix == "nef:") {
                $flatten = "";
            } else {
                $flatten = "-flatten";
            }
            $command = $convert_fullpath . ' ' . escapeshellarg($file) . '[0] +matte ' . $flatten . ' -quality ' . $imagemagick_quality;
            # fetch target width and height
            $tw = $ps[$n]["width"];
            $th = $ps[$n]["height"];
            $id = $ps[$n]["id"];
            # Debug
            debug("Contemplating " . $ps[$n]["id"] . " (sw={$sw}, tw={$tw}, sh={$sh}, th={$th}, extension={$extension})");
            # Always make a screen size for non-JPEG extensions regardless of actual image size
            # This is because the original file itself is not suitable for full screen preview, as it is with JPEG files.
            #
            # Always make preview sizes for smaller file sizes.
            #
            # Always make pre/thm/col sizes regardless of source image size.
            if ($id == "hpr" && !($extension == "jpg" || $extension == "jpeg") || $id == "scr" && !($extension == "jpg" || $extension == "jpeg") || $sw > $tw || $sh > $th || $id == "pre" || $id == "thm" || $id == "col") {
                # Find the target path
                $path = get_resource_path($ref, true, $ps[$n]["id"], false, "jpg", -1, 1, false, "", $alternative);
                # Debug
                debug("Generating preview size " . $ps[$n]["id"] . " to " . $path);
                # Delete any file at the target path. Unless using the previewbased option, in which case we need it.
                if (!hook("imagepskipdel")) {
                    if (!$previewbased) {
                        if (file_exists($path)) {
                            unlink($path);
                        }
                    }
                }
                # Also try the watermarked version.
                $wpath = get_resource_path($ref, true, $ps[$n]["id"], false, "jpg", -1, 1, true, "", $alternative);
                if (file_exists($wpath)) {
                    unlink($wpath);
                }
                # EXPERIMENTAL CODE TO USE EXISTING ICC PROFILE IF PRESENT
                global $icc_extraction, $icc_preview_profile, $icc_preview_options, $ffmpeg_supported_extensions;
                if ($icc_extraction) {
                    $iccpath = get_resource_path($ref, true, '', false, $extension . '.icc');
                    if (!file_exists($iccpath) && !isset($iccfound) && $extension != "pdf" && !in_array($extension, $ffmpeg_supported_extensions)) {
                        // extracted profile doesn't exist. Try extracting.
                        if (extract_icc_profile($ref, $extension)) {
                            $iccfound = true;
                        } else {
                            $iccfound = false;
                        }
                    }
                }
                if ($icc_extraction && file_exists($iccpath) && !$icc_transform_complete) {
                    // we have an extracted ICC profile, so use it as source
                    $targetprofile = dirname(__FILE__) . '/../iccprofiles/' . $icc_preview_profile;
                    $profile = " +profile \"*\" -profile {$iccpath} {$icc_preview_options} -profile {$targetprofile} +profile \"*\" ";
                    $icc_transform_complete = true;
                } else {
                    // use existing strategy for color profiles
                    # Preserve colour profiles? (omit for smaller sizes)
                    $profile = "+profile \"*\" -colorspace sRGB";
                    # By default, strip the colour profiles ('+' is remove the profile, confusingly)
                    if ($imagemagick_preserve_profiles && $id != "thm" && $id != "col" && $id != "pre" && $id != "scr") {
                        $profile = "";
                    }
                }
                $runcommand = $command . " +matte {$profile} -resize " . $tw . "x" . $th . "\">\" " . escapeshellarg($path);
                if (!hook("imagepskipthumb")) {
                    $output = run_command($runcommand);
                }
                //echo $runcommand."<br /><br/>";
                # echo $runcommand."<br>\n";
                # Add a watermarked image too?
                global $watermark;
                if ($alternative == -1 && isset($watermark) && ($ps[$n]["internal"] == 1 || $ps[$n]["allow_preview"] == 1)) {
                    $path = get_resource_path($ref, true, $ps[$n]["id"], false, "", -1, 1, true);
                    if (file_exists($path)) {
                        unlink($path);
                    }
                    $watermarkreal = dirname(__FILE__) . "/../" . $watermark;
                    $runcommand = $command . " +matte {$profile} -resize " . $tw . "x" . $th . "\">\" -tile " . escapeshellarg($watermarkreal) . " -draw \"rectangle 0,0 {$tw},{$th}\" " . escapeshellarg($path);
                    #die($runcommand);
                    $output = run_command($runcommand);
                }
            }
        }
        # For the thumbnail image, call extract_mean_colour() to save the colour/size information
        $target = @imagecreatefromjpeg(get_resource_path($ref, true, "thm", false, "jpg", -1, 1, false, "", $alternative));
        if ($target && $alternative == -1) {
            extract_mean_colour($target, $ref);
            # flag database so a thumbnail appears on the site
            sql_query("update resource set has_image=1,preview_extension='jpg',preview_attempts=0,file_modified=now() where ref='{$ref}'");
        } else {
            if (!$target) {
                $preview_attempts = sql_value("select preview_attempts as value from resource where ref=" . $ref, 0);
                sql_query("update resource set preview_attempts=" . ($preview_attempts + 1) . " where ref='{$ref}'");
            }
        }
        return true;
    } else {
        return false;
    }
}