function HookAction_datesPagestoolscron_copy_hitcountAddplugincronjob()
{
    global $lang, $action_dates_restrictfield, $action_dates_deletefield, $resource_deletion_state, $action_dates_reallydelete, $action_dates_email_admin_days, $email_notify, $email_from, $applicationname;
    $allowable_fields = sql_array("select ref as value from resource_type_field where type in (4,6,10)");
    # Check that this is a valid date field to use
    if (in_array($action_dates_restrictfield, $allowable_fields)) {
        $restrict_resources = sql_query("select resource, value from resource_data where resource_type_field = '{$action_dates_restrictfield}'");
        $emailrefs = array();
        foreach ($restrict_resources as $resource) {
            $ref = $resource["resource"];
            if ($action_dates_email_admin_days != "") {
                $action_dates_email_admin_seconds = intval($action_dates_email_admin_days) * 60 * 60 * 24;
                if (time() >= strtotime($resource["value"]) - $action_dates_email_admin_seconds && time() <= strtotime($resource["value"]) - $action_dates_email_admin_seconds + 86400) {
                    $emailrefs[] = $ref;
                }
            }
            if (time() >= strtotime($resource["value"])) {
                # Restrict access to the resource as date has been reached
                $existing_access = sql_value("select access as value from resource where ref='{$ref}'", "");
                if ($existing_access == 0) {
                    echo "restricting resource " . $ref . "\r\n";
                    sql_query("update resource set access=1 where ref='{$ref}'");
                    resource_log($ref, 'a', '', $lang['action_dates_restrict_logtext'], $existing_access, 1);
                }
            }
        }
        if (count($emailrefs) > 0) {
            global $baseurl;
            # Send email as the date is within the specified number of days
            $subject = $lang['action_dates_email_subject'];
            $message = str_replace("%%DAYS", $action_dates_email_admin_days, $lang['action_dates_email_text']) . "\r\n";
            $message .= $baseurl . "?r=" . implode("\r\n" . $baseurl . "?r=", $emailrefs) . "\r\n";
            $templatevars['message'] = $message;
            echo "Sending email to " . $email_notify . "\r\n";
            send_mail($email_notify, $subject, $message, $applicationname, $email_from, "emailexpiredresources", $templatevars, $applicationname);
        }
    }
    if (in_array($action_dates_deletefield, $allowable_fields)) {
        $delete_resources = sql_query("select resource, value from resource_data where resource_type_field = '{$action_dates_deletefield}'");
        foreach ($delete_resources as $resource) {
            $ref = $resource["resource"];
            if (time() >= strtotime($resource["value"])) {
                # Delete the resource as date has been reached
                echo "deleting resource " . $ref . "\r\n";
                if ($action_dates_reallydelete) {
                    delete_resource($ref);
                } else {
                    if (!isset($resource_deletion_state)) {
                        $resource_deletion_state = 3;
                    }
                    sql_query("update resource set archive='" . $resource_deletion_state . "' where ref='" . $ref . "'");
                }
                # Remove the resource from any collections
                sql_query("delete from collection_resource where resource='{$ref}'");
                resource_log($ref, 'x', '', $lang['action_dates_delete_logtext']);
            }
        }
    }
}
Example #2
0
function HookGrant_editEditeditbeforeheader()
{
    global $ref, $baseurl, $usergroup, $grant_edit_groups, $collection;
    // Do we have access to do any of this, or is it a template
    if (!in_array($usergroup, $grant_edit_groups) || $ref < 0) {
        return;
    }
    // Check for Ajax POST to delete users
    $grant_edit_action = getvalescaped("grant_edit_action", "");
    if ($grant_edit_action != "") {
        if ($grant_edit_action == "delete") {
            $remove_user = escape_check(getvalescaped("remove_user", "", TRUE));
            if ($remove_user != "") {
                sql_query("delete from grant_edit where resource='{$ref}' and user={$remove_user}");
                exit("SUCCESS");
            }
        }
        exit("FAILED");
    }
    # If 'users' is specified (i.e. access is private) then rebuild users list
    $users = getvalescaped("users", false);
    if ($users != false) {
        # Build a new list and insert
        $users = resolve_userlist_groups($users);
        $ulist = array_unique(trim_array(explode(",", $users)));
        $urefs = sql_array("select ref value from user where username in ('" . join("','", $ulist) . "')");
        if (count($urefs) > 0) {
            $inserttext = array();
            $grant_edit_expiry = getvalescaped("grant_edit_expiry", "");
            foreach ($urefs as $uref) {
                if ($grant_edit_expiry != "") {
                    $inserttext[] = $uref . ",'" . $grant_edit_expiry . "'";
                } else {
                    $inserttext[] = $uref . ",NULL";
                }
            }
            if ($collection != "") {
                global $items;
                foreach ($items as $collection_resource) {
                    sql_query("delete from grant_edit where resource='{$collection_resource}' and user in (" . implode(",", $urefs) . ")");
                    sql_query("insert into grant_edit(resource,user,expiry) values ({$collection_resource}," . join("),(" . $collection_resource . ",", $inserttext) . ")");
                    #log this
                    global $lang;
                    resource_log($collection_resource, 's', "", "Grant Edit -  " . $users . " - " . $lang['expires'] . ": " . ($grant_edit_expiry != "" ? nicedate($grant_edit_expiry) : $lang['never']));
                }
            } else {
                sql_query("delete from grant_edit where resource='{$ref}' and user in (" . implode(",", $urefs) . ")");
                sql_query("insert into grant_edit(resource,user,expiry) values ({$ref}," . join("),(" . $ref . ",", $inserttext) . ")");
                #log this
                global $lang;
                resource_log($ref, 's', "", "Grant Edit -  " . $users . " - " . $lang['expires'] . ": " . ($grant_edit_expiry != "" ? nicedate($grant_edit_expiry) : $lang['never']));
            }
        }
    }
    return true;
}
function HookAction_datesPagestoolscron_copy_hitcountAddplugincronjob()
	{
	global $lang, $action_dates_restrictfield,$action_dates_deletefield, $resource_deletion_state, $action_dates_reallydelete;
	
	
	$allowable_fields=sql_array("select ref as value from resource_type_field where type in (4,6,10)");
	# Check that this is a valid date field to use
	if(in_array($action_dates_restrictfield, $allowable_fields))
		{
		$restrict_resources=sql_query("select resource, value from resource_data where resource_type_field = '$action_dates_restrictfield'");
		
		foreach ($restrict_resources as $resource)
			{
			$ref=$resource["resource"];
			if (time()>=strtotime($resource["value"]))		
				{
				# Restrict access to the resource as date has been reached
				$existing_access=sql_value("select access as value from resource where ref='$ref'","");
				if($existing_access==0) # Only apply to resources that are currently open
					{
					echo "restricting resource " . $ref ."\r\n";
					sql_query("update resource set access=1 where ref='$ref'");
					resource_log($ref,'a','',$lang['action_dates_restrict_logtext'],$existing_access,1);		
					}
				}
			}
		}
	if(in_array($action_dates_deletefield, $allowable_fields))
		{
		$delete_resources=sql_query("select resource, value from resource_data where resource_type_field = '$action_dates_deletefield'");
		foreach ($delete_resources as $resource)
			{
			$ref=$resource["resource"];
			if (time()>=strtotime($resource["value"]))		
				{
				# Delete the resource as date has been reached
				echo "deleting resource " . $ref ."\r\n";
				if ($action_dates_reallydelete)
					{
					delete_resource($ref);
					}
				else
					{
					if (!isset($resource_deletion_state)){$resource_deletion_state=3;}
					sql_query("update resource set archive='" . $resource_deletion_state . "' where ref='" . $ref . "'");
					}
				# Remove the resource from any collections
				sql_query("delete from collection_resource where resource='$ref'");
				resource_log($ref,'x','',$lang['action_dates_delete_logtext']);			
				}	
			}
		}
	}
Example #4
0
if (!$speedtagging) {
    exit("This function is not enabled.");
}
if (getval("save", "") != "") {
    $ref = getvalescaped("ref", "", true);
    $keywords = getvalescaped("keywords", "");
    # support resource_type based tag fields
    $resource_type = get_resource_data($ref);
    $resource_type = $resource_type['resource_type'];
    if (isset($speedtagging_by_type[$resource_type])) {
        $speedtaggingfield = $speedtagging_by_type[$resource_type];
    }
    $oldval = get_data_by_field($ref, $speedtaggingfield);
    update_field($ref, $speedtaggingfield, $keywords);
    # Write this edit to the log.
    resource_log($ref, 'e', $speedtaggingfield, "", $oldval, $keywords);
}
# append resource type restrictions based on 'T' permission
# look for all 'T' permissions and append to the SQL filter.
global $userpermissions;
$rtfilter = array();
$sql_join = "";
$sql_filter = "";
for ($n = 0; $n < count($userpermissions); $n++) {
    if (substr($userpermissions[$n], 0, 1) == "T") {
        $rt = substr($userpermissions[$n], 1);
        if (is_numeric($rt)) {
            $rtfilter[] = $rt;
        }
    }
}
         if (getval("no_exif", "") == "") {
             extract_exif_comment($ref, $extension);
         }
         # extract text from documents (e.g. PDF, DOC).
         global $extracted_text_field;
         if (isset($extracted_text_field) && !$no_exif) {
             extract_text($ref, $extension);
         }
         $done++;
         # Add to collection?
         if ($collection != "") {
             $refs[] = $ref;
         }
         # Log this
         daily_stat("Resource upload", $ref);
         resource_log($ref, 'u', 0);
     }
 }
 if (!$use_local) {
     ftp_close($ftp);
 }
 switch ($done) {
     case 0:
         $summary_ok = $lang["resources_uploaded-0"];
         break;
     case 1:
         $summary_ok = $lang["resources_uploaded-1"];
         break;
     default:
         $summary_ok = str_replace("%done%", $done, $lang["resources_uploaded-n"]);
         break;
                     if (trim($commentdata['comment']) != "") {
                         $text .= wordwrap($lang["comment"] . ": " . $commentdata['comment'] . "\r\n", 65);
                     }
                     if (trim($commentdata['rating']) != "") {
                         $text .= wordwrap($lang["rating"] . ": " . $commentdata['rating'] . "\r\n", 65);
                     }
                     $text .= "-----------------------------------------------------------------\r\n\r\n";
                 }
             }
             $path .= $p . "\r\n";
             # build an array of paths so we can clean up any exiftool-modified files.
             if ($tmpfile !== false && file_exists($tmpfile)) {
                 $deletion_array[] = $tmpfile;
             }
             daily_stat("Resource download", $ref);
             resource_log($ref, 'd', 0);
             # 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}'");
             }
         }
     }
 }
 # Download and add external resources
 $xt_resources = sql_query("select * from resourceconnect_collection_resources where collection='" . $collection . "'");
 foreach ($xt_resources as $xt_resource) {
     # Work out download URL
     $url = $xt_resource["url"];
     $url = str_replace("view.php", "download.php", $url);
     $url .= "&size=" . $size;
Example #7
0
    $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.
        if ($alternative > 0) {
            # Fetch from the resource_alt_files alternatives table (this is an alternative file)
            $origfile = get_alternative_file($ref, $alternative);
            $origfile = get_data_by_field($ref, $filename_field) . "-" . $origfile["file_name"];
        } else {
Example #8
0
 } 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
     if (file_exists(get_temp_dir() . "/transform_plugin/pre_{$ref}.jpg")) {
         unlink(get_temp_dir() . "/transform_plugin/pre_{$ref}.jpg");
     }
     redirect("pages/view.php?ref={$ref}");
     exit;
 } elseif (getval("slideshow", "") != "" && !$cropperestricted) {
     # Produce slideshow.
         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);
     }
     # Log this
     daily_stat("Resource upload", $ref);
     resource_log($ref, "u", 0);
     $status = upload_file($ref, getval("no_exif", "") != "", false, getval('autorotate', '') != '');
     echo "SUCCESS: " . $ref;
     exit;
 } elseif ($replace == "" && $replace_resource != "") {
     # Replacing an existing resource file
     $status = upload_file($replace_resource, getval("no_exif", "") != "", false, getval('autorotate', '') != '');
     echo "SUCCESS: {$replace_resource}";
     exit;
 } else {
     # Overwrite an existing resource using the number from the filename.
     # Extract the number from the filename
     $plfilename = strtolower(str_replace(" ", "_", $plfilename));
     $s = explode(".", $plfilename);
     if (count($s) == 2) {
         $ref = trim($s[0]);
Example #10
0
function copy_resource($from,$resource_type=-1)
	{
	# Create a new resource, copying all data from the resource with reference $from.
	# Note this copies only the data and not any attached file. It's very unlikely the
	# same file would be in the system twice, however users may want to clone an existing resource
	# to avoid reentering data if the resource is very similar.
	# If $resource_type if specified then the resource type for the new resource will be set to $resource_type
	# rather than simply copied from the $from resource.
	
	# Check that the resource exists
	if (sql_value("select count(*) value from resource where ref='$from'",0)==0) {return false;}
	
	# copy joined fields to the resource column
	$joins=get_resource_table_joins();
	$joins_sql="";
	foreach ($joins as $join){
		$joins_sql.=",field$join ";
	}
	
	$add="";

	# Work out the archive status
	$archive=sql_value("select archive value from resource where ref='$from'",0);
	if (!checkperm("e" . $archive))
		{
		# Find the right permission mode to use
		for ($n=-2;$n<3;$n++)
			{
			if (checkperm("e" . $n)) {$archive=$n;break;}
			}
		}

	# First copy the resources row
	sql_query("insert into resource($add resource_type,creation_date,rating,archive,access,created_by $joins_sql) select $add" . (($resource_type==-1)?"resource_type":("'" . $resource_type . "'")) . ",now(),rating,'" . $archive . "',access,created_by $joins_sql from resource where ref='$from';");
	$to=sql_insert_id();
	
	# Copying a resource of the 'pending review' state? Notify, if configured.
	$archive=sql_value("select archive value from resource where ref='$from'",0);
	if ($archive==-1)
		{
		notify_user_contributed_submitted(array($to));
		}
	
	# Set that this resource was created by this user. 
	# This needs to be done if either:
	# 1) The user does not have direct 'resource create' permissions and is therefore contributing using My Contributions directly into the active state
	# 2) The user is contributiting via My Contributions to the standard User Contributed pre-active states.
	global $userref;
	global $always_record_resource_creator;
	if ((!checkperm("c")) || $archive<0 || (isset($always_record_resource_creator) && $always_record_resource_creator))
		{
		# Update the user record
		sql_query("update resource set created_by='$userref' where ref='$to'");

		# Also add the user's username and full name to the keywords index so the resource is searchable using this name.
		global $username,$userfullname;
		add_keyword_mappings($to,$username . " " . $userfullname,-1);
		}
	
	# Now copy all data
	sql_query("insert into resource_data(resource,resource_type_field,value) select '$to',rd.resource_type_field,rd.value from resource_data rd join resource r on rd.resource=r.ref join resource_type_field rtf on rd.resource_type_field=rtf.ref and (rtf.resource_type=r.resource_type or rtf.resource_type=999 or rtf.resource_type=0) where rd.resource='$from'");
	
	# Copy relationships
	sql_query("insert into resource_related(resource,related) select '$to',related from resource_related where resource='$from'");

	# Copy access
	sql_query("insert into resource_custom_access(resource,usergroup,access) select '$to',usergroup,access from resource_custom_access where resource='$from'");

	# Set any resource defaults
	set_resource_defaults($to);

	# Reindex the resource so the resource_keyword entries are created
	reindex_resource($to);
	
	# Log this			
	daily_stat("Create resource",$to);
	resource_log($to,'c',0);

	hook("afternewresource", "", array($to));
	
	return $to;
	}
Example #11
0
	}

# If requested, refresh the collection frame (for redirects from saves)
if (getval("refreshcollectionframe","")!="")
	{
	refresh_collection_frame();
	}

# Update the hitcounts for the search keywords (if search specified)
# (important we fetch directly from $_GET and not from a cookie
$usearch=@$_GET["search"];
if ((strpos($usearch,"!")===false) && ($usearch!="")) {update_resource_keyword_hitcount($ref,$usearch);}

# Log this activity
daily_stat("Resource view",$ref);
if ($log_resource_views) {resource_log($ref,'v',0);}

if ($direct_download && !$save_as){	
// check browser to see if forcing save_as 
if (!$direct_download_allow_opera  && strpos(strtolower($_SERVER["HTTP_USER_AGENT"]),"opera")!==false) {$save_as=true;}
if (!$direct_download_allow_ie7 && strpos(strtolower($_SERVER["HTTP_USER_AGENT"]),"msie 7.")!==false) {$save_as=true;}	
if (!$direct_download_allow_ie8 && strpos(strtolower($_SERVER["HTTP_USER_AGENT"]),"msie 8.")!==false) {$save_as=true;}	
}

# Show the header/sidebar
include "../include/header.php";

if ($metadata_report && isset($exiftool_path))
	{
	?>
	<script src="<?php echo $baseurl_short?>lib/js/metadata_report.js" type="text/javascript"></script>
            if (file_exists($newpath) && filesize_unlimited($newpath) > 0) {
                // success!
                if (!rename($newpath, $path)) {
                    echo " " . str_replace("%res", $resource, $lang['error-unable-to-rename']) . "<br />\n";
                    $failcount++;
                } else {
                    create_previews($resource, false, $new_ext);
                    // get final pixel dimensions of resulting file
                    $newfilesize = filesize_unlimited($path);
                    $newfiledimensions = getimagesize($path);
                    $newfilewidth = $newfiledimensions[0];
                    $newfileheight = $newfiledimensions[1];
                    # delete existing resource_dimensions
                    sql_query("delete from resource_dimensions where resource='{$resource}'");
                    sql_query("insert into resource_dimensions (resource, width, height, file_size) values ('{$resource}', '{$newfilewidth}', '{$newfileheight}', '{$newfilesize}')");
                    resource_log($resource, 't', '', 'batch transform');
                    echo "<img src='" . get_resource_path($resource, false, "thm", false, 'jpg', -1, 1) . "' /><br />\n";
                    echo " " . $lang['success'] . "<br />\n";
                    $successcount++;
                }
            } else {
                echo " " . str_replace("%res", $resource, $lang['error-transform-failed']) . "<br />\n";
                $failcount++;
            }
        }
        ?>
</div><?php 
        flush();
    }
    ?>
<script>CollectionDivLoad("<?php 
Example #13
0
function payment_set_complete($collection)
{
    # Mark items in the collection as paid so they can be downloaded.
    sql_query("update collection_resource set purchase_complete=1 where collection='{$collection}'");
    # For each resource, add an entry to the log to show it has been purchased.
    $resources = sql_query("select * from collection_resource where collection='{$collection}'");
    foreach ($resources as $resource) {
        resource_log($resource["resource"], "p", 0, "", "", "", 0, $resource["purchase_size"], $resource["purchase_price"]);
    }
    return true;
}
function copy_resource($from, $resource_type = -1)
{
    # Create a new resource, copying all data from the resource with reference $from.
    # Note this copies only the data and not any attached file. It's very unlikely the
    # same file would be in the system twice, however users may want to clone an existing resource
    # to avoid reentering data if the resource is very similar.
    # If $resource_type if specified then the resource type for the new resource will be set to $resource_type
    # rather than simply copied from the $from resource.
    # Check that the resource exists
    if (sql_value("select count(*) value from resource where ref='{$from}'", 0) == 0) {
        return false;
    }
    # copy joined fields to the resource column
    $joins = get_resource_table_joins();
    // Filter the joined columns so we only have the ones relevant to this resource type
    $query = sprintf('
			    SELECT rtf.ref AS value
			      FROM resource_type_field AS rtf
			INNER JOIN resource AS r ON (rtf.resource_type != r.resource_type AND rtf.resource_type != 0)
			     WHERE r.ref = "%s";
		', $from);
    $irrelevant_rtype_fields = sql_array($query);
    $irrelevant_rtype_fields = array_values(array_intersect($joins, $irrelevant_rtype_fields));
    $filtered_joins = array_values(array_diff($joins, $irrelevant_rtype_fields));
    $joins_sql = "";
    foreach ($filtered_joins as $join) {
        $joins_sql .= ",field{$join} ";
    }
    $add = "";
    # Determine if the user has access to the template archive status
    $archive = sql_value("select archive value from resource where ref='{$from}'", 0);
    if (!checkperm("e" . $archive)) {
        # Find the right permission mode to use
        for ($n = -2; $n < 3; $n++) {
            if (checkperm("e" . $n)) {
                $archive = $n;
                break;
            }
        }
    }
    # First copy the resources row
    sql_query("insert into resource({$add} resource_type,creation_date,rating,archive,access,created_by {$joins_sql}) select {$add}" . ($resource_type == -1 ? "resource_type" : "'" . $resource_type . "'") . ",now(),rating,'" . $archive . "',access,created_by {$joins_sql} from resource where ref='{$from}';");
    $to = sql_insert_id();
    # Set that this resource was created by this user.
    # This needs to be done if either:
    # 1) The user does not have direct 'resource create' permissions and is therefore contributing using My Contributions directly into the active state
    # 2) The user is contributiting via My Contributions to the standard User Contributed pre-active states.
    global $userref;
    global $always_record_resource_creator;
    if (!checkperm("c") || $archive < 0 || isset($always_record_resource_creator) && $always_record_resource_creator) {
        # Update the user record
        sql_query("update resource set created_by='{$userref}' where ref='{$to}'");
        # Also add the user's username and full name to the keywords index so the resource is searchable using this name.
        global $username, $userfullname;
        add_keyword_mappings($to, $username . " " . $userfullname, -1);
    }
    # Now copy all data
    sql_query("insert into resource_data(resource,resource_type_field,value) select '{$to}',rd.resource_type_field,rd.value from resource_data rd join resource r on rd.resource=r.ref join resource_type_field rtf on rd.resource_type_field=rtf.ref and (rtf.resource_type=r.resource_type or rtf.resource_type=999 or rtf.resource_type=0) where rd.resource='{$from}'");
    # Copy relationships
    sql_query("insert into resource_related(resource,related) select '{$to}',related from resource_related where resource='{$from}'");
    # Copy access
    sql_query("insert into resource_custom_access(resource,usergroup,access) select '{$to}',usergroup,access from resource_custom_access where resource='{$from}'");
    # Set any resource defaults
    set_resource_defaults($to);
    # Autocomplete any blank fields.
    autocomplete_blank_fields($to);
    # Reindex the resource so the resource_keyword entries are created
    reindex_resource($to);
    # Copying a resource of the 'pending review' state? Notify, if configured.
    global $send_collection_to_admin;
    if ($archive == -1 && !$send_collection_to_admin) {
        notify_user_contributed_submitted(array($to));
    }
    # Log this
    daily_stat("Create resource", $to);
    resource_log($to, 'c', 0);
    hook("afternewresource", "", array($to));
    return $to;
}
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;
    }
}
Example #16
0
            if ($enable_thumbnail_creation_on_upload) {
                create_previews($ref, false, $resource["file_extension"], false, false, -1, true);
                refresh_collection_frame();
            } else {
                sql_query("update resource set preview_attempts=0, has_image=0 where ref='{$ref}'");
            }
            break;
    }
    hook("moretweakingaction", "", array($tweak, $ref, $resource));
    # Reload resource data.
    $resource = get_resource_data($ref, false);
}
# Simulate reupload (preserving filename and thumbs, but otherwise resetting metadata).
if (getval("exif", "") != "") {
    upload_file($ref, $no_exif = false, true);
    resource_log($ref, "r", "");
}
# If requested, refresh the collection frame (for redirects from saves)
if (getval("refreshcollectionframe", "") != "") {
    refresh_collection_frame();
}
include "../include/header.php";
?>
<script type="text/javascript">


jQuery(document).ready(function()
    {

    jQuery('.CollapsibleSectionHead').click(function() 
        {
                }
                update_field($ref, $youtube_publish_url_field, $save_url);
                $youtube_old_url = $youtube_url;
                $youtube_url = $youtube_url . "<br><a href=\"" . $youtube_new_url . "\" target=\"_blank\">" . $youtube_new_url . "</a>";
            } else {
                if ($youtube_publish_add_anchor) {
                    $save_url = "<a href=\"" . $youtube_new_url . "\" target=\"_blank\">" . $youtube_new_url . "</a>";
                } else {
                    $save_url = $youtube_new_url;
                }
                update_field($ref, $youtube_publish_url_field, $save_url);
                $youtube_old_url = $youtube_url;
                $youtube_url = $youtube_new_url;
            }
        }
        resource_log($ref, 'e', $youtube_publish_url_field ? $youtube_publish_url_field : 0, $lang["youtube_publish_log_share"], $fromvalue = $youtube_old_url, $tovalue = $save_url);
    }
}
$title = get_data_by_field($ref, $youtube_publish_title_field);
#$description=get_data_by_field($ref,$youtube_publish_descriptionfield);
$description = "";
foreach ($youtube_publish_descriptionfields as $youtube_publish_descriptionfield) {
    $resource_description = get_data_by_field($ref, $youtube_publish_descriptionfield);
    if ($description != '') {
        $description .= "\r\n";
    }
    $description .= $resource_description;
}
$video_keywords = "";
foreach ($youtube_publish_keywords_fields as $youtube_publish_keywords_field) {
    $resource_keywords = get_data_by_field($ref, $youtube_publish_keywords_field);
Example #18
0
    $access = 1;
}
# If requested, refresh the collection frame (for redirects from saves)
if (getval("refreshcollectionframe", "") != "") {
    refresh_collection_frame();
}
# Update the hitcounts for the search keywords (if search specified)
# (important we fetch directly from $_GET and not from a cookie
$usearch = @$_GET["search"];
if (strpos($usearch, "!") === false && $usearch != "") {
    update_resource_keyword_hitcount($ref, $usearch);
}
# Log this activity
daily_stat("Resource view", $ref);
if ($log_resource_views) {
    resource_log($ref, 'v', 0);
}
if ($direct_download && !$save_as) {
    // check browser to see if forcing save_as
    if (!$direct_download_allow_opera && strpos(strtolower($_SERVER["HTTP_USER_AGENT"]), "opera") !== false) {
        $save_as = true;
    }
    if (!$direct_download_allow_ie7 && strpos(strtolower($_SERVER["HTTP_USER_AGENT"]), "msie 7.") !== false) {
        $save_as = true;
    }
    if (!$direct_download_allow_ie8 && strpos(strtolower($_SERVER["HTTP_USER_AGENT"]), "msie 8.") !== false) {
        $save_as = true;
    }
}
# Show the header/sidebar
include "../include/header.php";
Example #19
0
<?php

include '../../../../include/config.php';
include '../../../../include/db.php';
include '../../../../include/general.php';
include '../../../../include/resource_functions.php';
$value = getvalescaped("value", "");
$oldvalue = getvalescaped("oldvalue", "");
$ref = getvalescaped("ref", "");
$userref = getvalescaped("userref", "");
$field = getvalescaped("field", "");
debug("save:" . $field . "," . $ref . "," . $value);
update_field($ref, $field, $value);
resource_log($ref, 'e', $field, "", unescape($oldvalue), unescape($value));
echo "saved";
                     }
                     $text .= "-----------------------------------------------------------------\r\n\r\n";
                 }
             }
             hook('modifydownloadfile');
             $path .= $p . "\r\n";
             if ($use_zip_extension) {
                 $zip->addFile($p, $filename);
                 update_zip_progress_file("file " . $zip->numFiles);
             }
             # build an array of paths so we can clean up any exiftool-modified files.
             if ($tmpfile !== false && file_exists($tmpfile)) {
                 $deletion_array[] = $tmpfile;
             }
             daily_stat("Resource download", $ref);
             resource_log($ref, 'd', 0, "", "", "", -1, $size);
             # 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}'");
             }
         }
     }
 }
 if ($path == "") {
     exit($lang["nothing_to_download"]);
 }
 # Append summary notes about the completeness of the package, write the text file, add to archive, and schedule for deletion
 if ($zipped_collection_textfile == true && $includetext == "true") {
     $qty_sizes = count($available_sizes[$size]);
     $qty_total = count($result);
 function upload_file($ref, $no_exif = false, $revert = false, $autorotate = false)
 {
     hook("beforeuploadfile", "", array($ref));
     hook("clearaltfiles", "", array($ref));
     // optional: clear alternative files before uploading new resource
     # revert is mainly for metadata reversion, removing all metadata and simulating a reupload of the file from scratch.
     hook("removeannotations", "", array($ref));
     $exiftool_fullpath = get_utility_path("exiftool");
     # Process file upload for resource $ref
     if ($revert == true) {
         global $filename_field;
         $original_filename = get_data_by_field($ref, $filename_field);
         # Field 8 is used in a special way for staticsync, don't overwrite.
         $test_for_staticsync = get_resource_data($ref);
         if ($test_for_staticsync['file_path'] != "") {
             $staticsync_mod = " and resource_type_field != 8";
         } else {
             $staticsync_mod = "";
         }
         sql_query("delete from resource_data where resource={$ref} {$staticsync_mod}");
         sql_query("delete from resource_keyword where resource={$ref} {$staticsync_mod}");
         #clear 'joined' display fields which are based on metadata that is being deleted in a revert (original filename is reinserted later)
         $display_fields = get_resource_table_joins();
         if ($staticsync_mod != "") {
             $display_fields_new = array();
             for ($n = 0; $n < count($display_fields); $n++) {
                 if ($display_fields[$n] != 8) {
                     $display_fields_new[] = $display_fields[$n];
                 }
             }
             $display_fields = $display_fields_new;
         }
         $clear_fields = "";
         for ($x = 0; $x < count($display_fields); $x++) {
             $clear_fields .= "field" . $display_fields[$x] . "=''";
             if ($x < count($display_fields) - 1) {
                 $clear_fields .= ",";
             }
         }
         sql_query("update resource set " . $clear_fields . " where ref={$ref}");
         #also add the ref back into keywords:
         add_keyword_mappings($ref, $ref, -1);
         $extension = sql_value("select file_extension value from resource where ref={$ref}", "");
         $filename = get_resource_path($ref, true, "", false, $extension);
         $processfile['tmp_name'] = $filename;
     } else {
         # Work out which file has been posted
         if (isset($_FILES['userfile'])) {
             $processfile = $_FILES['userfile'];
         } elseif (isset($_FILES['Filedata'])) {
             $processfile = $_FILES['Filedata'];
         }
         # Java upload (at least) needs this
         # Plupload needs this
         if (isset($_REQUEST['name'])) {
             $filename = $_REQUEST['name'];
         } else {
             $filename = $processfile['name'];
         }
         global $filename_field;
         if ($no_exif && isset($filename_field)) {
             $user_set_filename = get_data_by_field($ref, $filename_field);
             if (trim($user_set_filename) != '') {
                 // Get extension of file just in case the user didn't provide one
                 $path_parts = pathinfo($filename);
                 $original_extension = $path_parts['extension'];
                 $filename = $user_set_filename;
                 // If the user filename doesn't have an extension add the original one
                 $path_parts = pathinfo($filename);
                 if (!isset($path_parts['extension'])) {
                     $filename .= '.' . $original_extension;
                 }
             }
         }
     }
     # Work out extension
     if (!isset($extension)) {
         # first try to get it from the filename
         $extension = explode(".", $filename);
         if (count($extension) > 1) {
             $extension = escape_check(trim(strtolower($extension[count($extension) - 1])));
         } else {
             if ($exiftool_fullpath != false) {
                 $file_type_by_exiftool = run_command($exiftool_fullpath . " -filetype -s -s -s " . escapeshellarg($processfile['tmp_name']));
                 if (strlen($file_type_by_exiftool) > 0) {
                     $extension = str_replace(" ", "_", trim(strtolower($file_type_by_exiftool)));
                     $filename = $filename;
                 } else {
                     return false;
                 }
             } else {
                 return false;
             }
         }
     }
     # Banned extension?
     global $banned_extensions;
     if (in_array($extension, $banned_extensions)) {
         return false;
     }
     $status = "Please provide a file name.";
     $filepath = get_resource_path($ref, true, "", true, $extension);
     if (!$revert) {
         # Remove existing file, if present
         hook("beforeremoveexistingfile", "", array("resourceId" => $ref));
         $old_extension = sql_value("select file_extension value from resource where ref='{$ref}'", "");
         if ($old_extension != "") {
             $old_path = get_resource_path($ref, true, "", true, $old_extension);
             if (file_exists($old_path)) {
                 unlink($old_path);
             }
         }
         // also remove any existing extracted icc profiles
         $icc_path = get_resource_path($ref, true, "", true, $extension . '.icc');
         if (file_exists($icc_path)) {
             unlink($icc_path);
         }
         global $pdf_pages;
         $iccx = 0;
         // if there is a -0.icc page, run through and delete as many as necessary.
         $finished = false;
         $badicc_path = str_replace(".icc", "-{$iccx}.icc", $icc_path);
         while (!$finished) {
             if (file_exists($badicc_path)) {
                 unlink($badicc_path);
                 $iccx++;
                 $badicc_path = str_replace(".icc", "-{$iccx}.icc", $icc_path);
             } else {
                 $finished = true;
             }
         }
         $iccx = 0;
     }
     if (!$revert) {
         if ($filename != "") {
             global $jupload_alternative_upload_location, $plupload_upload_location;
             if (isset($plupload_upload_location)) {
                 # PLUpload - file was sent chunked and reassembled - use the reassembled file location
                 $result = rename($plupload_upload_location, $filepath);
             } elseif (isset($jupload_alternative_upload_location)) {
                 # JUpload - file was sent chunked and reassembled - use the reassembled file location
                 $result = rename($jupload_alternative_upload_location, $filepath);
             } else {
                 # Standard upload.
                 if (!$revert) {
                     $result = move_uploaded_file($processfile['tmp_name'], $filepath);
                 } else {
                     $result = true;
                 }
             }
             if ($result == false) {
                 $status = "File upload error. Please check the size of the file you are trying to upload.";
                 return false;
             } else {
                 global $camera_autorotation;
                 global $ffmpeg_audio_extensions;
                 if ($camera_autorotation) {
                     if ($autorotate && !in_array($extension, $ffmpeg_audio_extensions)) {
                         AutoRotateImage($filepath);
                     }
                 }
                 chmod($filepath, 0777);
                 global $icc_extraction;
                 global $ffmpeg_supported_extensions;
                 if ($icc_extraction && $extension != "pdf" && !in_array($extension, $ffmpeg_supported_extensions)) {
                     extract_icc_profile($ref, $extension);
                 }
                 $status = "Your file has been uploaded.";
             }
         }
     }
     # Store extension in the database and update file modified time.
     if ($revert) {
         $has_image = "";
     } else {
         $has_image = ",has_image=0";
     }
     sql_query("update resource set file_extension='{$extension}',preview_extension='jpg',file_modified=now() {$has_image} where ref='{$ref}'");
     # delete existing resource_dimensions
     sql_query("delete from resource_dimensions where resource='{$ref}'");
     # get file metadata
     if (!$no_exif) {
         extract_exif_comment($ref, $extension);
     } else {
         global $merge_filename_with_title, $lang;
         if ($merge_filename_with_title) {
             $merge_filename_with_title_option = urlencode(getval('merge_filename_with_title_option', ''));
             $merge_filename_with_title_include_extensions = urlencode(getval('merge_filename_with_title_include_extensions', ''));
             $merge_filename_with_title_spacer = urlencode(getval('merge_filename_with_title_spacer', ''));
             $original_filename = '';
             if (isset($_REQUEST['name'])) {
                 $original_filename = $_REQUEST['name'];
             } else {
                 $original_filename = $processfile['name'];
             }
             if ($merge_filename_with_title_include_extensions == 'yes') {
                 $merged_filename = $original_filename;
             } else {
                 $merged_filename = strip_extension($original_filename);
             }
             // Get title field:
             $resource = get_resource_data($ref);
             $read_from = get_exiftool_fields($resource['resource_type']);
             for ($i = 0; $i < count($read_from); $i++) {
                 if ($read_from[$i]['name'] == 'title') {
                     $oldval = get_data_by_field($ref, $read_from[$i]['ref']);
                     if (strpos($oldval, $merged_filename) !== FALSE) {
                         continue;
                     }
                     switch ($merge_filename_with_title_option) {
                         case $lang['merge_filename_title_do_not_use']:
                             // Do nothing since the user doesn't want to use this feature
                             break;
                         case $lang['merge_filename_title_replace']:
                             $newval = $merged_filename;
                             break;
                         case $lang['merge_filename_title_prefix']:
                             $newval = $merged_filename . $merge_filename_with_title_spacer . $oldval;
                             if ($oldval == '') {
                                 $newval = $merged_filename;
                             }
                             break;
                         case $lang['merge_filename_title_suffix']:
                             $newval = $oldval . $merge_filename_with_title_spacer . $merged_filename;
                             if ($oldval == '') {
                                 $newval = $merged_filename;
                             }
                             break;
                         default:
                             // Do nothing
                             break;
                     }
                     update_field($ref, $read_from[$i]['ref'], $newval);
                 }
             }
         }
     }
     # extract text from documents (e.g. PDF, DOC).
     global $extracted_text_field;
     if (isset($extracted_text_field) && !$no_exif) {
         if (isset($unoconv_path) && in_array($extension, $unoconv_extensions)) {
             // omit, since the unoconv process will do it during preview creation below
         } else {
             extract_text($ref, $extension);
         }
     }
     # Store original filename in field, if set
     global $filename_field, $amended_filename;
     if (isset($filename_field)) {
         if (isset($amended_filename)) {
             $filename = $amended_filename;
         }
     }
     if (!$revert) {
         update_field($ref, $filename_field, $filename);
     } else {
         update_field($ref, $filename_field, $original_filename);
     }
     if (!$revert) {
         # Clear any existing FLV file or multi-page previews.
         global $pdf_pages;
         for ($n = 2; $n <= $pdf_pages; $n++) {
             # Remove preview page.
             $path = get_resource_path($ref, true, "scr", false, "jpg", -1, $n, false);
             if (file_exists($path)) {
                 unlink($path);
             }
             # Also try the watermarked version.
             $path = get_resource_path($ref, true, "scr", false, "jpg", -1, $n, true);
             if (file_exists($path)) {
                 unlink($path);
             }
         }
         # Remove any FLV video preview (except if the actual resource is an FLV file).
         global $ffmpeg_preview_extension;
         if ($extension != $ffmpeg_preview_extension) {
             $path = get_resource_path($ref, true, "", false, $ffmpeg_preview_extension);
             if (file_exists($path)) {
                 unlink($path);
             }
         }
         # Remove any FLV preview-only file
         $path = get_resource_path($ref, true, "pre", false, $ffmpeg_preview_extension);
         if (file_exists($path)) {
             unlink($path);
         }
         # Remove any MP3 (except if the actual resource is an MP3 file).
         if ($extension != "mp3") {
             $path = get_resource_path($ref, true, "", false, "mp3");
             if (file_exists($path)) {
                 unlink($path);
             }
         }
         # Create previews
         global $enable_thumbnail_creation_on_upload;
         if ($enable_thumbnail_creation_on_upload) {
             create_previews($ref, false, $extension);
         } else {
             # Offline thumbnail generation is being used. Set 'has_image' to zero so the offline create_previews.php script picks this up.
             sql_query("update resource set has_image=0 where ref='{$ref}'");
         }
     }
     # Update file dimensions
     get_original_imagesize($ref, $filepath, $extension);
     hook("Uploadfilesuccess", "", array("resourceId" => $ref));
     # Update disk usage
     update_disk_usage($ref);
     # Log this activity.
     $log_ref = resource_log($ref, "u", 0);
     hook("upload_image_after_log_write", "", array($ref, $log_ref));
     return $status;
 }
Example #22
0
function payment_set_complete($collection, $emailconfirmation = "")
{
    global $applicationname, $baseurl, $userref, $username, $useremail, $userfullname, $email_notify, $lang, $currency_symbol;
    # Mark items in the collection as paid so they can be downloaded.
    sql_query("update collection_resource set purchase_complete=1 where collection='{$collection}'");
    # For each resource, add an entry to the log to show it has been purchased.
    $resources = sql_query("select * from collection_resource where collection='{$collection}'");
    $summary = "<style>.InfoTable td {padding:5px;}</style><table border=\"1\" class=\"InfoTable\"><tr><td><strong>" . $lang["property-reference"] . "</strong></td><td><strong>" . $lang["size"] . "</strong></td><td><strong>" . $lang["price"] . "</strong></td></tr>";
    foreach ($resources as $resource) {
        $purchasesize = $resource["purchase_size"];
        if ($purchasesize == "") {
            $purchasesize = $lang["original"];
        }
        resource_log($resource["resource"], "p", 0, "", "", "", 0, $resource["purchase_size"], $resource["purchase_price"]);
        $summary .= "<tr><td>" . $resource["resource"] . "</td><td>" . $purchasesize . "</td><td>" . $currency_symbol . $resource["purchase_price"] . "</td></tr>";
    }
    $summary .= "</table>";
    # Send email to admin
    $message = $lang["purchase_complete_email_admin_body"] . "<br>" . $lang["username"] . ": " . $username . "(" . $userfullname . ")<br>" . $summary . "<br><br>{$baseurl}/?c=" . $collection . "<br>";
    send_mail($email_notify, $applicationname . ": " . $lang["purchase_complete_email_admin"], $message, "", "", "", null, "", "", true);
    #Send email to user
    $confirmation_address = $emailconfirmation != "" ? $emailconfirmation : $useremail;
    $userconfirmmessage = $lang["purchase_complete_email_user_body"] . $summary . "<br><br>{$baseurl}/?c=" . $collection . "<br>";
    send_mail($useremail, $applicationname . ": " . $lang["purchase_complete_email_user"], $userconfirmmessage, "", "", "", null, "", "", true);
    # Rename so that can be viewed on my purchases page
    sql_query("update collection set name= '" . date("Y-m-d H:i") . "' where ref='{$collection}'");
    return true;
}
Example #23
0
if (!checkperm("r")) {
    exit("Permission denied.");
}
include "../../../include/general.php";
include "../../../include/resource_functions.php";
$ref = getvalescaped("ref", "");
$resource = getvalescaped("resource", "");
# Check access
$edit_access = get_edit_access($resource);
if (!$edit_access) {
    exit("Access denied");
}
# Should never arrive at this page without edit access
if (getval("submitted", "") != "") {
    sql_query("delete from resource_license where ref='{$ref}' and resource='{$resource}'");
    resource_log($resource, "", "", $lang["delete_license"] . " " . $ref);
    redirect("pages/view.php?ref=" . $resource);
}
include "../../../include/header.php";
?>
<div class="BasicsBox">
<p><a href="<?php 
echo $baseurl_short;
?>
pages/view.php?ref=<?php 
echo $resource;
?>
"  onClick="return CentralSpaceLoad(this,true);">&lt;&nbsp;<?php 
echo $lang["backtoresourceview"];
?>
</a></p>
Example #24
0
    # Construct expiry date
    $expires = getvalescaped("expires_year", "") . "-" . getvalescaped("expires_month", "") . "-" . getvalescaped("expires_day", "");
    # Construct usage
    $license_usage = "";
    if (isset($_POST["license_usage"])) {
        $license_usage = escape_check(join(", ", $_POST["license_usage"]));
    }
    if ($ref == "new") {
        # New record
        sql_query("insert into resource_license (resource,outbound,holder,license_usage,description,expires) values ('" . getvalescaped("resource", "") . "', '" . getvalescaped("outbound", "") . "', '" . getvalescaped("holder", "") . "', '{$license_usage}', '" . getvalescaped("description", "") . "', '{$expires}')");
        $ref = sql_insert_id();
        resource_log($resource, "", "", $lang["new_license"] . " " . $ref);
    } else {
        # Existing record
        sql_query("update resource_license set outbound='" . getvalescaped("outbound", "") . "',holder='" . getvalescaped("holder", "") . "', license_usage='{$license_usage}',description='" . getvalescaped("description", "") . "',expires='{$expires}' where ref='{$ref}' and resource='{$resource}'");
        resource_log($resource, "", "", $lang["edit_license"] . " " . $ref);
    }
    redirect("pages/view.php?ref=" . $resource);
}
# Fetch license data
if ($ref == "new") {
    # Set default values for the creation of a new record.
    $license = array("resource" => $resource, "outbound" => 1, "holder" => "", "license_usage" => "", "description" => "", "expires" => date("Y-m-d"));
} else {
    $license = sql_query("select * from resource_license where ref='{$ref}'");
    if (count($license) == 0) {
        exit("License not found.");
    }
    $license = $license[0];
    $resource = $license["resource"];
}
function save_alternative_file($resource, $ref)
{
    # Saves the 'alternative file' edit form back to the database
    $sql = "";
    # Uploaded file provided?
    if (array_key_exists("userfile", $_FILES)) {
        # Fetch filename / path
        $processfile = $_FILES['userfile'];
        $filename = strtolower(str_replace(" ", "_", $processfile['name']));
        # Work out extension
        $extension = explode(".", $filename);
        $extension = trim(strtolower($extension[count($extension) - 1]));
        # Find the path for this resource.
        $path = get_resource_path($resource, true, "", true, $extension, -1, 1, false, "", $ref);
        # Debug
        debug("Uploading alternative file {$ref} with extension {$extension} to {$path}");
        if ($filename != "") {
            $result = move_uploaded_file($processfile['tmp_name'], $path);
            if ($result == false) {
                exit("File upload error. Please check the size of the file you are trying to upload.");
            } else {
                chmod($path, 0777);
                $file_size = @filesize_unlimited($path);
                $sql .= ",file_name='" . escape_check($filename) . "',file_extension='" . escape_check($extension) . "',file_size='" . $file_size . "',creation_date=now()";
            }
            # Preview creation for alternative files (enabled via config)
            global $alternative_file_previews, $lang;
            if ($alternative_file_previews) {
                create_previews($resource, false, $extension, false, false, $ref);
            }
            # Log this
            resource_log($resource, "b", "", $ref . ": " . getvalescaped("name", "") . ", " . getvalescaped("description", "") . ", " . escape_check($filename));
        }
    }
    # Save data back to the database.
    sql_query("update resource_alt_files set name='" . getvalescaped("name", "") . "',description='" . getvalescaped("description", "") . "',alt_type='" . getvalescaped("alt_type", "") . "' {$sql} where resource='{$resource}' and ref='{$ref}'");
    # Update disk usage
    update_disk_usage($resource);
}