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 # Generates a link to a SCM revision
101 # * :text - Link text (default to the formatted revision)
102 def link_to_revision(revision, project, options={})
103 text = options.delete(:text) || format_revision(revision)
105 link_to(text, {:controller => 'repositories', :action => 'revision', :id => project, :rev => revision}, :title => l(:label_revision_id, revision))
108 def toggle_link(name, id, options={})
109 onclick = "Element.toggle('#{id}'); "
110 onclick << (options[:focus] ? "Form.Element.focus('#{options[:focus]}'); " : "this.blur(); ")
111 onclick << "return false;"
112 link_to(name, "#", :onclick => onclick)
115 def image_to_function(name, function, html_options = {})
116 html_options.symbolize_keys!
117 tag(:input, html_options.merge({
118 :type => "image", :src => image_path(name),
119 :onclick => (html_options[:onclick] ? "#{html_options[:onclick]}; " : "") + "#{function};"
123 def prompt_to_remote(name, text, param, url, html_options = {})
124 html_options[:onclick] = "promptToRemote('#{text}', '#{param}', '#{url_for(url)}'); return false;"
125 link_to name, {}, html_options
128 def format_activity_title(text)
129 h(truncate_single_line(text, :length => 100))
132 def format_activity_day(date)
133 date == Date.today ? l(:label_today).titleize : format_date(date)
136 def format_activity_description(text)
137 h(truncate(text.to_s, :length => 120).gsub(%r{[\r\n]*<(pre|code)>.*$}m, '...')).gsub(/[\r\n]+/, "<br />")
140 def format_version_name(version)
141 if version.project == @project
144 h("#{version.project} - #{version}")
148 def due_date_distance_in_words(date)
150 l((date < Date.today ? :label_roadmap_overdue : :label_roadmap_due_in), distance_of_date_in_words(Date.today, date))
154 def render_page_hierarchy(pages, node=nil)
157 content << "<ul class=\"pages-hierarchy\">\n"
158 pages[node].each do |page|
160 content << link_to(h(page.pretty_title), {:controller => 'wiki', :action => 'index', :id => page.project, :page => page.title},
161 :title => (page.respond_to?(:updated_on) ? l(:label_updated_time, distance_of_time_in_words(Time.now, page.updated_on)) : nil))
162 content << "\n" + render_page_hierarchy(pages, page.id) if pages[page.id]
170 # Renders flash messages
171 def render_flash_messages
174 s << content_tag('div', v, :class => "flash #{k}")
179 # Renders tabs and their content
180 def render_tabs(tabs)
182 render :partial => 'common/tabs', :locals => {:tabs => tabs}
184 content_tag 'p', l(:label_no_data), :class => "nodata"
188 # Renders the project quick-jump box
189 def render_project_jump_box
190 # Retrieve them now to avoid a COUNT query
191 projects = User.current.projects.all
193 s = '<select onchange="if (this.value != \'\') { window.location = this.value; }">' +
194 "<option value=''>#{ l(:label_jump_to_a_project) }</option>" +
195 '<option value="" disabled="disabled">---</option>'
196 s << project_tree_options_for_select(projects, :selected => @project) do |p|
197 { :value => url_for(:controller => 'projects', :action => 'show', :id => p, :jump => current_menu_item) }
204 def project_tree_options_for_select(projects, options = {})
206 project_tree(projects) do |project, level|
207 name_prefix = (level > 0 ? (' ' * 2 * level + '» ') : '')
208 tag_options = {:value => project.id, :selected => ((project == options[:selected]) ? 'selected' : nil)}
209 tag_options.merge!(yield(project)) if block_given?
210 s << content_tag('option', name_prefix + h(project), tag_options)
215 # Yields the given block for each project with its level in the tree
216 def project_tree(projects, &block)
218 projects.sort_by(&:lft).each do |project|
219 while (ancestors.any? && !project.is_descendant_of?(ancestors.last))
222 yield project, ancestors.size
227 def project_nested_ul(projects, &block)
231 projects.sort_by(&:lft).each do |project|
232 if (ancestors.empty? || project.is_descendant_of?(ancestors.last))
237 while (ancestors.any? && !project.is_descendant_of?(ancestors.last))
243 s << yield(project).to_s
246 s << ("</li></ul>\n" * ancestors.size)
251 def principals_check_box_tags(name, principals)
253 principals.sort.each do |principal|
254 s << "<label>#{ check_box_tag name, principal.id, false } #{h principal}</label>\n"
259 # Truncates and returns the string as a single line
260 def truncate_single_line(string, *args)
261 truncate(string.to_s, *args).gsub(%r{[\r\n]+}m, ' ')
265 text.gsub(%r{(\d+)\.(\d+)}, '<span class="hours hours-int">\1</span><span class="hours hours-dec">.\2</span>')
268 def authoring(created, author, options={})
269 l(options[:label] || :label_added_time_by, :author => link_to_user(author), :age => time_tag(created))
273 text = distance_of_time_in_words(Time.now, time)
275 link_to(text, {:controller => 'projects', :action => 'activity', :id => @project, :from => time.to_date}, :title => format_time(time))
277 content_tag('acronym', text, :title => format_time(time))
281 def syntax_highlight(name, content)
282 type = CodeRay::FileType[name]
283 type ? CodeRay.scan(content, type).html : h(content)
286 def to_path_param(path)
287 path.to_s.split(%r{[/\\]}).select {|p| !p.blank?}
290 def pagination_links_full(paginator, count=nil, options={})
291 page_param = options.delete(:page_param) || :page
292 url_param = params.dup
293 # don't reuse query params if filters are present
294 url_param.merge!(:fields => nil, :values => nil, :operators => nil) if url_param.delete(:set_filter)
297 if paginator.current.previous
298 html << link_to_remote_content_update('« ' + l(:label_previous), url_param.merge(page_param => paginator.current.previous)) + ' '
301 html << (pagination_links_each(paginator, options) do |n|
302 link_to_remote_content_update(n.to_s, url_param.merge(page_param => n))
305 if paginator.current.next
306 html << ' ' + link_to_remote_content_update((l(:label_next) + ' »'), url_param.merge(page_param => paginator.current.next))
311 " (#{paginator.current.first_item}-#{paginator.current.last_item}/#{count})",
312 per_page_links(paginator.items_per_page)
313 ].compact.join(' | ')
319 def per_page_links(selected=nil)
320 url_param = params.dup
321 url_param.clear if url_param.has_key?(:set_filter)
323 links = Setting.per_page_options_array.collect do |n|
324 n == selected ? n : link_to_remote(n, {:update => "content",
325 :url => params.dup.merge(:per_page => n),
327 {:href => url_for(url_param.merge(:per_page => n))})
329 links.size > 1 ? l(:label_display_per_page, links.join(', ')) : nil
332 def reorder_links(name, url)
333 link_to(image_tag('2uparrow.png', :alt => l(:label_sort_highest)), url.merge({"#{name}[move_to]" => 'highest'}), :method => :post, :title => l(:label_sort_highest)) +
334 link_to(image_tag('1uparrow.png', :alt => l(:label_sort_higher)), url.merge({"#{name}[move_to]" => 'higher'}), :method => :post, :title => l(:label_sort_higher)) +
335 link_to(image_tag('1downarrow.png', :alt => l(:label_sort_lower)), url.merge({"#{name}[move_to]" => 'lower'}), :method => :post, :title => l(:label_sort_lower)) +
336 link_to(image_tag('2downarrow.png', :alt => l(:label_sort_lowest)), url.merge({"#{name}[move_to]" => 'lowest'}), :method => :post, :title => l(:label_sort_lowest))
339 def breadcrumb(*args)
340 elements = args.flatten
341 elements.any? ? content_tag('p', args.join(' » ') + ' » ', :class => 'breadcrumb') : nil
344 def other_formats_links(&block)
345 concat('<p class="other-formats">' + l(:label_export_to))
346 yield Redmine::Views::OtherFormatsBuilder.new(self)
350 def page_header_title
351 if @project.nil? || @project.new_record?
355 ancestors = (@project.root? ? [] : @project.ancestors.visible)
357 root = ancestors.shift
358 b << link_to(h(root), {:controller => 'projects', :action => 'show', :id => root, :jump => current_menu_item}, :class => 'root')
359 if ancestors.size > 2
361 ancestors = ancestors[-2, 2]
363 b += ancestors.collect {|p| link_to(h(p), {:controller => 'projects', :action => 'show', :id => p, :jump => current_menu_item}, :class => 'ancestor') }
370 def html_title(*args)
373 title << @project.name if @project
374 title += @html_title if @html_title
375 title << Setting.app_title
376 title.select {|t| !t.blank? }.join(' - ')
384 Redmine::AccessKeys.key_for s
387 # Formats text according to system settings.
388 # 2 ways to call this method:
389 # * with a String: textilizable(text, options)
390 # * with an object and one of its attribute: textilizable(issue, :description, options)
391 def textilizable(*args)
392 options = args.last.is_a?(Hash) ? args.pop : {}
395 obj = options[:object]
399 text = obj.send(args.shift).to_s
401 raise ArgumentError, 'invalid arguments to textilizable'
403 return '' if text.blank?
405 only_path = options.delete(:only_path) == false ? false : true
407 # when using an image link, try to use an attachment, if possible
408 attachments = options[:attachments] || (obj && obj.respond_to?(:attachments) ? obj.attachments : nil)
411 attachments = attachments.sort_by(&:created_on).reverse
412 text = text.gsub(/!((\<|\=|\>)?(\([^\)]+\))?(\[[^\]]+\])?(\{[^\}]+\})?)(\S+\.(bmp|gif|jpg|jpeg|png))!/i) do |m|
414 filename = $6.downcase
415 # search for the picture in attachments
416 if found = attachments.detect { |att| att.filename.downcase == filename }
417 image_url = url_for :only_path => only_path, :controller => 'attachments', :action => 'download', :id => found
418 desc = found.description.to_s.gsub(/^([^\(\)]*).*$/, "\\1")
419 alt = desc.blank? ? nil : "(#{desc})"
420 "!#{style}#{image_url}#{alt}!"
427 text = Redmine::WikiFormatting.to_html(Setting.text_formatting, text) { |macro, args| exec_macro(macro, obj, args) }
429 # different methods for formatting wiki links
430 case options[:wiki_links]
432 # used for local links to html files
433 format_wiki_link = Proc.new {|project, title, anchor| "#{title}.html" }
435 # used for single-file wiki export
436 format_wiki_link = Proc.new {|project, title, anchor| "##{title}" }
438 format_wiki_link = Proc.new {|project, title, anchor| url_for(:only_path => only_path, :controller => 'wiki', :action => 'index', :id => project, :page => title, :anchor => anchor) }
441 project = options[:project] || @project || (obj && obj.respond_to?(:project) ? obj.project : nil)
448 # wiki links can refer other project wikis, using project name or identifier:
449 # [[project:]] -> wiki starting page
450 # [[project:|mytext]]
452 # [[project:mypage|mytext]]
453 text = text.gsub(/(!)?(\[\[([^\]\n\|]+)(\|([^\]\n\|]+))?\]\])/) do |m|
454 link_project = project
455 esc, all, page, title = $1, $2, $3, $5
457 if page =~ /^([^\:]+)\:(.*)$/
458 link_project = Project.find_by_name($1) || Project.find_by_identifier($1)
460 title ||= $1 if page.blank?
463 if link_project && link_project.wiki
466 if page =~ /^(.+?)\#(.+)$/
467 page, anchor = $1, $2
469 # check if page exists
470 wiki_page = link_project.wiki.find_page(page)
471 link_to((title || page), format_wiki_link.call(link_project, Wiki.titleize(page), anchor),
472 :class => ('wiki-page' + (wiki_page ? '' : ' new')))
474 # project or wiki doesn't exist
486 # #52 -> Link to issue #52
488 # r52 -> Link to revision 52
489 # commit:a85130f -> Link to scmid starting with a85130f
491 # document#17 -> Link to document with id 17
492 # document:Greetings -> Link to the document with title "Greetings"
493 # document:"Some document" -> Link to the document with title "Some document"
495 # version#3 -> Link to version with id 3
496 # version:1.0.0 -> Link to version named "1.0.0"
497 # version:"1.0 beta 2" -> Link to version named "1.0 beta 2"
499 # attachment:file.zip -> Link to the attachment of the current object named file.zip
501 # source:some/file -> Link to the file located at /some/file in the project's repository
502 # source:some/file@52 -> Link to the file's revision 52
503 # source:some/file#L120 -> Link to line 120 of the file
504 # source:some/file@52#L120 -> Link to line 120 of the file's revision 52
505 # export:some/file -> Force the download of the file
507 # message#1218 -> Link to message with id 1218
508 text = text.gsub(%r{([\s\(,\-\>]|^)(!)?(attachment|document|version|commit|source|export|message)?((#|r)(\d+)|(:)([^"\s<>][^\s<>]*?|"[^"]+?"))(?=(?=[[:punct:]]\W)|,|\s|<|$)}) do |m|
509 leading, esc, prefix, sep, oid = $1, $2, $3, $5 || $7, $6 || $8
512 if prefix.nil? && sep == 'r'
513 if project && (changeset = project.changesets.find_by_revision(oid))
514 link = link_to("r#{oid}", {:only_path => only_path, :controller => 'repositories', :action => 'revision', :id => project, :rev => oid},
515 :class => 'changeset',
516 :title => truncate_single_line(changeset.comments, :length => 100))
522 if issue = Issue.visible.find_by_id(oid, :include => :status)
523 link = link_to("##{oid}", {:only_path => only_path, :controller => 'issues', :action => 'show', :id => oid},
524 :class => issue.css_classes,
525 :title => "#{truncate(issue.subject, :length => 100)} (#{issue.status.name})")
528 if document = Document.find_by_id(oid, :include => [:project], :conditions => Project.visible_by(User.current))
529 link = link_to h(document.title), {:only_path => only_path, :controller => 'documents', :action => 'show', :id => document},
533 if version = Version.find_by_id(oid, :include => [:project], :conditions => Project.visible_by(User.current))
534 link = link_to h(version.name), {:only_path => only_path, :controller => 'versions', :action => 'show', :id => version},
538 if message = Message.find_by_id(oid, :include => [:parent, {:board => :project}], :conditions => Project.visible_by(User.current))
539 link = link_to h(truncate(message.subject, :length => 60)), {:only_path => only_path,
540 :controller => 'messages',
542 :board_id => message.board,
544 :anchor => (message.parent ? "message-#{message.id}" : nil)},
549 # removes the double quotes if any
550 name = oid.gsub(%r{^"(.*)"$}, "\\1")
553 if project && document = project.documents.find_by_title(name)
554 link = link_to h(document.title), {:only_path => only_path, :controller => 'documents', :action => 'show', :id => document},
558 if project && version = project.versions.find_by_name(name)
559 link = link_to h(version.name), {:only_path => only_path, :controller => 'versions', :action => 'show', :id => version},
563 if project && (changeset = project.changesets.find(:first, :conditions => ["scmid LIKE ?", "#{name}%"]))
564 link = link_to h("#{name}"), {:only_path => only_path, :controller => 'repositories', :action => 'revision', :id => project, :rev => changeset.revision},
565 :class => 'changeset',
566 :title => truncate_single_line(changeset.comments, :length => 100)
568 when 'source', 'export'
569 if project && project.repository
570 name =~ %r{^[/\\]*(.*?)(@([0-9a-f]+))?(#(L\d+))?$}
571 path, rev, anchor = $1, $3, $5
572 link = link_to h("#{prefix}:#{name}"), {:controller => 'repositories', :action => 'entry', :id => project,
573 :path => to_path_param(path),
576 :format => (prefix == 'export' ? 'raw' : nil)},
577 :class => (prefix == 'export' ? 'source download' : 'source')
580 if attachments && attachment = attachments.detect {|a| a.filename == name }
581 link = link_to h(attachment.filename), {:only_path => only_path, :controller => 'attachments', :action => 'download', :id => attachment},
582 :class => 'attachment'
587 leading + (link || "#{prefix}#{sep}#{oid}")
593 # Same as Rails' simple_format helper without using paragraphs
594 def simple_format_without_paragraph(text)
596 gsub(/\r\n?/, "\n"). # \r\n and \r -> \n
597 gsub(/\n\n+/, "<br /><br />"). # 2+ newline -> 2 br
598 gsub(/([^\n]\n)(?=[^\n])/, '\1<br />') # 1 newline -> br
601 def lang_options_for_select(blank=true)
602 (blank ? [["(auto)", ""]] : []) +
603 valid_languages.collect{|lang| [ ll(lang.to_s, :general_lang_name), lang.to_s]}.sort{|x,y| x.last <=> y.last }
606 def label_tag_for(name, option_tags = nil, options = {})
607 label_text = l(("field_"+field.to_s.gsub(/\_id$/, "")).to_sym) + (options.delete(:required) ? @template.content_tag("span", " *", :class => "required"): "")
608 content_tag("label", label_text)
611 def labelled_tabular_form_for(name, object, options, &proc)
612 options[:html] ||= {}
613 options[:html][:class] = 'tabular' unless options[:html].has_key?(:class)
614 form_for(name, object, options.merge({ :builder => TabularFormBuilder, :lang => current_language}), &proc)
617 def back_url_hidden_field_tag
618 back_url = params[:back_url] || request.env['HTTP_REFERER']
619 back_url = CGI.unescape(back_url.to_s)
620 hidden_field_tag('back_url', CGI.escape(back_url)) unless back_url.blank?
623 def check_all_links(form_name)
624 link_to_function(l(:button_check_all), "checkAll('#{form_name}', true)") +
626 link_to_function(l(:button_uncheck_all), "checkAll('#{form_name}', false)")
629 def progress_bar(pcts, options={})
630 pcts = [pcts, pcts] unless pcts.is_a?(Array)
631 pcts = pcts.collect(&:round)
632 pcts[1] = pcts[1] - pcts[0]
633 pcts << (100 - pcts[1] - pcts[0])
634 width = options[:width] || '100px;'
635 legend = options[:legend] || ''
638 (pcts[0] > 0 ? content_tag('td', '', :style => "width: #{pcts[0]}%;", :class => 'closed') : '') +
639 (pcts[1] > 0 ? content_tag('td', '', :style => "width: #{pcts[1]}%;", :class => 'done') : '') +
640 (pcts[2] > 0 ? content_tag('td', '', :style => "width: #{pcts[2]}%;", :class => 'todo') : '')
641 ), :class => 'progress', :style => "width: #{width};") +
642 content_tag('p', legend, :class => 'pourcent')
645 def context_menu_link(name, url, options={})
646 options[:class] ||= ''
647 if options.delete(:selected)
648 options[:class] << ' icon-checked disabled'
649 options[:disabled] = true
651 if options.delete(:disabled)
652 options.delete(:method)
653 options.delete(:confirm)
654 options.delete(:onclick)
655 options[:class] << ' disabled'
658 link_to name, url, options
661 def calendar_for(field_id)
662 include_calendar_headers_tags
663 image_tag("calendar.png", {:id => "#{field_id}_trigger",:class => "calendar-trigger"}) +
664 javascript_tag("Calendar.setup({inputField : '#{field_id}', ifFormat : '%Y-%m-%d', button : '#{field_id}_trigger' });")
667 def include_calendar_headers_tags
668 unless @calendar_headers_tags_included
669 @calendar_headers_tags_included = true
670 content_for :header_tags do
671 start_of_week = case Setting.start_of_week.to_i
673 'Calendar._FD = 1;' # Monday
675 'Calendar._FD = 0;' # Sunday
680 javascript_include_tag('calendar/calendar') +
681 javascript_include_tag("calendar/lang/calendar-#{current_language.to_s.downcase}.js") +
682 javascript_tag(start_of_week) +
683 javascript_include_tag('calendar/calendar-setup') +
684 stylesheet_link_tag('calendar')
689 def content_for(name, content = nil, &block)
691 @has_content[name] = true
692 super(name, content, &block)
695 def has_content?(name)
696 (@has_content && @has_content[name]) || false
699 # Returns the avatar image tag for the given +user+ if avatars are enabled
700 # +user+ can be a User or a string that will be scanned for an email address (eg. 'joe <joe@foo.bar>')
701 def avatar(user, options = { })
702 if Setting.gravatar_enabled?
703 options.merge!({:ssl => Setting.protocol == 'https', :default => Setting.gravatar_default})
705 if user.respond_to?(:mail)
707 elsif user.to_s =~ %r{<(.+?)>}
710 return gravatar(email.to_s.downcase, options) unless email.blank? rescue nil
717 helper = Redmine::WikiFormatting.helper_for(Setting.text_formatting)
722 def link_to_remote_content_update(text, url_params)
724 {:url => url_params, :method => :get, :update => 'content', :complete => 'window.scrollTo(0,0)'},
725 {:href => url_for(:params => url_params)}