annotate app/helpers/application_helper.rb @ 1628:9c5f8e24dadc live tip

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