# Find out the path to the original file.
                $copy_path = get_resource_path($copy, true, "", true, "pdf");
                # Extract this one page to a new resource.
                $gscommand2 = $ghostscript_fullpath . " -dBATCH -dNOPAUSE -sDEVICE=pdfwrite -sOutputFile=" . escapeshellarg($copy_path) . "  -dFirstPage=" . $n . " -dLastPage=" . $n . " " . escapeshellarg($file);
                $output = run_command($gscommand2);
                # Update the file extension
                sql_query("update resource set file_extension='pdf' where ref='{$copy}'");
                # Create preview for the page.
                $pdf_split_pages_to_resources = false;
                # So we don't get stuck in a loop creating split pages for the single page PDFs.
                create_previews($copy, false, "pdf");
                $pdf_split_pages_to_resources = true;
            }
        }
        // set page number
        if (isset($pagecount) && $alternative != -1) {
            sql_query("update resource_alt_files set page_count={$pagecount} where ref={$alternative}");
        } else {
            if (isset($pagecount)) {
                sql_query("update resource_dimensions set page_count={$pagecount} where resource={$ref}");
            }
        }
    } else {
        # Not a PDF file, so single extraction only.
        create_previews_using_im($ref, false, $extension, $previewonly, false, $alternative);
    }
}
# If a file has been created, generate previews just as if a JPG was uploaded.
if (isset($newfile)) {
    create_previews($ref, false, "jpg", $previewonly, false, $alternative);
}
function create_previews($ref, $thumbonly = false, $extension = "jpg", $previewonly = false, $previewbased = false, $alternative = -1, $ignoremaxsize = false, $ingested = false)
{
    global $keep_for_hpr, $imagemagick_path, $preview_generate_max_file_size, $autorotate_no_ingest;
    // keep_for_hpr will be set to true if necessary in preview_preprocessing.php to indicate that an intermediate jpg can serve as the hpr.
    // otherwise when the file extension is a jpg it's assumed no hpr is needed.
    # Debug
    debug("create_previews(ref={$ref},thumbonly={$thumbonly},extension={$extension},previewonly={$previewonly},previewbased={$previewbased},alternative={$alternative},ingested={$ingested})");
    if (!$previewonly) {
        // make sure the extension is the same as the original so checksums aren't done for previews
        $o_ext = sql_value("select file_extension value from resource where ref={$ref}", "");
        if ($extension == $o_ext) {
            debug("create_previews - generate checksum for {$ref}");
            generate_file_checksum($ref, $extension);
        }
    }
    # first reset preview tweaks to 0
    sql_query("update resource set preview_tweaks = '0|1' where ref = '{$ref}'");
    // for compatibility with transform plugin, remove any
    // transform previews for this resource when regenerating previews
    $tpdir = get_temp_dir() . "/transform_plugin";
    if (is_dir($tpdir) && file_exists("{$tpdir}/pre_{$ref}.jpg")) {
        unlink("{$tpdir}/pre_{$ref}.jpg");
    }
    # pages/tools/update_previews.php?previewbased=true
    # use previewbased to avoid touching original files (to preserve manually-uploaded preview images
    # when regenerating previews (i.e. for watermarks)
    if ($previewbased || $autorotate_no_ingest && !$ingested) {
        $file = get_resource_path($ref, true, "lpr", false, "jpg", -1, 1, false, "", $alternative);
        if (!file_exists($file)) {
            $file = get_resource_path($ref, true, "scr", false, "jpg", -1, 1, false, "", $alternative);
            if (!file_exists($file)) {
                $file = get_resource_path($ref, true, "pre", false, "jpg", -1, 1, false, "", $alternative);
                if (!file_exists($file) && $autorotate_no_ingest && !$ingested) {
                    $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");
        }
    }
    # Debug
    debug("File source is {$file}");
    # Make sure the file exists, if not update preview_attempts so that we don't keep trying to generate a preview
    if (!file_exists($file)) {
        sql_query("update resource set preview_attempts=ifnull(preview_attempts,0) + 1 where ref='{$ref}'");
        return false;
    }
    # If configured, make sure the file is within the size limit for preview generation
    if (isset($preview_generate_max_file_size) && !$ignoremaxsize) {
        $filesize = filesize_unlimited($file) / (1024 * 1024);
        # Get filesize in MB
        if ($filesize > $preview_generate_max_file_size) {
            return false;
        }
    }
    # 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;
    }
    # Handle alternative image file generation.
    global $image_alternatives;
    if (isset($image_alternatives) && $alternative == -1) {
        for ($n = 0; $n < count($image_alternatives); $n++) {
            $exts = explode(",", $image_alternatives[$n]["source_extensions"]);
            if (in_array($extension, $exts)) {
                # Remove any existing alternative file(s) with this name.
                $existing = sql_query("select ref from resource_alt_files where resource='{$ref}' and name='" . escape_check($image_alternatives[$n]["name"]) . "'");
                for ($m = 0; $m < count($existing); $m++) {
                    delete_alternative_file($ref, $existing[$m]["ref"]);
                }
                # Create the alternative file.
                $aref = add_alternative_file($ref, $image_alternatives[$n]["name"]);
                $apath = get_resource_path($ref, true, "", true, $image_alternatives[$n]["target_extension"], -1, 1, false, "", $aref);
                $source_profile = '';
                if ($image_alternatives[$n]["icc"] === true) {
                    $iccpath = get_resource_path($ref, true, '', false, $extension) . '.icc';
                    global $icc_extraction;
                    global $ffmpeg_supported_extensions;
                    if (!file_exists($iccpath) && $extension != "pdf" && !in_array($extension, $ffmpeg_supported_extensions)) {
                        // extracted profile doesn't exist. Try extracting.
                        extract_icc_profile($ref, $extension);
                    }
                    if (file_exists($iccpath)) {
                        $source_profile = ' -strip -profile ' . $iccpath;
                    }
                }
                # Process the image
                $version = get_imagemagick_version();
                if ($version[0] > 5 || $version[0] == 5 && $version[1] > 5 || $version[0] == 5 && $version[1] == 5 && $version[2] > 7) {
                    // Use the new imagemagick command syntax (file then parameters)
                    $command = $convert_fullpath . ' ' . escapeshellarg($file) . ($extension == 'psd' ? '[0] +matte' : '') . $source_profile . ' ' . $image_alternatives[$n]['params'] . ' ' . escapeshellarg($apath);
                } else {
                    // Use the old imagemagick command syntax (parameters then file)
                    $command = $convert_fullpath . $source_profile . " " . $image_alternatives[$n]["params"] . " " . escapeshellarg($file) . " " . escapeshellarg($apath);
                }
                $output = run_command($command);
                if (file_exists($apath)) {
                    # Update the database with the new file details.
                    $file_size = filesize_unlimited($apath);
                    sql_query("update resource_alt_files set file_name='" . escape_check($image_alternatives[$n]["filename"] . "." . $image_alternatives[$n]["target_extension"]) . "',file_extension='" . escape_check($image_alternatives[$n]["target_extension"]) . "',file_size='" . $file_size . "',creation_date=now() where ref='{$aref}'");
                }
            }
        }
    }
    if ($extension == "jpg" || $extension == "jpeg" || $extension == "png" || $extension == "gif") {
        if (isset($imagemagick_path)) {
            create_previews_using_im($ref, $thumbonly, $extension, $previewonly, $previewbased, $alternative, $ingested);
        } else {
            # ----------------------------------------
            # Use the GD library to perform the resize
            # ----------------------------------------
            # For resource $ref, (re)create the various preview sizes listed in the table preview_sizes
            # Only create previews where the target size IS LESS THAN OR EQUAL TO the source size.
            # Set thumbonly=true to (re)generate thumbnails only.
            $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'";
            }
            # fetch source image size, if we fail, exit this function (file not an image, or file not a valid jpg/png/gif).
            if ((list($sw, $sh) = @getimagesize($file)) === false) {
                return false;
            }
            $ps = sql_query("select * from preview_size {$sizes}");
            for ($n = 0; $n < count($ps); $n++) {
                # fetch target width and height
                $tw = $ps[$n]["width"];
                $th = $ps[$n]["height"];
                $id = $ps[$n]["id"];
                # Find the target path
                $path = get_resource_path($ref, true, $ps[$n]["id"], false, "jpg", -1, 1, false, "", $alternative);
                if (file_exists($path) && !$previewbased) {
                    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);
                }
                # only create previews where the target size IS LESS THAN OR EQUAL TO the source size.
                # or when producing a small thumbnail (to make sure we have that as a minimum)
                if ($sw > $tw || $sh > $th || $id == "thm" || $id == "col") {
                    # Calculate width and height.
                    if ($sw > $sh) {
                        $ratio = $tw / $sw;
                    } else {
                        $ratio = $th / $sh;
                    }
                    # Portrait
                    $tw = floor($sw * $ratio);
                    $th = floor($sh * $ratio);
                    # ----------------------------------------
                    # Use the GD library to perform the resize
                    # ----------------------------------------
                    $target = imagecreatetruecolor($tw, $th);
                    if ($extension == "png") {
                        $source = @imagecreatefrompng($file);
                        if ($source === false) {
                            return false;
                        }
                    } elseif ($extension == "gif") {
                        $source = @imagecreatefromgif($file);
                        if ($source === false) {
                            return false;
                        }
                    } else {
                        $source = @imagecreatefromjpeg($file);
                        if ($source === false) {
                            return false;
                        }
                    }
                    imagecopyresampled($target, $source, 0, 0, 0, 0, $tw, $th, $sw, $sh);
                    imagejpeg($target, $path, 90);
                    if ($ps[$n]["id"] == "thm") {
                        extract_mean_colour($target, $ref);
                    }
                    imagedestroy($target);
                } elseif ($id == "pre" || $id == "thm" || $id == "col") {
                    # If the source is smaller than the pre/thm/col, we still need these sizes; just copy the file
                    copy($file, get_resource_path($ref, true, $id, false, $extension, -1, 1, false, "", $alternative));
                    if ($id == "thm") {
                        sql_query("update resource set thumb_width='{$sw}',thumb_height='{$sh}' where ref='{$ref}'");
                    }
                }
            }
            # flag database so a thumbnail appears on the site
            if ($alternative == -1) {
                sql_query("update resource set has_image=1,preview_extension='jpg',preview_attempts=0,file_modified=now() where ref='{$ref}'");
            }
        }
    } else {
        # If using ImageMagick, call preview_preprocessing.php which makes use of ImageMagick and other tools
        # to attempt to extract a preview.
        global $no_preview_extensions;
        if (isset($imagemagick_path) && !in_array(strtolower($extension), $no_preview_extensions)) {
            include dirname(__FILE__) . "/preview_preprocessing.php";
        }
    }
    return true;
}
  ini_set('max_execution_time', 1200);
  $resourcetype = $argv[1];
  $ref = trim($argv[2]);
  $extension = $argv[3];
  $attempts = $argv[4];
    if($resourcetype == 3 || $resourcetype == 4){
        $cp = create_previews($ref,$thumbonly=true,$extension);
        if($cp == true && $resourcetype == 3){
            $thumb_path = get_resource_path($ref,true,"thm",false,"jpg");
            $im_fullpath = get_utility_path("im-composite");
            $command = $im_fullpath . " -gravity center /var/www/gfx/video-overlay.png " . escapeshellarg($thumb_path) . " : " . escapeshellarg($thumb_path) . " 2>&1";
            $report_original = run_command($command);
        }
    }else{
        //create preview files in that directory
        $cp = create_previews_using_im($ref,false,$extension);
    }
    if ($cp == true){
        sql_query("UPDATE resource SET is_transcoding = 0 WHERE ref = $ref");

        //send result to elast search now that we have preview
        $results=array();
        $results[] = get_resource_data($ref,false);
        $thumb_path = array("thumbnail"=>$baseurl.str_replace("/var/www/include/..","",get_resource_path($ref,true,"thm",false,"jpg")));
        $newresults[] = array_merge($thumb_path,$results[0]);
        $results=$newresults;
        $resourcetype=get_resource_type_name($results[0]['resource_type']);
        if($resourcetype == "Audio"){
            $prv_path = array("preview"=>$baseurl.str_replace("/var/www/include/..","",get_resource_path($ref, true, "", false, "mp3")));
        }else if($resourcetype == "Video"){
            $prv_path = array("preview"=>$baseurl.str_replace("/var/www/include/..","",get_resource_path($ref, true, "pre", false, "mp4")));
        sql_query("update resource set file_extension = '" . $file_extension . "', field12 = now(), title ='".escape_check($filename)."'WHERE ref = '" . $ref . "'");
        $data['success']=true;
        $data['status']="success";
        $data['error']=false;
        $data['textStatus']= $file . " - Successfully Added";
        $data['ref']=$ref;
    }else{
        $data['error']=true;
        $data['textStatus']="could not move file to tmp";
    }
    if($resource_type==2){
        extract_text($ref,$file_extension);
    }
    if($resource_type != 2 && $resource_type != 3 && $resource_type != 4){
        //create preview files in that directory
        create_previews_using_im($ref,false,$file_extension);
        $nothumb = false;
    }else{
        $nothumb = true;
        sql_query("UPDATE resource SET is_transcoding = 1 WHERE ref = $ref");
        //Process previews in the backgrond and continue
        $attempts = 1;
        $command = "/usr/bin/php -q -f /var/www/plugins/mia_upload/pages/background_previews.php $resource_type $ref $file_extension $attempts";
        exec("$command > /dev/null &", $arrOutput);
    }
    savetoelastic($ref);
    echo(json_encode($data));
    ob_flush();
    flush();
}else{
    echo('Please Add a File');
function create_previews($ref, $thumbonly = false, $extension = "jpg", $previewonly = false, $previewbased = false, $alternative = -1)
{
    global $imagemagick_path, $preview_generate_max_file_size;
    # Debug
    debug("create_previews(ref={$ref},thumbonly={$thumbonly},extension={$extension},previewonly={$previewonly},previewbased={$previewbased},alternative={$alternative})");
    # File checksum (experimental) - disabled for now
    if (!$previewonly) {
        generate_file_checksum($ref, $extension);
    }
    # first reset preview tweaks to 0
    sql_query("update resource set preview_tweaks = '0|1' where ref = '{$ref}'");
    # pages/tools/update_previews.php?previewbased=true
    # use previewbased to avoid touching original files (to preserve manually-uploaded preview images
    # when regenerating previews (i.e. for watermarks)
    if ($previewbased) {
        $file = get_resource_path($ref, true, "lpr", false, "jpg", -1, 1, false, "", $alternative);
        if (!file_exists($file)) {
            $file = get_resource_path($ref, true, "scr", false, "jpg", -1, 1, false, "", $alternative);
            if (!file_exists($file)) {
                $file = get_resource_path($ref, true, "pre", false, "jpg", -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");
        }
    }
    # Debug
    debug("File source is {$file}");
    # Make sure the file exists
    if (!file_exists($file)) {
        return false;
    }
    # If configured, make sure the file is within the size limit for preview generation
    if (isset($preview_generate_max_file_size)) {
        $filesize = filesize_unlimited($file) / (1024 * 1024);
        # Get filesize in MB
        if ($filesize > $preview_generate_max_file_size) {
            return false;
        }
    }
    # Locate imagemagick.
    $convert_fullpath = get_utility_path("im-convert");
    if ($convert_fullpath == false) {
        exit("Could not find ImageMagick 'convert' utility at location '{$imagemagick_path}'");
    }
    # Handle alternative image file generation.
    global $image_alternatives;
    if (isset($image_alternatives) && $alternative == -1) {
        for ($n = 0; $n < count($image_alternatives); $n++) {
            $exts = explode(",", $image_alternatives[$n]["source_extensions"]);
            if (in_array($extension, $exts)) {
                # Remove any existing alternative file(s) with this name.
                $existing = sql_query("select ref from resource_alt_files where resource='{$ref}' and name='" . escape_check($image_alternatives[$n]["name"]) . "'");
                for ($m = 0; $m < count($existing); $m++) {
                    delete_alternative_file($ref, $existing[$m]["ref"]);
                }
                # Create the alternative file.
                $aref = add_alternative_file($ref, $image_alternatives[$n]["name"]);
                $apath = get_resource_path($ref, true, "", true, $image_alternatives[$n]["target_extension"], -1, 1, false, "", $aref);
                # Process the image
                $command = $convert_fullpath . " " . $image_alternatives[$n]["params"] . " " . escapeshellarg($file) . " " . escapeshellarg($apath);
                $output = run_command($command);
                if (file_exists($apath)) {
                    # Update the database with the new file details.
                    $file_size = filesize_unlimited($apath);
                    sql_query("update resource_alt_files set file_name='" . escape_check($image_alternatives[$n]["filename"] . "." . $image_alternatives[$n]["target_extension"]) . "',file_extension='" . escape_check($image_alternatives[$n]["target_extension"]) . "',file_size='" . $file_size . "',creation_date=now() where ref='{$aref}'");
                }
            }
        }
    }
    if ($extension == "jpg" || $extension == "jpeg" || $extension == "png" || $extension == "gif") {
        if (isset($imagemagick_path)) {
            create_previews_using_im($ref, $thumbonly, $extension, $previewonly, $previewbased, $alternative);
        } else {
            # ----------------------------------------
            # Use the GD library to perform the resize
            # ----------------------------------------
            # For resource $ref, (re)create the various preview sizes listed in the table preview_sizes
            # Only create previews where the target size IS LESS THAN OR EQUAL TO the source size.
            # Set thumbonly=true to (re)generate thumbnails only.
            $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'";
            }
            # fetch source image size, if we fail, exit this function (file not an image, or file not a valid jpg/png/gif).
            if ((list($sw, $sh) = @getimagesize($file)) === false) {
                return false;
            }
            $ps = sql_query("select * from preview_size {$sizes}");
            for ($n = 0; $n < count($ps); $n++) {
                # fetch target width and height
                $tw = $ps[$n]["width"];
                $th = $ps[$n]["height"];
                $id = $ps[$n]["id"];
                # Find the target path
                $path = get_resource_path($ref, true, $ps[$n]["id"], false, "jpg", -1, 1, false, "", $alternative);
                if (file_exists($path) && !$previewbased) {
                    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);
                }
                # only create previews where the target size IS LESS THAN OR EQUAL TO the source size.
                # or when producing a small thumbnail (to make sure we have that as a minimum)
                if ($sw > $tw || $sh > $th || $id == "thm" || $id == "col") {
                    # Calculate width and height.
                    if ($sw > $sh) {
                        $ratio = $tw / $sw;
                    } else {
                        $ratio = $th / $sh;
                    }
                    # Portrait
                    $tw = floor($sw * $ratio);
                    $th = floor($sh * $ratio);
                    # ----------------------------------------
                    # Use the GD library to perform the resize
                    # ----------------------------------------
                    $target = imagecreatetruecolor($tw, $th);
                    if ($extension == "png") {
                        $source = @imagecreatefrompng($file);
                        if ($source === false) {
                            return false;
                        }
                    } elseif ($extension == "gif") {
                        $source = @imagecreatefromgif($file);
                        if ($source === false) {
                            return false;
                        }
                    } else {
                        $source = @imagecreatefromjpeg($file);
                        if ($source === false) {
                            return false;
                        }
                    }
                    imagecopyresampled($target, $source, 0, 0, 0, 0, $tw, $th, $sw, $sh);
                    imagejpeg($target, $path, 90);
                    if ($ps[$n]["id"] == "thm") {
                        extract_mean_colour($target, $ref);
                    }
                    imagedestroy($target);
                } elseif ($id == "pre" || $id == "thm" || $id == "col") {
                    # If the source is smaller than the pre/thm/col, we still need these sizes; just copy the file
                    copy($file, get_resource_path($ref, true, $id, false, $extension, -1, 1, false, "", $alternative));
                    if ($id == "thm") {
                        sql_query("update resource set thumb_width='{$sw}',thumb_height='{$sh}' where ref='{$ref}'");
                    }
                }
            }
            # flag database so a thumbnail appears on the site
            if ($alternative == -1) {
                sql_query("update resource set has_image=1,preview_extension='jpg',preview_attempts=0,file_modified=now() where ref='{$ref}'");
            }
        }
    } else {
        # If using ImageMagick, call preview_preprocessing.php which makes use of ImageMagick and other tools
        # to attempt to extract a preview.
        global $no_preview_extensions;
        if (isset($imagemagick_path) && !in_array(strtolower($extension), $no_preview_extensions)) {
            include dirname(__FILE__) . "/preview_preprocessing.php";
        }
    }
    return true;
}