Esempio n. 1
0
 public function updateResource()
 {
     $rid = $this->resourceId();
     // resource does not exist - create it
     if ($rid == 0) {
         $rid = create_resource($this->type);
     } else {
         update_resource_type($rid, $this->type);
     }
     foreach ($this->fields as $k => $v) {
         update_field($rid, $k, $v);
     }
     if (file_exists($this->filename)) {
         $extension = explode(".", $this->filename);
         if (count($extension) > 1) {
             $extension = trim(strtolower($extension[count($extension) - 1]));
         } else {
             $extension = "";
         }
         $path = get_resource_path($rid, true, "", true, $extension);
         copy($this->filename, $path);
         create_previews($rid, false, $extension);
         # add file extension
         sql_query("update resource set file_extension='" . escapeString($extension) . "' where ref='" . escapeString($rid) . "'");
     }
     # add resource to collection (if the collection exists)
     if ($this->collection != null) {
         $col_ref = sql_value("select ref as value from collection where name='" . escapeString($this->collection) . "'", 0);
         if (isset($col_ref)) {
             add_resource_to_collection($rid, $col_ref);
         }
     }
     # set access rights
     if ($this->access != null) {
         sql_query("update resource set access='" . escapeString($this->access) . "' where ref='" . escapeString($rid) . "'");
     }
 }
    putenv("PATH=" . $ghostscript_path . ":" . $imagemagick_path);
    # Path
    $ghostscript_fullpath = get_utility_path("ghostscript");
    $command = $ghostscript_fullpath . " -sDEVICE=jpeg -dFirstPage={$previewpage} -o -r100 -dLastPage={$previewpage} -sOutputFile=" . escapeshellarg(get_temp_dir() . "/contactsheetrip.jpg") . " " . escapeshellarg(get_temp_dir() . "/contactsheet.pdf") . ($config_windows ? "" : " 2>&1");
    run_command($command);
    $convert_fullpath = get_utility_path("im-convert");
    if ($convert_fullpath == false) {
        exit("Could not find ImageMagick 'convert' utility at location '{$imagemagick_path}'");
    }
    $command = $convert_fullpath . " -resize " . $contact_sheet_preview_size . " -quality 90 -colorspace " . $imagemagick_colorspace . " \"" . get_temp_dir() . "/contactsheetrip.jpg\" \"" . get_temp_dir() . "/contactsheet.jpg\"" . ($config_windows ? "" : " 2>&1");
    run_command($command);
    exit;
}
#check configs, decide whether PDF outputs to browser or to a new resource.
if ($contact_sheet_resource == true) {
    $newresource = create_resource(1, 0);
    update_field($newresource, 8, i18n_get_collection_name($collectiondata) . " " . $date);
    update_field($newresource, $filename_field, $newresource . ".pdf");
    #Relate all resources in collection to the new contact sheet resource
    relate_to_collection($newresource, $collection);
    #update file extension
    sql_query("update resource set file_extension='pdf' where ref='{$newresource}'");
    # Create the file in the new resource folder:
    $path = get_resource_path($newresource, true, "", true, "pdf");
    $pdf->Output($path, 'F');
    #Create thumbnails and redirect browser to the new contact sheet resource
    create_previews($newresource, true, "pdf");
    redirect($baseurl_short . "pages/view.php?ref=" . $newresource);
} else {
    $out1 = ob_get_contents();
    if ($out1 != "") {
Esempio n. 3
0
function import_resource($path,$type,$title,$ingest=false)
	{
	# Import the resource at the given path
	# This is used by staticsync.php and Camillo's SOAP API
	# Note that the file will be used at it's present location and will not be copied.

	# Create resource
	$r=create_resource($type);
	return update_resource($r, $path, $type, $title, $ingest);
	}
Esempio n. 4
0
         } else {
             $optionstring = "";
         }
         $error_message .= "{$fieldname} is required. Use field{$required_field}=[string] as a parameter. {$optionstring}\n";
         $missing_fields = true;
     }
 }
 if ($missing_fields) {
     header("HTTP/1.0 403 Forbidden.");
     echo "HTTP/1.0 403 Forbidden. {$error_message}";
     exit;
 }
 // create resource
 $ref = hook('apiuploadreplaceref');
 if (!$ref) {
     $ref = create_resource(getval("resourcetype", 1), $status, $userref);
 }
 $path_parts = pathinfo($_FILES['userfile']['name']);
 $extension = strtolower($path_parts['extension']);
 $filepath = get_resource_path($ref, true, "", true, $extension);
 $collection = getvalescaped('collection', "", true);
 $result = move_uploaded_file($_FILES['userfile']['tmp_name'], $filepath);
 $wait = sql_query("update resource set file_extension='{$extension}',preview_extension='jpg',file_modified=now() ,has_image=0 where ref='{$ref}'");
 # Store original filename in field, if set
 global $filename_field;
 if (isset($filename_field)) {
     $wait = update_field($ref, $filename_field, $_FILES['userfile']['name']);
 }
 // extract metadata
 $wait = extract_exif_comment($ref, $extension);
 $resource = get_resource_data($ref);
Esempio n. 5
0
$resources = get_nodes_by_tag("RESOURCE");
foreach ($resources as $resource) {
    # For each resource
    # Find keyfield info
    $keyfields = get_nodes_by_tag("KEYFIELD", $resource["id"]);
    if (count($keyfields) !== 1) {
        exit("There must be exactly one 'keyfield' element for each resource.<br/>");
    }
    $keyfield = $keyfields[0];
    # Search for a matching resource
    $ref = sql_value("select resource value from resource_data where resource_type_field='" . escape_check($keyfield["attributes"]["REF"]) . "' and value='" . escape_check(trim($keyfield["value"])) . "'", 0);
    if ($ref == 0) {
        # No matching resource found. Insert a new resource.
        echo "<br><br>" . $keyfield["value"] . ": No resource found.";
        # Add a new resource and set the key field
        $ref = create_resource($resource["attributes"]["TYPE"]);
        update_field($ref, $keyfield["attributes"]["REF"], $keyfield["value"]);
    } else {
        # Existing resource found.
        echo "<br><br>" . $keyfield["value"] . ": Existing resource.";
    }
    # Update metadata fields
    $fields = get_nodes_by_tag("FIELD", $resource["id"]);
    foreach ($fields as $field) {
        echo "<br>" . $field["attributes"]["REF"] . "=" . $field["value"];
        update_field($ref, $field["attributes"]["REF"], $field["value"]);
    }
    # Update resource type
    update_resource_type($ref, $resource["attributes"]["TYPE"]);
    # Update file, if specified
    $filenames = get_nodes_by_tag("FILENAME", $resource["id"]);
Esempio n. 6
0
	
	$data=imap_fetchbody($imap,$current_message,$file['key']);
	$fp=fopen($temp_dir."/".$file['filename'],"w");
	$data=getdecodevalue($data,$file['encoding']);	
	fputs($fp,$data); echo "Downloading to filestore/tmp/checkmail_in \r\n";
	fclose($fp);

	// Get resource defaults for user's group
	$userresourcedefaults=sql_query("select resource_defaults from usergroup where ref='" . $fromuser['groupref'] . "'");
	if (isset($userresourcedefaults)){
		$userresourcedefaults=$userresourcedefaults[0];
		$userresourcedefaults=$userresourcedefaults["resource_defaults"];
		}

	// Create resource
	$r=create_resource($resource_type,$checkmail_archive_state,$fromuser_ref);  echo "Creating Resource $r \r\n";
	sql_query("update resource set access='".$access."',file_extension='".$file['extension']."',preview_extension='jpg',file_modified=now() where ref='$r'");
		
	// Update metadata fields  // HTML OPTIONS
	update_field($r,$filename_field,$file['filename']); 
	update_field($r,$checkmail_subject_field,$subject);
	if ($body_html!='' && $checkmail_html){
	update_field($r,$checkmail_body_field,$body_html);
	} else {
	update_field($r,$checkmail_body_field,$body);
	}
	echo "Updating Metadata \r\n";

	# Move the file
	$destination=get_resource_path($r,true,"",true,$file['extension']);	
	$result=rename($temp_dir."/".$file['filename'],$destination);  echo "Moving file to filestore \r\n";
Esempio n. 7
0
        };

        $_POST = array_merge($_POST, $metaids);
    }else{
        $data['error']=true;
        $data['success']=false;
        $data['textStatus']='Internal Error - Failed to extract metadata';
        echo(json_encode($data));
        exit();
    }

    //add the filename to the post variable
    $_POST['field_8']=$filename;

    //CREATE THE RESOURCE
    $ref = create_resource($resource_type,0,1);

    //if Object Id  (TMS Object ID) is detected in Metadata
    if(array_key_exists("objectid",$metadata)){
        $objid = $metadata['objectid'];
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, 'http://api.yoursite.org/objects/objectid');
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $request = curl_exec($curl);
        if($request == FALSE){
            $request = "failed to connect to TMS";
            //Create a tms cron job to resolve;
            createCronTms(1, $ref, $objid);
        }else{
            $request = json_decode($request);
function csv_upload_process($filename, &$meta, $resource_types, &$messages, $override = "", $max_error_count = 100, $processcsv = false)
{
    // echo "csv_upload_process(" . $filename . ", Resource types: ";
    // foreach($resource_types as $restype) {echo $restype. ", ";}
    // echo "Override:" . $override . "<br>";
    // if($processcsv){echo "Processing CSV file<br>";}
    $file = fopen($filename, 'r');
    $line_count = 0;
    if (($header = fgetcsv($file)) == false) {
        array_push($messages, "No header found");
        fclose($file);
        return false;
    }
    for ($i = 0; $i < count($header); $i++) {
        $header[$i] = strtoupper($header[$i]);
    }
    # ----- start of header row checks -----
    $resource_types_allowed = array();
    $resource_type_filter = getvalescaped("resource_type", "", true);
    if (getvalescaped("add_to_collection", "") != "") {
        include dirname(__FILE__) . "/../../../include/collections_functions.php";
        global $usercollection;
        $add_to_collection = true;
    } else {
        $add_to_collection = false;
    }
    foreach (array_keys($resource_types) as $resource_type) {
        if (!isset($meta[$resource_type])) {
            continue;
        }
        $missing_fields = array();
        foreach ($meta[$resource_type] as $field_name => $field_attributes) {
            if ($override != "" && $resource_type_filter != $resource_type && $resource_type != 0) {
                continue;
            }
            if ($field_attributes['required'] && array_search($field_name, $header) === false) {
                $meta[$resource_type][$field_name]['missing'] = true;
                array_push($missing_fields, $meta[$resource_type][$field_name]['nicename']);
            }
        }
        //if (count($missing_fields)==0 || $override==0 || ($override=="" || ($override==0 && $resource_type==$resource_type_filter)))
        if ($override == 0 || count($missing_fields) == 0 && ($override == "" || $resource_type == $resource_type_filter)) {
            array_push($messages, "Info: Found correct field headers for resource_type {$resource_type}({$resource_types[$resource_type]})");
            array_push($resource_types_allowed, $resource_type);
        } else {
            array_push($messages, "Warning: resource_type {$resource_type}({$resource_types[$resource_type]}) has missing field headers (" . implode(",", $missing_fields) . ") and will be ignored");
        }
    }
    if ($override != "" && array_search($resource_type_filter, $resource_types_allowed) === false) {
        array_push($messages, "Error: override resource_type {$resource_type_filter}({$resource_types[$resource_type_filter]}) not found or headers are incomplete");
        fclose($file);
        return false;
    } else {
        if ($override != "") {
            array_push($messages, "Info: Override resource_type {$resource_type_filter}({$resource_types[$resource_type_filter]}) is valid");
        }
    }
    if (count($header) == count(array_unique($header))) {
        array_push($messages, "Info: No duplicate header fields found");
    } else {
        array_push($messages, "Error: duplicate header fields found");
        fclose($file);
        return false;
    }
    # ----- end of header row checks, process each of the rows checking data -----
    $resource_type_index = array_search("RESOURCE_TYPE", $header);
    // index of column that contains the resource type
    $error_count = 0;
    echo "Processing " . count($header) . " columns<br>";
    while (($line = fgetcsv($file)) !== false && $error_count < $max_error_count) {
        $line_count++;
        if (!$processcsv && count($line) != count($header)) {
            array_push($messages, "Error: Incorrect number of columns(" . count($line) . ") found on line " . $line_count . " (should be " . count($header) . ")");
            $error_count++;
            continue;
        }
        // important! this is where the override happens
        if ($resource_type_index !== false && $override != 1) {
            $resource_type = $line[$resource_type_index];
            if ($override === 0 && $resource_type_filter != $resource_type) {
                continue;
            }
            // User has selected to only import a specific resource type
        } else {
            $resource_type = $resource_type_filter;
        }
        //echo "Resource type: " . $resource_type . "<br>";
        if (array_search($resource_type, $resource_types_allowed) === false) {
            if ($processcsv) {
                array_push($messages, "Skipping resource type " . $resource_type);
            }
            continue;
        }
        if ($processcsv) {
            // Create the new resource
            $newref = create_resource($resource_type);
            array_push($messages, "Created new resource: #" . $newref . " (" . $resource_types[$resource_type] . ")");
            if ($add_to_collection) {
                add_resource_to_collection($newref, $usercollection);
            }
        }
        $cell_count = -1;
        global $additional_archive_states;
        $valid_archive_states = array_merge(array(-2, -1, 0, 1, 2, 3), $additional_archive_states);
        // Now process the actual data
        foreach ($header as $field_name) {
            if ($field_name == "RESOURCE_TYPE") {
                $cell_count++;
                continue;
            }
            //echo "Getting data for " . $field_name . "<br>";
            $cell_count++;
            $cell_value = trim($line[$cell_count]);
            // important! we trim values, as options may contain a space after the comma
            //echo "Found value for " . $field_name . ": " . $cell_value . "<br>";
            if ($field_name == "ACCESS" && $processcsv) {
                //echo "Checking access<br>";
                $selectedaccess = in_array(getvalescaped("access", "", true), array(0, 1, 2)) ? getvalescaped("access", "", true) : "default";
                // Must be a valid access value
                if ($selectedaccess == "default") {
                    continue 2;
                }
                // Ignore this and the system will use default
                $cellaccess = in_array($cell_value, array(0, 1, 2)) ? $cell_value : "";
                // value from CSV
                $accessaction = getvalescaped("access_action", "", true);
                // Do we always override or only use the user selected value if missing or invalid CSV value
                if ($accessaction == 2 || $cellaccess == "") {
                    $access = $selectedaccess;
                } else {
                    $access = $cellaccess;
                }
                // use the cell value
                //echo "Updating the resource access: " . $access . "<br>";
                sql_query("update resource set access='{$access}' where ref='{$newref}'");
                continue;
            }
            if ($field_name == "STATUS" && $processcsv) {
                //echo "Checking status<br>";
                $selectedarchivestatus = in_array(getvalescaped("status", "", true), $valid_archive_states) ? getvalescaped("status", "", true) : "default";
                // Must be a valid status value
                if ($selectedarchivestatus == "default") {
                    continue 2;
                }
                // Ignore this and the system will use default
                $cellarchivestatus = in_array($cell_value, $valid_archive_states) ? $cell_value : "";
                // value from CSV
                $statusaction = getvalescaped("status_action", "", true);
                // Do we always override or only use the user selected value if missing or invalid CSV value
                if ($statusaction == 2 || $cellarchivestatus == "") {
                    $status = $selectedarchivestatus;
                } else {
                    $status = $cellarchivestatus;
                }
                // use the cell value
                //echo "Updating the resource archive status: " . $status . "<br>";
                update_archive_status($newref, $status);
                continue;
            }
            if (!isset($meta[$resource_type][$field_name])) {
                if (isset($meta[0][$field_name])) {
                    $field_resource_type = 0;
                } else {
                    //echo "Field not found : " . $field_name . "<br>";
                    continue;
                }
            } else {
                $field_resource_type = $resource_type;
            }
            if (!($field_name == "ACCESS" || $field_name == "RESOURCE_TYPE" || $field_name == "STATUS")) {
                // Check for multiple options
                if (strpos($cell_value, ",") > 0 && count($meta[$field_resource_type][$field_name]['options']) > 0 && !in_array($meta[$field_resource_type][$field_name]['type'], array(3, 12))) {
                    $cell_values = explode(",", $cell_value);
                } else {
                    // Make single value into a dummy array
                    $cell_values = array($cell_value);
                }
                $update_dynamic_field = false;
                if ($meta[$field_resource_type][$field_name]['required']) {
                    if ($cell_value == null or $cell_value == "") {
                        array_push($messages, "Error: Empty value for \"{$field_name}\" required field not allowed - found on line {$line_count}");
                        $error_count++;
                        continue;
                    }
                    foreach ($cell_values as $cell_actual_value) {
                        if (count($meta[$field_resource_type][$field_name]['options']) > 0 && array_search($cell_actual_value, $meta[$field_resource_type][$field_name]['options']) === false) {
                            if ($meta[$field_resource_type][$field_name]['type'] == 9) {
                                // Need to add to options table
                                $meta[$field_resource_type][$field_name]['options'][] = trim($cell_actual_value);
                                $update_dynamic_field = true;
                            } else {
                                array_push($messages, "Error: Value \"{$cell_actual_value}\" not found in lookup for \"{$field_name}\" required field - found on line {$line_count}");
                                $error_count++;
                                continue;
                            }
                        }
                    }
                } else {
                    if ($cell_value == null or $cell_value == "") {
                        continue;
                    }
                    foreach ($cell_values as $cell_actual_value) {
                        if (count($meta[$field_resource_type][$field_name]['options']) > 0 && array_search(trim($cell_actual_value), $meta[$field_resource_type][$field_name]['options']) === false) {
                            if ($meta[$field_resource_type][$field_name]['type'] == 9) {
                                // Need to add to options table
                                $meta[$field_resource_type][$field_name]['options'][] = trim($cell_actual_value);
                                $update_dynamic_field = true;
                                array_push($messages, "Adding option for field " . $meta[$field_resource_type][$field_name]['remote_ref'] . ": " . $cell_actual_value);
                            } else {
                                array_push($messages, "Error: Value \"{$cell_actual_value}\" not found in lookup for \"{$field_name}\" field - found on line {$line_count}");
                                $error_count++;
                                continue;
                            }
                        }
                    }
                }
                if ($processcsv) {
                    // Prefix value with comma as this is required for indexing and rendering selected options
                    if (in_array($meta[$field_resource_type][$field_name]['type'], array(2, 3, 7, 9, 12)) && substr($cell_value, 0, 1) != ',') {
                        $cell_value = ',' . $cell_value;
                    }
                    update_field($newref, $meta[$field_resource_type][$field_name]['remote_ref'], $cell_value);
                    if ($meta[$field_resource_type][$field_name]['type'] == 9 && $update_dynamic_field) {
                        debug("updating dynamic field options for field " . $field_name);
                        sql_query("update resource_type_field set options='," . escape_check(implode(",", $meta[$field_resource_type][$field_name]['options'])) . "' where ref='" . $meta[$field_resource_type][$field_name]['remote_ref'] . "'");
                    }
                }
            }
            ob_flush();
        }
        // end of cell loop
        // Set archive state if no header found in CSV
        if ($processcsv && !in_array("STATUS", $header)) {
            $selectedarchivestatus = in_array(getvalescaped("status", ""), $valid_archive_states) ? getvalescaped("status", "") : "default";
            // Must be a valid status value
            if ($selectedarchivestatus != "default") {
                update_archive_status($newref, $selectedarchivestatus);
            }
        }
        // Set access if no header found in CSV
        if ($processcsv && !in_array("ACCESS", $header)) {
            $selectedaccess = in_array(getvalescaped("access", "", true), array(0, 1, 2)) ? getvalescaped("access", "", true) : "default";
            // Must be a valid access value
            if ($selectedaccess != "default") {
                sql_query("update resource set access='{$selectedaccess}' where ref='{$newref}'");
            }
        }
    }
    // end of loop through lines
    fclose($file);
    if ($line_count == 1 && !$processcsv) {
        array_push($messages, "Error: No lines of data found in file");
    }
    if ($error_count > 0) {
        if ($error_count == $max_error_count) {
            array_push($messages, "Warning: Showing first {$max_error_count} data validation errors only - more may exist");
        }
        return false;
    }
    array_push($messages, "Info: data successfully validated");
    return true;
}
Esempio n. 9
0
<?php

include dirname(__FILE__) . "/../../include/db.php";
include dirname(__FILE__) . "/../../include/general.php";
include dirname(__FILE__) . "/../../include/image_processing.php";
include dirname(__FILE__) . "/../../include/resource_functions.php";
$api = true;
include dirname(__FILE__) . "/../../include/authenticate.php";
// required: check that this plugin is available to the user
if (!in_array("api_upload", $plugins)) {
    die("no access");
}
if (isset($_FILES['userfile'])) {
    $ref = create_resource(getval("resourcetype", 1), getval("archive", 0), $userref);
    $path_parts = pathinfo($_FILES['userfile']['name']);
    $extension = strtolower($path_parts['extension']);
    $filepath = get_resource_path($ref, true, "", true, $extension);
    print_r($_FILES);
    $result = move_uploaded_file($_FILES['userfile']['tmp_name'], $filepath);
    $wait = sql_query("update resource set file_extension='{$extension}',preview_extension='jpg',file_modified=now() ,has_image=0 where ref='{$ref}'");
    # Store original filename in field, if set
    global $filename_field;
    if (isset($filename_field)) {
        $wait = update_field($ref, $filename_field, $_FILES['userfile']['name']);
    }
    // extract metadata
    $wait = extract_exif_comment($ref, $extension);
    //create previews
    $wait = create_previews($ref, false, $extension);
    echo "resource created";
} else {
function import_resource($path, $type, $title, $ingest = false)
{
    # Import the resource at the given path
    # This is used by staticsync.php and Camillo's SOAP API
    # Note that the file will be used at it's present location and will not be copied.
    global $syncdir, $staticsync_prefer_embedded_title;
    # Create resource
    $r = create_resource($type);
    # Work out extension based on path
    $extension = explode(".", $path);
    $extension = trim(strtolower(end($extension)));
    # file_path should only really be set to indicate a staticsync location. Otherwise, it should just be left blank.
    if ($ingest) {
        $file_path = "";
    } else {
        $file_path = escape_check($path);
    }
    # Store extension/data in the database
    sql_query("update resource set archive=0,file_path='" . $file_path . "',file_extension='{$extension}',preview_extension='{$extension}',file_modified=now() where ref='{$r}'");
    # Store original filename in field, if set
    if (!$ingest) {
        # This file remains in situ; store the full path in file_path to indicate that the file is stored remotely.
        global $filename_field;
        if (isset($filename_field)) {
            $s = explode("/", $path);
            $filename = end($s);
            update_field($r, $filename_field, $filename);
        }
    } else {
        # This file is being ingested. Store only the filename.
        $s = explode("/", $path);
        $filename = end($s);
        global $filename_field;
        if (isset($filename_field)) {
            update_field($r, $filename_field, $filename);
        }
        # Move the file
        global $syncdir;
        $destination = get_resource_path($r, true, "", true, $extension);
        $result = rename($syncdir . "/" . $path, $destination);
        if ($result === false) {
            # The rename failed. The file is possibly still being copied or uploaded and must be ignored on this pass.
            # Delete the resouce just created and return false.
            delete_resource($r);
            return false;
        }
        chmod($destination, 0777);
    }
    # generate title and extract embedded metadata
    # order depends on which title should be the default (embedded or generated)
    if ($staticsync_prefer_embedded_title) {
        update_field($r, 8, $title);
        extract_exif_comment($r, $extension);
    } else {
        extract_exif_comment($r, $extension);
        update_field($r, 8, $title);
    }
    # Ensure folder is created, then create previews.
    get_resource_path($r, false, "pre", true, $extension);
    # Generate previews/thumbnails (if configured i.e if not completed by offline process 'create_previews.php')
    global $enable_thumbnail_creation_on_upload;
    if ($enable_thumbnail_creation_on_upload) {
        create_previews($r, false, $extension);
    }
    # Pass back the newly created resource ID.
    return $r;
}
     }
 }
 $data = imap_fetchbody($imap, $current_message, $file['key']);
 $fp = fopen($temp_dir . "/" . $file['filename'], "w");
 $data = getdecodevalue($data, $file['encoding']);
 fputs($fp, $data);
 echo "Downloading to filestore/tmp/checkmail_in \r\n";
 fclose($fp);
 // Get resource defaults for user's group
 $userresourcedefaults = sql_query("select resource_defaults from usergroup where ref='" . $fromuser['groupref'] . "'");
 if (isset($userresourcedefaults)) {
     $userresourcedefaults = $userresourcedefaults[0];
     $userresourcedefaults = $userresourcedefaults["resource_defaults"];
 }
 // Create resource
 $r = create_resource($resource_type, $checkmail_archive_state, $fromuser_ref);
 echo "Creating Resource {$r} \r\n";
 sql_query("update resource set access='" . $access . "',file_extension='" . $file['extension'] . "',preview_extension='jpg',file_modified=now() where ref='{$r}'");
 // Update metadata fields  // HTML OPTIONS
 update_field($r, $filename_field, $file['filename']);
 update_field($r, $checkmail_subject_field, $subject);
 if ($body_html != '' && $checkmail_html) {
     update_field($r, $checkmail_body_field, $body_html);
 } else {
     update_field($r, $checkmail_body_field, $body);
 }
 echo "Updating Metadata \r\n";
 # Move the file
 $destination = get_resource_path($r, true, "", true, $file['extension']);
 $result = rename($temp_dir . "/" . $file['filename'], $destination);
 echo "Moving file to filestore \r\n";