To check out this repository please hg clone the following URL, or open the URL using EasyMercurial or your preferred Mercurial client.

Statistics Download as Zip
| Branch: | Tag: | Revision:

root / app / helpers / application_helper.rb @ 1297:0a574315af3e

History | View | Annotate | Download (48 KB)

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