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 / .svn / pristine / 04 / 048c8c7c3fc4fac08662cbdaac59cd6348bb3d14.svn-base @ 1298:4f746d8966dd

History | View | Annotate | Download (47.5 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
      s << "<label>#{ check_box_tag name, principal.id, false } #{h principal}</label>\n"
313
    end
314
    s.html_safe
315
  end
316

    
317
  # Returns a string for users/groups option tags
318
  def principals_options_for_select(collection, selected=nil)
319
    s = ''
320
    if collection.include?(User.current)
321
      s << content_tag('option', "<< #{l(:label_me)} >>", :value => User.current.id)
322
    end
323
    groups = ''
324
    collection.sort.each do |element|
325
      selected_attribute = ' selected="selected"' if option_value_selected?(element, selected)
326
      (element.is_a?(Group) ? groups : s) << %(<option value="#{element.id}"#{selected_attribute}>#{h element.name}</option>)
327
    end
328
    unless groups.empty?
329
      s << %(<optgroup label="#{h(l(:label_group_plural))}">#{groups}</optgroup>)
330
    end
331
    s.html_safe
332
  end
333

    
334
  # Options for the new membership projects combo-box
335
  def options_for_membership_project_select(principal, projects)
336
    options = content_tag('option', "--- #{l(:actionview_instancetag_blank_option)} ---")
337
    options << project_tree_options_for_select(projects) do |p|
338
      {:disabled => principal.projects.include?(p)}
339
    end
340
    options
341
  end
342

    
343
  # Truncates and returns the string as a single line
344
  def truncate_single_line(string, *args)
345
    truncate(string.to_s, *args).gsub(%r{[\r\n]+}m, ' ')
346
  end
347

    
348
  # Truncates at line break after 250 characters or options[:length]
349
  def truncate_lines(string, options={})
350
    length = options[:length] || 250
351
    if string.to_s =~ /\A(.{#{length}}.*?)$/m
352
      "#{$1}..."
353
    else
354
      string
355
    end
356
  end
357

    
358
  def anchor(text)
359
    text.to_s.gsub(' ', '_')
360
  end
361

    
362
  def html_hours(text)
363
    text.gsub(%r{(\d+)\.(\d+)}, '<span class="hours hours-int">\1</span><span class="hours hours-dec">.\2</span>').html_safe
364
  end
365

    
366
  def authoring(created, author, options={})
367
    l(options[:label] || :label_added_time_by, :author => link_to_user(author), :age => time_tag(created)).html_safe
368
  end
369

    
370
  def time_tag(time)
371
    text = distance_of_time_in_words(Time.now, time)
372
    if @project
373
      link_to(text, {:controller => 'activities', :action => 'index', :id => @project, :from => User.current.time_to_date(time)}, :title => format_time(time))
374
    else
375
      content_tag('acronym', text, :title => format_time(time))
376
    end
377
  end
378

    
379
  def syntax_highlight_lines(name, content)
380
    lines = []
381
    syntax_highlight(name, content).each_line { |line| lines << line }
382
    lines
383
  end
384

    
385
  def syntax_highlight(name, content)
386
    Redmine::SyntaxHighlighting.highlight_by_filename(content, name)
387
  end
388

    
389
  def to_path_param(path)
390
    str = path.to_s.split(%r{[/\\]}).select{|p| !p.blank?}.join("/")
391
    str.blank? ? nil : str
392
  end
393

    
394
  def pagination_links_full(paginator, count=nil, options={})
395
    page_param = options.delete(:page_param) || :page
396
    per_page_links = options.delete(:per_page_links)
397
    url_param = params.dup
398

    
399
    html = ''
400
    if paginator.current.previous
401
      # \xc2\xab(utf-8) = &#171;
402
      html << link_to_content_update(
403
                   "\xc2\xab " + l(:label_previous),
404
                   url_param.merge(page_param => paginator.current.previous)) + ' '
405
    end
406

    
407
    html << (pagination_links_each(paginator, options) do |n|
408
      link_to_content_update(n.to_s, url_param.merge(page_param => n))
409
    end || '')
410

    
411
    if paginator.current.next
412
      # \xc2\xbb(utf-8) = &#187;
413
      html << ' ' + link_to_content_update(
414
                      (l(:label_next) + " \xc2\xbb"),
415
                      url_param.merge(page_param => paginator.current.next))
416
    end
417

    
418
    unless count.nil?
419
      html << " (#{paginator.current.first_item}-#{paginator.current.last_item}/#{count})"
420
      if per_page_links != false && links = per_page_links(paginator.items_per_page, count)
421
	      html << " | #{links}"
422
      end
423
    end
424

    
425
    html.html_safe
426
  end
427

    
428
  def per_page_links(selected=nil, item_count=nil)
429
    values = Setting.per_page_options_array
430
    if item_count && values.any?
431
      if item_count > values.first
432
        max = values.detect {|value| value >= item_count} || item_count
433
      else
434
        max = item_count
435
      end
436
      values = values.select {|value| value <= max || value == selected}
437
    end
438
    if values.empty? || (values.size == 1 && values.first == selected)
439
      return nil
440
    end
441
    links = values.collect do |n|
442
      n == selected ? n : link_to_content_update(n, params.merge(:per_page => n))
443
    end
444
    l(:label_display_per_page, links.join(', '))
445
  end
446

    
447
  def reorder_links(name, url, method = :post)
448
    link_to(image_tag('2uparrow.png', :alt => l(:label_sort_highest)),
449
            url.merge({"#{name}[move_to]" => 'highest'}),
450
            :method => method, :title => l(:label_sort_highest)) +
451
    link_to(image_tag('1uparrow.png',   :alt => l(:label_sort_higher)),
452
            url.merge({"#{name}[move_to]" => 'higher'}),
453
           :method => method, :title => l(:label_sort_higher)) +
454
    link_to(image_tag('1downarrow.png', :alt => l(:label_sort_lower)),
455
            url.merge({"#{name}[move_to]" => 'lower'}),
456
            :method => method, :title => l(:label_sort_lower)) +
457
    link_to(image_tag('2downarrow.png', :alt => l(:label_sort_lowest)),
458
            url.merge({"#{name}[move_to]" => 'lowest'}),
459
           :method => method, :title => l(:label_sort_lowest))
460
  end
461

    
462
  def breadcrumb(*args)
463
    elements = args.flatten
464
    elements.any? ? content_tag('p', (args.join(" \xc2\xbb ") + " \xc2\xbb ").html_safe, :class => 'breadcrumb') : nil
465
  end
466

    
467
  def other_formats_links(&block)
468
    concat('<p class="other-formats">'.html_safe + l(:label_export_to))
469
    yield Redmine::Views::OtherFormatsBuilder.new(self)
470
    concat('</p>'.html_safe)
471
  end
472

    
473
  def page_header_title
474
    if @project.nil? || @project.new_record?
475
      h(Setting.app_title)
476
    else
477
      b = []
478
      ancestors = (@project.root? ? [] : @project.ancestors.visible.all)
479
      if ancestors.any?
480
        root = ancestors.shift
481
        b << link_to_project(root, {:jump => current_menu_item}, :class => 'root')
482
        if ancestors.size > 2
483
          b << "\xe2\x80\xa6"
484
          ancestors = ancestors[-2, 2]
485
        end
486
        b += ancestors.collect {|p| link_to_project(p, {:jump => current_menu_item}, :class => 'ancestor') }
487
      end
488
      b << h(@project)
489
      b.join(" \xc2\xbb ").html_safe
490
    end
491
  end
492

    
493
  def html_title(*args)
494
    if args.empty?
495
      title = @html_title || []
496
      title << @project.name if @project
497
      title << Setting.app_title unless Setting.app_title == title.last
498
      title.select {|t| !t.blank? }.join(' - ')
499
    else
500
      @html_title ||= []
501
      @html_title += args
502
    end
503
  end
504

    
505
  # Returns the theme, controller name, and action as css classes for the
506
  # HTML body.
507
  def body_css_classes
508
    css = []
509
    if theme = Redmine::Themes.theme(Setting.ui_theme)
510
      css << 'theme-' + theme.name
511
    end
512

    
513
    css << 'controller-' + controller_name
514
    css << 'action-' + action_name
515
    css.join(' ')
516
  end
517

    
518
  def accesskey(s)
519
    Redmine::AccessKeys.key_for s
520
  end
521

    
522
  # Formats text according to system settings.
523
  # 2 ways to call this method:
524
  # * with a String: textilizable(text, options)
525
  # * with an object and one of its attribute: textilizable(issue, :description, options)
526
  def textilizable(*args)
527
    options = args.last.is_a?(Hash) ? args.pop : {}
528
    case args.size
529
    when 1
530
      obj = options[:object]
531
      text = args.shift
532
    when 2
533
      obj = args.shift
534
      attr = args.shift
535
      text = obj.send(attr).to_s
536
    else
537
      raise ArgumentError, 'invalid arguments to textilizable'
538
    end
539
    return '' if text.blank?
540
    project = options[:project] || @project || (obj && obj.respond_to?(:project) ? obj.project : nil)
541
    only_path = options.delete(:only_path) == false ? false : true
542

    
543
    text = text.dup
544
    macros = catch_macros(text)
545
    text = Redmine::WikiFormatting.to_html(Setting.text_formatting, text, :object => obj, :attribute => attr)
546

    
547
    @parsed_headings = []
548
    @heading_anchors = {}
549
    @current_section = 0 if options[:edit_section_links]
550

    
551
    parse_sections(text, project, obj, attr, only_path, options)
552
    text = parse_non_pre_blocks(text, obj, macros) do |text|
553
      [:parse_inline_attachments, :parse_wiki_links, :parse_redmine_links].each do |method_name|
554
        send method_name, text, project, obj, attr, only_path, options
555
      end
556
    end
557
    parse_headings(text, project, obj, attr, only_path, options)
558

    
559
    if @parsed_headings.any?
560
      replace_toc(text, @parsed_headings)
561
    end
562

    
563
    text.html_safe
564
  end
565

    
566
  def parse_non_pre_blocks(text, obj, macros)
567
    s = StringScanner.new(text)
568
    tags = []
569
    parsed = ''
570
    while !s.eos?
571
      s.scan(/(.*?)(<(\/)?(pre|code)(.*?)>|\z)/im)
572
      text, full_tag, closing, tag = s[1], s[2], s[3], s[4]
573
      if tags.empty?
574
        yield text
575
        inject_macros(text, obj, macros) if macros.any?
576
      else
577
        inject_macros(text, obj, macros, false) if macros.any?
578
      end
579
      parsed << text
580
      if tag
581
        if closing
582
          if tags.last == tag.downcase
583
            tags.pop
584
          end
585
        else
586
          tags << tag.downcase
587
        end
588
        parsed << full_tag
589
      end
590
    end
591
    # Close any non closing tags
592
    while tag = tags.pop
593
      parsed << "</#{tag}>"
594
    end
595
    parsed
596
  end
597

    
598
  def parse_inline_attachments(text, project, obj, attr, only_path, options)
599
    # when using an image link, try to use an attachment, if possible
600
    attachments = options[:attachments] || []
601
    attachments += obj.attachments if obj.respond_to?(:attachments)
602
    if attachments.present?
603
      text.gsub!(/src="([^\/"]+\.(bmp|gif|jpg|jpe|jpeg|png))"(\s+alt="([^"]*)")?/i) do |m|
604
        filename, ext, alt, alttext = $1.downcase, $2, $3, $4
605
        # search for the picture in attachments
606
        if found = Attachment.latest_attach(attachments, filename)
607
          image_url = url_for :only_path => only_path, :controller => 'attachments',
608
                              :action => 'download', :id => found
609
          desc = found.description.to_s.gsub('"', '')
610
          if !desc.blank? && alttext.blank?
611
            alt = " title=\"#{desc}\" alt=\"#{desc}\""
612
          end
613
          "src=\"#{image_url}\"#{alt}"
614
        else
615
          m
616
        end
617
      end
618
    end
619
  end
620

    
621
  # Wiki links
622
  #
623
  # Examples:
624
  #   [[mypage]]
625
  #   [[mypage|mytext]]
626
  # wiki links can refer other project wikis, using project name or identifier:
627
  #   [[project:]] -> wiki starting page
628
  #   [[project:|mytext]]
629
  #   [[project:mypage]]
630
  #   [[project:mypage|mytext]]
631
  def parse_wiki_links(text, project, obj, attr, only_path, options)
632
    text.gsub!(/(!)?(\[\[([^\]\n\|]+)(\|([^\]\n\|]+))?\]\])/) do |m|
633
      link_project = project
634
      esc, all, page, title = $1, $2, $3, $5
635
      if esc.nil?
636
        if page =~ /^([^\:]+)\:(.*)$/
637
          link_project = Project.find_by_identifier($1) || Project.find_by_name($1)
638
          page = $2
639
          title ||= $1 if page.blank?
640
        end
641

    
642
        if link_project && link_project.wiki
643
          # extract anchor
644
          anchor = nil
645
          if page =~ /^(.+?)\#(.+)$/
646
            page, anchor = $1, $2
647
          end
648
          anchor = sanitize_anchor_name(anchor) if anchor.present?
649
          # check if page exists
650
          wiki_page = link_project.wiki.find_page(page)
651
          url = if anchor.present? && wiki_page.present? && (obj.is_a?(WikiContent) || obj.is_a?(WikiContent::Version)) && obj.page == wiki_page
652
            "##{anchor}"
653
          else
654
            case options[:wiki_links]
655
            when :local; "#{page.present? ? Wiki.titleize(page) : ''}.html" + (anchor.present? ? "##{anchor}" : '')
656
            when :anchor; "##{page.present? ? Wiki.titleize(page) : title}" + (anchor.present? ? "_#{anchor}" : '') # used for single-file wiki export
657
            else
658
              wiki_page_id = page.present? ? Wiki.titleize(page) : nil
659
              parent = wiki_page.nil? && obj.is_a?(WikiContent) && obj.page && project == link_project ? obj.page.title : nil
660
              url_for(:only_path => only_path, :controller => 'wiki', :action => 'show', :project_id => link_project, 
661
               :id => wiki_page_id, :version => nil, :anchor => anchor, :parent => parent)
662
            end
663
          end
664
          link_to(title.present? ? title.html_safe : h(page), url, :class => ('wiki-page' + (wiki_page ? '' : ' new')))
665
        else
666
          # project or wiki doesn't exist
667
          all
668
        end
669
      else
670
        all
671
      end
672
    end
673
  end
674

    
675
  # Redmine links
676
  #
677
  # Examples:
678
  #   Issues:
679
  #     #52 -> Link to issue #52
680
  #   Changesets:
681
  #     r52 -> Link to revision 52
682
  #     commit:a85130f -> Link to scmid starting with a85130f
683
  #   Documents:
684
  #     document#17 -> Link to document with id 17
685
  #     document:Greetings -> Link to the document with title "Greetings"
686
  #     document:"Some document" -> Link to the document with title "Some document"
687
  #   Versions:
688
  #     version#3 -> Link to version with id 3
689
  #     version:1.0.0 -> Link to version named "1.0.0"
690
  #     version:"1.0 beta 2" -> Link to version named "1.0 beta 2"
691
  #   Attachments:
692
  #     attachment:file.zip -> Link to the attachment of the current object named file.zip
693
  #   Source files:
694
  #     source:some/file -> Link to the file located at /some/file in the project's repository
695
  #     source:some/file@52 -> Link to the file's revision 52
696
  #     source:some/file#L120 -> Link to line 120 of the file
697
  #     source:some/file@52#L120 -> Link to line 120 of the file's revision 52
698
  #     export:some/file -> Force the download of the file
699
  #   Forum messages:
700
  #     message#1218 -> Link to message with id 1218
701
  #
702
  #   Links can refer other objects from other projects, using project identifier:
703
  #     identifier:r52
704
  #     identifier:document:"Some document"
705
  #     identifier:version:1.0.0
706
  #     identifier:source:some/file
707
  def parse_redmine_links(text, default_project, obj, attr, only_path, options)
708
    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|
709
      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
710
      link = nil
711
      project = default_project
712
      if project_identifier
713
        project = Project.visible.find_by_identifier(project_identifier)
714
      end
715
      if esc.nil?
716
        if prefix.nil? && sep == 'r'
717
          if project
718
            repository = nil
719
            if repo_identifier
720
              repository = project.repositories.detect {|repo| repo.identifier == repo_identifier}
721
            else
722
              repository = project.repository
723
            end
724
            # project.changesets.visible raises an SQL error because of a double join on repositories
725
            if repository && (changeset = Changeset.visible.find_by_repository_id_and_revision(repository.id, identifier))
726
              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},
727
                                        :class => 'changeset',
728
                                        :title => truncate_single_line(changeset.comments, :length => 100))
729
            end
730
          end
731
        elsif sep == '#'
732
          oid = identifier.to_i
733
          case prefix
734
          when nil
735
            if oid.to_s == identifier && issue = Issue.visible.find_by_id(oid, :include => :status)
736
              anchor = comment_id ? "note-#{comment_id}" : nil
737
              link = link_to("##{oid}", {:only_path => only_path, :controller => 'issues', :action => 'show', :id => oid, :anchor => anchor},
738
                                        :class => issue.css_classes,
739
                                        :title => "#{truncate(issue.subject, :length => 100)} (#{issue.status.name})")
740
            end
741
          when 'document'
742
            if document = Document.visible.find_by_id(oid)
743
              link = link_to h(document.title), {:only_path => only_path, :controller => 'documents', :action => 'show', :id => document},
744
                                                :class => 'document'
745
            end
746
          when 'version'
747
            if version = Version.visible.find_by_id(oid)
748
              link = link_to h(version.name), {:only_path => only_path, :controller => 'versions', :action => 'show', :id => version},
749
                                              :class => 'version'
750
            end
751
          when 'message'
752
            if message = Message.visible.find_by_id(oid, :include => :parent)
753
              link = link_to_message(message, {:only_path => only_path}, :class => 'message')
754
            end
755
          when 'forum'
756
            if board = Board.visible.find_by_id(oid)
757
              link = link_to h(board.name), {:only_path => only_path, :controller => 'boards', :action => 'show', :id => board, :project_id => board.project},
758
                                             :class => 'board'
759
            end
760
          when 'news'
761
            if news = News.visible.find_by_id(oid)
762
              link = link_to h(news.title), {:only_path => only_path, :controller => 'news', :action => 'show', :id => news},
763
                                            :class => 'news'
764
            end
765
          when 'project'
766
            if p = Project.visible.find_by_id(oid)
767
              link = link_to_project(p, {:only_path => only_path}, :class => 'project')
768
            end
769
          end
770
        elsif sep == ':'
771
          # removes the double quotes if any
772
          name = identifier.gsub(%r{^"(.*)"$}, "\\1")
773
          case prefix
774
          when 'document'
775
            if project && document = project.documents.visible.find_by_title(name)
776
              link = link_to h(document.title), {:only_path => only_path, :controller => 'documents', :action => 'show', :id => document},
777
                                                :class => 'document'
778
            end
779
          when 'version'
780
            if project && version = project.versions.visible.find_by_name(name)
781
              link = link_to h(version.name), {:only_path => only_path, :controller => 'versions', :action => 'show', :id => version},
782
                                              :class => 'version'
783
            end
784
          when 'forum'
785
            if project && board = project.boards.visible.find_by_name(name)
786
              link = link_to h(board.name), {:only_path => only_path, :controller => 'boards', :action => 'show', :id => board, :project_id => board.project},
787
                                             :class => 'board'
788
            end
789
          when 'news'
790
            if project && news = project.news.visible.find_by_title(name)
791
              link = link_to h(news.title), {:only_path => only_path, :controller => 'news', :action => 'show', :id => news},
792
                                            :class => 'news'
793
            end
794
          when 'commit', 'source', 'export'
795
            if project
796
              repository = nil
797
              if name =~ %r{^(([a-z0-9\-_]+)\|)(.+)$}
798
                repo_prefix, repo_identifier, name = $1, $2, $3
799
                repository = project.repositories.detect {|repo| repo.identifier == repo_identifier}
800
              else
801
                repository = project.repository
802
              end
803
              if prefix == 'commit'
804
                if repository && (changeset = Changeset.visible.find(:first, :conditions => ["repository_id = ? AND scmid LIKE ?", repository.id, "#{name}%"]))
805
                  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},
806
                                               :class => 'changeset',
807
                                               :title => truncate_single_line(h(changeset.comments), :length => 100)
808
                end
809
              else
810
                if repository && User.current.allowed_to?(:browse_repository, project)
811
                  name =~ %r{^[/\\]*(.*?)(@([0-9a-f]+))?(#(L\d+))?$}
812
                  path, rev, anchor = $1, $3, $5
813
                  link = link_to h("#{project_prefix}#{prefix}:#{repo_prefix}#{name}"), {:controller => 'repositories', :action => (prefix == 'export' ? 'raw' : 'entry'), :id => project, :repository_id => repository.identifier_param,
814
                                                          :path => to_path_param(path),
815
                                                          :rev => rev,
816
                                                          :anchor => anchor},
817
                                                         :class => (prefix == 'export' ? 'source download' : 'source')
818
                end
819
              end
820
              repo_prefix = nil
821
            end
822
          when 'attachment'
823
            attachments = options[:attachments] || (obj && obj.respond_to?(:attachments) ? obj.attachments : nil)
824
            if attachments && attachment = Attachment.latest_attach(attachments, name)
825
              link = link_to h(attachment.filename), {:only_path => only_path, :controller => 'attachments', :action => 'download', :id => attachment},
826
                                                     :class => 'attachment'
827
            end
828
          when 'project'
829
            if p = Project.visible.find(:first, :conditions => ["identifier = :s OR LOWER(name) = :s", {:s => name.downcase}])
830
              link = link_to_project(p, {:only_path => only_path}, :class => 'project')
831
            end
832
          end
833
        end
834
      end
835
      (leading + (link || "#{project_prefix}#{prefix}#{repo_prefix}#{sep}#{identifier}#{comment_suffix}"))
836
    end
837
  end
838

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

    
841
  def parse_sections(text, project, obj, attr, only_path, options)
842
    return unless options[:edit_section_links]
843
    text.gsub!(HEADING_RE) do
844
      heading = $1
845
      @current_section += 1
846
      if @current_section > 1
847
        content_tag('div',
848
          link_to(image_tag('edit.png'), options[:edit_section_links].merge(:section => @current_section)),
849
          :class => 'contextual',
850
          :title => l(:button_edit_section)) + heading.html_safe
851
      else
852
        heading
853
      end
854
    end
855
  end
856

    
857
  # Headings and TOC
858
  # Adds ids and links to headings unless options[:headings] is set to false
859
  def parse_headings(text, project, obj, attr, only_path, options)
860
    return if options[:headings] == false
861

    
862
    text.gsub!(HEADING_RE) do
863
      level, attrs, content = $2.to_i, $3, $4
864
      item = strip_tags(content).strip
865
      anchor = sanitize_anchor_name(item)
866
      # used for single-file wiki export
867
      anchor = "#{obj.page.title}_#{anchor}" if options[:wiki_links] == :anchor && (obj.is_a?(WikiContent) || obj.is_a?(WikiContent::Version))
868
      @heading_anchors[anchor] ||= 0
869
      idx = (@heading_anchors[anchor] += 1)
870
      if idx > 1
871
        anchor = "#{anchor}-#{idx}"
872
      end
873
      @parsed_headings << [level, anchor, item]
874
      "<a name=\"#{anchor}\"></a>\n<h#{level} #{attrs}>#{content}<a href=\"##{anchor}\" class=\"wiki-anchor\">&para;</a></h#{level}>"
875
    end
876
  end
877

    
878
  MACROS_RE = /(
879
                (!)?                        # escaping
880
                (
881
                \{\{                        # opening tag
882
                ([\w]+)                     # macro name
883
                (\(([^\n\r]*?)\))?          # optional arguments
884
                ([\n\r].*?[\n\r])?          # optional block of text
885
                \}\}                        # closing tag
886
                )
887
               )/mx unless const_defined?(:MACROS_RE)
888

    
889
  MACRO_SUB_RE = /(
890
                  \{\{
891
                  macro\((\d+)\)
892
                  \}\}
893
                  )/x unless const_defined?(:MACRO_SUB_RE)
894

    
895
  # Extracts macros from text
896
  def catch_macros(text)
897
    macros = {}
898
    text.gsub!(MACROS_RE) do
899
      all, macro = $1, $4.downcase
900
      if macro_exists?(macro) || all =~ MACRO_SUB_RE
901
        index = macros.size
902
        macros[index] = all
903
        "{{macro(#{index})}}"
904
      else
905
        all
906
      end
907
    end
908
    macros
909
  end
910

    
911
  # Executes and replaces macros in text
912
  def inject_macros(text, obj, macros, execute=true)
913
    text.gsub!(MACRO_SUB_RE) do
914
      all, index = $1, $2.to_i
915
      orig = macros.delete(index)
916
      if execute && orig && orig =~ MACROS_RE
917
        esc, all, macro, args, block = $2, $3, $4.downcase, $6.to_s, $7.try(:strip)
918
        if esc.nil?
919
          h(exec_macro(macro, obj, args, block) || all)
920
        else
921
          h(all)
922
        end
923
      elsif orig
924
        h(orig)
925
      else
926
        h(all)
927
      end
928
    end
929
  end
930

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

    
933
  # Renders the TOC with given headings
934
  def replace_toc(text, headings)
935
    text.gsub!(TOC_RE) do
936
      # Keep only the 4 first levels
937
      headings = headings.select{|level, anchor, item| level <= 4}
938
      if headings.empty?
939
        ''
940
      else
941
        div_class = 'toc'
942
        div_class << ' right' if $1 == '>'
943
        div_class << ' left' if $1 == '<'
944
        out = "<ul class=\"#{div_class}\"><li>"
945
        root = headings.map(&:first).min
946
        current = root
947
        started = false
948
        headings.each do |level, anchor, item|
949
          if level > current
950
            out << '<ul><li>' * (level - current)
951
          elsif level < current
952
            out << "</li></ul>\n" * (current - level) + "</li><li>"
953
          elsif started
954
            out << '</li><li>'
955
          end
956
          out << "<a href=\"##{anchor}\">#{item}</a>"
957
          current = level
958
          started = true
959
        end
960
        out << '</li></ul>' * (current - root)
961
        out << '</li></ul>'
962
      end
963
    end
964
  end
965

    
966
  # Same as Rails' simple_format helper without using paragraphs
967
  def simple_format_without_paragraph(text)
968
    text.to_s.
969
      gsub(/\r\n?/, "\n").                    # \r\n and \r -> \n
970
      gsub(/\n\n+/, "<br /><br />").          # 2+ newline  -> 2 br
971
      gsub(/([^\n]\n)(?=[^\n])/, '\1<br />'). # 1 newline   -> br
972
      html_safe
973
  end
974

    
975
  def lang_options_for_select(blank=true)
976
    (blank ? [["(auto)", ""]] : []) + languages_options
977
  end
978

    
979
  def label_tag_for(name, option_tags = nil, options = {})
980
    label_text = l(("field_"+field.to_s.gsub(/\_id$/, "")).to_sym) + (options.delete(:required) ? @template.content_tag("span", " *", :class => "required"): "")
981
    content_tag("label", label_text)
982
  end
983

    
984
  def labelled_form_for(*args, &proc)
985
    args << {} unless args.last.is_a?(Hash)
986
    options = args.last
987
    if args.first.is_a?(Symbol)
988
      options.merge!(:as => args.shift)
989
    end
990
    options.merge!({:builder => Redmine::Views::LabelledFormBuilder})
991
    form_for(*args, &proc)
992
  end
993

    
994
  def labelled_fields_for(*args, &proc)
995
    args << {} unless args.last.is_a?(Hash)
996
    options = args.last
997
    options.merge!({:builder => Redmine::Views::LabelledFormBuilder})
998
    fields_for(*args, &proc)
999
  end
1000

    
1001
  def labelled_remote_form_for(*args, &proc)
1002
    ActiveSupport::Deprecation.warn "ApplicationHelper#labelled_remote_form_for is deprecated and will be removed in Redmine 2.2."
1003
    args << {} unless args.last.is_a?(Hash)
1004
    options = args.last
1005
    options.merge!({:builder => Redmine::Views::LabelledFormBuilder, :remote => true})
1006
    form_for(*args, &proc)
1007
  end
1008

    
1009
  def error_messages_for(*objects)
1010
    html = ""
1011
    objects = objects.map {|o| o.is_a?(String) ? instance_variable_get("@#{o}") : o}.compact
1012
    errors = objects.map {|o| o.errors.full_messages}.flatten
1013
    if errors.any?
1014
      html << "<div id='errorExplanation'><ul>\n"
1015
      errors.each do |error|
1016
        html << "<li>#{h error}</li>\n"
1017
      end
1018
      html << "</ul></div>\n"
1019
    end
1020
    html.html_safe
1021
  end  
1022

    
1023
  def delete_link(url, options={})
1024
    options = {
1025
      :method => :delete,
1026
      :data => {:confirm => l(:text_are_you_sure)},
1027
      :class => 'icon icon-del'
1028
    }.merge(options)
1029

    
1030
    link_to l(:button_delete), url, options
1031
  end
1032

    
1033
  def preview_link(url, form, target='preview', options={})
1034
    content_tag 'a', l(:label_preview), {
1035
        :href => "#", 
1036
        :onclick => %|submitPreview("#{escape_javascript url_for(url)}", "#{escape_javascript form}", "#{escape_javascript target}"); return false;|, 
1037
        :accesskey => accesskey(:preview)
1038
      }.merge(options)
1039
  end
1040

    
1041
  def link_to_function(name, function, html_options={})
1042
    content_tag(:a, name, {:href => '#', :onclick => "#{function}; return false;"}.merge(html_options))
1043
  end
1044

    
1045
  # Helper to render JSON in views
1046
  def raw_json(arg)
1047
    arg.to_json.to_s.gsub('/', '\/').html_safe
1048
  end
1049

    
1050
  def back_url
1051
    url = params[:back_url]
1052
    if url.nil? && referer = request.env['HTTP_REFERER']
1053
      url = CGI.unescape(referer.to_s)
1054
    end
1055
    url
1056
  end
1057

    
1058
  def back_url_hidden_field_tag
1059
    url = back_url
1060
    hidden_field_tag('back_url', url, :id => nil) unless url.blank?
1061
  end
1062

    
1063
  def check_all_links(form_name)
1064
    link_to_function(l(:button_check_all), "checkAll('#{form_name}', true)") +
1065
    " | ".html_safe +
1066
    link_to_function(l(:button_uncheck_all), "checkAll('#{form_name}', false)")
1067
  end
1068

    
1069
  def progress_bar(pcts, options={})
1070
    pcts = [pcts, pcts] unless pcts.is_a?(Array)
1071
    pcts = pcts.collect(&:round)
1072
    pcts[1] = pcts[1] - pcts[0]
1073
    pcts << (100 - pcts[1] - pcts[0])
1074
    width = options[:width] || '100px;'
1075
    legend = options[:legend] || ''
1076
    content_tag('table',
1077
      content_tag('tr',
1078
        (pcts[0] > 0 ? content_tag('td', '', :style => "width: #{pcts[0]}%;", :class => 'closed') : ''.html_safe) +
1079
        (pcts[1] > 0 ? content_tag('td', '', :style => "width: #{pcts[1]}%;", :class => 'done') : ''.html_safe) +
1080
        (pcts[2] > 0 ? content_tag('td', '', :style => "width: #{pcts[2]}%;", :class => 'todo') : ''.html_safe)
1081
      ), :class => 'progress', :style => "width: #{width};").html_safe +
1082
      content_tag('p', legend, :class => 'pourcent').html_safe
1083
  end
1084

    
1085
  def checked_image(checked=true)
1086
    if checked
1087
      image_tag 'toggle_check.png'
1088
    end
1089
  end
1090

    
1091
  def context_menu(url)
1092
    unless @context_menu_included
1093
      content_for :header_tags do
1094
        javascript_include_tag('context_menu') +
1095
          stylesheet_link_tag('context_menu')
1096
      end
1097
      if l(:direction) == 'rtl'
1098
        content_for :header_tags do
1099
          stylesheet_link_tag('context_menu_rtl')
1100
        end
1101
      end
1102
      @context_menu_included = true
1103
    end
1104
    javascript_tag "contextMenuInit('#{ url_for(url) }')"
1105
  end
1106

    
1107
  def calendar_for(field_id)
1108
    include_calendar_headers_tags
1109
    javascript_tag("$(function() { $('##{field_id}').datepicker(datepickerOptions); });")
1110
  end
1111

    
1112
  def include_calendar_headers_tags
1113
    unless @calendar_headers_tags_included
1114
      @calendar_headers_tags_included = true
1115
      content_for :header_tags do
1116
        start_of_week = Setting.start_of_week
1117
        start_of_week = l(:general_first_day_of_week, :default => '1') if start_of_week.blank?
1118
        # Redmine uses 1..7 (monday..sunday) in settings and locales
1119
        # JQuery uses 0..6 (sunday..saturday), 7 needs to be changed to 0
1120
        start_of_week = start_of_week.to_i % 7
1121

    
1122
        tags = javascript_tag(
1123
                   "var datepickerOptions={dateFormat: 'yy-mm-dd', firstDay: #{start_of_week}, " +
1124
                     "showOn: 'button', buttonImageOnly: true, buttonImage: '" + 
1125
                     path_to_image('/images/calendar.png') +
1126
                     "', showButtonPanel: true};")
1127
        jquery_locale = l('jquery.locale', :default => current_language.to_s)
1128
        unless jquery_locale == 'en'
1129
          tags << javascript_include_tag("i18n/jquery.ui.datepicker-#{jquery_locale}.js") 
1130
        end
1131
        tags
1132
      end
1133
    end
1134
  end
1135

    
1136
  # Overrides Rails' stylesheet_link_tag with themes and plugins support.
1137
  # Examples:
1138
  #   stylesheet_link_tag('styles') # => picks styles.css from the current theme or defaults
1139
  #   stylesheet_link_tag('styles', :plugin => 'foo) # => picks styles.css from plugin's assets
1140
  #
1141
  def stylesheet_link_tag(*sources)
1142
    options = sources.last.is_a?(Hash) ? sources.pop : {}
1143
    plugin = options.delete(:plugin)
1144
    sources = sources.map do |source|
1145
      if plugin
1146
        "/plugin_assets/#{plugin}/stylesheets/#{source}"
1147
      elsif current_theme && current_theme.stylesheets.include?(source)
1148
        current_theme.stylesheet_path(source)
1149
      else
1150
        source
1151
      end
1152
    end
1153
    super sources, options
1154
  end
1155

    
1156
  # Overrides Rails' image_tag with themes and plugins support.
1157
  # Examples:
1158
  #   image_tag('image.png') # => picks image.png from the current theme or defaults
1159
  #   image_tag('image.png', :plugin => 'foo) # => picks image.png from plugin's assets
1160
  #
1161
  def image_tag(source, options={})
1162
    if plugin = options.delete(:plugin)
1163
      source = "/plugin_assets/#{plugin}/images/#{source}"
1164
    elsif current_theme && current_theme.images.include?(source)
1165
      source = current_theme.image_path(source)
1166
    end
1167
    super source, options
1168
  end
1169

    
1170
  # Overrides Rails' javascript_include_tag with plugins support
1171
  # Examples:
1172
  #   javascript_include_tag('scripts') # => picks scripts.js from defaults
1173
  #   javascript_include_tag('scripts', :plugin => 'foo) # => picks scripts.js from plugin's assets
1174
  #
1175
  def javascript_include_tag(*sources)
1176
    options = sources.last.is_a?(Hash) ? sources.pop : {}
1177
    if plugin = options.delete(:plugin)
1178
      sources = sources.map do |source|
1179
        if plugin
1180
          "/plugin_assets/#{plugin}/javascripts/#{source}"
1181
        else
1182
          source
1183
        end
1184
      end
1185
    end
1186
    super sources, options
1187
  end
1188

    
1189
  def content_for(name, content = nil, &block)
1190
    @has_content ||= {}
1191
    @has_content[name] = true
1192
    super(name, content, &block)
1193
  end
1194

    
1195
  def has_content?(name)
1196
    (@has_content && @has_content[name]) || false
1197
  end
1198

    
1199
  def sidebar_content?
1200
    has_content?(:sidebar) || view_layouts_base_sidebar_hook_response.present?
1201
  end
1202

    
1203
  def view_layouts_base_sidebar_hook_response
1204
    @view_layouts_base_sidebar_hook_response ||= call_hook(:view_layouts_base_sidebar)
1205
  end
1206

    
1207
  def email_delivery_enabled?
1208
    !!ActionMailer::Base.perform_deliveries
1209
  end
1210

    
1211
  # Returns the avatar image tag for the given +user+ if avatars are enabled
1212
  # +user+ can be a User or a string that will be scanned for an email address (eg. 'joe <joe@foo.bar>')
1213
  def avatar(user, options = { })
1214
    if Setting.gravatar_enabled?
1215
      options.merge!({:ssl => (request && request.ssl?), :default => Setting.gravatar_default})
1216
      email = nil
1217
      if user.respond_to?(:mail)
1218
        email = user.mail
1219
      elsif user.to_s =~ %r{<(.+?)>}
1220
        email = $1
1221
      end
1222
      return gravatar(email.to_s.downcase, options) unless email.blank? rescue nil
1223
    else
1224
      ''
1225
    end
1226
  end
1227

    
1228
  def sanitize_anchor_name(anchor)
1229
    if ''.respond_to?(:encoding) || RUBY_PLATFORM == 'java'
1230
      anchor.gsub(%r{[^\p{Word}\s\-]}, '').gsub(%r{\s+(\-+\s*)?}, '-')
1231
    else
1232
      # TODO: remove when ruby1.8 is no longer supported
1233
      anchor.gsub(%r{[^\w\s\-]}, '').gsub(%r{\s+(\-+\s*)?}, '-')
1234
    end
1235
  end
1236

    
1237
  # Returns the javascript tags that are included in the html layout head
1238
  def javascript_heads
1239
    tags = javascript_include_tag('jquery-1.7.2-ui-1.8.21-ujs-2.0.3', 'application')
1240
    unless User.current.pref.warn_on_leaving_unsaved == '0'
1241
      tags << "\n".html_safe + javascript_tag("$(window).load(function(){ warnLeavingUnsaved('#{escape_javascript l(:text_warn_on_leaving_unsaved)}'); });")
1242
    end
1243
    tags
1244
  end
1245

    
1246
  def favicon
1247
    "<link rel='shortcut icon' href='#{image_path('/favicon.ico')}' />".html_safe
1248
  end
1249

    
1250
  def robot_exclusion_tag
1251
    '<meta name="robots" content="noindex,follow,noarchive" />'.html_safe
1252
  end
1253

    
1254
  # Returns true if arg is expected in the API response
1255
  def include_in_api_response?(arg)
1256
    unless @included_in_api_response
1257
      param = params[:include]
1258
      @included_in_api_response = param.is_a?(Array) ? param.collect(&:to_s) : param.to_s.split(',')
1259
      @included_in_api_response.collect!(&:strip)
1260
    end
1261
    @included_in_api_response.include?(arg.to_s)
1262
  end
1263

    
1264
  # Returns options or nil if nometa param or X-Redmine-Nometa header
1265
  # was set in the request
1266
  def api_meta(options)
1267
    if params[:nometa].present? || request.headers['X-Redmine-Nometa']
1268
      # compatibility mode for activeresource clients that raise
1269
      # an error when unserializing an array with attributes
1270
      nil
1271
    else
1272
      options
1273
    end
1274
  end
1275

    
1276
  private
1277

    
1278
  def wiki_helper
1279
    helper = Redmine::WikiFormatting.helper_for(Setting.text_formatting)
1280
    extend helper
1281
    return self
1282
  end
1283

    
1284
  def link_to_content_update(text, url_params = {}, html_options = {})
1285
    link_to(text, url_params, html_options)
1286
  end
1287
end