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
68 def link_to_issue(issue, options={})
71 if options[:subject] == false
72 title = truncate(issue.subject, :length => 60)
74 subject = issue.subject
76 subject = truncate(subject, :length => options[:truncate])
79 s = link_to "#{issue.tracker} ##{issue.id}", {:controller => "issues", :action => "show", :id => issue},
80 :class => issue.css_classes,
82 s << ": #{h subject}" if subject
86 # Generates a link to an attachment.
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'
94 link_to(h(text), {:controller => 'attachments', :action => action, :id => attachment, :filename => attachment.filename }, options)
97 def toggle_link(name, id, options={})
98 onclick = "Element.toggle('#{id}'); "
99 onclick << (options[:focus] ? "Form.Element.focus('#{options[:focus]}'); " : "this.blur(); ")
100 onclick << "return false;"
101 link_to(name, "#", :onclick => onclick)
104 def image_to_function(name, function, html_options = {})
105 html_options.symbolize_keys!
106 tag(:input, html_options.merge({
107 :type => "image", :src => image_path(name),
108 :onclick => (html_options[:onclick] ? "#{html_options[:onclick]}; " : "") + "#{function};"
112 def prompt_to_remote(name, text, param, url, html_options = {})
113 html_options[:onclick] = "promptToRemote('#{text}', '#{param}', '#{url_for(url)}'); return false;"
114 link_to name, {}, html_options
117 def format_activity_title(text)
118 h(truncate_single_line(text, :length => 100))
121 def format_activity_day(date)
122 date == Date.today ? l(:label_today).titleize : format_date(date)
125 def format_activity_description(text)
126 h(truncate(text.to_s, :length => 120).gsub(%r{[\r\n]*<(pre|code)>.*$}m, '...')).gsub(/[\r\n]+/, "<br />")
129 def due_date_distance_in_words(date)
131 l((date < Date.today ? :label_roadmap_overdue : :label_roadmap_due_in), distance_of_date_in_words(Date.today, date))
135 def render_page_hierarchy(pages, node=nil)
138 content << "<ul class=\"pages-hierarchy\">\n"
139 pages[node].each do |page|
141 content << link_to(h(page.pretty_title), {:controller => 'wiki', :action => 'index', :id => page.project, :page => page.title},
142 :title => (page.respond_to?(:updated_on) ? l(:label_updated_time, distance_of_time_in_words(Time.now, page.updated_on)) : nil))
143 content << "\n" + render_page_hierarchy(pages, page.id) if pages[page.id]
151 # Renders flash messages
152 def render_flash_messages
155 s << content_tag('div', v, :class => "flash #{k}")
160 # Renders tabs and their content
161 def render_tabs(tabs)
163 render :partial => 'common/tabs', :locals => {:tabs => tabs}
165 content_tag 'p', l(:label_no_data), :class => "nodata"
169 # Renders the project quick-jump box
170 def render_project_jump_box
171 # Retrieve them now to avoid a COUNT query
172 projects = User.current.projects.all
174 s = '<select onchange="if (this.value != \'\') { window.location = this.value; }">' +
175 "<option value=''>#{ l(:label_jump_to_a_project) }</option>" +
176 '<option value="" disabled="disabled">---</option>'
177 s << project_tree_options_for_select(projects, :selected => @project) do |p|
178 { :value => url_for(:controller => 'projects', :action => 'show', :id => p, :jump => current_menu_item) }
185 def project_tree_options_for_select(projects, options = {})
187 project_tree(projects) do |project, level|
188 name_prefix = (level > 0 ? (' ' * 2 * level + '» ') : '')
189 tag_options = {:value => project.id, :selected => ((project == options[:selected]) ? 'selected' : nil)}
190 tag_options.merge!(yield(project)) if block_given?
191 s << content_tag('option', name_prefix + h(project), tag_options)
196 # Yields the given block for each project with its level in the tree
197 def project_tree(projects, &block)
199 projects.sort_by(&:lft).each do |project|
200 while (ancestors.any? && !project.is_descendant_of?(ancestors.last))
203 yield project, ancestors.size
208 def project_nested_ul(projects, &block)
212 projects.sort_by(&:lft).each do |project|
213 if (ancestors.empty? || project.is_descendant_of?(ancestors.last))
218 while (ancestors.any? && !project.is_descendant_of?(ancestors.last))
224 s << yield(project).to_s
227 s << ("</li></ul>\n" * ancestors.size)
232 def principals_check_box_tags(name, principals)
234 principals.sort.each do |principal|
235 s << "<label>#{ check_box_tag name, principal.id, false } #{h principal}</label>\n"
240 # Truncates and returns the string as a single line
241 def truncate_single_line(string, *args)
242 truncate(string.to_s, *args).gsub(%r{[\r\n]+}m, ' ')
246 text.gsub(%r{(\d+)\.(\d+)}, '<span class="hours hours-int">\1</span><span class="hours hours-dec">.\2</span>')
249 def authoring(created, author, options={})
250 l(options[:label] || :label_added_time_by, :author => link_to_user(author), :age => time_tag(created))
254 text = distance_of_time_in_words(Time.now, time)
256 link_to(text, {:controller => 'projects', :action => 'activity', :id => @project, :from => time.to_date}, :title => format_time(time))
258 content_tag('acronym', text, :title => format_time(time))
262 def syntax_highlight(name, content)
263 type = CodeRay::FileType[name]
264 type ? CodeRay.scan(content, type).html : h(content)
267 def to_path_param(path)
268 path.to_s.split(%r{[/\\]}).select {|p| !p.blank?}
271 def pagination_links_full(paginator, count=nil, options={})
272 page_param = options.delete(:page_param) || :page
273 url_param = params.dup
274 # don't reuse query params if filters are present
275 url_param.merge!(:fields => nil, :values => nil, :operators => nil) if url_param.delete(:set_filter)
278 if paginator.current.previous
279 html << link_to_remote_content_update('« ' + l(:label_previous), url_param.merge(page_param => paginator.current.previous)) + ' '
282 html << (pagination_links_each(paginator, options) do |n|
283 link_to_remote_content_update(n.to_s, url_param.merge(page_param => n))
286 if paginator.current.next
287 html << ' ' + link_to_remote_content_update((l(:label_next) + ' »'), url_param.merge(page_param => paginator.current.next))
292 " (#{paginator.current.first_item}-#{paginator.current.last_item}/#{count})",
293 per_page_links(paginator.items_per_page)
294 ].compact.join(' | ')
300 def per_page_links(selected=nil)
301 url_param = params.dup
302 url_param.clear if url_param.has_key?(:set_filter)
304 links = Setting.per_page_options_array.collect do |n|
305 n == selected ? n : link_to_remote(n, {:update => "content",
306 :url => params.dup.merge(:per_page => n),
308 {:href => url_for(url_param.merge(:per_page => n))})
310 links.size > 1 ? l(:label_display_per_page, links.join(', ')) : nil
313 def reorder_links(name, url)
314 link_to(image_tag('2uparrow.png', :alt => l(:label_sort_highest)), url.merge({"#{name}[move_to]" => 'highest'}), :method => :post, :title => l(:label_sort_highest)) +
315 link_to(image_tag('1uparrow.png', :alt => l(:label_sort_higher)), url.merge({"#{name}[move_to]" => 'higher'}), :method => :post, :title => l(:label_sort_higher)) +
316 link_to(image_tag('1downarrow.png', :alt => l(:label_sort_lower)), url.merge({"#{name}[move_to]" => 'lower'}), :method => :post, :title => l(:label_sort_lower)) +
317 link_to(image_tag('2downarrow.png', :alt => l(:label_sort_lowest)), url.merge({"#{name}[move_to]" => 'lowest'}), :method => :post, :title => l(:label_sort_lowest))
320 def breadcrumb(*args)
321 elements = args.flatten
322 elements.any? ? content_tag('p', args.join(' » ') + ' » ', :class => 'breadcrumb') : nil
325 def other_formats_links(&block)
326 concat('<p class="other-formats">' + l(:label_export_to))
327 yield Redmine::Views::OtherFormatsBuilder.new(self)
331 def page_header_title
332 if @project.nil? || @project.new_record?
336 ancestors = (@project.root? ? [] : @project.ancestors.visible)
338 root = ancestors.shift
339 b << link_to(h(root), {:controller => 'projects', :action => 'show', :id => root, :jump => current_menu_item}, :class => 'root')
340 if ancestors.size > 2
342 ancestors = ancestors[-2, 2]
344 b += ancestors.collect {|p| link_to(h(p), {:controller => 'projects', :action => 'show', :id => p, :jump => current_menu_item}, :class => 'ancestor') }
351 def html_title(*args)
354 title << @project.name if @project
355 title += @html_title if @html_title
356 title << Setting.app_title
357 title.select {|t| !t.blank? }.join(' - ')
365 Redmine::AccessKeys.key_for s
368 # Formats text according to system settings.
369 # 2 ways to call this method:
370 # * with a String: textilizable(text, options)
371 # * with an object and one of its attribute: textilizable(issue, :description, options)
372 def textilizable(*args)
373 options = args.last.is_a?(Hash) ? args.pop : {}
376 obj = options[:object]
380 text = obj.send(args.shift).to_s
382 raise ArgumentError, 'invalid arguments to textilizable'
384 return '' if text.blank?
386 only_path = options.delete(:only_path) == false ? false : true
388 # when using an image link, try to use an attachment, if possible
389 attachments = options[:attachments] || (obj && obj.respond_to?(:attachments) ? obj.attachments : nil)
392 attachments = attachments.sort_by(&:created_on).reverse
393 text = text.gsub(/!((\<|\=|\>)?(\([^\)]+\))?(\[[^\]]+\])?(\{[^\}]+\})?)(\S+\.(bmp|gif|jpg|jpeg|png))!/i) do |m|
395 filename = $6.downcase
396 # search for the picture in attachments
397 if found = attachments.detect { |att| att.filename.downcase == filename }
398 image_url = url_for :only_path => only_path, :controller => 'attachments', :action => 'download', :id => found
399 desc = found.description.to_s.gsub(/^([^\(\)]*).*$/, "\\1")
400 alt = desc.blank? ? nil : "(#{desc})"
401 "!#{style}#{image_url}#{alt}!"
408 text = Redmine::WikiFormatting.to_html(Setting.text_formatting, text) { |macro, args| exec_macro(macro, obj, args) }
410 # different methods for formatting wiki links
411 case options[:wiki_links]
413 # used for local links to html files
414 format_wiki_link = Proc.new {|project, title, anchor| "#{title}.html" }
416 # used for single-file wiki export
417 format_wiki_link = Proc.new {|project, title, anchor| "##{title}" }
419 format_wiki_link = Proc.new {|project, title, anchor| url_for(:only_path => only_path, :controller => 'wiki', :action => 'index', :id => project, :page => title, :anchor => anchor) }
422 project = options[:project] || @project || (obj && obj.respond_to?(:project) ? obj.project : nil)
429 # wiki links can refer other project wikis, using project name or identifier:
430 # [[project:]] -> wiki starting page
431 # [[project:|mytext]]
433 # [[project:mypage|mytext]]
434 text = text.gsub(/(!)?(\[\[([^\]\n\|]+)(\|([^\]\n\|]+))?\]\])/) do |m|
435 link_project = project
436 esc, all, page, title = $1, $2, $3, $5
438 if page =~ /^([^\:]+)\:(.*)$/
439 link_project = Project.find_by_name($1) || Project.find_by_identifier($1)
441 title ||= $1 if page.blank?
444 if link_project && link_project.wiki
447 if page =~ /^(.+?)\#(.+)$/
448 page, anchor = $1, $2
450 # check if page exists
451 wiki_page = link_project.wiki.find_page(page)
452 link_to((title || page), format_wiki_link.call(link_project, Wiki.titleize(page), anchor),
453 :class => ('wiki-page' + (wiki_page ? '' : ' new')))
455 # project or wiki doesn't exist
467 # #52 -> Link to issue #52
469 # r52 -> Link to revision 52
470 # commit:a85130f -> Link to scmid starting with a85130f
472 # document#17 -> Link to document with id 17
473 # document:Greetings -> Link to the document with title "Greetings"
474 # document:"Some document" -> Link to the document with title "Some document"
476 # version#3 -> Link to version with id 3
477 # version:1.0.0 -> Link to version named "1.0.0"
478 # version:"1.0 beta 2" -> Link to version named "1.0 beta 2"
480 # attachment:file.zip -> Link to the attachment of the current object named file.zip
482 # source:some/file -> Link to the file located at /some/file in the project's repository
483 # source:some/file@52 -> Link to the file's revision 52
484 # source:some/file#L120 -> Link to line 120 of the file
485 # source:some/file@52#L120 -> Link to line 120 of the file's revision 52
486 # export:some/file -> Force the download of the file
488 # message#1218 -> Link to message with id 1218
489 text = text.gsub(%r{([\s\(,\-\>]|^)(!)?(attachment|document|version|commit|source|export|message)?((#|r)(\d+)|(:)([^"\s<>][^\s<>]*?|"[^"]+?"))(?=(?=[[:punct:]]\W)|,|\s|<|$)}) do |m|
490 leading, esc, prefix, sep, oid = $1, $2, $3, $5 || $7, $6 || $8
493 if prefix.nil? && sep == 'r'
494 if project && (changeset = project.changesets.find_by_revision(oid))
495 link = link_to("r#{oid}", {:only_path => only_path, :controller => 'repositories', :action => 'revision', :id => project, :rev => oid},
496 :class => 'changeset',
497 :title => truncate_single_line(changeset.comments, :length => 100))
503 if issue = Issue.visible.find_by_id(oid, :include => :status)
504 link = link_to("##{oid}", {:only_path => only_path, :controller => 'issues', :action => 'show', :id => oid},
505 :class => issue.css_classes,
506 :title => "#{truncate(issue.subject, :length => 100)} (#{issue.status.name})")
509 if document = Document.find_by_id(oid, :include => [:project], :conditions => Project.visible_by(User.current))
510 link = link_to h(document.title), {:only_path => only_path, :controller => 'documents', :action => 'show', :id => document},
514 if version = Version.find_by_id(oid, :include => [:project], :conditions => Project.visible_by(User.current))
515 link = link_to h(version.name), {:only_path => only_path, :controller => 'versions', :action => 'show', :id => version},
519 if message = Message.find_by_id(oid, :include => [:parent, {:board => :project}], :conditions => Project.visible_by(User.current))
520 link = link_to h(truncate(message.subject, :length => 60)), {:only_path => only_path,
521 :controller => 'messages',
523 :board_id => message.board,
525 :anchor => (message.parent ? "message-#{message.id}" : nil)},
530 # removes the double quotes if any
531 name = oid.gsub(%r{^"(.*)"$}, "\\1")
534 if project && document = project.documents.find_by_title(name)
535 link = link_to h(document.title), {:only_path => only_path, :controller => 'documents', :action => 'show', :id => document},
539 if project && version = project.versions.find_by_name(name)
540 link = link_to h(version.name), {:only_path => only_path, :controller => 'versions', :action => 'show', :id => version},
544 if project && (changeset = project.changesets.find(:first, :conditions => ["scmid LIKE ?", "#{name}%"]))
545 link = link_to h("#{name}"), {:only_path => only_path, :controller => 'repositories', :action => 'revision', :id => project, :rev => changeset.revision},
546 :class => 'changeset',
547 :title => truncate_single_line(changeset.comments, :length => 100)
549 when 'source', 'export'
550 if project && project.repository
551 name =~ %r{^[/\\]*(.*?)(@([0-9a-f]+))?(#(L\d+))?$}
552 path, rev, anchor = $1, $3, $5
553 link = link_to h("#{prefix}:#{name}"), {:controller => 'repositories', :action => 'entry', :id => project,
554 :path => to_path_param(path),
557 :format => (prefix == 'export' ? 'raw' : nil)},
558 :class => (prefix == 'export' ? 'source download' : 'source')
561 if attachments && attachment = attachments.detect {|a| a.filename == name }
562 link = link_to h(attachment.filename), {:only_path => only_path, :controller => 'attachments', :action => 'download', :id => attachment},
563 :class => 'attachment'
568 leading + (link || "#{prefix}#{sep}#{oid}")
574 # Same as Rails' simple_format helper without using paragraphs
575 def simple_format_without_paragraph(text)
577 gsub(/\r\n?/, "\n"). # \r\n and \r -> \n
578 gsub(/\n\n+/, "<br /><br />"). # 2+ newline -> 2 br
579 gsub(/([^\n]\n)(?=[^\n])/, '\1<br />') # 1 newline -> br
582 def lang_options_for_select(blank=true)
583 (blank ? [["(auto)", ""]] : []) +
584 valid_languages.collect{|lang| [ ll(lang.to_s, :general_lang_name), lang.to_s]}.sort{|x,y| x.last <=> y.last }
587 def label_tag_for(name, option_tags = nil, options = {})
588 label_text = l(("field_"+field.to_s.gsub(/\_id$/, "")).to_sym) + (options.delete(:required) ? @template.content_tag("span", " *", :class => "required"): "")
589 content_tag("label", label_text)
592 def labelled_tabular_form_for(name, object, options, &proc)
593 options[:html] ||= {}
594 options[:html][:class] = 'tabular' unless options[:html].has_key?(:class)
595 form_for(name, object, options.merge({ :builder => TabularFormBuilder, :lang => current_language}), &proc)
598 def back_url_hidden_field_tag
599 back_url = params[:back_url] || request.env['HTTP_REFERER']
600 back_url = CGI.unescape(back_url.to_s)
601 hidden_field_tag('back_url', CGI.escape(back_url)) unless back_url.blank?
604 def check_all_links(form_name)
605 link_to_function(l(:button_check_all), "checkAll('#{form_name}', true)") +
607 link_to_function(l(:button_uncheck_all), "checkAll('#{form_name}', false)")
610 def progress_bar(pcts, options={})
611 pcts = [pcts, pcts] unless pcts.is_a?(Array)
612 pcts = pcts.collect(&:round)
613 pcts[1] = pcts[1] - pcts[0]
614 pcts << (100 - pcts[1] - pcts[0])
615 width = options[:width] || '100px;'
616 legend = options[:legend] || ''
619 (pcts[0] > 0 ? content_tag('td', '', :style => "width: #{pcts[0]}%;", :class => 'closed') : '') +
620 (pcts[1] > 0 ? content_tag('td', '', :style => "width: #{pcts[1]}%;", :class => 'done') : '') +
621 (pcts[2] > 0 ? content_tag('td', '', :style => "width: #{pcts[2]}%;", :class => 'todo') : '')
622 ), :class => 'progress', :style => "width: #{width};") +
623 content_tag('p', legend, :class => 'pourcent')
626 def context_menu_link(name, url, options={})
627 options[:class] ||= ''
628 if options.delete(:selected)
629 options[:class] << ' icon-checked disabled'
630 options[:disabled] = true
632 if options.delete(:disabled)
633 options.delete(:method)
634 options.delete(:confirm)
635 options.delete(:onclick)
636 options[:class] << ' disabled'
639 link_to name, url, options
642 def calendar_for(field_id)
643 include_calendar_headers_tags
644 image_tag("calendar.png", {:id => "#{field_id}_trigger",:class => "calendar-trigger"}) +
645 javascript_tag("Calendar.setup({inputField : '#{field_id}', ifFormat : '%Y-%m-%d', button : '#{field_id}_trigger' });")
648 def include_calendar_headers_tags
649 unless @calendar_headers_tags_included
650 @calendar_headers_tags_included = true
651 content_for :header_tags do
652 javascript_include_tag('calendar/calendar') +
653 javascript_include_tag("calendar/lang/calendar-#{current_language.to_s.downcase}.js") +
654 javascript_include_tag('calendar/calendar-setup') +
655 stylesheet_link_tag('calendar')
660 def content_for(name, content = nil, &block)
662 @has_content[name] = true
663 super(name, content, &block)
666 def has_content?(name)
667 (@has_content && @has_content[name]) || false
670 # Returns the avatar image tag for the given +user+ if avatars are enabled
671 # +user+ can be a User or a string that will be scanned for an email address (eg. 'joe <joe@foo.bar>')
672 def avatar(user, options = { })
673 if Setting.gravatar_enabled?
674 options.merge!({:ssl => Setting.protocol == 'https', :default => Setting.gravatar_default})
676 if user.respond_to?(:mail)
678 elsif user.to_s =~ %r{<(.+?)>}
681 return gravatar(email.to_s.downcase, options) unless email.blank? rescue nil
688 helper = Redmine::WikiFormatting.helper_for(Setting.text_formatting)
693 def link_to_remote_content_update(text, url_params)
695 {:url => url_params, :method => :get, :update => 'content', :complete => 'window.scrollTo(0,0)'},
696 {:href => url_for(:params => url_params)}