function get_original_imagesize($ref = "", $path = "", $extension = "jpg")
{
    $fileinfo = array();
    if ($ref == "" || $path == "") {
        return false;
    }
    global $imagemagick_path, $imagemagick_calculate_sizes;
    $file = $path;
    $filesize = filesize_unlimited($file);
    # imagemagick_calculate_sizes is normally turned off
    if (isset($imagemagick_path) && $imagemagick_calculate_sizes) {
        # Use ImageMagick to calculate the size
        $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);
        @(list(, $sw, $sh) = $smatches);
        if ($sw != '' && $sh != '') {
            sql_query("insert into resource_dimensions (resource, width, height, file_size) values('" . $ref . "', '" . $sw . "', '" . $sh . "', '" . $filesize . "')");
        }
    } else {
        # check if this is a raw file.
        $rawfile = false;
        if (preg_match('/^(dng|nef|x3f|cr2|crw|mrw|orf|raf|dcr)$/i', $extension, $rawext)) {
            $rawfile = true;
        }
        # Use GD to calculate the size
        if (!(@(list($sw, $sh) = @getimagesize($file)) === false) && !$rawfile) {
            sql_query("insert into resource_dimensions (resource, width, height, file_size) values('" . $ref . "', '" . $sw . "', '" . $sh . "', '" . $filesize . "')");
        } else {
            # Assume size cannot be calculated.
            $sw = "?";
            $sh = "?";
            global $ffmpeg_supported_extensions;
            if (in_array(strtolower($extension), $ffmpeg_supported_extensions) && function_exists('json_decode')) {
                $ffprobe_fullpath = get_utility_path("ffprobe");
                $file = get_resource_path($ref, true, "", false, $extension);
                $ffprobe_output = run_command($ffprobe_fullpath . " -v 0 " . escapeshellarg($file) . " -show_streams -of json");
                $ffprobe_array = json_decode($ffprobe_output, true);
                # Different versions of ffprobe store the dimensions in different parts of the json output. Test both.
                if (!empty($ffprobe_array['width'])) {
                    $sw = intval($ffprobe_array['width']);
                }
                if (!empty($ffprobe_array['height'])) {
                    $sh = intval($ffprobe_array['height']);
                }
                if (isset($ffprobe_array['streams']) && is_array($ffprobe_array['streams'])) {
                    foreach ($ffprobe_array['streams'] as $stream) {
                        if (!empty($stream['codec_type']) && $stream['codec_type'] === 'video') {
                            $sw = intval($stream['width']);
                            $sh = intval($stream['height']);
                            break;
                        }
                    }
                }
            }
            if ($sw !== '?' && $sh !== '?') {
                # Size could be calculated after all
                sql_query("insert into resource_dimensions (resource, width, height, file_size) values('" . $ref . "', '" . $sw . "', '" . $sh . "', '" . $filesize . "')");
            } else {
                # Size cannot be calculated.
                $sw = "?";
                $sh = "?";
                # Insert a dummy row to prevent recalculation on every view.
                sql_query("insert into resource_dimensions (resource, width, height, file_size) values('" . $ref . "','0', '0', '" . $filesize . "')");
            }
        }
    }
    $fileinfo[0] = $filesize;
    $fileinfo[1] = $sw;
    $fileinfo[2] = $sh;
    return $fileinfo;
}
function get_utility_version($utilityname)
{
    global $lang;
    # Get utility path.
    $utility_fullpath = get_utility_path($utilityname, $path);
    # Get utility display name.
    $name = get_utility_displayname($utilityname);
    # Check path.
    if ($path == null) {
        # There was no complete path to check - the utility is not installed.
        $error_msg = $lang["status-notinstalled"];
        return array("name" => $name, "version" => "", "success" => false, "error" => $error_msg);
    }
    if ($utility_fullpath == false) {
        # There was a path but it was incorrect - the utility couldn't be found.
        $error_msg = $lang["status-fail"] . ":<br>" . str_replace("?", $path, $lang["softwarenotfound"]);
        return array("name" => $name, "version" => "", "success" => false, "error" => $error_msg);
    }
    # Look up the argument to use to get the version.
    switch (strtolower($utilityname)) {
        case "exiftool":
            $version_argument = "-ver";
            break;
        default:
            $version_argument = "-version";
    }
    # Check execution and find out version.
    $version_command = $utility_fullpath . " " . $version_argument;
    $version = run_command($version_command);
    switch (strtolower($utilityname)) {
        case "im-convert":
            if (strpos($version, "ImageMagick") !== false) {
                $name = "ImageMagick";
            }
            if (strpos($version, "GraphicsMagick") !== false) {
                $name = "GraphicsMagick";
            }
            if ($name == "ImageMagick" || $name == "GraphicsMagick") {
                $expected = true;
            } else {
                $expected = false;
            }
            break;
        case "ghostscript":
            if (strpos(strtolower($version), "ghostscript") === false) {
                $expected = false;
            } else {
                $expected = true;
            }
            break;
        case "ffmpeg":
            if (strpos(strtolower($version), "ffmpeg") === false) {
                $expected = false;
            } else {
                $expected = true;
            }
            break;
        case "exiftool":
            if (preg_match("/^([0-9]+)+\\.([0-9]+)\$/", $version) == false) {
                $expected = false;
            } else {
                $expected = true;
            }
            break;
    }
    if ($expected == false) {
        # There was a correct path but the version check failed - unexpected output when executing the command.
        $error_msg = $lang["status-fail"] . ":<br>" . str_replace(array("%command", "%output"), array($version_command, $version), $lang["execution_failed"]);
        return array("name" => $name, "version" => "", "success" => false, "error" => $error_msg);
    } else {
        # There was a working path and the output was the expected - the version is returned.
        $s = explode("\n", $version);
        return array("name" => $name, "version" => $s[0], "success" => true, "error" => "");
    }
}
function generate_transform_preview($ref){
	global $storagedir;	
        global $imagemagick_path;
	global $imversion;

	if (!isset($imversion)){
		$imversion = get_imagemagick_version();
	}

	$tmpdir = get_temp_dir();

        // get imagemagick path
        $command = get_utility_path("im-convert");
        if ($command==false) {exit("Could not find ImageMagick 'convert' utility.");}

        $orig_ext = sql_value("select file_extension value from resource where ref = '$ref'",'');
        $originalpath= get_resource_path($ref,true,'',false,$orig_ext);

	# Since this check is in get_temp_dir() omit: if(!is_dir($storagedir."/tmp")){mkdir($storagedir."/tmp",0777);}
	if(!is_dir(get_temp_dir() . "/transform_plugin")){mkdir(get_temp_dir() . "/transform_plugin",0777);}

       if ($imversion[0]<6 || ($imversion[0] == 6 &&  $imversion[1]<7) || ($imversion[0] == 6 && $imversion[1] == 7 && $imversion[2]<5)){
                $colorspace1 = " -colorspace sRGB ";
                $colorspace2 =  " -colorspace RGB ";
        } else {
                $colorspace1 = " -colorspace RGB ";
                $colorspace2 =  " -colorspace sRGB ";
        }

        $command .= " \"$originalpath\" +matte -delete 1--1 -flatten $colorspace1 -geometry 450 $colorspace2 \"$tmpdir/transform_plugin/pre_$ref.jpg\"";
        run_command($command);


	// while we're here, clean up any old files still hanging around
	$dp = opendir(get_temp_dir() . "/transform_plugin");
	while ($file = readdir($dp)) {
		if ($file <> '.' && $file <> '..'){
			if ((filemtime(get_temp_dir() . "/transform_plugin/$file")) < (strtotime('-2 days'))) {
				unlink(get_temp_dir() . "/transform_plugin/$file");
			}
		}
	}
	closedir($dp);

        return true;
  
}
function generate_transform_preview($ref)
{
    global $storagedir;
    global $imagemagick_path;
    global $imversion;
    if (!isset($imversion)) {
        $imversion = get_imagemagick_version();
    }
    $tmpdir = get_temp_dir();
    // get imagemagick path
    $command = get_utility_path("im-convert");
    if ($command == false) {
        exit("Could not find ImageMagick 'convert' utility.");
    }
    $orig_ext = sql_value("select file_extension value from resource where ref = '{$ref}'", '');
    $transformsourcepath = get_resource_path($ref, true, 'scr', false, 'jpg');
    //use screen size if available to save time
    if (!file_exists($transformsourcepath)) {
        $transformsourcepath = get_resource_path($ref, true, '', false, $orig_ext);
    }
    # Since this check is in get_temp_dir() omit: if(!is_dir($storagedir."/tmp")){mkdir($storagedir."/tmp",0777);}
    if (!is_dir(get_temp_dir() . "/transform_plugin")) {
        mkdir(get_temp_dir() . "/transform_plugin", 0777);
    }
    if ($imversion[0] < 6 || $imversion[0] == 6 && $imversion[1] < 7 || $imversion[0] == 6 && $imversion[1] == 7 && $imversion[2] < 5) {
        $colorspace1 = " -colorspace sRGB ";
        $colorspace2 = " -colorspace RGB ";
    } else {
        $colorspace1 = " -colorspace RGB ";
        $colorspace2 = " -colorspace sRGB ";
    }
    $command .= " \"{$transformsourcepath}\"[0] +matte -flatten {$colorspace1} -geometry 450 {$colorspace2} \"{$tmpdir}/transform_plugin/pre_{$ref}.jpg\"";
    run_command($command);
    // while we're here, clean up any old files still hanging around
    $dp = opendir(get_temp_dir() . "/transform_plugin");
    while ($file = readdir($dp)) {
        if ($file != '.' && $file != '..') {
            if (filemtime(get_temp_dir() . "/transform_plugin/{$file}") < strtotime('-2 days')) {
                unlink(get_temp_dir() . "/transform_plugin/{$file}");
            }
        }
    }
    closedir($dp);
    return true;
}
include "../../include/db.php";
include "../../include/general.php";
# Fetch a list of MySQL processes and kill any that exceed the timeout limit.
# Config vars
$query_timeout = 10;
# Timeout in seconds.
$sleep_timeout = 360;
#$mysql_path="/usr/local/mysql-standard-5.0.15-osx10.4-powerpc/bin/";
$mysql_path = "/usr/bin/";
$mysql_command = $mysql_path . "mysqladmin -h {$mysql_server} -u {$mysql_username} " . ($mysql_password == "" ? "" : "-p" . $mysql_password);
for ($s = 0; $s < 60; $s += 10) {
    # Fetch process list
    $list = explode("\n", run_command($mysql_command . " processlist"));
    #echo "<pre>";
    #print_r($list);
    for ($n = 3; $n < count($list) - 2; $n++) {
        $vals = explode("|", $list[$n]);
        $id = trim($vals[1]);
        $type = trim($vals[5]);
        $time = trim($vals[6]);
        $info = trim($vals[6]) . " : " . trim($vals[7]);
        $query = trim($vals[8]);
        if ($type == "Query" && $time > $query_timeout && (strpos($query, "select") !== false || strpos($query, "create temporary table") !== false) || $type == "Sleep" && $time > $sleep_timeout) {
            # Kill this process.
            echo "killing {$id}... {$info}\n";
            run_command($mysql_command . " kill " . $id);
        }
    }
    sleep(10);
}
     $s = explode(":", $r);
     $from = $s[0];
     $to = $s[1];
     if (getval("method", "") == "alternativefile") {
         $aref = add_alternative_file($ref, $lang["pages"] . " " . $from . " - " . $to, "", "", "pdf");
         $copy_path = get_resource_path($ref, true, "", true, "pdf", -1, 1, false, "", $aref);
     } else {
         # Create a new resource based upon the metadata/type of the current resource.
         $copy = copy_resource($ref);
         # 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.
     $ghostscript_fullpath = get_utility_path("ghostscript");
     $gscommand = $ghostscript_fullpath . " -dBATCH -dNOPAUSE -sDEVICE=pdfwrite -sOutputFile=" . escapeshellarg($copy_path) . "  -dFirstPage=" . $from . " -dLastPage=" . $to . " " . escapeshellarg($file);
     $output = run_command($gscommand);
     if (getval("method", "") == "alternativefile") {
         # Preview creation for alternative files (enabled via config)
         global $alternative_file_previews;
         if ($alternative_file_previews) {
             create_previews($ref, false, "pdf", false, false, $aref);
         }
         # Update size.
         sql_query("update resource_alt_files set file_size='" . filesize_unlimited($copy_path) . "' where ref='{$aref}'");
     } else {
         # Update the file extension
         sql_query("update resource set file_extension='pdf' where ref='{$copy}'");
         # Create preview for the page.
         create_previews($copy, false, "pdf");
     }
 }
Exemple #7
0
    # Remove critical characters from filename
    $filename = preg_replace('/:/', '_', $filename);
    hook("downloadfilename");
    if (!$direct) {
        # We use quotes around the filename to handle filenames with spaces.
        header(sprintf('Content-Disposition: attachment; filename="%s"', $filename));
    }
}
# We assign a default mime-type, in case we can find the one associated to the file extension.
$mime = "application/octet-stream";
if ($noattach == "") {
    # Get mime type via exiftool if possible
    $exiftool_fullpath = get_utility_path("exiftool");
    if ($exiftool_fullpath != false) {
        $command = $exiftool_fullpath . " -s -s -s -t -mimetype " . escapeshellarg($path);
        $mime = run_command($command);
    }
    # Override or correct for lack of exiftool with config mappings
    if (isset($mime_type_by_extension[$ext])) {
        $mime = $mime_type_by_extension[$ext];
    }
}
# We declare the downloaded content mime type.
header("Content-Type: {$mime}");
set_time_limit(0);
#echo file_get_contents($path);
# The above required that the downloaded file was read into PHP's memory space first.
# Perhaps this is not the case for readfile().
# Old method
#readfile($path);
# New method
        exit();
    };

    //if user submitted a blank form?
    if ($file==''){
        $data['error'] = true;
        $data['success'] = false;
        $data['textStatus'] = 'Please Choose A Resource';
        echo(json_encode($data));
        exit();
    };

    $uploaddir = '/var/www/filestore/tmp/uploads/';
    $exiftool_fullpath = get_utility_path("exiftool");
    $command = $exiftool_fullpath . " -j --filename --exiftoolversion --filepermissions --NativeDigest --History --Directory " . escapeshellarg($uploaddir.$file)." 2>&1";
    $report_original = run_command($command);
    $extension = pathinfo($uploaddir.$file, PATHINFO_EXTENSION);
    $resource_type="";
    //get all of the available resource types and check the file extesion of uploaded file
    $resource_types=get_resource_types();
	//make sure file extension is all lowercase to ensure accurate match
    $file_extension = strtolower($extension);

    //for all of the resource types found
	for($i=0; $i<count($resource_types); $i++){
        //explode the allowed extensions into an array and remove any whitespaces
        $extension = preg_replace('/\s*/', '', $resource_types[$i]['allowed_extensions']);
        $resource_extensions=explode(',' , strtolower($extension));
        //check the array for the file extension
        if(in_array($file_extension,$resource_extensions)){
            //if the extension is found set the resource type for the found extension
 $file = get_resource_path($ref, true, "", false, $extension);
 $filesize = @filesize_unlimited($file);
 if (isset($imagemagick_path)) {
     # Check ImageMagick identify utility.
     $identify_fullpath = get_utility_path("im-identify");
     if ($identify_fullpath == false) {
         exit("Could not find ImageMagick 'identify' utility.");
     }
     $prefix = '';
     # Camera RAW images need prefix
     if (preg_match('/^(dng|nef|x3f|cr2|crw|mrw|orf|raf|dcr)$/i', $extension, $rawext)) {
         $prefix = $rawext[0] . ':';
     }
     # 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);
     @(list(, $sw, $sh) = $smatches);
     if ($sw != '' && $sh != '') {
         $size_db = sql_query("select 'true' from resource_dimensions where resource = " . $ref);
         if (count($size_db)) {
             sql_query("update resource_dimensions set width=" . $sw . ", height=" . $sh . ", file_size='{$filesize}' where resource=" . $ref);
         } else {
             sql_query("insert into resource_dimensions (resource, width, height, file_size) values(" . $ref . ", " . $sw . ", " . $sh . ", '{$filesize}')");
         }
     }
 } else {
     # 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)) {
         $size_db = sql_query("select 'true' from resource_dimensions where resource = " . $ref);
         if (count($size_db)) {
Exemple #10
0
 if ($flip || $rotation > 0) {
     // assume we should reset exif orientation flag since they have rotated to another orientation
     $command .= " -orient undefined ";
 }
 $command .= $colorspace2;
 $command .= " \"{$newpath}\"";
 if ($cropper_debug && !$download && getval("slideshow", "") == "") {
     error_log($command);
     if (isset($_REQUEST['showcommand'])) {
         echo "{$command}";
         delete_alternative_file($ref, $newfile);
         exit;
     }
 }
 // fixme -- do we need to trap for errors from imagemagick?
 $shell_result = run_command($command);
 if ($cropper_debug) {
     error_log("SHELL RESULT: {$shell_result}");
 }
 // get final pixel dimensions of resulting file
 $newfilesize = filesize_unlimited($newpath);
 $newfiledimensions = getimagesize($newpath);
 $newfilewidth = $newfiledimensions[0];
 $newfileheight = $newfiledimensions[1];
 // generate previews if needed
 global $alternative_file_previews;
 if ($alternative_file_previews && !$download && !$original && getval("slideshow", "") == "") {
     create_previews($ref, false, $new_ext, false, false, $newfile);
 }
 // strip of any extensions from the filename, since we'll provide that
 if (preg_match("/(.*)\\.\\w\\w\\w\\\$/", $filename, $matches)) {
Exemple #11
0
 public function on_command($pars)
 {
     $bundle_id = $this->stripFileName($pars['bundle']);
     $command = str_replace('..', '', $pars['command']);
     $command_path = $this->configuration['support-path'] . '/bundles/' . $bundle_id . '/commands/' . $command . '.amCommandDef';
     include_once $command_path;
     if (function_exists('run_command')) {
         run_command($this, $pars['text'], $pars);
         self::raiseError('Command returned no result.');
     } else {
         self::raiseError('Command not found.');
     }
 }
     if (!$config_windows) {
         $path = preg_replace('/\\r\\n/', "\n", $path);
     }
     fwrite($fh, $path);
     fclose($fh);
 }
 # Execute the archiver command.
 # If $collection_download is true the $collection_download_settings are used if defined, else the legacy $zipcommand is used.
 if ($use_zip_extension) {
     update_zip_progress_file("zipping");
     $wait = $zip->close();
     update_zip_progress_file("complete");
     sleep(1);
 } else {
     if ($archiver) {
         run_command($archiver_fullpath . " " . $collection_download_settings[$settings_id]["arguments"] . " " . escapeshellarg($zipfile) . " " . $archiver_listfile_argument . escapeshellarg($cmdfile));
     } else {
         if (!$use_zip_extension) {
             if ($config_windows) {
                 exec("{$zipcommand} " . escapeshellarg($zipfile) . " @" . escapeshellarg($cmdfile));
             } else {
                 # Pipe the command file, containing the filenames, to the executable.
                 exec("{$zipcommand} " . escapeshellarg($zipfile) . " -@ < " . escapeshellarg($cmdfile));
             }
         }
     }
 }
 # Archive created, schedule the command file for deletion.
 if (!$use_zip_extension) {
     $deletion_array[] = $cmdfile;
 }
     }
     # Create the alternative file.
     $aref = add_alternative_file($ref, $ffmpeg_alternatives[$n]["name"]);
     $apath = get_resource_path($ref, true, "", true, $ffmpeg_alternatives[$n]["extension"], -1, 1, false, "", $aref);
     # Process the video
     $shell_exec_cmd = $ffmpeg_fullpath . "  {$ffmpeg_global_options} -y -i " . escapeshellarg($file) . " " . $ffmpeg_alternatives[$n]["params"] . " " . escapeshellarg($apath);
     $tmp = hook("ffmpegmodaltparams", "", array($shell_exec_cmd, $ffmpeg_fullpath, $file, $n, $aref));
     if ($tmp) {
         $shell_exec_cmd = $tmp;
     }
     $output = run_command($shell_exec_cmd);
     if (isset($qtfaststart_path)) {
         if ($qtfaststart_path && file_exists($qtfaststart_path . "/qt-faststart") && in_array($ffmpeg_alternatives[$n]["extension"], $qtfaststart_extensions)) {
             $apathtmp = $apath . ".tmp";
             rename($apath, $apathtmp);
             $output = run_command($qtfaststart_path . "/qt-faststart " . escapeshellarg($apathtmp) . " " . escapeshellarg($apath) . " 2>&1");
             unlink($apathtmp);
         }
     }
     if (file_exists($apath)) {
         # Update the database with the new file details.
         $file_size = filesize_unlimited($apath);
         # SQL Connection may have hit a timeout
         sql_connect();
         sql_query("update resource_alt_files set file_name='" . escape_check($ffmpeg_alternatives[$n]["filename"] . "." . $ffmpeg_alternatives[$n]["extension"]) . "',file_extension='" . escape_check($ffmpeg_alternatives[$n]["extension"]) . "',file_size='" . $file_size . "',creation_date=now() where ref='{$aref}'");
         // add this filename to be added to resource.ffmpeg_alt_previews
         if (isset($ffmpeg_alternatives[$n]['alt_preview']) && $ffmpeg_alternatives[$n]['alt_preview'] == true) {
             $ffmpeg_alt_previews[] = basename($apath);
         }
     }
 }
Exemple #14
0
function get_image_sizes($ref,$internal=false,$extension="jpg",$onlyifexists=true)
	{
	# Returns a table of available image sizes for resource $ref. The standard image sizes are translated using $lang. Custom image sizes are i18n translated.
	# The original image file assumes the name of the 'nearest size (up)' in the table

	global $imagemagick_calculate_sizes;

	# Work out resource type
	$resource_type=sql_value("select resource_type value from resource where ref='$ref'","");

	# add the original image
	$return=array();
	$lastname=sql_value("select name value from preview_size where width=(select max(width) from preview_size)",""); # Start with the highest resolution.
	$lastpreview=0;$lastrestricted=0;
	$path2=get_resource_path($ref,true,'',false,$extension);

	if (file_exists($path2) && !checkperm("T" . $resource_type . "_"))
	{ 
		$returnline=array();
		$returnline["name"]=lang_or_i18n_get_translated($lastname, "imagesize-");
		$returnline["allow_preview"]=$lastpreview;
		$returnline["allow_restricted"]=$lastrestricted;
		$returnline["path"]=$path2;
		$returnline["id"]="";
		$dimensions = sql_query("select width,height,file_size,resolution,unit from resource_dimensions where resource=". $ref);
		
		if (count($dimensions))
			{
			$sw = $dimensions[0]['width']; if ($sw==0) {$sw="?";}
			$sh = $dimensions[0]['height']; if ($sh==0) {$sh="?";}
			$filesize=$dimensions[0]['file_size'];
			# resolution and unit are not necessarily available, set to empty string if so.
			$resolution = ($dimensions[0]['resolution'])?$dimensions[0]['resolution']:"";
			$unit = ($dimensions[0]['unit'])?$dimensions[0]['unit']:"";
			}
		else
			{
			global $imagemagick_path;
			$file=$path2;
			$filesize=filesize_unlimited($file);
			
			# imagemagick_calculate_sizes is normally turned off 
			if (isset($imagemagick_path) && $imagemagick_calculate_sizes)
				{
				# Use ImageMagick to calculate the size
				
				$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);
				@list(,$sw,$sh) = $smatches;
				if (($sw!='') && ($sh!=''))
				  {
					sql_query("insert into resource_dimensions (resource, width, height, file_size) values('". $ref ."', '". $sw ."', '". $sh ."', '" . $filesize . "')");
					}
				}	
			else 
				{
				# check if this is a raw file.	
				$rawfile = false;
				if (preg_match('/^(dng|nef|x3f|cr2|crw|mrw|orf|raf|dcr)$/i', $extension, $rawext)){$rawfile=true;}
					
				# Use GD to calculate the size
				if (!((@list($sw,$sh) = @getimagesize($file))===false)&& !$rawfile)
				 	{		
					sql_query("insert into resource_dimensions (resource, width, height, file_size) values('". $ref ."', '". $sw ."', '". $sh ."', '" . $filesize . "')");
					}
				else
					{
					# Size cannot be calculated.
					$sw="?";$sh="?";
					
					# Insert a dummy row to prevent recalculation on every view.
					sql_query("insert into resource_dimensions (resource, width, height, file_size) values('". $ref ."','0', '0', '" . $filesize . "')");
					}
				}
			}
		if (!is_numeric($filesize)) {$returnline["filesize"]="?";$returnline["filedown"]="?";}
		else {$returnline["filedown"]=ceil($filesize/50000) . " seconds @ broadband";$returnline["filesize"]=formatfilesize($filesize);}
		$returnline["width"]=$sw;			
		$returnline["height"]=$sh;
		$returnline["extension"]=$extension;
		(isset($resolution))?$returnline["resolution"]=$resolution:$returnline["resolution"]="";
		(isset($unit))?$returnline["unit"]=$unit:$returnline["unit"]="";
		$return[]=$returnline;
	}
	# loop through all image sizes
	$sizes=sql_query("select * from preview_size order by width desc");
	for ($n=0;$n<count($sizes);$n++)
		{
		$path=get_resource_path($ref,true,$sizes[$n]["id"],false,"jpg");

		$resource_type=sql_value("select resource_type value from resource where ref='$ref'","");
		if ((file_exists($path) || (!$onlyifexists)) && !checkperm("T" . $resource_type . "_" . $sizes[$n]["id"]))
			{
			if (($sizes[$n]["internal"]==0) || ($internal))
				{
				$returnline=array();
				$returnline["name"]=lang_or_i18n_get_translated($sizes[$n]["name"], "imagesize-");
				$returnline["allow_preview"]=$sizes[$n]["allow_preview"];

				# The ability to restrict download size by user group and resource type.
				if (checkperm("X" . $resource_type . "_" . $sizes[$n]["id"]))
					{
					# Permission set. Always restrict this download if this resource is restricted.
					$returnline["allow_restricted"]=false;
					}
				else
					{
					# Take the restriction from the settings for this download size.
					$returnline["allow_restricted"]=$sizes[$n]["allow_restricted"];
					}
				$returnline["path"]=$path;
				$returnline["id"]=$sizes[$n]["id"];
				if ((list($sw,$sh) = @getimagesize($path))===false) {$sw=0;$sh=0;}
				if (($filesize=@filesize_unlimited($path))===false) {$returnline["filesize"]="?";$returnline["filedown"]="?";}
				else {$returnline["filedown"]=ceil($filesize/50000) . " seconds @ broadband";$filesize=formatfilesize($filesize);}
				$returnline["filesize"]=$filesize;			
				$returnline["width"]=$sw;			
				$returnline["height"]=$sh;
				$returnline["extension"]='jpg';
				$return[]=$returnline;
				}
			}
		$lastname=lang_or_i18n_get_translated($sizes[$n]["name"], "imagesize-");
		$lastpreview=$sizes[$n]["allow_preview"];
		$lastrestricted=$sizes[$n]["allow_restricted"];
		}
	return $return;
	}
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;
    }
}
                        $filtermatch = $filtermatch || $filter == "" || stripos($fields[$y], $filter) !== false;
                        $result[$headings[$y]] = $fields[$y];
                    }
                    if ($filtermatch) {
                        array_push($results, $result);
                    }
                }
            } else {
                ?>
<p><?php 
                echo $lang["systemconsoleonfailedtasklistcommand"];
                ?>
</p><?php 
            }
        } else {
            $lines = run_command("top -b -n 1", true);
            $lines = explode("\n", $lines);
            if (is_array($lines) && count($lines) > 6) {
                $headings = preg_split('/\\s+/', $lines[6]);
                array_shift($headings);
                array_pop($headings);
                for ($i = 7; $i < count($lines); $i++) {
                    $fields = preg_split('/\\s+/', $lines[$i]);
                    array_shift($fields);
                    array_pop($fields);
                    if (count($fields) != count($headings)) {
                        continue;
                    }
                    $filtermatch = false;
                    $result = array();
                    for ($y = 0; $y < count($fields); $y++) {
function upload_video($access_token="")
	{
	global $lang, $video_title, $video_description, $video_keywords, $video_category, $filename, $ref, $status, $youtube_video_url, $youtube_publish_developer_key;

	
	# Set status as necessary
	if ($status=="private"){$private = '<yt:private/>';} 
		else{$private = '';}
	if ($status=="unlisted"){$accesscontrol = '<yt:accessControl action="list" permission="denied"/>';}
		else{$accesscontrol = '';}
	
    $data= '<?xml version="1.0"?>
                <entry xmlns="http://www.w3.org/2005/Atom"
                  xmlns:media="http://search.yahoo.com/mrss/"
                  xmlns:yt="http://gdata.youtube.com/schemas/2007">
                  <media:group>
                    <media:title type="plain">' . htmlspecialchars( $video_title ) . '</media:title>
					' . $private . '			
                    <media:description type="plain">' . htmlspecialchars( $video_description ) . '</media:description>
                    <media:category
                      scheme="http://gdata.youtube.com/schemas/2007/categories.cat">' . htmlspecialchars($video_category) .'</media:category>
                    <media:keywords>' . htmlspecialchars($video_keywords) . '</media:keywords>
                  </media:group>
				  ' . $accesscontrol . '
                </entry>';
				
	$data.= "\r\n\r\n";			
				
	#####	For resumable
	
	$headers = array( "Authorization: Bearer " . $access_token,
                 "GData-Version: 2",
                 "X-GData-Key: key=" . $youtube_publish_developer_key,
                 "Content-length: " . strlen($data),
                 "Content-Type: application/atom+xml; charset=UTF-8",
				 "Slug: " . htmlspecialchars($filename),
				 "Connection: close" ,
				 "Expect:"
				 );
				 
				 
	$youtube_upload_url="http://uploads.gdata.youtube.com/resumable/feeds/api/users/default/uploads";
		
	$curl = curl_init($youtube_upload_url);
	
		
	//curl_setopt( $curl, CURLOPT_USERAGENT, $_SERVER["HTTP_USER_AGENT"] );
	curl_setopt( $curl, CURLOPT_RETURNTRANSFER, 1 );;
	curl_setopt( $curl, CURLOPT_TIMEOUT, 10 );
	curl_setopt( $curl, CURLINFO_HEADER_OUT , 1 );
	curl_setopt( $curl, CURLOPT_SSL_VERIFYPEER, 0 );
	curl_setopt( $curl, CURLOPT_POST, 1 );
	curl_setopt( $curl, CURLOPT_FOLLOWLOCATION, 0 );
	curl_setopt( $curl, CURLOPT_HTTPHEADER, $headers );
	curl_setopt( $curl, CURLOPT_POSTFIELDS, $data );
	curl_setopt($curl, CURLOPT_HEADER, TRUE);
	
	$response = curl_exec( $curl );
	
	
	if(!curl_errno($curl))
		{
		$info = curl_getinfo($curl);
		if ($info['http_code']==401)
			{
			curl_close( $curl );
			get_youtube_access_token(true);
			return array(false,$lang["youtube_publish_renewing_token"],true);
			}		
		}
	else
		{
		curl_close( $curl );
		$upload_result=$lang["error"] . curl_error($curl);
		return array(false,curl_errno($curl),false);			
		}
			
	$header = substr($response, 0, $info['header_size']);
	$retVal = array();
	$fields = explode("\r\n", preg_replace('/\x0D\x0A[\x09\x20]+/', ' ', $header));
        foreach( $fields as $field ) 
			{
            if( preg_match('/([^:]+): (.+)/m', $field, $match) ) {
                $match[1] = preg_replace('/(?<=^|[\x09\x20\x2D])./e', 'strtoupper("\0")', strtolower(trim($match[1])));
                if( isset($retVal[$match[1]]) ) 
					{
                    $retVal[$match[1]] = array($retVal[$match[1]], $match[2]);
					} 
				else
					{
                    $retVal[$match[1]] = trim($match[2]);
					}
				}
			}
	if (isset($retVal['Location']))
		{
		$location =  $retVal['Location'];
		}
	else
		{
		$upload_result=$lang["youtube_publish_failedupload_nolocation"];
		curl_close( $curl );
		return array(false,$upload_result,false);
		}
	
			
	
	curl_close( $curl );
	
	# Finally upload the file			
	
	# Get file info for upload
	$resource=get_resource_data($ref);
	$alternative=-1;
	$ext=$resource["file_extension"];
	$path=get_resource_path($ref,true,"",false,$ext,-1,1,false,"",$alternative);
	
	# We assign a default mime-type, in case we can find the one associated to the file extension.
	$mime="application/octet-stream";
			
	# Get mime type via exiftool if possible
	$exiftool_fullpath = get_utility_path("exiftool");
	if ($exiftool_fullpath!=false)
		{	
		$command=$exiftool_fullpath . " -s -s -s -t -mimetype " . escapeshellarg($path);
		$mime=run_command($command);
		}	
		
	# Override or correct for lack of exiftool with config mappings	
	if (isset($mime_type_by_extension[$ext]))
		{
		$mime = $mime_type_by_extension[$ext];
		}
	
	
	$video_file = fopen($path, 'rb');
	
	$curl = curl_init($location);
	
	curl_setopt($curl, CURLOPT_PUT, 1);
	curl_setopt($curl, CURLOPT_BINARYTRANSFER, 1);	 
	curl_setopt($curl, CURLOPT_INFILE, $video_file); // file pointer
	curl_setopt($curl, CURLOPT_INFILESIZE, filesize($path));
	curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
	curl_setopt($curl, CURLOPT_HEADER, $mime );
	curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 3600); 
	
	
	$response = curl_exec( $curl );
	$videoxml = new SimpleXmlElement($response, LIBXML_NOCDATA);
	
	$urlAtt = $videoxml->link->attributes();
	$youtube_new_url	= $urlAtt['href'];
	$youtube_urlmatch = '#http://(www\.)youtube\.com/watch\?v=([^ &\n]+)(&.*?(\n|\s))?#i';
	preg_match($youtube_urlmatch, $youtube_new_url, $matches);	
	$youtube_new_url=$matches[0];	
		
	# end of actual file upload
	
	
	fclose($video_file);
    $video_file = null;	
	
	return array(true,$youtube_new_url,false);
	}
 $exiftool_version = run_command($command);
 if ($exiftool_version >= 7.4) {
     #build array of writable formats
     $command = $exiftool_fullpath . " -listwf";
     $writable_formats = run_command($command);
     $writable_formats = str_replace("\n", "", $writable_formats);
     $writable_formats_array = explode(" ", $writable_formats);
     $file_writability = in_array($ext, $writable_formats_array);
 }
 # Create a report for the original file.
 $command = $exiftool_fullpath . " -s -t -G --filename --exiftoolversion --filepermissions --NativeDigest --History --Directory " . escapeshellarg($image) . " 2>&1";
 $report_original = run_command($command);
 # Create a temporary file (simulate download) and create a report for it.
 $tmpfile = write_metadata($image, $ref);
 $command = $exiftool_fullpath . " -s -t -G --filename --exiftoolversion --filepermissions --NativeDigest --History --Directory " . escapeshellarg($tmpfile) . " 2>&1";
 $report_simulated = run_command($command);
 # Remove the temporary file.
 unlink($tmpfile);
 # Process the report of the simulated download.
 $results_simulated = array();
 $i = 0;
 $fields_simulated = explode("\n", $report_simulated);
 foreach ($fields_simulated as $field_simulated) {
     $tag_value = explode("\t", $field_simulated);
     if (count($tag_value) == 3) {
         $results_simulated[$i]["group"] = trim(strtolower($tag_value[0]));
         $results_simulated[$i]["tag"] = trim(strtolower($tag_value[1]));
         $results_simulated[$i]["value"] = trim($tag_value[2]);
         $tagprops = "";
         if (in_array($results_simulated[$i]["tag"], $writable_tags_array) && $file_writability) {
             $tagprops .= "w";
        if(array_key_exists("field_171",$_POST)){$creator = $_POST['field_171'];contacts($creator, $_POST, 171);};
        if(array_key_exists("field_125",$_POST)){$creator = $_POST['field_125'];contacts($creator, $_POST, 125);};
        if(array_key_exists("field_177",$_POST)){$creator = $_POST['field_177'];contacts($creator, $_POST, 177);};
        if(array_key_exists("field_178",$_POST)){$creator = $_POST['field_178'];contacts($creator, $_POST, 178);};
        if(array_key_exists("field_180",$_POST)){$creator = $_POST['field_180'];contacts($creator, $_POST, 180);};

        //Update image sizes in database
        get_original_imagesize($ref,$rs_path,$file_extension);
        // Update disk usage
        update_disk_usage($ref);

        //Bug Fix for Videos not storing width and height values in the resource_dimensions table
        if($resource_type==3){
            $exiftool_fullpath = get_utility_path("exiftool");
            $command = $exiftool_fullpath . " -j -sourceImageWidth -sourceImageHeight ".escapeshellarg($rs_path)." 2>&1";
            $dimensions = run_command($command);
            $result=json_decode($dimensions);

            //if extraction was success
            if(isset($result[0]->SourceImageWidth) && isset($result[0]->SourceImageHeight)){
                $width = $result[0]->SourceImageWidth;
                $height = $result[0]->SourceImageHeight;
                $resolution = $width*$height;
                if(isset($width) && isset($height)){
                    sql_query("UPDATE resource_dimensions SET width=$width,height=$height,resolution=$resolution WHERE resource = $ref");
                }
            }
        }
        hook("editbeforesave");
        //Save the data
        save_resource_data($ref,false);
function get_page_count($resource,$alternative=-1)
    {
    # gets page count for multipage previews from resource_dimensions table.
    # also handle alternative file multipage previews by switching $resource array if necessary
    # $alternative specifies an actual alternative file
    $ref=$resource['ref'];
    if ($alternative!=-1)
        {
        $pagecount=sql_value("select page_count value from resource_alt_files where ref=$alternative","");
        $resource=get_alternative_file($ref,$alternative);
        }
    else
        {
        $pagecount=sql_value("select page_count value from resource_dimensions where resource=$ref","");
        }
    if ($pagecount!=""){return $pagecount;}
    # or, populate this column with exiftool (for installations with many pdfs already previewed and indexed, this allows pagecount updates on the fly when needed):
    # use exiftool. 
    # locate exiftool
    $exiftool_fullpath = get_utility_path("exiftool");
    if ($exiftool_fullpath==false){}
    else
        {
        $command = $exiftool_fullpath;
        if ($resource['file_extension']=="pdf" && $alternative==-1)
            {
            $file=get_resource_path($ref,true,"",false,"pdf");
            }
        else if ($alternative==-1)
            {
            # some unoconv files are not pdfs but this needs to use the auto-alt file
            $alt_ref=sql_value("select ref value from resource_alt_files where resource=$ref and unoconv=1","");
            $file=get_resource_path($ref,true,"",false,"pdf",-1,1,false,"",$alt_ref);
            }
        else
            {
            $file=get_resource_path($ref,true,"",false,"pdf",-1,1,false,"",$alternative);
            }
    
        $command=$command." -sss -pagecount $file";
        $output=run_command($command);
        $pages=str_replace("Page Count","",$output);
        $pages=str_replace(":","",$pages);
        $pages=trim($pages);

    if (!is_numeric($pages)){ $pages = 1; } // default to 1 page if we didn't get anything back

        if ($alternative!=-1)
            {
            sql_query("update resource_alt_files set page_count='$pages' where ref=$alternative");
            }
        else
            {
            sql_query("update resource_dimensions set page_count='$pages' where resource=$ref");
            }
        return $pages;
    }
}
Exemple #21
0
                /* client is attempting to disconnect, so do it */
                /* write message to the socket and close */
                close_connection($read_sock, 'WARNING: Host broke connection');
                /* let's make sure we don't enter into a race conditiion waiting on an rrdupdate that
                 * may never happen.
                 */
                if (isset($rrdupdates_in_process[intval($read_sock)])) {
                    unset($rrdupdates_in_process[intval($read_sock)]);
                }
            } else {
                if (ord($data) == 13) {
                    $response = run_command($read_sock, $command[intval($read_sock)], $multiprocess);
                    $command[intval($read_sock)] = '';
                } else {
                    if (strlen($data) > 1) {
                        $response = run_command($read_sock, $data, $multiprocess);
                        $command[intval($read_sock)] = '';
                    } else {
                        $command[intval($read_sock)] .= $data;
                    }
                }
            }
        }
    }
}
/* close the rrdtool command if this is single process boost */
if (!read_config_option('boost_server_multiprocess')) {
    rrd_close($rrdtool_pipe);
}
/* close the listening socket */
socket_close($sock);
if ($exiftool_fullpath == false) {
    $custom_field_5 = "N/A";
    # Should not be translated as this information is sent to the bug tracker.
} else {
    $version = run_command($exiftool_fullpath . ' -ver');
    # Set version
    $s = explode("\n", $version);
    $custom_field_5 = $s[0];
}
# FFmpeg version
$ffmpeg_fullpath = get_utility_path("ffmpeg");
if ($ffmpeg_fullpath == false) {
    $custom_field_6 = "N/A";
    # Should not be translated as this information is sent to the bug tracker.
} else {
    $version = run_command($ffmpeg_fullpath . " -version");
    # Set version
    $s = explode("\n", $version);
    $custom_field_6 = $s[0];
}
# Server Platform
$serverversion = $_SERVER['SERVER_SOFTWARE'];
# PHP version
$custom_field_3 = phpversion();
if (isset($_REQUEST['submit'])) {
    header("Location: " . 'http://bugs.resourcespace.org/bug_report_advanced_page.php?' . "platform={$serverversion}&" . "product_version={$p_version}&" . "custom_field_2={$custom_field_2}&" . "custom_field_4={$custom_field_4}&" . "custom_field_6={$custom_field_6}&" . "custom_field_5={$custom_field_5}&" . "custom_field_3={$custom_field_3}&" . "build={$build}&" . "additional_info={$errortext}");
} else {
    include "../../include/header.php";
    ?>
    <div class="BasicsBox"> 
        <h1><?php 
function get_imagemagick_version($array = true)
{
    // return version number of ImageMagick, or false if it is not installed or cannot be determined.
    // will return an array of major/minor/version/patch if $array is true, otherwise just the version string
    # Locate imagemagick, or return false if it isn't installed
    $convert_fullpath = get_utility_path("im-convert");
    if ($convert_fullpath == false) {
        return false;
    }
    $versionstring = run_command($convert_fullpath . " --version");
    // example:
    //          Version: ImageMagick 6.5.0-0 2011-02-18 Q16 http://www.imagemagick.org
    //          Copyright: Copyright (C) 1999-2009 ImageMagick Studio LLC
    if (preg_match("/^Version: +ImageMagick (\\d+)\\.(\\d+)\\.(\\d+)-(\\d+) /", $versionstring, $matches)) {
        $majorver = $matches[1];
        $minorver = $matches[2];
        $revision = $matches[3];
        $patch = $matches[4];
        if ($array) {
            return array($majorver, $minorver, $revision, $patch);
        } else {
            return "{$majorver}.{$minorver}.{$revision}-{$patch}";
        }
    } else {
        return false;
    }
}
Exemple #24
0
function get_mime_type($path, $ext = null)
{
    global $mime_type_by_extension;
    if (empty($ext)) {
        $ext = pathinfo($path, PATHINFO_EXTENSION);
    }
    if (isset($mime_type_by_extension[$ext])) {
        return $mime_type_by_extension[$ext];
    }
    # Get mime type via exiftool if possible
    $exiftool_fullpath = get_utility_path("exiftool");
    if ($exiftool_fullpath != false) {
        $command = $exiftool_fullpath . " -s -s -s -t -mimetype " . escapeshellarg($path);
        return run_command($command);
    }
    return "application/octet-stream";
}
function HookImage_textDownloadModifydownloadfile()
{
    global $ref, $path, $tmpfile, $userref, $usergroup, $ext, $resource_data, $image_text_restypes, $image_text_override_groups, $image_text_filetypes, $size, $page, $use_watermark, $alternative, $image_text_height_proportion, $image_text_max_height, $image_text_min_height, $image_text_font, $image_text_position, $image_text_banner_position;
    # Return if not configured for this resource type or if user has requested no overlay and is permitted this
    if (!in_array($resource_data['resource_type'], $image_text_restypes) || !in_array(strtoupper($ext), $image_text_filetypes) || getval("nooverlay", "") != "" && in_array($usergroup, $image_text_override_groups) || $use_watermark) {
        return false;
    }
    # Get text from field
    global $image_text_field_select, $image_text_default_text;
    $overlaytext = get_data_by_field($ref, $image_text_field_select);
    if ($overlaytext == "") {
        if ($image_text_default_text != "") {
            $overlaytext = $image_text_default_text;
        } else {
            return false;
        }
    }
    # If this is not a temporary file having metadata written see if we already have a suitable size with the correct text
    $image_text_saved_file = get_resource_path($ref, true, $size . "_image_text_" . md5($overlaytext . $image_text_height_proportion . $image_text_max_height . $image_text_min_height . $image_text_font . $image_text_position . $image_text_banner_position) . "_", false, $ext, -1, $page);
    if ($path != $tmpfile && file_exists($image_text_saved_file)) {
        $path = $image_text_saved_file;
        return true;
    }
    # 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($path);
    $identoutput = run_command($identcommand);
    preg_match('/^([0-9]+)x([0-9]+)$/ims', $identoutput, $smatches);
    if (@(list(, $width, $height) = $smatches) === false) {
        return false;
    }
    $olheight = floor($height * $image_text_height_proportion);
    if ($olheight < $image_text_min_height && intval($image_text_min_height) != 0) {
        $olheight = $image_text_min_height;
    }
    if ($olheight > $image_text_max_height && intval($image_text_max_height) != 0) {
        $olheight = $image_text_max_height;
    }
    # Locate imagemagick.
    $convert_fullpath = get_utility_path("im-convert");
    if ($convert_fullpath == false) {
        exit("Could not find ImageMagick 'convert' utility at location '{$imagemagick_path}'");
    }
    $tmpolfile = get_temp_dir() . "/" . $ref . "_image_text_" . $userref . "." . $ext;
    $createolcommand = $convert_fullpath . ' -background "#000" -fill white -gravity "' . $image_text_position . '" -font "' . $image_text_font . '" -size ' . $width . 'x' . $olheight . ' caption:" ' . $overlaytext . '  " ' . escapeshellarg($tmpolfile);
    $result = run_command($createolcommand);
    $newdlfile = get_temp_dir() . "/" . $ref . "_image_text_result_" . $userref . "." . $ext;
    if ($image_text_banner_position == "bottom") {
        $convertcommand = $convert_fullpath . " " . escapeshellarg($path) . ' ' . escapeshellarg($tmpolfile) . ' -append ' . escapeshellarg($newdlfile);
    } else {
        $convertcommand = $convert_fullpath . " " . escapeshellarg($tmpolfile) . ' ' . escapeshellarg($path) . ' -append ' . escapeshellarg($newdlfile);
    }
    $result = run_command($convertcommand);
    $oldpath = $path;
    if ($path != $tmpfile) {
        copy($newdlfile, $image_text_saved_file);
    }
    $path = $newdlfile;
    if (strpos(get_temp_dir(), $oldpath) !== false) {
        unlink($oldpath);
    }
    unlink($tmpolfile);
    return true;
}
Exemple #26
0
     }
 }
 // fixme -- do we need to trap for errors from imagemagick?
 $shell_result = run_command($command);
 if ($cropper_debug) {
     error_log("SHELL RESULT: {$shell_result}");
 }
 if ($resolution != "") {
     // See if we have got exiftool, in which case we can target the Photoshop specific PPI data
     $exiftool_fullpath = get_utility_path("exiftool");
     global $exiftool_no_process;
     if ($exiftool_fullpath != false && !in_array($new_ext, $exiftool_no_process)) {
         $command = $exiftool_fullpath . " -m -overwrite_original -E ";
         $command .= "-Photoshop:XResolution={$resolution} -Photoshop:YResolution={$resolution}";
         $command .= " " . escapeshellarg($newpath);
         $output = run_command($command);
     }
 }
 // get final pixel dimensions of resulting file
 $newfilesize = filesize_unlimited($newpath);
 $newfiledimensions = getimagesize($newpath);
 $newfilewidth = $newfiledimensions[0];
 $newfileheight = $newfiledimensions[1];
 // generate previews if needed
 global $alternative_file_previews;
 if ($cropper_enable_alternative_files && $alternative_file_previews && !$download && !$original && getval("slideshow", "") == "" && !$cropperestricted) {
     create_previews($ref, false, $new_ext, false, false, $newfile);
 }
 // strip of any extensions from the filename, since we'll provide that
 if (preg_match("/(.*)\\.\\w\\w\\w\\\$/", $filename, $matches)) {
     $filename = $matches[1];
    }
    echo $pdf->GetPage();
    $pdf->Output(get_temp_dir() . "/contactsheet.pdf", "F");
    # Set up
    putenv("MAGICK_HOME=" . $imagemagick_path);
    putenv("PATH=" . $ghostscript_path . ":" . $imagemagick_path);
    # Path
    $ghostscript_fullpath = get_utility_path("ghostscript");
    $command = $ghostscript_fullpath . " -sDEVICE=jpeg -dFirstPage={$previewpage} -o -r100 -dLastPage={$previewpage} -sOutputFile=" . escapeshellarg(get_temp_dir() . "/contactsheetrip.jpg") . " " . escapeshellarg(get_temp_dir() . "/contactsheet.pdf") . ($config_windows ? "" : " 2>&1");
    run_command($command);
    $convert_fullpath = get_utility_path("im-convert");
    if ($convert_fullpath == false) {
        exit("Could not find ImageMagick 'convert' utility at location '{$imagemagick_path}'");
    }
    $command = $convert_fullpath . " -resize " . $contact_sheet_preview_size . " -quality 90 -colorspace " . $imagemagick_colorspace . " \"" . get_temp_dir() . "/contactsheetrip.jpg\" \"" . get_temp_dir() . "/contactsheet.jpg\"" . ($config_windows ? "" : " 2>&1");
    run_command($command);
    exit;
}
#check configs, decide whether PDF outputs to browser or to a new resource.
if ($contact_sheet_resource == true) {
    $newresource = create_resource(1, 0);
    update_field($newresource, 8, i18n_get_collection_name($collectiondata) . " " . $date);
    update_field($newresource, $filename_field, $newresource . ".pdf");
    #Relate all resources in collection to the new contact sheet resource
    relate_to_collection($newresource, $collection);
    #update file extension
    sql_query("update resource set file_extension='pdf' where ref='{$newresource}'");
    # Create the file in the new resource folder:
    $path = get_resource_path($newresource, true, "", true, "pdf");
    $pdf->Output($path, 'F');
    #Create thumbnails and redirect browser to the new contact sheet resource
Exemple #28
0
/**
* $output_format can be: language, prosilver and subsilver2
*/
function build_code_changes($output_format)
{
    global $substitute_new, $substitute_old, $simple_name_old, $simple_name_new, $echo_changes, $package_changed_files, $location, $debug_file, $s_name;
    // Global array holding the data entries
    $data = array('header' => array(), 'diff' => array());
    // Read diff file and prepare the output filedata...
    //$patch_filename = '../new_version/patches/phpBB-' . $substitute_old . '_to_' . $substitute_new . '.patch';
    $release_filename = 'phpbb-' . $substitute_old . '_to_' . $substitute_new . '_' . $output_format . '.txt';
    if (!$package_changed_files) {
        if (!$echo_changes) {
            $fp = fopen('save/' . $s_name . '/' . $output_format . '/' . $release_filename, 'wb');
            if (!$fp) {
                die('Unable to create ' . $release_filename);
            }
        }
    }
    include_once $location . '/build_helper.php';
    $package = new build_package(array($substitute_old, $substitute_new), false);
    $titles = array('language' => 'phpBB ' . $substitute_old . ' to phpBB ' . $substitute_new . ' Language Pack Changes', 'prosilver' => 'phpBB ' . $substitute_old . ' to phpBB ' . $substitute_new . ' prosilver Changes', 'subsilver2' => 'phpBB ' . $substitute_old . ' to phpBB ' . $substitute_new . ' subsilver2 Changes');
    $data['header'] = array('title' => $titles[$output_format], 'intro' => '

These are the ' . $titles[$output_format] . ' summed up into a little Mod. These changes are only partial and do not include any code changes, therefore not meant for updating phpBB.

	', 'included_files' => array());
    // We collect the files we want to diff first (ironically we grab this from a diff file)
    if (!$echo_changes) {
        echo "\n\nCollecting Filenames:";
    }
    // We re-create the patch file
    foreach ($package->old_packages as $_package_name => $dest_package_filename) {
        chdir($package->locations['old_versions']);
        if (!$echo_changes) {
            echo "\n\n" . 'Creating patch/diff files for phpBB-' . $dest_package_filename . $package->get('new_version_number');
        }
        $dest_package_filename = $location . '/save/' . $s_name . '/phpBB-' . $dest_package_filename . $package->get('new_version_number') . '.patch';
        $package->run_command('diff ' . $package->diff_options . ' ' . $_package_name . ' ' . $package->get('simple_name') . ' > ' . $dest_package_filename);
        // Parse this diff to determine file changes from the checked versions and save them
        $result = $package->collect_diff_files($dest_package_filename, $_package_name);
        $package->run_command('rm ' . $dest_package_filename);
    }
    chdir($location);
    $filenames = array();
    foreach ($result['files'] as $filename) {
        if ($debug_file !== false && $filename != $debug_file) {
            continue;
        }
        // Decide which files to compare...
        switch ($output_format) {
            case 'language':
                if (strpos($filename, 'language/en/') !== 0) {
                    continue 2;
                }
                break;
            case 'prosilver':
                if (strpos($filename, 'styles/prosilver/') !== 0) {
                    continue 2;
                }
                break;
            case 'subsilver2':
                if (strpos($filename, 'styles/subsilver2/') !== 0) {
                    continue 2;
                }
                break;
        }
        if (!file_exists($location . '/old_versions/' . $simple_name_old . '/' . $filename)) {
            // New file... include it
            $data['header']['included_files'][] = array('old' => $location . '/old_versions/' . $simple_name_old . '/' . $filename, 'new' => $location . '/old_versions/' . $simple_name_new . '/' . $filename, 'phpbb_filename' => $filename);
            continue;
        }
        $filenames[] = array('old' => $location . '/old_versions/' . $simple_name_old . '/' . $filename, 'new' => $location . '/old_versions/' . $simple_name_new . '/' . $filename, 'phpbb_filename' => $filename);
    }
    // Now let us go through the filenames list and create a more comprehensive diff
    if (!$echo_changes) {
        fwrite($fp, build_header($output_format, $filenames, $data['header']));
    } else {
        //echo build_header('text', $filenames, $data['header']);
    }
    // Copy files...
    $files_to_copy = array();
    foreach ($data['header']['included_files'] as $filename) {
        $files_to_copy[] = $filename['phpbb_filename'];
    }
    // First step is to copy the new version over (clean structure)
    if (!$echo_changes && sizeof($files_to_copy)) {
        foreach ($files_to_copy as $file) {
            // Create directory?
            $dirname = dirname($file);
            if ($dirname) {
                $dirname = explode('/', $dirname);
                $__dir = array();
                foreach ($dirname as $i => $dir) {
                    $__dir[] = $dir;
                    run_command("mkdir -p {$location}/save/" . $s_name . '/' . $output_format . '/' . implode('/', $__dir));
                }
            }
            $source_file = $location . '/new_version/phpBB3/' . $file;
            $dest_file = $location . '/save/' . $s_name . '/' . $output_format . '/';
            $dest_file .= $file;
            $command = "cp -p {$source_file} {$dest_file}";
            $result = trim(`{$command}`);
            echo "- Copied File: " . $source_file . " -> " . $dest_file . "\n";
        }
    }
    include_once 'diff_class.php';
    if (!$echo_changes) {
        echo "\n\nDiffing Codebases:";
    }
    foreach ($filenames as $file_ary) {
        if (!file_exists($file_ary['old'])) {
            $lines1 = array();
        } else {
            $lines1 = file($file_ary['old']);
        }
        $lines2 = file($file_ary['new']);
        if (!sizeof($lines1)) {
            // New File
        } else {
            $diff = new Diff($lines1, $lines2);
            $fmt = new BBCodeDiffFormatter(false, 5, $debug_file);
            if (!$echo_changes) {
                fwrite($fp, $fmt->format_open($file_ary['phpbb_filename']));
                fwrite($fp, $fmt->format($diff, $lines1));
                fwrite($fp, $fmt->format_close($file_ary['phpbb_filename']));
            } else {
                echo $fmt->format_open($file_ary['phpbb_filename']);
                echo $fmt->format($diff, $lines1);
                echo $fmt->format_close($file_ary['phpbb_filename']);
            }
            if ($debug_file !== false) {
                echo $fmt->format_open($file_ary['phpbb_filename']);
                echo $fmt->format($diff, $lines1);
                echo $fmt->format_close($file_ary['phpbb_filename']);
                exit;
            }
        }
    }
    if (!$echo_changes) {
        fwrite($fp, build_footer($output_format));
        // Close file
        fclose($fp);
        chmod('save/' . $s_name . '/' . $output_format . '/' . $release_filename, 0666);
    } else {
        echo build_footer($output_format);
    }
}
	}	

	for ($n=0;$n<count($rd);$n++)
		{		
		
		$ref=$rd[$n]['ref'];
		$extension=$rd[$n]['file_extension'];
	
		$image=get_resource_path($ref,true,"",false,$extension);
		if (file_exists($image)) {
		
		$resource=get_resource_data($ref);
			
		$command = $exiftool_fullpath . " -s -s -s -" . $exiftool_tag . " " . escapeshellarg($image);
	
		$value = iptc_return_utf8(trim(run_command($command)));
	
		$plugin="../../plugins/exiftool_filter_" . $name . ".php";
		if ($exiftool_filter!=""){
			eval($exiftool_filter);
			}
		if (file_exists($plugin)) {include $plugin;}
	
		if ($blanks=="true"){
			update_field($ref,$fieldref,$value);
			echo ("<br>Updated Resource $ref <br> -Exiftool found \"$value\" embedded in the -$exiftool_tag tag and applied it to ResourceSpace Field $fieldref<br><br>");
			}
		else {
			if ($value!=""){
				update_field($ref,$fieldref,$value);
				echo ("<br>Updated Resource $ref <br> -Exiftool found \"$value\" embedded in the -$exiftool_tag tag and applied it to ResourceSpace Field $fieldref<br><br>");	
Exemple #30
-1
/**
 * Converts the file of the given resource to the new target file with the specified size. The
 * target file format is determined from the suffix of the target file.
 * The original colorspace of the image is retained. If $width and $height are zero, the image
 * keeps its original size.
 */
function convertImage($resource, $page, $alternative, $target, $width, $height, $profile)
{
    $command = get_utility_path("im-convert");
    if (!$command) {
        die("Could not find ImageMagick 'convert' utility.");
    }
    $originalPath = get_resource_path($resource['ref'], true, '', false, $resource['file_extension'], -1, $page, false, '', $alternative);
    $command .= " \"{$originalPath}\"[0] -auto-orient";
    if ($width != 0 && $height != 0) {
        # Apply resize ('>' means: never enlarge)
        $command .= " -resize \"{$width}";
        if ($height > 0) {
            $command .= "x{$height}";
        }
        $command .= '>"';
    }
    if ($profile === '') {
        $command .= ' +profile *';
    } else {
        if (!empty($profile)) {
            // Find out if the image does already have a profile
            $identify = get_utility_path("im-identify");
            $identify .= ' -verbose "' . $originalPath . '"';
            $info = run_command($command);
            $basePath = dirname(__FILE__) . '/../../../';
            if (preg_match("/Profile-icc:/", $info) != 1) {
                $command .= ' -profile "' . $basePath . 'config/sRGB_IEC61966-2-1_black_scaled.icc"';
            }
            $command .= ' -profile "' . $basePath . $profile . '"';
        }
    }
    $command .= " \"{$target}\"";
    run_command($command);
}