##// END OF EJS Templates
Add inline image preview/display for attachments and repository entries (#22058)....
Jean-Philippe Lang -
r14942:2fbce6515d6f
parent child
Show More
@@ -0,0 +1,3
1 <%= render :layout => 'layouts/file' do %>
2 <%= render :partial => 'common/image', :locals => {:path => download_named_attachment_url(@attachment, @attachment.filename), :alt => @attachment.filename} %>
3 <% end %>
@@ -0,0 +1,1
1 <%= image_tag path, :alt => alt, :class => 'filecontent image' %>
@@ -1,191 +1,193
1 1 # Redmine - project management software
2 2 # Copyright (C) 2006-2016 Jean-Philippe Lang
3 3 #
4 4 # This program is free software; you can redistribute it and/or
5 5 # modify it under the terms of the GNU General Public License
6 6 # as published by the Free Software Foundation; either version 2
7 7 # of the License, or (at your option) any later version.
8 8 #
9 9 # This program is distributed in the hope that it will be useful,
10 10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 12 # GNU General Public License for more details.
13 13 #
14 14 # You should have received a copy of the GNU General Public License
15 15 # along with this program; if not, write to the Free Software
16 16 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17 17
18 18 class AttachmentsController < ApplicationController
19 19 before_filter :find_attachment, :only => [:show, :download, :thumbnail, :destroy]
20 20 before_filter :find_editable_attachments, :only => [:edit, :update]
21 21 before_filter :file_readable, :read_authorize, :only => [:show, :download, :thumbnail]
22 22 before_filter :delete_authorize, :only => :destroy
23 23 before_filter :authorize_global, :only => :upload
24 24
25 25 accept_api_auth :show, :download, :thumbnail, :upload
26 26
27 27 def show
28 28 respond_to do |format|
29 29 format.html {
30 30 if @attachment.is_diff?
31 31 @diff = File.read(@attachment.diskfile, :mode => "rb")
32 32 @diff_type = params[:type] || User.current.pref[:diff_type] || 'inline'
33 33 @diff_type = 'inline' unless %w(inline sbs).include?(@diff_type)
34 34 # Save diff type as user preference
35 35 if User.current.logged? && @diff_type != User.current.pref[:diff_type]
36 36 User.current.pref[:diff_type] = @diff_type
37 37 User.current.preference.save
38 38 end
39 39 render :action => 'diff'
40 40 elsif @attachment.is_text? && @attachment.filesize <= Setting.file_max_size_displayed.to_i.kilobyte
41 41 @content = File.read(@attachment.diskfile, :mode => "rb")
42 42 render :action => 'file'
43 elsif @attachment.is_image?
44 render :action => 'image'
43 45 else
44 46 download
45 47 end
46 48 }
47 49 format.api
48 50 end
49 51 end
50 52
51 53 def download
52 54 if @attachment.container.is_a?(Version) || @attachment.container.is_a?(Project)
53 55 @attachment.increment_download
54 56 end
55 57
56 58 if stale?(:etag => @attachment.digest)
57 59 # images are sent inline
58 60 send_file @attachment.diskfile, :filename => filename_for_content_disposition(@attachment.filename),
59 61 :type => detect_content_type(@attachment),
60 62 :disposition => (@attachment.image? ? 'inline' : 'attachment')
61 63 end
62 64 end
63 65
64 66 def thumbnail
65 67 if @attachment.thumbnailable? && tbnail = @attachment.thumbnail(:size => params[:size])
66 68 if stale?(:etag => tbnail)
67 69 send_file tbnail,
68 70 :filename => filename_for_content_disposition(@attachment.filename),
69 71 :type => detect_content_type(@attachment),
70 72 :disposition => 'inline'
71 73 end
72 74 else
73 75 # No thumbnail for the attachment or thumbnail could not be created
74 76 render :nothing => true, :status => 404
75 77 end
76 78 end
77 79
78 80 def upload
79 81 # Make sure that API users get used to set this content type
80 82 # as it won't trigger Rails' automatic parsing of the request body for parameters
81 83 unless request.content_type == 'application/octet-stream'
82 84 render :nothing => true, :status => 406
83 85 return
84 86 end
85 87
86 88 @attachment = Attachment.new(:file => request.raw_post)
87 89 @attachment.author = User.current
88 90 @attachment.filename = params[:filename].presence || Redmine::Utils.random_hex(16)
89 91 @attachment.content_type = params[:content_type].presence
90 92 saved = @attachment.save
91 93
92 94 respond_to do |format|
93 95 format.js
94 96 format.api {
95 97 if saved
96 98 render :action => 'upload', :status => :created
97 99 else
98 100 render_validation_errors(@attachment)
99 101 end
100 102 }
101 103 end
102 104 end
103 105
104 106 def edit
105 107 end
106 108
107 109 def update
108 110 if params[:attachments].is_a?(Hash)
109 111 if Attachment.update_attachments(@attachments, params[:attachments])
110 112 redirect_back_or_default home_path
111 113 return
112 114 end
113 115 end
114 116 render :action => 'edit'
115 117 end
116 118
117 119 def destroy
118 120 if @attachment.container.respond_to?(:init_journal)
119 121 @attachment.container.init_journal(User.current)
120 122 end
121 123 if @attachment.container
122 124 # Make sure association callbacks are called
123 125 @attachment.container.attachments.delete(@attachment)
124 126 else
125 127 @attachment.destroy
126 128 end
127 129
128 130 respond_to do |format|
129 131 format.html { redirect_to_referer_or project_path(@project) }
130 132 format.js
131 133 end
132 134 end
133 135
134 136 private
135 137
136 138 def find_attachment
137 139 @attachment = Attachment.find(params[:id])
138 140 # Show 404 if the filename in the url is wrong
139 141 raise ActiveRecord::RecordNotFound if params[:filename] && params[:filename] != @attachment.filename
140 142 @project = @attachment.project
141 143 rescue ActiveRecord::RecordNotFound
142 144 render_404
143 145 end
144 146
145 147 def find_editable_attachments
146 148 klass = params[:object_type].to_s.singularize.classify.constantize rescue nil
147 149 unless klass && klass.reflect_on_association(:attachments)
148 150 render_404
149 151 return
150 152 end
151 153
152 154 @container = klass.find(params[:object_id])
153 155 if @container.respond_to?(:visible?) && !@container.visible?
154 156 render_403
155 157 return
156 158 end
157 159 @attachments = @container.attachments.select(&:editable?)
158 160 if @container.respond_to?(:project)
159 161 @project = @container.project
160 162 end
161 163 render_404 if @attachments.empty?
162 164 rescue ActiveRecord::RecordNotFound
163 165 render_404
164 166 end
165 167
166 168 # Checks that the file exists and is readable
167 169 def file_readable
168 170 if @attachment.readable?
169 171 true
170 172 else
171 173 logger.error "Cannot send attachment, #{@attachment.diskfile} does not exist or is unreadable."
172 174 render_404
173 175 end
174 176 end
175 177
176 178 def read_authorize
177 179 @attachment.visible? ? true : deny_access
178 180 end
179 181
180 182 def delete_authorize
181 183 @attachment.deletable? ? true : deny_access
182 184 end
183 185
184 186 def detect_content_type(attachment)
185 187 content_type = attachment.content_type
186 188 if content_type.blank? || content_type == "application/octet-stream"
187 189 content_type = Redmine::MimeType.of(attachment.filename)
188 190 end
189 191 content_type.to_s
190 192 end
191 193 end
@@ -1,439 +1,441
1 1 # Redmine - project management software
2 2 # Copyright (C) 2006-2016 Jean-Philippe Lang
3 3 #
4 4 # This program is free software; you can redistribute it and/or
5 5 # modify it under the terms of the GNU General Public License
6 6 # as published by the Free Software Foundation; either version 2
7 7 # of the License, or (at your option) any later version.
8 8 #
9 9 # This program is distributed in the hope that it will be useful,
10 10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 12 # GNU General Public License for more details.
13 13 #
14 14 # You should have received a copy of the GNU General Public License
15 15 # along with this program; if not, write to the Free Software
16 16 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17 17
18 18 require 'SVG/Graph/Bar'
19 19 require 'SVG/Graph/BarHorizontal'
20 20 require 'digest/sha1'
21 21 require 'redmine/scm/adapters'
22 22
23 23 class ChangesetNotFound < Exception; end
24 24 class InvalidRevisionParam < Exception; end
25 25
26 26 class RepositoriesController < ApplicationController
27 27 menu_item :repository
28 28 menu_item :settings, :only => [:new, :create, :edit, :update, :destroy, :committers]
29 29 default_search_scope :changesets
30 30
31 31 before_filter :find_project_by_project_id, :only => [:new, :create]
32 32 before_filter :find_repository, :only => [:edit, :update, :destroy, :committers]
33 33 before_filter :find_project_repository, :except => [:new, :create, :edit, :update, :destroy, :committers]
34 34 before_filter :find_changeset, :only => [:revision, :add_related_issue, :remove_related_issue]
35 35 before_filter :authorize
36 36 accept_rss_auth :revisions
37 37
38 38 rescue_from Redmine::Scm::Adapters::CommandFailed, :with => :show_error_command_failed
39 39
40 40 def new
41 41 scm = params[:repository_scm] || (Redmine::Scm::Base.all & Setting.enabled_scm).first
42 42 @repository = Repository.factory(scm)
43 43 @repository.is_default = @project.repository.nil?
44 44 @repository.project = @project
45 45 end
46 46
47 47 def create
48 48 attrs = pickup_extra_info
49 49 @repository = Repository.factory(params[:repository_scm])
50 50 @repository.safe_attributes = params[:repository]
51 51 if attrs[:attrs_extra].keys.any?
52 52 @repository.merge_extra_info(attrs[:attrs_extra])
53 53 end
54 54 @repository.project = @project
55 55 if request.post? && @repository.save
56 56 redirect_to settings_project_path(@project, :tab => 'repositories')
57 57 else
58 58 render :action => 'new'
59 59 end
60 60 end
61 61
62 62 def edit
63 63 end
64 64
65 65 def update
66 66 attrs = pickup_extra_info
67 67 @repository.safe_attributes = attrs[:attrs]
68 68 if attrs[:attrs_extra].keys.any?
69 69 @repository.merge_extra_info(attrs[:attrs_extra])
70 70 end
71 71 @repository.project = @project
72 72 if @repository.save
73 73 redirect_to settings_project_path(@project, :tab => 'repositories')
74 74 else
75 75 render :action => 'edit'
76 76 end
77 77 end
78 78
79 79 def pickup_extra_info
80 80 p = {}
81 81 p_extra = {}
82 82 params[:repository].each do |k, v|
83 83 if k =~ /^extra_/
84 84 p_extra[k] = v
85 85 else
86 86 p[k] = v
87 87 end
88 88 end
89 89 {:attrs => p, :attrs_extra => p_extra}
90 90 end
91 91 private :pickup_extra_info
92 92
93 93 def committers
94 94 @committers = @repository.committers
95 95 @users = @project.users.to_a
96 96 additional_user_ids = @committers.collect(&:last).collect(&:to_i) - @users.collect(&:id)
97 97 @users += User.where(:id => additional_user_ids).to_a unless additional_user_ids.empty?
98 98 @users.compact!
99 99 @users.sort!
100 100 if request.post? && params[:committers].is_a?(Hash)
101 101 # Build a hash with repository usernames as keys and corresponding user ids as values
102 102 @repository.committer_ids = params[:committers].values.inject({}) {|h, c| h[c.first] = c.last; h}
103 103 flash[:notice] = l(:notice_successful_update)
104 104 redirect_to settings_project_path(@project, :tab => 'repositories')
105 105 end
106 106 end
107 107
108 108 def destroy
109 109 @repository.destroy if request.delete?
110 110 redirect_to settings_project_path(@project, :tab => 'repositories')
111 111 end
112 112
113 113 def show
114 114 @repository.fetch_changesets if @project.active? && Setting.autofetch_changesets? && @path.empty?
115 115
116 116 @entries = @repository.entries(@path, @rev)
117 117 @changeset = @repository.find_changeset_by_name(@rev)
118 118 if request.xhr?
119 119 @entries ? render(:partial => 'dir_list_content') : render(:nothing => true)
120 120 else
121 121 (show_error_not_found; return) unless @entries
122 122 @changesets = @repository.latest_changesets(@path, @rev)
123 123 @properties = @repository.properties(@path, @rev)
124 124 @repositories = @project.repositories
125 125 render :action => 'show'
126 126 end
127 127 end
128 128
129 129 alias_method :browse, :show
130 130
131 131 def changes
132 132 @entry = @repository.entry(@path, @rev)
133 133 (show_error_not_found; return) unless @entry
134 134 @changesets = @repository.latest_changesets(@path, @rev, Setting.repository_log_display_limit.to_i)
135 135 @properties = @repository.properties(@path, @rev)
136 136 @changeset = @repository.find_changeset_by_name(@rev)
137 137 end
138 138
139 139 def revisions
140 140 @changeset_count = @repository.changesets.count
141 141 @changeset_pages = Paginator.new @changeset_count,
142 142 per_page_option,
143 143 params['page']
144 144 @changesets = @repository.changesets.
145 145 limit(@changeset_pages.per_page).
146 146 offset(@changeset_pages.offset).
147 147 includes(:user, :repository, :parents).
148 148 to_a
149 149
150 150 respond_to do |format|
151 151 format.html { render :layout => false if request.xhr? }
152 152 format.atom { render_feed(@changesets, :title => "#{@project.name}: #{l(:label_revision_plural)}") }
153 153 end
154 154 end
155 155
156 156 def raw
157 157 entry_and_raw(true)
158 158 end
159 159
160 160 def entry
161 161 entry_and_raw(false)
162 162 end
163 163
164 164 def entry_and_raw(is_raw)
165 165 @entry = @repository.entry(@path, @rev)
166 166 (show_error_not_found; return) unless @entry
167 167
168 168 # If the entry is a dir, show the browser
169 169 (show; return) if @entry.is_dir?
170 170
171 171 @content = @repository.cat(@path, @rev)
172 172 (show_error_not_found; return) unless @content
173 if is_raw ||
173 if !is_raw && Redmine::MimeType.is_type?('image', @path)
174 # simply render
175 elsif is_raw ||
174 176 (@content.size && @content.size > Setting.file_max_size_displayed.to_i.kilobyte) ||
175 177 ! is_entry_text_data?(@content, @path)
176 178 # Force the download
177 179 send_opt = { :filename => filename_for_content_disposition(@path.split('/').last) }
178 180 send_type = Redmine::MimeType.of(@path)
179 181 send_opt[:type] = send_type.to_s if send_type
180 182 send_opt[:disposition] = (Redmine::MimeType.is_type?('image', @path) && !is_raw ? 'inline' : 'attachment')
181 183 send_data @content, send_opt
182 184 else
183 185 # Prevent empty lines when displaying a file with Windows style eol
184 186 # TODO: UTF-16
185 187 # Is this needs? AttachmentsController reads file simply.
186 188 @content.gsub!("\r\n", "\n")
187 189 @changeset = @repository.find_changeset_by_name(@rev)
188 190 end
189 191 end
190 192 private :entry_and_raw
191 193
192 194 def is_entry_text_data?(ent, path)
193 195 # UTF-16 contains "\x00".
194 196 # It is very strict that file contains less than 30% of ascii symbols
195 197 # in non Western Europe.
196 198 return true if Redmine::MimeType.is_type?('text', path)
197 199 # Ruby 1.8.6 has a bug of integer divisions.
198 200 # http://apidock.com/ruby/v1_8_6_287/String/is_binary_data%3F
199 201 return false if ent.is_binary_data?
200 202 true
201 203 end
202 204 private :is_entry_text_data?
203 205
204 206 def annotate
205 207 @entry = @repository.entry(@path, @rev)
206 208 (show_error_not_found; return) unless @entry
207 209
208 210 @annotate = @repository.scm.annotate(@path, @rev)
209 211 if @annotate.nil? || @annotate.empty?
210 212 (render_error l(:error_scm_annotate); return)
211 213 end
212 214 ann_buf_size = 0
213 215 @annotate.lines.each do |buf|
214 216 ann_buf_size += buf.size
215 217 end
216 218 if ann_buf_size > Setting.file_max_size_displayed.to_i.kilobyte
217 219 (render_error l(:error_scm_annotate_big_text_file); return)
218 220 end
219 221 @changeset = @repository.find_changeset_by_name(@rev)
220 222 end
221 223
222 224 def revision
223 225 respond_to do |format|
224 226 format.html
225 227 format.js {render :layout => false}
226 228 end
227 229 end
228 230
229 231 # Adds a related issue to a changeset
230 232 # POST /projects/:project_id/repository/(:repository_id/)revisions/:rev/issues
231 233 def add_related_issue
232 234 issue_id = params[:issue_id].to_s.sub(/^#/,'')
233 235 @issue = @changeset.find_referenced_issue_by_id(issue_id)
234 236 if @issue && (!@issue.visible? || @changeset.issues.include?(@issue))
235 237 @issue = nil
236 238 end
237 239
238 240 if @issue
239 241 @changeset.issues << @issue
240 242 end
241 243 end
242 244
243 245 # Removes a related issue from a changeset
244 246 # DELETE /projects/:project_id/repository/(:repository_id/)revisions/:rev/issues/:issue_id
245 247 def remove_related_issue
246 248 @issue = Issue.visible.find_by_id(params[:issue_id])
247 249 if @issue
248 250 @changeset.issues.delete(@issue)
249 251 end
250 252 end
251 253
252 254 def diff
253 255 if params[:format] == 'diff'
254 256 @diff = @repository.diff(@path, @rev, @rev_to)
255 257 (show_error_not_found; return) unless @diff
256 258 filename = "changeset_r#{@rev}"
257 259 filename << "_r#{@rev_to}" if @rev_to
258 260 send_data @diff.join, :filename => "#{filename}.diff",
259 261 :type => 'text/x-patch',
260 262 :disposition => 'attachment'
261 263 else
262 264 @diff_type = params[:type] || User.current.pref[:diff_type] || 'inline'
263 265 @diff_type = 'inline' unless %w(inline sbs).include?(@diff_type)
264 266
265 267 # Save diff type as user preference
266 268 if User.current.logged? && @diff_type != User.current.pref[:diff_type]
267 269 User.current.pref[:diff_type] = @diff_type
268 270 User.current.preference.save
269 271 end
270 272 @cache_key = "repositories/diff/#{@repository.id}/" +
271 273 Digest::MD5.hexdigest("#{@path}-#{@rev}-#{@rev_to}-#{@diff_type}-#{current_language}")
272 274 unless read_fragment(@cache_key)
273 275 @diff = @repository.diff(@path, @rev, @rev_to)
274 276 show_error_not_found unless @diff
275 277 end
276 278
277 279 @changeset = @repository.find_changeset_by_name(@rev)
278 280 @changeset_to = @rev_to ? @repository.find_changeset_by_name(@rev_to) : nil
279 281 @diff_format_revisions = @repository.diff_format_revisions(@changeset, @changeset_to)
280 282 end
281 283 end
282 284
283 285 def stats
284 286 end
285 287
286 288 def graph
287 289 data = nil
288 290 case params[:graph]
289 291 when "commits_per_month"
290 292 data = graph_commits_per_month(@repository)
291 293 when "commits_per_author"
292 294 data = graph_commits_per_author(@repository)
293 295 end
294 296 if data
295 297 headers["Content-Type"] = "image/svg+xml"
296 298 send_data(data, :type => "image/svg+xml", :disposition => "inline")
297 299 else
298 300 render_404
299 301 end
300 302 end
301 303
302 304 private
303 305
304 306 def find_repository
305 307 @repository = Repository.find(params[:id])
306 308 @project = @repository.project
307 309 rescue ActiveRecord::RecordNotFound
308 310 render_404
309 311 end
310 312
311 313 REV_PARAM_RE = %r{\A[a-f0-9]*\Z}i
312 314
313 315 def find_project_repository
314 316 @project = Project.find(params[:id])
315 317 if params[:repository_id].present?
316 318 @repository = @project.repositories.find_by_identifier_param(params[:repository_id])
317 319 else
318 320 @repository = @project.repository
319 321 end
320 322 (render_404; return false) unless @repository
321 323 @path = params[:path].is_a?(Array) ? params[:path].join('/') : params[:path].to_s
322 324 @rev = params[:rev].blank? ? @repository.default_branch : params[:rev].to_s.strip
323 325 @rev_to = params[:rev_to]
324 326
325 327 unless @rev.to_s.match(REV_PARAM_RE) && @rev_to.to_s.match(REV_PARAM_RE)
326 328 if @repository.branches.blank?
327 329 raise InvalidRevisionParam
328 330 end
329 331 end
330 332 rescue ActiveRecord::RecordNotFound
331 333 render_404
332 334 rescue InvalidRevisionParam
333 335 show_error_not_found
334 336 end
335 337
336 338 def find_changeset
337 339 if @rev.present?
338 340 @changeset = @repository.find_changeset_by_name(@rev)
339 341 end
340 342 show_error_not_found unless @changeset
341 343 end
342 344
343 345 def show_error_not_found
344 346 render_error :message => l(:error_scm_not_found), :status => 404
345 347 end
346 348
347 349 # Handler for Redmine::Scm::Adapters::CommandFailed exception
348 350 def show_error_command_failed(exception)
349 351 render_error l(:error_scm_command_failed, exception.message)
350 352 end
351 353
352 354 def graph_commits_per_month(repository)
353 355 @date_to = Date.today
354 356 @date_from = @date_to << 11
355 357 @date_from = Date.civil(@date_from.year, @date_from.month, 1)
356 358 commits_by_day = Changeset.
357 359 where("repository_id = ? AND commit_date BETWEEN ? AND ?", repository.id, @date_from, @date_to).
358 360 group(:commit_date).
359 361 count
360 362 commits_by_month = [0] * 12
361 363 commits_by_day.each {|c| commits_by_month[(@date_to.month - c.first.to_date.month) % 12] += c.last }
362 364
363 365 changes_by_day = Change.
364 366 joins(:changeset).
365 367 where("#{Changeset.table_name}.repository_id = ? AND #{Changeset.table_name}.commit_date BETWEEN ? AND ?", repository.id, @date_from, @date_to).
366 368 group(:commit_date).
367 369 count
368 370 changes_by_month = [0] * 12
369 371 changes_by_day.each {|c| changes_by_month[(@date_to.month - c.first.to_date.month) % 12] += c.last }
370 372
371 373 fields = []
372 374 12.times {|m| fields << month_name(((Date.today.month - 1 - m) % 12) + 1)}
373 375
374 376 graph = SVG::Graph::Bar.new(
375 377 :height => 300,
376 378 :width => 800,
377 379 :fields => fields.reverse,
378 380 :stack => :side,
379 381 :scale_integers => true,
380 382 :step_x_labels => 2,
381 383 :show_data_values => false,
382 384 :graph_title => l(:label_commits_per_month),
383 385 :show_graph_title => true
384 386 )
385 387
386 388 graph.add_data(
387 389 :data => commits_by_month[0..11].reverse,
388 390 :title => l(:label_revision_plural)
389 391 )
390 392
391 393 graph.add_data(
392 394 :data => changes_by_month[0..11].reverse,
393 395 :title => l(:label_change_plural)
394 396 )
395 397
396 398 graph.burn
397 399 end
398 400
399 401 def graph_commits_per_author(repository)
400 402 #data
401 403 stats = repository.stats_by_author
402 404 fields, commits_data, changes_data = [], [], []
403 405 stats.each do |name, hsh|
404 406 fields << name
405 407 commits_data << hsh[:commits_count]
406 408 changes_data << hsh[:changes_count]
407 409 end
408 410
409 411 #expand to 10 values if needed
410 412 fields = fields + [""]*(10 - fields.length) if fields.length<10
411 413 commits_data = commits_data + [0]*(10 - commits_data.length) if commits_data.length<10
412 414 changes_data = changes_data + [0]*(10 - changes_data.length) if changes_data.length<10
413 415
414 416 # Remove email address in usernames
415 417 fields = fields.collect {|c| c.gsub(%r{<.+@.+>}, '') }
416 418
417 419 #prepare graph
418 420 graph = SVG::Graph::BarHorizontal.new(
419 421 :height => 30 * commits_data.length,
420 422 :width => 800,
421 423 :fields => fields,
422 424 :stack => :side,
423 425 :scale_integers => true,
424 426 :show_data_values => false,
425 427 :rotate_y_labels => false,
426 428 :graph_title => l(:label_commits_per_author),
427 429 :show_graph_title => true
428 430 )
429 431 graph.add_data(
430 432 :data => commits_data,
431 433 :title => l(:label_revision_plural)
432 434 )
433 435 graph.add_data(
434 436 :data => changes_data,
435 437 :title => l(:label_change_plural)
436 438 )
437 439 graph.burn
438 440 end
439 441 end
@@ -1,402 +1,406
1 1 # Redmine - project management software
2 2 # Copyright (C) 2006-2016 Jean-Philippe Lang
3 3 #
4 4 # This program is free software; you can redistribute it and/or
5 5 # modify it under the terms of the GNU General Public License
6 6 # as published by the Free Software Foundation; either version 2
7 7 # of the License, or (at your option) any later version.
8 8 #
9 9 # This program is distributed in the hope that it will be useful,
10 10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 12 # GNU General Public License for more details.
13 13 #
14 14 # You should have received a copy of the GNU General Public License
15 15 # along with this program; if not, write to the Free Software
16 16 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17 17
18 18 require "digest/md5"
19 19 require "fileutils"
20 20
21 21 class Attachment < ActiveRecord::Base
22 22 belongs_to :container, :polymorphic => true
23 23 belongs_to :author, :class_name => "User"
24 24
25 25 validates_presence_of :filename, :author
26 26 validates_length_of :filename, :maximum => 255
27 27 validates_length_of :disk_filename, :maximum => 255
28 28 validates_length_of :description, :maximum => 255
29 29 validate :validate_max_file_size, :validate_file_extension
30 30 attr_protected :id
31 31
32 32 acts_as_event :title => :filename,
33 33 :url => Proc.new {|o| {:controller => 'attachments', :action => 'download', :id => o.id, :filename => o.filename}}
34 34
35 35 acts_as_activity_provider :type => 'files',
36 36 :permission => :view_files,
37 37 :author_key => :author_id,
38 38 :scope => select("#{Attachment.table_name}.*").
39 39 joins("LEFT JOIN #{Version.table_name} ON #{Attachment.table_name}.container_type='Version' AND #{Version.table_name}.id = #{Attachment.table_name}.container_id " +
40 40 "LEFT JOIN #{Project.table_name} ON #{Version.table_name}.project_id = #{Project.table_name}.id OR ( #{Attachment.table_name}.container_type='Project' AND #{Attachment.table_name}.container_id = #{Project.table_name}.id )")
41 41
42 42 acts_as_activity_provider :type => 'documents',
43 43 :permission => :view_documents,
44 44 :author_key => :author_id,
45 45 :scope => select("#{Attachment.table_name}.*").
46 46 joins("LEFT JOIN #{Document.table_name} ON #{Attachment.table_name}.container_type='Document' AND #{Document.table_name}.id = #{Attachment.table_name}.container_id " +
47 47 "LEFT JOIN #{Project.table_name} ON #{Document.table_name}.project_id = #{Project.table_name}.id")
48 48
49 49 cattr_accessor :storage_path
50 50 @@storage_path = Redmine::Configuration['attachments_storage_path'] || File.join(Rails.root, "files")
51 51
52 52 cattr_accessor :thumbnails_storage_path
53 53 @@thumbnails_storage_path = File.join(Rails.root, "tmp", "thumbnails")
54 54
55 55 before_create :files_to_final_location
56 56 after_rollback :delete_from_disk, :on => :create
57 57 after_commit :delete_from_disk, :on => :destroy
58 58
59 59 # Returns an unsaved copy of the attachment
60 60 def copy(attributes=nil)
61 61 copy = self.class.new
62 62 copy.attributes = self.attributes.dup.except("id", "downloads")
63 63 copy.attributes = attributes if attributes
64 64 copy
65 65 end
66 66
67 67 def validate_max_file_size
68 68 if @temp_file && self.filesize > Setting.attachment_max_size.to_i.kilobytes
69 69 errors.add(:base, l(:error_attachment_too_big, :max_size => Setting.attachment_max_size.to_i.kilobytes))
70 70 end
71 71 end
72 72
73 73 def validate_file_extension
74 74 if @temp_file
75 75 extension = File.extname(filename)
76 76 unless self.class.valid_extension?(extension)
77 77 errors.add(:base, l(:error_attachment_extension_not_allowed, :extension => extension))
78 78 end
79 79 end
80 80 end
81 81
82 82 def file=(incoming_file)
83 83 unless incoming_file.nil?
84 84 @temp_file = incoming_file
85 85 if @temp_file.size > 0
86 86 if @temp_file.respond_to?(:original_filename)
87 87 self.filename = @temp_file.original_filename
88 88 self.filename.force_encoding("UTF-8")
89 89 end
90 90 if @temp_file.respond_to?(:content_type)
91 91 self.content_type = @temp_file.content_type.to_s.chomp
92 92 end
93 93 self.filesize = @temp_file.size
94 94 end
95 95 end
96 96 end
97 97
98 98 def file
99 99 nil
100 100 end
101 101
102 102 def filename=(arg)
103 103 write_attribute :filename, sanitize_filename(arg.to_s)
104 104 filename
105 105 end
106 106
107 107 # Copies the temporary file to its final location
108 108 # and computes its MD5 hash
109 109 def files_to_final_location
110 110 if @temp_file && (@temp_file.size > 0)
111 111 self.disk_directory = target_directory
112 112 self.disk_filename = Attachment.disk_filename(filename, disk_directory)
113 113 logger.info("Saving attachment '#{self.diskfile}' (#{@temp_file.size} bytes)") if logger
114 114 path = File.dirname(diskfile)
115 115 unless File.directory?(path)
116 116 FileUtils.mkdir_p(path)
117 117 end
118 118 md5 = Digest::MD5.new
119 119 File.open(diskfile, "wb") do |f|
120 120 if @temp_file.respond_to?(:read)
121 121 buffer = ""
122 122 while (buffer = @temp_file.read(8192))
123 123 f.write(buffer)
124 124 md5.update(buffer)
125 125 end
126 126 else
127 127 f.write(@temp_file)
128 128 md5.update(@temp_file)
129 129 end
130 130 end
131 131 self.digest = md5.hexdigest
132 132 end
133 133 @temp_file = nil
134 134
135 135 if content_type.blank? && filename.present?
136 136 self.content_type = Redmine::MimeType.of(filename)
137 137 end
138 138 # Don't save the content type if it's longer than the authorized length
139 139 if self.content_type && self.content_type.length > 255
140 140 self.content_type = nil
141 141 end
142 142 end
143 143
144 144 # Deletes the file from the file system if it's not referenced by other attachments
145 145 def delete_from_disk
146 146 if Attachment.where("disk_filename = ? AND id <> ?", disk_filename, id).empty?
147 147 delete_from_disk!
148 148 end
149 149 end
150 150
151 151 # Returns file's location on disk
152 152 def diskfile
153 153 File.join(self.class.storage_path, disk_directory.to_s, disk_filename.to_s)
154 154 end
155 155
156 156 def title
157 157 title = filename.to_s
158 158 if description.present?
159 159 title << " (#{description})"
160 160 end
161 161 title
162 162 end
163 163
164 164 def increment_download
165 165 increment!(:downloads)
166 166 end
167 167
168 168 def project
169 169 container.try(:project)
170 170 end
171 171
172 172 def visible?(user=User.current)
173 173 if container_id
174 174 container && container.attachments_visible?(user)
175 175 else
176 176 author == user
177 177 end
178 178 end
179 179
180 180 def editable?(user=User.current)
181 181 if container_id
182 182 container && container.attachments_editable?(user)
183 183 else
184 184 author == user
185 185 end
186 186 end
187 187
188 188 def deletable?(user=User.current)
189 189 if container_id
190 190 container && container.attachments_deletable?(user)
191 191 else
192 192 author == user
193 193 end
194 194 end
195 195
196 196 def image?
197 197 !!(self.filename =~ /\.(bmp|gif|jpg|jpe|jpeg|png)$/i)
198 198 end
199 199
200 200 def thumbnailable?
201 201 image?
202 202 end
203 203
204 204 # Returns the full path the attachment thumbnail, or nil
205 205 # if the thumbnail cannot be generated.
206 206 def thumbnail(options={})
207 207 if thumbnailable? && readable?
208 208 size = options[:size].to_i
209 209 if size > 0
210 210 # Limit the number of thumbnails per image
211 211 size = (size / 50) * 50
212 212 # Maximum thumbnail size
213 213 size = 800 if size > 800
214 214 else
215 215 size = Setting.thumbnails_size.to_i
216 216 end
217 217 size = 100 unless size > 0
218 218 target = File.join(self.class.thumbnails_storage_path, "#{id}_#{digest}_#{size}.thumb")
219 219
220 220 begin
221 221 Redmine::Thumbnail.generate(self.diskfile, target, size)
222 222 rescue => e
223 223 logger.error "An error occured while generating thumbnail for #{disk_filename} to #{target}\nException was: #{e.message}" if logger
224 224 return nil
225 225 end
226 226 end
227 227 end
228 228
229 229 # Deletes all thumbnails
230 230 def self.clear_thumbnails
231 231 Dir.glob(File.join(thumbnails_storage_path, "*.thumb")).each do |file|
232 232 File.delete file
233 233 end
234 234 end
235 235
236 236 def is_text?
237 237 Redmine::MimeType.is_type?('text', filename)
238 238 end
239 239
240 def is_image?
241 Redmine::MimeType.is_type?('image', filename)
242 end
243
240 244 def is_diff?
241 245 self.filename =~ /\.(patch|diff)$/i
242 246 end
243 247
244 248 # Returns true if the file is readable
245 249 def readable?
246 250 File.readable?(diskfile)
247 251 end
248 252
249 253 # Returns the attachment token
250 254 def token
251 255 "#{id}.#{digest}"
252 256 end
253 257
254 258 # Finds an attachment that matches the given token and that has no container
255 259 def self.find_by_token(token)
256 260 if token.to_s =~ /^(\d+)\.([0-9a-f]+)$/
257 261 attachment_id, attachment_digest = $1, $2
258 262 attachment = Attachment.where(:id => attachment_id, :digest => attachment_digest).first
259 263 if attachment && attachment.container.nil?
260 264 attachment
261 265 end
262 266 end
263 267 end
264 268
265 269 # Bulk attaches a set of files to an object
266 270 #
267 271 # Returns a Hash of the results:
268 272 # :files => array of the attached files
269 273 # :unsaved => array of the files that could not be attached
270 274 def self.attach_files(obj, attachments)
271 275 result = obj.save_attachments(attachments, User.current)
272 276 obj.attach_saved_attachments
273 277 result
274 278 end
275 279
276 280 # Updates the filename and description of a set of attachments
277 281 # with the given hash of attributes. Returns true if all
278 282 # attachments were updated.
279 283 #
280 284 # Example:
281 285 # Attachment.update_attachments(attachments, {
282 286 # 4 => {:filename => 'foo'},
283 287 # 7 => {:filename => 'bar', :description => 'file description'}
284 288 # })
285 289 #
286 290 def self.update_attachments(attachments, params)
287 291 params = params.transform_keys {|key| key.to_i}
288 292
289 293 saved = true
290 294 transaction do
291 295 attachments.each do |attachment|
292 296 if p = params[attachment.id]
293 297 attachment.filename = p[:filename] if p.key?(:filename)
294 298 attachment.description = p[:description] if p.key?(:description)
295 299 saved &&= attachment.save
296 300 end
297 301 end
298 302 unless saved
299 303 raise ActiveRecord::Rollback
300 304 end
301 305 end
302 306 saved
303 307 end
304 308
305 309 def self.latest_attach(attachments, filename)
306 310 attachments.sort_by(&:created_on).reverse.detect do |att|
307 311 filename.casecmp(att.filename) == 0
308 312 end
309 313 end
310 314
311 315 def self.prune(age=1.day)
312 316 Attachment.where("created_on < ? AND (container_type IS NULL OR container_type = '')", Time.now - age).destroy_all
313 317 end
314 318
315 319 # Moves an existing attachment to its target directory
316 320 def move_to_target_directory!
317 321 return unless !new_record? & readable?
318 322
319 323 src = diskfile
320 324 self.disk_directory = target_directory
321 325 dest = diskfile
322 326
323 327 return if src == dest
324 328
325 329 if !FileUtils.mkdir_p(File.dirname(dest))
326 330 logger.error "Could not create directory #{File.dirname(dest)}" if logger
327 331 return
328 332 end
329 333
330 334 if !FileUtils.mv(src, dest)
331 335 logger.error "Could not move attachment from #{src} to #{dest}" if logger
332 336 return
333 337 end
334 338
335 339 update_column :disk_directory, disk_directory
336 340 end
337 341
338 342 # Moves existing attachments that are stored at the root of the files
339 343 # directory (ie. created before Redmine 2.3) to their target subdirectories
340 344 def self.move_from_root_to_target_directory
341 345 Attachment.where("disk_directory IS NULL OR disk_directory = ''").find_each do |attachment|
342 346 attachment.move_to_target_directory!
343 347 end
344 348 end
345 349
346 350 # Returns true if the extension is allowed, otherwise false
347 351 def self.valid_extension?(extension)
348 352 extension = extension.downcase.sub(/\A\.+/, '')
349 353
350 354 denied, allowed = [:attachment_extensions_denied, :attachment_extensions_allowed].map do |setting|
351 355 Setting.send(setting).to_s.split(",").map {|s| s.strip.downcase.sub(/\A\.+/, '')}.reject(&:blank?)
352 356 end
353 357 if denied.present? && denied.include?(extension)
354 358 return false
355 359 end
356 360 unless allowed.blank? || allowed.include?(extension)
357 361 return false
358 362 end
359 363 true
360 364 end
361 365
362 366 private
363 367
364 368 # Physically deletes the file from the file system
365 369 def delete_from_disk!
366 370 if disk_filename.present? && File.exist?(diskfile)
367 371 File.delete(diskfile)
368 372 end
369 373 end
370 374
371 375 def sanitize_filename(value)
372 376 # get only the filename, not the whole path
373 377 just_filename = value.gsub(/\A.*(\\|\/)/m, '')
374 378
375 379 # Finally, replace invalid characters with underscore
376 380 just_filename.gsub(/[\/\?\%\*\:\|\"\'<>\n\r]+/, '_')
377 381 end
378 382
379 383 # Returns the subdirectory in which the attachment will be saved
380 384 def target_directory
381 385 time = created_on || DateTime.now
382 386 time.strftime("%Y/%m")
383 387 end
384 388
385 389 # Returns an ASCII or hashed filename that do not
386 390 # exists yet in the given subdirectory
387 391 def self.disk_filename(filename, directory=nil)
388 392 timestamp = DateTime.now.strftime("%y%m%d%H%M%S")
389 393 ascii = ''
390 394 if filename =~ %r{^[a-zA-Z0-9_\.\-]*$}
391 395 ascii = filename
392 396 else
393 397 ascii = Digest::MD5.hexdigest(filename)
394 398 # keep the extension if any
395 399 ascii << $1 if filename =~ %r{(\.[a-zA-Z0-9]+)$}
396 400 end
397 401 while File.exist?(File.join(storage_path, directory.to_s, "#{timestamp}_#{ascii}"))
398 402 timestamp.succ!
399 403 end
400 404 "#{timestamp}_#{ascii}"
401 405 end
402 406 end
@@ -1,42 +1,42
1 1 <div class="attachments">
2 2 <div class="contextual">
3 3 <%= link_to(l(:label_edit_attachments),
4 4 container_attachments_edit_path(container),
5 5 :title => l(:label_edit_attachments),
6 6 :class => 'icon-only icon-edit'
7 7 ) if options[:editable] %>
8 8 </div>
9 9 <% for attachment in attachments %>
10 10 <p><%= link_to_attachment attachment, :class => 'icon icon-attachment', :download => true -%>
11 <% if attachment.is_text? %>
11 <% if attachment.is_text? || attachment.is_image? %>
12 12 <%= link_to l(:button_view),
13 13 { :controller => 'attachments', :action => 'show',
14 14 :id => attachment, :filename => attachment.filename },
15 15 :class => 'icon-only icon-magnifier',
16 16 :title => l(:button_view) %>
17 17 <% end %>
18 18 <%= " - #{attachment.description}" unless attachment.description.blank? %>
19 19 <span class="size">(<%= number_to_human_size attachment.filesize %>)</span>
20 20 <% if options[:deletable] %>
21 21 <%= link_to l(:button_delete), attachment_path(attachment),
22 22 :data => {:confirm => l(:text_are_you_sure)},
23 23 :method => :delete,
24 24 :class => 'delete icon-only icon-del',
25 25 :title => l(:button_delete) %>
26 26 <% end %>
27 27 <% if options[:author] %>
28 28 <span class="author"><%= attachment.author %>, <%= format_time(attachment.created_on) %></span>
29 29 <% end %>
30 30 </p>
31 31 <% end %>
32 32 <% if defined?(thumbnails) && thumbnails %>
33 33 <% images = attachments.select(&:thumbnailable?) %>
34 34 <% if images.any? %>
35 35 <div class="thumbnails">
36 36 <% images.each do |attachment| %>
37 37 <div><%= thumbnail_tag(attachment) %></div>
38 38 <% end %>
39 39 </div>
40 40 <% end %>
41 41 <% end %>
42 42 </div>
@@ -1,15 +1,19
1 1 <%= call_hook(:view_repositories_show_contextual, { :repository => @repository, :project => @project }) %>
2 2
3 3 <div class="contextual">
4 4 <%= render :partial => 'navigation' %>
5 5 </div>
6 6
7 7 <h2><%= render :partial => 'breadcrumbs', :locals => { :path => @path, :kind => 'file', :revision => @rev } %></h2>
8 8
9 9 <%= render :partial => 'link_to_functions' %>
10 10
11 <% if Redmine::MimeType.is_type?('image', @path) %>
12 <%= render :partial => 'common/image', :locals => {:path => url_for(params.merge(:action => 'raw')), :alt => @path} %>
13 <% else %>
11 14 <%= render :partial => 'common/file', :locals => {:filename => @path, :content => @content} %>
15 <% end %>
12 16
13 17 <% content_for :header_tags do %>
14 18 <%= stylesheet_link_tag "scm" %>
15 19 <% end %>
@@ -1,107 +1,109
1 1
2 2 table.revision-info td {
3 3 margin: 0px;
4 4 padding: 0px;
5 5 }
6 6
7 7 div.revision-graph { position: absolute; min-width: 1px; }
8 8
9 9 div.changeset-changes ul { margin: 0; padding: 0; }
10 10 div.changeset-changes ul > ul { margin-left: 18px; padding: 0; }
11 11
12 12 li.change {
13 13 list-style-type:none;
14 14 background-image: url(../images/bullet_black.png);
15 15 background-position: 1px 1px;
16 16 background-repeat: no-repeat;
17 17 padding-top: 1px;
18 18 padding-bottom: 1px;
19 19 padding-left: 20px;
20 20 margin: 0;
21 21 }
22 22 li.change.folder { background-image: url(../images/folder_open.png); }
23 23 li.change.folder.change-A { background-image: url(../images/folder_open_add.png); }
24 24 li.change.folder.change-M { background-image: url(../images/folder_open_orange.png); }
25 25 li.change.change-A { background-image: url(../images/bullet_add.png); }
26 26 li.change.change-M { background-image: url(../images/bullet_orange.png); }
27 27 li.change.change-C { background-image: url(../images/bullet_blue.png); }
28 28 li.change.change-R { background-image: url(../images/bullet_purple.png); }
29 29 li.change.change-D { background-image: url(../images/bullet_delete.png); }
30 30
31 31 li.change .copied-from { font-style: italic; color: #999; font-size: 0.9em; }
32 32 li.change .copied-from:before { content: " - "}
33 33
34 34 #changes-legend { float: right; font-size: 0.8em; margin: 0; }
35 35 #changes-legend li { float: left; background-position: 5px 0; }
36 36
37 37 table.filecontent { border: 1px solid #e2e2e2; border-collapse: collapse; width:98%; background-color: #fafafa; }
38 38 table.filecontent tbody {font-family:Consolas, Menlo, "Liberation Mono", Courier, monospace; font-size:12px;}
39 39 table.filecontent th { border: 1px solid #e2e2e2; background-color: #eee; }
40 40 table.filecontent th.filename { background-color: #e4e4d4; text-align: left; padding:5px;}
41 41 table.filecontent tr.spacing th { text-align:center; }
42 42 table.filecontent tr.spacing td { height: 0.4em; background: #EAF2F5;}
43 43 table.filecontent th.line-num {
44 44 border: 1px solid #e2e2e2;
45 45 text-align: right;
46 46 width: 2%;
47 47 padding: 0 3px 0 0;
48 48 color: #999;
49 49 user-select: none;
50 50 -moz-user-select: none;
51 51 -o-user-select: none;
52 52 -ms-user-select: none;
53 53 -webkit-user-select: none;
54 54 font-weight:normal;
55 55 }
56 56 table.filecontent th.line-num a {
57 57 text-decoration: none;
58 58 color: inherit;
59 59 }
60 60 table.filecontent td.line-code {padding: 0 0 0 4px;}
61 61 table.filecontent td.line-code pre {
62 62 margin: 0px;
63 63 white-space: pre-wrap;
64 64 font-family:Consolas, Menlo, "Liberation Mono", Courier, monospace; font-size:12px;
65 65 }
66 66
67 67 table.filecontent tr:target th.line-num { background-color:#E0E0E0; color: #777; }
68 68 table.filecontent tr:target td.line-code { background-color:#DDEEFF; }
69 69
70 img.filecontent.image { max-width: 100%; }
71
70 72 /* 12 different colors for the annonate view */
71 73 table.annotate tr.bloc-0 {background: #FFFFBF;}
72 74 table.annotate tr.bloc-1 {background: #EABFFF;}
73 75 table.annotate tr.bloc-2 {background: #BFFFFF;}
74 76 table.annotate tr.bloc-3 {background: #FFD9BF;}
75 77 table.annotate tr.bloc-4 {background: #E6FFBF;}
76 78 table.annotate tr.bloc-5 {background: #BFCFFF;}
77 79 table.annotate tr.bloc-6 {background: #FFBFEF;}
78 80 table.annotate tr.bloc-7 {background: #FFE6BF;}
79 81 table.annotate tr.bloc-8 {background: #FFE680;}
80 82 table.annotate tr.bloc-9 {background: #AA80FF;}
81 83 table.annotate tr.bloc-10 {background: #FFBFDC;}
82 84 table.annotate tr.bloc-11 {background: #BFE4FF;}
83 85
84 86 table.annotate td.revision {
85 87 padding:0;
86 88 text-align: center;
87 89 width: 2%;
88 90 padding-left: 1em;
89 91 background: inherit;
90 92 }
91 93
92 94 table.annotate td.author {
93 95 padding:0;
94 96 text-align: center;
95 97 border-right: 1px solid #d7d7d7;
96 98 white-space: nowrap;
97 99 padding-left: 1em;
98 100 padding-right: 1em;
99 101 width: 3%;
100 102 background: inherit;
101 103 }
102 104
103 105 table.annotate td.line-code { background-color: #fafafa; }
104 106
105 107 div.action_M { background: #fd8 }
106 108 div.action_D { background: #f88 }
107 109 div.action_A { background: #bfb }
General Comments 0
You need to be logged in to leave comments. Login now