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 @ 1330:441b66f148b6

History | View | Annotate | Download (48 KB)

1
# encoding: utf-8
2
#
3
# Redmine - project management software
4
# Copyright (C) 2006-2012  Jean-Philippe Lang
5
#
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
  #
38
  # @param [String] name Anchor text (passed to link_to)
39
  # @param [Hash] options Hash params. This will checked by authorize_for to see if the user is authorized
40
  # @param [optional, Hash] html_options Options passed to link_to
41
  # @param [optional, Hash] parameters_for_method_reference Extra parameters for link_to
42
  def link_to_if_authorized(name, options = {}, html_options = nil, *parameters_for_method_reference)
43
    link_to(name, options, html_options, *parameters_for_method_reference) if authorize_for(options[:controller] || params[:controller], options[:action])
44
  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
      if user.active? || (User.current.admin? && user.logged?)
51
        link_to name, user_path(user), :class => user.css_classes
52
      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
  #
63
  #   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
  #   link_to_issue(issue, :subject => false, :tracker => false)     # => #6
68
  #
69
  def link_to_issue(issue, options={})
70
    title = nil
71
    subject = nil
72
    text = options[:tracker] == false ? "##{issue.id}" : "#{issue.tracker} ##{issue.id}"
73
    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
    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
    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
    opt_only_path = {}
95
    opt_only_path[:only_path] = (options[:only_path] == false ? false : true)
96
    options.delete(:only_path)
97
    link_to(h(text),
98
           {:controller => 'attachments', :action => action,
99
            :id => attachment, :filename => attachment.filename}.merge(opt_only_path),
100
           options)
101
  end
102

    
103
  # Generates a link to a SCM revision
104
  # Options:
105
  # * :text - Link text (default to the formatted revision)
106
  def link_to_revision(revision, repository, options={})
107
    if repository.is_a?(Project)
108
      repository = repository.repository
109
    end
110
    text = options.delete(:text) || format_revision(revision)
111
    rev = revision.respond_to?(:identifier) ? revision.identifier : revision
112
    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
  end
118

    
119
  # 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
        :id => (message.parent_id || message.id),
126
        :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

    
133
  # Generates a link to a project if active
134
  # Examples:
135
  #
136
  #   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
    if project.archived?
143
      h(project)
144
    else
145
      url = {:controller => 'projects', :action => 'show', :id => project}.merge(options)
146
      link_to(h(project), url, html_options)
147
    end
148
  end
149

    
150
  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
  def toggle_link(name, id, options={})
161
    onclick = "$('##{id}').toggle(); "
162
    onclick << (options[:focus] ? "$('##{options[:focus]}').focus(); " : "this.blur(); ")
163
    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

    
179
  def format_activity_day(date)
180
    date == User.current.today ? l(:label_today).titleize : format_date(date)
181
  end
182

    
183
  def format_activity_description(text)
184
    h(truncate(text.to_s, :length => 120).gsub(%r{[\r\n]*<(pre|code)>.*$}m, '...')
185
       ).gsub(/[\r\n]+/, "<br />").html_safe
186
  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

    
196
  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
  # 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
  def render_page_hierarchy(pages, node=nil, options={})
236
    content = ''
237
    if pages[node]
238
      content << "<ul class=\"pages-hierarchy\">\n"
239
      pages[node].each do |page|
240
        content << "<li>"
241
        content << link_to(h(page.pretty_title), {:controller => 'wiki', :action => 'show', :project_id => page.project, :id => page.title, :version => nil},
242
                           :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
        content << "</li>\n"
245
      end
246
      content << "</ul>\n"
247
    end
248
    content.html_safe
249
  end
250

    
251
  # Renders flash messages
252
  def render_flash_messages
253
    s = ''
254
    flash.each do |k,v|
255
      s << content_tag('div', v.html_safe, :class => "flash #{k}", :id => "flash_#{k}")
256
    end
257
    s.html_safe
258
  end
259

    
260
  # 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

    
269
  # Renders the project quick-jump box
270
  def render_project_jump_box
271
    return unless User.current.logged?
272
    projects = User.current.memberships.collect(&:project).compact.select(&:active?).uniq
273
    if projects.any?
274
      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
      end
281

    
282
      select_tag('project_quick_jump_box', options, :onchange => 'if (this.value != \'\') { window.location = this.value; }')
283
    end
284
  end
285

    
286
  def project_tree_options_for_select(projects, options = {})
287
    s = ''
288
    project_tree(projects) do |project, level|
289
      name_prefix = (level > 0 ? '&nbsp;' * 2 * level + '&#187; ' : '').html_safe
290
      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
    s.html_safe
300
  end
301

    
302
  # Yields the given block for each project with its level in the tree
303
  #
304
  # Wrapper for Project#project_tree
305
  def project_tree(projects, &block)
306
    Project.project_tree(projects, &block)
307
  end
308

    
309
  def principals_check_box_tags(name, principals)
310
    s = ''
311
    principals.sort.each do |principal|
312

    
313
      if principal.type == "User"
314
        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

    
319
    end
320
    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
    if collection.include?(User.current)
327
      s << content_tag('option', "<< #{l(:label_me)} >>", :value => User.current.id)
328
    end
329
    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
    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
  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

    
354
  # 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
  def anchor(text)
365
    text.to_s.gsub(' ', '_')
366
  end
367

    
368
  def html_hours(text)
369
    text.gsub(%r{(\d+)\.(\d+)}, '<span class="hours hours-int">\1</span><span class="hours hours-dec">.\2</span>').html_safe
370
  end
371

    
372
  def authoring(created, author, options={})
373
    l(options[:label] || :label_added_time_by, :author => link_to_user(author), :age => time_tag(created)).html_safe
374
  end
375

    
376
  def time_tag(time)
377
    text = distance_of_time_in_words(Time.now, time)
378
    if @project
379
      link_to(text, {:controller => 'activities', :action => 'index', :id => @project, :from => User.current.time_to_date(time)}, :title => format_time(time))
380
    else
381
      content_tag('acronym', text, :title => format_time(time))
382
    end
383
  end
384

    
385
  def syntax_highlight_lines(name, content)
386
    lines = []
387
    syntax_highlight(name, content).each_line { |line| lines << line }
388
    lines
389
  end
390

    
391
  def syntax_highlight(name, content)
392
    Redmine::SyntaxHighlighting.highlight_by_filename(content, name)
393
  end
394

    
395
  def to_path_param(path)
396
    str = path.to_s.split(%r{[/\\]}).select{|p| !p.blank?}.join("/")
397
    str.blank? ? nil : str
398
  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
      # \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
    end
412

    
413
    html << (pagination_links_each(paginator, options) do |n|
414
      link_to_content_update(n.to_s, url_param.merge(page_param => n))
415
    end || '')
416

    
417
    if paginator.current.next
418
      # \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
    end
423

    
424
    unless count.nil?
425
      html << " (#{paginator.current.first_item}-#{paginator.current.last_item}/#{count})"
426
      if per_page_links != false && links = per_page_links(paginator.items_per_page, count)
427
              html << " | #{links}"
428
      end
429
    end
430

    
431
    html.html_safe
432
  end
433

    
434
  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
      n == selected ? n : link_to_content_update(n, params.merge(:per_page => n))
449
    end
450
    l(:label_display_per_page, links.join(', '))
451
  end
452

    
453
  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
  end
467

    
468
  def breadcrumb(*args)
469
    elements = args.flatten
470
    elements.any? ? content_tag('p', (args.join(" \xc2\xbb ") + " \xc2\xbb ").html_safe, :class => 'breadcrumb') : nil
471
  end
472

    
473
  def other_formats_links(&block)
474
    concat('<p class="other-formats">'.html_safe + l(:label_export_to))
475
    yield Redmine::Views::OtherFormatsBuilder.new(self)
476
    concat('</p>'.html_safe)
477
  end
478

    
479
  def page_header_title
480
    if @project.nil? || @project.new_record?
481
      a = [h(Setting.app_title), '']
482

    
483
    else
484
      pname = []
485
      b = []
486
      ancestors = (@project.root? ? [] : @project.ancestors.visible.all)
487
      if ancestors.any?
488
        root = ancestors.shift
489
        b << link_to_project(root, {:jump => current_menu_item}, :class => 'root')
490
        if ancestors.size > 2
491
          b << '&#8230;'
492
          ancestors = ancestors[-2, 2]
493
        end
494
        b += ancestors.collect {|p| link_to_project(p, {:jump => current_menu_item}, :class => 'ancestor') }
495
        b = b.join(' &#187; ').html_safe
496
        b << (' &#187;'.html_safe)
497
      end
498

    
499
      pname << h(@project)
500

    
501
      a = [pname, b]
502

    
503
    end
504
  end
505

    
506
  def html_title(*args)
507
    if args.empty?
508
      title = @html_title || []
509
      title << @project.name if @project
510
      title << Setting.app_title unless Setting.app_title == title.last
511
      title.select {|t| !t.blank? }.join(' - ')
512
    else
513
      @html_title ||= []
514
      @html_title += args
515
    end
516
  end
517

    
518
  # 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
    css << 'controller-' + controller_name
527
    css << 'action-' + action_name
528
    css.join(' ')
529
  end
530

    
531
  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
    text = text.dup
557
    macros = catch_macros(text)
558
    text = Redmine::WikiFormatting.to_html(Setting.text_formatting, text, :object => obj, :attribute => attr)
559

    
560
    @parsed_headings = []
561
    @heading_anchors = {}
562
    @current_section = 0 if options[:edit_section_links]
563

    
564
    parse_sections(text, project, obj, attr, only_path, options)
565
    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
        send method_name, text, project, obj, attr, only_path, options
568
      end
569
    end
570
    parse_headings(text, project, obj, attr, only_path, options)
571

    
572
    if @parsed_headings.any?
573
      replace_toc(text, @parsed_headings)
574
    end
575

    
576
    text.html_safe
577
  end
578

    
579
  def parse_non_pre_blocks(text, obj, macros)
580
    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
        inject_macros(text, obj, macros) if macros.any?
589
      else
590
        inject_macros(text, obj, macros, false) if macros.any?
591
      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
    parsed
609
  end
610

    
611
  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
    attachments = options[:attachments] || []
614
    attachments += obj.attachments if obj.respond_to?(:attachments)
615
    if attachments.present?
616
      text.gsub!(/src="([^\/"]+\.(bmp|gif|jpg|jpe|jpeg|png))"(\s+alt="([^"]*)")?/i) do |m|
617
        filename, ext, alt, alttext = $1.downcase, $2, $3, $4
618
        # search for the picture in attachments
619
        if found = Attachment.latest_attach(attachments, filename)
620
          image_url = url_for :only_path => only_path, :controller => 'attachments',
621
                              :action => 'download', :id => found
622
          desc = found.description.to_s.gsub('"', '')
623
          if !desc.blank? && alttext.blank?
624
            alt = " title=\"#{desc}\" alt=\"#{desc}\""
625
          end
626
          "src=\"#{image_url}\"#{alt}"
627
        else
628
          m
629
        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
          link_project = Project.find_by_identifier($1) || Project.find_by_name($1)
651
          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
          anchor = sanitize_anchor_name(anchor) if anchor.present?
662
          # check if page exists
663
          wiki_page = link_project.wiki.find_page(page)
664
          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
            else
671
              wiki_page_id = page.present? ? Wiki.titleize(page) : nil
672
              parent = wiki_page.nil? && obj.is_a?(WikiContent) && obj.page && project == link_project ? obj.page.title : nil
673
              url_for(:only_path => only_path, :controller => 'wiki', :action => 'show', :project_id => link_project,
674
               :id => wiki_page_id, :version => nil, :anchor => anchor, :parent => parent)
675
            end
676
          end
677
          link_to(title.present? ? title.html_safe : h(page), url, :class => ('wiki-page' + (wiki_page ? '' : ' new')))
678
        else
679
          # project or wiki doesn't exist
680
          all
681
        end
682
      else
683
        all
684
      end
685
    end
686
  end
687

    
688
  # 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
  #   Forum messages:
713
  #     message#1218 -> Link to message with id 1218
714
  #
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
  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
      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
      link = nil
724
      project = default_project
725
      if project_identifier
726
        project = Project.visible.find_by_identifier(project_identifier)
727
      end
728
      if esc.nil?
729
        if prefix.nil? && sep == 'r'
730
          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
          end
744
        elsif sep == '#'
745
          oid = identifier.to_i
746
          case prefix
747
          when nil
748
            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
                                        :class => issue.css_classes,
752
                                        :title => "#{truncate(issue.subject, :length => 100)} (#{issue.status.name})")
753
            end
754
          when 'document'
755
            if document = Document.visible.find_by_id(oid)
756
              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
            if version = Version.visible.find_by_id(oid)
761
              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
            if message = Message.visible.find_by_id(oid, :include => :parent)
766
              link = link_to_message(message, {:only_path => only_path}, :class => 'message')
767
            end
768
          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
          when 'project'
779
            if p = Project.visible.find_by_id(oid)
780
              link = link_to_project(p, {:only_path => only_path}, :class => 'project')
781
            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
            if project && document = project.documents.visible.find_by_title(name)
789
              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
            if project && version = project.versions.visible.find_by_name(name)
794
              link = link_to h(version.name), {:only_path => only_path, :controller => 'versions', :action => 'show', :id => version},
795
                                              :class => 'version'
796
            end
797
          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
          when 'commit', 'source', 'export'
808
            if project
809
              repository = nil
810
              if name =~ %r{^(([a-z0-9\-_]+)\|)(.+)$}
811
                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
            end
835
          when 'attachment'
836
            attachments = options[:attachments] || (obj && obj.respond_to?(:attachments) ? obj.attachments : nil)
837
            if attachments && attachment = Attachment.latest_attach(attachments, name)
838
              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
              link = link_to_project(p, {:only_path => only_path}, :class => 'project')
844
            end
845
          end
846
        end
847
      end
848
      (leading + (link || "#{project_prefix}#{prefix}#{repo_prefix}#{sep}#{identifier}#{comment_suffix}"))
849
    end
850
  end
851

    
852
  HEADING_RE = /(<h(\d)( [^>]+)?>(.+?)<\/h(\d)>)/i unless const_defined?(:HEADING_RE)
853

    
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
      heading = $1
858
      @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
          :title => l(:button_edit_section)) + heading.html_safe
864
      else
865
        heading
866
      end
867
    end
868
  end
869

    
870
  # Headings and TOC
871
  # Adds ids and links to headings unless options[:headings] is set to false
872
  def parse_headings(text, project, obj, attr, only_path, options)
873
    return if options[:headings] == false
874

    
875
    text.gsub!(HEADING_RE) do
876
      level, attrs, content = $2.to_i, $3, $4
877
      item = strip_tags(content).strip
878
      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
      @heading_anchors[anchor] ||= 0
882
      idx = (@heading_anchors[anchor] += 1)
883
      if idx > 1
884
        anchor = "#{anchor}-#{idx}"
885
      end
886
      @parsed_headings << [level, anchor, item]
887
      "<a name=\"#{anchor}\"></a>\n<h#{level} #{attrs}>#{content}<a href=\"##{anchor}\" class=\"wiki-anchor\">&para;</a></h#{level}>"
888
    end
889
  end
890

    
891
  MACROS_RE = /(
892
                (!)?                        # escaping
893
                (
894
                \{\{                        # opening tag
895
                ([\w]+)                     # macro name
896
                (\(([^\n\r]*?)\))?          # optional arguments
897
                ([\n\r].*?[\n\r])?          # optional block of text
898
                \}\}                        # closing tag
899
                )
900
               )/mx unless const_defined?(:MACROS_RE)
901

    
902
  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
    text.gsub!(MACROS_RE) do
912
      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
      else
918
        all
919
      end
920
    end
921
    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
  end
943

    
944
  TOC_RE = /<p>\{\{([<>]?)toc\}\}<\/p>/i unless const_defined?(:TOC_RE)
945

    
946
  # Renders the TOC with given headings
947
  def replace_toc(text, headings)
948
    text.gsub!(TOC_RE) do
949
      # Keep only the 4 first levels
950
      headings = headings.select{|level, anchor, item| level <= 4}
951
      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

    
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
      gsub(/([^\n]\n)(?=[^\n])/, '\1<br />'). # 1 newline   -> br
985
      html_safe
986
  end
987

    
988
  def lang_options_for_select(blank=true)
989
    (blank ? [["(auto)", ""]] : []) + languages_options
990
  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
  def labelled_form_for(*args, &proc)
998
    args << {} unless args.last.is_a?(Hash)
999
    options = args.last
1000
    if args.first.is_a?(Symbol)
1001
      options.merge!(:as => args.shift)
1002
    end
1003
    options.merge!({:builder => Redmine::Views::LabelledFormBuilder})
1004
    form_for(*args, &proc)
1005
  end
1006

    
1007
  def labelled_fields_for(*args, &proc)
1008
    args << {} unless args.last.is_a?(Hash)
1009
    options = args.last
1010
    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
    form_for(*args, &proc)
1020
  end
1021

    
1022
  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
  end
1035

    
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
        :href => "#",
1049
        :onclick => %|submitPreview("#{escape_javascript url_for(url)}", "#{escape_javascript form}", "#{escape_javascript target}"); return false;|,
1050
        :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
  def back_url_hidden_field_tag
1072
    url = back_url
1073
    hidden_field_tag('back_url', url, :id => nil) unless url.blank?
1074
  end
1075

    
1076
  def check_all_links(form_name)
1077
    link_to_function(l(:button_check_all), "checkAll('#{form_name}', true)") +
1078
    " | ".html_safe +
1079
    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
        (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
  end
1097

    
1098
  def checked_image(checked=true)
1099
    if checked
1100
      image_tag 'toggle_check.png'
1101
    end
1102
  end
1103

    
1104
  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
      if l(:direction) == 'rtl'
1111
        content_for :header_tags do
1112
          stylesheet_link_tag('context_menu_rtl')
1113
        end
1114
      end
1115
      @context_menu_included = true
1116
    end
1117
    javascript_tag "contextMenuInit('#{ url_for(url) }')"
1118
  end
1119

    
1120
  def calendar_for(field_id)
1121
    include_calendar_headers_tags
1122
    javascript_tag("$(function() { $('##{field_id}').datepicker(datepickerOptions); });")
1123
  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
        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
                     "showOn: 'button', buttonImageOnly: true, buttonImage: '" +
1138
                     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
          tags << javascript_include_tag("i18n/jquery.ui.datepicker-#{jquery_locale}.js")
1143
        end
1144
        tags
1145
      end
1146
    end
1147
  end
1148

    
1149
  # 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
  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
  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
  def email_delivery_enabled?
1221
    !!ActionMailer::Base.perform_deliveries
1222
  end
1223

    
1224
  # 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
      options.merge!({:ssl => (request && request.ssl?), :default => Setting.gravatar_default})
1229
      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
    else
1237
      ''
1238
    end
1239
  end
1240

    
1241
  def sanitize_anchor_name(anchor)
1242
    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
  end
1249

    
1250
  # Returns the javascript tags that are included in the html layout head
1251
  def javascript_heads
1252
    tags = javascript_include_tag('jquery-1.7.2-ui-1.8.21-ujs-2.0.3', 'application')
1253
    unless User.current.pref.warn_on_leaving_unsaved == '0'
1254
      tags << "\n".html_safe + javascript_tag("$(window).load(function(){ warnLeavingUnsaved('#{escape_javascript l(:text_warn_on_leaving_unsaved)}'); });")
1255
    end
1256
    tags
1257
  end
1258

    
1259
  def favicon
1260
    "<link rel='shortcut icon' href='#{image_path('/favicon.ico')}' />".html_safe
1261
  end
1262

    
1263
  def robot_exclusion_tag
1264
    '<meta name="robots" content="noindex,follow,noarchive" />'.html_safe
1265
  end
1266

    
1267
  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
  # 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

    
1288
  # 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

    
1300
  private
1301

    
1302
  def wiki_helper
1303
    helper = Redmine::WikiFormatting.helper_for(Setting.text_formatting)
1304
    extend helper
1305
    return self
1306
  end
1307

    
1308
  def link_to_content_update(text, url_params = {}, html_options = {})
1309
    link_to(text, url_params, html_options)
1310
  end
1311
end