2016-04-28 13:46:13 +02:00
|
|
|
require 'filemagic'
|
|
|
|
|
|
|
|
class DocumentsController < ApplicationController
|
|
|
|
before_filter -> { require_plugin_enabled FoodsoftDocuments }
|
|
|
|
|
|
|
|
def index
|
|
|
|
if params["sort"]
|
|
|
|
sort = case params["sort"]
|
|
|
|
when "name" then "name"
|
|
|
|
when "created_at" then "created_at"
|
|
|
|
when "name_reverse" then "name DESC"
|
|
|
|
when "created_at_reverse" then "created_at DESC"
|
|
|
|
end
|
|
|
|
else
|
|
|
|
sort = "name"
|
|
|
|
end
|
|
|
|
|
|
|
|
@documents = Document.page(params[:page]).per(@per_page).order(sort)
|
|
|
|
end
|
|
|
|
|
|
|
|
def new
|
|
|
|
@document = Document.new
|
|
|
|
end
|
|
|
|
|
|
|
|
def create
|
|
|
|
@document = Document.new
|
|
|
|
@document.data = params[:document][:data].read
|
|
|
|
@document.mime = FileMagic.new(FileMagic::MAGIC_MIME).buffer(@document.data)
|
2017-10-11 02:39:35 +02:00
|
|
|
raise t('.not_allowed_mime', mime: @document.mime) unless allowed_mime? @document.mime
|
2016-04-28 13:46:13 +02:00
|
|
|
if params[:document][:name] == ''
|
|
|
|
name = params[:document][:data].original_filename
|
|
|
|
name = File.basename(name)
|
|
|
|
@document.name = name.gsub(/[^\w\.\-]/, '_')
|
|
|
|
else
|
|
|
|
@document.name = params[:document][:name]
|
|
|
|
end
|
|
|
|
@document.created_by = current_user
|
|
|
|
@document.save!
|
2017-10-11 01:37:40 +02:00
|
|
|
redirect_to documents_path, notice: t('.notice')
|
2016-04-28 13:46:13 +02:00
|
|
|
rescue => error
|
2017-10-11 01:37:40 +02:00
|
|
|
redirect_to documents_path, alert: t('.error', error: error.message)
|
2016-04-28 13:46:13 +02:00
|
|
|
end
|
|
|
|
|
|
|
|
def destroy
|
|
|
|
@document = Document.find(params[:id])
|
|
|
|
if @document.created_by == current_user or current_user.role_admin?
|
|
|
|
@document.destroy
|
2017-10-11 01:37:40 +02:00
|
|
|
redirect_to documents_path, notice: t('.notice')
|
2016-04-28 13:46:13 +02:00
|
|
|
else
|
2017-10-11 01:37:40 +02:00
|
|
|
redirect_to documents_path, alert: t('.no_right')
|
2016-04-28 13:46:13 +02:00
|
|
|
end
|
|
|
|
rescue => error
|
2017-10-11 01:37:40 +02:00
|
|
|
redirect_to documents_path, alert: t('.error', error: error.message)
|
2016-04-28 13:46:13 +02:00
|
|
|
end
|
|
|
|
|
|
|
|
def show
|
|
|
|
@document = Document.find(params[:id])
|
2017-10-11 01:30:29 +02:00
|
|
|
send_data(@document.data, filename: @document.filename, type: @document.mime)
|
2016-04-28 13:46:13 +02:00
|
|
|
end
|
2017-10-11 02:39:35 +02:00
|
|
|
|
|
|
|
def allowed_mime?(mime)
|
|
|
|
whitelist = FoodsoftConfig[:documents_allowed_extension].split
|
|
|
|
MIME::Types.type_for(whitelist).each do |type|
|
|
|
|
return true if type.like? mime
|
|
|
|
end
|
|
|
|
false
|
|
|
|
end
|
2016-04-28 13:46:13 +02:00
|
|
|
end
|