OSDN Git Service

cdb64f4173859234fbee4db209047b7341aaf702
[redminele/redmine.git] / app / helpers / application_helper.rb
1 # redMine - project management software
2 # Copyright (C) 2006-2007  Jean-Philippe Lang
3 #
4 # This program is free software; you can redistribute it and/or
5 # modify it under the terms of the GNU General Public License
6 # as published by the Free Software Foundation; either version 2
7 # of the License, or (at your option) any later version.
8 #
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12 # GNU General Public License for more details.
13 #
14 # You should have received a copy of the GNU General Public License
15 # along with this program; if not, write to the Free Software
16 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
17
18 require 'coderay'
19 require 'coderay/helpers/file_type'
20 require 'forwardable'
21 require 'cgi'
22
23 module ApplicationHelper
24   include Redmine::WikiFormatting::Macros::Definitions
25   include Redmine::I18n
26   include GravatarHelper::PublicMethods
27
28   extend Forwardable
29   def_delegators :wiki_helper, :wikitoolbar_for, :heads_for_wiki_formatter
30
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)
34   end
35
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])
39   end
40
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])
45   end
46
47   # Displays a link to user's account page if active
48   def link_to_user(user, options={})
49     if user.is_a?(User)
50       name = h(user.name(options[:format]))
51       if user.active?
52         link_to name, :controller => 'users', :action => 'show', :id => user
53       else
54         name
55       end
56     else
57       h(user.to_s)
58     end
59   end
60
61   # Displays a link to +issue+ with its subject.
62   # Examples:
63   # 
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
68   #
69   def link_to_issue(issue, options={})
70     title = nil
71     subject = nil
72     if options[:subject] == false
73       title = truncate(issue.subject, :length => 60)
74     else
75       subject = issue.subject
76       if options[:truncate]
77         subject = truncate(subject, :length => options[:truncate])
78       end
79     end
80     s = link_to "#{issue.tracker} ##{issue.id}", {:controller => "issues", :action => "show", :id => issue}, 
81                                                  :class => issue.css_classes,
82                                                  :title => title
83     s << ": #{h subject}" if subject
84     s = "#{h issue.project} - " + s if options[:project]
85     s
86   end
87
88   # Generates a link to an attachment.
89   # Options:
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'
95
96     link_to(h(text), {:controller => 'attachments', :action => action, :id => attachment, :filename => attachment.filename }, options)
97   end
98
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)
104   end
105
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};"
111         }))
112   end
113
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
117   end
118   
119   def format_activity_title(text)
120     h(truncate_single_line(text, :length => 100))
121   end
122   
123   def format_activity_day(date)
124     date == Date.today ? l(:label_today).titleize : format_date(date)
125   end
126   
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 />")
129   end
130
131   def format_version_name(version)
132     if version.project == @project
133         h(version)
134     else
135       h("#{version.project} - #{version}")
136     end
137   end
138   
139   def due_date_distance_in_words(date)
140     if date
141       l((date < Date.today ? :label_roadmap_overdue : :label_roadmap_due_in), distance_of_date_in_words(Date.today, date))
142     end
143   end
144
145   def render_page_hierarchy(pages, node=nil)
146     content = ''
147     if pages[node]
148       content << "<ul class=\"pages-hierarchy\">\n"
149       pages[node].each do |page|
150         content << "<li>"
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]
154         content << "</li>\n"
155       end
156       content << "</ul>\n"
157     end
158     content
159   end
160   
161   # Renders flash messages
162   def render_flash_messages
163     s = ''
164     flash.each do |k,v|
165       s << content_tag('div', v, :class => "flash #{k}")
166     end
167     s
168   end
169   
170   # Renders tabs and their content
171   def render_tabs(tabs)
172     if tabs.any?
173       render :partial => 'common/tabs', :locals => {:tabs => tabs}
174     else
175       content_tag 'p', l(:label_no_data), :class => "nodata"
176     end
177   end
178   
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
183     if projects.any?
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) }
189       end
190       s << '</select>'
191       s
192     end
193   end
194   
195   def project_tree_options_for_select(projects, options = {})
196     s = ''
197     project_tree(projects) do |project, level|
198       name_prefix = (level > 0 ? ('&nbsp;' * 2 * level + '&#187; ') : '')
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)
202     end
203     s
204   end
205   
206   # Yields the given block for each project with its level in the tree
207   def project_tree(projects, &block)
208     ancestors = []
209     projects.sort_by(&:lft).each do |project|
210       while (ancestors.any? && !project.is_descendant_of?(ancestors.last)) 
211         ancestors.pop
212       end
213       yield project, ancestors.size
214       ancestors << project
215     end
216   end
217   
218   def project_nested_ul(projects, &block)
219     s = ''
220     if projects.any?
221       ancestors = []
222       projects.sort_by(&:lft).each do |project|
223         if (ancestors.empty? || project.is_descendant_of?(ancestors.last))
224           s << "<ul>\n"
225         else
226           ancestors.pop
227           s << "</li>"
228           while (ancestors.any? && !project.is_descendant_of?(ancestors.last)) 
229             ancestors.pop
230             s << "</ul></li>\n"
231           end
232         end
233         s << "<li>"
234         s << yield(project).to_s
235         ancestors << project
236       end
237       s << ("</li></ul>\n" * ancestors.size)
238     end
239     s
240   end
241   
242   def principals_check_box_tags(name, principals)
243     s = ''
244     principals.sort.each do |principal|
245       s << "<label>#{ check_box_tag name, principal.id, false } #{h principal}</label>\n"
246     end
247     s 
248   end
249
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, ' ')
253   end
254
255   def html_hours(text)
256     text.gsub(%r{(\d+)\.(\d+)}, '<span class="hours hours-int">\1</span><span class="hours hours-dec">.\2</span>')
257   end
258
259   def authoring(created, author, options={})
260     l(options[:label] || :label_added_time_by, :author => link_to_user(author), :age => time_tag(created))
261   end
262   
263   def time_tag(time)
264     text = distance_of_time_in_words(Time.now, time)
265     if @project
266       link_to(text, {:controller => 'projects', :action => 'activity', :id => @project, :from => time.to_date}, :title => format_time(time))
267     else
268       content_tag('acronym', text, :title => format_time(time))
269     end
270   end
271
272   def syntax_highlight(name, content)
273     type = CodeRay::FileType[name]
274     type ? CodeRay.scan(content, type).html : h(content)
275   end
276
277   def to_path_param(path)
278     path.to_s.split(%r{[/\\]}).select {|p| !p.blank?}
279   end
280
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)
286
287     html = ''
288     if paginator.current.previous
289       html << link_to_remote_content_update('&#171; ' + l(:label_previous), url_param.merge(page_param => paginator.current.previous)) + ' '
290     end
291
292     html << (pagination_links_each(paginator, options) do |n|
293       link_to_remote_content_update(n.to_s, url_param.merge(page_param => n))
294     end || '')
295     
296     if paginator.current.next
297       html << ' ' + link_to_remote_content_update((l(:label_next) + ' &#187;'), url_param.merge(page_param => paginator.current.next))
298     end
299
300     unless count.nil?
301       html << [
302         " (#{paginator.current.first_item}-#{paginator.current.last_item}/#{count})",
303         per_page_links(paginator.items_per_page)
304       ].compact.join(' | ')
305     end
306
307     html
308   end
309   
310   def per_page_links(selected=nil)
311     url_param = params.dup
312     url_param.clear if url_param.has_key?(:set_filter)
313
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),
317                                              :method => :get},
318                                             {:href => url_for(url_param.merge(:per_page => n))})
319     end
320     links.size > 1 ? l(:label_display_per_page, links.join(', ')) : nil
321   end
322   
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))
328   end
329
330   def breadcrumb(*args)
331     elements = args.flatten
332     elements.any? ? content_tag('p', args.join(' &#187; ') + ' &#187; ', :class => 'breadcrumb') : nil
333   end
334   
335   def other_formats_links(&block)
336     concat('<p class="other-formats">' + l(:label_export_to))
337     yield Redmine::Views::OtherFormatsBuilder.new(self)
338     concat('</p>')
339   end
340   
341   def page_header_title
342     if @project.nil? || @project.new_record?
343       h(Setting.app_title)
344     else
345       b = []
346       ancestors = (@project.root? ? [] : @project.ancestors.visible)
347       if ancestors.any?
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
351           b << '&#8230;'
352           ancestors = ancestors[-2, 2]
353         end
354         b += ancestors.collect {|p| link_to(h(p), {:controller => 'projects', :action => 'show', :id => p, :jump => current_menu_item}, :class => 'ancestor') }
355       end
356       b << h(@project)
357       b.join(' &#187; ')
358     end
359   end
360
361   def html_title(*args)
362     if args.empty?
363       title = []
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(' - ')
368     else
369       @html_title ||= []
370       @html_title += args
371     end
372   end
373
374   def accesskey(s)
375     Redmine::AccessKeys.key_for s
376   end
377
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 : {}
384     case args.size
385     when 1
386       obj = options[:object]
387       text = args.shift
388     when 2
389       obj = args.shift
390       text = obj.send(args.shift).to_s
391     else
392       raise ArgumentError, 'invalid arguments to textilizable'
393     end
394     return '' if text.blank?
395
396     only_path = options.delete(:only_path) == false ? false : true
397
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)
400
401     if attachments
402       attachments = attachments.sort_by(&:created_on).reverse
403       text = text.gsub(/!((\<|\=|\>)?(\([^\)]+\))?(\[[^\]]+\])?(\{[^\}]+\})?)(\S+\.(bmp|gif|jpg|jpeg|png))!/i) do |m|
404         style = $1
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}!"
412         else
413           m
414         end
415       end
416     end
417
418     text = Redmine::WikiFormatting.to_html(Setting.text_formatting, text) { |macro, args| exec_macro(macro, obj, args) }
419
420     # different methods for formatting wiki links
421     case options[:wiki_links]
422     when :local
423       # used for local links to html files
424       format_wiki_link = Proc.new {|project, title, anchor| "#{title}.html" }
425     when :anchor
426       # used for single-file wiki export
427       format_wiki_link = Proc.new {|project, title, anchor| "##{title}" }
428     else
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) }
430     end
431
432     project = options[:project] || @project || (obj && obj.respond_to?(:project) ? obj.project : nil)
433
434     # Wiki links
435     #
436     # Examples:
437     #   [[mypage]]
438     #   [[mypage|mytext]]
439     # wiki links can refer other project wikis, using project name or identifier:
440     #   [[project:]] -> wiki starting page
441     #   [[project:|mytext]]
442     #   [[project:mypage]]
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
447       if esc.nil?
448         if page =~ /^([^\:]+)\:(.*)$/
449           link_project = Project.find_by_name($1) || Project.find_by_identifier($1)
450           page = $2
451           title ||= $1 if page.blank?
452         end
453
454         if link_project && link_project.wiki
455           # extract anchor
456           anchor = nil
457           if page =~ /^(.+?)\#(.+)$/
458             page, anchor = $1, $2
459           end
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')))
464         else
465           # project or wiki doesn't exist
466           all
467         end
468       else
469         all
470       end
471     end
472
473     # Redmine links
474     #
475     # Examples:
476     #   Issues:
477     #     #52 -> Link to issue #52
478     #   Changesets:
479     #     r52 -> Link to revision 52
480     #     commit:a85130f -> Link to scmid starting with a85130f
481     #   Documents:
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"
485     #   Versions:
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"
489     #   Attachments:
490     #     attachment:file.zip -> Link to the attachment of the current object named file.zip
491     #   Source files:
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
497     #  Forum messages:
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
501       link = nil
502       if esc.nil?
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))
508           end
509         elsif sep == '#'
510           oid = oid.to_i
511           case prefix
512           when nil
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})")
517             end
518           when 'document'
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},
521                                                 :class => 'document'
522             end
523           when 'version'
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},
526                                               :class => 'version'
527             end
528           when 'message'
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',
532                                                                 :action => 'show',
533                                                                 :board_id => message.board,
534                                                                 :id => message.root,
535                                                                 :anchor => (message.parent ? "message-#{message.id}" : nil)},
536                                                  :class => 'message'
537             end
538           end
539         elsif sep == ':'
540           # removes the double quotes if any
541           name = oid.gsub(%r{^"(.*)"$}, "\\1")
542           case prefix
543           when 'document'
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},
546                                                 :class => 'document'
547             end
548           when 'version'
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},
551                                               :class => 'version'
552             end
553           when 'commit'
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)
558             end
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),
565                                                       :rev => rev,
566                                                       :anchor => anchor,
567                                                       :format => (prefix == 'export' ? 'raw' : nil)},
568                                                      :class => (prefix == 'export' ? 'source download' : 'source')
569             end
570           when 'attachment'
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'
574             end
575           end
576         end
577       end
578       leading + (link || "#{prefix}#{sep}#{oid}")
579     end
580
581     text
582   end
583
584   # Same as Rails' simple_format helper without using paragraphs
585   def simple_format_without_paragraph(text)
586     text.to_s.
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
590   end
591
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 }
595   end
596
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)
600   end
601
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)
606   end
607
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?
612   end
613
614   def check_all_links(form_name)
615     link_to_function(l(:button_check_all), "checkAll('#{form_name}', true)") +
616     " | " +
617     link_to_function(l(:button_uncheck_all), "checkAll('#{form_name}', false)")
618   end
619
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] || ''
627     content_tag('table',
628       content_tag('tr',
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')
634   end
635
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
641     end
642     if options.delete(:disabled)
643       options.delete(:method)
644       options.delete(:confirm)
645       options.delete(:onclick)
646       options[:class] << ' disabled'
647       url = '#'
648     end
649     link_to name, url, options
650   end
651
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' });")
656   end
657
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
663         when 1
664           'Calendar._FD = 1;' # Monday
665         when 7
666           'Calendar._FD = 0;' # Sunday
667         else
668           '' # use language
669         end
670         
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')
676       end
677     end
678   end
679
680   def content_for(name, content = nil, &block)
681     @has_content ||= {}
682     @has_content[name] = true
683     super(name, content, &block)
684   end
685
686   def has_content?(name)
687     (@has_content && @has_content[name]) || false
688   end
689
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})
695       email = nil
696       if user.respond_to?(:mail)
697         email = user.mail
698       elsif user.to_s =~ %r{<(.+?)>}
699         email = $1
700       end
701       return gravatar(email.to_s.downcase, options) unless email.blank? rescue nil
702     end
703   end
704
705   private
706
707   def wiki_helper
708     helper = Redmine::WikiFormatting.helper_for(Setting.text_formatting)
709     extend helper
710     return self
711   end
712   
713   def link_to_remote_content_update(text, url_params)
714     link_to_remote(text,
715       {:url => url_params, :method => :get, :update => 'content', :complete => 'window.scrollTo(0,0)'},
716       {:href => url_for(:params => url_params)}
717     )
718   end
719   
720 end