attachments_controller.rb 2.53 KB
Newer Older
1
#-- encoding: UTF-8
2 3
#-- copyright
# ChiliProject is a project management system.
4
#
Holger Just's avatar
Holger Just committed
5
# Copyright (C) 2010-2013 the ChiliProject Team
6
#
7 8 9 10
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
11
#
12 13 14
# See doc/COPYRIGHT.rdoc for more details.
#++

15
class AttachmentsController < ApplicationController
16
  before_filter :find_project
17
  before_filter :file_readable, :read_authorize, :except => :destroy
18
  before_filter :delete_authorize, :only => :destroy
19

20
  verify :method => :post, :only => :destroy
21

22 23 24 25
  def show
    if @attachment.is_diff?
      @diff = File.new(@attachment.diskfile, "rb").read
      render :action => 'diff'
26
    elsif @attachment.is_text? && @attachment.filesize <= Setting.file_max_size_displayed.to_i.kilobyte
27 28
      @content = File.new(@attachment.diskfile, "rb").read
      render :action => 'file'
29
    else
30 31 32
      download
    end
  end
33

34
  def download
35 36 37
    if @attachment.container.is_a?(Version) || @attachment.container.is_a?(Project)
      @attachment.increment_download
    end
38

39
    # images are sent inline
40
    send_file @attachment.diskfile, :filename => filename_for_content_disposition(@attachment.filename),
41
                                    :type => detect_content_type(@attachment),
42
                                    :disposition => (@attachment.image? ? 'inline' : 'attachment')
43

44
  end
45

46 47 48 49 50 51 52
  def destroy
    # Make sure association callbacks are called
    @attachment.container.attachments.delete(@attachment)
    redirect_to :back
  rescue ::ActionController::RedirectBackError
    redirect_to :controller => 'projects', :action => 'show', :id => @project
  end
53

54 55 56
private
  def find_project
    @attachment = Attachment.find(params[:id])
57 58
    # Show 404 if the filename in the url is wrong
    raise ActiveRecord::RecordNotFound if params[:filename] && params[:filename] != @attachment.filename
59
    @project = @attachment.project
60 61
  rescue ActiveRecord::RecordNotFound
    render_404
62
  end
63

64 65 66 67
  # Checks that the file exists and is readable
  def file_readable
    @attachment.readable? ? true : render_404
  end
68

69 70 71
  def read_authorize
    @attachment.visible? ? true : deny_access
  end
72

73 74 75
  def delete_authorize
    @attachment.deletable? ? true : deny_access
  end
76

77 78 79 80 81
  def detect_content_type(attachment)
    content_type = attachment.content_type
    if content_type.blank?
      content_type = Redmine::MimeType.of(attachment.filename)
    end
82
    content_type.to_s
83
  end
84
end