comparison app/helpers/application_helper.rb @ 0:513646585e45

* Import Redmine trunk SVN rev 3859
author Chris Cannam
date Fri, 23 Jul 2010 15:52:44 +0100
parents
children 7c48bad7d85d 1d32c0a0efbf
comparison
equal deleted inserted replaced
-1:000000000000 0:513646585e45
1 # redMine - project management software
2 # Copyright (C) 2006-2007 Jean-Philippe Lang
3 #
4 # This program is free software; you can redistribute it and/or
5 # modify it under the terms of the GNU General Public License
6 # as published by the Free Software Foundation; either version 2
7 # of the License, or (at your option) any later version.
8 #
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU General Public License for more details.
13 #
14 # You should have received a copy of the GNU General Public License
15 # along with this program; if not, write to the Free Software
16 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17
18 require 'forwardable'
19 require 'cgi'
20
21 module ApplicationHelper
22 include Redmine::WikiFormatting::Macros::Definitions
23 include Redmine::I18n
24 include GravatarHelper::PublicMethods
25
26 extend Forwardable
27 def_delegators :wiki_helper, :wikitoolbar_for, :heads_for_wiki_formatter
28
29 # Return true if user is authorized for controller/action, otherwise false
30 def authorize_for(controller, action)
31 User.current.allowed_to?({:controller => controller, :action => action}, @project)
32 end
33
34 # Display a link if user is authorized
35 def link_to_if_authorized(name, options = {}, html_options = nil, *parameters_for_method_reference)
36 link_to(name, options, html_options, *parameters_for_method_reference) if authorize_for(options[:controller] || params[:controller], options[:action])
37 end
38
39 # Display a link to remote if user is authorized
40 def link_to_remote_if_authorized(name, options = {}, html_options = nil)
41 url = options[:url] || {}
42 link_to_remote(name, options, html_options) if authorize_for(url[:controller] || params[:controller], url[:action])
43 end
44
45 # Displays a link to user's account page if active
46 def link_to_user(user, options={})
47 if user.is_a?(User)
48 name = h(user.name(options[:format]))
49 if user.active?
50 link_to name, :controller => 'users', :action => 'show', :id => user
51 else
52 name
53 end
54 else
55 h(user.to_s)
56 end
57 end
58
59 # Displays a link to +issue+ with its subject.
60 # Examples:
61 #
62 # link_to_issue(issue) # => Defect #6: This is the subject
63 # link_to_issue(issue, :truncate => 6) # => Defect #6: This i...
64 # link_to_issue(issue, :subject => false) # => Defect #6
65 # link_to_issue(issue, :project => true) # => Foo - Defect #6
66 #
67 def link_to_issue(issue, options={})
68 title = nil
69 subject = nil
70 if options[:subject] == false
71 title = truncate(issue.subject, :length => 60)
72 else
73 subject = issue.subject
74 if options[:truncate]
75 subject = truncate(subject, :length => options[:truncate])
76 end
77 end
78 s = link_to "#{issue.tracker} ##{issue.id}", {:controller => "issues", :action => "show", :id => issue},
79 :class => issue.css_classes,
80 :title => title
81 s << ": #{h subject}" if subject
82 s = "#{h issue.project} - " + s if options[:project]
83 s
84 end
85
86 # Generates a link to an attachment.
87 # Options:
88 # * :text - Link text (default to attachment filename)
89 # * :download - Force download (default: false)
90 def link_to_attachment(attachment, options={})
91 text = options.delete(:text) || attachment.filename
92 action = options.delete(:download) ? 'download' : 'show'
93
94 link_to(h(text), {:controller => 'attachments', :action => action, :id => attachment, :filename => attachment.filename }, options)
95 end
96
97 # Generates a link to a SCM revision
98 # Options:
99 # * :text - Link text (default to the formatted revision)
100 def link_to_revision(revision, project, options={})
101 text = options.delete(:text) || format_revision(revision)
102
103 link_to(text, {:controller => 'repositories', :action => 'revision', :id => project, :rev => revision}, :title => l(:label_revision_id, revision))
104 end
105
106 def toggle_link(name, id, options={})
107 onclick = "Element.toggle('#{id}'); "
108 onclick << (options[:focus] ? "Form.Element.focus('#{options[:focus]}'); " : "this.blur(); ")
109 onclick << "return false;"
110 link_to(name, "#", :onclick => onclick)
111 end
112
113 def image_to_function(name, function, html_options = {})
114 html_options.symbolize_keys!
115 tag(:input, html_options.merge({
116 :type => "image", :src => image_path(name),
117 :onclick => (html_options[:onclick] ? "#{html_options[:onclick]}; " : "") + "#{function};"
118 }))
119 end
120
121 def prompt_to_remote(name, text, param, url, html_options = {})
122 html_options[:onclick] = "promptToRemote('#{text}', '#{param}', '#{url_for(url)}'); return false;"
123 link_to name, {}, html_options
124 end
125
126 def format_activity_title(text)
127 h(truncate_single_line(text, :length => 100))
128 end
129
130 def format_activity_day(date)
131 date == Date.today ? l(:label_today).titleize : format_date(date)
132 end
133
134 def format_activity_description(text)
135 h(truncate(text.to_s, :length => 120).gsub(%r{[\r\n]*<(pre|code)>.*$}m, '...')).gsub(/[\r\n]+/, "<br />")
136 end
137
138 def format_version_name(version)
139 if version.project == @project
140 h(version)
141 else
142 h("#{version.project} - #{version}")
143 end
144 end
145
146 def due_date_distance_in_words(date)
147 if date
148 l((date < Date.today ? :label_roadmap_overdue : :label_roadmap_due_in), distance_of_date_in_words(Date.today, date))
149 end
150 end
151
152 def render_page_hierarchy(pages, node=nil)
153 content = ''
154 if pages[node]
155 content << "<ul class=\"pages-hierarchy\">\n"
156 pages[node].each do |page|
157 content << "<li>"
158 content << link_to(h(page.pretty_title), {:controller => 'wiki', :action => 'index', :id => page.project, :page => page.title},
159 :title => (page.respond_to?(:updated_on) ? l(:label_updated_time, distance_of_time_in_words(Time.now, page.updated_on)) : nil))
160 content << "\n" + render_page_hierarchy(pages, page.id) if pages[page.id]
161 content << "</li>\n"
162 end
163 content << "</ul>\n"
164 end
165 content
166 end
167
168 # Renders flash messages
169 def render_flash_messages
170 s = ''
171 flash.each do |k,v|
172 s << content_tag('div', v, :class => "flash #{k}")
173 end
174 s
175 end
176
177 # Renders tabs and their content
178 def render_tabs(tabs)
179 if tabs.any?
180 render :partial => 'common/tabs', :locals => {:tabs => tabs}
181 else
182 content_tag 'p', l(:label_no_data), :class => "nodata"
183 end
184 end
185
186 # Renders the project quick-jump box
187 def render_project_jump_box
188 # Retrieve them now to avoid a COUNT query
189 projects = User.current.projects.all
190 if projects.any?
191 s = '<select onchange="if (this.value != \'\') { window.location = this.value; }">' +
192 "<option value=''>#{ l(:label_jump_to_a_project) }</option>" +
193 '<option value="" disabled="disabled">---</option>'
194 s << project_tree_options_for_select(projects, :selected => @project) do |p|
195 { :value => url_for(:controller => 'projects', :action => 'show', :id => p, :jump => current_menu_item) }
196 end
197 s << '</select>'
198 s
199 end
200 end
201
202 def project_tree_options_for_select(projects, options = {})
203 s = ''
204 project_tree(projects) do |project, level|
205 name_prefix = (level > 0 ? ('&nbsp;' * 2 * level + '&#187; ') : '')
206 tag_options = {:value => project.id}
207 if project == options[:selected] || (options[:selected].respond_to?(:include?) && options[:selected].include?(project))
208 tag_options[:selected] = 'selected'
209 else
210 tag_options[:selected] = nil
211 end
212 tag_options.merge!(yield(project)) if block_given?
213 s << content_tag('option', name_prefix + h(project), tag_options)
214 end
215 s
216 end
217
218 # Yields the given block for each project with its level in the tree
219 def project_tree(projects, &block)
220 ancestors = []
221 projects.sort_by(&:lft).each do |project|
222 while (ancestors.any? && !project.is_descendant_of?(ancestors.last))
223 ancestors.pop
224 end
225 yield project, ancestors.size
226 ancestors << project
227 end
228 end
229
230 def project_nested_ul(projects, &block)
231 s = ''
232 if projects.any?
233 ancestors = []
234 projects.sort_by(&:lft).each do |project|
235 if (ancestors.empty? || project.is_descendant_of?(ancestors.last))
236 s << "<ul>\n"
237 else
238 ancestors.pop
239 s << "</li>"
240 while (ancestors.any? && !project.is_descendant_of?(ancestors.last))
241 ancestors.pop
242 s << "</ul></li>\n"
243 end
244 end
245 s << "<li>"
246 s << yield(project).to_s
247 ancestors << project
248 end
249 s << ("</li></ul>\n" * ancestors.size)
250 end
251 s
252 end
253
254 def principals_check_box_tags(name, principals)
255 s = ''
256 principals.sort.each do |principal|
257 s << "<label>#{ check_box_tag name, principal.id, false } #{h principal}</label>\n"
258 end
259 s
260 end
261
262 # Truncates and returns the string as a single line
263 def truncate_single_line(string, *args)
264 truncate(string.to_s, *args).gsub(%r{[\r\n]+}m, ' ')
265 end
266
267 # Truncates at line break after 250 characters or options[:length]
268 def truncate_lines(string, options={})
269 length = options[:length] || 250
270 if string.to_s =~ /\A(.{#{length}}.*?)$/m
271 "#{$1}..."
272 else
273 string
274 end
275 end
276
277 def html_hours(text)
278 text.gsub(%r{(\d+)\.(\d+)}, '<span class="hours hours-int">\1</span><span class="hours hours-dec">.\2</span>')
279 end
280
281 def authoring(created, author, options={})
282 l(options[:label] || :label_added_time_by, :author => link_to_user(author), :age => time_tag(created))
283 end
284
285 def time_tag(time)
286 text = distance_of_time_in_words(Time.now, time)
287 if @project
288 link_to(text, {:controller => 'projects', :action => 'activity', :id => @project, :from => time.to_date}, :title => format_time(time))
289 else
290 content_tag('acronym', text, :title => format_time(time))
291 end
292 end
293
294 def syntax_highlight(name, content)
295 Redmine::SyntaxHighlighting.highlight_by_filename(content, name)
296 end
297
298 def to_path_param(path)
299 path.to_s.split(%r{[/\\]}).select {|p| !p.blank?}
300 end
301
302 def pagination_links_full(paginator, count=nil, options={})
303 page_param = options.delete(:page_param) || :page
304 per_page_links = options.delete(:per_page_links)
305 url_param = params.dup
306 # don't reuse query params if filters are present
307 url_param.merge!(:fields => nil, :values => nil, :operators => nil) if url_param.delete(:set_filter)
308
309 html = ''
310 if paginator.current.previous
311 html << link_to_remote_content_update('&#171; ' + l(:label_previous), url_param.merge(page_param => paginator.current.previous)) + ' '
312 end
313
314 html << (pagination_links_each(paginator, options) do |n|
315 link_to_remote_content_update(n.to_s, url_param.merge(page_param => n))
316 end || '')
317
318 if paginator.current.next
319 html << ' ' + link_to_remote_content_update((l(:label_next) + ' &#187;'), url_param.merge(page_param => paginator.current.next))
320 end
321
322 unless count.nil?
323 html << " (#{paginator.current.first_item}-#{paginator.current.last_item}/#{count})"
324 if per_page_links != false && links = per_page_links(paginator.items_per_page)
325 html << " | #{links}"
326 end
327 end
328
329 html
330 end
331
332 def per_page_links(selected=nil)
333 url_param = params.dup
334 url_param.clear if url_param.has_key?(:set_filter)
335
336 links = Setting.per_page_options_array.collect do |n|
337 n == selected ? n : link_to_remote(n, {:update => "content",
338 :url => params.dup.merge(:per_page => n),
339 :method => :get},
340 {:href => url_for(url_param.merge(:per_page => n))})
341 end
342 links.size > 1 ? l(:label_display_per_page, links.join(', ')) : nil
343 end
344
345 def reorder_links(name, url)
346 link_to(image_tag('2uparrow.png', :alt => l(:label_sort_highest)), url.merge({"#{name}[move_to]" => 'highest'}), :method => :post, :title => l(:label_sort_highest)) +
347 link_to(image_tag('1uparrow.png', :alt => l(:label_sort_higher)), url.merge({"#{name}[move_to]" => 'higher'}), :method => :post, :title => l(:label_sort_higher)) +
348 link_to(image_tag('1downarrow.png', :alt => l(:label_sort_lower)), url.merge({"#{name}[move_to]" => 'lower'}), :method => :post, :title => l(:label_sort_lower)) +
349 link_to(image_tag('2downarrow.png', :alt => l(:label_sort_lowest)), url.merge({"#{name}[move_to]" => 'lowest'}), :method => :post, :title => l(:label_sort_lowest))
350 end
351
352 def breadcrumb(*args)
353 elements = args.flatten
354 elements.any? ? content_tag('p', args.join(' &#187; ') + ' &#187; ', :class => 'breadcrumb') : nil
355 end
356
357 def other_formats_links(&block)
358 concat('<p class="other-formats">' + l(:label_export_to))
359 yield Redmine::Views::OtherFormatsBuilder.new(self)
360 concat('</p>')
361 end
362
363 def page_header_title
364 if @project.nil? || @project.new_record?
365 h(Setting.app_title)
366 else
367 b = []
368 ancestors = (@project.root? ? [] : @project.ancestors.visible)
369 if ancestors.any?
370 root = ancestors.shift
371 b << link_to(h(root), {:controller => 'projects', :action => 'show', :id => root, :jump => current_menu_item}, :class => 'root')
372 if ancestors.size > 2
373 b << '&#8230;'
374 ancestors = ancestors[-2, 2]
375 end
376 b += ancestors.collect {|p| link_to(h(p), {:controller => 'projects', :action => 'show', :id => p, :jump => current_menu_item}, :class => 'ancestor') }
377 end
378 b << h(@project)
379 b.join(' &#187; ')
380 end
381 end
382
383 def html_title(*args)
384 if args.empty?
385 title = []
386 title << @project.name if @project
387 title += @html_title if @html_title
388 title << Setting.app_title
389 title.select {|t| !t.blank? }.join(' - ')
390 else
391 @html_title ||= []
392 @html_title += args
393 end
394 end
395
396 def accesskey(s)
397 Redmine::AccessKeys.key_for s
398 end
399
400 # Formats text according to system settings.
401 # 2 ways to call this method:
402 # * with a String: textilizable(text, options)
403 # * with an object and one of its attribute: textilizable(issue, :description, options)
404 def textilizable(*args)
405 options = args.last.is_a?(Hash) ? args.pop : {}
406 case args.size
407 when 1
408 obj = options[:object]
409 text = args.shift
410 when 2
411 obj = args.shift
412 attr = args.shift
413 text = obj.send(attr).to_s
414 else
415 raise ArgumentError, 'invalid arguments to textilizable'
416 end
417 return '' if text.blank?
418 project = options[:project] || @project || (obj && obj.respond_to?(:project) ? obj.project : nil)
419 only_path = options.delete(:only_path) == false ? false : true
420
421 text = Redmine::WikiFormatting.to_html(Setting.text_formatting, text, :object => obj, :attribute => attr) { |macro, args| exec_macro(macro, obj, args) }
422
423 parse_non_pre_blocks(text) do |text|
424 [:parse_inline_attachments, :parse_wiki_links, :parse_redmine_links].each do |method_name|
425 send method_name, text, project, obj, attr, only_path, options
426 end
427 end
428 end
429
430 def parse_non_pre_blocks(text)
431 s = StringScanner.new(text)
432 tags = []
433 parsed = ''
434 while !s.eos?
435 s.scan(/(.*?)(<(\/)?(pre|code)(.*?)>|\z)/im)
436 text, full_tag, closing, tag = s[1], s[2], s[3], s[4]
437 if tags.empty?
438 yield text
439 end
440 parsed << text
441 if tag
442 if closing
443 if tags.last == tag.downcase
444 tags.pop
445 end
446 else
447 tags << tag.downcase
448 end
449 parsed << full_tag
450 end
451 end
452 # Close any non closing tags
453 while tag = tags.pop
454 parsed << "</#{tag}>"
455 end
456 parsed
457 end
458
459 def parse_inline_attachments(text, project, obj, attr, only_path, options)
460 # when using an image link, try to use an attachment, if possible
461 if options[:attachments] || (obj && obj.respond_to?(:attachments))
462 attachments = nil
463 text.gsub!(/src="([^\/"]+\.(bmp|gif|jpg|jpeg|png))"(\s+alt="([^"]*)")?/i) do |m|
464 filename, ext, alt, alttext = $1.downcase, $2, $3, $4
465 attachments ||= (options[:attachments] || obj.attachments).sort_by(&:created_on).reverse
466 # search for the picture in attachments
467 if found = attachments.detect { |att| att.filename.downcase == filename }
468 image_url = url_for :only_path => only_path, :controller => 'attachments', :action => 'download', :id => found
469 desc = found.description.to_s.gsub('"', '')
470 if !desc.blank? && alttext.blank?
471 alt = " title=\"#{desc}\" alt=\"#{desc}\""
472 end
473 "src=\"#{image_url}\"#{alt}"
474 else
475 m
476 end
477 end
478 end
479 end
480
481 # Wiki links
482 #
483 # Examples:
484 # [[mypage]]
485 # [[mypage|mytext]]
486 # wiki links can refer other project wikis, using project name or identifier:
487 # [[project:]] -> wiki starting page
488 # [[project:|mytext]]
489 # [[project:mypage]]
490 # [[project:mypage|mytext]]
491 def parse_wiki_links(text, project, obj, attr, only_path, options)
492 text.gsub!(/(!)?(\[\[([^\]\n\|]+)(\|([^\]\n\|]+))?\]\])/) do |m|
493 link_project = project
494 esc, all, page, title = $1, $2, $3, $5
495 if esc.nil?
496 if page =~ /^([^\:]+)\:(.*)$/
497 link_project = Project.find_by_name($1) || Project.find_by_identifier($1)
498 page = $2
499 title ||= $1 if page.blank?
500 end
501
502 if link_project && link_project.wiki
503 # extract anchor
504 anchor = nil
505 if page =~ /^(.+?)\#(.+)$/
506 page, anchor = $1, $2
507 end
508 # check if page exists
509 wiki_page = link_project.wiki.find_page(page)
510 url = case options[:wiki_links]
511 when :local; "#{title}.html"
512 when :anchor; "##{title}" # used for single-file wiki export
513 else
514 url_for(:only_path => only_path, :controller => 'wiki', :action => 'index', :id => link_project, :page => Wiki.titleize(page), :anchor => anchor)
515 end
516 link_to((title || page), url, :class => ('wiki-page' + (wiki_page ? '' : ' new')))
517 else
518 # project or wiki doesn't exist
519 all
520 end
521 else
522 all
523 end
524 end
525 end
526
527 # Redmine links
528 #
529 # Examples:
530 # Issues:
531 # #52 -> Link to issue #52
532 # Changesets:
533 # r52 -> Link to revision 52
534 # commit:a85130f -> Link to scmid starting with a85130f
535 # Documents:
536 # document#17 -> Link to document with id 17
537 # document:Greetings -> Link to the document with title "Greetings"
538 # document:"Some document" -> Link to the document with title "Some document"
539 # Versions:
540 # version#3 -> Link to version with id 3
541 # version:1.0.0 -> Link to version named "1.0.0"
542 # version:"1.0 beta 2" -> Link to version named "1.0 beta 2"
543 # Attachments:
544 # attachment:file.zip -> Link to the attachment of the current object named file.zip
545 # Source files:
546 # source:some/file -> Link to the file located at /some/file in the project's repository
547 # source:some/file@52 -> Link to the file's revision 52
548 # source:some/file#L120 -> Link to line 120 of the file
549 # source:some/file@52#L120 -> Link to line 120 of the file's revision 52
550 # export:some/file -> Force the download of the file
551 # Forum messages:
552 # message#1218 -> Link to message with id 1218
553 def parse_redmine_links(text, project, obj, attr, only_path, options)
554 text.gsub!(%r{([\s\(,\-\[\>]|^)(!)?(attachment|document|version|commit|source|export|message|project)?((#|r)(\d+)|(:)([^"\s<>][^\s<>]*?|"[^"]+?"))(?=(?=[[:punct:]]\W)|,|\s|\]|<|$)}) do |m|
555 leading, esc, prefix, sep, identifier = $1, $2, $3, $5 || $7, $6 || $8
556 link = nil
557 if esc.nil?
558 if prefix.nil? && sep == 'r'
559 if project && (changeset = project.changesets.find_by_revision(identifier))
560 link = link_to("r#{identifier}", {:only_path => only_path, :controller => 'repositories', :action => 'revision', :id => project, :rev => changeset.revision},
561 :class => 'changeset',
562 :title => truncate_single_line(changeset.comments, :length => 100))
563 end
564 elsif sep == '#'
565 oid = identifier.to_i
566 case prefix
567 when nil
568 if issue = Issue.visible.find_by_id(oid, :include => :status)
569 link = link_to("##{oid}", {:only_path => only_path, :controller => 'issues', :action => 'show', :id => oid},
570 :class => issue.css_classes,
571 :title => "#{truncate(issue.subject, :length => 100)} (#{issue.status.name})")
572 end
573 when 'document'
574 if document = Document.find_by_id(oid, :include => [:project], :conditions => Project.visible_by(User.current))
575 link = link_to h(document.title), {:only_path => only_path, :controller => 'documents', :action => 'show', :id => document},
576 :class => 'document'
577 end
578 when 'version'
579 if version = Version.find_by_id(oid, :include => [:project], :conditions => Project.visible_by(User.current))
580 link = link_to h(version.name), {:only_path => only_path, :controller => 'versions', :action => 'show', :id => version},
581 :class => 'version'
582 end
583 when 'message'
584 if message = Message.find_by_id(oid, :include => [:parent, {:board => :project}], :conditions => Project.visible_by(User.current))
585 link = link_to h(truncate(message.subject, :length => 60)), {:only_path => only_path,
586 :controller => 'messages',
587 :action => 'show',
588 :board_id => message.board,
589 :id => message.root,
590 :anchor => (message.parent ? "message-#{message.id}" : nil)},
591 :class => 'message'
592 end
593 when 'project'
594 if p = Project.visible.find_by_id(oid)
595 link = link_to h(p.name), {:only_path => only_path, :controller => 'projects', :action => 'show', :id => p},
596 :class => 'project'
597 end
598 end
599 elsif sep == ':'
600 # removes the double quotes if any
601 name = identifier.gsub(%r{^"(.*)"$}, "\\1")
602 case prefix
603 when 'document'
604 if project && document = project.documents.find_by_title(name)
605 link = link_to h(document.title), {:only_path => only_path, :controller => 'documents', :action => 'show', :id => document},
606 :class => 'document'
607 end
608 when 'version'
609 if project && version = project.versions.find_by_name(name)
610 link = link_to h(version.name), {:only_path => only_path, :controller => 'versions', :action => 'show', :id => version},
611 :class => 'version'
612 end
613 when 'commit'
614 if project && (changeset = project.changesets.find(:first, :conditions => ["scmid LIKE ?", "#{name}%"]))
615 link = link_to h("#{name}"), {:only_path => only_path, :controller => 'repositories', :action => 'revision', :id => project, :rev => changeset.revision},
616 :class => 'changeset',
617 :title => truncate_single_line(changeset.comments, :length => 100)
618 end
619 when 'source', 'export'
620 if project && project.repository
621 name =~ %r{^[/\\]*(.*?)(@([0-9a-f]+))?(#(L\d+))?$}
622 path, rev, anchor = $1, $3, $5
623 link = link_to h("#{prefix}:#{name}"), {:controller => 'repositories', :action => 'entry', :id => project,
624 :path => to_path_param(path),
625 :rev => rev,
626 :anchor => anchor,
627 :format => (prefix == 'export' ? 'raw' : nil)},
628 :class => (prefix == 'export' ? 'source download' : 'source')
629 end
630 when 'attachment'
631 attachments = options[:attachments] || (obj && obj.respond_to?(:attachments) ? obj.attachments : nil)
632 if attachments && attachment = attachments.detect {|a| a.filename == name }
633 link = link_to h(attachment.filename), {:only_path => only_path, :controller => 'attachments', :action => 'download', :id => attachment},
634 :class => 'attachment'
635 end
636 when 'project'
637 if p = Project.visible.find(:first, :conditions => ["identifier = :s OR LOWER(name) = :s", {:s => name.downcase}])
638 link = link_to h(p.name), {:only_path => only_path, :controller => 'projects', :action => 'show', :id => p},
639 :class => 'project'
640 end
641 end
642 end
643 end
644 leading + (link || "#{prefix}#{sep}#{identifier}")
645 end
646 end
647
648 # Same as Rails' simple_format helper without using paragraphs
649 def simple_format_without_paragraph(text)
650 text.to_s.
651 gsub(/\r\n?/, "\n"). # \r\n and \r -> \n
652 gsub(/\n\n+/, "<br /><br />"). # 2+ newline -> 2 br
653 gsub(/([^\n]\n)(?=[^\n])/, '\1<br />') # 1 newline -> br
654 end
655
656 def lang_options_for_select(blank=true)
657 (blank ? [["(auto)", ""]] : []) +
658 valid_languages.collect{|lang| [ ll(lang.to_s, :general_lang_name), lang.to_s]}.sort{|x,y| x.last <=> y.last }
659 end
660
661 def label_tag_for(name, option_tags = nil, options = {})
662 label_text = l(("field_"+field.to_s.gsub(/\_id$/, "")).to_sym) + (options.delete(:required) ? @template.content_tag("span", " *", :class => "required"): "")
663 content_tag("label", label_text)
664 end
665
666 def labelled_tabular_form_for(name, object, options, &proc)
667 options[:html] ||= {}
668 options[:html][:class] = 'tabular' unless options[:html].has_key?(:class)
669 form_for(name, object, options.merge({ :builder => TabularFormBuilder, :lang => current_language}), &proc)
670 end
671
672 def back_url_hidden_field_tag
673 back_url = params[:back_url] || request.env['HTTP_REFERER']
674 back_url = CGI.unescape(back_url.to_s)
675 hidden_field_tag('back_url', CGI.escape(back_url)) unless back_url.blank?
676 end
677
678 def check_all_links(form_name)
679 link_to_function(l(:button_check_all), "checkAll('#{form_name}', true)") +
680 " | " +
681 link_to_function(l(:button_uncheck_all), "checkAll('#{form_name}', false)")
682 end
683
684 def progress_bar(pcts, options={})
685 pcts = [pcts, pcts] unless pcts.is_a?(Array)
686 pcts = pcts.collect(&:round)
687 pcts[1] = pcts[1] - pcts[0]
688 pcts << (100 - pcts[1] - pcts[0])
689 width = options[:width] || '100px;'
690 legend = options[:legend] || ''
691 content_tag('table',
692 content_tag('tr',
693 (pcts[0] > 0 ? content_tag('td', '', :style => "width: #{pcts[0]}%;", :class => 'closed') : '') +
694 (pcts[1] > 0 ? content_tag('td', '', :style => "width: #{pcts[1]}%;", :class => 'done') : '') +
695 (pcts[2] > 0 ? content_tag('td', '', :style => "width: #{pcts[2]}%;", :class => 'todo') : '')
696 ), :class => 'progress', :style => "width: #{width};") +
697 content_tag('p', legend, :class => 'pourcent')
698 end
699
700 def checked_image(checked=true)
701 if checked
702 image_tag 'toggle_check.png'
703 end
704 end
705
706 def context_menu(url)
707 unless @context_menu_included
708 content_for :header_tags do
709 javascript_include_tag('context_menu') +
710 stylesheet_link_tag('context_menu')
711 end
712 @context_menu_included = true
713 end
714 javascript_tag "new ContextMenu('#{ url_for(url) }')"
715 end
716
717 def context_menu_link(name, url, options={})
718 options[:class] ||= ''
719 if options.delete(:selected)
720 options[:class] << ' icon-checked disabled'
721 options[:disabled] = true
722 end
723 if options.delete(:disabled)
724 options.delete(:method)
725 options.delete(:confirm)
726 options.delete(:onclick)
727 options[:class] << ' disabled'
728 url = '#'
729 end
730 link_to name, url, options
731 end
732
733 def calendar_for(field_id)
734 include_calendar_headers_tags
735 image_tag("calendar.png", {:id => "#{field_id}_trigger",:class => "calendar-trigger"}) +
736 javascript_tag("Calendar.setup({inputField : '#{field_id}', ifFormat : '%Y-%m-%d', button : '#{field_id}_trigger' });")
737 end
738
739 def include_calendar_headers_tags
740 unless @calendar_headers_tags_included
741 @calendar_headers_tags_included = true
742 content_for :header_tags do
743 start_of_week = case Setting.start_of_week.to_i
744 when 1
745 'Calendar._FD = 1;' # Monday
746 when 7
747 'Calendar._FD = 0;' # Sunday
748 else
749 '' # use language
750 end
751
752 javascript_include_tag('calendar/calendar') +
753 javascript_include_tag("calendar/lang/calendar-#{current_language.to_s.downcase}.js") +
754 javascript_tag(start_of_week) +
755 javascript_include_tag('calendar/calendar-setup') +
756 stylesheet_link_tag('calendar')
757 end
758 end
759 end
760
761 def content_for(name, content = nil, &block)
762 @has_content ||= {}
763 @has_content[name] = true
764 super(name, content, &block)
765 end
766
767 def has_content?(name)
768 (@has_content && @has_content[name]) || false
769 end
770
771 # Returns the avatar image tag for the given +user+ if avatars are enabled
772 # +user+ can be a User or a string that will be scanned for an email address (eg. 'joe <joe@foo.bar>')
773 def avatar(user, options = { })
774 if Setting.gravatar_enabled?
775 options.merge!({:ssl => Setting.protocol == 'https', :default => Setting.gravatar_default})
776 email = nil
777 if user.respond_to?(:mail)
778 email = user.mail
779 elsif user.to_s =~ %r{<(.+?)>}
780 email = $1
781 end
782 return gravatar(email.to_s.downcase, options) unless email.blank? rescue nil
783 end
784 end
785
786 private
787
788 def wiki_helper
789 helper = Redmine::WikiFormatting.helper_for(Setting.text_formatting)
790 extend helper
791 return self
792 end
793
794 def link_to_remote_content_update(text, url_params)
795 link_to_remote(text,
796 {:url => url_params, :method => :get, :update => 'content', :complete => 'window.scrollTo(0,0)'},
797 {:href => url_for(:params => url_params)}
798 )
799 end
800
801 end