Exemplo n.º 1
0
 $extension = strtolower($path_parts['extension']);
 $filepath = get_resource_path($ref, true, "", true, $extension);
 $collection = getvalescaped('collection', "", true);
 $result = move_uploaded_file($_FILES['userfile']['tmp_name'], $filepath);
 $wait = sql_query("update resource set file_extension='{$extension}',preview_extension='jpg',file_modified=now() ,has_image=0 where ref='{$ref}'");
 # Store original filename in field, if set
 global $filename_field;
 if (isset($filename_field)) {
     $wait = update_field($ref, $filename_field, $_FILES['userfile']['name']);
 }
 // extract metadata
 $wait = extract_exif_comment($ref, $extension);
 $resource = get_resource_data($ref);
 //create previews
 if ($camera_autorotation) {
     AutoRotateImage($filepath);
 }
 $wait = create_previews($ref, false, $extension);
 // add resource to collection
 if ($collection != "") {
     $collection_exists = sql_value("select name value from collection where ref='" . escape_check($collection) . "'", "");
     if ($collection_exists != "") {
         if (!add_resource_to_collection($ref, $collection)) {
             header("HTTP/1.0 403 Forbidden.");
             echo "HTTP/1.0 403 Forbidden. Collection is not writable by this user.\n";
             exit;
         }
     } else {
         header("HTTP/1.0 403 Forbidden.");
         echo "HTTP/1.0 403 Forbidden. Collection does not exist.\n";
         exit;
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;
    }
}
function update_resource($r, $path, $type, $title, $ingest = false, $createPreviews = true)
{
    # Update the resource with the file at the given path
    # Note that the file will be used at it's present location and will not be copied.
    global $syncdir, $staticsync_prefer_embedded_title;
    update_resource_type($r, $type);
    # Work out extension based on path
    $extension = explode(".", $path);
    if (count($extension) > 1) {
        $extension = trim(strtolower(end($extension)));
    } else {
        //No extension
        $extension = "";
    }
    # file_path should only really be set to indicate a staticsync location. Otherwise, it should just be left blank.
    if ($ingest) {
        $file_path = "";
    } else {
        $file_path = escape_check($path);
    }
    # Store extension/data in the database
    sql_query("update resource set archive=0,file_path='" . $file_path . "',file_extension='{$extension}',preview_extension='{$extension}',file_modified=now() where ref='{$r}'");
    # Store original filename in field, if set
    if (!$ingest) {
        # This file remains in situ; store the full path in file_path to indicate that the file is stored remotely.
        global $filename_field;
        if (isset($filename_field)) {
            $s = explode("/", $path);
            $filename = end($s);
            update_field($r, $filename_field, $filename);
        }
    } else {
        # This file is being ingested. Store only the filename.
        $s = explode("/", $path);
        $filename = end($s);
        global $filename_field;
        if (isset($filename_field)) {
            update_field($r, $filename_field, $filename);
        }
        # Move the file
        global $syncdir;
        $destination = get_resource_path($r, true, "", true, $extension);
        $result = rename($syncdir . "/" . $path, $destination);
        if ($result === false) {
            # The rename failed. The file is possibly still being copied or uploaded and must be ignored on this pass.
            # Delete the resouce just created and return false.
            delete_resource($r);
            return false;
        }
        chmod($destination, 0777);
    }
    # generate title and extract embedded metadata
    # order depends on which title should be the default (embedded or generated)
    if ($staticsync_prefer_embedded_title) {
        update_field($r, 8, $title);
        extract_exif_comment($r, $extension);
    } else {
        extract_exif_comment($r, $extension);
        update_field($r, 8, $title);
    }
    # Ensure folder is created, then create previews.
    get_resource_path($r, false, "pre", true, $extension);
    if ($createPreviews) {
        # Attempt autorotation
        global $autorotate_ingest;
        if ($ingest && $autorotate_ingest) {
            AutoRotateImage($destination);
        }
        # Generate previews/thumbnails (if configured i.e if not completed by offline process 'create_previews.php')
        global $enable_thumbnail_creation_on_upload;
        if ($enable_thumbnail_creation_on_upload) {
            create_previews($r, false, $extension, false, false, -1, false, $ingest);
        }
    }
    # Pass back the newly created resource ID.
    return $r;
}
 function upload_file($ref, $no_exif = false, $revert = false, $autorotate = false)
 {
     hook("clearaltfiles", "", array($ref));
     // optional: clear alternative files before uploading new resource
     # revert is mainly for metadata reversion, removing all metadata and simulating a reupload of the file from scratch.
     hook("removeannotations");
     $exiftool_fullpath = get_utility_path("exiftool");
     # Process file upload for resource $ref
     if ($revert == true) {
         global $filename_field;
         $original_filename = get_data_by_field($ref, $filename_field);
         # Field 8 is used in a special way for staticsync, don't overwrite.
         $test_for_staticsync = get_resource_data($ref);
         if ($test_for_staticsync['file_path'] != "") {
             $staticsync_mod = " and resource_type_field != 8";
         } else {
             $staticsync_mod = "";
         }
         sql_query("delete from resource_data where resource={$ref} {$staticsync_mod}");
         sql_query("delete from resource_keyword where resource={$ref} {$staticsync_mod}");
         #clear 'joined' display fields which are based on metadata that is being deleted in a revert (original filename is reinserted later)
         $display_fields = get_resource_table_joins();
         if ($staticsync_mod != "") {
             $display_fields_new = array();
             for ($n = 0; $n < count($display_fields); $n++) {
                 if ($display_fields[$n] != 8) {
                     $display_fields_new[] = $display_fields[$n];
                 }
             }
             $display_fields = $display_fields_new;
         }
         $clear_fields = "";
         for ($x = 0; $x < count($display_fields); $x++) {
             $clear_fields .= "field" . $display_fields[$x] . "=''";
             if ($x < count($display_fields) - 1) {
                 $clear_fields .= ",";
             }
         }
         sql_query("update resource set " . $clear_fields . " where ref={$ref}");
         #also add the ref back into keywords:
         add_keyword_mappings($ref, $ref, -1);
         $extension = sql_value("select file_extension value from resource where ref={$ref}", "");
         $filename = get_resource_path($ref, true, "", false, $extension);
         $processfile['tmp_name'] = $filename;
     } else {
         # Work out which file has been posted
         if (isset($_FILES['userfile'])) {
             $processfile = $_FILES['userfile'];
         } elseif (isset($_FILES['Filedata'])) {
             $processfile = $_FILES['Filedata'];
         }
         # Java upload (at least) needs this
         # Plupload needs this
         if (isset($_REQUEST['name'])) {
             $filename = $_REQUEST['name'];
         } else {
             $filename = $processfile['name'];
         }
     }
     # Work out extension
     if (!isset($extension)) {
         # first try to get it from the filename
         $extension = explode(".", $filename);
         if (count($extension) > 1) {
             $extension = trim(strtolower($extension[count($extension) - 1]));
         } else {
             if ($exiftool_fullpath != false) {
                 $file_type_by_exiftool = run_command($exiftool_fullpath . " -filetype -s -s -s " . escapeshellarg($processfile['tmp_name']));
                 if (strlen($file_type_by_exiftool) > 0) {
                     $extension = str_replace(" ", "_", trim(strtolower($file_type_by_exiftool)));
                     $filename = $filename;
                 } else {
                     return false;
                 }
             } else {
                 return false;
             }
         }
     }
     # Banned extension?
     global $banned_extensions;
     if (in_array($extension, $banned_extensions)) {
         return false;
     }
     $status = "Please provide a file name.";
     $filepath = get_resource_path($ref, true, "", true, $extension);
     if (!$revert) {
         # Remove existing file, if present
         hook("beforeremoveexistingfile", "", array("resourceId" => $ref));
         $old_extension = sql_value("select file_extension value from resource where ref='{$ref}'", "");
         if ($old_extension != "") {
             $old_path = get_resource_path($ref, true, "", true, $old_extension);
             if (file_exists($old_path)) {
                 unlink($old_path);
             }
         }
         // also remove any existing extracted icc profiles
         $icc_path = get_resource_path($ref, true, "", true, $extension . '.icc');
         if (file_exists($icc_path)) {
             unlink($icc_path);
         }
         global $pdf_pages;
         $iccx = 0;
         // if there is a -0.icc page, run through and delete as many as necessary.
         $finished = false;
         $badicc_path = str_replace(".icc", "-{$iccx}.icc", $icc_path);
         while (!$finished) {
             if (file_exists($badicc_path)) {
                 unlink($badicc_path);
                 $iccx++;
                 $badicc_path = str_replace(".icc", "-{$iccx}.icc", $icc_path);
             } else {
                 $finished = true;
             }
         }
         $iccx = 0;
     }
     if (!$revert) {
         if ($filename != "") {
             global $jupload_alternative_upload_location, $plupload_upload_location;
             if (isset($plupload_upload_location)) {
                 # PLUpload - file was sent chunked and reassembled - use the reassembled file location
                 $result = rename($plupload_upload_location, $filepath);
             } elseif (isset($jupload_alternative_upload_location)) {
                 # JUpload - file was sent chunked and reassembled - use the reassembled file location
                 $result = rename($jupload_alternative_upload_location, $filepath);
             } else {
                 # Standard upload.
                 if (!$revert) {
                     $result = move_uploaded_file($processfile['tmp_name'], $filepath);
                 } else {
                     $result = true;
                 }
             }
             if ($result == false) {
                 $status = "File upload error. Please check the size of the file you are trying to upload.";
                 return false;
             } else {
                 global $camera_autorotation;
                 global $ffmpeg_audio_extensions;
                 if ($camera_autorotation) {
                     if ($autorotate && !in_array($extension, $ffmpeg_audio_extensions)) {
                         AutoRotateImage($filepath);
                     }
                 }
                 chmod($filepath, 0777);
                 global $icc_extraction;
                 global $ffmpeg_supported_extensions;
                 if ($icc_extraction && $extension != "pdf" && !in_array($extension, $ffmpeg_supported_extensions)) {
                     extract_icc_profile($ref, $extension);
                 }
                 $status = "Your file has been uploaded.";
             }
         }
     }
     # Store extension in the database and update file modified time.
     if ($revert) {
         $has_image = "";
     } else {
         $has_image = ",has_image=0";
     }
     sql_query("update resource set file_extension='{$extension}',preview_extension='jpg',file_modified=now() {$has_image} where ref='{$ref}'");
     # delete existing resource_dimensions
     sql_query("delete from resource_dimensions where resource='{$ref}'");
     # get file metadata
     if (!$no_exif) {
         extract_exif_comment($ref, $extension);
     }
     # extract text from documents (e.g. PDF, DOC).
     global $extracted_text_field;
     if (isset($extracted_text_field) && !$no_exif) {
         if (isset($unoconv_path) && in_array($extension, $unoconv_extensions)) {
             // omit, since the unoconv process will do it during preview creation below
         } else {
             extract_text($ref, $extension);
         }
     }
     # Store original filename in field, if set
     global $filename_field;
     if (isset($filename_field)) {
         if (!$revert) {
             update_field($ref, $filename_field, $filename);
         } else {
             update_field($ref, $filename_field, $original_filename);
         }
     }
     if (!$revert) {
         # Clear any existing FLV file or multi-page previews.
         global $pdf_pages;
         for ($n = 2; $n <= $pdf_pages; $n++) {
             # Remove preview page.
             $path = get_resource_path($ref, true, "scr", false, "jpg", -1, $n, false);
             if (file_exists($path)) {
                 unlink($path);
             }
             # Also try the watermarked version.
             $path = get_resource_path($ref, true, "scr", false, "jpg", -1, $n, true);
             if (file_exists($path)) {
                 unlink($path);
             }
         }
         # Remove any FLV video preview (except if the actual resource is an FLV file).
         global $ffmpeg_preview_extension;
         if ($extension != $ffmpeg_preview_extension) {
             $path = get_resource_path($ref, true, "", false, $ffmpeg_preview_extension);
             if (file_exists($path)) {
                 unlink($path);
             }
         }
         # Remove any FLV preview-only file
         $path = get_resource_path($ref, true, "pre", false, $ffmpeg_preview_extension);
         if (file_exists($path)) {
             unlink($path);
         }
         # Remove any MP3 (except if the actual resource is an MP3 file).
         if ($extension != "mp3") {
             $path = get_resource_path($ref, true, "", false, "mp3");
             if (file_exists($path)) {
                 unlink($path);
             }
         }
         # Create previews
         global $enable_thumbnail_creation_on_upload;
         if ($enable_thumbnail_creation_on_upload) {
             create_previews($ref, false, $extension);
         } else {
             # Offline thumbnail generation is being used. Set 'has_image' to zero so the offline create_previews.php script picks this up.
             sql_query("update resource set has_image=0 where ref='{$ref}'");
         }
     }
     # Update file dimensions
     get_original_imagesize($ref, $filepath, $extension);
     hook("Uploadfilesuccess", "", array("resourceId" => $ref));
     # Update disk usage
     update_disk_usage($ref);
     # Log this activity.
     $log_ref = resource_log($ref, "u", 0);
     hook("upload_image_after_log_write", "", array($ref, $log_ref));
     return $status;
 }