annotate app/helpers/application_helper.rb @ 1465:ab8bd24eeb65 bug_635

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