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