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 @ 912:5e80956cc792

History | View | Annotate | Download (39.7 KB)

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