# packages/acs-subsite/www/image.vuh
#
# Subsite handler for images
#
# @author Dave Bauer (dave@thedesignexperience.org)
# @creation-date 2006-08-01
# @cvs-id $Id: image.vuh,v 1.8 2010/10/22 14:31:14 raulm Exp $
set url [ad_conn path_info]
if {![regexp {^/([0-9]+)(/(|thumbnail|avatar|info))?(/(private)/([0-9]+))?(/(.*))?$} $url match object_id extra_arg_slash extra_arg private_slash private private_parent_id filename_slash filename anchor]} {
    ad_return_warning "Invalid object id" [subst {
        The identifier given for this object (${object_id}) is invalid.  Please check your url 
        or contact the webmaster if you think it should work.
    }]
    return
}

# check permissions!
if { $private eq "private" } {
    # find if the image has a parent link to the object
    # that is, if the image is used in a content item and you can read the
    # content item, you can read the image regardless of the permissions
    
    set object_to_check $object_id

    if { [application_data_link::link_exists \
              -from_object_id $private_parent_id \
              -to_object_id $object_id] } {
        # if the link does not exist it might be
        # because its a new object
        # that means you uploaded the image so you can see it in 
        # the editor while you are working on it
        set object_to_check $private_parent_id
    }
    if {![permission::permission_p \
              -privilege "read" \
              -object_id $object_to_check \
              -party_id [ad_conn user_id]]} {
        ns_returnnotfound
        ad_script_abort
    }
} else { 
    permission::require_permission \
        -privilege "read" \
        -object_id $object_id \
        -party_id [ad_conn user_id]
}

# find a cr_item and serve it

if { $extra_arg eq "thumbnail" || $extra_arg eq "avatar" } {
    #find the thumbnail object_id
    set new_object_id [image::get_resized_item_id -item_id $object_id -size_name $extra_arg]
    if {$new_object_id eq ""} {
        # We need to resize the image it seems
        set new_object_id [image::resize -item_id $object_id -size_name $extra_arg]
    }
    set object_id $new_object_id
}

if {$extra_arg eq "info"} {
    rp_form_put item_id $object_id
    rp_form_put filename $filename
    rp_internal_redirect "/packages/acs-content-repository/www/image-info"
    ad_script_abort
} else {
    cr_write_content -item_id $object_id
}
