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;
}
Beispiel #2
0
function alt_from_resource($source,$target,$name='',$delete=false){
	// Copy a resource as an alt file of another resource
	// alt is the source resource, $ref is the target resource that will get the new alternate
	global $view_title_field;
	$srcdata=get_resource_data($source);
	$srcext = $srcdata['file_extension'];
	$srcpath = get_resource_path($source,true,"",false,$srcext);
	if ($name == ''){
		$name = sql_value("select value from resource_data where resource_type_field = '$view_title_field' and resource = '$source'",'Untitled');
	}

	$description = '';
	if (!file_exists($srcpath)){
		echo "ERROR: File not found.";
		return false;
	} else {

		$file_size = filesize_unlimited($srcpath);
		$altid = add_alternative_file($target,$name,$description="",$file_name="",$file_extension="",$file_size,$alt_type='');
		$newpath = get_resource_path($target,true,"",true,$srcext,-1,1,false,'',$altid);
		copy($srcpath,$newpath);
		# Preview creation for alternative files (enabled via config)
                global $alternative_file_previews;
                if ($alternative_file_previews){
			create_previews($target,false,$srcext,false,false,$altid);
               	}
		if ($delete){
			// we are supposed to delete the original resource when we're done
			# Not allowed to edit this resource? They shouldn't have been able to get here.
			if ((!get_edit_access($source,$srcdata["archive"]))||checkperm('D')) {
				exit ("Permission denied.");
			} else {
				delete_resource($source);
			}
		}
		return true;

	}
}
Beispiel #3
0
            # Show the no-preview icon
            ?>
	<img src="<?php 
            echo $baseurl_short;
            ?>
gfx/<?php 
            echo get_nopreview_icon($resource["resource_type"], $resource["file_extension"], true);
            ?>
" />
	<br />
	<?php 
        }
        if ($resource["file_extension"] != "") {
            ?>
<strong><?php 
            echo str_replace_formatted_placeholder("%extension", $resource["file_extension"], $lang["cell-fileoftype"]) . " (" . formatfilesize(@filesize_unlimited(get_resource_path($ref, true, "", false, $resource["file_extension"]))) . ")";
            ?>
</strong><?php 
            if (checkperm("w") && $resource["has_image"] == 1 && file_exists($wmpath)) {
                ?>
 &nbsp;&nbsp;<a href="#" onclick="jQuery('#wmpreview').toggle();jQuery('#preview').toggle();if (jQuery(this).text()=='<?php 
                echo $lang['showwatermark'];
                ?>
'){jQuery(this).text('<?php 
                echo $lang['hidewatermark'];
                ?>
');} else {jQuery(this).text('<?php 
                echo $lang['showwatermark'];
                ?>
');}"><?php 
                echo $lang['showwatermark'];
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 {
            # 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 ProcessFolder($folder)
{
    #echo "<br>processing folder $folder";
    global $syncdir, $nogo, $max, $count, $done, $modtimes, $lastsync, $ffmpeg_preview_extension, $staticsync_autotheme, $staticsync_extension_mapping_default, $staticsync_extension_mapping, $staticsync_mapped_category_tree, $staticsync_title_includes_path, $staticsync_ingest, $staticsync_mapfolders, $staticsync_alternatives_suffix, $staticsync_alt_suffixes, $staticsync_alt_suffix_array, $file_minimum_age, $staticsync_run_timestamp;
    $collection = 0;
    echo "Processing Folder: {$folder}\n";
    # List all files in this folder.
    $dh = opendir($folder);
    echo date('Y-m-d H:i:s    ');
    echo "Reading from {$folder}\n";
    while (($file = readdir($dh)) !== false) {
        // because of alternative processing, some files may disappear during the run
        // that's ok - just ignore it and move on
        if (!file_exists($folder . "/" . $file)) {
            echo date('Y-m-d H:i:s    ');
            echo "File {$file} missing. Moving on.\n";
            continue;
        }
        $filetype = filetype($folder . "/" . $file);
        $fullpath = $folder . "/" . $file;
        $shortpath = str_replace($syncdir . "/", "", $fullpath);
        if ($staticsync_mapped_category_tree) {
            $path_parts = explode("/", $shortpath);
            array_pop($path_parts);
            touch_category_tree_level($path_parts);
        }
        # -----FOLDERS-------------
        if (($filetype == "dir" || $filetype == "link") && $file != "." && $file != ".." && strpos($nogo, "[" . $file . "]") === false && strpos($file, $staticsync_alternatives_suffix) === false) {
            # Recurse
            #echo "\n$file : " . filemtime($folder . "/" . $file) . " > " . $lastsync;
            if (true || strlen($lastsync) == "" || filemtime($folder . "/" . $file) > $lastsync - 26000) {
                ProcessFolder($folder . "/" . $file);
            }
        }
        # -------FILES---------------
        if ($filetype == "file" && substr($file, 0, 1) != "." && strtolower($file) != "thumbs.db" && !ss_is_alt($file)) {
            // we want to make sure we don't touch files that are too new
            // so check this
            if (time() - filectime($folder . "/" . $file) < $file_minimum_age) {
                echo date('Y-m-d H:i:s    ');
                echo "   {$file} too new -- skipping .\n";
                //echo filectime($folder . "/" . $file) . " " . time() . "\n";
                continue;
            }
            # Already exists?
            if (!in_array($shortpath, $done)) {
                $count++;
                if ($count > $max) {
                    return true;
                }
                echo date('Y-m-d H:i:s    ');
                echo "Processing file: {$fullpath}\n";
                if ($collection == 0 && $staticsync_autotheme) {
                    # Make a new collection for this folder.
                    $e = explode("/", $shortpath);
                    $theme = ucwords($e[0]);
                    $name = count($e) == 1 ? "" : $e[count($e) - 2];
                    echo date('Y-m-d H:i:s    ');
                    echo "\nCollection {$name}, theme={$theme}";
                    $collection = sql_value("select ref value from collection where name='" . escape_check($name) . "' and theme='" . escape_check($theme) . "'", 0);
                    if ($collection == 0) {
                        sql_query("insert into collection (name,created,public,theme,allow_changes) values ('" . escape_check($name) . "',now(),1,'" . escape_check($theme) . "',0)");
                        $collection = sql_insert_id();
                    }
                }
                # Work out extension
                $extension = explode(".", $file);
                $extension = trim(strtolower($extension[count($extension) - 1]));
                // if coming from collections or la folders, assume these are the resource types
                if (stristr(strtolower($fullpath), 'collection services/curatorial')) {
                    $type = 5;
                } elseif (stristr(strtolower($fullpath), 'collection services/conservation')) {
                    $type = 5;
                } elseif (stristr(strtolower($fullpath), 'collection services/library_archives')) {
                    $type = 6;
                } else {
                    # Work out a resource type based on the extension.
                    $type = $staticsync_extension_mapping_default;
                    reset($staticsync_extension_mapping);
                    foreach ($staticsync_extension_mapping as $rt => $extensions) {
                        if ($rt == 5 or $rt == 6) {
                            continue;
                        }
                        // we already eliminated those
                        if (in_array($extension, $extensions)) {
                            $type = $rt;
                        }
                    }
                }
                # Formulate a title
                if ($staticsync_title_includes_path) {
                    $title = str_ireplace("." . $extension, "", str_replace("/", " - ", $shortpath));
                    $title = ucfirst(str_replace("_", " ", $title));
                } else {
                    $title = str_ireplace("." . $extension, "", $file);
                }
                # Import this file
                $r = import_resource($shortpath, $type, $title, $staticsync_ingest);
                if ($r !== false) {
                    # Add to mapped category tree (if configured)
                    if (isset($staticsync_mapped_category_tree)) {
                        $basepath = "";
                        # Save tree position to category tree field
                        # For each node level, expand it back to the root so the full path is stored.
                        for ($n = 0; $n < count($path_parts); $n++) {
                            if ($basepath != "") {
                                $basepath .= "~";
                            }
                            $basepath .= $path_parts[$n];
                            $path_parts[$n] = $basepath;
                        }
                        update_field($r, $staticsync_mapped_category_tree, "," . join(",", $path_parts));
                        #echo "update_field($r,$staticsync_mapped_category_tree," . "," . join(",",$path_parts) . ");\n";
                    }
                    # StaticSync path / metadata mapping
                    # Extract metadata from the file path as per $staticsync_mapfolders in config.php
                    if (isset($staticsync_mapfolders)) {
                        foreach ($staticsync_mapfolders as $mapfolder) {
                            $match = $mapfolder["match"];
                            $field = $mapfolder["field"];
                            $level = $mapfolder["level"];
                            if (strpos("/" . $shortpath, $match) !== false) {
                                # Match. Extract metadata.
                                $path_parts = explode("/", $shortpath);
                                if ($level < count($path_parts)) {
                                    # Save the value
                                    print_r($path_parts);
                                    $value = $path_parts[$level - 1];
                                    update_field($r, $field, $value);
                                    echo " - Extracted metadata from path: {$value}\n";
                                }
                            }
                        }
                    }
                    // add the timestamp from this run to the keywords field to help retrieve this batch later
                    $currentkeywords = sql_value("select value from resource_data where resource = '{$r}' and resource_type_field = '1'", "");
                    if (strlen($currentkeywords) > 0) {
                        $currentkeywords .= ',';
                    }
                    update_field($r, 1, $currentkeywords . $staticsync_run_timestamp);
                    if (function_exists('staticsync_local_functions')) {
                        // if local cleanup functions have been defined, run them
                        staticsync_local_functions($r);
                    }
                    # Add any alternative files
                    $altpath = $fullpath . $staticsync_alternatives_suffix;
                    if ($staticsync_ingest && file_exists($altpath)) {
                        $adh = opendir($altpath);
                        while (($altfile = readdir($adh)) !== false) {
                            $filetype = filetype($altpath . "/" . $altfile);
                            if ($filetype == "file" && substr($file, 0, 1) != "." && strtolower($file) != "thumbs.db") {
                                # Create alternative file
                                global $lang;
                                # Find extension
                                $ext = explode(".", $altfile);
                                $ext = $ext[count($ext) - 1];
                                $aref = add_alternative_file($r, $altfile, strtoupper($ext) . " " . $lang["file"], $altfile, $ext, filesize_unlimited($altpath . "/" . $altfile));
                                $path = get_resource_path($r, true, "", true, $ext, -1, 1, false, "", $aref);
                                rename($altpath . "/" . $altfile, $path);
                                # Move alternative file
                            }
                        }
                    }
                    # check for alt files that match suffix list
                    if ($staticsync_alt_suffixes) {
                        $ss_nametocheck = substr($file, 0, strlen($file) - strlen($extension) - 1);
                        //review all files still in directory and see if they are alt files matching this one
                        $althandle = opendir($folder);
                        while (($altcandidate = readdir($althandle)) !== false) {
                            if ($filetype == "file" && substr($file, 0, 1) != "." && strtolower($file) != "thumbs.db") {
                                # Find extension
                                $ext = explode(".", $altcandidate);
                                $ext = $ext[count($ext) - 1];
                                $altcandidate_name = substr($altcandidate, 0, strlen($altcandidate) - strlen($ext) - 1);
                                $altcandidate_validated = false;
                                foreach ($staticsync_alt_suffix_array as $sssuffix) {
                                    if ($altcandidate_name == $ss_nametocheck . $sssuffix) {
                                        $altcandidate_validated = true;
                                        $thisfilesuffix = $sssuffix;
                                        break;
                                    }
                                }
                                if ($altcandidate_validated) {
                                    echo date('Y-m-d H:i:s    ');
                                    echo "    Attaching {$altcandidate} as alternative.\n";
                                    $filetype = filetype($folder . "/" . $altcandidate);
                                    # Create alternative file
                                    global $lang;
                                    if (preg_match("/^_VERSO[0-9]*/i", $thisfilesuffix)) {
                                        $alt_title = "Verso";
                                    } elseif (preg_match("/^_DNG[0-9]*/i", $thisfilesuffix)) {
                                        $alt_title = "DNG";
                                    } elseif (preg_match("/^_ORIG[0-9]*/i", $thisfilesuffix)) {
                                        $alt_title = "Original Scan";
                                    } elseif (preg_match("/^_TPV[0-9]*/i", $thisfilesuffix)) {
                                        $alt_title = "Title Page Verso";
                                    } elseif (preg_match("/^_TP[0-9]*/i", $thisfilesuffix)) {
                                        $alt_title = "Title Page";
                                    } elseif (preg_match("/^_COV[0-9]*/i", $thisfilesuffix)) {
                                        $alt_title = "Cover";
                                    } elseif (preg_match("/^_SCR[0-9]*/i", $thisfilesuffix)) {
                                        $alt_title = "Inscription";
                                    } elseif (preg_match("/^_EX[0-9]*/i", $thisfilesuffix)) {
                                        $alt_title = "Enclosure";
                                    } else {
                                        $alt_title = $altcandidate;
                                    }
                                    $aref = add_alternative_file($r, $alt_title, strtoupper($ext) . " " . $lang["file"], $altcandidate, $ext, filesize_unlimited($folder . "/" . $altcandidate));
                                    $path = get_resource_path($r, true, "", true, $ext, -1, 1, false, "", $aref);
                                    rename($folder . "/" . $altcandidate, $path);
                                    # Move alternative file
                                    global $alternative_file_previews;
                                    if ($alternative_file_previews) {
                                        create_previews($r, false, $ext, false, false, $aref);
                                    }
                                }
                            }
                        }
                    }
                    # Add to collection
                    if ($staticsync_autotheme) {
                        sql_query("insert into collection_resource(collection,resource,date_added) values ('{$collection}','{$r}',now())");
                    }
                    // fix permissions
                    // get directory to fix
                    global $scramble_key;
                    $permfixfolder = "/hne/rs/filestore/";
                    for ($n = 0; $n < strlen($r); $n++) {
                        $permfixfolder .= substr($r, $n, 1);
                        if ($n == strlen($r) - 1) {
                            $permfixfolder .= "_" . substr(md5($r . "_" . $scramble_key), 0, 15);
                        }
                        $permfixfolder .= "/";
                    }
                    exec("/bin/chown -R wwwrun {$permfixfolder}");
                    exec("/bin/chgrp -R www {$permfixfolder}");
                } else {
                    # Import failed - file still being uploaded?
                    echo date('Y-m-d H:i:s    ');
                    echo " *** Skipping file - it was not possible to move the file (still being imported/uploaded?) \n";
                }
            } else {
                # check modified date and update previews if necessary
                $filemod = filemtime($fullpath);
                if (array_key_exists($shortpath, $modtimes) && $filemod > strtotime($modtimes[$shortpath])) {
                    # File has been modified since we last created previews. Create again.
                    $rd = sql_query("select ref,has_image,file_modified,file_extension from resource where file_path='" . escape_check($shortpath) . "'");
                    if (count($rd) > 0) {
                        $rd = $rd[0];
                        $rref = $rd["ref"];
                        echo date('Y-m-d H:i:s    ');
                        echo "Resource {$rref} has changed, regenerating previews: {$fullpath}\n";
                        create_previews($rref, false, $rd["file_extension"]);
                        sql_query("update resource set file_modified=now() where ref='{$rref}'");
                    }
                }
            }
        }
    }
}
Beispiel #6
0
function sendFile($filename)
{
    $suffix = pathinfo($filename, PATHINFO_EXTENSION);
    $size = filesize_unlimited($filename);
    header('Content-Transfer-Encoding: binary');
    header('Content-Disposition: attachment; filename="' . mb_basename($filename) . '"');
    header('Content-Type: ' . get_mime_type($filename, $suffix));
    header('Content-Length: ' . $size);
    header("Content-Type: application/octet-stream");
    ob_end_flush();
    readfile($filename);
}
                } elseif (preg_match("/^_ORIG[0-9]*/i", $thisfilesuffix)) {
                    $alt_title = "Original Scan";
                } elseif (preg_match("/^_TPV[0-9]*/i", $thisfilesuffix)) {
                    $alt_title = "Title Page Verso";
                } elseif (preg_match("/^_TP[0-9]*/i", $thisfilesuffix)) {
                    $alt_title = "Title Page";
                } elseif (preg_match("/^_COV[0-9]*/i", $thisfilesuffix)) {
                    $alt_title = "Cover";
                } elseif (preg_match("/^_SCR[0-9]*/i", $thisfilesuffix)) {
                    $alt_title = "Inscription";
                } elseif (preg_match("/^_EX[0-9]*/i", $thisfilesuffix)) {
                    $alt_title = "Enclosure";
                } else {
                    $alt_title = $filename;
                }
                $aref = add_alternative_file($resource, $alt_title, strtoupper($ext) . " " . $lang["file"], $thefile, $ext, filesize_unlimited($thefile));
                $path = get_resource_path($resource, true, "", true, $ext, -1, 1, false, "", $aref);
                rename($thefile, $path);
                # Move alternative file
                global $alternative_file_previews;
                if ($alternative_file_previews) {
                    create_previews($resource, false, $ext, false, false, $aref);
                }
            } else {
                echo date('Y-m-d H:i:s    ');
                echo "matching resource not found.\n";
            }
        }
    }
}
function dir_tree($dir)
     $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);
         }
     }
 }
 /*// update the resource table with any ffmpeg_alt_previews	
 		if (count($ffmpeg_alt_previews)>0){
 			$ffmpeg_alternative_previews=implode(",",$ffmpeg_alt_previews);
 			sql_query("update resource set ffmpeg_alt_previews='".escape_check($ffmpeg_alternative_previews)."' where ref='$ref'");
 		}
 		*/
     # Upload an alternative file (JUpload only)
     # Add a new alternative file
     $aref = add_alternative_file($alternative, $plfilename);
     # Work out the extension
     $extension = explode(".", $plfilepath);
     $extension = trim(strtolower($extension[count($extension) - 1]));
     # Find the path for this resource.
     $path = get_resource_path($alternative, true, "", true, $extension, -1, 1, false, "", $aref);
     # Move the sent file to the alternative file location
     # PLUpload - file was sent chunked and reassembled - use the reassembled file location
     $result = rename($plfilepath, $path);
     if ($result === false) {
         exit("ERROR: File upload error. Please check the size of the file you are trying to upload.");
     }
     chmod($path, 0777);
     $file_size = @filesize_unlimited($path);
     # Save alternative file data.
     sql_query("update resource_alt_files set file_name='" . escape_check($plfilename) . "',file_extension='" . escape_check($extension) . "',file_size='" . $file_size . "',creation_date=now() where resource='{$alternative}' and ref='{$aref}'");
     if ($alternative_file_previews_batch) {
         create_previews($alternative, false, $extension, false, false, $aref);
     }
     echo "SUCCESS";
     exit;
 }
 if ($replace == "" && $replace_resource == "") {
     # Standard upload of a new resource
     $ref = copy_resource(0 - $userref);
     # Copy from user template
     # Add to collection?
     if ($collection_add != "") {
         add_resource_to_collection($ref, $collection_add);
Beispiel #10
0
function ProcessFolder($folder)
	{
	#echo "<br>processing folder $folder";
	global $syncdir,$nogo,$max,$count,$done,$modtimes,$lastsync, $ffmpeg_preview_extension, $staticsync_autotheme, $staticsync_folder_structure,$staticsync_extension_mapping_default, $staticsync_extension_mapping, $staticsync_mapped_category_tree,$staticsync_title_includes_path, $staticsync_ingest, $staticsync_mapfolders,$staticsync_alternatives_suffix;
	
	$collection=0;
	
	echo "Processing Folder: $folder\n";
	
	# List all files in this folder.
	$dh=opendir($folder);
	while (($file = readdir($dh)) !== false)
		{
		$filetype=filetype($folder . "/" . $file);
		$fullpath=$folder . "/" . $file;
		$shortpath=str_replace($syncdir . "/","",$fullpath);
		# Work out extension
		$extension=explode(".",$file);$extension=trim(strtolower($extension[count($extension)-1]));
		
		if ($staticsync_mapped_category_tree)
			{
			$path_parts=explode("/",$shortpath);
			array_pop($path_parts);
			touch_category_tree_level($path_parts);
			}	
		
		# -----FOLDERS-------------
		if ((($filetype=="dir") || $filetype=="link") && ($file!=".") && ($file!="..") && (strpos($nogo,"[" . $file . "]")===false) && strpos($file,$staticsync_alternatives_suffix)===false)
			{
			# Recurse
			#echo "\n$file : " . filemtime($folder . "/" . $file) . " > " . $lastsync;
			if (true || (strlen($lastsync)=="") || (filemtime($folder . "/" . $file)>($lastsync-26000)))
				{
				ProcessFolder($folder . "/" . $file);
				}
			}
			
		# -------FILES---------------
		if (($filetype=="file") && (substr($file,0,1)!=".") && (strtolower($file)!="thumbs.db"))
			{
			# Already exists?
			if (!in_array($shortpath,$done))
				{
				$count++;if ($count>$max) {return(true);}

				echo "Processing file: $fullpath\n";
				
				if ($collection==0 && $staticsync_autotheme)
					{
					# Make a new collection for this folder.
					$e=explode("/",$shortpath);
					$theme=ucwords($e[0]);
					$themesql="theme='".ucwords(escape_check($e[0]))."'";
					$themecolumns="theme";
					$themevalues="'".ucwords(escape_check($e[0]))."'";
					
					if ($staticsync_folder_structure){
						for ($x=0;$x<count($e)-1;$x++){
							if ($x==0){} else {$themeindex=$x+1;
							global $theme_category_levels;
							if ($themeindex>$theme_category_levels){
								$theme_category_levels=$themeindex;
								if ($x==count($e)-2){echo "\n\nUPDATE THEME_CATEGORY_LEVELS TO $themeindex IN CONFIG!!!!\n\n";}
							}
							$themesql.=" and theme".$themeindex."='".ucwords(escape_check($e[$x]))."'";
							$themevalues.=",'".ucwords(escape_check($e[$x]))."'";
							$themecolumns.=",theme".$themeindex;
							}
						}
					}
					
					$name=(count($e)==1?"":$e[count($e)-2]);
					echo "\nCollection $name, theme=$theme";
					$collection=sql_value("select ref value from collection where name='" . escape_check($name) . "' and " . $themesql ,0);
					if ($collection==0){
						sql_query("insert into collection (name,created,public,$themecolumns,allow_changes) values ('" . escape_check($name) . "',now(),1,".$themevalues.",0)");
						$collection=sql_insert_id();
					}
				}

				# Work out a resource type based on the extension.
				$type=$staticsync_extension_mapping_default;
				reset ($staticsync_extension_mapping);
				foreach ($staticsync_extension_mapping as $rt=>$extensions)
					{
					if (in_array($extension,$extensions)) {$type=$rt;}
					}
				
				# Formulate a title
				if ($staticsync_title_includes_path)
					{
					$title=str_ireplace("." . $extension,"",str_replace("/"," - ",$shortpath));
					$title=ucfirst(str_replace("_"," ",$title));
					}
				else
					{
					$title=str_ireplace("." . $extension,"",$file);
					}
				
				# Import this file
				$r=import_resource($shortpath,$type,$title,$staticsync_ingest);
				if ($r!==false)
					{
					# Add to mapped category tree (if configured)
					if (isset($staticsync_mapped_category_tree))
						{
						$basepath="";
						# Save tree position to category tree field
				
						# For each node level, expand it back to the root so the full path is stored.
						for ($n=0;$n<count($path_parts);$n++)
							{
							if ($basepath!="") {$basepath.="~";}
							$basepath.=$path_parts[$n];
							$path_parts[$n]=$basepath;
							}
						
						update_field ($r,$staticsync_mapped_category_tree,"," . join(",",$path_parts));
						#echo "update_field($r,$staticsync_mapped_category_tree," . "," . join(",",$path_parts) . ");\n";
						}			

					// default access level. This may be overridden by metadata mapping.
					$accessval = 0;

					# StaticSync path / metadata mapping
					# Extract metadata from the file path as per $staticsync_mapfolders in config.php
					if (isset($staticsync_mapfolders))
						{
						foreach ($staticsync_mapfolders as $mapfolder)
							{
							$match=$mapfolder["match"];
							$field=$mapfolder["field"];
							$level=$mapfolder["level"];
														
							global $lang;

							if (strpos("/" . $shortpath,$match)!==false)
								{
								# Match. Extract metadata.
								$path_parts=explode("/",$shortpath);
								if ($level<count($path_parts))
									{
									// special cases first.
									if ($field == 'access')
										{
											// access level is a special case
											// first determine if the value matches a defined access level

											$value = $path_parts[$level-1];

											for ($n=0; $n<3; $n++){
												// if we get an exact match or a match except for case
												if ($value == $lang["access" . $n] || strtoupper($value) == strtoupper($lang['access' . $n])){
													$accessval = $n;
													echo "Will set access level to " . $lang['access' . $n] . " ($n)\n";
												}
											}

										} else {
										# Save the value
										print_r($path_parts);
										$value=$path_parts[$level-1];
										update_field ($r,$field,$value);
										echo " - Extracted metadata from path: $value\n";
										}
									}
								}
							}
						}
					
					// update access level
					sql_query("update resource set access = '$accessval' where ref = '$r'");
					
					# Add any alternative files
					$altpath=$fullpath . $staticsync_alternatives_suffix;
					if ($staticsync_ingest && file_exists($altpath))
						{
						$adh=opendir($altpath);
						while (($altfile = readdir($adh)) !== false)
							{
							$filetype=filetype($altpath . "/" . $altfile);
							if (($filetype=="file") && (substr($file,0,1)!=".") && (strtolower($file)!="thumbs.db"))
								{
								# Create alternative file
								global $lang;
								
								# Find extension
								$ext=explode(".",$altfile);$ext=$ext[count($ext)-1];
								
								$aref = add_alternative_file($r, $altfile, str_replace("?",strtoupper($ext),$lang["originalfileoftype"]), $altfile, $ext, filesize_unlimited($altpath . "/" . $altfile));
								$path=get_resource_path($r, true, "", true, $ext, -1, 1, false, "", $aref);
								rename ($altpath . "/" . $altfile,$path); # Move alternative file
								}
							}	
						}
					
					# Add to collection
					if ($staticsync_autotheme)
						{
						$test="";	
						$test=sql_query("select * from collection_resource where collection='$collection' and resource='$r'");
						if (count($test)==0){
							sql_query("insert into collection_resource(collection,resource,date_added) values ('$collection','$r',now())");
							}
						}
					}
				else
					{
					# Import failed - file still being uploaded?
					echo " *** Skipping file - it was not possible to move the file (still being imported/uploaded?) \n";
					}
				}
			else
				{
				# check modified date and update previews if necessary
				$filemod=filemtime($fullpath);
				if (array_key_exists($shortpath,$modtimes) && ($filemod>strtotime($modtimes[$shortpath])))
					{
					# File has been modified since we last created previews. Create again.
					$rd=sql_query("select ref,has_image,file_modified,file_extension from resource where file_path='" . (escape_check($shortpath)) . "'");
					if (count($rd)>0)
						{
						$rd=$rd[0];
						$rref=$rd["ref"];
						
						echo "Resource $rref has changed, regenerating previews: $fullpath\n";
						extract_exif_comment($rref,$rd["file_extension"]);
						
						# extract text from documents (e.g. PDF, DOC).
						global $extracted_text_field;
						if (isset($extracted_text_field)) {
							if (isset($unoconv_path) && in_array($extension,$unoconv_extensions)){
								// omit, since the unoconv process will do it during preview creation below
								}
							else {
							extract_text($rref,$extension);
							}
						}

						# Store original filename in field, if set
						global $filename_field;
						if (isset($filename_field))
							{
							update_field($rref,$filename_field,$file);	
							}
						
						create_previews($rref,false,$rd["file_extension"]);
						sql_query("update resource set file_modified=now() where ref='$rref'");
						}
					}
				}
			}	
		}	
	}
            # A JPEG was created. Set as the file to process.
            $newfile = $target;
        }
    }
}
/* ----------------------------------------
	Try MP3 preview extraction via exiftool
   ----------------------------------------
*/
if ($extension == "mp3" && !isset($newfile)) {
    if ($exiftool_fullpath != false) {
        run_command($exiftool_fullpath . ' -b -picture ' . escapeshellarg($file) . ' > ' . $target);
    }
    if (file_exists($target)) {
        #if the file contains an image, use it; if it's blank, it needs to be erased because it will cause an error in ffmpeg_processing.php
        if (filesize_unlimited($target) > 0) {
            $newfile = $target;
        } else {
            unlink($target);
        }
    }
}
/* ----------------------------------------
	Try text file to JPG conversion
   ----------------------------------------
*/
# Support text files simply by rendering them on a JPEG.
if ($extension == "txt" && !isset($newfile)) {
    $text = wordwrap(file_get_contents($file), 90);
    $width = 650;
    $height = 850;
function HookImagestreamUpload_pluploadInitialuploadprocessing()
{
    #Support for uploading multi files as zip
    global $config_windows, $id, $targetDir, $resource_type, $imagestream_restypes, $imagestream_transitiontime, $zipcommand, $use_zip_extension, $userref, $session_hash, $filename, $filename_field, $collection_add, $archiver, $zipcommand, $ffmpeg_fullpath, $ffmpeg_preview_extension, $ffmpeg_preview_options, $ffmpeg_preview_min_height, $ffmpeg_preview_max_height, $ffmpeg_preview_min_width, $ffmpeg_preview_max_width, $lang, $collection_download_settings, $archiver_listfile_argument;
    $ffmpeg_fullpath = get_utility_path("ffmpeg");
    debug("DEBUG: Imagestream - checking restype: " . $resource_type . $imagestream_restypes);
    if (in_array($resource_type, $imagestream_restypes)) {
        debug("DEBUG: Imagestream - uploading file");
        #Check that we have an archiver configured
        $archiver_fullpath = get_utility_path("archiver");
        if (!isset($zipcommand) && !$use_zip_extension) {
            if ($archiver_fullpath == false) {
                exit($lang["archiver-utility-not-found"]);
            }
        }
        echo print_r($_POST) . print_r($_GET);
        if (getval("lastqueued", "")) {
            debug("DEBUG: Imagestream - last queued file");
            $ref = copy_resource(0 - $userref);
            # Copy from user template
            debug("DEBUG: Imagestream - creating resource: " . $ref);
            # Create the zip file
            $imagestreamzippath = get_resource_path($ref, true, "", true, "zip");
            if ($use_zip_extension) {
                $zip = new ZipArchive();
                $zip->open($imagestreamzippath, ZIPARCHIVE::CREATE);
            }
            $deletion_array = array();
            debug("DEBUG: opening directory: " . $targetDir);
            $imagestream_files = opendir($targetDir);
            $imagestream_workingfiles = get_temp_dir() . DIRECTORY_SEPARATOR . "plupload" . DIRECTORY_SEPARATOR . $session_hash . "workingfiles";
            if (!file_exists($imagestream_workingfiles)) {
                if ($config_windows) {
                    @mkdir($imagestream_workingfiles);
                } else {
                    @mkdir($imagestream_workingfiles, 0777, true);
                }
            }
            $filenumber = 00;
            $imagestream_filelist = array();
            while ($imagestream_filelist[] = readdir($imagestream_files)) {
                sort($imagestream_filelist);
            }
            closedir($imagestream_files);
            $imageindex = 1;
            foreach ($imagestream_filelist as $imagestream_file) {
                if ($imagestream_file != '.' && $imagestream_file != '..') {
                    $filenumber = sprintf("%03d", $filenumber);
                    $deletion_array[] = $targetDir . DIRECTORY_SEPARATOR . $imagestream_file;
                    if (!$use_zip_extension) {
                        $imagestreamcmd_file = get_temp_dir(false, $id) . "/imagestreamzipcmd" . $imagestream_file . ".txt";
                        $fh = fopen($imagestreamcmd_file, 'w') or die("can't open file");
                        fwrite($fh, $targetDir . DIRECTORY_SEPARATOR . $imagestream_file . "\r\n");
                        fclose($fh);
                        $deletion_array[] = $imagestreamcmd_file;
                    }
                    if ($use_zip_extension) {
                        debug("DEBUG: Imagestream - adding filename: " . $imagestream_file);
                        debug("DEBUG: using zip PHP extension, set up zip at : " . $imagestreamzippath);
                        $zip->addFile($imagestream_file);
                        debug(" Added files number : " . $zip->numFiles);
                        $wait = $zip->close();
                        debug("DEBUG: closed zip");
                    } else {
                        if ($archiver_fullpath) {
                            debug("DEBUG: using archiver, running command: \r\n" . $archiver_fullpath . " " . $collection_download_settings[0]["arguments"] . " " . escapeshellarg($imagestreamzippath) . " " . $archiver_listfile_argument . escapeshellarg($imagestream_file));
                            run_command($archiver_fullpath . " " . $collection_download_settings[0]["arguments"] . " " . escapeshellarg($imagestreamzippath) . " " . $archiver_listfile_argument . escapeshellarg($imagestreamcmd_file));
                        } else {
                            if (!$use_zip_extension) {
                                if ($config_windows) {
                                    debug("DEBUG: using zip command: . {$zipcommand} " . escapeshellarg($imagestreamzippath) . " @" . escapeshellarg($imagestreamcmd_file));
                                    exec("{$zipcommand} " . escapeshellarg($imagestreamzippath) . " @" . escapeshellarg($imagestreamcmd_file));
                                } else {
                                    # Pipe the command file, containing the filenames, to the executable.
                                    exec("{$zipcommand} " . escapeshellarg($imagestreamzippath) . " -@ < " . escapeshellarg($imagestreamcmd_file));
                                }
                            }
                        }
                    }
                    #Create a JPEG if not already in that format
                    $imagestream_file_parts = explode('.', $imagestream_file);
                    $imagestream_file_ext = $imagestream_file_parts[count($imagestream_file_parts) - 1];
                    $imagestream_file_noext = basename($imagestream_file, $imagestream_file_ext);
                    global $imagemagick_path, $imagemagick_quality;
                    $icc_transform_complete = false;
                    # Camera RAW images need prefix
                    if (preg_match('/^(dng|nef|x3f|cr2|crw|mrw|orf|raf|dcr)$/i', $imagestream_file_ext, $rawext)) {
                        $prefix = $rawext[0] . ':';
                    }
                    # Locate imagemagick.
                    $convert_fullpath = get_utility_path("im-convert");
                    if ($convert_fullpath == false) {
                        exit("Could not find ImageMagick 'convert' utility at location '{$imagemagick_path}'.");
                    }
                    $prefix = '';
                    if ($prefix == "cr2:" || $prefix == "nef:") {
                        $flatten = "";
                    } else {
                        $flatten = "-flatten";
                    }
                    $command = $convert_fullpath . ' ' . escapeshellarg($targetDir . DIRECTORY_SEPARATOR . $imagestream_file) . ' +matte ' . $flatten . ' -quality ' . $imagemagick_quality;
                    # EXPERIMENTAL CODE TO USE EXISTING ICC PROFILE IF PRESENT
                    global $icc_extraction, $icc_preview_profile, $icc_preview_options, $ffmpeg_supported_extensions;
                    if ($icc_extraction) {
                        $iccpath = $targetDir . DIRECTORY_SEPARATOR . $imagestream_file . '.icc';
                        if (!file_exists($iccpath) && !isset($iccfound) && $extension != "pdf" && !in_array($imagestream_file_ext, $ffmpeg_supported_extensions)) {
                            // extracted profile doesn't exist. Try extracting.
                            if (extract_icc_profile($ref, $imagestream_file_ext)) {
                                $iccfound = true;
                            } else {
                                $iccfound = false;
                            }
                        }
                    }
                    if ($icc_extraction && file_exists($iccpath) && !$icc_transform_complete) {
                        // we have an extracted ICC profile, so use it as source
                        $targetprofile = dirname(__FILE__) . '/../iccprofiles/' . $icc_preview_profile;
                        $profile = " +profile \"*\" -profile {$iccpath} {$icc_preview_options} -profile {$targetprofile} +profile \"*\" ";
                        $icc_transform_complete = true;
                    } else {
                        // use existing strategy for color profiles
                        # Preserve colour profiles? (omit for smaller sizes)
                        $profile = "+profile \"*\" -colorspace RGB";
                        # By default, strip the colour profiles ('+' is remove the profile, confusingly)
                        #if ($imagemagick_preserve_profiles && $id!="thm" && $id!="col" && $id!="pre" && $id!="scr") {$profile="";}
                    }
                    $runcommand = $command . " +matte {$profile} " . escapeshellarg($imagestream_workingfiles . DIRECTORY_SEPARATOR . "imagestream" . $filenumber . ".jpg");
                    $deletion_array[] = $imagestream_workingfiles . DIRECTORY_SEPARATOR . "imagestream" . $filenumber . ".jpg";
                    $output = run_command($runcommand);
                    debug("processed file" . $filenumber . ": " . $imagestream_file . "\r\n");
                    debug("Image index: " . $imageindex . ". file count: " . count($imagestream_filelist));
                    if ($filenumber == 00) {
                        $snapshotsize = getimagesize($imagestream_workingfiles . DIRECTORY_SEPARATOR . "imagestream" . $filenumber . ".jpg");
                        list($width, $height) = $snapshotsize;
                        # Frame size must be a multiple of two
                        if ($width % 2) {
                            $width++;
                        }
                        if ($height % 2) {
                            $height++;
                        }
                    }
                    if ($imageindex == count($imagestream_filelist) - 1) {
                        $additionalfile = $filenumber + 1;
                        $additionalfile = sprintf("%03d", $additionalfile);
                        copy($imagestream_workingfiles . DIRECTORY_SEPARATOR . "imagestream" . $filenumber . ".jpg", $imagestream_workingfiles . DIRECTORY_SEPARATOR . "imagestream" . $additionalfile . ".jpg");
                        $deletion_array[] = $imagestream_workingfiles . DIRECTORY_SEPARATOR . "imagestream" . $additionalfile . ".jpg";
                    }
                    $filenumber++;
                }
                #end of loop for each uploadedfile
                $imageindex++;
            }
            #Add the resource and move this zip file, set extension
            # Add to collection?
            if ($collection_add != "") {
                add_resource_to_collection($ref, $collection_add);
            }
            # Log this
            daily_stat("Resource upload", $ref);
            resource_log($ref, "u", 0);
            #Change this!!!!!!!!!!!
            #$status=upload_file($ref,true,false,false));
            if (!$config_windows) {
                @chmod($imagestreamzippath, 0777);
            }
            # Store extension in the database and update file modified time.
            sql_query("update resource set file_extension='zip',preview_extension='zip',file_modified=now(), has_image=0 where ref='{$ref}'");
            #update_field($ref,$filename_field,$filename);
            update_disk_usage($ref);
            # create the mp4 version
            # Add a new alternative file
            $aref = add_alternative_file($ref, "MP4 version");
            $imagestreamqtfile = get_resource_path($ref, true, "", false, "mp4", -1, 1, false, "", $aref);
            $shell_exec_cmd = $ffmpeg_fullpath . " -loglevel panic -y -r " . $imagestream_transitiontime . " -i " . $imagestream_workingfiles . DIRECTORY_SEPARATOR . "imagestream%3d.jpg -r " . $imagestream_transitiontime . " -s {$width}x{$height} " . $imagestreamqtfile;
            echo "Running command: " . $shell_exec_cmd;
            if ($config_windows) {
                $shell_exec_cmd = $ffmpeg_fullpath . " -loglevel panic -y -r " . $imagestream_transitiontime . " -i " . $imagestream_workingfiles . DIRECTORY_SEPARATOR . "imagestream%%3d.jpg -r " . $imagestream_transitiontime . " -s {$width}x{$height} " . $imagestreamqtfile;
                file_put_contents(get_temp_dir() . DIRECTORY_SEPARATOR . "imagestreammp4" . $session_hash . ".bat", $shell_exec_cmd);
                $shell_exec_cmd = get_temp_dir() . DIRECTORY_SEPARATOR . "imagestreammp4" . $session_hash . ".bat";
                $deletion_array[] = $shell_exec_cmd;
            }
            run_command($shell_exec_cmd);
            debug("DEBUG created slideshow MP4 video");
            if (!$config_windows) {
                @chmod($imagestreamqtfile, 0777);
            }
            $file_size = @filesize_unlimited($imagestreamqtfile);
            # Save alternative file data.
            sql_query("update resource_alt_files set file_name='quicktime.mp4',file_extension='mp4',file_size='" . $file_size . "',creation_date=now() where resource='{$ref}' and ref='{$aref}'");
            #create the FLV preview as per normal video processing if possible?
            if ($height < $ffmpeg_preview_min_height) {
                $height = $ffmpeg_preview_min_height;
            }
            if ($width < $ffmpeg_preview_min_width) {
                $width = $ffmpeg_preview_min_width;
            }
            if ($height > $ffmpeg_preview_max_height) {
                $width = ceil($width * ($ffmpeg_preview_max_height / $height));
                $height = $ffmpeg_preview_max_height;
            }
            if ($width > $ffmpeg_preview_max_width) {
                $height = ceil($height * ($ffmpeg_preview_max_width / $width));
                $width = $ffmpeg_preview_max_width;
            }
            $flvzippreviewfile = get_resource_path($ref, true, "pre", false, $ffmpeg_preview_extension);
            $shell_exec_cmd = $ffmpeg_fullpath . " -loglevel panic -y -i " . $imagestreamqtfile . " {$ffmpeg_preview_options} -s {$width}x{$height} " . $flvzippreviewfile;
            debug("Running command: " . $shell_exec_cmd);
            if ($config_windows) {
                file_put_contents(get_temp_dir() . DIRECTORY_SEPARATOR . "imagestreamflv" . $session_hash . ".bat", $shell_exec_cmd);
                $shell_exec_cmd = get_temp_dir() . DIRECTORY_SEPARATOR . "imagestreamflv" . $session_hash . ".bat";
                $deletion_array[] = $shell_exec_cmd;
            }
            run_command($shell_exec_cmd);
            debug("DEBUG created slideshow FLV video");
            if (!$config_windows) {
                @chmod($flvzippreviewfile, 0777);
            }
            #Tidy up
            rcRmdir($imagestream_workingfiles);
            rcRmdir($targetDir);
            foreach ($deletion_array as $tmpfile) {
                debug("\r\nDEBUG: Deleting: " . $tmpfile);
                delete_exif_tmpfile($tmpfile);
            }
            echo "SUCCESS";
            #return true;
            exit;
        } else {
            echo "SUCCESS";
            exit;
        }
        return true;
    } else {
        return false;
    }
}
function extract_icc($infile)
{
    global $config_windows;
    # Locate imagemagick, or fail this if it isn't installed
    $convert_fullpath = get_utility_path("im-convert");
    if ($convert_fullpath == false) {
        return false;
    }
    if ($config_windows) {
        $stderrclause = '';
    } else {
        $stderrclause = '2>&1';
    }
    //$outfile=get_resource_path($ref,true,"",false,$extension.".icc");
    //new, more flexible approach: we will just create a file for anything the caller hands to us.
    //this makes things work with alternatives, the deepzoom plugin, etc.
    $path_parts = pathinfo($infile);
    $outfile = $path_parts['dirname'] . '/' . $path_parts['filename'] . '.' . $path_parts['extension'] . '.icc';
    if (file_exists($outfile)) {
        // extracted profile already existed. We'll remove it and start over
        unlink($outfile);
    }
    $cmdout = run_command("{$convert_fullpath} {$infile}" . '[0]' . " {$outfile} {$stderrclause}");
    if (preg_match("/no color profile is available/", $cmdout) || !file_exists($outfile) || filesize_unlimited($outfile) == 0) {
        // the icc profile extraction failed. So delete file.
        if (file_exists($outfile)) {
            unlink($outfile);
        }
        return false;
    }
    if (file_exists($outfile)) {
        return true;
    } else {
        return false;
    }
}
Beispiel #14
0
		?>
		<td class="DownloadButton DownloadDisabled"><?php echo $lang["access1"]?></td>
		<?php
		}
	?>
	</tr>
	<?php
	}
	
if (isset($flv_download) && $flv_download)
	{
	# Allow the FLV preview to be downloaded. $flv_download is set when showing the FLV preview video above.
	?>
	<tr class="DownloadDBlend">
	<td class="DownloadFileName"><h2><?php echo (isset($ffmpeg_preview_download_name)) ? $ffmpeg_preview_download_name : str_replace_formatted_placeholder("%extension", $ffmpeg_preview_extension, $lang["cell-fileoftype"]); ?></h2></td>
	<td class="DownloadFileSize"><?php echo formatfilesize(filesize_unlimited($flvfile))?></td>
	<td class="DownloadButton">
	<?php if (!$direct_download || $save_as){?>
		<a href="<?php echo $baseurl_short?>pages/terms.php?ref=<?php echo urlencode($ref)?>&search=<?php echo $search ?>&k=<?php echo urlencode($k)?>&url=<?php echo urlencode("pages/download_progress.php?ref=" . $ref . "&ext=" . $ffmpeg_preview_extension . "&size=pre&k=" . $k . "&search=" . urlencode($search) . "&offset=" . $offset . "&archive=" . $archive . "&sort=".$sort."&order_by=" . urlencode($order_by))?>"  onClick="return CentralSpaceLoad(this,true);"><?php echo $lang["action-download"] ?></a>
	<?php } else { ?>
		<a href="#" onclick="directDownload('<?php echo $baseurl_short?>pages/download_progress.php?ref=<?php echo urlencode($ref)?>&ext=<?php echo $ffmpeg_preview_extension?>&size=pre&k=<?php echo urlencode($k)?>')"><?php echo $lang["action-download"]?></a>
	<?php } // end if direct_download ?></td>
	</tr>
	<?php
	}

hook("additionalresourcetools2");
	
# Alternative files listing
$alt_access=hook("altfilesaccess");
if ($access==0) $alt_access=true; # open access (not restricted)
Beispiel #15
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;
	}
Beispiel #16
0
		?>
		<td class="DownloadButton DownloadDisabled"><?php echo $lang["access1"]?></td>
		<?php
		}
	?>
	</tr>
	<?php
	}
	
if (isset($flv_download) && $flv_download)
	{
	# Allow the FLV preview to be downloaded. $flv_download is set when showing the FLV preview video above.
	?>
	<tr class="DownloadDBlend">
	<td><h2><?php echo (isset($ffmpeg_preview_download_name)) ? $ffmpeg_preview_download_name : str_replace_formatted_placeholder("%extension", $ffmpeg_preview_extension, $lang["cell-fileoftype"]); ?></h2></td>
	<td><?php echo formatfilesize(filesize_unlimited($flvfile))?></td>
	<td class="DownloadButton">
	<?php if (!$direct_download || $save_as){?>
		<a href="<?php echo $baseurl_short?>pages/terms.php?ref=<?php echo urlencode($ref)?>&search=<?php echo $search ?>&k=<?php echo urlencode($k)?>&url=<?php echo urlencode("pages/download_progress.php?ref=" . $ref . "&ext=" . $ffmpeg_preview_extension . "&size=pre&k=" . $k . "&search=" . urlencode($search) . "&offset=" . $offset . "&archive=" . $archive . "&sort=".$sort."&order_by=" . urlencode($order_by))?>"  onClick="return CentralSpaceLoad(this,true);"><?php echo $lang["action-download"] ?></a>
	<?php } else { ?>
		<a href="#" onclick="directDownload('<?php echo $baseurl_short?>pages/download_progress.php?ref=<?php echo urlencode($ref)?>&ext=<?php echo $ffmpeg_preview_extension?>&size=pre&k=<?php echo urlencode($k)?>')"><?php echo $lang["action-download"]?></a>
	<?php } // end if direct_download ?></td>
	</tr>
	<?php
	}
	
# Alternative files listing
if ($access==0) # open access only (not restricted)
	{
	$alt_order_by="";$alt_sort="";
	if ($alt_types_organize){$alt_order_by="alt_type";$alt_sort="asc";} 
# get all resources in the DB
$resources = sql_query("select ref,field" . $view_title_field . ",file_extension from resource where ref>0 order by ref DESC");
//loop:
foreach ($resources as $resource) {
    $resource_path = get_resource_path($resource['ref'], true, "", false, $resource['file_extension']);
    if (file_exists($resource_path)) {
        $filesize = filesize_unlimited($resource_path);
        sql_query("update resource_dimensions set file_size={$filesize} where resource='" . $resource['ref'] . "'");
        echo "Ref: " . $resource['ref'] . " - " . $resource['field' . $view_title_field] . " - updating resource_dimensions file_size column - " . formatfilesize($filesize);
        echo "<br />";
    }
    $alt_files = sql_query("select file_extension,file_name,ref from resource_alt_files where resource=" . $resource['ref']);
    if (count($alt_files) > 0) {
        foreach ($alt_files as $alt) {
            $alt_path = get_resource_path($resource['ref'], true, "", false, $alt['file_extension'], -1, 1, false, "", $alt['ref']);
            if (file_exists($alt_path)) {
                // allow to re-run script without re-copying files
                $filesize = filesize_unlimited($alt_path);
                sql_query("update resource_alt_files set file_size={$filesize} where resource='" . $resource['ref'] . "' and ref='" . $alt['ref'] . "'");
                echo "&nbsp;&nbsp;&nbsp;&nbsp;ALT - " . $alt['file_name'] . " - updating alt file size - " . formatfilesize($filesize);
                echo "<br />";
            }
        }
    }
    update_disk_usage($resource['ref']);
    echo "updating disk usage";
    echo "<br />";
    echo "<br />";
    flush();
    ob_flush();
}
            $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");
        }
    }
    redirect("pages/view.php?ref=" . $ref);
}
include "../../../include/header.php";
?>

<div class="BasicsBox">
<h1><?php 
echo $lang["splitpdf"];
function update_disk_usage($resource)
	{

	# we're also going to record the size of the primary resource here before we do the entire folder
	$ext = sql_value("select file_extension value from resource where ref = '$resource'",'jpg');
	$path = get_resource_path($resource,true,'',false,$ext);
	if (file_exists($path)){
		$rsize = filesize_unlimited($path);
	} else {
		$rsize = 0;
	}

	# Scan the appropriate filestore folder and update the disk usage fields on the resource table.
	$dir=dirname(get_resource_path($resource,true,"",false));
	if (!file_exists($dir)) {return false;} # Folder does not yet exist.
	$d = dir($dir); 
	$total=0;
	while ($f = $d->read())
		{
		if ($f!=".." && $f!=".")
			{
			$s=filesize_unlimited($dir . "/" .$f);
			#echo "<br/>-". $f . " : " . $s;
			$total+=$s;
			}
		}
	#echo "<br/>total=" . $total;
	sql_query("update resource set disk_usage='$total',disk_usage_last_updated=now(),file_size='$rsize' where ref='$resource'");
	return true;
	}
Beispiel #20
0
<div class="Fixed">
<?php
if ($resource["has_image"]==1)
	{
	?><img align="top" src="<?php echo get_resource_path($ref,false,($edit_large_preview?"pre":"thm"),false,$resource["preview_extension"],-1,1,checkperm("w"))?>" class="ImageBorder" style="margin-right:10px;"/><br />
	<?php
	}
else
	{
	# Show the no-preview icon
	?>
	<img src="../gfx/<?php echo get_nopreview_icon($resource["resource_type"],$resource["file_extension"],true)?>" />
	<br />
	<?php
	}
if ($resource["file_extension"]!="") { ?><strong><?php echo str_replace_formatted_placeholder("%extension", $resource["file_extension"], $lang["cell-fileoftype"]) . " (" . formatfilesize(@filesize_unlimited(get_resource_path($ref,true,"",false,$resource["file_extension"]))) . ")" ?></strong><br /><?php } ?>

	<?php if ($resource["has_image"]!=1) { ?>
	<a href="<?php echo $baseurl_short?>pages/upload.php?ref=<?php echo urlencode($ref) ?>&search=<?php echo urlencode($search)?>&offset=<?php echo urlencode($offset) ?>&order_by=<?php echo urlencode($order_by) ?>&sort=<?php echo urlencode($sort) ?>&archive=<?php echo urlencode($archive) ?>&upload_a_file=true" onClick="return CentralSpaceLoad(this,true);">&gt;&nbsp;<?php echo $lang["uploadafile"]?></a>
	<?php } else { ?>
	<a href="<?php echo $baseurl_short?>pages/upload_<?php echo $top_nav_upload_type ?>.php?ref=<?php echo urlencode($ref) ?>&search=<?php echo urlencode($search)?>&offset=<?php echo urlencode($offset) ?>&order_by=<?php echo urlencode($order_by) ?>&sort=<?php echo urlencode($sort) ?>&archive=<?php echo urlencode($archive) ?>&replace_resource=<?php echo urlencode($ref)  ?>&resource_type=<?php echo $resource['resource_type']?>" onClick="return CentralSpaceLoad(this,true);">&gt;&nbsp;<?php echo $lang["replacefile"]?></a>
	<?php hook("afterreplacefile"); ?>
	<?php } ?>
	<?php if (! $disable_upload_preview) { ?><br />
	<a href="<?php echo $baseurl_short?>pages/upload_preview.php?ref=<?php echo urlencode($ref) ?>&search=<?php echo urlencode($search)?>&offset=<?php echo urlencode($offset) ?>&order_by=<?php echo urlencode($order_by) ?>&sort=<?php echo urlencode($sort) ?>&archive=<?php echo urlencode($archive) ?>" onClick="return CentralSpaceLoad(this,true);">&gt;&nbsp;<?php echo $lang["uploadpreview"]?></a><?php } ?>
	<?php if (! $disable_alternative_files) { ?><br />
	<a href="<?php echo $baseurl_short?>pages/alternative_files.php?ref=<?php echo urlencode($ref) ?>&search=<?php echo urlencode($search)?>&offset=<?php echo urlencode($offset) ?>&order_by=<?php echo urlencode($order_by) ?>&sort=<?php echo urlencode($sort) ?>&archive=<?php echo urlencode($archive) ?>"  onClick="return CentralSpaceLoad(this,true);">&gt;&nbsp;<?php echo $lang["managealternativefiles"]?></a><?php } ?>
	<?php if ($allow_metadata_revert){?><br />
	<a href="<?php echo $baseurl_short?>pages/edit.php?ref=<?php echo urlencode($ref) ?>&exif=true&search=<?php echo urlencode($search)?>&offset=<?php echo urlencode($offset) ?>&order_by=<?php echo urlencode($order_by) ?>&sort=<?php echo urlencode($sort) ?>&archive=<?php echo urlencode($archive) ?>" onClick="return confirm('<?php echo $lang["confirm-revertmetadata"]?>');">&gt; 
	<?php echo $lang["action-revertmetadata"]?></a><?php } ?>
	<?php hook("afterfileoptions"); ?>
Beispiel #21
0
		<?php 
                    }
                    ?>
	</tr>
	<?php 
                }
                if (isset($flv_download) && $flv_download) {
                    # Allow the FLV preview to be downloaded. $flv_download is set when showing the FLV preview video above.
                    ?>
	<tr class="DownloadDBlend">
	<td class="DownloadFileName"><h2><?php 
                    echo isset($ffmpeg_preview_download_name) ? $ffmpeg_preview_download_name : str_replace_formatted_placeholder("%extension", $ffmpeg_preview_extension, $lang["cell-fileoftype"]);
                    ?>
</h2></td>
	<td class="DownloadFileSize"><?php 
                    echo formatfilesize(filesize_unlimited($flvfile));
                    ?>
</td>
	<td class="DownloadButton">
	<?php 
                    if (!$direct_download || $save_as) {
                        ?>
		<a href="<?php 
                        echo $baseurl_short;
                        ?>
pages/terms.php?ref=<?php 
                        echo urlencode($ref);
                        ?>
&search=<?php 
                        echo $search;
                        ?>
function recover_resource_files($id, $res, $meta, $alts)
{
    // this is where we actually start doing the import
    global $res_skipped;
    $ext = pathinfo($res, PATHINFO_EXTENSION);
    if (sql_value("select count(*) value from resource where ref = '{$id}'", "0") > 0) {
        echo "resource {$id} already exists! Skipping!\n";
        $res_skipped++;
        return false;
    } else {
        echo "new resource\n";
        // 1: photo, 2:document, 3:video, 4: audio
        // going to have to guess at the type for now, since the xml file did not record it. Fixme - xml file should have this.
        global $ffmpeg_supported_extensions, $ffmpeg_audio_extensions, $camera_autorotation_ext, $unoconv_extensions;
        if (in_array($ext, $ffmpeg_supported_extensions)) {
            $rtype = '3';
        } elseif (in_array($ext, $ffmpeg_audio_extensions)) {
            $rtype = '4';
        } elseif (in_array($ext, $unoconv_extensions)) {
            $rtype = '2';
        } elseif (in_array($ext, $camera_autorotation_ext)) {
            $rtype = '1';
        } else {
            $rtype = 'null';
        }
        $sql = "insert into resource (ref, title, file_extension,resource_type) values ('{$id}','RECOVERED','{$ext}','{$rtype}')";
        sql_query($sql);
        $newpath = get_resource_path($id, true, '', true, $ext);
        if (!copy($res, $newpath)) {
            echo "ERROR copying {$res}.\n";
            die;
        }
        // fixme: add alternates
        foreach ($alts as $altid => $altpath) {
            $filext = pathinfo($altpath, PATHINFO_EXTENSION);
            $filesize = filesize_unlimited($altpath);
            $newid = add_alternative_file($id, "{$altid}.{$filext}", '', '', $filext, $filesize);
            $newpath = get_resource_path($id, true, "", false, $filext, -1, 1, false, "", $newid);
            if (!copy($altpath, $newpath)) {
                echo "ERROR copying {$res}.\n";
                die;
            }
            echo "previews: " . create_previews($id, false, $filext, false, false, $newid);
            echo "\n\n";
        }
        create_previews($id, false, $ext);
        populate_metadata_from_dump($id, $meta);
    }
}
                 # 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;
 }
 # Remove temporary files.
 foreach ($deletion_array as $tmpfile) {
     delete_exif_tmpfile($tmpfile);
 }
 # Get the file size of the archive.
 $filesize = @filesize_unlimited($zipfile);
 if ($use_collection_name_in_zip_name) {
     # Use collection name (if configured)
     if ($archiver) {
         $filename = $lang["collectionidprefix"] . $collection . "-" . safe_file_name(i18n_get_collection_name($collectiondata)) . "-" . $size . "." . $collection_download_settings[$settings_id]["extension"];
     } else {
         $filename = $lang["collectionidprefix"] . $collection . "-" . safe_file_name(i18n_get_collection_name($collectiondata)) . "-" . $size . ".zip";
     }
 } else {
     # Do not include the collection name in the filename (default)
     if ($archiver) {
         $filename = $lang["collectionidprefix"] . $collection . "-" . $size . "." . $collection_download_settings[$settings_id]["extension"];
     } else {
         $filename = $lang["collectionidprefix"] . $collection . "-" . $size . ".zip";
     }
 }
Beispiel #24
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 {
            $fileinfo = get_original_imagesize($ref, $path2, $extension);
            $filesize = $fileinfo[0];
            $sw = $fileinfo[1];
            $sh = $fileinfo[2];
        }
        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");
        $file_exists = file_exists($path);
        if (($file_exists || !$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 ($file_exists) {
                    $filesize = @filesize_unlimited($path);
                } else {
                    $filesize = 0;
                }
                if ($filesize === 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;
}
Beispiel #25
0
function ProcessFolder($folder, $version_dir, &$resource_array, &$resource_error)
{
    global $lang, $syncdir, $nogo, $staticsync_max_files, $count, $done, $modtimes, $lastsync, $ffmpeg_preview_extension, $staticsync_autotheme, $staticsync_folder_structure, $staticsync_extension_mapping_default, $staticsync_extension_mapping, $staticsync_mapped_category_tree, $staticsync_title_includes_path, $staticsync_ingest, $staticsync_mapfolders, $staticsync_alternatives_suffix, $theme_category_levels, $staticsync_defaultstate, $additional_archive_states, $staticsync_extension_mapping_append_values, $image_alternatives, $exclude_resize, $post_host, $media_endpoint, $image_required_height, $sync_bucket, $aws_key, $aws_secret_key;
    $collection = 0;
    echo "Processing Folder: {$folder}" . PHP_EOL;
    #$alt_path = get_resource_path(59, TRUE, '', FALSE, 'png', -1, 1, FALSE, '', 4);
    # List all files in this folder.
    $dh = opendir($folder);
    while (($file = readdir($dh)) !== false) {
        if ($file == '.' || $file == '..') {
            continue;
        }
        $filetype = filetype($folder . "/" . $file);
        $fullpath = $folder . "/" . $file;
        $shortpath = str_replace($syncdir . "/", '', $fullpath);
        # Work out extension
        $extension = explode(".", $file);
        if (count($extension) > 1) {
            $extension = trim(strtolower($extension[count($extension) - 1]));
        } else {
            //No extension
            $extension = "";
        }
        if (strpos($fullpath, $nogo)) {
            echo "This directory is to be ignored." . PHP_EOL;
            continue;
        }
        if ($staticsync_mapped_category_tree) {
            $path_parts = explode("/", $shortpath);
            array_pop($path_parts);
            touch_category_tree_level($path_parts);
        }
        # -----FOLDERS-------------
        if (($filetype == "dir" || $filetype == "link") && strpos($nogo, "[{$file}]") === false && strpos($file, $staticsync_alternatives_suffix) === false) {
            # Get current version direcotries.
            if (preg_match("/[0-9]{2}-[0-9]{2}-[0-9]{4}\$/", $file)) {
                if (!in_array($file, $version_dir)) {
                    array_push($version_dir, $file);
                }
                if (preg_match('/in_progress*/', $file)) {
                    echo "The Barcode is still being processed." . PHP_EOL;
                    continue;
                }
            }
            # Recurse
            ProcessFolder($folder . "/" . $file, $version_dir, $resource_array, $resource_error);
        }
        $psd_files = array();
        if (preg_match('/images/', $fullpath)) {
            $path_array = explode('/', $fullpath);
            $psd_array = array_splice($path_array, 0, array_search('images', $path_array));
            $psd_path = implode('/', $psd_array) . '/psd/';
            $psd_files = array_diff(scandir($psd_path), array('..', '.'));
            foreach ($psd_files as $index => $psd_file) {
                $psd_files[$index] = pathinfo($psd_file, PATHINFO_FILENAME);
            }
        }
        # -------FILES---------------
        if ($filetype == "file" && substr($file, 0, 1) != "." && strtolower($file) != "thumbs.db") {
            /* Below Code Adapted  from CMay's bug report */
            global $banned_extensions;
            # Check to see if extension is banned, do not add if it is banned
            if (array_search($extension, $banned_extensions)) {
                continue;
            }
            /* Above Code Adapted from CMay's bug report */
            $count++;
            if ($count > $staticsync_max_files) {
                return true;
            }
            $last_sync_date = sql_value("select value from sysvars where name = 'last_sync'", "");
            $file_creation_date = date("Y-m-d H:i:s", filectime($fullpath));
            if (isset($last_sync_date) && $last_sync_date > $file_creation_date) {
                echo "No new file found.." . PHP_EOL;
                continue;
            }
            # Already exists?
            if (!isset($done[$shortpath])) {
                echo "Processing file: {$fullpath}" . PHP_EOL;
                if ($collection == 0 && $staticsync_autotheme) {
                    # Make a new collection for this folder.
                    $e = explode("/", $shortpath);
                    $theme = ucwords($e[0]);
                    $themesql = "theme='" . ucwords(escape_check($e[0])) . "'";
                    $themecolumns = "theme";
                    $themevalues = "'" . ucwords(escape_check($e[0])) . "'";
                    if ($staticsync_folder_structure) {
                        for ($x = 0; $x < count($e) - 1; $x++) {
                            if ($x != 0) {
                                $themeindex = $x + 1;
                                if ($themeindex > $theme_category_levels) {
                                    $theme_category_levels = $themeindex;
                                    if ($x == count($e) - 2) {
                                        echo PHP_EOL . PHP_EOL . "UPDATE THEME_CATEGORY_LEVELS TO {$themeindex} IN CONFIG!!!!" . PHP_EOL . PHP_EOL;
                                    }
                                }
                                $th_name = ucwords(escape_check($e[$x]));
                                $themesql .= " AND theme{$themeindex} = '{$th_name}'";
                                $themevalues .= ",'{$th_name}'";
                                $themecolumns .= ",theme{$themeindex}";
                            }
                        }
                    }
                    $name = count($e) == 1 ? '' : $e[count($e) - 2];
                    echo "Collection {$name}, theme={$theme}" . PHP_EOL;
                    $ul_username = $theme;
                    $escaped_name = escape_check($name);
                    $collection = sql_value("SELECT ref value FROM collection WHERE name='{$escaped_name}' AND {$themesql}", 0);
                    if ($collection == 0) {
                        sql_query("INSERT INTO collection (name,created,public,{$themecolumns},allow_changes)\n                                                   VALUES ('{$escaped_name}', NOW(), 1, {$themevalues}, 0)");
                        $collection = sql_insert_id();
                    }
                }
                # Work out a resource type based on the extension.
                $type = $staticsync_extension_mapping_default;
                reset($staticsync_extension_mapping);
                foreach ($staticsync_extension_mapping as $rt => $extensions) {
                    if (in_array($extension, $extensions)) {
                        $type = $rt;
                    }
                }
                $modified_type = hook('modify_type', 'staticsync', array($type));
                if (is_numeric($modified_type)) {
                    $type = $modified_type;
                }
                # Formulate a title
                if ($staticsync_title_includes_path) {
                    $title_find = array('/', '_', ".{$extension}");
                    $title_repl = array(' - ', ' ', '');
                    $title = ucfirst(str_ireplace($title_find, $title_repl, $shortpath));
                } else {
                    $title = str_ireplace(".{$extension}", '', $file);
                }
                $modified_title = hook('modify_title', 'staticsync', array($title));
                if ($modified_title !== false) {
                    $title = $modified_title;
                }
                # Import this file
                #$r = import_resource($shortpath, $type, $title, $staticsync_ingest);
                #Check for file name containing the psd.
                if (!empty($psd_files)) {
                    $image_file_array = explode('/', $fullpath);
                    $image_file = $image_file_array[count($image_file_array) - 1];
                    $image_psd_name = explode('_', $image_file)[0];
                    if (array_search($image_psd_name, $psd_files)) {
                        #Image name is in right format.
                        if (!validate_image_size($fullpath, $image_required_height)) {
                            $resource_error['size'][$file] = $fullpath;
                        }
                        $r = import_resource($fullpath, $type, $title, $staticsync_ingest);
                        sql_query("INSERT INTO resource_data (resource,resource_type_field,value)\n                               VALUES ('{$r}', (SELECT ref FROM resource_type_field WHERE name = 'logical_id'), '{$image_psd_name}')");
                        $original_filepath = sql_query("SELECT value FROM resource_data WHERE resource = '{$r}' AND\n                                                     resource_type_field = (SELECT ref FROM resource_type_field where name = 'original_filepath')");
                        if (isset($original_filepath)) {
                            sql_query("INSERT INTO resource_data (resource,resource_type_field,value)\n                                 VALUES ('{$r}',(SELECT ref FROM resource_type_field WHERE name = 'original_filepath'), '{$fullpath}')");
                        }
                    } else {
                        echo "Filename '{$fullpath}' is not in right format.." . PHP_EOL;
                        $resource_error['name'][$file] = $fullpath;
                        continue;
                    }
                } elseif (word_in_string($exclude_resize, explode('/', $fullpath))) {
                    $r = import_resource($fullpath, $type, $title, $staticsync_ingest);
                }
                if ($r !== false) {
                    array_push($resource_array, $r);
                    # Create current version for resource.
                    #print_r($version_dir);
                    if (count($version_dir) == 1) {
                        sql_query("INSERT into resource_data (resource,resource_type_field,value)\n                                    VALUES ('{$r}',(SELECT ref FROM resource_type_field WHERE name = 'current'), 'TRUE')");
                    }
                    $sync_status = sync_to_s3($syncdir, $sync_bucket, $aws_key, $aws_secret_key);
                    if (!$sync_status) {
                        echo "Failed to sync";
                    }
                    # Add to mapped category tree (if configured)
                    if (isset($staticsync_mapped_category_tree)) {
                        $basepath = '';
                        # Save tree position to category tree field
                        # For each node level, expand it back to the root so the full path is stored.
                        for ($n = 0; $n < count($path_parts); $n++) {
                            if ($basepath != '') {
                                $basepath .= "~";
                            }
                            $basepath .= $path_parts[$n];
                            $path_parts[$n] = $basepath;
                        }
                        update_field($r, $staticsync_mapped_category_tree, "," . join(",", $path_parts));
                    }
                    #This is an override to add user data to the resouces
                    if (!isset($userref)) {
                        $ul_username = ucfirst(strtolower($ul_username));
                        $current_user_ref = sql_query("Select ref from user where username = '******' ");
                        if (!empty($current_user_ref)) {
                            $current_user_ref = $current_user_ref[0]['ref'];
                            sql_query("UPDATE resource SET created_by='{$current_user_ref}' where ref = {$r}");
                        }
                    }
                    # default access level. This may be overridden by metadata mapping.
                    $accessval = 0;
                    # StaticSync path / metadata mapping
                    # Extract metadata from the file path as per $staticsync_mapfolders in config.php
                    if (isset($staticsync_mapfolders)) {
                        foreach ($staticsync_mapfolders as $mapfolder) {
                            $match = $mapfolder["match"];
                            $field = $mapfolder["field"];
                            $level = $mapfolder["level"];
                            if (strpos("/" . $shortpath, $match) !== false) {
                                # Match. Extract metadata.
                                $path_parts = explode("/", $shortpath);
                                if ($level < count($path_parts)) {
                                    // special cases first.
                                    if ($field == 'access') {
                                        # access level is a special case
                                        # first determine if the value matches a defined access level
                                        $value = $path_parts[$level - 1];
                                        for ($n = 0; $n < 3; $n++) {
                                            # if we get an exact match or a match except for case
                                            if ($value == $lang["access" . $n] || strtoupper($value) == strtoupper($lang['access' . $n])) {
                                                $accessval = $n;
                                                echo "Will set access level to " . $lang['access' . $n] . " ({$n})" . PHP_EOL;
                                            }
                                        }
                                    } else {
                                        if ($field == 'archive') {
                                            # archive level is a special case
                                            # first determin if the value matches a defined archive level
                                            $value = $mapfolder["archive"];
                                            $archive_array = array_merge(array(-2, -1, 0, 1, 2, 3), $additional_archive_states);
                                            if (in_array($value, $archive_array)) {
                                                $archiveval = $value;
                                                echo "Will set archive level to " . $lang['status' . $value] . " ({$archiveval})" . PHP_EOL;
                                            }
                                        } else {
                                            # Save the value
                                            #print_r($path_parts);
                                            $value = $path_parts[$level - 1];
                                            if ($staticsync_extension_mapping_append_values) {
                                                $given_value = $value;
                                                // append the values if possible...not used on dropdown, date, categroy tree, datetime, or radio buttons
                                                $field_info = get_resource_type_field($field);
                                                if (in_array($field['type'], array(0, 1, 2, 4, 5, 6, 7, 8))) {
                                                    $old_value = sql_value("select value value from resource_data where resource={$r} and resource_type_field={$field}", "");
                                                    $value = append_field_value($field_info, $value, $old_value);
                                                }
                                            }
                                            update_field($r, $field, trim($value));
                                            if (strtotime(trim($value))) {
                                                add_keyword_mappings($r, trim($value), $field, false, true);
                                            } else {
                                                add_keyword_mappings($r, trim($value), $field);
                                            }
                                            if ($staticsync_extension_mapping_append_values) {
                                                $value = $given_value;
                                            }
                                            echo " - Extracted metadata from path: {$value}" . PHP_EOL;
                                        }
                                    }
                                }
                            }
                        }
                    }
                    #Resize only original images.
                    if (!word_in_string($exclude_resize, explode('/', $fullpath))) {
                        echo "Creating preview..";
                        create_previews($r, false, $extension, false, false, -1, false, $staticsync_ingest);
                    }
                    # update access level
                    sql_query("UPDATE resource SET access = '{$accessval}',archive='{$staticsync_defaultstate}' WHERE ref = '{$r}'");
                    # Add any alternative files
                    $altpath = $fullpath . $staticsync_alternatives_suffix;
                    if ($staticsync_ingest && file_exists($altpath)) {
                        $adh = opendir($altpath);
                        while (($altfile = readdir($adh)) !== false) {
                            $filetype = filetype($altpath . "/" . $altfile);
                            if ($filetype == "file" && substr($file, 0, 1) != "." && strtolower($file) != "thumbs.db") {
                                # Create alternative file
                                # Find extension
                                $ext = explode(".", $altfile);
                                $ext = $ext[count($ext) - 1];
                                $description = str_replace("?", strtoupper($ext), $lang["originalfileoftype"]);
                                $file_size = filesize_unlimited($altpath . "/" . $altfile);
                                $aref = add_alternative_file($r, $altfile, $description, $altfile, $ext, $file_size);
                                $path = get_resource_path($r, true, '', true, $ext, -1, 1, false, '', $aref);
                                rename($altpath . "/" . $altfile, $path);
                                # Move alternative file
                            }
                        }
                    }
                    # Add to collection
                    if ($staticsync_autotheme) {
                        $test = '';
                        $test = sql_query("SELECT * FROM collection_resource WHERE collection='{$collection}' AND resource='{$r}'");
                        if (count($test) == 0) {
                            sql_query("INSERT INTO collection_resource (collection, resource, date_added)\n                                            VALUES ('{$collection}', '{$r}', NOW())");
                        }
                    }
                } else {
                    # Import failed - file still being uploaded?
                    echo " *** Skipping file - it was not possible to move the file (still being imported/uploaded?)" . PHP_EOL;
                }
            } else {
                # check modified date and update previews if necessary
                $filemod = filemtime($fullpath);
                if (array_key_exists($shortpath, $modtimes) && $filemod > strtotime($modtimes[$shortpath])) {
                    # File has been modified since we last created previews. Create again.
                    $rd = sql_query("SELECT ref, has_image, file_modified, file_extension FROM resource\n                                        WHERE file_path='" . escape_check($shortpath) . "'");
                    if (count($rd) > 0) {
                        $rd = $rd[0];
                        $rref = $rd["ref"];
                        echo "Resource {$rref} has changed, regenerating previews: {$fullpath}" . PHP_EOL;
                        extract_exif_comment($rref, $rd["file_extension"]);
                        # extract text from documents (e.g. PDF, DOC).
                        global $extracted_text_field;
                        if (isset($extracted_text_field)) {
                            if (isset($unoconv_path) && in_array($extension, $unoconv_extensions)) {
                                // omit, since the unoconv process will do it during preview creation below
                            } else {
                                extract_text($rref, $extension);
                            }
                        }
                        # Store original filename in field, if set
                        global $filename_field;
                        if (isset($filename_field)) {
                            update_field($rref, $filename_field, $file);
                        }
                        create_previews($rref, false, $rd["file_extension"], false, false, -1, false, $staticsync_ingest);
                        sql_query("UPDATE resource SET file_modified=NOW() WHERE ref='{$rref}'");
                    }
                }
            }
        }
    }
}
 } else {
     if ($config_windows) {
         exec("{$zipcommand} " . escapeshellarg(get_temp_dir() . "/" . $file) . " @" . escapeshellarg($cmdfile));
     } else {
         # Pipe the command file, containing the filenames, to the executable.
         exec("{$zipcommand} " . escapeshellarg(get_temp_dir() . "/" . $file) . " -@ < " . escapeshellarg($cmdfile));
     }
 }
 # Archive created, schedule the command file for deletion.
 $deletion_array[] = $cmdfile;
 # Remove temporary files.
 foreach ($deletion_array as $tmpfile) {
     delete_exif_tmpfile($tmpfile);
 }
 # Get the file size of the archive.
 $filesize = @filesize_unlimited(get_temp_dir() . "/" . $file);
 if ($use_collection_name_in_zip_name) {
     # Use collection name (if configured)
     if ($archiver) {
         $filename = $lang["collectionidprefix"] . $collection . "-" . safe_file_name(i18n_get_collection_name($collectiondata)) . "-" . $size . "." . $collection_download_settings[$settings_id]["extension"];
     } else {
         $filename = $lang["collectionidprefix"] . $collection . "-" . safe_file_name(i18n_get_collection_name($collectiondata)) . "-" . $size . ".zip";
     }
 } else {
     # Do not include the collection name in the filename (default)
     if ($archiver) {
         $filename = $lang["collectionidprefix"] . $collection . "-" . $size . "." . $collection_download_settings[$settings_id]["extension"];
     } else {
         $filename = $lang["collectionidprefix"] . $collection . "-" . $size . ".zip";
     }
 }
Beispiel #27
0
     $sql = "update resource_alt_files set file_name='{$filename}." . $lcext . "',file_extension='{$lcext}', file_size = '{$newfilesize}', description = concat(description,'" . $deschyphen . $newfilewidth . " x " . $newfileheight . " " . $lang['pixels'] . " {$mptext}') ";
     $sql .= ", transform_scale_w=" . ($new_width > 0 ? "'{$new_width}'" : "null") . ", transform_scale_h=" . ($new_height > 0 ? "'{$new_height}'" : "null") . "";
     $sql .= ", transform_crop_w=" . ($finalwidth > 0 ? "'{$finalwidth}'" : "null") . ", transform_crop_h=" . ($finalheight > 0 ? "'{$finalheight}'" : "null") . ", transform_crop_x=" . ($finalxcoord > 0 ? "'{$finalxcoord}'" : "null") . ", transform_crop_y=" . ($finalycoord > 0 ? "'{$finalycoord}'" : "null") . "";
     $sql .= ", transform_flop=" . ($flip ? "'1'" : "null") . ", transform_rotation=" . ($rotation > 0 ? "'{$rotation}'" : "null") . "";
     $sql .= " where ref='{$newfile}'";
     $result = sql_query($sql);
     resource_log($ref, 'b', '', "{$new_ext} " . strtolower($verb) . " to {$newfilewidth} x {$newfileheight}");
 } elseif ($original && getval("slideshow", "") == "" && !$cropperestricted) {
     // we are supposed to replace the original file
     $origalttitle = $lang['priorversion'];
     $origaltdesc = $lang['replaced'] . " " . strftime("%Y-%m-%d, %H:%M");
     $origfilename = sql_value("select value from resource_data left join resource_type_field on resource_data.resource_type_field = resource_type_field.ref where resource = '{$ref}' and name = 'original_filename'", $ref . "_original.{$orig_ext}");
     $origalt = add_alternative_file($ref, $origalttitle, $origaltdesc);
     $origaltpath = get_resource_path($ref, true, "", true, $orig_ext, -1, 1, false, "", $origalt);
     $mporig = round($origwidth * $origheight / 1000000, 2);
     $filesizeorig = filesize_unlimited($originalpath);
     rename($originalpath, $origaltpath);
     $result = sql_query("update resource_alt_files set file_name='{$origfilename}',file_extension='{$orig_ext}',file_size = '{$filesizeorig}' where ref='{$origalt}'");
     $neworigpath = get_resource_path($ref, true, '', false, $new_ext);
     rename($newpath, $neworigpath);
     $result = sql_query("update resource set file_extension = '{$new_ext}' where ref = '{$ref}' limit 1");
     // update extension
     resource_log($ref, 't', '', 'original transformed');
     create_previews($ref, false, $orig_ext, false, false, $origalt);
     create_previews($ref, false, $new_ext);
     # delete existing resource_dimensions
     sql_query("delete from resource_dimensions where resource='{$ref}'");
     sql_query("insert into resource_dimensions (resource, width, height, file_size) values ('{$ref}', '{$newfilewidth}', '{$newfileheight}', '{$newfilesize}')");
     # call remove annotations, since they will not apply to transformed
     hook("removeannotations");
     // remove the cached transform preview, since it will no longer be accurate
function ProcessFolder($folder)
    {
    global $lang, $syncdir, $nogo, $staticsync_max_files, $count, $done, $modtimes, $lastsync, $ffmpeg_preview_extension, 
           $staticsync_autotheme, $staticsync_folder_structure, $staticsync_extension_mapping_default, 
           $staticsync_extension_mapping, $staticsync_mapped_category_tree, $staticsync_title_includes_path, 
           $staticsync_ingest, $staticsync_mapfolders, $staticsync_alternatives_suffix, $theme_category_levels, $staticsync_defaultstate;
    
    $collection = 0;
    
    echo "Processing Folder: $folder" . PHP_EOL;
    
    # List all files in this folder.
    $dh = opendir($folder);
    while (($file = readdir($dh)) !== false)
        {
        if ( $file == '.' || $file == '..')
            {
            continue;
            }
        $filetype  = filetype($folder . "/" . $file);
        $fullpath  = $folder . "/" . $file;
        $shortpath = str_replace($syncdir . "/", '', $fullpath);
        # Work out extension
        $extension = explode(".", $file);
        if(count($extension)>1)
            {
            $extension = trim(strtolower($extension[count($extension)-1]));
            }
        else
            {
            //No extension
            $extension="";
            }
       
        
        if ($staticsync_mapped_category_tree)
            {
            $path_parts = explode("/", $shortpath);
            array_pop($path_parts);
            touch_category_tree_level($path_parts);
            }   

        # -----FOLDERS-------------
        if ((($filetype == "dir") || $filetype == "link") && 
            (strpos($nogo, "[$file]") === false) && 
            (strpos($file, $staticsync_alternatives_suffix) === false))
            {
            # Recurse
            ProcessFolder($folder . "/" . $file);
            }

        # -------FILES---------------
        if (($filetype == "file") && (substr($file,0,1) != ".") && (strtolower($file) != "thumbs.db"))
            {

            /* Below Code Adapted  from CMay's bug report */
            global $banned_extensions;
            # Check to see if extension is banned, do not add if it is banned
            if(array_search($extension, $banned_extensions)){continue;}
            /* Above Code Adapted from CMay's bug report */
            
            $count++;
            if ($count > $staticsync_max_files) { return(true); }

            # Already exists?
            if (!isset($done[$shortpath]))
                {
                echo "Processing file: $fullpath" . PHP_EOL;
                
                if ($collection == 0 && $staticsync_autotheme)
                    {
                    # Make a new collection for this folder.
                    $e = explode("/", $shortpath);
                    $theme        = ucwords($e[0]);
                    $themesql     = "theme='" . ucwords(escape_check($e[0])) . "'";
                    $themecolumns = "theme";
                    $themevalues  = "'" . ucwords(escape_check($e[0])) . "'";
                    
                    if ($staticsync_folder_structure)
                        {
                        for ($x=0;$x<count($e)-1;$x++)
                            {
                            if ($x != 0)
                                {
                                $themeindex = $x+1;
                                if ($themeindex >$theme_category_levels)
                                    {
                                    $theme_category_levels = $themeindex;
                                    if ($x == count($e)-2)
                                        {
                                        echo PHP_EOL . PHP_EOL . 
                                             "UPDATE THEME_CATEGORY_LEVELS TO $themeindex IN CONFIG!!!!" . 
                                             PHP_EOL . PHP_EOL;
                                        }
                                    }
                                $th_name       = ucwords(escape_check($e[$x]));
                                $themesql     .= " AND theme{$themeindex} = '$th_name'";
                                $themevalues  .= ",'$th_name'";
                                $themecolumns .= ",theme{$themeindex}";
                                }
                            }
                        }

                    $name = (count($e) == 1) ? '' : $e[count($e)-2];
                    echo "Collection $name, theme=$theme" . PHP_EOL;
                    $escaped_name = escape_check($name);
                    $collection = sql_value("SELECT ref value FROM collection WHERE name='$escaped_name' AND $themesql", 0);
                    if ($collection == 0)
                        {
                        sql_query("INSERT INTO collection (name,created,public,$themecolumns,allow_changes) 
                                                   VALUES ('$escaped_name', NOW(), 1, $themevalues, 0)");
                        $collection = sql_insert_id();
                        }
                    }

                # Work out a resource type based on the extension.
                $type = $staticsync_extension_mapping_default;
                reset($staticsync_extension_mapping);
                foreach ($staticsync_extension_mapping as $rt => $extensions)
                    {
                    if (in_array($extension,$extensions)) { $type = $rt; }
                    }
                $modified_type = hook('modify_type', 'staticsync', array( $type ));
                if (is_numeric($modified_type)) { $type = $modified_type; }

                # Formulate a title
                if ($staticsync_title_includes_path)
                    {
                    $title_find = array('/',   '_', ".$extension" );
                    $title_repl = array(' - ', ' ', '');
                    $title      = ucfirst(str_ireplace($title_find, $title_repl, $shortpath));
                    }
                else
                    {
                    $title = str_ireplace(".$extension", '', $file);
                    }
                $modified_title = hook('modify_title', 'staticsync', array( $title ));
                if ($modified_title !== false) { $title = $modified_title; }

                # Import this file
                $r = import_resource($shortpath, $type, $title, $staticsync_ingest);
                if ($r !== false)
                    {
                    # Add to mapped category tree (if configured)
                    if (isset($staticsync_mapped_category_tree))
                        {
                        $basepath = '';
                        # Save tree position to category tree field

                        # For each node level, expand it back to the root so the full path is stored.
                        for ($n=0;$n<count($path_parts);$n++)
                            {
                            if ($basepath != '') 
                                { 
                                $basepath .= "~";
                                }
                            $basepath .= $path_parts[$n];
                            $path_parts[$n] = $basepath;
                            }
                        
                        update_field($r, $staticsync_mapped_category_tree, "," . join(",", $path_parts));
                        }           

                    # default access level. This may be overridden by metadata mapping.
                    $accessval = 0;

                    # StaticSync path / metadata mapping
                    # Extract metadata from the file path as per $staticsync_mapfolders in config.php
                    if (isset($staticsync_mapfolders))
                        {
                        foreach ($staticsync_mapfolders as $mapfolder)
                            {
                            $match = $mapfolder["match"];
                            $field = $mapfolder["field"];
                            $level = $mapfolder["level"];

                            if (strpos("/" . $shortpath, $match) !== false)
                                {
                                # Match. Extract metadata.
                                $path_parts = explode("/", $shortpath);
                                if ($level < count($path_parts))
                                    {
                                    // special cases first.
                                    if ($field == 'access')
                                        {
                                        # access level is a special case
                                        # first determine if the value matches a defined access level

                                        $value = $path_parts[$level-1];

                                        for ($n=0; $n<3; $n++){
                                            # if we get an exact match or a match except for case
                                            if ($value == $lang["access" . $n] || strtoupper($value) == strtoupper($lang['access' . $n]))
                                                {
                                                $accessval = $n;
                                                echo "Will set access level to " . $lang['access' . $n] . " ($n)" . PHP_EOL;
                                                }
                                            }

                                        }
                                    else 
                                        {
                                        # Save the value
                                        print_r($path_parts);
                                        $value = $path_parts[$level-1];
                                        update_field ($r, $field, $value);
                                        echo " - Extracted metadata from path: $value" . PHP_EOL;
                                        }
                                    }
                                }
                            }
                        }

                    # update access level
                    sql_query("UPDATE resource SET access = '$accessval',archive='$staticsync_defaultstate' WHERE ref = '$r'");

                    # Add any alternative files
                    $altpath = $fullpath . $staticsync_alternatives_suffix;
                    if ($staticsync_ingest && file_exists($altpath))
                        {
                        $adh = opendir($altpath);
                        while (($altfile = readdir($adh)) !== false)
                            {
                            $filetype = filetype($altpath . "/" . $altfile);
                            if (($filetype == "file") && (substr($file,0,1) != ".") && (strtolower($file) != "thumbs.db"))
                                {
                                # Create alternative file                               
                                # Find extension
                                $ext = explode(".", $altfile);
                                $ext = $ext[count($ext)-1];
                                
                                $description = str_replace("?", strtoupper($ext), $lang["originalfileoftype"]);
                                $file_size   = filesize_unlimited($altpath . "/" . $altfile);
                                
                                $aref = add_alternative_file($r, $altfile, $description, $altfile, $ext, $file_size);
                                $path = get_resource_path($r, true, '', true, $ext, -1, 1, false, '', $aref);
                                rename($altpath . "/" . $altfile,$path); # Move alternative file
                                }
                            }   
                        }

                    # Add to collection
                    if ($staticsync_autotheme)
                        {
                        $test = ''; 
                        $test = sql_query("SELECT * FROM collection_resource WHERE collection='$collection' AND resource='$r'");
                        if (count($test) == 0)
                            {
                            sql_query("INSERT INTO collection_resource (collection, resource, date_added) 
                                            VALUES ('$collection', '$r', NOW())");
                            }
                        }
                    }
                else
                    {
                    # Import failed - file still being uploaded?
                    echo " *** Skipping file - it was not possible to move the file (still being imported/uploaded?)" . PHP_EOL;
                    }
                }
            else
                {
                # check modified date and update previews if necessary
                $filemod = filemtime($fullpath);
                if (array_key_exists($shortpath,$modtimes) && ($filemod > strtotime($modtimes[$shortpath])))
                    {
                    # File has been modified since we last created previews. Create again.
                    $rd = sql_query("SELECT ref, has_image, file_modified, file_extension FROM resource 
                                        WHERE file_path='" . escape_check($shortpath) . "'");
                    if (count($rd) > 0)
                        {
                        $rd   = $rd[0];
                        $rref = $rd["ref"];

                        echo "Resource $rref has changed, regenerating previews: $fullpath" . PHP_EOL;
                        extract_exif_comment($rref,$rd["file_extension"]);

                        # extract text from documents (e.g. PDF, DOC).
                        global $extracted_text_field;
                        if (isset($extracted_text_field)) {
                            if (isset($unoconv_path) && in_array($extension,$unoconv_extensions)){
                                // omit, since the unoconv process will do it during preview creation below
                                }
                            else {
                            extract_text($rref,$extension);
                            }
                        }

                        # Store original filename in field, if set
                        global $filename_field;
                        if (isset($filename_field))
                            {
                            update_field($rref,$filename_field,$file);  
                            }

                        create_previews($rref, false, $rd["file_extension"], false, false, -1, false, $staticsync_ingest);
                        sql_query("UPDATE resource SET file_modified=NOW() WHERE ref='$rref'");
                        }
                    }
                }
            }   
        }   
    }
Beispiel #29
0
    $path = get_resource_path($ref, true, "", false, $ext, -1, $page, false, "", $alternative);
}
if (!file_exists($path) && $noattach != "") {
    # Return icon for file (for previews)
    $info = get_resource_data($ref);
    $path = "../gfx/" . get_nopreview_icon($info["resource_type"], $ext, "thm");
}
# writing RS metadata to files: exiftool
if ($noattach == "" && $alternative == -1) {
    $tmpfile = write_metadata($path, $ref);
    if ($tmpfile !== false && file_exists($tmpfile)) {
        $path = $tmpfile;
    }
}
hook('modifydownloadfile');
$filesize = filesize_unlimited($path);
header("Content-Length: " . $filesize);
# Log this activity (download only, not preview)
if ($noattach == "") {
    daily_stat("Resource download", $ref);
    resource_log($ref, 'd', 0, $usagecomment, "", "", $usage, $size);
    hook('moredlactions');
    # update hit count if tracking downloads only
    if ($resource_hit_count_on_downloads) {
        # greatest() is used so the value is taken from the hit_count column in the event that new_hit_count is zero to support installations that did not previously have a new_hit_count column (i.e. upgrade compatability).
        sql_query("update resource set new_hit_count=greatest(hit_count,new_hit_count)+1 where ref='{$ref}'");
    }
    # We compute a file name for the download.
    $filename = $ref . $size . ($alternative > 0 ? "_" . $alternative : "") . "." . $ext;
    if ($original_filenames_when_downloading) {
        # Use the original filename.
function extract_icc_profile($ref, $extension)
{
    global $config_windows;
    # Locate imagemagick, or fail this if it isn't installed
    $convert_fullpath = get_utility_path("im-convert");
    if ($convert_fullpath == false) {
        return false;
    }
    if ($config_windows) {
        $stderrclause = '';
    } else {
        $stderrclause = '2>&1';
    }
    $infile = get_resource_path($ref, true, "", true, $extension);
    $outfile = get_resource_path($ref, true, "", false, $extension . ".icc");
    if (file_exists($outfile)) {
        // extracted profile already existed. We'll remove it and start over
        unlink($outfile);
    }
    $cmdout = run_command("{$convert_fullpath} {$infile} {$outfile} {$stderrclause}");
    if (preg_match("/no color profile is available/", $cmdout) || !file_exists($outfile) || filesize_unlimited($outfile) == 0) {
        // the icc profile extraction failed. So delete file.
        if (file_exists($outfile)) {
            unlink($outfile);
        }
        return false;
    }
    if (file_exists($outfile)) {
        return true;
    } else {
        return false;
    }
}