Chris@909: # encoding: utf-8 Chris@909: # chris@37: # Redmine - project management software Chris@1494: # Copyright (C) 2006-2014 Jean-Philippe Lang Chris@0: # Chris@0: # This program is free software; you can redistribute it and/or Chris@0: # modify it under the terms of the GNU General Public License Chris@0: # as published by the Free Software Foundation; either version 2 Chris@0: # of the License, or (at your option) any later version. Chris@0: # Chris@0: # This program is distributed in the hope that it will be useful, Chris@0: # but WITHOUT ANY WARRANTY; without even the implied warranty of Chris@0: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the Chris@0: # GNU General Public License for more details. Chris@0: # Chris@0: # You should have received a copy of the GNU General Public License Chris@0: # along with this program; if not, write to the Free Software Chris@0: # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. Chris@0: Chris@0: require 'forwardable' Chris@0: require 'cgi' Chris@0: Chris@0: module ApplicationHelper Chris@0: include Redmine::WikiFormatting::Macros::Definitions Chris@0: include Redmine::I18n Chris@0: include GravatarHelper::PublicMethods Chris@1464: include Redmine::Pagination::Helper Chris@0: Chris@0: extend Forwardable Chris@0: def_delegators :wiki_helper, :wikitoolbar_for, :heads_for_wiki_formatter Chris@0: Chris@0: # Return true if user is authorized for controller/action, otherwise false Chris@0: def authorize_for(controller, action) Chris@0: User.current.allowed_to?({:controller => controller, :action => action}, @project) Chris@0: end Chris@0: Chris@0: # Display a link if user is authorized chris@22: # chris@22: # @param [String] name Anchor text (passed to link_to) chris@37: # @param [Hash] options Hash params. This will checked by authorize_for to see if the user is authorized chris@22: # @param [optional, Hash] html_options Options passed to link_to chris@22: # @param [optional, Hash] parameters_for_method_reference Extra parameters for link_to Chris@0: def link_to_if_authorized(name, options = {}, html_options = nil, *parameters_for_method_reference) chris@37: link_to(name, options, html_options, *parameters_for_method_reference) if authorize_for(options[:controller] || params[:controller], options[:action]) Chris@0: end Chris@0: Chris@0: # Displays a link to user's account page if active Chris@0: def link_to_user(user, options={}) Chris@0: if user.is_a?(User) Chris@0: name = h(user.name(options[:format])) Chris@1115: if user.active? || (User.current.admin? && user.logged?) Chris@1115: link_to name, user_path(user), :class => user.css_classes Chris@0: else Chris@0: name Chris@0: end Chris@0: else Chris@0: h(user.to_s) Chris@0: end Chris@0: end Chris@0: Chris@0: # Displays a link to +issue+ with its subject. Chris@0: # Examples: Chris@441: # Chris@0: # link_to_issue(issue) # => Defect #6: This is the subject Chris@0: # link_to_issue(issue, :truncate => 6) # => Defect #6: This i... Chris@0: # link_to_issue(issue, :subject => false) # => Defect #6 Chris@0: # link_to_issue(issue, :project => true) # => Foo - Defect #6 Chris@1115: # link_to_issue(issue, :subject => false, :tracker => false) # => #6 Chris@0: # Chris@0: def link_to_issue(issue, options={}) Chris@0: title = nil Chris@0: subject = nil Chris@1115: text = options[:tracker] == false ? "##{issue.id}" : "#{issue.tracker} ##{issue.id}" Chris@0: if options[:subject] == false Chris@1517: title = issue.subject.truncate(60) Chris@0: else Chris@0: subject = issue.subject Chris@1517: if truncate_length = options[:truncate] Chris@1517: subject = subject.truncate(truncate_length) Chris@0: end Chris@0: end Chris@1464: only_path = options[:only_path].nil? ? true : options[:only_path] Chris@1517: s = link_to(text, issue_path(issue, :only_path => only_path), Chris@1517: :class => issue.css_classes, :title => title) Chris@1115: s << h(": #{subject}") if subject Chris@1115: s = h("#{issue.project} - ") + s if options[:project] Chris@0: s Chris@0: end Chris@0: Chris@0: # Generates a link to an attachment. Chris@0: # Options: Chris@0: # * :text - Link text (default to attachment filename) Chris@0: # * :download - Force download (default: false) Chris@0: def link_to_attachment(attachment, options={}) Chris@0: text = options.delete(:text) || attachment.filename Chris@1464: route_method = options.delete(:download) ? :download_named_attachment_path : :named_attachment_path Chris@1464: html_options = options.slice!(:only_path) Chris@1464: url = send(route_method, attachment, attachment.filename, options) Chris@1464: link_to text, url, html_options Chris@0: end Chris@0: Chris@0: # Generates a link to a SCM revision Chris@0: # Options: Chris@0: # * :text - Link text (default to the formatted revision) Chris@1115: def link_to_revision(revision, repository, options={}) Chris@1115: if repository.is_a?(Project) Chris@1115: repository = repository.repository Chris@1115: end Chris@0: text = options.delete(:text) || format_revision(revision) Chris@119: rev = revision.respond_to?(:identifier) ? revision.identifier : revision Chris@1115: link_to( Chris@1115: h(text), Chris@1115: {:controller => 'repositories', :action => 'revision', :id => repository.project, :repository_id => repository.identifier_param, :rev => rev}, Chris@1115: :title => l(:label_revision_id, format_revision(revision)) Chris@1115: ) Chris@0: end Chris@441: Chris@210: # Generates a link to a message Chris@210: def link_to_message(message, options={}, html_options = nil) Chris@210: link_to( Chris@1517: message.subject.truncate(60), Chris@1464: board_message_path(message.board_id, message.parent_id || message.id, { Chris@210: :r => (message.parent_id && message.id), Chris@210: :anchor => (message.parent_id ? "message-#{message.id}" : nil) Chris@1464: }.merge(options)), Chris@210: html_options Chris@210: ) Chris@210: end Chris@0: Chris@14: # Generates a link to a project if active Chris@14: # Examples: Chris@441: # Chris@14: # link_to_project(project) # => link to the specified project overview Chris@14: # link_to_project(project, {:only_path => false}, :class => "project") # => 3rd arg adds html options Chris@14: # link_to_project(project, {}, :class => "project") # => html options with default url (project overview) Chris@14: # Chris@14: def link_to_project(project, options={}, html_options = nil) Chris@1115: if project.archived? Chris@1464: h(project.name) Chris@1464: elsif options.key?(:action) Chris@1464: ActiveSupport::Deprecation.warn "#link_to_project with :action option is deprecated and will be removed in Redmine 3.0." Chris@1464: url = {:controller => 'projects', :action => 'show', :id => project}.merge(options) Chris@1464: link_to project.name, url, html_options Chris@1115: else Chris@1464: link_to project.name, project_path(project, options), html_options Chris@1464: end Chris@1464: end Chris@1464: Chris@1464: # Generates a link to a project settings if active Chris@1464: def link_to_project_settings(project, options={}, html_options=nil) Chris@1464: if project.active? Chris@1464: link_to project.name, settings_project_path(project, options), html_options Chris@1464: elsif project.archived? Chris@1464: h(project.name) Chris@1464: else Chris@1464: link_to project.name, project_path(project, options), html_options Chris@14: end Chris@14: end Chris@14: Chris@1517: # Helper that formats object for html or text rendering Chris@1517: def format_object(object, html=true) Chris@1517: case object.class.name Chris@1517: when 'Array' Chris@1517: object.map {|o| format_object(o, html)}.join(', ').html_safe Chris@1517: when 'Time' Chris@1517: format_time(object) Chris@1517: when 'Date' Chris@1517: format_date(object) Chris@1517: when 'Fixnum' Chris@1517: object.to_s Chris@1517: when 'Float' Chris@1517: sprintf "%.2f", object Chris@1517: when 'User' Chris@1517: html ? link_to_user(object) : object.to_s Chris@1517: when 'Project' Chris@1517: html ? link_to_project(object) : object.to_s Chris@1517: when 'Version' Chris@1517: html ? link_to(object.name, version_path(object)) : object.to_s Chris@1517: when 'TrueClass' Chris@1517: l(:general_text_Yes) Chris@1517: when 'FalseClass' Chris@1517: l(:general_text_No) Chris@1517: when 'Issue' Chris@1517: object.visible? && html ? link_to_issue(object) : "##{object.id}" Chris@1517: when 'CustomValue', 'CustomFieldValue' Chris@1517: if object.custom_field Chris@1517: f = object.custom_field.format.formatted_custom_value(self, object, html) Chris@1517: if f.nil? || f.is_a?(String) Chris@1517: f Chris@1517: else Chris@1517: format_object(f, html) Chris@1517: end Chris@1517: else Chris@1517: object.value.to_s Chris@1517: end Chris@1517: else Chris@1517: html ? h(object) : object.to_s Chris@1517: end Chris@1517: end Chris@1517: Chris@1115: def wiki_page_path(page, options={}) Chris@1115: url_for({:controller => 'wiki', :action => 'show', :project_id => page.project, :id => page.title}.merge(options)) Chris@1115: end Chris@1115: Chris@1115: def thumbnail_tag(attachment) Chris@1464: link_to image_tag(thumbnail_path(attachment)), Chris@1464: named_attachment_path(attachment, attachment.filename), Chris@1115: :title => attachment.filename Chris@1115: end Chris@1115: Chris@0: def toggle_link(name, id, options={}) Chris@1115: onclick = "$('##{id}').toggle(); " Chris@1115: onclick << (options[:focus] ? "$('##{options[:focus]}').focus(); " : "this.blur(); ") Chris@0: onclick << "return false;" Chris@0: link_to(name, "#", :onclick => onclick) Chris@0: end Chris@0: Chris@0: def image_to_function(name, function, html_options = {}) Chris@0: html_options.symbolize_keys! Chris@0: tag(:input, html_options.merge({ Chris@0: :type => "image", :src => image_path(name), Chris@0: :onclick => (html_options[:onclick] ? "#{html_options[:onclick]}; " : "") + "#{function};" Chris@0: })) Chris@0: end Chris@0: Chris@0: def format_activity_title(text) Chris@1517: h(truncate_single_line_raw(text, 100)) Chris@0: end Chris@441: Chris@0: def format_activity_day(date) Chris@1115: date == User.current.today ? l(:label_today).titleize : format_date(date) Chris@0: end Chris@441: Chris@0: def format_activity_description(text) Chris@1517: h(text.to_s.truncate(120).gsub(%r{[\r\n]*<(pre|code)>.*$}m, '...') Chris@1115: ).gsub(/[\r\n]+/, "
").html_safe Chris@0: end Chris@0: Chris@0: def format_version_name(version) Chris@0: if version.project == @project Chris@1464: h(version) Chris@0: else Chris@0: h("#{version.project} - #{version}") Chris@0: end Chris@0: end Chris@441: Chris@0: def due_date_distance_in_words(date) Chris@0: if date Chris@0: l((date < Date.today ? :label_roadmap_overdue : :label_roadmap_due_in), distance_of_date_in_words(Date.today, date)) Chris@0: end Chris@0: end Chris@0: Chris@1115: # Renders a tree of projects as a nested set of unordered lists Chris@1115: # The given collection may be a subset of the whole project tree Chris@1115: # (eg. some intermediate nodes are private and can not be seen) Chris@1115: def render_project_nested_lists(projects) Chris@1115: s = '' Chris@1115: if projects.any? Chris@1115: ancestors = [] Chris@1115: original_project = @project Chris@1115: projects.sort_by(&:lft).each do |project| Chris@1115: # set the project environment to please macros. Chris@1115: @project = project Chris@1115: if (ancestors.empty? || project.is_descendant_of?(ancestors.last)) Chris@1115: s << "\n" Chris@1115: end Chris@1115: end Chris@1115: classes = (ancestors.empty? ? 'root' : 'child') Chris@1115: s << "
  • " Chris@1115: s << h(block_given? ? yield(project) : project.name) Chris@1115: s << "
    \n" Chris@1115: ancestors << project Chris@1115: end Chris@1115: s << ("
  • \n" * ancestors.size) Chris@1115: @project = original_project Chris@1115: end Chris@1115: s.html_safe Chris@1115: end Chris@1115: Chris@441: def render_page_hierarchy(pages, node=nil, options={}) Chris@0: content = '' Chris@0: if pages[node] Chris@0: content << "\n" Chris@0: end Chris@909: content.html_safe Chris@0: end Chris@441: Chris@0: # Renders flash messages Chris@0: def render_flash_messages Chris@0: s = '' Chris@0: flash.each do |k,v| Chris@1115: s << content_tag('div', v.html_safe, :class => "flash #{k}", :id => "flash_#{k}") Chris@0: end Chris@909: s.html_safe Chris@0: end Chris@441: Chris@0: # Renders tabs and their content Chris@1517: def render_tabs(tabs, selected=params[:tab]) Chris@0: if tabs.any? Chris@1517: unless tabs.detect {|tab| tab[:name] == selected} Chris@1517: selected = nil Chris@1517: end Chris@1517: selected ||= tabs.first[:name] Chris@1517: render :partial => 'common/tabs', :locals => {:tabs => tabs, :selected_tab => selected} Chris@0: else Chris@0: content_tag 'p', l(:label_no_data), :class => "nodata" Chris@0: end Chris@0: end Chris@441: Chris@0: # Renders the project quick-jump box Chris@0: def render_project_jump_box Chris@441: return unless User.current.logged? Chris@1115: projects = User.current.memberships.collect(&:project).compact.select(&:active?).uniq Chris@0: if projects.any? Chris@1115: options = Chris@1115: ("" + Chris@1115: '').html_safe Chris@1115: Chris@1115: options << project_tree_options_for_select(projects, :selected => @project) do |p| Chris@1115: { :value => project_path(:id => p, :jump => current_menu_item) } Chris@0: end Chris@1115: Chris@1115: select_tag('project_quick_jump_box', options, :onchange => 'if (this.value != \'\') { window.location = this.value; }') Chris@0: end Chris@0: end Chris@441: Chris@0: def project_tree_options_for_select(projects, options = {}) Chris@0: s = '' Chris@0: project_tree(projects) do |project, level| Chris@1115: name_prefix = (level > 0 ? ' ' * 2 * level + '» ' : '').html_safe Chris@0: tag_options = {:value => project.id} Chris@0: if project == options[:selected] || (options[:selected].respond_to?(:include?) && options[:selected].include?(project)) Chris@0: tag_options[:selected] = 'selected' Chris@0: else Chris@0: tag_options[:selected] = nil Chris@0: end Chris@0: tag_options.merge!(yield(project)) if block_given? Chris@0: s << content_tag('option', name_prefix + h(project), tag_options) Chris@0: end Chris@909: s.html_safe Chris@0: end Chris@441: Chris@0: # Yields the given block for each project with its level in the tree chris@37: # chris@37: # Wrapper for Project#project_tree Chris@0: def project_tree(projects, &block) chris@37: Project.project_tree(projects, &block) Chris@0: end Chris@441: Chris@0: def principals_check_box_tags(name, principals) Chris@0: s = '' Chris@1484: Chris@1294: principals.sort.each do |principal| luis@1120: luis@1120: if principal.type == "User" Chris@1484: s << "\n" luis@948: else Chris@1484: s << "\n" luis@948: end luis@1120: Chris@0: end Chris@909: s.html_safe Chris@909: end Chris@909: Chris@909: # Returns a string for users/groups option tags Chris@909: def principals_options_for_select(collection, selected=nil) Chris@909: s = '' Chris@1115: if collection.include?(User.current) Chris@1115: s << content_tag('option', "<< #{l(:label_me)} >>", :value => User.current.id) Chris@1115: end Chris@909: groups = '' Chris@909: collection.sort.each do |element| Chris@1464: selected_attribute = ' selected="selected"' if option_value_selected?(element, selected) || element.id.to_s == selected Chris@909: (element.is_a?(Group) ? groups : s) << %() Chris@909: end Chris@909: unless groups.empty? Chris@909: s << %(#{groups}) Chris@909: end Chris@1115: s.html_safe Chris@1115: end Chris@1115: Chris@1115: # Options for the new membership projects combo-box Chris@1115: def options_for_membership_project_select(principal, projects) Chris@1115: options = content_tag('option', "--- #{l(:actionview_instancetag_blank_option)} ---") Chris@1115: options << project_tree_options_for_select(projects) do |p| Chris@1464: {:disabled => principal.projects.to_a.include?(p)} Chris@1115: end Chris@1115: options Chris@0: end Chris@0: Chris@1464: def option_tag(name, text, value, selected=nil, options={}) Chris@1464: content_tag 'option', value, options.merge(:value => value, :selected => (value == selected)) Chris@1464: end Chris@1464: Chris@0: # Truncates and returns the string as a single line Chris@0: def truncate_single_line(string, *args) Chris@1517: ActiveSupport::Deprecation.warn( Chris@1517: "ApplicationHelper#truncate_single_line is deprecated and will be removed in Rails 4 poring") Chris@1517: # Rails 4 ActionView::Helpers::TextHelper#truncate escapes. Chris@1517: # So, result is broken. Chris@0: truncate(string.to_s, *args).gsub(%r{[\r\n]+}m, ' ') Chris@0: end Chris@441: Chris@1517: def truncate_single_line_raw(string, length) Chris@1517: string.truncate(length).gsub(%r{[\r\n]+}m, ' ') Chris@1517: end Chris@1517: Chris@0: # Truncates at line break after 250 characters or options[:length] Chris@0: def truncate_lines(string, options={}) Chris@0: length = options[:length] || 250 Chris@0: if string.to_s =~ /\A(.{#{length}}.*?)$/m Chris@0: "#{$1}..." Chris@0: else Chris@0: string Chris@0: end Chris@0: end Chris@0: Chris@1115: def anchor(text) Chris@1115: text.to_s.gsub(' ', '_') Chris@1115: end Chris@1115: Chris@0: def html_hours(text) Chris@909: text.gsub(%r{(\d+)\.(\d+)}, '\1.\2').html_safe Chris@0: end Chris@0: Chris@0: def authoring(created, author, options={}) Chris@909: l(options[:label] || :label_added_time_by, :author => link_to_user(author), :age => time_tag(created)).html_safe Chris@0: end Chris@441: Chris@0: def time_tag(time) Chris@0: text = distance_of_time_in_words(Time.now, time) Chris@0: if @project Chris@1115: link_to(text, {:controller => 'activities', :action => 'index', :id => @project, :from => User.current.time_to_date(time)}, :title => format_time(time)) Chris@0: else Chris@1464: content_tag('abbr', text, :title => format_time(time)) Chris@0: end Chris@0: end Chris@0: Chris@1115: def syntax_highlight_lines(name, content) Chris@1115: lines = [] Chris@1115: syntax_highlight(name, content).each_line { |line| lines << line } Chris@1115: lines Chris@1115: end Chris@1115: Chris@0: def syntax_highlight(name, content) Chris@0: Redmine::SyntaxHighlighting.highlight_by_filename(content, name) Chris@0: end Chris@0: Chris@0: def to_path_param(path) Chris@1115: str = path.to_s.split(%r{[/\\]}).select{|p| !p.blank?}.join("/") Chris@1115: str.blank? ? nil : str Chris@0: end Chris@0: Chris@909: def reorder_links(name, url, method = :post) Chris@909: link_to(image_tag('2uparrow.png', :alt => l(:label_sort_highest)), Chris@909: url.merge({"#{name}[move_to]" => 'highest'}), Chris@909: :method => method, :title => l(:label_sort_highest)) + Chris@909: link_to(image_tag('1uparrow.png', :alt => l(:label_sort_higher)), Chris@909: url.merge({"#{name}[move_to]" => 'higher'}), Chris@909: :method => method, :title => l(:label_sort_higher)) + Chris@909: link_to(image_tag('1downarrow.png', :alt => l(:label_sort_lower)), Chris@909: url.merge({"#{name}[move_to]" => 'lower'}), Chris@909: :method => method, :title => l(:label_sort_lower)) + Chris@909: link_to(image_tag('2downarrow.png', :alt => l(:label_sort_lowest)), Chris@909: url.merge({"#{name}[move_to]" => 'lowest'}), Chris@909: :method => method, :title => l(:label_sort_lowest)) Chris@0: end Chris@0: Chris@0: def breadcrumb(*args) Chris@0: elements = args.flatten Chris@909: elements.any? ? content_tag('p', (args.join(" \xc2\xbb ") + " \xc2\xbb ").html_safe, :class => 'breadcrumb') : nil Chris@0: end Chris@441: Chris@0: def other_formats_links(&block) Chris@909: concat('

    '.html_safe + l(:label_export_to)) Chris@0: yield Redmine::Views::OtherFormatsBuilder.new(self) Chris@909: concat('

    '.html_safe) Chris@0: end Chris@441: Chris@0: def page_header_title Chris@0: if @project.nil? || @project.new_record? luisf@144: a = [h(Setting.app_title), ''] luisf@144: Chris@0: else luisf@144: pname = [] Chris@0: b = [] Chris@441: ancestors = (@project.root? ? [] : @project.ancestors.visible.all) Chris@0: if ancestors.any? Chris@0: root = ancestors.shift Chris@14: b << link_to_project(root, {:jump => current_menu_item}, :class => 'root') Chris@0: if ancestors.size > 2 luis@1120: b << '…' Chris@0: ancestors = ancestors[-2, 2] Chris@0: end Chris@14: b += ancestors.collect {|p| link_to_project(p, {:jump => current_menu_item}, :class => 'ancestor') } chris@1152: b = b.join(' » ').html_safe chris@1152: b << (' »'.html_safe) Chris@0: end luisf@144: luisf@144: pname << h(@project) luisf@144: chris@1152: a = [pname, b] luisf@144: Chris@0: end Chris@0: end Chris@0: Chris@1464: # Returns a h2 tag and sets the html title with the given arguments Chris@1464: def title(*args) Chris@1464: strings = args.map do |arg| Chris@1464: if arg.is_a?(Array) && arg.size >= 2 Chris@1464: link_to(*arg) Chris@1464: else Chris@1464: h(arg.to_s) Chris@1464: end Chris@1464: end Chris@1464: html_title args.reverse.map {|s| (s.is_a?(Array) ? s.first : s).to_s} Chris@1464: content_tag('h2', strings.join(' » ').html_safe) Chris@1464: end Chris@1464: Chris@1464: # Sets the html title Chris@1464: # Returns the html title when called without arguments Chris@1464: # Current project name and app_title and automatically appended Chris@1464: # Exemples: Chris@1464: # html_title 'Foo', 'Bar' Chris@1464: # html_title # => 'Foo - Bar - My Project - Redmine' Chris@0: def html_title(*args) Chris@0: if args.empty? Chris@909: title = @html_title || [] Chris@0: title << @project.name if @project Chris@909: title << Setting.app_title unless Setting.app_title == title.last Chris@1464: title.reject(&:blank?).join(' - ') Chris@0: else Chris@0: @html_title ||= [] Chris@0: @html_title += args Chris@0: end Chris@0: end Chris@0: Chris@14: # Returns the theme, controller name, and action as css classes for the Chris@14: # HTML body. Chris@14: def body_css_classes Chris@14: css = [] Chris@14: if theme = Redmine::Themes.theme(Setting.ui_theme) Chris@14: css << 'theme-' + theme.name Chris@14: end Chris@14: Chris@1464: css << 'project-' + @project.identifier if @project && @project.identifier.present? Chris@1115: css << 'controller-' + controller_name Chris@1115: css << 'action-' + action_name Chris@14: css.join(' ') Chris@14: end Chris@14: Chris@0: def accesskey(s) Chris@1464: @used_accesskeys ||= [] Chris@1464: key = Redmine::AccessKeys.key_for(s) Chris@1464: return nil if @used_accesskeys.include?(key) Chris@1464: @used_accesskeys << key Chris@1464: key Chris@0: end Chris@0: Chris@0: # Formats text according to system settings. Chris@0: # 2 ways to call this method: Chris@0: # * with a String: textilizable(text, options) Chris@0: # * with an object and one of its attribute: textilizable(issue, :description, options) Chris@0: def textilizable(*args) Chris@0: options = args.last.is_a?(Hash) ? args.pop : {} Chris@0: case args.size Chris@0: when 1 Chris@0: obj = options[:object] Chris@0: text = args.shift Chris@0: when 2 Chris@0: obj = args.shift Chris@0: attr = args.shift Chris@0: text = obj.send(attr).to_s Chris@0: else Chris@0: raise ArgumentError, 'invalid arguments to textilizable' Chris@0: end Chris@0: return '' if text.blank? Chris@0: project = options[:project] || @project || (obj && obj.respond_to?(:project) ? obj.project : nil) Chris@0: only_path = options.delete(:only_path) == false ? false : true Chris@0: Chris@1115: text = text.dup Chris@1115: macros = catch_macros(text) Chris@909: text = Redmine::WikiFormatting.to_html(Setting.text_formatting, text, :object => obj, :attribute => attr) Chris@441: Chris@119: @parsed_headings = [] Chris@929: @heading_anchors = {} Chris@909: @current_section = 0 if options[:edit_section_links] Chris@929: Chris@929: parse_sections(text, project, obj, attr, only_path, options) Chris@1115: text = parse_non_pre_blocks(text, obj, macros) do |text| Chris@1115: [:parse_inline_attachments, :parse_wiki_links, :parse_redmine_links].each do |method_name| Chris@0: send method_name, text, project, obj, attr, only_path, options Chris@0: end Chris@0: end Chris@929: parse_headings(text, project, obj, attr, only_path, options) Chris@441: Chris@119: if @parsed_headings.any? Chris@119: replace_toc(text, @parsed_headings) Chris@119: end Chris@441: Chris@1115: text.html_safe Chris@0: end Chris@441: Chris@1115: def parse_non_pre_blocks(text, obj, macros) Chris@0: s = StringScanner.new(text) Chris@0: tags = [] Chris@0: parsed = '' Chris@0: while !s.eos? Chris@0: s.scan(/(.*?)(<(\/)?(pre|code)(.*?)>|\z)/im) Chris@0: text, full_tag, closing, tag = s[1], s[2], s[3], s[4] Chris@0: if tags.empty? Chris@0: yield text Chris@1115: inject_macros(text, obj, macros) if macros.any? Chris@1115: else Chris@1115: inject_macros(text, obj, macros, false) if macros.any? Chris@0: end Chris@0: parsed << text Chris@0: if tag Chris@0: if closing Chris@0: if tags.last == tag.downcase Chris@0: tags.pop Chris@0: end Chris@0: else Chris@0: tags << tag.downcase Chris@0: end Chris@0: parsed << full_tag Chris@0: end Chris@0: end Chris@0: # Close any non closing tags Chris@0: while tag = tags.pop Chris@0: parsed << "" Chris@0: end Chris@1115: parsed Chris@0: end Chris@441: Chris@0: def parse_inline_attachments(text, project, obj, attr, only_path, options) Chris@0: # when using an image link, try to use an attachment, if possible Chris@1294: attachments = options[:attachments] || [] Chris@1294: attachments += obj.attachments if obj.respond_to?(:attachments) Chris@1294: if attachments.present? Chris@909: text.gsub!(/src="([^\/"]+\.(bmp|gif|jpg|jpe|jpeg|png))"(\s+alt="([^"]*)")?/i) do |m| Chris@441: filename, ext, alt, alttext = $1.downcase, $2, $3, $4 Chris@0: # search for the picture in attachments Chris@909: if found = Attachment.latest_attach(attachments, filename) Chris@1464: image_url = download_named_attachment_path(found, found.filename, :only_path => only_path) Chris@0: desc = found.description.to_s.gsub('"', '') Chris@0: if !desc.blank? && alttext.blank? Chris@0: alt = " title=\"#{desc}\" alt=\"#{desc}\"" Chris@0: end Chris@1115: "src=\"#{image_url}\"#{alt}" Chris@0: else Chris@1115: m Chris@0: end Chris@0: end Chris@0: end Chris@0: end Chris@0: Chris@0: # Wiki links Chris@0: # Chris@0: # Examples: Chris@0: # [[mypage]] Chris@0: # [[mypage|mytext]] Chris@0: # wiki links can refer other project wikis, using project name or identifier: Chris@0: # [[project:]] -> wiki starting page Chris@0: # [[project:|mytext]] Chris@0: # [[project:mypage]] Chris@0: # [[project:mypage|mytext]] Chris@0: def parse_wiki_links(text, project, obj, attr, only_path, options) Chris@0: text.gsub!(/(!)?(\[\[([^\]\n\|]+)(\|([^\]\n\|]+))?\]\])/) do |m| Chris@0: link_project = project Chris@0: esc, all, page, title = $1, $2, $3, $5 Chris@0: if esc.nil? Chris@0: if page =~ /^([^\:]+)\:(.*)$/ Chris@1464: identifier, page = $1, $2 Chris@1464: link_project = Project.find_by_identifier(identifier) || Project.find_by_name(identifier) Chris@1464: title ||= identifier if page.blank? Chris@0: end Chris@0: Chris@0: if link_project && link_project.wiki Chris@0: # extract anchor Chris@0: anchor = nil Chris@0: if page =~ /^(.+?)\#(.+)$/ Chris@0: page, anchor = $1, $2 Chris@0: end Chris@909: anchor = sanitize_anchor_name(anchor) if anchor.present? Chris@0: # check if page exists Chris@0: wiki_page = link_project.wiki.find_page(page) Chris@909: url = if anchor.present? && wiki_page.present? && (obj.is_a?(WikiContent) || obj.is_a?(WikiContent::Version)) && obj.page == wiki_page Chris@909: "##{anchor}" Chris@909: else Chris@909: case options[:wiki_links] Chris@909: when :local; "#{page.present? ? Wiki.titleize(page) : ''}.html" + (anchor.present? ? "##{anchor}" : '') Chris@909: when :anchor; "##{page.present? ? Wiki.titleize(page) : title}" + (anchor.present? ? "_#{anchor}" : '') # used for single-file wiki export Chris@0: else chris@37: wiki_page_id = page.present? ? Wiki.titleize(page) : nil Chris@1115: parent = wiki_page.nil? && obj.is_a?(WikiContent) && obj.page && project == link_project ? obj.page.title : nil Chris@1464: url_for(:only_path => only_path, :controller => 'wiki', :action => 'show', :project_id => link_project, Chris@1115: :id => wiki_page_id, :version => nil, :anchor => anchor, :parent => parent) Chris@0: end Chris@909: end Chris@909: link_to(title.present? ? title.html_safe : h(page), url, :class => ('wiki-page' + (wiki_page ? '' : ' new'))) Chris@0: else Chris@0: # project or wiki doesn't exist Chris@1115: all Chris@0: end Chris@0: else Chris@1115: all Chris@0: end Chris@0: end Chris@0: end Chris@441: Chris@0: # Redmine links Chris@0: # Chris@0: # Examples: Chris@0: # Issues: Chris@0: # #52 -> Link to issue #52 Chris@0: # Changesets: Chris@0: # r52 -> Link to revision 52 Chris@0: # commit:a85130f -> Link to scmid starting with a85130f Chris@0: # Documents: Chris@0: # document#17 -> Link to document with id 17 Chris@0: # document:Greetings -> Link to the document with title "Greetings" Chris@0: # document:"Some document" -> Link to the document with title "Some document" Chris@0: # Versions: Chris@0: # version#3 -> Link to version with id 3 Chris@0: # version:1.0.0 -> Link to version named "1.0.0" Chris@0: # version:"1.0 beta 2" -> Link to version named "1.0 beta 2" Chris@0: # Attachments: Chris@0: # attachment:file.zip -> Link to the attachment of the current object named file.zip Chris@0: # Source files: Chris@0: # source:some/file -> Link to the file located at /some/file in the project's repository Chris@0: # source:some/file@52 -> Link to the file's revision 52 Chris@0: # source:some/file#L120 -> Link to line 120 of the file Chris@0: # source:some/file@52#L120 -> Link to line 120 of the file's revision 52 Chris@0: # export:some/file -> Force the download of the file Chris@210: # Forum messages: Chris@0: # message#1218 -> Link to message with id 1218 Chris@1464: # Projects: Chris@1464: # project:someproject -> Link to project named "someproject" Chris@1464: # project#3 -> Link to project with id 3 Chris@210: # Chris@210: # Links can refer other objects from other projects, using project identifier: Chris@210: # identifier:r52 Chris@210: # identifier:document:"Some document" Chris@210: # identifier:version:1.0.0 Chris@210: # identifier:source:some/file Chris@1294: def parse_redmine_links(text, default_project, obj, attr, only_path, options) Chris@1294: text.gsub!(%r{([\s\(,\-\[\>]|^)(!)?(([a-z0-9\-_]+):)?(attachment|document|version|forum|news|message|project|commit|source|export)?(((#)|((([a-z0-9\-_]+)\|)?(r)))((\d+)((#note)?-(\d+))?)|(:)([^"\s<>][^\s<>]*?|"[^"]+?"))(?=(?=[[:punct:]][^A-Za-z0-9_/])|,|\s|\]|<|$)}) do |m| Chris@1115: leading, esc, project_prefix, project_identifier, prefix, repo_prefix, repo_identifier, sep, identifier, comment_suffix, comment_id = $1, $2, $3, $4, $5, $10, $11, $8 || $12 || $18, $14 || $19, $15, $17 Chris@0: link = nil Chris@1294: project = default_project Chris@210: if project_identifier Chris@210: project = Project.visible.find_by_identifier(project_identifier) Chris@210: end Chris@0: if esc.nil? Chris@0: if prefix.nil? && sep == 'r' Chris@1115: if project Chris@1115: repository = nil Chris@1115: if repo_identifier Chris@1115: repository = project.repositories.detect {|repo| repo.identifier == repo_identifier} Chris@1115: else Chris@1115: repository = project.repository Chris@1115: end Chris@1115: # project.changesets.visible raises an SQL error because of a double join on repositories Chris@1517: if repository && Chris@1517: (changeset = Changeset.visible. Chris@1517: find_by_repository_id_and_revision(repository.id, identifier)) Chris@1517: link = link_to(h("#{project_prefix}#{repo_prefix}r#{identifier}"), Chris@1517: {:only_path => only_path, :controller => 'repositories', Chris@1517: :action => 'revision', :id => project, Chris@1517: :repository_id => repository.identifier_param, Chris@1517: :rev => changeset.revision}, Chris@1517: :class => 'changeset', Chris@1517: :title => truncate_single_line_raw(changeset.comments, 100)) Chris@1115: end Chris@0: end Chris@0: elsif sep == '#' Chris@0: oid = identifier.to_i Chris@0: case prefix Chris@0: when nil Chris@1517: if oid.to_s == identifier && Chris@1517: issue = Issue.visible.includes(:status).find_by_id(oid) Chris@1115: anchor = comment_id ? "note-#{comment_id}" : nil Chris@1517: link = link_to(h("##{oid}#{comment_suffix}"), Chris@1517: {:only_path => only_path, :controller => 'issues', Chris@1517: :action => 'show', :id => oid, :anchor => anchor}, Chris@1517: :class => issue.css_classes, Chris@1517: :title => "#{issue.subject.truncate(100)} (#{issue.status.name})") Chris@0: end Chris@0: when 'document' Chris@210: if document = Document.visible.find_by_id(oid) Chris@0: link = link_to h(document.title), {:only_path => only_path, :controller => 'documents', :action => 'show', :id => document}, Chris@0: :class => 'document' Chris@0: end Chris@0: when 'version' Chris@210: if version = Version.visible.find_by_id(oid) Chris@0: link = link_to h(version.name), {:only_path => only_path, :controller => 'versions', :action => 'show', :id => version}, Chris@0: :class => 'version' Chris@0: end Chris@0: when 'message' Chris@1517: if message = Message.visible.includes(:parent).find_by_id(oid) Chris@210: link = link_to_message(message, {:only_path => only_path}, :class => 'message') Chris@0: end Chris@909: when 'forum' Chris@909: if board = Board.visible.find_by_id(oid) Chris@909: link = link_to h(board.name), {:only_path => only_path, :controller => 'boards', :action => 'show', :id => board, :project_id => board.project}, Chris@909: :class => 'board' Chris@909: end Chris@909: when 'news' Chris@909: if news = News.visible.find_by_id(oid) Chris@909: link = link_to h(news.title), {:only_path => only_path, :controller => 'news', :action => 'show', :id => news}, Chris@909: :class => 'news' Chris@909: end Chris@0: when 'project' Chris@0: if p = Project.visible.find_by_id(oid) Chris@14: link = link_to_project(p, {:only_path => only_path}, :class => 'project') Chris@0: end Chris@0: end Chris@0: elsif sep == ':' Chris@0: # removes the double quotes if any Chris@0: name = identifier.gsub(%r{^"(.*)"$}, "\\1") Chris@1517: name = CGI.unescapeHTML(name) Chris@0: case prefix Chris@0: when 'document' Chris@210: if project && document = project.documents.visible.find_by_title(name) Chris@0: link = link_to h(document.title), {:only_path => only_path, :controller => 'documents', :action => 'show', :id => document}, Chris@0: :class => 'document' Chris@0: end Chris@0: when 'version' Chris@210: if project && version = project.versions.visible.find_by_name(name) Chris@0: link = link_to h(version.name), {:only_path => only_path, :controller => 'versions', :action => 'show', :id => version}, Chris@0: :class => 'version' Chris@0: end Chris@909: when 'forum' Chris@909: if project && board = project.boards.visible.find_by_name(name) Chris@909: link = link_to h(board.name), {:only_path => only_path, :controller => 'boards', :action => 'show', :id => board, :project_id => board.project}, Chris@909: :class => 'board' Chris@909: end Chris@909: when 'news' Chris@909: if project && news = project.news.visible.find_by_title(name) Chris@909: link = link_to h(news.title), {:only_path => only_path, :controller => 'news', :action => 'show', :id => news}, Chris@909: :class => 'news' Chris@909: end Chris@1115: when 'commit', 'source', 'export' Chris@1115: if project Chris@1115: repository = nil Chris@1294: if name =~ %r{^(([a-z0-9\-_]+)\|)(.+)$} Chris@1115: repo_prefix, repo_identifier, name = $1, $2, $3 Chris@1115: repository = project.repositories.detect {|repo| repo.identifier == repo_identifier} Chris@1115: else Chris@1115: repository = project.repository Chris@1115: end Chris@1115: if prefix == 'commit' Chris@1464: if repository && (changeset = Changeset.visible.where("repository_id = ? AND scmid LIKE ?", repository.id, "#{name}%").first) Chris@1115: link = link_to h("#{project_prefix}#{repo_prefix}#{name}"), {:only_path => only_path, :controller => 'repositories', :action => 'revision', :id => project, :repository_id => repository.identifier_param, :rev => changeset.identifier}, Chris@1115: :class => 'changeset', Chris@1517: :title => truncate_single_line_raw(changeset.comments, 100) Chris@1115: end Chris@1115: else Chris@1115: if repository && User.current.allowed_to?(:browse_repository, project) Chris@1464: name =~ %r{^[/\\]*(.*?)(@([^/\\@]+?))?(#(L\d+))?$} Chris@1115: path, rev, anchor = $1, $3, $5 Chris@1517: link = link_to h("#{project_prefix}#{prefix}:#{repo_prefix}#{name}"), {:only_path => only_path, :controller => 'repositories', :action => (prefix == 'export' ? 'raw' : 'entry'), :id => project, :repository_id => repository.identifier_param, Chris@1115: :path => to_path_param(path), Chris@1115: :rev => rev, Chris@1115: :anchor => anchor}, Chris@1115: :class => (prefix == 'export' ? 'source download' : 'source') Chris@1115: end Chris@1115: end Chris@1115: repo_prefix = nil Chris@0: end Chris@0: when 'attachment' Chris@1517: attachments = options[:attachments] || [] Chris@1517: attachments += obj.attachments if obj.respond_to?(:attachments) Chris@1294: if attachments && attachment = Attachment.latest_attach(attachments, name) Chris@1464: link = link_to_attachment(attachment, :only_path => only_path, :download => true, :class => 'attachment') Chris@0: end Chris@0: when 'project' Chris@1464: if p = Project.visible.where("identifier = :s OR LOWER(name) = :s", :s => name.downcase).first Chris@14: link = link_to_project(p, {:only_path => only_path}, :class => 'project') Chris@0: end Chris@0: end Chris@0: end Chris@0: end Chris@1115: (leading + (link || "#{project_prefix}#{prefix}#{repo_prefix}#{sep}#{identifier}#{comment_suffix}")) Chris@0: end Chris@0: end Chris@441: Chris@1115: HEADING_RE = /(]+)?>(.+?)<\/h(\d)>)/i unless const_defined?(:HEADING_RE) Chris@909: Chris@909: def parse_sections(text, project, obj, attr, only_path, options) Chris@909: return unless options[:edit_section_links] Chris@909: text.gsub!(HEADING_RE) do Chris@1115: heading = $1 Chris@909: @current_section += 1 Chris@909: if @current_section > 1 Chris@909: content_tag('div', Chris@909: link_to(image_tag('edit.png'), options[:edit_section_links].merge(:section => @current_section)), Chris@909: :class => 'contextual', Chris@1464: :title => l(:button_edit_section), Chris@1464: :id => "section-#{@current_section}") + heading.html_safe Chris@909: else Chris@1115: heading Chris@909: end Chris@909: end Chris@909: end Chris@441: chris@37: # Headings and TOC Chris@119: # Adds ids and links to headings unless options[:headings] is set to false chris@37: def parse_headings(text, project, obj, attr, only_path, options) Chris@119: return if options[:headings] == false Chris@441: chris@37: text.gsub!(HEADING_RE) do Chris@909: level, attrs, content = $2.to_i, $3, $4 chris@37: item = strip_tags(content).strip Chris@909: anchor = sanitize_anchor_name(item) Chris@909: # used for single-file wiki export Chris@909: anchor = "#{obj.page.title}_#{anchor}" if options[:wiki_links] == :anchor && (obj.is_a?(WikiContent) || obj.is_a?(WikiContent::Version)) Chris@929: @heading_anchors[anchor] ||= 0 Chris@929: idx = (@heading_anchors[anchor] += 1) Chris@929: if idx > 1 Chris@929: anchor = "#{anchor}-#{idx}" Chris@929: end Chris@119: @parsed_headings << [level, anchor, item] Chris@441: "\n#{content}" Chris@119: end Chris@119: end Chris@441: Chris@1115: MACROS_RE = /( Chris@909: (!)? # escaping Chris@909: ( Chris@909: \{\{ # opening tag Chris@909: ([\w]+) # macro name Chris@1115: (\(([^\n\r]*?)\))? # optional arguments Chris@1115: ([\n\r].*?[\n\r])? # optional block of text Chris@909: \}\} # closing tag Chris@909: ) Chris@1115: )/mx unless const_defined?(:MACROS_RE) Chris@909: Chris@1115: MACRO_SUB_RE = /( Chris@1115: \{\{ Chris@1115: macro\((\d+)\) Chris@1115: \}\} Chris@1115: )/x unless const_defined?(:MACRO_SUB_RE) Chris@1115: Chris@1115: # Extracts macros from text Chris@1115: def catch_macros(text) Chris@1115: macros = {} Chris@909: text.gsub!(MACROS_RE) do Chris@1115: all, macro = $1, $4.downcase Chris@1115: if macro_exists?(macro) || all =~ MACRO_SUB_RE Chris@1115: index = macros.size Chris@1115: macros[index] = all Chris@1115: "{{macro(#{index})}}" Chris@909: else Chris@909: all Chris@909: end Chris@909: end Chris@1115: macros Chris@1115: end Chris@1115: Chris@1115: # Executes and replaces macros in text Chris@1115: def inject_macros(text, obj, macros, execute=true) Chris@1115: text.gsub!(MACRO_SUB_RE) do Chris@1115: all, index = $1, $2.to_i Chris@1115: orig = macros.delete(index) Chris@1115: if execute && orig && orig =~ MACROS_RE Chris@1115: esc, all, macro, args, block = $2, $3, $4.downcase, $6.to_s, $7.try(:strip) Chris@1115: if esc.nil? Chris@1115: h(exec_macro(macro, obj, args, block) || all) Chris@1115: else Chris@1115: h(all) Chris@1115: end Chris@1115: elsif orig Chris@1115: h(orig) Chris@1115: else Chris@1115: h(all) Chris@1115: end Chris@1115: end Chris@909: end Chris@909: Chris@1517: TOC_RE = /

    \{\{((<|<)|(>|>))?toc\}\}<\/p>/i unless const_defined?(:TOC_RE) Chris@441: Chris@119: # Renders the TOC with given headings Chris@119: def replace_toc(text, headings) chris@37: text.gsub!(TOC_RE) do Chris@1517: left_align, right_align = $2, $3 Chris@1115: # Keep only the 4 first levels Chris@1115: headings = headings.select{|level, anchor, item| level <= 4} chris@37: if headings.empty? chris@37: '' chris@37: else chris@37: div_class = 'toc' Chris@1517: div_class << ' right' if right_align Chris@1517: div_class << ' left' if left_align chris@37: out = "

    ' * (current - root) chris@37: out << '' chris@37: end chris@37: end chris@37: end Chris@0: Chris@0: # Same as Rails' simple_format helper without using paragraphs Chris@0: def simple_format_without_paragraph(text) Chris@0: text.to_s. Chris@0: gsub(/\r\n?/, "\n"). # \r\n and \r -> \n Chris@0: gsub(/\n\n+/, "

    "). # 2+ newline -> 2 br Chris@909: gsub(/([^\n]\n)(?=[^\n])/, '\1
    '). # 1 newline -> br Chris@909: html_safe Chris@0: end Chris@0: Chris@0: def lang_options_for_select(blank=true) Chris@1115: (blank ? [["(auto)", ""]] : []) + languages_options Chris@0: end Chris@0: Chris@0: def label_tag_for(name, option_tags = nil, options = {}) Chris@0: label_text = l(("field_"+field.to_s.gsub(/\_id$/, "")).to_sym) + (options.delete(:required) ? @template.content_tag("span", " *", :class => "required"): "") Chris@0: content_tag("label", label_text) Chris@0: end Chris@0: Chris@1115: def labelled_form_for(*args, &proc) Chris@909: args << {} unless args.last.is_a?(Hash) Chris@909: options = args.last Chris@1115: if args.first.is_a?(Symbol) Chris@1115: options.merge!(:as => args.shift) Chris@1115: end Chris@1115: options.merge!({:builder => Redmine::Views::LabelledFormBuilder}) Chris@909: form_for(*args, &proc) Chris@909: end Chris@909: Chris@1115: def labelled_fields_for(*args, &proc) Chris@909: args << {} unless args.last.is_a?(Hash) Chris@909: options = args.last Chris@1115: options.merge!({:builder => Redmine::Views::LabelledFormBuilder}) Chris@1115: fields_for(*args, &proc) Chris@1115: end Chris@1115: Chris@1115: def labelled_remote_form_for(*args, &proc) Chris@1115: ActiveSupport::Deprecation.warn "ApplicationHelper#labelled_remote_form_for is deprecated and will be removed in Redmine 2.2." Chris@1115: args << {} unless args.last.is_a?(Hash) Chris@1115: options = args.last Chris@1115: options.merge!({:builder => Redmine::Views::LabelledFormBuilder, :remote => true}) Chris@909: form_for(*args, &proc) Chris@0: end Chris@0: Chris@1115: def error_messages_for(*objects) Chris@1115: html = "" Chris@1115: objects = objects.map {|o| o.is_a?(String) ? instance_variable_get("@#{o}") : o}.compact Chris@1115: errors = objects.map {|o| o.errors.full_messages}.flatten Chris@1115: if errors.any? Chris@1115: html << "
    \n" Chris@1115: end Chris@1115: html.html_safe Chris@1464: end Chris@1115: Chris@1115: def delete_link(url, options={}) Chris@1115: options = { Chris@1115: :method => :delete, Chris@1115: :data => {:confirm => l(:text_are_you_sure)}, Chris@1115: :class => 'icon icon-del' Chris@1115: }.merge(options) Chris@1115: Chris@1115: link_to l(:button_delete), url, options Chris@1115: end Chris@1115: Chris@1115: def preview_link(url, form, target='preview', options={}) Chris@1115: content_tag 'a', l(:label_preview), { Chris@1464: :href => "#", Chris@1464: :onclick => %|submitPreview("#{escape_javascript url_for(url)}", "#{escape_javascript form}", "#{escape_javascript target}"); return false;|, Chris@1115: :accesskey => accesskey(:preview) Chris@1115: }.merge(options) Chris@1115: end Chris@1115: Chris@1115: def link_to_function(name, function, html_options={}) Chris@1115: content_tag(:a, name, {:href => '#', :onclick => "#{function}; return false;"}.merge(html_options)) Chris@1115: end Chris@1115: Chris@1115: # Helper to render JSON in views Chris@1115: def raw_json(arg) Chris@1115: arg.to_json.to_s.gsub('/', '\/').html_safe Chris@1115: end Chris@1115: Chris@1115: def back_url Chris@1115: url = params[:back_url] Chris@1115: if url.nil? && referer = request.env['HTTP_REFERER'] Chris@1115: url = CGI.unescape(referer.to_s) Chris@1115: end Chris@1115: url Chris@1115: end Chris@1115: Chris@0: def back_url_hidden_field_tag Chris@1115: url = back_url Chris@1115: hidden_field_tag('back_url', url, :id => nil) unless url.blank? Chris@0: end Chris@0: Chris@0: def check_all_links(form_name) Chris@0: link_to_function(l(:button_check_all), "checkAll('#{form_name}', true)") + Chris@909: " | ".html_safe + Chris@0: link_to_function(l(:button_uncheck_all), "checkAll('#{form_name}', false)") Chris@0: end Chris@0: Chris@0: def progress_bar(pcts, options={}) Chris@0: pcts = [pcts, pcts] unless pcts.is_a?(Array) Chris@0: pcts = pcts.collect(&:round) Chris@0: pcts[1] = pcts[1] - pcts[0] Chris@0: pcts << (100 - pcts[1] - pcts[0]) Chris@0: width = options[:width] || '100px;' Chris@0: legend = options[:legend] || '' Chris@0: content_tag('table', Chris@0: content_tag('tr', Chris@909: (pcts[0] > 0 ? content_tag('td', '', :style => "width: #{pcts[0]}%;", :class => 'closed') : ''.html_safe) + Chris@909: (pcts[1] > 0 ? content_tag('td', '', :style => "width: #{pcts[1]}%;", :class => 'done') : ''.html_safe) + Chris@909: (pcts[2] > 0 ? content_tag('td', '', :style => "width: #{pcts[2]}%;", :class => 'todo') : ''.html_safe) Chris@1464: ), :class => "progress progress-#{pcts[0]}", :style => "width: #{width};").html_safe + Chris@1464: content_tag('p', legend, :class => 'percent').html_safe Chris@0: end Chris@441: Chris@0: def checked_image(checked=true) Chris@0: if checked Chris@0: image_tag 'toggle_check.png' Chris@0: end Chris@0: end Chris@441: Chris@0: def context_menu(url) Chris@0: unless @context_menu_included Chris@0: content_for :header_tags do Chris@0: javascript_include_tag('context_menu') + Chris@0: stylesheet_link_tag('context_menu') Chris@0: end Chris@14: if l(:direction) == 'rtl' Chris@14: content_for :header_tags do Chris@14: stylesheet_link_tag('context_menu_rtl') Chris@14: end Chris@14: end Chris@0: @context_menu_included = true Chris@0: end Chris@1115: javascript_tag "contextMenuInit('#{ url_for(url) }')" Chris@0: end Chris@0: Chris@0: def calendar_for(field_id) Chris@0: include_calendar_headers_tags Chris@1115: javascript_tag("$(function() { $('##{field_id}').datepicker(datepickerOptions); });") Chris@0: end Chris@0: Chris@0: def include_calendar_headers_tags Chris@0: unless @calendar_headers_tags_included Chris@1464: tags = javascript_include_tag("datepicker") Chris@0: @calendar_headers_tags_included = true Chris@0: content_for :header_tags do Chris@1115: start_of_week = Setting.start_of_week Chris@1115: start_of_week = l(:general_first_day_of_week, :default => '1') if start_of_week.blank? Chris@1115: # Redmine uses 1..7 (monday..sunday) in settings and locales Chris@1115: # JQuery uses 0..6 (sunday..saturday), 7 needs to be changed to 0 Chris@1115: start_of_week = start_of_week.to_i % 7 Chris@1464: tags << javascript_tag( Chris@1115: "var datepickerOptions={dateFormat: 'yy-mm-dd', firstDay: #{start_of_week}, " + Chris@1464: "showOn: 'button', buttonImageOnly: true, buttonImage: '" + Chris@1115: path_to_image('/images/calendar.png') + Chris@1464: "', showButtonPanel: true, showWeek: true, showOtherMonths: true, " + Chris@1464: "selectOtherMonths: true, changeMonth: true, changeYear: true, " + Chris@1464: "beforeShow: beforeShowDatePicker};") Chris@1115: jquery_locale = l('jquery.locale', :default => current_language.to_s) Chris@1115: unless jquery_locale == 'en' Chris@1464: tags << javascript_include_tag("i18n/jquery.ui.datepicker-#{jquery_locale}.js") Chris@0: end Chris@1115: tags Chris@0: end Chris@0: end Chris@0: end Chris@0: Chris@1115: # Overrides Rails' stylesheet_link_tag with themes and plugins support. Chris@1115: # Examples: Chris@1115: # stylesheet_link_tag('styles') # => picks styles.css from the current theme or defaults Chris@1115: # stylesheet_link_tag('styles', :plugin => 'foo) # => picks styles.css from plugin's assets Chris@1115: # Chris@1115: def stylesheet_link_tag(*sources) Chris@1115: options = sources.last.is_a?(Hash) ? sources.pop : {} Chris@1115: plugin = options.delete(:plugin) Chris@1115: sources = sources.map do |source| Chris@1115: if plugin Chris@1115: "/plugin_assets/#{plugin}/stylesheets/#{source}" Chris@1115: elsif current_theme && current_theme.stylesheets.include?(source) Chris@1115: current_theme.stylesheet_path(source) Chris@1115: else Chris@1115: source Chris@1115: end Chris@1115: end Chris@1115: super sources, options Chris@1115: end Chris@1115: Chris@1115: # Overrides Rails' image_tag with themes and plugins support. Chris@1115: # Examples: Chris@1115: # image_tag('image.png') # => picks image.png from the current theme or defaults Chris@1115: # image_tag('image.png', :plugin => 'foo) # => picks image.png from plugin's assets Chris@1115: # Chris@1115: def image_tag(source, options={}) Chris@1115: if plugin = options.delete(:plugin) Chris@1115: source = "/plugin_assets/#{plugin}/images/#{source}" Chris@1115: elsif current_theme && current_theme.images.include?(source) Chris@1115: source = current_theme.image_path(source) Chris@1115: end Chris@1115: super source, options Chris@1115: end Chris@1115: Chris@1115: # Overrides Rails' javascript_include_tag with plugins support Chris@1115: # Examples: Chris@1115: # javascript_include_tag('scripts') # => picks scripts.js from defaults Chris@1115: # javascript_include_tag('scripts', :plugin => 'foo) # => picks scripts.js from plugin's assets Chris@1115: # Chris@1115: def javascript_include_tag(*sources) Chris@1115: options = sources.last.is_a?(Hash) ? sources.pop : {} Chris@1115: if plugin = options.delete(:plugin) Chris@1115: sources = sources.map do |source| Chris@1115: if plugin Chris@1115: "/plugin_assets/#{plugin}/javascripts/#{source}" Chris@1115: else Chris@1115: source Chris@1115: end Chris@1115: end Chris@1115: end Chris@1115: super sources, options Chris@1115: end Chris@1115: Chris@1464: # TODO: remove this in 2.5.0 Chris@0: def has_content?(name) Chris@1464: content_for?(name) Chris@0: end Chris@0: Chris@1115: def sidebar_content? Chris@1464: content_for?(:sidebar) || view_layouts_base_sidebar_hook_response.present? Chris@1115: end Chris@1115: Chris@1115: def view_layouts_base_sidebar_hook_response Chris@1115: @view_layouts_base_sidebar_hook_response ||= call_hook(:view_layouts_base_sidebar) Chris@1115: end Chris@1115: Chris@909: def email_delivery_enabled? Chris@909: !!ActionMailer::Base.perform_deliveries Chris@909: end Chris@909: Chris@0: # Returns the avatar image tag for the given +user+ if avatars are enabled Chris@0: # +user+ can be a User or a string that will be scanned for an email address (eg. 'joe ') Chris@0: def avatar(user, options = { }) Chris@0: if Setting.gravatar_enabled? Chris@1115: options.merge!({:ssl => (request && request.ssl?), :default => Setting.gravatar_default}) Chris@0: email = nil Chris@0: if user.respond_to?(:mail) Chris@0: email = user.mail Chris@0: elsif user.to_s =~ %r{<(.+?)>} Chris@0: email = $1 Chris@0: end Chris@0: return gravatar(email.to_s.downcase, options) unless email.blank? rescue nil chris@22: else chris@22: '' Chris@0: end Chris@0: end Chris@441: Chris@909: def sanitize_anchor_name(anchor) Chris@1115: if ''.respond_to?(:encoding) || RUBY_PLATFORM == 'java' Chris@1464: anchor.gsub(%r{[^\s\-\p{Word}]}, '').gsub(%r{\s+(\-+\s*)?}, '-') Chris@1115: else Chris@1115: # TODO: remove when ruby1.8 is no longer supported Chris@1115: anchor.gsub(%r{[^\w\s\-]}, '').gsub(%r{\s+(\-+\s*)?}, '-') Chris@1115: end Chris@909: end Chris@909: Chris@245: # Returns the javascript tags that are included in the html layout head Chris@245: def javascript_heads Chris@1464: tags = javascript_include_tag('jquery-1.8.3-ui-1.9.2-ujs-2.0.3', 'application') Chris@245: unless User.current.pref.warn_on_leaving_unsaved == '0' Chris@1115: tags << "\n".html_safe + javascript_tag("$(window).load(function(){ warnLeavingUnsaved('#{escape_javascript l(:text_warn_on_leaving_unsaved)}'); });") Chris@245: end Chris@245: tags Chris@245: end Chris@0: Chris@14: def favicon Chris@1517: "".html_safe Chris@1517: end Chris@1517: Chris@1517: # Returns the path to the favicon Chris@1517: def favicon_path Chris@1517: icon = (current_theme && current_theme.favicon?) ? current_theme.favicon_path : '/favicon.ico' Chris@1517: image_path(icon) Chris@1517: end Chris@1517: Chris@1517: # Returns the full URL to the favicon Chris@1517: def favicon_url Chris@1517: # TODO: use #image_url introduced in Rails4 Chris@1517: path = favicon_path Chris@1517: base = url_for(:controller => 'welcome', :action => 'index', :only_path => false) Chris@1517: base.sub(%r{/+$},'') + '/' + path.sub(%r{^/+},'') Chris@14: end Chris@441: Chris@441: def robot_exclusion_tag Chris@909: ''.html_safe Chris@441: end Chris@441: chris@503: def stylesheet_platform_font_tag chris@503: agent = request.env['HTTP_USER_AGENT'] chris@503: name = 'fonts-generic' chris@503: if agent and agent =~ %r{Windows} chris@503: name = 'fonts-ms' chris@503: elsif agent and agent =~ %r{Macintosh} chris@503: name = 'fonts-mac' chris@503: end chris@503: stylesheet_link_tag name, :media => 'all' chris@503: end chris@503: Chris@119: # Returns true if arg is expected in the API response Chris@119: def include_in_api_response?(arg) Chris@119: unless @included_in_api_response Chris@119: param = params[:include] Chris@119: @included_in_api_response = param.is_a?(Array) ? param.collect(&:to_s) : param.to_s.split(',') Chris@119: @included_in_api_response.collect!(&:strip) Chris@119: end Chris@119: @included_in_api_response.include?(arg.to_s) Chris@119: end Chris@14: Chris@119: # Returns options or nil if nometa param or X-Redmine-Nometa header Chris@119: # was set in the request Chris@119: def api_meta(options) Chris@119: if params[:nometa].present? || request.headers['X-Redmine-Nometa'] Chris@119: # compatibility mode for activeresource clients that raise Chris@119: # an error when unserializing an array with attributes Chris@119: nil Chris@119: else Chris@119: options Chris@119: end Chris@119: end Chris@441: Chris@0: private Chris@0: Chris@0: def wiki_helper Chris@0: helper = Redmine::WikiFormatting.helper_for(Setting.text_formatting) Chris@0: extend helper Chris@0: return self Chris@0: end Chris@441: Chris@441: def link_to_content_update(text, url_params = {}, html_options = {}) Chris@441: link_to(text, url_params, html_options) Chris@0: end Chris@0: end