annotate app/helpers/application_helper.rb @ 1516:b450a9d58aed redmine-2.4

Update to Redmine SVN revision 13356 on 2.4-stable branch
author Chris Cannam
date Tue, 09 Sep 2014 09:28:31 +0100
parents e248c7af89ec
children c86dacc2ef0a dffacf8a6908
rev   line source
Chris@909 1 # encoding: utf-8
Chris@909 2 #
chris@37 3 # Redmine - project management software
Chris@1494 4 # Copyright (C) 2006-2014 Jean-Philippe Lang
Chris@0 5 #
Chris@0 6 # This program is free software; you can redistribute it and/or
Chris@0 7 # modify it under the terms of the GNU General Public License
Chris@0 8 # as published by the Free Software Foundation; either version 2
Chris@0 9 # of the License, or (at your option) any later version.
Chris@0 10 #
Chris@0 11 # This program is distributed in the hope that it will be useful,
Chris@0 12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
Chris@0 13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
Chris@0 14 # GNU General Public License for more details.
Chris@0 15 #
Chris@0 16 # You should have received a copy of the GNU General Public License
Chris@0 17 # along with this program; if not, write to the Free Software
Chris@0 18 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
Chris@0 19
Chris@0 20 require 'forwardable'
Chris@0 21 require 'cgi'
Chris@0 22
Chris@0 23 module ApplicationHelper
Chris@0 24 include Redmine::WikiFormatting::Macros::Definitions
Chris@0 25 include Redmine::I18n
Chris@0 26 include GravatarHelper::PublicMethods
Chris@1464 27 include Redmine::Pagination::Helper
Chris@0 28
Chris@0 29 extend Forwardable
Chris@0 30 def_delegators :wiki_helper, :wikitoolbar_for, :heads_for_wiki_formatter
Chris@0 31
Chris@0 32 # Return true if user is authorized for controller/action, otherwise false
Chris@0 33 def authorize_for(controller, action)
Chris@0 34 User.current.allowed_to?({:controller => controller, :action => action}, @project)
Chris@0 35 end
Chris@0 36
Chris@0 37 # Display a link if user is authorized
chris@22 38 #
chris@22 39 # @param [String] name Anchor text (passed to link_to)
chris@37 40 # @param [Hash] options Hash params. This will checked by authorize_for to see if the user is authorized
chris@22 41 # @param [optional, Hash] html_options Options passed to link_to
chris@22 42 # @param [optional, Hash] parameters_for_method_reference Extra parameters for link_to
Chris@0 43 def link_to_if_authorized(name, options = {}, html_options = nil, *parameters_for_method_reference)
chris@37 44 link_to(name, options, html_options, *parameters_for_method_reference) if authorize_for(options[:controller] || params[:controller], options[:action])
Chris@0 45 end
Chris@0 46
Chris@0 47 # Displays a link to user's account page if active
Chris@0 48 def link_to_user(user, options={})
Chris@0 49 if user.is_a?(User)
Chris@0 50 name = h(user.name(options[:format]))
Chris@1115 51 if user.active? || (User.current.admin? && user.logged?)
Chris@1115 52 link_to name, user_path(user), :class => user.css_classes
Chris@0 53 else
Chris@0 54 name
Chris@0 55 end
Chris@0 56 else
Chris@0 57 h(user.to_s)
Chris@0 58 end
Chris@0 59 end
Chris@0 60
Chris@0 61 # Displays a link to +issue+ with its subject.
Chris@0 62 # Examples:
Chris@441 63 #
Chris@0 64 # link_to_issue(issue) # => Defect #6: This is the subject
Chris@0 65 # link_to_issue(issue, :truncate => 6) # => Defect #6: This i...
Chris@0 66 # link_to_issue(issue, :subject => false) # => Defect #6
Chris@0 67 # link_to_issue(issue, :project => true) # => Foo - Defect #6
Chris@1115 68 # link_to_issue(issue, :subject => false, :tracker => false) # => #6
Chris@0 69 #
Chris@0 70 def link_to_issue(issue, options={})
Chris@0 71 title = nil
Chris@0 72 subject = nil
Chris@1115 73 text = options[:tracker] == false ? "##{issue.id}" : "#{issue.tracker} ##{issue.id}"
Chris@0 74 if options[:subject] == false
Chris@0 75 title = truncate(issue.subject, :length => 60)
Chris@0 76 else
Chris@0 77 subject = issue.subject
Chris@0 78 if options[:truncate]
Chris@0 79 subject = truncate(subject, :length => options[:truncate])
Chris@0 80 end
Chris@0 81 end
Chris@1464 82 only_path = options[:only_path].nil? ? true : options[:only_path]
Chris@1464 83 s = link_to text, issue_path(issue, :only_path => only_path), :class => issue.css_classes, :title => title
Chris@1115 84 s << h(": #{subject}") if subject
Chris@1115 85 s = h("#{issue.project} - ") + s if options[:project]
Chris@0 86 s
Chris@0 87 end
Chris@0 88
Chris@0 89 # Generates a link to an attachment.
Chris@0 90 # Options:
Chris@0 91 # * :text - Link text (default to attachment filename)
Chris@0 92 # * :download - Force download (default: false)
Chris@0 93 def link_to_attachment(attachment, options={})
Chris@0 94 text = options.delete(:text) || attachment.filename
Chris@1464 95 route_method = options.delete(:download) ? :download_named_attachment_path : :named_attachment_path
Chris@1464 96 html_options = options.slice!(:only_path)
Chris@1464 97 url = send(route_method, attachment, attachment.filename, options)
Chris@1464 98 link_to text, url, html_options
Chris@0 99 end
Chris@0 100
Chris@0 101 # Generates a link to a SCM revision
Chris@0 102 # Options:
Chris@0 103 # * :text - Link text (default to the formatted revision)
Chris@1115 104 def link_to_revision(revision, repository, options={})
Chris@1115 105 if repository.is_a?(Project)
Chris@1115 106 repository = repository.repository
Chris@1115 107 end
Chris@0 108 text = options.delete(:text) || format_revision(revision)
Chris@119 109 rev = revision.respond_to?(:identifier) ? revision.identifier : revision
Chris@1115 110 link_to(
Chris@1115 111 h(text),
Chris@1115 112 {:controller => 'repositories', :action => 'revision', :id => repository.project, :repository_id => repository.identifier_param, :rev => rev},
Chris@1115 113 :title => l(:label_revision_id, format_revision(revision))
Chris@1115 114 )
Chris@0 115 end
Chris@441 116
Chris@210 117 # Generates a link to a message
Chris@210 118 def link_to_message(message, options={}, html_options = nil)
Chris@210 119 link_to(
Chris@1464 120 truncate(message.subject, :length => 60),
Chris@1464 121 board_message_path(message.board_id, message.parent_id || message.id, {
Chris@210 122 :r => (message.parent_id && message.id),
Chris@210 123 :anchor => (message.parent_id ? "message-#{message.id}" : nil)
Chris@1464 124 }.merge(options)),
Chris@210 125 html_options
Chris@210 126 )
Chris@210 127 end
Chris@0 128
Chris@14 129 # Generates a link to a project if active
Chris@14 130 # Examples:
Chris@441 131 #
Chris@14 132 # link_to_project(project) # => link to the specified project overview
Chris@14 133 # link_to_project(project, {:only_path => false}, :class => "project") # => 3rd arg adds html options
Chris@14 134 # link_to_project(project, {}, :class => "project") # => html options with default url (project overview)
Chris@14 135 #
Chris@14 136 def link_to_project(project, options={}, html_options = nil)
Chris@1115 137 if project.archived?
Chris@1464 138 h(project.name)
Chris@1464 139 elsif options.key?(:action)
Chris@1464 140 ActiveSupport::Deprecation.warn "#link_to_project with :action option is deprecated and will be removed in Redmine 3.0."
Chris@1464 141 url = {:controller => 'projects', :action => 'show', :id => project}.merge(options)
Chris@1464 142 link_to project.name, url, html_options
Chris@1115 143 else
Chris@1464 144 link_to project.name, project_path(project, options), html_options
Chris@1464 145 end
Chris@1464 146 end
Chris@1464 147
Chris@1464 148 # Generates a link to a project settings if active
Chris@1464 149 def link_to_project_settings(project, options={}, html_options=nil)
Chris@1464 150 if project.active?
Chris@1464 151 link_to project.name, settings_project_path(project, options), html_options
Chris@1464 152 elsif project.archived?
Chris@1464 153 h(project.name)
Chris@1464 154 else
Chris@1464 155 link_to project.name, project_path(project, options), html_options
Chris@14 156 end
Chris@14 157 end
Chris@14 158
Chris@1115 159 def wiki_page_path(page, options={})
Chris@1115 160 url_for({:controller => 'wiki', :action => 'show', :project_id => page.project, :id => page.title}.merge(options))
Chris@1115 161 end
Chris@1115 162
Chris@1115 163 def thumbnail_tag(attachment)
Chris@1464 164 link_to image_tag(thumbnail_path(attachment)),
Chris@1464 165 named_attachment_path(attachment, attachment.filename),
Chris@1115 166 :title => attachment.filename
Chris@1115 167 end
Chris@1115 168
Chris@0 169 def toggle_link(name, id, options={})
Chris@1115 170 onclick = "$('##{id}').toggle(); "
Chris@1115 171 onclick << (options[:focus] ? "$('##{options[:focus]}').focus(); " : "this.blur(); ")
Chris@0 172 onclick << "return false;"
Chris@0 173 link_to(name, "#", :onclick => onclick)
Chris@0 174 end
Chris@0 175
Chris@0 176 def image_to_function(name, function, html_options = {})
Chris@0 177 html_options.symbolize_keys!
Chris@0 178 tag(:input, html_options.merge({
Chris@0 179 :type => "image", :src => image_path(name),
Chris@0 180 :onclick => (html_options[:onclick] ? "#{html_options[:onclick]}; " : "") + "#{function};"
Chris@0 181 }))
Chris@0 182 end
Chris@0 183
Chris@0 184 def format_activity_title(text)
Chris@0 185 h(truncate_single_line(text, :length => 100))
Chris@0 186 end
Chris@441 187
Chris@0 188 def format_activity_day(date)
Chris@1115 189 date == User.current.today ? l(:label_today).titleize : format_date(date)
Chris@0 190 end
Chris@441 191
Chris@0 192 def format_activity_description(text)
Chris@1115 193 h(truncate(text.to_s, :length => 120).gsub(%r{[\r\n]*<(pre|code)>.*$}m, '...')
Chris@1115 194 ).gsub(/[\r\n]+/, "<br />").html_safe
Chris@0 195 end
Chris@0 196
Chris@0 197 def format_version_name(version)
Chris@0 198 if version.project == @project
Chris@1464 199 h(version)
Chris@0 200 else
Chris@0 201 h("#{version.project} - #{version}")
Chris@0 202 end
Chris@0 203 end
Chris@441 204
Chris@0 205 def due_date_distance_in_words(date)
Chris@0 206 if date
Chris@0 207 l((date < Date.today ? :label_roadmap_overdue : :label_roadmap_due_in), distance_of_date_in_words(Date.today, date))
Chris@0 208 end
Chris@0 209 end
Chris@0 210
Chris@1115 211 # Renders a tree of projects as a nested set of unordered lists
Chris@1115 212 # The given collection may be a subset of the whole project tree
Chris@1115 213 # (eg. some intermediate nodes are private and can not be seen)
Chris@1115 214 def render_project_nested_lists(projects)
Chris@1115 215 s = ''
Chris@1115 216 if projects.any?
Chris@1115 217 ancestors = []
Chris@1115 218 original_project = @project
Chris@1115 219 projects.sort_by(&:lft).each do |project|
Chris@1115 220 # set the project environment to please macros.
Chris@1115 221 @project = project
Chris@1115 222 if (ancestors.empty? || project.is_descendant_of?(ancestors.last))
Chris@1115 223 s << "<ul class='projects #{ ancestors.empty? ? 'root' : nil}'>\n"
Chris@1115 224 else
Chris@1115 225 ancestors.pop
Chris@1115 226 s << "</li>"
Chris@1115 227 while (ancestors.any? && !project.is_descendant_of?(ancestors.last))
Chris@1115 228 ancestors.pop
Chris@1115 229 s << "</ul></li>\n"
Chris@1115 230 end
Chris@1115 231 end
Chris@1115 232 classes = (ancestors.empty? ? 'root' : 'child')
Chris@1115 233 s << "<li class='#{classes}'><div class='#{classes}'>"
Chris@1115 234 s << h(block_given? ? yield(project) : project.name)
Chris@1115 235 s << "</div>\n"
Chris@1115 236 ancestors << project
Chris@1115 237 end
Chris@1115 238 s << ("</li></ul>\n" * ancestors.size)
Chris@1115 239 @project = original_project
Chris@1115 240 end
Chris@1115 241 s.html_safe
Chris@1115 242 end
Chris@1115 243
Chris@441 244 def render_page_hierarchy(pages, node=nil, options={})
Chris@0 245 content = ''
Chris@0 246 if pages[node]
Chris@0 247 content << "<ul class=\"pages-hierarchy\">\n"
Chris@0 248 pages[node].each do |page|
Chris@0 249 content << "<li>"
Chris@1115 250 content << link_to(h(page.pretty_title), {:controller => 'wiki', :action => 'show', :project_id => page.project, :id => page.title, :version => nil},
Chris@441 251 :title => (options[:timestamp] && page.updated_on ? l(:label_updated_time, distance_of_time_in_words(Time.now, page.updated_on)) : nil))
Chris@441 252 content << "\n" + render_page_hierarchy(pages, page.id, options) if pages[page.id]
Chris@0 253 content << "</li>\n"
Chris@0 254 end
Chris@0 255 content << "</ul>\n"
Chris@0 256 end
Chris@909 257 content.html_safe
Chris@0 258 end
Chris@441 259
Chris@0 260 # Renders flash messages
Chris@0 261 def render_flash_messages
Chris@0 262 s = ''
Chris@0 263 flash.each do |k,v|
Chris@1115 264 s << content_tag('div', v.html_safe, :class => "flash #{k}", :id => "flash_#{k}")
Chris@0 265 end
Chris@909 266 s.html_safe
Chris@0 267 end
Chris@441 268
Chris@0 269 # Renders tabs and their content
Chris@0 270 def render_tabs(tabs)
Chris@0 271 if tabs.any?
Chris@0 272 render :partial => 'common/tabs', :locals => {:tabs => tabs}
Chris@0 273 else
Chris@0 274 content_tag 'p', l(:label_no_data), :class => "nodata"
Chris@0 275 end
Chris@0 276 end
Chris@441 277
Chris@0 278 # Renders the project quick-jump box
Chris@0 279 def render_project_jump_box
Chris@441 280 return unless User.current.logged?
Chris@1115 281 projects = User.current.memberships.collect(&:project).compact.select(&:active?).uniq
Chris@0 282 if projects.any?
Chris@1115 283 options =
Chris@1115 284 ("<option value=''>#{ l(:label_jump_to_a_project) }</option>" +
Chris@1115 285 '<option value="" disabled="disabled">---</option>').html_safe
Chris@1115 286
Chris@1115 287 options << project_tree_options_for_select(projects, :selected => @project) do |p|
Chris@1115 288 { :value => project_path(:id => p, :jump => current_menu_item) }
Chris@0 289 end
Chris@1115 290
Chris@1115 291 select_tag('project_quick_jump_box', options, :onchange => 'if (this.value != \'\') { window.location = this.value; }')
Chris@0 292 end
Chris@0 293 end
Chris@441 294
Chris@0 295 def project_tree_options_for_select(projects, options = {})
Chris@0 296 s = ''
Chris@0 297 project_tree(projects) do |project, level|
Chris@1115 298 name_prefix = (level > 0 ? '&nbsp;' * 2 * level + '&#187; ' : '').html_safe
Chris@0 299 tag_options = {:value => project.id}
Chris@0 300 if project == options[:selected] || (options[:selected].respond_to?(:include?) && options[:selected].include?(project))
Chris@0 301 tag_options[:selected] = 'selected'
Chris@0 302 else
Chris@0 303 tag_options[:selected] = nil
Chris@0 304 end
Chris@0 305 tag_options.merge!(yield(project)) if block_given?
Chris@0 306 s << content_tag('option', name_prefix + h(project), tag_options)
Chris@0 307 end
Chris@909 308 s.html_safe
Chris@0 309 end
Chris@441 310
Chris@0 311 # Yields the given block for each project with its level in the tree
chris@37 312 #
chris@37 313 # Wrapper for Project#project_tree
Chris@0 314 def project_tree(projects, &block)
chris@37 315 Project.project_tree(projects, &block)
Chris@0 316 end
Chris@441 317
Chris@0 318 def principals_check_box_tags(name, principals)
Chris@0 319 s = ''
Chris@1464 320 principals.each do |principal|
Chris@1464 321 s << "<label>#{ check_box_tag name, principal.id, false, :id => nil } #{h principal}</label>\n"
Chris@0 322 end
Chris@909 323 s.html_safe
Chris@909 324 end
Chris@909 325
Chris@909 326 # Returns a string for users/groups option tags
Chris@909 327 def principals_options_for_select(collection, selected=nil)
Chris@909 328 s = ''
Chris@1115 329 if collection.include?(User.current)
Chris@1115 330 s << content_tag('option', "<< #{l(:label_me)} >>", :value => User.current.id)
Chris@1115 331 end
Chris@909 332 groups = ''
Chris@909 333 collection.sort.each do |element|
Chris@1464 334 selected_attribute = ' selected="selected"' if option_value_selected?(element, selected) || element.id.to_s == selected
Chris@909 335 (element.is_a?(Group) ? groups : s) << %(<option value="#{element.id}"#{selected_attribute}>#{h element.name}</option>)
Chris@909 336 end
Chris@909 337 unless groups.empty?
Chris@909 338 s << %(<optgroup label="#{h(l(:label_group_plural))}">#{groups}</optgroup>)
Chris@909 339 end
Chris@1115 340 s.html_safe
Chris@1115 341 end
Chris@1115 342
Chris@1115 343 # Options for the new membership projects combo-box
Chris@1115 344 def options_for_membership_project_select(principal, projects)
Chris@1115 345 options = content_tag('option', "--- #{l(:actionview_instancetag_blank_option)} ---")
Chris@1115 346 options << project_tree_options_for_select(projects) do |p|
Chris@1464 347 {:disabled => principal.projects.to_a.include?(p)}
Chris@1115 348 end
Chris@1115 349 options
Chris@0 350 end
Chris@0 351
Chris@1464 352 def option_tag(name, text, value, selected=nil, options={})
Chris@1464 353 content_tag 'option', value, options.merge(:value => value, :selected => (value == selected))
Chris@1464 354 end
Chris@1464 355
Chris@0 356 # Truncates and returns the string as a single line
Chris@0 357 def truncate_single_line(string, *args)
Chris@0 358 truncate(string.to_s, *args).gsub(%r{[\r\n]+}m, ' ')
Chris@0 359 end
Chris@441 360
Chris@0 361 # Truncates at line break after 250 characters or options[:length]
Chris@0 362 def truncate_lines(string, options={})
Chris@0 363 length = options[:length] || 250
Chris@0 364 if string.to_s =~ /\A(.{#{length}}.*?)$/m
Chris@0 365 "#{$1}..."
Chris@0 366 else
Chris@0 367 string
Chris@0 368 end
Chris@0 369 end
Chris@0 370
Chris@1115 371 def anchor(text)
Chris@1115 372 text.to_s.gsub(' ', '_')
Chris@1115 373 end
Chris@1115 374
Chris@0 375 def html_hours(text)
Chris@909 376 text.gsub(%r{(\d+)\.(\d+)}, '<span class="hours hours-int">\1</span><span class="hours hours-dec">.\2</span>').html_safe
Chris@0 377 end
Chris@0 378
Chris@0 379 def authoring(created, author, options={})
Chris@909 380 l(options[:label] || :label_added_time_by, :author => link_to_user(author), :age => time_tag(created)).html_safe
Chris@0 381 end
Chris@441 382
Chris@0 383 def time_tag(time)
Chris@0 384 text = distance_of_time_in_words(Time.now, time)
Chris@0 385 if @project
Chris@1115 386 link_to(text, {:controller => 'activities', :action => 'index', :id => @project, :from => User.current.time_to_date(time)}, :title => format_time(time))
Chris@0 387 else
Chris@1464 388 content_tag('abbr', text, :title => format_time(time))
Chris@0 389 end
Chris@0 390 end
Chris@0 391
Chris@1115 392 def syntax_highlight_lines(name, content)
Chris@1115 393 lines = []
Chris@1115 394 syntax_highlight(name, content).each_line { |line| lines << line }
Chris@1115 395 lines
Chris@1115 396 end
Chris@1115 397
Chris@0 398 def syntax_highlight(name, content)
Chris@0 399 Redmine::SyntaxHighlighting.highlight_by_filename(content, name)
Chris@0 400 end
Chris@0 401
Chris@0 402 def to_path_param(path)
Chris@1115 403 str = path.to_s.split(%r{[/\\]}).select{|p| !p.blank?}.join("/")
Chris@1115 404 str.blank? ? nil : str
Chris@0 405 end
Chris@0 406
Chris@909 407 def reorder_links(name, url, method = :post)
Chris@909 408 link_to(image_tag('2uparrow.png', :alt => l(:label_sort_highest)),
Chris@909 409 url.merge({"#{name}[move_to]" => 'highest'}),
Chris@909 410 :method => method, :title => l(:label_sort_highest)) +
Chris@909 411 link_to(image_tag('1uparrow.png', :alt => l(:label_sort_higher)),
Chris@909 412 url.merge({"#{name}[move_to]" => 'higher'}),
Chris@909 413 :method => method, :title => l(:label_sort_higher)) +
Chris@909 414 link_to(image_tag('1downarrow.png', :alt => l(:label_sort_lower)),
Chris@909 415 url.merge({"#{name}[move_to]" => 'lower'}),
Chris@909 416 :method => method, :title => l(:label_sort_lower)) +
Chris@909 417 link_to(image_tag('2downarrow.png', :alt => l(:label_sort_lowest)),
Chris@909 418 url.merge({"#{name}[move_to]" => 'lowest'}),
Chris@909 419 :method => method, :title => l(:label_sort_lowest))
Chris@0 420 end
Chris@0 421
Chris@0 422 def breadcrumb(*args)
Chris@0 423 elements = args.flatten
Chris@909 424 elements.any? ? content_tag('p', (args.join(" \xc2\xbb ") + " \xc2\xbb ").html_safe, :class => 'breadcrumb') : nil
Chris@0 425 end
Chris@441 426
Chris@0 427 def other_formats_links(&block)
Chris@909 428 concat('<p class="other-formats">'.html_safe + l(:label_export_to))
Chris@0 429 yield Redmine::Views::OtherFormatsBuilder.new(self)
Chris@909 430 concat('</p>'.html_safe)
Chris@0 431 end
Chris@441 432
Chris@0 433 def page_header_title
Chris@0 434 if @project.nil? || @project.new_record?
Chris@0 435 h(Setting.app_title)
Chris@0 436 else
Chris@0 437 b = []
Chris@441 438 ancestors = (@project.root? ? [] : @project.ancestors.visible.all)
Chris@0 439 if ancestors.any?
Chris@0 440 root = ancestors.shift
Chris@14 441 b << link_to_project(root, {:jump => current_menu_item}, :class => 'root')
Chris@0 442 if ancestors.size > 2
Chris@909 443 b << "\xe2\x80\xa6"
Chris@0 444 ancestors = ancestors[-2, 2]
Chris@0 445 end
Chris@14 446 b += ancestors.collect {|p| link_to_project(p, {:jump => current_menu_item}, :class => 'ancestor') }
Chris@0 447 end
Chris@0 448 b << h(@project)
Chris@909 449 b.join(" \xc2\xbb ").html_safe
Chris@0 450 end
Chris@0 451 end
Chris@0 452
Chris@1464 453 # Returns a h2 tag and sets the html title with the given arguments
Chris@1464 454 def title(*args)
Chris@1464 455 strings = args.map do |arg|
Chris@1464 456 if arg.is_a?(Array) && arg.size >= 2
Chris@1464 457 link_to(*arg)
Chris@1464 458 else
Chris@1464 459 h(arg.to_s)
Chris@1464 460 end
Chris@1464 461 end
Chris@1464 462 html_title args.reverse.map {|s| (s.is_a?(Array) ? s.first : s).to_s}
Chris@1464 463 content_tag('h2', strings.join(' &#187; ').html_safe)
Chris@1464 464 end
Chris@1464 465
Chris@1464 466 # Sets the html title
Chris@1464 467 # Returns the html title when called without arguments
Chris@1464 468 # Current project name and app_title and automatically appended
Chris@1464 469 # Exemples:
Chris@1464 470 # html_title 'Foo', 'Bar'
Chris@1464 471 # html_title # => 'Foo - Bar - My Project - Redmine'
Chris@0 472 def html_title(*args)
Chris@0 473 if args.empty?
Chris@909 474 title = @html_title || []
Chris@0 475 title << @project.name if @project
Chris@909 476 title << Setting.app_title unless Setting.app_title == title.last
Chris@1464 477 title.reject(&:blank?).join(' - ')
Chris@0 478 else
Chris@0 479 @html_title ||= []
Chris@0 480 @html_title += args
Chris@0 481 end
Chris@0 482 end
Chris@0 483
Chris@14 484 # Returns the theme, controller name, and action as css classes for the
Chris@14 485 # HTML body.
Chris@14 486 def body_css_classes
Chris@14 487 css = []
Chris@14 488 if theme = Redmine::Themes.theme(Setting.ui_theme)
Chris@14 489 css << 'theme-' + theme.name
Chris@14 490 end
Chris@14 491
Chris@1464 492 css << 'project-' + @project.identifier if @project && @project.identifier.present?
Chris@1115 493 css << 'controller-' + controller_name
Chris@1115 494 css << 'action-' + action_name
Chris@14 495 css.join(' ')
Chris@14 496 end
Chris@14 497
Chris@0 498 def accesskey(s)
Chris@1464 499 @used_accesskeys ||= []
Chris@1464 500 key = Redmine::AccessKeys.key_for(s)
Chris@1464 501 return nil if @used_accesskeys.include?(key)
Chris@1464 502 @used_accesskeys << key
Chris@1464 503 key
Chris@0 504 end
Chris@0 505
Chris@0 506 # Formats text according to system settings.
Chris@0 507 # 2 ways to call this method:
Chris@0 508 # * with a String: textilizable(text, options)
Chris@0 509 # * with an object and one of its attribute: textilizable(issue, :description, options)
Chris@0 510 def textilizable(*args)
Chris@0 511 options = args.last.is_a?(Hash) ? args.pop : {}
Chris@0 512 case args.size
Chris@0 513 when 1
Chris@0 514 obj = options[:object]
Chris@0 515 text = args.shift
Chris@0 516 when 2
Chris@0 517 obj = args.shift
Chris@0 518 attr = args.shift
Chris@0 519 text = obj.send(attr).to_s
Chris@0 520 else
Chris@0 521 raise ArgumentError, 'invalid arguments to textilizable'
Chris@0 522 end
Chris@0 523 return '' if text.blank?
Chris@0 524 project = options[:project] || @project || (obj && obj.respond_to?(:project) ? obj.project : nil)
Chris@0 525 only_path = options.delete(:only_path) == false ? false : true
Chris@0 526
Chris@1115 527 text = text.dup
Chris@1115 528 macros = catch_macros(text)
Chris@909 529 text = Redmine::WikiFormatting.to_html(Setting.text_formatting, text, :object => obj, :attribute => attr)
Chris@441 530
Chris@119 531 @parsed_headings = []
Chris@929 532 @heading_anchors = {}
Chris@909 533 @current_section = 0 if options[:edit_section_links]
Chris@929 534
Chris@929 535 parse_sections(text, project, obj, attr, only_path, options)
Chris@1115 536 text = parse_non_pre_blocks(text, obj, macros) do |text|
Chris@1115 537 [:parse_inline_attachments, :parse_wiki_links, :parse_redmine_links].each do |method_name|
Chris@0 538 send method_name, text, project, obj, attr, only_path, options
Chris@0 539 end
Chris@0 540 end
Chris@929 541 parse_headings(text, project, obj, attr, only_path, options)
Chris@441 542
Chris@119 543 if @parsed_headings.any?
Chris@119 544 replace_toc(text, @parsed_headings)
Chris@119 545 end
Chris@441 546
Chris@1115 547 text.html_safe
Chris@0 548 end
Chris@441 549
Chris@1115 550 def parse_non_pre_blocks(text, obj, macros)
Chris@0 551 s = StringScanner.new(text)
Chris@0 552 tags = []
Chris@0 553 parsed = ''
Chris@0 554 while !s.eos?
Chris@0 555 s.scan(/(.*?)(<(\/)?(pre|code)(.*?)>|\z)/im)
Chris@0 556 text, full_tag, closing, tag = s[1], s[2], s[3], s[4]
Chris@0 557 if tags.empty?
Chris@0 558 yield text
Chris@1115 559 inject_macros(text, obj, macros) if macros.any?
Chris@1115 560 else
Chris@1115 561 inject_macros(text, obj, macros, false) if macros.any?
Chris@0 562 end
Chris@0 563 parsed << text
Chris@0 564 if tag
Chris@0 565 if closing
Chris@0 566 if tags.last == tag.downcase
Chris@0 567 tags.pop
Chris@0 568 end
Chris@0 569 else
Chris@0 570 tags << tag.downcase
Chris@0 571 end
Chris@0 572 parsed << full_tag
Chris@0 573 end
Chris@0 574 end
Chris@0 575 # Close any non closing tags
Chris@0 576 while tag = tags.pop
Chris@0 577 parsed << "</#{tag}>"
Chris@0 578 end
Chris@1115 579 parsed
Chris@0 580 end
Chris@441 581
Chris@0 582 def parse_inline_attachments(text, project, obj, attr, only_path, options)
Chris@0 583 # when using an image link, try to use an attachment, if possible
Chris@1294 584 attachments = options[:attachments] || []
Chris@1294 585 attachments += obj.attachments if obj.respond_to?(:attachments)
Chris@1294 586 if attachments.present?
Chris@909 587 text.gsub!(/src="([^\/"]+\.(bmp|gif|jpg|jpe|jpeg|png))"(\s+alt="([^"]*)")?/i) do |m|
Chris@441 588 filename, ext, alt, alttext = $1.downcase, $2, $3, $4
Chris@0 589 # search for the picture in attachments
Chris@909 590 if found = Attachment.latest_attach(attachments, filename)
Chris@1464 591 image_url = download_named_attachment_path(found, found.filename, :only_path => only_path)
Chris@0 592 desc = found.description.to_s.gsub('"', '')
Chris@0 593 if !desc.blank? && alttext.blank?
Chris@0 594 alt = " title=\"#{desc}\" alt=\"#{desc}\""
Chris@0 595 end
Chris@1115 596 "src=\"#{image_url}\"#{alt}"
Chris@0 597 else
Chris@1115 598 m
Chris@0 599 end
Chris@0 600 end
Chris@0 601 end
Chris@0 602 end
Chris@0 603
Chris@0 604 # Wiki links
Chris@0 605 #
Chris@0 606 # Examples:
Chris@0 607 # [[mypage]]
Chris@0 608 # [[mypage|mytext]]
Chris@0 609 # wiki links can refer other project wikis, using project name or identifier:
Chris@0 610 # [[project:]] -> wiki starting page
Chris@0 611 # [[project:|mytext]]
Chris@0 612 # [[project:mypage]]
Chris@0 613 # [[project:mypage|mytext]]
Chris@0 614 def parse_wiki_links(text, project, obj, attr, only_path, options)
Chris@0 615 text.gsub!(/(!)?(\[\[([^\]\n\|]+)(\|([^\]\n\|]+))?\]\])/) do |m|
Chris@0 616 link_project = project
Chris@0 617 esc, all, page, title = $1, $2, $3, $5
Chris@0 618 if esc.nil?
Chris@0 619 if page =~ /^([^\:]+)\:(.*)$/
Chris@1464 620 identifier, page = $1, $2
Chris@1464 621 link_project = Project.find_by_identifier(identifier) || Project.find_by_name(identifier)
Chris@1464 622 title ||= identifier if page.blank?
Chris@0 623 end
Chris@0 624
Chris@0 625 if link_project && link_project.wiki
Chris@0 626 # extract anchor
Chris@0 627 anchor = nil
Chris@0 628 if page =~ /^(.+?)\#(.+)$/
Chris@0 629 page, anchor = $1, $2
Chris@0 630 end
Chris@909 631 anchor = sanitize_anchor_name(anchor) if anchor.present?
Chris@0 632 # check if page exists
Chris@0 633 wiki_page = link_project.wiki.find_page(page)
Chris@909 634 url = if anchor.present? && wiki_page.present? && (obj.is_a?(WikiContent) || obj.is_a?(WikiContent::Version)) && obj.page == wiki_page
Chris@909 635 "##{anchor}"
Chris@909 636 else
Chris@909 637 case options[:wiki_links]
Chris@909 638 when :local; "#{page.present? ? Wiki.titleize(page) : ''}.html" + (anchor.present? ? "##{anchor}" : '')
Chris@909 639 when :anchor; "##{page.present? ? Wiki.titleize(page) : title}" + (anchor.present? ? "_#{anchor}" : '') # used for single-file wiki export
Chris@0 640 else
chris@37 641 wiki_page_id = page.present? ? Wiki.titleize(page) : nil
Chris@1115 642 parent = wiki_page.nil? && obj.is_a?(WikiContent) && obj.page && project == link_project ? obj.page.title : nil
Chris@1464 643 url_for(:only_path => only_path, :controller => 'wiki', :action => 'show', :project_id => link_project,
Chris@1115 644 :id => wiki_page_id, :version => nil, :anchor => anchor, :parent => parent)
Chris@0 645 end
Chris@909 646 end
Chris@909 647 link_to(title.present? ? title.html_safe : h(page), url, :class => ('wiki-page' + (wiki_page ? '' : ' new')))
Chris@0 648 else
Chris@0 649 # project or wiki doesn't exist
Chris@1115 650 all
Chris@0 651 end
Chris@0 652 else
Chris@1115 653 all
Chris@0 654 end
Chris@0 655 end
Chris@0 656 end
Chris@441 657
Chris@0 658 # Redmine links
Chris@0 659 #
Chris@0 660 # Examples:
Chris@0 661 # Issues:
Chris@0 662 # #52 -> Link to issue #52
Chris@0 663 # Changesets:
Chris@0 664 # r52 -> Link to revision 52
Chris@0 665 # commit:a85130f -> Link to scmid starting with a85130f
Chris@0 666 # Documents:
Chris@0 667 # document#17 -> Link to document with id 17
Chris@0 668 # document:Greetings -> Link to the document with title "Greetings"
Chris@0 669 # document:"Some document" -> Link to the document with title "Some document"
Chris@0 670 # Versions:
Chris@0 671 # version#3 -> Link to version with id 3
Chris@0 672 # version:1.0.0 -> Link to version named "1.0.0"
Chris@0 673 # version:"1.0 beta 2" -> Link to version named "1.0 beta 2"
Chris@0 674 # Attachments:
Chris@0 675 # attachment:file.zip -> Link to the attachment of the current object named file.zip
Chris@0 676 # Source files:
Chris@0 677 # source:some/file -> Link to the file located at /some/file in the project's repository
Chris@0 678 # source:some/file@52 -> Link to the file's revision 52
Chris@0 679 # source:some/file#L120 -> Link to line 120 of the file
Chris@0 680 # source:some/file@52#L120 -> Link to line 120 of the file's revision 52
Chris@0 681 # export:some/file -> Force the download of the file
Chris@210 682 # Forum messages:
Chris@0 683 # message#1218 -> Link to message with id 1218
Chris@1464 684 # Projects:
Chris@1464 685 # project:someproject -> Link to project named "someproject"
Chris@1464 686 # project#3 -> Link to project with id 3
Chris@210 687 #
Chris@210 688 # Links can refer other objects from other projects, using project identifier:
Chris@210 689 # identifier:r52
Chris@210 690 # identifier:document:"Some document"
Chris@210 691 # identifier:version:1.0.0
Chris@210 692 # identifier:source:some/file
Chris@1294 693 def parse_redmine_links(text, default_project, obj, attr, only_path, options)
Chris@1294 694 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 695 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 696 link = nil
Chris@1294 697 project = default_project
Chris@210 698 if project_identifier
Chris@210 699 project = Project.visible.find_by_identifier(project_identifier)
Chris@210 700 end
Chris@0 701 if esc.nil?
Chris@0 702 if prefix.nil? && sep == 'r'
Chris@1115 703 if project
Chris@1115 704 repository = nil
Chris@1115 705 if repo_identifier
Chris@1115 706 repository = project.repositories.detect {|repo| repo.identifier == repo_identifier}
Chris@1115 707 else
Chris@1115 708 repository = project.repository
Chris@1115 709 end
Chris@1115 710 # project.changesets.visible raises an SQL error because of a double join on repositories
Chris@1115 711 if repository && (changeset = Changeset.visible.find_by_repository_id_and_revision(repository.id, identifier))
Chris@1115 712 link = link_to(h("#{project_prefix}#{repo_prefix}r#{identifier}"), {:only_path => only_path, :controller => 'repositories', :action => 'revision', :id => project, :repository_id => repository.identifier_param, :rev => changeset.revision},
Chris@1115 713 :class => 'changeset',
Chris@1115 714 :title => truncate_single_line(changeset.comments, :length => 100))
Chris@1115 715 end
Chris@0 716 end
Chris@0 717 elsif sep == '#'
Chris@0 718 oid = identifier.to_i
Chris@0 719 case prefix
Chris@0 720 when nil
Chris@1115 721 if oid.to_s == identifier && issue = Issue.visible.find_by_id(oid, :include => :status)
Chris@1115 722 anchor = comment_id ? "note-#{comment_id}" : nil
Chris@1464 723 link = link_to(h("##{oid}#{comment_suffix}"), {:only_path => only_path, :controller => 'issues', :action => 'show', :id => oid, :anchor => anchor},
Chris@0 724 :class => issue.css_classes,
Chris@0 725 :title => "#{truncate(issue.subject, :length => 100)} (#{issue.status.name})")
Chris@0 726 end
Chris@0 727 when 'document'
Chris@210 728 if document = Document.visible.find_by_id(oid)
Chris@0 729 link = link_to h(document.title), {:only_path => only_path, :controller => 'documents', :action => 'show', :id => document},
Chris@0 730 :class => 'document'
Chris@0 731 end
Chris@0 732 when 'version'
Chris@210 733 if version = Version.visible.find_by_id(oid)
Chris@0 734 link = link_to h(version.name), {:only_path => only_path, :controller => 'versions', :action => 'show', :id => version},
Chris@0 735 :class => 'version'
Chris@0 736 end
Chris@0 737 when 'message'
Chris@210 738 if message = Message.visible.find_by_id(oid, :include => :parent)
Chris@210 739 link = link_to_message(message, {:only_path => only_path}, :class => 'message')
Chris@0 740 end
Chris@909 741 when 'forum'
Chris@909 742 if board = Board.visible.find_by_id(oid)
Chris@909 743 link = link_to h(board.name), {:only_path => only_path, :controller => 'boards', :action => 'show', :id => board, :project_id => board.project},
Chris@909 744 :class => 'board'
Chris@909 745 end
Chris@909 746 when 'news'
Chris@909 747 if news = News.visible.find_by_id(oid)
Chris@909 748 link = link_to h(news.title), {:only_path => only_path, :controller => 'news', :action => 'show', :id => news},
Chris@909 749 :class => 'news'
Chris@909 750 end
Chris@0 751 when 'project'
Chris@0 752 if p = Project.visible.find_by_id(oid)
Chris@14 753 link = link_to_project(p, {:only_path => only_path}, :class => 'project')
Chris@0 754 end
Chris@0 755 end
Chris@0 756 elsif sep == ':'
Chris@0 757 # removes the double quotes if any
Chris@0 758 name = identifier.gsub(%r{^"(.*)"$}, "\\1")
Chris@0 759 case prefix
Chris@0 760 when 'document'
Chris@210 761 if project && document = project.documents.visible.find_by_title(name)
Chris@0 762 link = link_to h(document.title), {:only_path => only_path, :controller => 'documents', :action => 'show', :id => document},
Chris@0 763 :class => 'document'
Chris@0 764 end
Chris@0 765 when 'version'
Chris@210 766 if project && version = project.versions.visible.find_by_name(name)
Chris@0 767 link = link_to h(version.name), {:only_path => only_path, :controller => 'versions', :action => 'show', :id => version},
Chris@0 768 :class => 'version'
Chris@0 769 end
Chris@909 770 when 'forum'
Chris@909 771 if project && board = project.boards.visible.find_by_name(name)
Chris@909 772 link = link_to h(board.name), {:only_path => only_path, :controller => 'boards', :action => 'show', :id => board, :project_id => board.project},
Chris@909 773 :class => 'board'
Chris@909 774 end
Chris@909 775 when 'news'
Chris@909 776 if project && news = project.news.visible.find_by_title(name)
Chris@909 777 link = link_to h(news.title), {:only_path => only_path, :controller => 'news', :action => 'show', :id => news},
Chris@909 778 :class => 'news'
Chris@909 779 end
Chris@1115 780 when 'commit', 'source', 'export'
Chris@1115 781 if project
Chris@1115 782 repository = nil
Chris@1294 783 if name =~ %r{^(([a-z0-9\-_]+)\|)(.+)$}
Chris@1115 784 repo_prefix, repo_identifier, name = $1, $2, $3
Chris@1115 785 repository = project.repositories.detect {|repo| repo.identifier == repo_identifier}
Chris@1115 786 else
Chris@1115 787 repository = project.repository
Chris@1115 788 end
Chris@1115 789 if prefix == 'commit'
Chris@1464 790 if repository && (changeset = Changeset.visible.where("repository_id = ? AND scmid LIKE ?", repository.id, "#{name}%").first)
Chris@1115 791 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 792 :class => 'changeset',
Chris@1464 793 :title => truncate_single_line(changeset.comments, :length => 100)
Chris@1115 794 end
Chris@1115 795 else
Chris@1115 796 if repository && User.current.allowed_to?(:browse_repository, project)
Chris@1464 797 name =~ %r{^[/\\]*(.*?)(@([^/\\@]+?))?(#(L\d+))?$}
Chris@1115 798 path, rev, anchor = $1, $3, $5
Chris@1115 799 link = link_to h("#{project_prefix}#{prefix}:#{repo_prefix}#{name}"), {:controller => 'repositories', :action => (prefix == 'export' ? 'raw' : 'entry'), :id => project, :repository_id => repository.identifier_param,
Chris@1115 800 :path => to_path_param(path),
Chris@1115 801 :rev => rev,
Chris@1115 802 :anchor => anchor},
Chris@1115 803 :class => (prefix == 'export' ? 'source download' : 'source')
Chris@1115 804 end
Chris@1115 805 end
Chris@1115 806 repo_prefix = nil
Chris@0 807 end
Chris@0 808 when 'attachment'
Chris@0 809 attachments = options[:attachments] || (obj && obj.respond_to?(:attachments) ? obj.attachments : nil)
Chris@1294 810 if attachments && attachment = Attachment.latest_attach(attachments, name)
Chris@1464 811 link = link_to_attachment(attachment, :only_path => only_path, :download => true, :class => 'attachment')
Chris@0 812 end
Chris@0 813 when 'project'
Chris@1464 814 if p = Project.visible.where("identifier = :s OR LOWER(name) = :s", :s => name.downcase).first
Chris@14 815 link = link_to_project(p, {:only_path => only_path}, :class => 'project')
Chris@0 816 end
Chris@0 817 end
Chris@0 818 end
Chris@0 819 end
Chris@1115 820 (leading + (link || "#{project_prefix}#{prefix}#{repo_prefix}#{sep}#{identifier}#{comment_suffix}"))
Chris@0 821 end
Chris@0 822 end
Chris@441 823
Chris@1115 824 HEADING_RE = /(<h(\d)( [^>]+)?>(.+?)<\/h(\d)>)/i unless const_defined?(:HEADING_RE)
Chris@909 825
Chris@909 826 def parse_sections(text, project, obj, attr, only_path, options)
Chris@909 827 return unless options[:edit_section_links]
Chris@909 828 text.gsub!(HEADING_RE) do
Chris@1115 829 heading = $1
Chris@909 830 @current_section += 1
Chris@909 831 if @current_section > 1
Chris@909 832 content_tag('div',
Chris@909 833 link_to(image_tag('edit.png'), options[:edit_section_links].merge(:section => @current_section)),
Chris@909 834 :class => 'contextual',
Chris@1464 835 :title => l(:button_edit_section),
Chris@1464 836 :id => "section-#{@current_section}") + heading.html_safe
Chris@909 837 else
Chris@1115 838 heading
Chris@909 839 end
Chris@909 840 end
Chris@909 841 end
Chris@441 842
chris@37 843 # Headings and TOC
Chris@119 844 # Adds ids and links to headings unless options[:headings] is set to false
chris@37 845 def parse_headings(text, project, obj, attr, only_path, options)
Chris@119 846 return if options[:headings] == false
Chris@441 847
chris@37 848 text.gsub!(HEADING_RE) do
Chris@909 849 level, attrs, content = $2.to_i, $3, $4
chris@37 850 item = strip_tags(content).strip
Chris@909 851 anchor = sanitize_anchor_name(item)
Chris@909 852 # used for single-file wiki export
Chris@909 853 anchor = "#{obj.page.title}_#{anchor}" if options[:wiki_links] == :anchor && (obj.is_a?(WikiContent) || obj.is_a?(WikiContent::Version))
Chris@929 854 @heading_anchors[anchor] ||= 0
Chris@929 855 idx = (@heading_anchors[anchor] += 1)
Chris@929 856 if idx > 1
Chris@929 857 anchor = "#{anchor}-#{idx}"
Chris@929 858 end
Chris@119 859 @parsed_headings << [level, anchor, item]
Chris@441 860 "<a name=\"#{anchor}\"></a>\n<h#{level} #{attrs}>#{content}<a href=\"##{anchor}\" class=\"wiki-anchor\">&para;</a></h#{level}>"
Chris@119 861 end
Chris@119 862 end
Chris@441 863
Chris@1115 864 MACROS_RE = /(
Chris@909 865 (!)? # escaping
Chris@909 866 (
Chris@909 867 \{\{ # opening tag
Chris@909 868 ([\w]+) # macro name
Chris@1115 869 (\(([^\n\r]*?)\))? # optional arguments
Chris@1115 870 ([\n\r].*?[\n\r])? # optional block of text
Chris@909 871 \}\} # closing tag
Chris@909 872 )
Chris@1115 873 )/mx unless const_defined?(:MACROS_RE)
Chris@909 874
Chris@1115 875 MACRO_SUB_RE = /(
Chris@1115 876 \{\{
Chris@1115 877 macro\((\d+)\)
Chris@1115 878 \}\}
Chris@1115 879 )/x unless const_defined?(:MACRO_SUB_RE)
Chris@1115 880
Chris@1115 881 # Extracts macros from text
Chris@1115 882 def catch_macros(text)
Chris@1115 883 macros = {}
Chris@909 884 text.gsub!(MACROS_RE) do
Chris@1115 885 all, macro = $1, $4.downcase
Chris@1115 886 if macro_exists?(macro) || all =~ MACRO_SUB_RE
Chris@1115 887 index = macros.size
Chris@1115 888 macros[index] = all
Chris@1115 889 "{{macro(#{index})}}"
Chris@909 890 else
Chris@909 891 all
Chris@909 892 end
Chris@909 893 end
Chris@1115 894 macros
Chris@1115 895 end
Chris@1115 896
Chris@1115 897 # Executes and replaces macros in text
Chris@1115 898 def inject_macros(text, obj, macros, execute=true)
Chris@1115 899 text.gsub!(MACRO_SUB_RE) do
Chris@1115 900 all, index = $1, $2.to_i
Chris@1115 901 orig = macros.delete(index)
Chris@1115 902 if execute && orig && orig =~ MACROS_RE
Chris@1115 903 esc, all, macro, args, block = $2, $3, $4.downcase, $6.to_s, $7.try(:strip)
Chris@1115 904 if esc.nil?
Chris@1115 905 h(exec_macro(macro, obj, args, block) || all)
Chris@1115 906 else
Chris@1115 907 h(all)
Chris@1115 908 end
Chris@1115 909 elsif orig
Chris@1115 910 h(orig)
Chris@1115 911 else
Chris@1115 912 h(all)
Chris@1115 913 end
Chris@1115 914 end
Chris@909 915 end
Chris@909 916
Chris@119 917 TOC_RE = /<p>\{\{([<>]?)toc\}\}<\/p>/i unless const_defined?(:TOC_RE)
Chris@441 918
Chris@119 919 # Renders the TOC with given headings
Chris@119 920 def replace_toc(text, headings)
chris@37 921 text.gsub!(TOC_RE) do
Chris@1115 922 # Keep only the 4 first levels
Chris@1115 923 headings = headings.select{|level, anchor, item| level <= 4}
chris@37 924 if headings.empty?
chris@37 925 ''
chris@37 926 else
chris@37 927 div_class = 'toc'
chris@37 928 div_class << ' right' if $1 == '>'
chris@37 929 div_class << ' left' if $1 == '<'
chris@37 930 out = "<ul class=\"#{div_class}\"><li>"
chris@37 931 root = headings.map(&:first).min
chris@37 932 current = root
chris@37 933 started = false
chris@37 934 headings.each do |level, anchor, item|
chris@37 935 if level > current
chris@37 936 out << '<ul><li>' * (level - current)
chris@37 937 elsif level < current
chris@37 938 out << "</li></ul>\n" * (current - level) + "</li><li>"
chris@37 939 elsif started
chris@37 940 out << '</li><li>'
chris@37 941 end
chris@37 942 out << "<a href=\"##{anchor}\">#{item}</a>"
chris@37 943 current = level
chris@37 944 started = true
chris@37 945 end
chris@37 946 out << '</li></ul>' * (current - root)
chris@37 947 out << '</li></ul>'
chris@37 948 end
chris@37 949 end
chris@37 950 end
Chris@0 951
Chris@0 952 # Same as Rails' simple_format helper without using paragraphs
Chris@0 953 def simple_format_without_paragraph(text)
Chris@0 954 text.to_s.
Chris@0 955 gsub(/\r\n?/, "\n"). # \r\n and \r -> \n
Chris@0 956 gsub(/\n\n+/, "<br /><br />"). # 2+ newline -> 2 br
Chris@909 957 gsub(/([^\n]\n)(?=[^\n])/, '\1<br />'). # 1 newline -> br
Chris@909 958 html_safe
Chris@0 959 end
Chris@0 960
Chris@0 961 def lang_options_for_select(blank=true)
Chris@1115 962 (blank ? [["(auto)", ""]] : []) + languages_options
Chris@0 963 end
Chris@0 964
Chris@0 965 def label_tag_for(name, option_tags = nil, options = {})
Chris@0 966 label_text = l(("field_"+field.to_s.gsub(/\_id$/, "")).to_sym) + (options.delete(:required) ? @template.content_tag("span", " *", :class => "required"): "")
Chris@0 967 content_tag("label", label_text)
Chris@0 968 end
Chris@0 969
Chris@1115 970 def labelled_form_for(*args, &proc)
Chris@909 971 args << {} unless args.last.is_a?(Hash)
Chris@909 972 options = args.last
Chris@1115 973 if args.first.is_a?(Symbol)
Chris@1115 974 options.merge!(:as => args.shift)
Chris@1115 975 end
Chris@1115 976 options.merge!({:builder => Redmine::Views::LabelledFormBuilder})
Chris@909 977 form_for(*args, &proc)
Chris@909 978 end
Chris@909 979
Chris@1115 980 def labelled_fields_for(*args, &proc)
Chris@909 981 args << {} unless args.last.is_a?(Hash)
Chris@909 982 options = args.last
Chris@1115 983 options.merge!({:builder => Redmine::Views::LabelledFormBuilder})
Chris@1115 984 fields_for(*args, &proc)
Chris@1115 985 end
Chris@1115 986
Chris@1115 987 def labelled_remote_form_for(*args, &proc)
Chris@1115 988 ActiveSupport::Deprecation.warn "ApplicationHelper#labelled_remote_form_for is deprecated and will be removed in Redmine 2.2."
Chris@1115 989 args << {} unless args.last.is_a?(Hash)
Chris@1115 990 options = args.last
Chris@1115 991 options.merge!({:builder => Redmine::Views::LabelledFormBuilder, :remote => true})
Chris@909 992 form_for(*args, &proc)
Chris@0 993 end
Chris@0 994
Chris@1115 995 def error_messages_for(*objects)
Chris@1115 996 html = ""
Chris@1115 997 objects = objects.map {|o| o.is_a?(String) ? instance_variable_get("@#{o}") : o}.compact
Chris@1115 998 errors = objects.map {|o| o.errors.full_messages}.flatten
Chris@1115 999 if errors.any?
Chris@1115 1000 html << "<div id='errorExplanation'><ul>\n"
Chris@1115 1001 errors.each do |error|
Chris@1115 1002 html << "<li>#{h error}</li>\n"
Chris@1115 1003 end
Chris@1115 1004 html << "</ul></div>\n"
Chris@1115 1005 end
Chris@1115 1006 html.html_safe
Chris@1464 1007 end
Chris@1115 1008
Chris@1115 1009 def delete_link(url, options={})
Chris@1115 1010 options = {
Chris@1115 1011 :method => :delete,
Chris@1115 1012 :data => {:confirm => l(:text_are_you_sure)},
Chris@1115 1013 :class => 'icon icon-del'
Chris@1115 1014 }.merge(options)
Chris@1115 1015
Chris@1115 1016 link_to l(:button_delete), url, options
Chris@1115 1017 end
Chris@1115 1018
Chris@1115 1019 def preview_link(url, form, target='preview', options={})
Chris@1115 1020 content_tag 'a', l(:label_preview), {
Chris@1464 1021 :href => "#",
Chris@1464 1022 :onclick => %|submitPreview("#{escape_javascript url_for(url)}", "#{escape_javascript form}", "#{escape_javascript target}"); return false;|,
Chris@1115 1023 :accesskey => accesskey(:preview)
Chris@1115 1024 }.merge(options)
Chris@1115 1025 end
Chris@1115 1026
Chris@1115 1027 def link_to_function(name, function, html_options={})
Chris@1115 1028 content_tag(:a, name, {:href => '#', :onclick => "#{function}; return false;"}.merge(html_options))
Chris@1115 1029 end
Chris@1115 1030
Chris@1115 1031 # Helper to render JSON in views
Chris@1115 1032 def raw_json(arg)
Chris@1115 1033 arg.to_json.to_s.gsub('/', '\/').html_safe
Chris@1115 1034 end
Chris@1115 1035
Chris@1115 1036 def back_url
Chris@1115 1037 url = params[:back_url]
Chris@1115 1038 if url.nil? && referer = request.env['HTTP_REFERER']
Chris@1115 1039 url = CGI.unescape(referer.to_s)
Chris@1115 1040 end
Chris@1115 1041 url
Chris@1115 1042 end
Chris@1115 1043
Chris@0 1044 def back_url_hidden_field_tag
Chris@1115 1045 url = back_url
Chris@1115 1046 hidden_field_tag('back_url', url, :id => nil) unless url.blank?
Chris@0 1047 end
Chris@0 1048
Chris@0 1049 def check_all_links(form_name)
Chris@0 1050 link_to_function(l(:button_check_all), "checkAll('#{form_name}', true)") +
Chris@909 1051 " | ".html_safe +
Chris@0 1052 link_to_function(l(:button_uncheck_all), "checkAll('#{form_name}', false)")
Chris@0 1053 end
Chris@0 1054
Chris@0 1055 def progress_bar(pcts, options={})
Chris@0 1056 pcts = [pcts, pcts] unless pcts.is_a?(Array)
Chris@0 1057 pcts = pcts.collect(&:round)
Chris@0 1058 pcts[1] = pcts[1] - pcts[0]
Chris@0 1059 pcts << (100 - pcts[1] - pcts[0])
Chris@0 1060 width = options[:width] || '100px;'
Chris@0 1061 legend = options[:legend] || ''
Chris@0 1062 content_tag('table',
Chris@0 1063 content_tag('tr',
Chris@909 1064 (pcts[0] > 0 ? content_tag('td', '', :style => "width: #{pcts[0]}%;", :class => 'closed') : ''.html_safe) +
Chris@909 1065 (pcts[1] > 0 ? content_tag('td', '', :style => "width: #{pcts[1]}%;", :class => 'done') : ''.html_safe) +
Chris@909 1066 (pcts[2] > 0 ? content_tag('td', '', :style => "width: #{pcts[2]}%;", :class => 'todo') : ''.html_safe)
Chris@1464 1067 ), :class => "progress progress-#{pcts[0]}", :style => "width: #{width};").html_safe +
Chris@1464 1068 content_tag('p', legend, :class => 'percent').html_safe
Chris@0 1069 end
Chris@441 1070
Chris@0 1071 def checked_image(checked=true)
Chris@0 1072 if checked
Chris@0 1073 image_tag 'toggle_check.png'
Chris@0 1074 end
Chris@0 1075 end
Chris@441 1076
Chris@0 1077 def context_menu(url)
Chris@0 1078 unless @context_menu_included
Chris@0 1079 content_for :header_tags do
Chris@0 1080 javascript_include_tag('context_menu') +
Chris@0 1081 stylesheet_link_tag('context_menu')
Chris@0 1082 end
Chris@14 1083 if l(:direction) == 'rtl'
Chris@14 1084 content_for :header_tags do
Chris@14 1085 stylesheet_link_tag('context_menu_rtl')
Chris@14 1086 end
Chris@14 1087 end
Chris@0 1088 @context_menu_included = true
Chris@0 1089 end
Chris@1115 1090 javascript_tag "contextMenuInit('#{ url_for(url) }')"
Chris@0 1091 end
Chris@0 1092
Chris@0 1093 def calendar_for(field_id)
Chris@0 1094 include_calendar_headers_tags
Chris@1115 1095 javascript_tag("$(function() { $('##{field_id}').datepicker(datepickerOptions); });")
Chris@0 1096 end
Chris@0 1097
Chris@0 1098 def include_calendar_headers_tags
Chris@0 1099 unless @calendar_headers_tags_included
Chris@1464 1100 tags = javascript_include_tag("datepicker")
Chris@0 1101 @calendar_headers_tags_included = true
Chris@0 1102 content_for :header_tags do
Chris@1115 1103 start_of_week = Setting.start_of_week
Chris@1115 1104 start_of_week = l(:general_first_day_of_week, :default => '1') if start_of_week.blank?
Chris@1115 1105 # Redmine uses 1..7 (monday..sunday) in settings and locales
Chris@1115 1106 # JQuery uses 0..6 (sunday..saturday), 7 needs to be changed to 0
Chris@1115 1107 start_of_week = start_of_week.to_i % 7
Chris@1464 1108 tags << javascript_tag(
Chris@1115 1109 "var datepickerOptions={dateFormat: 'yy-mm-dd', firstDay: #{start_of_week}, " +
Chris@1464 1110 "showOn: 'button', buttonImageOnly: true, buttonImage: '" +
Chris@1115 1111 path_to_image('/images/calendar.png') +
Chris@1464 1112 "', showButtonPanel: true, showWeek: true, showOtherMonths: true, " +
Chris@1464 1113 "selectOtherMonths: true, changeMonth: true, changeYear: true, " +
Chris@1464 1114 "beforeShow: beforeShowDatePicker};")
Chris@1115 1115 jquery_locale = l('jquery.locale', :default => current_language.to_s)
Chris@1115 1116 unless jquery_locale == 'en'
Chris@1464 1117 tags << javascript_include_tag("i18n/jquery.ui.datepicker-#{jquery_locale}.js")
Chris@0 1118 end
Chris@1115 1119 tags
Chris@0 1120 end
Chris@0 1121 end
Chris@0 1122 end
Chris@0 1123
Chris@1115 1124 # Overrides Rails' stylesheet_link_tag with themes and plugins support.
Chris@1115 1125 # Examples:
Chris@1115 1126 # stylesheet_link_tag('styles') # => picks styles.css from the current theme or defaults
Chris@1115 1127 # stylesheet_link_tag('styles', :plugin => 'foo) # => picks styles.css from plugin's assets
Chris@1115 1128 #
Chris@1115 1129 def stylesheet_link_tag(*sources)
Chris@1115 1130 options = sources.last.is_a?(Hash) ? sources.pop : {}
Chris@1115 1131 plugin = options.delete(:plugin)
Chris@1115 1132 sources = sources.map do |source|
Chris@1115 1133 if plugin
Chris@1115 1134 "/plugin_assets/#{plugin}/stylesheets/#{source}"
Chris@1115 1135 elsif current_theme && current_theme.stylesheets.include?(source)
Chris@1115 1136 current_theme.stylesheet_path(source)
Chris@1115 1137 else
Chris@1115 1138 source
Chris@1115 1139 end
Chris@1115 1140 end
Chris@1115 1141 super sources, options
Chris@1115 1142 end
Chris@1115 1143
Chris@1115 1144 # Overrides Rails' image_tag with themes and plugins support.
Chris@1115 1145 # Examples:
Chris@1115 1146 # image_tag('image.png') # => picks image.png from the current theme or defaults
Chris@1115 1147 # image_tag('image.png', :plugin => 'foo) # => picks image.png from plugin's assets
Chris@1115 1148 #
Chris@1115 1149 def image_tag(source, options={})
Chris@1115 1150 if plugin = options.delete(:plugin)
Chris@1115 1151 source = "/plugin_assets/#{plugin}/images/#{source}"
Chris@1115 1152 elsif current_theme && current_theme.images.include?(source)
Chris@1115 1153 source = current_theme.image_path(source)
Chris@1115 1154 end
Chris@1115 1155 super source, options
Chris@1115 1156 end
Chris@1115 1157
Chris@1115 1158 # Overrides Rails' javascript_include_tag with plugins support
Chris@1115 1159 # Examples:
Chris@1115 1160 # javascript_include_tag('scripts') # => picks scripts.js from defaults
Chris@1115 1161 # javascript_include_tag('scripts', :plugin => 'foo) # => picks scripts.js from plugin's assets
Chris@1115 1162 #
Chris@1115 1163 def javascript_include_tag(*sources)
Chris@1115 1164 options = sources.last.is_a?(Hash) ? sources.pop : {}
Chris@1115 1165 if plugin = options.delete(:plugin)
Chris@1115 1166 sources = sources.map do |source|
Chris@1115 1167 if plugin
Chris@1115 1168 "/plugin_assets/#{plugin}/javascripts/#{source}"
Chris@1115 1169 else
Chris@1115 1170 source
Chris@1115 1171 end
Chris@1115 1172 end
Chris@1115 1173 end
Chris@1115 1174 super sources, options
Chris@1115 1175 end
Chris@1115 1176
Chris@1464 1177 # TODO: remove this in 2.5.0
Chris@0 1178 def has_content?(name)
Chris@1464 1179 content_for?(name)
Chris@0 1180 end
Chris@0 1181
Chris@1115 1182 def sidebar_content?
Chris@1464 1183 content_for?(:sidebar) || view_layouts_base_sidebar_hook_response.present?
Chris@1115 1184 end
Chris@1115 1185
Chris@1115 1186 def view_layouts_base_sidebar_hook_response
Chris@1115 1187 @view_layouts_base_sidebar_hook_response ||= call_hook(:view_layouts_base_sidebar)
Chris@1115 1188 end
Chris@1115 1189
Chris@909 1190 def email_delivery_enabled?
Chris@909 1191 !!ActionMailer::Base.perform_deliveries
Chris@909 1192 end
Chris@909 1193
Chris@0 1194 # Returns the avatar image tag for the given +user+ if avatars are enabled
Chris@0 1195 # +user+ can be a User or a string that will be scanned for an email address (eg. 'joe <joe@foo.bar>')
Chris@0 1196 def avatar(user, options = { })
Chris@0 1197 if Setting.gravatar_enabled?
Chris@1115 1198 options.merge!({:ssl => (request && request.ssl?), :default => Setting.gravatar_default})
Chris@0 1199 email = nil
Chris@0 1200 if user.respond_to?(:mail)
Chris@0 1201 email = user.mail
Chris@0 1202 elsif user.to_s =~ %r{<(.+?)>}
Chris@0 1203 email = $1
Chris@0 1204 end
Chris@0 1205 return gravatar(email.to_s.downcase, options) unless email.blank? rescue nil
chris@22 1206 else
chris@22 1207 ''
Chris@0 1208 end
Chris@0 1209 end
Chris@441 1210
Chris@909 1211 def sanitize_anchor_name(anchor)
Chris@1115 1212 if ''.respond_to?(:encoding) || RUBY_PLATFORM == 'java'
Chris@1464 1213 anchor.gsub(%r{[^\s\-\p{Word}]}, '').gsub(%r{\s+(\-+\s*)?}, '-')
Chris@1115 1214 else
Chris@1115 1215 # TODO: remove when ruby1.8 is no longer supported
Chris@1115 1216 anchor.gsub(%r{[^\w\s\-]}, '').gsub(%r{\s+(\-+\s*)?}, '-')
Chris@1115 1217 end
Chris@909 1218 end
Chris@909 1219
Chris@245 1220 # Returns the javascript tags that are included in the html layout head
Chris@245 1221 def javascript_heads
Chris@1464 1222 tags = javascript_include_tag('jquery-1.8.3-ui-1.9.2-ujs-2.0.3', 'application')
Chris@245 1223 unless User.current.pref.warn_on_leaving_unsaved == '0'
Chris@1115 1224 tags << "\n".html_safe + javascript_tag("$(window).load(function(){ warnLeavingUnsaved('#{escape_javascript l(:text_warn_on_leaving_unsaved)}'); });")
Chris@245 1225 end
Chris@245 1226 tags
Chris@245 1227 end
Chris@0 1228
Chris@14 1229 def favicon
Chris@909 1230 "<link rel='shortcut icon' href='#{image_path('/favicon.ico')}' />".html_safe
Chris@14 1231 end
Chris@441 1232
Chris@441 1233 def robot_exclusion_tag
Chris@909 1234 '<meta name="robots" content="noindex,follow,noarchive" />'.html_safe
Chris@441 1235 end
Chris@441 1236
Chris@119 1237 # Returns true if arg is expected in the API response
Chris@119 1238 def include_in_api_response?(arg)
Chris@119 1239 unless @included_in_api_response
Chris@119 1240 param = params[:include]
Chris@119 1241 @included_in_api_response = param.is_a?(Array) ? param.collect(&:to_s) : param.to_s.split(',')
Chris@119 1242 @included_in_api_response.collect!(&:strip)
Chris@119 1243 end
Chris@119 1244 @included_in_api_response.include?(arg.to_s)
Chris@119 1245 end
Chris@14 1246
Chris@119 1247 # Returns options or nil if nometa param or X-Redmine-Nometa header
Chris@119 1248 # was set in the request
Chris@119 1249 def api_meta(options)
Chris@119 1250 if params[:nometa].present? || request.headers['X-Redmine-Nometa']
Chris@119 1251 # compatibility mode for activeresource clients that raise
Chris@119 1252 # an error when unserializing an array with attributes
Chris@119 1253 nil
Chris@119 1254 else
Chris@119 1255 options
Chris@119 1256 end
Chris@119 1257 end
Chris@441 1258
Chris@0 1259 private
Chris@0 1260
Chris@0 1261 def wiki_helper
Chris@0 1262 helper = Redmine::WikiFormatting.helper_for(Setting.text_formatting)
Chris@0 1263 extend helper
Chris@0 1264 return self
Chris@0 1265 end
Chris@441 1266
Chris@441 1267 def link_to_content_update(text, url_params = {}, html_options = {})
Chris@441 1268 link_to(text, url_params, html_options)
Chris@0 1269 end
Chris@0 1270 end