1 # redMine - project management software
2 # Copyright (C) 2006-2007 Jean-Philippe Lang
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.
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.
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.
19 require 'coderay/helpers/file_type'
23 module ApplicationHelper
24 include Redmine::WikiFormatting::Macros::Definitions
26 include GravatarHelper::PublicMethods
29 def_delegators :wiki_helper, :wikitoolbar_for, :heads_for_wiki_formatter
31 # Return true if user is authorized for controller/action, otherwise false
32 def authorize_for(controller, action)
33 User.current.allowed_to?({:controller => controller, :action => action}, @project)
36 # Display a link if user is authorized
37 def link_to_if_authorized(name, options = {}, html_options = nil, *parameters_for_method_reference)
38 link_to(name, options, html_options, *parameters_for_method_reference) if authorize_for(options[:controller] || params[:controller], options[:action])
41 # Display a link to remote if user is authorized
42 def link_to_remote_if_authorized(name, options = {}, html_options = nil)
43 url = options[:url] || {}
44 link_to_remote(name, options, html_options) if authorize_for(url[:controller] || params[:controller], url[:action])
47 # Displays a link to user's account page if active
48 def link_to_user(user, options={})
50 name = h(user.name(options[:format]))
52 link_to name, :controller => 'users', :action => 'show', :id => user
61 # Displays a link to +issue+ with its subject.
64 # link_to_issue(issue) # => Defect #6: This is the subject
65 # link_to_issue(issue, :truncate => 6) # => Defect #6: This i...
66 # link_to_issue(issue, :subject => false) # => Defect #6
67 # link_to_issue(issue, :project => true) # => Foo - Defect #6
69 def link_to_issue(issue, options={})
72 if options[:subject] == false
73 title = truncate(issue.subject, :length => 60)
75 subject = issue.subject
77 subject = truncate(subject, :length => options[:truncate])
80 s = link_to "#{issue.tracker} ##{issue.id}", {:controller => "issues", :action => "show", :id => issue},
81 :class => issue.css_classes,
83 s << ": #{h subject}" if subject
84 s = "#{h issue.project} - " + s if options[:project]
88 # Generates a link to an attachment.
90 # * :text - Link text (default to attachment filename)
91 # * :download - Force download (default: false)
92 def link_to_attachment(attachment, options={})
93 text = options.delete(:text) || attachment.filename
94 action = options.delete(:download) ? 'download' : 'show'
96 link_to(h(text), {:controller => 'attachments', :action => action, :id => attachment, :filename => attachment.filename }, options)
99 def toggle_link(name, id, options={})
100 onclick = "Element.toggle('#{id}'); "
101 onclick << (options[:focus] ? "Form.Element.focus('#{options[:focus]}'); " : "this.blur(); ")
102 onclick << "return false;"
103 link_to(name, "#", :onclick => onclick)
106 def image_to_function(name, function, html_options = {})
107 html_options.symbolize_keys!
108 tag(:input, html_options.merge({
109 :type => "image", :src => image_path(name),
110 :onclick => (html_options[:onclick] ? "#{html_options[:onclick]}; " : "") + "#{function};"
114 def prompt_to_remote(name, text, param, url, html_options = {})
115 html_options[:onclick] = "promptToRemote('#{text}', '#{param}', '#{url_for(url)}'); return false;"
116 link_to name, {}, html_options
119 def format_activity_title(text)
120 h(truncate_single_line(text, :length => 100))
123 def format_activity_day(date)
124 date == Date.today ? l(:label_today).titleize : format_date(date)
127 def format_activity_description(text)
128 h(truncate(text.to_s, :length => 120).gsub(%r{[\r\n]*<(pre|code)>.*$}m, '...')).gsub(/[\r\n]+/, "<br />")
131 def format_version_name(version)
132 if version.project == @project
135 h("#{version.project} - #{version}")
139 def due_date_distance_in_words(date)
141 l((date < Date.today ? :label_roadmap_overdue : :label_roadmap_due_in), distance_of_date_in_words(Date.today, date))
145 def render_page_hierarchy(pages, node=nil)
148 content << "<ul class=\"pages-hierarchy\">\n"
149 pages[node].each do |page|
151 content << link_to(h(page.pretty_title), {:controller => 'wiki', :action => 'index', :id => page.project, :page => page.title},
152 :title => (page.respond_to?(:updated_on) ? l(:label_updated_time, distance_of_time_in_words(Time.now, page.updated_on)) : nil))
153 content << "\n" + render_page_hierarchy(pages, page.id) if pages[page.id]
161 # Renders flash messages
162 def render_flash_messages
165 s << content_tag('div', v, :class => "flash #{k}")
170 # Renders tabs and their content
171 def render_tabs(tabs)
173 render :partial => 'common/tabs', :locals => {:tabs => tabs}
175 content_tag 'p', l(:label_no_data), :class => "nodata"
179 # Renders the project quick-jump box
180 def render_project_jump_box
181 # Retrieve them now to avoid a COUNT query
182 projects = User.current.projects.all
184 s = '<select onchange="if (this.value != \'\') { window.location = this.value; }">' +
185 "<option value=''>#{ l(:label_jump_to_a_project) }</option>" +
186 '<option value="" disabled="disabled">---</option>'
187 s << project_tree_options_for_select(projects, :selected => @project) do |p|
188 { :value => url_for(:controller => 'projects', :action => 'show', :id => p, :jump => current_menu_item) }
195 def project_tree_options_for_select(projects, options = {})
197 project_tree(projects) do |project, level|
198 name_prefix = (level > 0 ? (' ' * 2 * level + '» ') : '')
199 tag_options = {:value => project.id, :selected => ((project == options[:selected]) ? 'selected' : nil)}
200 tag_options.merge!(yield(project)) if block_given?
201 s << content_tag('option', name_prefix + h(project), tag_options)
206 # Yields the given block for each project with its level in the tree
207 def project_tree(projects, &block)
209 projects.sort_by(&:lft).each do |project|
210 while (ancestors.any? && !project.is_descendant_of?(ancestors.last))
213 yield project, ancestors.size
218 def project_nested_ul(projects, &block)
222 projects.sort_by(&:lft).each do |project|
223 if (ancestors.empty? || project.is_descendant_of?(ancestors.last))
228 while (ancestors.any? && !project.is_descendant_of?(ancestors.last))
234 s << yield(project).to_s
237 s << ("</li></ul>\n" * ancestors.size)
242 def principals_check_box_tags(name, principals)
244 principals.sort.each do |principal|
245 s << "<label>#{ check_box_tag name, principal.id, false } #{h principal}</label>\n"
250 # Truncates and returns the string as a single line
251 def truncate_single_line(string, *args)
252 truncate(string.to_s, *args).gsub(%r{[\r\n]+}m, ' ')
256 text.gsub(%r{(\d+)\.(\d+)}, '<span class="hours hours-int">\1</span><span class="hours hours-dec">.\2</span>')
259 def authoring(created, author, options={})
260 l(options[:label] || :label_added_time_by, :author => link_to_user(author), :age => time_tag(created))
264 text = distance_of_time_in_words(Time.now, time)
266 link_to(text, {:controller => 'projects', :action => 'activity', :id => @project, :from => time.to_date}, :title => format_time(time))
268 content_tag('acronym', text, :title => format_time(time))
272 def syntax_highlight(name, content)
273 type = CodeRay::FileType[name]
274 type ? CodeRay.scan(content, type).html : h(content)
277 def to_path_param(path)
278 path.to_s.split(%r{[/\\]}).select {|p| !p.blank?}
281 def pagination_links_full(paginator, count=nil, options={})
282 page_param = options.delete(:page_param) || :page
283 url_param = params.dup
284 # don't reuse query params if filters are present
285 url_param.merge!(:fields => nil, :values => nil, :operators => nil) if url_param.delete(:set_filter)
288 if paginator.current.previous
289 html << link_to_remote_content_update('« ' + l(:label_previous), url_param.merge(page_param => paginator.current.previous)) + ' '
292 html << (pagination_links_each(paginator, options) do |n|
293 link_to_remote_content_update(n.to_s, url_param.merge(page_param => n))
296 if paginator.current.next
297 html << ' ' + link_to_remote_content_update((l(:label_next) + ' »'), url_param.merge(page_param => paginator.current.next))
302 " (#{paginator.current.first_item}-#{paginator.current.last_item}/#{count})",
303 per_page_links(paginator.items_per_page)
304 ].compact.join(' | ')
310 def per_page_links(selected=nil)
311 url_param = params.dup
312 url_param.clear if url_param.has_key?(:set_filter)
314 links = Setting.per_page_options_array.collect do |n|
315 n == selected ? n : link_to_remote(n, {:update => "content",
316 :url => params.dup.merge(:per_page => n),
318 {:href => url_for(url_param.merge(:per_page => n))})
320 links.size > 1 ? l(:label_display_per_page, links.join(', ')) : nil
323 def reorder_links(name, url)
324 link_to(image_tag('2uparrow.png', :alt => l(:label_sort_highest)), url.merge({"#{name}[move_to]" => 'highest'}), :method => :post, :title => l(:label_sort_highest)) +
325 link_to(image_tag('1uparrow.png', :alt => l(:label_sort_higher)), url.merge({"#{name}[move_to]" => 'higher'}), :method => :post, :title => l(:label_sort_higher)) +
326 link_to(image_tag('1downarrow.png', :alt => l(:label_sort_lower)), url.merge({"#{name}[move_to]" => 'lower'}), :method => :post, :title => l(:label_sort_lower)) +
327 link_to(image_tag('2downarrow.png', :alt => l(:label_sort_lowest)), url.merge({"#{name}[move_to]" => 'lowest'}), :method => :post, :title => l(:label_sort_lowest))
330 def breadcrumb(*args)
331 elements = args.flatten
332 elements.any? ? content_tag('p', args.join(' » ') + ' » ', :class => 'breadcrumb') : nil
335 def other_formats_links(&block)
336 concat('<p class="other-formats">' + l(:label_export_to))
337 yield Redmine::Views::OtherFormatsBuilder.new(self)
341 def page_header_title
342 if @project.nil? || @project.new_record?
346 ancestors = (@project.root? ? [] : @project.ancestors.visible)
348 root = ancestors.shift
349 b << link_to(h(root), {:controller => 'projects', :action => 'show', :id => root, :jump => current_menu_item}, :class => 'root')
350 if ancestors.size > 2
352 ancestors = ancestors[-2, 2]
354 b += ancestors.collect {|p| link_to(h(p), {:controller => 'projects', :action => 'show', :id => p, :jump => current_menu_item}, :class => 'ancestor') }
361 def html_title(*args)
364 title << @project.name if @project
365 title += @html_title if @html_title
366 title << Setting.app_title
367 title.select {|t| !t.blank? }.join(' - ')
375 Redmine::AccessKeys.key_for s
378 # Formats text according to system settings.
379 # 2 ways to call this method:
380 # * with a String: textilizable(text, options)
381 # * with an object and one of its attribute: textilizable(issue, :description, options)
382 def textilizable(*args)
383 options = args.last.is_a?(Hash) ? args.pop : {}
386 obj = options[:object]
390 text = obj.send(args.shift).to_s
392 raise ArgumentError, 'invalid arguments to textilizable'
394 return '' if text.blank?
396 only_path = options.delete(:only_path) == false ? false : true
398 # when using an image link, try to use an attachment, if possible
399 attachments = options[:attachments] || (obj && obj.respond_to?(:attachments) ? obj.attachments : nil)
402 attachments = attachments.sort_by(&:created_on).reverse
403 text = text.gsub(/!((\<|\=|\>)?(\([^\)]+\))?(\[[^\]]+\])?(\{[^\}]+\})?)(\S+\.(bmp|gif|jpg|jpeg|png))!/i) do |m|
405 filename = $6.downcase
406 # search for the picture in attachments
407 if found = attachments.detect { |att| att.filename.downcase == filename }
408 image_url = url_for :only_path => only_path, :controller => 'attachments', :action => 'download', :id => found
409 desc = found.description.to_s.gsub(/^([^\(\)]*).*$/, "\\1")
410 alt = desc.blank? ? nil : "(#{desc})"
411 "!#{style}#{image_url}#{alt}!"
418 text = Redmine::WikiFormatting.to_html(Setting.text_formatting, text) { |macro, args| exec_macro(macro, obj, args) }
420 # different methods for formatting wiki links
421 case options[:wiki_links]
423 # used for local links to html files
424 format_wiki_link = Proc.new {|project, title, anchor| "#{title}.html" }
426 # used for single-file wiki export
427 format_wiki_link = Proc.new {|project, title, anchor| "##{title}" }
429 format_wiki_link = Proc.new {|project, title, anchor| url_for(:only_path => only_path, :controller => 'wiki', :action => 'index', :id => project, :page => title, :anchor => anchor) }
432 project = options[:project] || @project || (obj && obj.respond_to?(:project) ? obj.project : nil)
439 # wiki links can refer other project wikis, using project name or identifier:
440 # [[project:]] -> wiki starting page
441 # [[project:|mytext]]
443 # [[project:mypage|mytext]]
444 text = text.gsub(/(!)?(\[\[([^\]\n\|]+)(\|([^\]\n\|]+))?\]\])/) do |m|
445 link_project = project
446 esc, all, page, title = $1, $2, $3, $5
448 if page =~ /^([^\:]+)\:(.*)$/
449 link_project = Project.find_by_name($1) || Project.find_by_identifier($1)
451 title ||= $1 if page.blank?
454 if link_project && link_project.wiki
457 if page =~ /^(.+?)\#(.+)$/
458 page, anchor = $1, $2
460 # check if page exists
461 wiki_page = link_project.wiki.find_page(page)
462 link_to((title || page), format_wiki_link.call(link_project, Wiki.titleize(page), anchor),
463 :class => ('wiki-page' + (wiki_page ? '' : ' new')))
465 # project or wiki doesn't exist
477 # #52 -> Link to issue #52
479 # r52 -> Link to revision 52
480 # commit:a85130f -> Link to scmid starting with a85130f
482 # document#17 -> Link to document with id 17
483 # document:Greetings -> Link to the document with title "Greetings"
484 # document:"Some document" -> Link to the document with title "Some document"
486 # version#3 -> Link to version with id 3
487 # version:1.0.0 -> Link to version named "1.0.0"
488 # version:"1.0 beta 2" -> Link to version named "1.0 beta 2"
490 # attachment:file.zip -> Link to the attachment of the current object named file.zip
492 # source:some/file -> Link to the file located at /some/file in the project's repository
493 # source:some/file@52 -> Link to the file's revision 52
494 # source:some/file#L120 -> Link to line 120 of the file
495 # source:some/file@52#L120 -> Link to line 120 of the file's revision 52
496 # export:some/file -> Force the download of the file
498 # message#1218 -> Link to message with id 1218
499 text = text.gsub(%r{([\s\(,\-\>]|^)(!)?(attachment|document|version|commit|source|export|message)?((#|r)(\d+)|(:)([^"\s<>][^\s<>]*?|"[^"]+?"))(?=(?=[[:punct:]]\W)|,|\s|<|$)}) do |m|
500 leading, esc, prefix, sep, oid = $1, $2, $3, $5 || $7, $6 || $8
503 if prefix.nil? && sep == 'r'
504 if project && (changeset = project.changesets.find_by_revision(oid))
505 link = link_to("r#{oid}", {:only_path => only_path, :controller => 'repositories', :action => 'revision', :id => project, :rev => oid},
506 :class => 'changeset',
507 :title => truncate_single_line(changeset.comments, :length => 100))
513 if issue = Issue.visible.find_by_id(oid, :include => :status)
514 link = link_to("##{oid}", {:only_path => only_path, :controller => 'issues', :action => 'show', :id => oid},
515 :class => issue.css_classes,
516 :title => "#{truncate(issue.subject, :length => 100)} (#{issue.status.name})")
519 if document = Document.find_by_id(oid, :include => [:project], :conditions => Project.visible_by(User.current))
520 link = link_to h(document.title), {:only_path => only_path, :controller => 'documents', :action => 'show', :id => document},
524 if version = Version.find_by_id(oid, :include => [:project], :conditions => Project.visible_by(User.current))
525 link = link_to h(version.name), {:only_path => only_path, :controller => 'versions', :action => 'show', :id => version},
529 if message = Message.find_by_id(oid, :include => [:parent, {:board => :project}], :conditions => Project.visible_by(User.current))
530 link = link_to h(truncate(message.subject, :length => 60)), {:only_path => only_path,
531 :controller => 'messages',
533 :board_id => message.board,
535 :anchor => (message.parent ? "message-#{message.id}" : nil)},
540 # removes the double quotes if any
541 name = oid.gsub(%r{^"(.*)"$}, "\\1")
544 if project && document = project.documents.find_by_title(name)
545 link = link_to h(document.title), {:only_path => only_path, :controller => 'documents', :action => 'show', :id => document},
549 if project && version = project.versions.find_by_name(name)
550 link = link_to h(version.name), {:only_path => only_path, :controller => 'versions', :action => 'show', :id => version},
554 if project && (changeset = project.changesets.find(:first, :conditions => ["scmid LIKE ?", "#{name}%"]))
555 link = link_to h("#{name}"), {:only_path => only_path, :controller => 'repositories', :action => 'revision', :id => project, :rev => changeset.revision},
556 :class => 'changeset',
557 :title => truncate_single_line(changeset.comments, :length => 100)
559 when 'source', 'export'
560 if project && project.repository
561 name =~ %r{^[/\\]*(.*?)(@([0-9a-f]+))?(#(L\d+))?$}
562 path, rev, anchor = $1, $3, $5
563 link = link_to h("#{prefix}:#{name}"), {:controller => 'repositories', :action => 'entry', :id => project,
564 :path => to_path_param(path),
567 :format => (prefix == 'export' ? 'raw' : nil)},
568 :class => (prefix == 'export' ? 'source download' : 'source')
571 if attachments && attachment = attachments.detect {|a| a.filename == name }
572 link = link_to h(attachment.filename), {:only_path => only_path, :controller => 'attachments', :action => 'download', :id => attachment},
573 :class => 'attachment'
578 leading + (link || "#{prefix}#{sep}#{oid}")
584 # Same as Rails' simple_format helper without using paragraphs
585 def simple_format_without_paragraph(text)
587 gsub(/\r\n?/, "\n"). # \r\n and \r -> \n
588 gsub(/\n\n+/, "<br /><br />"). # 2+ newline -> 2 br
589 gsub(/([^\n]\n)(?=[^\n])/, '\1<br />') # 1 newline -> br
592 def lang_options_for_select(blank=true)
593 (blank ? [["(auto)", ""]] : []) +
594 valid_languages.collect{|lang| [ ll(lang.to_s, :general_lang_name), lang.to_s]}.sort{|x,y| x.last <=> y.last }
597 def label_tag_for(name, option_tags = nil, options = {})
598 label_text = l(("field_"+field.to_s.gsub(/\_id$/, "")).to_sym) + (options.delete(:required) ? @template.content_tag("span", " *", :class => "required"): "")
599 content_tag("label", label_text)
602 def labelled_tabular_form_for(name, object, options, &proc)
603 options[:html] ||= {}
604 options[:html][:class] = 'tabular' unless options[:html].has_key?(:class)
605 form_for(name, object, options.merge({ :builder => TabularFormBuilder, :lang => current_language}), &proc)
608 def back_url_hidden_field_tag
609 back_url = params[:back_url] || request.env['HTTP_REFERER']
610 back_url = CGI.unescape(back_url.to_s)
611 hidden_field_tag('back_url', CGI.escape(back_url)) unless back_url.blank?
614 def check_all_links(form_name)
615 link_to_function(l(:button_check_all), "checkAll('#{form_name}', true)") +
617 link_to_function(l(:button_uncheck_all), "checkAll('#{form_name}', false)")
620 def progress_bar(pcts, options={})
621 pcts = [pcts, pcts] unless pcts.is_a?(Array)
622 pcts = pcts.collect(&:round)
623 pcts[1] = pcts[1] - pcts[0]
624 pcts << (100 - pcts[1] - pcts[0])
625 width = options[:width] || '100px;'
626 legend = options[:legend] || ''
629 (pcts[0] > 0 ? content_tag('td', '', :style => "width: #{pcts[0]}%;", :class => 'closed') : '') +
630 (pcts[1] > 0 ? content_tag('td', '', :style => "width: #{pcts[1]}%;", :class => 'done') : '') +
631 (pcts[2] > 0 ? content_tag('td', '', :style => "width: #{pcts[2]}%;", :class => 'todo') : '')
632 ), :class => 'progress', :style => "width: #{width};") +
633 content_tag('p', legend, :class => 'pourcent')
636 def context_menu_link(name, url, options={})
637 options[:class] ||= ''
638 if options.delete(:selected)
639 options[:class] << ' icon-checked disabled'
640 options[:disabled] = true
642 if options.delete(:disabled)
643 options.delete(:method)
644 options.delete(:confirm)
645 options.delete(:onclick)
646 options[:class] << ' disabled'
649 link_to name, url, options
652 def calendar_for(field_id)
653 include_calendar_headers_tags
654 image_tag("calendar.png", {:id => "#{field_id}_trigger",:class => "calendar-trigger"}) +
655 javascript_tag("Calendar.setup({inputField : '#{field_id}', ifFormat : '%Y-%m-%d', button : '#{field_id}_trigger' });")
658 def include_calendar_headers_tags
659 unless @calendar_headers_tags_included
660 @calendar_headers_tags_included = true
661 content_for :header_tags do
662 start_of_week = case Setting.start_of_week.to_i
664 'Calendar._FD = 1;' # Monday
666 'Calendar._FD = 0;' # Sunday
671 javascript_include_tag('calendar/calendar') +
672 javascript_include_tag("calendar/lang/calendar-#{current_language.to_s.downcase}.js") +
673 javascript_tag(start_of_week) +
674 javascript_include_tag('calendar/calendar-setup') +
675 stylesheet_link_tag('calendar')
680 def content_for(name, content = nil, &block)
682 @has_content[name] = true
683 super(name, content, &block)
686 def has_content?(name)
687 (@has_content && @has_content[name]) || false
690 # Returns the avatar image tag for the given +user+ if avatars are enabled
691 # +user+ can be a User or a string that will be scanned for an email address (eg. 'joe <joe@foo.bar>')
692 def avatar(user, options = { })
693 if Setting.gravatar_enabled?
694 options.merge!({:ssl => Setting.protocol == 'https', :default => Setting.gravatar_default})
696 if user.respond_to?(:mail)
698 elsif user.to_s =~ %r{<(.+?)>}
701 return gravatar(email.to_s.downcase, options) unless email.blank? rescue nil
708 helper = Redmine::WikiFormatting.helper_for(Setting.text_formatting)
713 def link_to_remote_content_update(text, url_params)
715 {:url => url_params, :method => :get, :update => 'content', :complete => 'window.scrollTo(0,0)'},
716 {:href => url_for(:params => url_params)}