OSDN Git Service

Refactor: use :id instead of :page when linking to Wiki Pages
[redminele/redmine.git] / app / helpers / application_helper.rb
index 27930ac..12f4b6e 100644 (file)
 # along with this program; if not, write to the Free Software
 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 
-require 'coderay'
-require 'coderay/helpers/file_type'
 require 'forwardable'
 require 'cgi'
 
 module ApplicationHelper
   include Redmine::WikiFormatting::Macros::Definitions
+  include Redmine::I18n
   include GravatarHelper::PublicMethods
 
   extend Forwardable
   def_delegators :wiki_helper, :wikitoolbar_for, :heads_for_wiki_formatter
 
-  def current_role
-    @current_role ||= User.current.role_for_project(@project)
-  end
-
   # Return true if user is authorized for controller/action, otherwise false
   def authorize_for(controller, action)
     User.current.allowed_to?({:controller => controller, :action => action}, @project)
   end
 
   # Display a link if user is authorized
+  #
+  # @param [String] name Anchor text (passed to link_to)
+  # @param [Hash] options Hash params. This will checked by authorize_for to see if the user is authorized
+  # @param [optional, Hash] html_options Options passed to link_to
+  # @param [optional, Hash] parameters_for_method_reference Extra parameters for link_to
   def link_to_if_authorized(name, options = {}, html_options = nil, *parameters_for_method_reference)
     link_to(name, options, html_options, *parameters_for_method_reference) if authorize_for(options[:controller] || params[:controller], options[:action])
   end
@@ -47,16 +47,45 @@ module ApplicationHelper
     link_to_remote(name, options, html_options) if authorize_for(url[:controller] || params[:controller], url[:action])
   end
 
-  # Display a link to user's account page
+  # Displays a link to user's account page if active
   def link_to_user(user, options={})
-    (user && !user.anonymous?) ? link_to(user.name(options[:format]), :controller => 'account', :action => 'show', :id => user) : 'Anonymous'
+    if user.is_a?(User)
+      name = h(user.name(options[:format]))
+      if user.active?
+        link_to name, :controller => 'users', :action => 'show', :id => user
+      else
+        name
+      end
+    else
+      h(user.to_s)
+    end
   end
 
+  # Displays a link to +issue+ with its subject.
+  # Examples:
+  # 
+  #   link_to_issue(issue)                        # => Defect #6: This is the subject
+  #   link_to_issue(issue, :truncate => 6)        # => Defect #6: This i...
+  #   link_to_issue(issue, :subject => false)     # => Defect #6
+  #   link_to_issue(issue, :project => true)      # => Foo - Defect #6
+  #
   def link_to_issue(issue, options={})
-    options[:class] ||= ''
-    options[:class] << ' issue'
-    options[:class] << ' closed' if issue.closed?
-    link_to "#{issue.tracker.name} ##{issue.id}", {:controller => "issues", :action => "show", :id => issue}, options
+    title = nil
+    subject = nil
+    if options[:subject] == false
+      title = truncate(issue.subject, :length => 60)
+    else
+      subject = issue.subject
+      if options[:truncate]
+        subject = truncate(subject, :length => options[:truncate])
+      end
+    end
+    s = link_to "#{issue.tracker} ##{issue.id}", {:controller => "issues", :action => "show", :id => issue}, 
+                                                 :class => issue.css_classes,
+                                                 :title => title
+    s << ": #{h subject}" if subject
+    s = "#{h issue.project} - " + s if options[:project]
+    s
   end
 
   # Generates a link to an attachment.
@@ -70,6 +99,32 @@ module ApplicationHelper
     link_to(h(text), {:controller => 'attachments', :action => action, :id => attachment, :filename => attachment.filename }, options)
   end
 
+  # Generates a link to a SCM revision
+  # Options:
+  # * :text - Link text (default to the formatted revision)
+  def link_to_revision(revision, project, options={})
+    text = options.delete(:text) || format_revision(revision)
+
+    link_to(text, {:controller => 'repositories', :action => 'revision', :id => project, :rev => revision}, :title => l(:label_revision_id, revision))
+  end
+
+  # Generates a link to a project if active
+  # Examples:
+  # 
+  #   link_to_project(project)                          # => link to the specified project overview
+  #   link_to_project(project, :action=>'settings')     # => link to project settings
+  #   link_to_project(project, {:only_path => false}, :class => "project") # => 3rd arg adds html options
+  #   link_to_project(project, {}, :class => "project") # => html options with default url (project overview)
+  #
+  def link_to_project(project, options={}, html_options = nil)
+    if project.active?
+      url = {:controller => 'projects', :action => 'show', :id => project}.merge(options)
+      link_to(h(project), url, html_options)
+    else
+      h(project)
+    end
+  end
+
   def toggle_link(name, id, options={})
     onclick = "Element.toggle('#{id}'); "
     onclick << (options[:focus] ? "Form.Element.focus('#{options[:focus]}'); " : "this.blur(); ")
@@ -89,26 +144,9 @@ module ApplicationHelper
     html_options[:onclick] = "promptToRemote('#{text}', '#{param}', '#{url_for(url)}'); return false;"
     link_to name, {}, html_options
   end
-
-  def format_date(date)
-    return nil unless date
-    # "Setting.date_format.size < 2" is a temporary fix (content of date_format setting changed)
-    @date_format ||= (Setting.date_format.blank? || Setting.date_format.size < 2 ? l(:general_fmt_date) : Setting.date_format)
-    date.strftime(@date_format)
-  end
-
-  def format_time(time, include_date = true)
-    return nil unless time
-    time = time.to_time if time.is_a?(String)
-    zone = User.current.time_zone
-    local = zone ? time.in_time_zone(zone) : (time.utc? ? time.localtime : time)
-    @date_format ||= (Setting.date_format.blank? || Setting.date_format.size < 2 ? l(:general_fmt_date) : Setting.date_format)
-    @time_format ||= (Setting.time_format.blank? ? l(:general_fmt_time) : Setting.time_format)
-    include_date ? local.strftime("#{@date_format} #{@time_format}") : local.strftime(@time_format)
-  end
   
   def format_activity_title(text)
-    h(truncate_single_line(text, 100))
+    h(truncate_single_line(text, :length => 100))
   end
   
   def format_activity_day(date)
@@ -116,16 +154,17 @@ module ApplicationHelper
   end
   
   def format_activity_description(text)
-    h(truncate(text.to_s, 120).gsub(%r{[\r\n]*<(pre|code)>.*$}m, '...')).gsub(/[\r\n]+/, "<br />")
+    h(truncate(text.to_s, :length => 120).gsub(%r{[\r\n]*<(pre|code)>.*$}m, '...')).gsub(/[\r\n]+/, "<br />")
   end
 
-  def distance_of_date_in_words(from_date, to_date = 0)
-    from_date = from_date.to_date if from_date.respond_to?(:to_date)
-    to_date = to_date.to_date if to_date.respond_to?(:to_date)
-    distance_in_days = (to_date - from_date).abs
-    lwr(:actionview_datehelper_time_in_words_day, distance_in_days)
+  def format_version_name(version)
+    if version.project == @project
+       h(version)
+    else
+      h("#{version.project} - #{version}")
+    end
   end
-
+  
   def due_date_distance_in_words(date)
     if date
       l((date < Date.today ? :label_roadmap_overdue : :label_roadmap_due_in), distance_of_date_in_words(Date.today, date))
@@ -138,7 +177,7 @@ module ApplicationHelper
       content << "<ul class=\"pages-hierarchy\">\n"
       pages[node].each do |page|
         content << "<li>"
-        content << link_to(h(page.pretty_title), {:controller => 'wiki', :action => 'index', :id => page.project, :page => page.title},
+        content << link_to(h(page.pretty_title), {:controller => 'wiki', :action => 'show', :project_id => page.project, :id => page.title},
                            :title => (page.respond_to?(:updated_on) ? l(:label_updated_time, distance_of_time_in_words(Time.now, page.updated_on)) : nil))
         content << "\n" + render_page_hierarchy(pages, page.id) if pages[page.id]
         content << "</li>\n"
@@ -157,15 +196,24 @@ module ApplicationHelper
     s
   end
   
+  # Renders tabs and their content
+  def render_tabs(tabs)
+    if tabs.any?
+      render :partial => 'common/tabs', :locals => {:tabs => tabs}
+    else
+      content_tag 'p', l(:label_no_data), :class => "nodata"
+    end
+  end
+  
   # Renders the project quick-jump box
   def render_project_jump_box
     # Retrieve them now to avoid a COUNT query
     projects = User.current.projects.all
     if projects.any?
       s = '<select onchange="if (this.value != \'\') { window.location = this.value; }">' +
-            "<option selected='selected'>#{ l(:label_jump_to_a_project) }</option>" +
-            '<option disabled="disabled">---</option>'
-      s << project_tree_options_for_select(projects) do |p|
+            "<option value=''>#{ l(:label_jump_to_a_project) }</option>" +
+            '<option value="" disabled="disabled">---</option>'
+      s << project_tree_options_for_select(projects, :selected => @project) do |p|
         { :value => url_for(:controller => 'projects', :action => 'show', :id => p, :jump => current_menu_item) }
       end
       s << '</select>'
@@ -177,7 +225,12 @@ module ApplicationHelper
     s = ''
     project_tree(projects) do |project, level|
       name_prefix = (level > 0 ? ('&nbsp;' * 2 * level + '&#187; ') : '')
-      tag_options = {:value => project.id, :selected => ((project == options[:selected]) ? 'selected' : nil)}
+      tag_options = {:value => project.id}
+      if project == options[:selected] || (options[:selected].respond_to?(:include?) && options[:selected].include?(project))
+        tag_options[:selected] = 'selected'
+      else
+        tag_options[:selected] = nil
+      end
       tag_options.merge!(yield(project)) if block_given?
       s << content_tag('option', name_prefix + h(project), tag_options)
     end
@@ -185,15 +238,10 @@ module ApplicationHelper
   end
   
   # Yields the given block for each project with its level in the tree
+  #
+  # Wrapper for Project#project_tree
   def project_tree(projects, &block)
-    ancestors = []
-    projects.sort_by(&:lft).each do |project|
-      while (ancestors.any? && !project.is_descendant_of?(ancestors.last)) 
-        ancestors.pop
-      end
-      yield project, ancestors.size
-      ancestors << project
-    end
+    Project.project_tree(projects, &block)
   end
   
   def project_nested_ul(projects, &block)
@@ -219,10 +267,28 @@ module ApplicationHelper
     end
     s
   end
+  
+  def principals_check_box_tags(name, principals)
+    s = ''
+    principals.sort.each do |principal|
+      s << "<label>#{ check_box_tag name, principal.id, false } #{h principal}</label>\n"
+    end
+    s 
+  end
 
   # Truncates and returns the string as a single line
   def truncate_single_line(string, *args)
-    truncate(string, *args).gsub(%r{[\r\n]+}m, ' ')
+    truncate(string.to_s, *args).gsub(%r{[\r\n]+}m, ' ')
+  end
+  
+  # Truncates at line break after 250 characters or options[:length]
+  def truncate_lines(string, options={})
+    length = options[:length] || 250
+    if string.to_s =~ /\A(.{#{length}}.*?)$/m
+      "#{$1}..."
+    else
+      string
+    end
   end
 
   def html_hours(text)
@@ -230,30 +296,20 @@ module ApplicationHelper
   end
 
   def authoring(created, author, options={})
-    time_tag = @project.nil? ? content_tag('acronym', distance_of_time_in_words(Time.now, created), :title => format_time(created)) :
-                               link_to(distance_of_time_in_words(Time.now, created), 
-                                       {:controller => 'projects', :action => 'activity', :id => @project, :from => created.to_date},
-                                       :title => format_time(created))
-    author_tag = (author.is_a?(User) && !author.anonymous?) ? link_to(h(author), :controller => 'account', :action => 'show', :id => author) : h(author || 'Anonymous')
-    l(options[:label] || :label_added_time_by, author_tag, time_tag)
-  end
-
-  def l_or_humanize(s, options={})
-    k = "#{options[:prefix]}#{s}".to_sym
-    l_has_string?(k) ? l(k) : s.to_s.humanize
+    l(options[:label] || :label_added_time_by, :author => link_to_user(author), :age => time_tag(created))
   end
-
-  def day_name(day)
-    l(:general_day_names).split(',')[day-1]
-  end
-
-  def month_name(month)
-    l(:actionview_datehelper_select_month_names).split(',')[month-1]
+  
+  def time_tag(time)
+    text = distance_of_time_in_words(Time.now, time)
+    if @project
+      link_to(text, {:controller => 'activities', :action => 'index', :id => @project, :from => time.to_date}, :title => format_time(time))
+    else
+      content_tag('acronym', text, :title => format_time(time))
+    end
   end
 
   def syntax_highlight(name, content)
-    type = CodeRay::FileType[name]
-    type ? CodeRay.scan(content, type).html : h(content)
+    Redmine::SyntaxHighlighting.highlight_by_filename(content, name)
   end
 
   def to_path_param(path)
@@ -262,9 +318,10 @@ module ApplicationHelper
 
   def pagination_links_full(paginator, count=nil, options={})
     page_param = options.delete(:page_param) || :page
+    per_page_links = options.delete(:per_page_links)
     url_param = params.dup
-    # don't reuse params if filters are present
-    url_param.clear if url_param.has_key?(:set_filter)
+    # don't reuse query params if filters are present
+    url_param.merge!(:fields => nil, :values => nil, :operators => nil) if url_param.delete(:set_filter)
 
     html = ''
     if paginator.current.previous
@@ -280,10 +337,10 @@ module ApplicationHelper
     end
 
     unless count.nil?
-      html << [
-        " (#{paginator.current.first_item}-#{paginator.current.last_item}/#{count})",
-        per_page_links(paginator.items_per_page)
-      ].compact.join(' | ')
+      html << " (#{paginator.current.first_item}-#{paginator.current.last_item}/#{count})"
+      if per_page_links != false && links = per_page_links(paginator.items_per_page)
+             html << " | #{links}"
+      end
     end
 
     html
@@ -301,6 +358,13 @@ module ApplicationHelper
     end
     links.size > 1 ? l(:label_display_per_page, links.join(', ')) : nil
   end
+  
+  def reorder_links(name, url)
+    link_to(image_tag('2uparrow.png',   :alt => l(:label_sort_highest)), url.merge({"#{name}[move_to]" => 'highest'}), :method => :post, :title => l(:label_sort_highest)) +
+    link_to(image_tag('1uparrow.png',   :alt => l(:label_sort_higher)),  url.merge({"#{name}[move_to]" => 'higher'}),  :method => :post, :title => l(:label_sort_higher)) +
+    link_to(image_tag('1downarrow.png', :alt => l(:label_sort_lower)),   url.merge({"#{name}[move_to]" => 'lower'}),   :method => :post, :title => l(:label_sort_lower)) +
+    link_to(image_tag('2downarrow.png', :alt => l(:label_sort_lowest)),  url.merge({"#{name}[move_to]" => 'lowest'}),  :method => :post, :title => l(:label_sort_lowest))
+  end
 
   def breadcrumb(*args)
     elements = args.flatten
@@ -308,9 +372,29 @@ module ApplicationHelper
   end
   
   def other_formats_links(&block)
-    concat('<p class="other-formats">' + l(:label_export_to), block.binding)
+    concat('<p class="other-formats">' + l(:label_export_to))
     yield Redmine::Views::OtherFormatsBuilder.new(self)
-    concat('</p>', block.binding)
+    concat('</p>')
+  end
+  
+  def page_header_title
+    if @project.nil? || @project.new_record?
+      h(Setting.app_title)
+    else
+      b = []
+      ancestors = (@project.root? ? [] : @project.ancestors.visible)
+      if ancestors.any?
+        root = ancestors.shift
+        b << link_to_project(root, {:jump => current_menu_item}, :class => 'root')
+        if ancestors.size > 2
+          b << '&#8230;'
+          ancestors = ancestors[-2, 2]
+        end
+        b += ancestors.collect {|p| link_to_project(p, {:jump => current_menu_item}, :class => 'ancestor') }
+      end
+      b << h(@project)
+      b.join(' &#187; ')
+    end
   end
 
   def html_title(*args)
@@ -319,13 +403,26 @@ module ApplicationHelper
       title << @project.name if @project
       title += @html_title if @html_title
       title << Setting.app_title
-      title.compact.join(' - ')
+      title.select {|t| !t.blank? }.join(' - ')
     else
       @html_title ||= []
       @html_title += args
     end
   end
 
+  # Returns the theme, controller name, and action as css classes for the
+  # HTML body.
+  def body_css_classes
+    css = []
+    if theme = Redmine::Themes.theme(Setting.ui_theme)
+      css << 'theme-' + theme.name
+    end
+
+    css << 'controller-' + params[:controller]
+    css << 'action-' + params[:action]
+    css.join(' ')
+  end
+
   def accesskey(s)
     Redmine::AccessKeys.key_for s
   end
@@ -342,62 +439,87 @@ module ApplicationHelper
       text = args.shift
     when 2
       obj = args.shift
-      text = obj.send(args.shift).to_s
+      attr = args.shift
+      text = obj.send(attr).to_s
     else
       raise ArgumentError, 'invalid arguments to textilizable'
     end
     return '' if text.blank?
-
+    project = options[:project] || @project || (obj && obj.respond_to?(:project) ? obj.project : nil)
     only_path = options.delete(:only_path) == false ? false : true
 
+    text = Redmine::WikiFormatting.to_html(Setting.text_formatting, text, :object => obj, :attribute => attr) { |macro, args| exec_macro(macro, obj, args) }
+      
+    parse_non_pre_blocks(text) do |text|
+      [:parse_inline_attachments, :parse_wiki_links, :parse_redmine_links].each do |method_name|
+        send method_name, text, project, obj, attr, only_path, options
+      end
+    end
+  end
+  
+  def parse_non_pre_blocks(text)
+    s = StringScanner.new(text)
+    tags = []
+    parsed = ''
+    while !s.eos?
+      s.scan(/(.*?)(<(\/)?(pre|code)(.*?)>|\z)/im)
+      text, full_tag, closing, tag = s[1], s[2], s[3], s[4]
+      if tags.empty?
+        yield text
+      end
+      parsed << text
+      if tag
+        if closing
+          if tags.last == tag.downcase
+            tags.pop
+          end
+        else
+          tags << tag.downcase
+        end
+        parsed << full_tag
+      end
+    end
+    # Close any non closing tags
+    while tag = tags.pop
+      parsed << "</#{tag}>"
+    end
+    parsed
+  end
+  
+  def parse_inline_attachments(text, project, obj, attr, only_path, options)
     # when using an image link, try to use an attachment, if possible
-    attachments = options[:attachments] || (obj && obj.respond_to?(:attachments) ? obj.attachments : nil)
-
-    if attachments
-      attachments = attachments.sort_by(&:created_on).reverse
-      text = text.gsub(/!((\<|\=|\>)?(\([^\)]+\))?(\[[^\]]+\])?(\{[^\}]+\})?)(\S+\.(bmp|gif|jpg|jpeg|png))!/i) do |m|
-        style = $1
-        filename = $6
-        rf = Regexp.new(Regexp.escape(filename),  Regexp::IGNORECASE)
+    if options[:attachments] || (obj && obj.respond_to?(:attachments))
+      attachments = nil
+      text.gsub!(/src="([^\/"]+\.(bmp|gif|jpg|jpeg|png))"(\s+alt="([^"]*)")?/i) do |m|
+        filename, ext, alt, alttext = $1.downcase, $2, $3, $4 
+        attachments ||= (options[:attachments] || obj.attachments).sort_by(&:created_on).reverse
         # search for the picture in attachments
-        if found = attachments.detect { |att| att.filename =~ rf }
+        if found = attachments.detect { |att| att.filename.downcase == filename }
           image_url = url_for :only_path => only_path, :controller => 'attachments', :action => 'download', :id => found
-          desc = found.description.to_s.gsub(/^([^\(\)]*).*$/, "\\1")
-          alt = desc.blank? ? nil : "(#{desc})"
-          "!#{style}#{image_url}#{alt}!"
+          desc = found.description.to_s.gsub('"', '')
+          if !desc.blank? && alttext.blank?
+            alt = " title=\"#{desc}\" alt=\"#{desc}\""
+          end
+          "src=\"#{image_url}\"#{alt}"
         else
-          "!#{style}#{filename}!"
+          m
         end
       end
     end
+  end
 
-    text = Redmine::WikiFormatting.to_html(Setting.text_formatting, text) { |macro, args| exec_macro(macro, obj, args) }
-
-    # different methods for formatting wiki links
-    case options[:wiki_links]
-    when :local
-      # used for local links to html files
-      format_wiki_link = Proc.new {|project, title, anchor| "#{title}.html" }
-    when :anchor
-      # used for single-file wiki export
-      format_wiki_link = Proc.new {|project, title, anchor| "##{title}" }
-    else
-      format_wiki_link = Proc.new {|project, title, anchor| url_for(:only_path => only_path, :controller => 'wiki', :action => 'index', :id => project, :page => title, :anchor => anchor) }
-    end
-
-    project = options[:project] || @project || (obj && obj.respond_to?(:project) ? obj.project : nil)
-
-    # Wiki links
-    #
-    # Examples:
-    #   [[mypage]]
-    #   [[mypage|mytext]]
-    # wiki links can refer other project wikis, using project name or identifier:
-    #   [[project:]] -> wiki starting page
-    #   [[project:|mytext]]
-    #   [[project:mypage]]
-    #   [[project:mypage|mytext]]
-    text = text.gsub(/(!)?(\[\[([^\]\n\|]+)(\|([^\]\n\|]+))?\]\])/) do |m|
+  # Wiki links
+  #
+  # Examples:
+  #   [[mypage]]
+  #   [[mypage|mytext]]
+  # wiki links can refer other project wikis, using project name or identifier:
+  #   [[project:]] -> wiki starting page
+  #   [[project:|mytext]]
+  #   [[project:mypage]]
+  #   [[project:mypage|mytext]]
+  def parse_wiki_links(text, project, obj, attr, only_path, options)
+    text.gsub!(/(!)?(\[\[([^\]\n\|]+)(\|([^\]\n\|]+))?\]\])/) do |m|
       link_project = project
       esc, all, page, title = $1, $2, $3, $5
       if esc.nil?
@@ -415,62 +537,68 @@ module ApplicationHelper
           end
           # check if page exists
           wiki_page = link_project.wiki.find_page(page)
-          link_to((title || page), format_wiki_link.call(link_project, Wiki.titleize(page), anchor),
-                                   :class => ('wiki-page' + (wiki_page ? '' : ' new')))
+          url = case options[:wiki_links]
+            when :local; "#{title}.html"
+            when :anchor; "##{title}"   # used for single-file wiki export
+            else
+              url_for(:only_path => only_path, :controller => 'wiki', :action => 'show', :project_id => link_project, :id => Wiki.titleize(page), :anchor => anchor)
+            end
+          link_to((title || page), url, :class => ('wiki-page' + (wiki_page ? '' : ' new')))
         else
           # project or wiki doesn't exist
-          title || page
+          all
         end
       else
         all
       end
     end
-
-    # Redmine links
-    #
-    # Examples:
-    #   Issues:
-    #     #52 -> Link to issue #52
-    #   Changesets:
-    #     r52 -> Link to revision 52
-    #     commit:a85130f -> Link to scmid starting with a85130f
-    #   Documents:
-    #     document#17 -> Link to document with id 17
-    #     document:Greetings -> Link to the document with title "Greetings"
-    #     document:"Some document" -> Link to the document with title "Some document"
-    #   Versions:
-    #     version#3 -> Link to version with id 3
-    #     version:1.0.0 -> Link to version named "1.0.0"
-    #     version:"1.0 beta 2" -> Link to version named "1.0 beta 2"
-    #   Attachments:
-    #     attachment:file.zip -> Link to the attachment of the current object named file.zip
-    #   Source files:
-    #     source:some/file -> Link to the file located at /some/file in the project's repository
-    #     source:some/file@52 -> Link to the file's revision 52
-    #     source:some/file#L120 -> Link to line 120 of the file
-    #     source:some/file@52#L120 -> Link to line 120 of the file's revision 52
-    #     export:some/file -> Force the download of the file
-    #  Forum messages:
-    #     message#1218 -> Link to message with id 1218
-    text = text.gsub(%r{([\s\(,\-\>]|^)(!)?(attachment|document|version|commit|source|export|message)?((#|r)(\d+)|(:)([^"\s<>][^\s<>]*?|"[^"]+?"))(?=(?=[[:punct:]]\W)|\s|<|$)}) do |m|
-      leading, esc, prefix, sep, oid = $1, $2, $3, $5 || $7, $6 || $8
+  end
+  
+  # Redmine links
+  #
+  # Examples:
+  #   Issues:
+  #     #52 -> Link to issue #52
+  #   Changesets:
+  #     r52 -> Link to revision 52
+  #     commit:a85130f -> Link to scmid starting with a85130f
+  #   Documents:
+  #     document#17 -> Link to document with id 17
+  #     document:Greetings -> Link to the document with title "Greetings"
+  #     document:"Some document" -> Link to the document with title "Some document"
+  #   Versions:
+  #     version#3 -> Link to version with id 3
+  #     version:1.0.0 -> Link to version named "1.0.0"
+  #     version:"1.0 beta 2" -> Link to version named "1.0 beta 2"
+  #   Attachments:
+  #     attachment:file.zip -> Link to the attachment of the current object named file.zip
+  #   Source files:
+  #     source:some/file -> Link to the file located at /some/file in the project's repository
+  #     source:some/file@52 -> Link to the file's revision 52
+  #     source:some/file#L120 -> Link to line 120 of the file
+  #     source:some/file@52#L120 -> Link to line 120 of the file's revision 52
+  #     export:some/file -> Force the download of the file
+  #  Forum messages:
+  #     message#1218 -> Link to message with id 1218
+  def parse_redmine_links(text, project, obj, attr, only_path, options)
+    text.gsub!(%r{([\s\(,\-\[\>]|^)(!)?(attachment|document|version|commit|source|export|message|project)?((#|r)(\d+)|(:)([^"\s<>][^\s<>]*?|"[^"]+?"))(?=(?=[[:punct:]]\W)|,|\s|\]|<|$)}) do |m|
+      leading, esc, prefix, sep, identifier = $1, $2, $3, $5 || $7, $6 || $8
       link = nil
       if esc.nil?
         if prefix.nil? && sep == 'r'
-          if project && (changeset = project.changesets.find_by_revision(oid))
-            link = link_to("r#{oid}", {:only_path => only_path, :controller => 'repositories', :action => 'revision', :id => project, :rev => oid},
+          if project && (changeset = project.changesets.find_by_revision(identifier))
+            link = link_to("r#{identifier}", {:only_path => only_path, :controller => 'repositories', :action => 'revision', :id => project, :rev => changeset.revision},
                                       :class => 'changeset',
-                                      :title => truncate_single_line(changeset.comments, 100))
+                                      :title => truncate_single_line(changeset.comments, :length => 100))
           end
         elsif sep == '#'
-          oid = oid.to_i
+          oid = identifier.to_i
           case prefix
           when nil
-            if issue = Issue.find_by_id(oid, :include => [:project, :status], :conditions => Project.visible_by(User.current))
+            if issue = Issue.visible.find_by_id(oid, :include => :status)
               link = link_to("##{oid}", {:only_path => only_path, :controller => 'issues', :action => 'show', :id => oid},
-                                        :class => (issue.closed? ? 'issue closed' : 'issue'),
-                                        :title => "#{truncate(issue.subject, 100)} (#{issue.status.name})")
-              link = content_tag('del', link) if issue.closed?
+                                        :class => issue.css_classes,
+                                        :title => "#{truncate(issue.subject, :length => 100)} (#{issue.status.name})")
             end
           when 'document'
             if document = Document.find_by_id(oid, :include => [:project], :conditions => Project.visible_by(User.current))
@@ -484,7 +612,7 @@ module ApplicationHelper
             end
           when 'message'
             if message = Message.find_by_id(oid, :include => [:parent, {:board => :project}], :conditions => Project.visible_by(User.current))
-              link = link_to h(truncate(message.subject, 60)), {:only_path => only_path,
+              link = link_to h(truncate(message.subject, :length => 60)), {:only_path => only_path,
                                                                 :controller => 'messages',
                                                                 :action => 'show',
                                                                 :board_id => message.board,
@@ -492,10 +620,14 @@ module ApplicationHelper
                                                                 :anchor => (message.parent ? "message-#{message.id}" : nil)},
                                                  :class => 'message'
             end
+          when 'project'
+            if p = Project.visible.find_by_id(oid)
+              link = link_to_project(p, {:only_path => only_path}, :class => 'project')
+            end
           end
         elsif sep == ':'
           # removes the double quotes if any
-          name = oid.gsub(%r{^"(.*)"$}, "\\1")
+          name = identifier.gsub(%r{^"(.*)"$}, "\\1")
           case prefix
           when 'document'
             if project && document = project.documents.find_by_title(name)
@@ -511,7 +643,7 @@ module ApplicationHelper
             if project && (changeset = project.changesets.find(:first, :conditions => ["scmid LIKE ?", "#{name}%"]))
               link = link_to h("#{name}"), {:only_path => only_path, :controller => 'repositories', :action => 'revision', :id => project, :rev => changeset.revision},
                                            :class => 'changeset',
-                                           :title => truncate_single_line(changeset.comments, 100)
+                                           :title => truncate_single_line(changeset.comments, :length => 100)
             end
           when 'source', 'export'
             if project && project.repository
@@ -525,17 +657,20 @@ module ApplicationHelper
                                                      :class => (prefix == 'export' ? 'source download' : 'source')
             end
           when 'attachment'
+            attachments = options[:attachments] || (obj && obj.respond_to?(:attachments) ? obj.attachments : nil)
             if attachments && attachment = attachments.detect {|a| a.filename == name }
               link = link_to h(attachment.filename), {:only_path => only_path, :controller => 'attachments', :action => 'download', :id => attachment},
                                                      :class => 'attachment'
             end
+          when 'project'
+            if p = Project.visible.find(:first, :conditions => ["identifier = :s OR LOWER(name) = :s", {:s => name.downcase}])
+              link = link_to_project(p, {:only_path => only_path}, :class => 'project')
+            end
           end
         end
       end
-      leading + (link || "#{prefix}#{sep}#{oid}")
+      leading + (link || "#{prefix}#{sep}#{identifier}")
     end
-
-    text
   end
 
   # Same as Rails' simple_format helper without using paragraphs
@@ -546,46 +681,9 @@ module ApplicationHelper
       gsub(/([^\n]\n)(?=[^\n])/, '\1<br />')  # 1 newline   -> br
   end
 
-  def error_messages_for(object_name, options = {})
-    options = options.symbolize_keys
-    object = instance_variable_get("@#{object_name}")
-    if object && !object.errors.empty?
-      # build full_messages here with controller current language
-      full_messages = []
-      object.errors.each do |attr, msg|
-        next if msg.nil?
-        msg = msg.first if msg.is_a? Array
-        if attr == "base"
-          full_messages << l(msg)
-        else
-          full_messages << "&#171; " + (l_has_string?("field_" + attr) ? l("field_" + attr) : object.class.human_attribute_name(attr)) + " &#187; " + l(msg) unless attr == "custom_values"
-        end
-      end
-      # retrieve custom values error messages
-      if object.errors[:custom_values]
-        object.custom_values.each do |v|
-          v.errors.each do |attr, msg|
-            next if msg.nil?
-            msg = msg.first if msg.is_a? Array
-            full_messages << "&#171; " + v.custom_field.name + " &#187; " + l(msg)
-          end
-        end
-      end
-      content_tag("div",
-        content_tag(
-          options[:header_tag] || "span", lwr(:gui_validation_error, full_messages.length) + ":"
-        ) +
-        content_tag("ul", full_messages.collect { |msg| content_tag("li", msg) }),
-        "id" => options[:id] || "errorExplanation", "class" => options[:class] || "errorExplanation"
-      )
-    else
-      ""
-    end
-  end
-
   def lang_options_for_select(blank=true)
     (blank ? [["(auto)", ""]] : []) +
-      GLoc.valid_languages.collect{|lang| [ ll(lang.to_s, :general_lang_name), lang.to_s]}.sort{|x,y| x.last <=> y.last }
+      valid_languages.collect{|lang| [ ll(lang.to_s, :general_lang_name), lang.to_s]}.sort{|x,y| x.last <=> y.last }
   end
 
   def label_tag_for(name, option_tags = nil, options = {})
@@ -613,18 +711,41 @@ module ApplicationHelper
 
   def progress_bar(pcts, options={})
     pcts = [pcts, pcts] unless pcts.is_a?(Array)
+    pcts = pcts.collect(&:round)
     pcts[1] = pcts[1] - pcts[0]
     pcts << (100 - pcts[1] - pcts[0])
     width = options[:width] || '100px;'
     legend = options[:legend] || ''
     content_tag('table',
       content_tag('tr',
-        (pcts[0] > 0 ? content_tag('td', '', :style => "width: #{pcts[0].floor}%;", :class => 'closed') : '') +
-        (pcts[1] > 0 ? content_tag('td', '', :style => "width: #{pcts[1].floor}%;", :class => 'done') : '') +
-        (pcts[2] > 0 ? content_tag('td', '', :style => "width: #{pcts[2].floor}%;", :class => 'todo') : '')
+        (pcts[0] > 0 ? content_tag('td', '', :style => "width: #{pcts[0]}%;", :class => 'closed') : '') +
+        (pcts[1] > 0 ? content_tag('td', '', :style => "width: #{pcts[1]}%;", :class => 'done') : '') +
+        (pcts[2] > 0 ? content_tag('td', '', :style => "width: #{pcts[2]}%;", :class => 'todo') : '')
       ), :class => 'progress', :style => "width: #{width};") +
       content_tag('p', legend, :class => 'pourcent')
   end
+  
+  def checked_image(checked=true)
+    if checked
+      image_tag 'toggle_check.png'
+    end
+  end
+  
+  def context_menu(url)
+    unless @context_menu_included
+      content_for :header_tags do
+        javascript_include_tag('context_menu') +
+          stylesheet_link_tag('context_menu')
+      end
+      if l(:direction) == 'rtl'
+        content_for :header_tags do
+          stylesheet_link_tag('context_menu_rtl')
+        end
+      end
+      @context_menu_included = true
+    end
+    javascript_tag "new ContextMenu('#{ url_for(url) }')"
+  end
 
   def context_menu_link(name, url, options={})
     options[:class] ||= ''
@@ -652,8 +773,18 @@ module ApplicationHelper
     unless @calendar_headers_tags_included
       @calendar_headers_tags_included = true
       content_for :header_tags do
+        start_of_week = case Setting.start_of_week.to_i
+        when 1
+          'Calendar._FD = 1;' # Monday
+        when 7
+          'Calendar._FD = 0;' # Sunday
+        else
+          '' # use language
+        end
+        
         javascript_include_tag('calendar/calendar') +
-        javascript_include_tag("calendar/lang/calendar-#{current_language}.js") +
+        javascript_include_tag("calendar/lang/calendar-#{current_language.to_s.downcase}.js") +
+        javascript_tag(start_of_week) +  
         javascript_include_tag('calendar/calendar-setup') +
         stylesheet_link_tag('calendar')
       end
@@ -674,6 +805,7 @@ module ApplicationHelper
   # +user+ can be a User or a string that will be scanned for an email address (eg. 'joe <joe@foo.bar>')
   def avatar(user, options = { })
     if Setting.gravatar_enabled?
+      options.merge!({:ssl => (defined?(request) && request.ssl?), :default => Setting.gravatar_default})
       email = nil
       if user.respond_to?(:mail)
         email = user.mail
@@ -681,9 +813,15 @@ module ApplicationHelper
         email = $1
       end
       return gravatar(email.to_s.downcase, options) unless email.blank? rescue nil
+    else
+      ''
     end
   end
 
+  def favicon
+    "<link rel='shortcut icon' href='#{image_path('/favicon.ico')}' />"
+  end
+
   private
 
   def wiki_helper