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 @ 414:576a1dca2ee2

History | View | Annotate | Download (33.5 KB)

1
# Redmine - project management software
2
# Copyright (C) 2006-2010  Jean-Philippe Lang
3
#
4
# This program is free software; you can redistribute it and/or
5
# modify it under the terms of the GNU General Public License
6
# as published by the Free Software Foundation; either version 2
7
# of the License, or (at your option) any later version.
8
#
9
# This program is distributed in the hope that it will be useful,
10
# but WITHOUT ANY WARRANTY; without even the implied warranty of
11
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12
# GNU General Public License for more details.
13
#
14
# You should have received a copy of the GNU General Public License
15
# along with this program; if not, write to the Free Software
16
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
17

    
18
require 'forwardable'
19
require 'cgi'
20

    
21
module ApplicationHelper
22
  include Redmine::WikiFormatting::Macros::Definitions
23
  include Redmine::I18n
24
  include GravatarHelper::PublicMethods
25

    
26
  extend Forwardable
27
  def_delegators :wiki_helper, :wikitoolbar_for, :heads_for_wiki_formatter
28

    
29
  # Return true if user is authorized for controller/action, otherwise false
30
  def authorize_for(controller, action)
31
    User.current.allowed_to?({:controller => controller, :action => action}, @project)
32
  end
33

    
34
  # Display a link if user is authorized
35
  #
36
  # @param [String] name Anchor text (passed to link_to)
37
  # @param [Hash] options Hash params. This will checked by authorize_for to see if the user is authorized
38
  # @param [optional, Hash] html_options Options passed to link_to
39
  # @param [optional, Hash] parameters_for_method_reference Extra parameters for link_to
40
  def link_to_if_authorized(name, options = {}, html_options = nil, *parameters_for_method_reference)
41
    link_to(name, options, html_options, *parameters_for_method_reference) if authorize_for(options[:controller] || params[:controller], options[:action])
42
  end
43

    
44
  # Display a link to remote if user is authorized
45
  def link_to_remote_if_authorized(name, options = {}, html_options = nil)
46
    url = options[:url] || {}
47
    link_to_remote(name, options, html_options) if authorize_for(url[:controller] || params[:controller], url[:action])
48
  end
49

    
50
  # Displays a link to user's account page if active
51
  def link_to_user(user, options={})
52
    if user.is_a?(User)
53
      name = h(user.name(options[:format]))
54
      if user.active?
55
        link_to(name, :controller => 'users', :action => 'show', :id => user)
56
      else
57
        name
58
      end
59
    else
60
      h(user.to_s)
61
    end
62
  end
63

    
64
  # Displays a link to +issue+ with its subject.
65
  # Examples:
66
  # 
67
  #   link_to_issue(issue)                        # => Defect #6: This is the subject
68
  #   link_to_issue(issue, :truncate => 6)        # => Defect #6: This i...
69
  #   link_to_issue(issue, :subject => false)     # => Defect #6
70
  #   link_to_issue(issue, :project => true)      # => Foo - Defect #6
71
  #
72
  def link_to_issue(issue, options={})
73
    title = nil
74
    subject = nil
75
    if options[:subject] == false
76
      title = truncate(issue.subject, :length => 60)
77
    else
78
      subject = issue.subject
79
      if options[:truncate]
80
        subject = truncate(subject, :length => options[:truncate])
81
      end
82
    end
83
    s = link_to "#{issue.tracker} ##{issue.id}", {:controller => "issues", :action => "show", :id => issue}, 
84
                                                 :class => issue.css_classes,
85
                                                 :title => title
86
    s << ": #{h subject}" if subject
87
    s = "#{h issue.project} - " + s if options[:project]
88
    s
89
  end
90

    
91
  # Generates a link to an attachment.
92
  # Options:
93
  # * :text - Link text (default to attachment filename)
94
  # * :download - Force download (default: false)
95
  def link_to_attachment(attachment, options={})
96
    text = options.delete(:text) || attachment.filename
97
    action = options.delete(:download) ? 'download' : 'show'
98

    
99
    link_to(h(text), {:controller => 'attachments', :action => action, :id => attachment, :filename => attachment.filename }, options)
100
  end
101

    
102
  # Generates a link to a SCM revision
103
  # Options:
104
  # * :text - Link text (default to the formatted revision)
105
  def link_to_revision(revision, project, options={})
106
    text = options.delete(:text) || format_revision(revision)
107
    rev = revision.respond_to?(:identifier) ? revision.identifier : revision
108

    
109
    link_to(text, {:controller => 'repositories', :action => 'revision', :id => project, :rev => rev},
110
            :title => l(:label_revision_id, format_revision(revision)))
111
  end
112

    
113
  # Generates a link to a project if active
114
  # Examples:
115
  # 
116
  #   link_to_project(project)                          # => link to the specified project overview
117
  #   link_to_project(project, :action=>'settings')     # => link to project settings
118
  #   link_to_project(project, {:only_path => false}, :class => "project") # => 3rd arg adds html options
119
  #   link_to_project(project, {}, :class => "project") # => html options with default url (project overview)
120
  #
121
  def link_to_project(project, options={}, html_options = nil)
122
    if project.active?
123
      url = {:controller => 'projects', :action => 'show', :id => project}.merge(options)
124
      link_to(h(project), url, html_options)
125
    else
126
      h(project)
127
    end
128
  end
129

    
130
  def toggle_link(name, id, options={})
131
    onclick = "Element.toggle('#{id}'); "
132
    onclick << (options[:focus] ? "Form.Element.focus('#{options[:focus]}'); " : "this.blur(); ")
133
    onclick << "return false;"
134
    link_to(name, "#", :onclick => onclick)
135
  end
136

    
137
  def image_to_function(name, function, html_options = {})
138
    html_options.symbolize_keys!
139
    tag(:input, html_options.merge({
140
        :type => "image", :src => image_path(name),
141
        :onclick => (html_options[:onclick] ? "#{html_options[:onclick]}; " : "") + "#{function};"
142
        }))
143
  end
144

    
145
  def prompt_to_remote(name, text, param, url, html_options = {})
146
    html_options[:onclick] = "promptToRemote('#{text}', '#{param}', '#{url_for(url)}'); return false;"
147
    link_to name, {}, html_options
148
  end
149
  
150
  def format_activity_title(text)
151
    h(truncate_single_line(text, :length => 100))
152
  end
153
  
154
  def format_activity_day(date)
155
    date == Date.today ? l(:label_today).titleize : format_date(date)
156
  end
157
  
158
  def format_activity_description(text)
159
    h(truncate(text.to_s, :length => 120).gsub(%r{[\r\n]*<(pre|code)>.*$}m, '...')).gsub(/[\r\n]+/, "<br />")
160
  end
161

    
162
  def format_version_name(version)
163
    if version.project == @project
164
            h(version)
165
    else
166
      h("#{version.project} - #{version}")
167
    end
168
  end
169
  
170
  def due_date_distance_in_words(date)
171
    if date
172
      l((date < Date.today ? :label_roadmap_overdue : :label_roadmap_due_in), distance_of_date_in_words(Date.today, date))
173
    end
174
  end
175

    
176
  def render_page_hierarchy(pages, node=nil)
177
    content = ''
178
    if pages[node]
179
      content << "<ul class=\"pages-hierarchy\">\n"
180
      pages[node].each do |page|
181
        content << "<li>"
182
        content << link_to(h(page.pretty_title), {:controller => 'wiki', :action => 'show', :project_id => page.project, :id => page.title},
183
                           :title => (page.respond_to?(:updated_on) ? l(:label_updated_time, distance_of_time_in_words(Time.now, page.updated_on)) : nil))
184
        content << "\n" + render_page_hierarchy(pages, page.id) if pages[page.id]
185
        content << "</li>\n"
186
      end
187
      content << "</ul>\n"
188
    end
189
    content
190
  end
191
  
192
  # Renders flash messages
193
  def render_flash_messages
194
    s = ''
195
    flash.each do |k,v|
196
      s << content_tag('div', v, :class => "flash #{k}")
197
    end
198
    s
199
  end
200
  
201
  # Renders tabs and their content
202
  def render_tabs(tabs)
203
    if tabs.any?
204
      render :partial => 'common/tabs', :locals => {:tabs => tabs}
205
    else
206
      content_tag 'p', l(:label_no_data), :class => "nodata"
207
    end
208
  end
209
  
210
  # Renders the project quick-jump box
211
  def render_project_jump_box
212
    # Retrieve them now to avoid a COUNT query
213
    projects = User.current.projects.all
214
    if projects.any?
215
      s = '<select onchange="if (this.value != \'\') { window.location = this.value; }">' +
216
            "<option value=''>#{ l(:label_jump_to_a_project) }</option>" +
217
            '<option value="" disabled="disabled">---</option>'
218
      s << project_tree_options_for_select(projects, :selected => @project) do |p|
219
        { :value => url_for(:controller => 'projects', :action => 'show', :id => p, :jump => current_menu_item) }
220
      end
221
      s << '</select>'
222
      s
223
    end
224
  end
225
  
226
  def project_tree_options_for_select(projects, options = {})
227
    s = ''
228
    project_tree(projects) do |project, level|
229
      name_prefix = (level > 0 ? ('&nbsp;' * 2 * level + '&#187; ') : '')
230
      tag_options = {:value => project.id}
231
      if project == options[:selected] || (options[:selected].respond_to?(:include?) && options[:selected].include?(project))
232
        tag_options[:selected] = 'selected'
233
      else
234
        tag_options[:selected] = nil
235
      end
236
      tag_options.merge!(yield(project)) if block_given?
237
      s << content_tag('option', name_prefix + h(project), tag_options)
238
    end
239
    s
240
  end
241
  
242
  # Yields the given block for each project with its level in the tree
243
  #
244
  # Wrapper for Project#project_tree
245
  def project_tree(projects, &block)
246
    Project.project_tree(projects, &block)
247
  end
248
  
249
  def project_nested_ul(projects, &block)
250
    s = ''
251
    if projects.any?
252
      ancestors = []
253
      projects.sort_by(&:lft).each do |project|
254
        if (ancestors.empty? || project.is_descendant_of?(ancestors.last))
255
          s << "<ul>\n"
256
        else
257
          ancestors.pop
258
          s << "</li>"
259
          while (ancestors.any? && !project.is_descendant_of?(ancestors.last)) 
260
            ancestors.pop
261
            s << "</ul></li>\n"
262
          end
263
        end
264
        s << "<li>"
265
        s << yield(project).to_s
266
        ancestors << project
267
      end
268
      s << ("</li></ul>\n" * ancestors.size)
269
    end
270
    s
271
  end
272
  
273
  def principals_check_box_tags(name, principals)
274
    s = ''
275
    principals.sort.each do |principal|
276
      s << "<label>#{ check_box_tag name, principal.id, false } #{link_to_user principal}</label>\n"
277
    end
278
    s 
279
  end
280

    
281
  # Truncates and returns the string as a single line
282
  def truncate_single_line(string, *args)
283
    truncate(string.to_s, *args).gsub(%r{[\r\n]+}m, ' ')
284
  end
285
  
286
  # Truncates at line break after 250 characters or options[:length]
287
  def truncate_lines(string, options={})
288
    length = options[:length] || 250
289
    if string.to_s =~ /\A(.{#{length}}.*?)$/m
290
      "#{$1}..."
291
    else
292
      string
293
    end
294
  end
295

    
296
  def html_hours(text)
297
    text.gsub(%r{(\d+)\.(\d+)}, '<span class="hours hours-int">\1</span><span class="hours hours-dec">.\2</span>')
298
  end
299

    
300
  def authoring(created, author, options={})
301
    l(options[:label] || :label_added_time_by, :author => link_to_user(author), :age => time_tag(created))
302
  end
303
  
304
  def time_tag(time)
305
    text = distance_of_time_in_words(Time.now, time)
306
    if @project
307
      link_to(text, {:controller => 'activities', :action => 'index', :id => @project, :from => time.to_date}, :title => format_time(time))
308
    else
309
      content_tag('acronym', text, :title => format_time(time))
310
    end
311
  end
312

    
313
  def syntax_highlight(name, content)
314
    Redmine::SyntaxHighlighting.highlight_by_filename(content, name)
315
  end
316

    
317
  def to_path_param(path)
318
    path.to_s.split(%r{[/\\]}).select {|p| !p.blank?}
319
  end
320

    
321
  def pagination_links_full(paginator, count=nil, options={})
322
    page_param = options.delete(:page_param) || :page
323
    per_page_links = options.delete(:per_page_links)
324
    url_param = params.dup
325
    # don't reuse query params if filters are present
326
    url_param.merge!(:fields => nil, :values => nil, :operators => nil) if url_param.delete(:set_filter)
327

    
328
    html = ''
329
    if paginator.current.previous
330
      html << link_to_remote_content_update('&#171; ' + l(:label_previous), url_param.merge(page_param => paginator.current.previous)) + ' '
331
    end
332

    
333
    html << (pagination_links_each(paginator, options) do |n|
334
      link_to_remote_content_update(n.to_s, url_param.merge(page_param => n))
335
    end || '')
336
    
337
    if paginator.current.next
338
      html << ' ' + link_to_remote_content_update((l(:label_next) + ' &#187;'), url_param.merge(page_param => paginator.current.next))
339
    end
340

    
341
    unless count.nil?
342
      html << " (#{paginator.current.first_item}-#{paginator.current.last_item}/#{count})"
343
      if per_page_links != false && links = per_page_links(paginator.items_per_page)
344
              html << " | #{links}"
345
      end
346
    end
347

    
348
    html
349
  end
350
  
351
  def per_page_links(selected=nil)
352
    url_param = params.dup
353
    url_param.clear if url_param.has_key?(:set_filter)
354

    
355
    links = Setting.per_page_options_array.collect do |n|
356
      n == selected ? n : link_to_remote(n, {:update => "content",
357
                                             :url => params.dup.merge(:per_page => n),
358
                                             :method => :get},
359
                                            {:href => url_for(url_param.merge(:per_page => n))})
360
    end
361
    links.size > 1 ? l(:label_display_per_page, links.join(', ')) : nil
362
  end
363
  
364
  def reorder_links(name, url)
365
    link_to(image_tag('2uparrow.png',   :alt => l(:label_sort_highest)), url.merge({"#{name}[move_to]" => 'highest'}), :method => :post, :title => l(:label_sort_highest)) +
366
    link_to(image_tag('1uparrow.png',   :alt => l(:label_sort_higher)),  url.merge({"#{name}[move_to]" => 'higher'}),  :method => :post, :title => l(:label_sort_higher)) +
367
    link_to(image_tag('1downarrow.png', :alt => l(:label_sort_lower)),   url.merge({"#{name}[move_to]" => 'lower'}),   :method => :post, :title => l(:label_sort_lower)) +
368
    link_to(image_tag('2downarrow.png', :alt => l(:label_sort_lowest)),  url.merge({"#{name}[move_to]" => 'lowest'}),  :method => :post, :title => l(:label_sort_lowest))
369
  end
370

    
371
  def breadcrumb(*args)
372
    elements = args.flatten
373
    elements.any? ? content_tag('p', args.join(' &#187; ') + ' &#187; ', :class => 'breadcrumb') : nil
374
  end
375
  
376
  def other_formats_links(&block)
377
    concat('<p class="other-formats">' + l(:label_export_to))
378
    yield Redmine::Views::OtherFormatsBuilder.new(self)
379
    concat('</p>')
380
  end
381
  
382
  def page_header_title
383
    if @project.nil? || @project.new_record?
384
      a = [h(Setting.app_title), '']
385

    
386
    else
387
      pname = []
388
      b = []
389
      ancestors = (@project.root? ? [] : @project.ancestors.visible)
390
      if ancestors.any?
391
        root = ancestors.shift
392
        b << link_to_project(root, {:jump => current_menu_item}, :class => 'root')
393
        if ancestors.size > 2
394
          b << '&#8230;' 
395
          ancestors = ancestors[-2, 2]
396
        end
397
        b += ancestors.collect {|p| link_to_project(p, {:jump => current_menu_item}, :class => 'ancestor') }
398
        b = b.join(' &#187; ')
399
        b << (' &#187;')
400
      end
401

    
402
      pname << h(@project)
403

    
404
      a = [pname, b]
405

    
406
    end
407
  end
408

    
409
  def html_title(*args)
410
    if args.empty?
411
      title = []
412
      title << @project.name if @project
413
      title += @html_title if @html_title
414
      title << Setting.app_title
415
      title.select {|t| !t.blank? }.join(' - ')
416
    else
417
      @html_title ||= []
418
      @html_title += args
419
    end
420
  end
421

    
422
  # Returns the theme, controller name, and action as css classes for the
423
  # HTML body.
424
  def body_css_classes
425
    css = []
426
    if theme = Redmine::Themes.theme(Setting.ui_theme)
427
      css << 'theme-' + theme.name
428
    end
429

    
430
    css << 'controller-' + params[:controller]
431
    css << 'action-' + params[:action]
432
    css.join(' ')
433
  end
434

    
435
  def accesskey(s)
436
    Redmine::AccessKeys.key_for s
437
  end
438

    
439
  # Formats text according to system settings.
440
  # 2 ways to call this method:
441
  # * with a String: textilizable(text, options)
442
  # * with an object and one of its attribute: textilizable(issue, :description, options)
443
  def textilizable(*args)
444
    options = args.last.is_a?(Hash) ? args.pop : {}
445
    case args.size
446
    when 1
447
      obj = options[:object]
448
      text = args.shift
449
    when 2
450
      obj = args.shift
451
      attr = args.shift
452
      text = obj.send(attr).to_s
453
    else
454
      raise ArgumentError, 'invalid arguments to textilizable'
455
    end
456
    return '' if text.blank?
457
    project = options[:project] || @project || (obj && obj.respond_to?(:project) ? obj.project : nil)
458
    only_path = options.delete(:only_path) == false ? false : true
459

    
460
    text = Redmine::WikiFormatting.to_html(Setting.text_formatting, text, :object => obj, :attribute => attr) { |macro, args| exec_macro(macro, obj, args) }
461
      
462
    parse_non_pre_blocks(text) do |text|
463
      [:parse_inline_attachments, :parse_wiki_links, :parse_redmine_links, :parse_headings].each do |method_name|
464
        send method_name, text, project, obj, attr, only_path, options
465
      end
466
    end
467
  end
468
  
469
  def parse_non_pre_blocks(text)
470
    s = StringScanner.new(text)
471
    tags = []
472
    parsed = ''
473
    while !s.eos?
474
      s.scan(/(.*?)(<(\/)?(pre|code)(.*?)>|\z)/im)
475
      text, full_tag, closing, tag = s[1], s[2], s[3], s[4]
476
      if tags.empty?
477
        yield text
478
      end
479
      parsed << text
480
      if tag
481
        if closing
482
          if tags.last == tag.downcase
483
            tags.pop
484
          end
485
        else
486
          tags << tag.downcase
487
        end
488
        parsed << full_tag
489
      end
490
    end
491
    # Close any non closing tags
492
    while tag = tags.pop
493
      parsed << "</#{tag}>"
494
    end
495
    parsed
496
  end
497
  
498
  def parse_inline_attachments(text, project, obj, attr, only_path, options)
499
    # when using an image link, try to use an attachment, if possible
500
    if options[:attachments] || (obj && obj.respond_to?(:attachments))
501
      attachments = nil
502
      text.gsub!(/src="([^\/"]+\.(bmp|gif|jpg|jpeg|png))"(\s+alt="([^"]*)")?/i) do |m|
503
        filename, ext, alt, alttext = $1.downcase, $2, $3, $4 
504
        attachments ||= (options[:attachments] || obj.attachments).sort_by(&:created_on).reverse
505
        # search for the picture in attachments
506
        if found = attachments.detect { |att| att.filename.downcase == filename }
507
          image_url = url_for :only_path => only_path, :controller => 'attachments', :action => 'download', :id => found
508
          desc = found.description.to_s.gsub('"', '')
509
          if !desc.blank? && alttext.blank?
510
            alt = " title=\"#{desc}\" alt=\"#{desc}\""
511
          end
512
          "src=\"#{image_url}\"#{alt}"
513
        else
514
          m
515
        end
516
      end
517
    end
518
  end
519

    
520
  # Wiki links
521
  #
522
  # Examples:
523
  #   [[mypage]]
524
  #   [[mypage|mytext]]
525
  # wiki links can refer other project wikis, using project name or identifier:
526
  #   [[project:]] -> wiki starting page
527
  #   [[project:|mytext]]
528
  #   [[project:mypage]]
529
  #   [[project:mypage|mytext]]
530
  def parse_wiki_links(text, project, obj, attr, only_path, options)
531
    text.gsub!(/(!)?(\[\[([^\]\n\|]+)(\|([^\]\n\|]+))?\]\])/) do |m|
532
      link_project = project
533
      esc, all, page, title = $1, $2, $3, $5
534
      if esc.nil?
535
        if page =~ /^([^\:]+)\:(.*)$/
536
          link_project = Project.find_by_identifier($1) || Project.find_by_name($1)
537
          page = $2
538
          title ||= $1 if page.blank?
539
        end
540

    
541
        if link_project && link_project.wiki
542
          # extract anchor
543
          anchor = nil
544
          if page =~ /^(.+?)\#(.+)$/
545
            page, anchor = $1, $2
546
          end
547
          # check if page exists
548
          wiki_page = link_project.wiki.find_page(page)
549
          url = case options[:wiki_links]
550
            when :local; "#{title}.html"
551
            when :anchor; "##{title}"   # used for single-file wiki export
552
            else
553
              wiki_page_id = page.present? ? Wiki.titleize(page) : nil
554
              url_for(:only_path => only_path, :controller => 'wiki', :action => 'show', :project_id => link_project, :id => wiki_page_id, :anchor => anchor)
555
            end
556
          link_to((title || page), url, :class => ('wiki-page' + (wiki_page ? '' : ' new')))
557
        else
558
          # project or wiki doesn't exist
559
          all
560
        end
561
      else
562
        all
563
      end
564
    end
565
  end
566
  
567
  # Redmine links
568
  #
569
  # Examples:
570
  #   Issues:
571
  #     #52 -> Link to issue #52
572
  #   Changesets:
573
  #     r52 -> Link to revision 52
574
  #     commit:a85130f -> Link to scmid starting with a85130f
575
  #   Documents:
576
  #     document#17 -> Link to document with id 17
577
  #     document:Greetings -> Link to the document with title "Greetings"
578
  #     document:"Some document" -> Link to the document with title "Some document"
579
  #   Versions:
580
  #     version#3 -> Link to version with id 3
581
  #     version:1.0.0 -> Link to version named "1.0.0"
582
  #     version:"1.0 beta 2" -> Link to version named "1.0 beta 2"
583
  #   Attachments:
584
  #     attachment:file.zip -> Link to the attachment of the current object named file.zip
585
  #   Source files:
586
  #     source:some/file -> Link to the file located at /some/file in the project's repository
587
  #     source:some/file@52 -> Link to the file's revision 52
588
  #     source:some/file#L120 -> Link to line 120 of the file
589
  #     source:some/file@52#L120 -> Link to line 120 of the file's revision 52
590
  #     export:some/file -> Force the download of the file
591
  #  Forum messages:
592
  #     message#1218 -> Link to message with id 1218
593
  def parse_redmine_links(text, project, obj, attr, only_path, options)
594
    text.gsub!(%r{([\s\(,\-\[\>]|^)(!)?(attachment|document|version|commit|source|export|message|project)?((#|r)(\d+)|(:)([^"\s<>][^\s<>]*?|"[^"]+?"))(?=(?=[[:punct:]]\W)|,|\s|\]|<|$)}) do |m|
595
      leading, esc, prefix, sep, identifier = $1, $2, $3, $5 || $7, $6 || $8
596
      link = nil
597
      if esc.nil?
598
        if prefix.nil? && sep == 'r'
599
          if project && (changeset = project.changesets.find_by_revision(identifier))
600
            link = link_to("r#{identifier}", {:only_path => only_path, :controller => 'repositories', :action => 'revision', :id => project, :rev => changeset.revision},
601
                                      :class => 'changeset',
602
                                      :title => truncate_single_line(changeset.comments, :length => 100))
603
          end
604
        elsif sep == '#'
605
          oid = identifier.to_i
606
          case prefix
607
          when nil
608
            if issue = Issue.visible.find_by_id(oid, :include => :status)
609
              link = link_to("##{oid}", {:only_path => only_path, :controller => 'issues', :action => 'show', :id => oid},
610
                                        :class => issue.css_classes,
611
                                        :title => "#{truncate(issue.subject, :length => 100)} (#{issue.status.name})")
612
            end
613
          when 'document'
614
            if document = Document.find_by_id(oid, :include => [:project], :conditions => Project.visible_by(User.current))
615
              link = link_to h(document.title), {:only_path => only_path, :controller => 'documents', :action => 'show', :id => document},
616
                                                :class => 'document'
617
            end
618
          when 'version'
619
            if version = Version.find_by_id(oid, :include => [:project], :conditions => Project.visible_by(User.current))
620
              link = link_to h(version.name), {:only_path => only_path, :controller => 'versions', :action => 'show', :id => version},
621
                                              :class => 'version'
622
            end
623
          when 'message'
624
            if message = Message.find_by_id(oid, :include => [:parent, {:board => :project}], :conditions => Project.visible_by(User.current))
625
              link = link_to h(truncate(message.subject, :length => 60)), {:only_path => only_path,
626
                                                                :controller => 'messages',
627
                                                                :action => 'show',
628
                                                                :board_id => message.board,
629
                                                                :id => message.root,
630
                                                                :anchor => (message.parent ? "message-#{message.id}" : nil)},
631
                                                 :class => 'message'
632
            end
633
          when 'project'
634
            if p = Project.visible.find_by_id(oid)
635
              link = link_to_project(p, {:only_path => only_path}, :class => 'project')
636
            end
637
          end
638
        elsif sep == ':'
639
          # removes the double quotes if any
640
          name = identifier.gsub(%r{^"(.*)"$}, "\\1")
641
          case prefix
642
          when 'document'
643
            if project && document = project.documents.find_by_title(name)
644
              link = link_to h(document.title), {:only_path => only_path, :controller => 'documents', :action => 'show', :id => document},
645
                                                :class => 'document'
646
            end
647
          when 'version'
648
            if project && version = project.versions.find_by_name(name)
649
              link = link_to h(version.name), {:only_path => only_path, :controller => 'versions', :action => 'show', :id => version},
650
                                              :class => 'version'
651
            end
652
          when 'commit'
653
            if project && (changeset = project.changesets.find(:first, :conditions => ["scmid LIKE ?", "#{name}%"]))
654
              link = link_to h("#{name}"), {:only_path => only_path, :controller => 'repositories', :action => 'revision', :id => project, :rev => changeset.identifier},
655
                                           :class => 'changeset',
656
                                           :title => truncate_single_line(changeset.comments, :length => 100)
657
            end
658
          when 'source', 'export'
659
            if project && project.repository
660
              name =~ %r{^[/\\]*(.*?)(@([0-9a-f]+))?(#(L\d+))?$}
661
              path, rev, anchor = $1, $3, $5
662
              link = link_to h("#{prefix}:#{name}"), {:controller => 'repositories', :action => 'entry', :id => project,
663
                                                      :path => to_path_param(path),
664
                                                      :rev => rev,
665
                                                      :anchor => anchor,
666
                                                      :format => (prefix == 'export' ? 'raw' : nil)},
667
                                                     :class => (prefix == 'export' ? 'source download' : 'source')
668
            end
669
          when 'attachment'
670
            attachments = options[:attachments] || (obj && obj.respond_to?(:attachments) ? obj.attachments : nil)
671
            if attachments && attachment = attachments.detect {|a| a.filename == name }
672
              link = link_to h(attachment.filename), {:only_path => only_path, :controller => 'attachments', :action => 'download', :id => attachment},
673
                                                     :class => 'attachment'
674
            end
675
          when 'project'
676
            if p = Project.visible.find(:first, :conditions => ["identifier = :s OR LOWER(name) = :s", {:s => name.downcase}])
677
              link = link_to_project(p, {:only_path => only_path}, :class => 'project')
678
            end
679
          end
680
        end
681
      end
682
      leading + (link || "#{prefix}#{sep}#{identifier}")
683
    end
684
  end
685
  
686
  TOC_RE = /<p>\{\{([<>]?)toc\}\}<\/p>/i unless const_defined?(:TOC_RE)
687
  HEADING_RE = /<h(1|2|3|4)( [^>]+)?>(.+?)<\/h(1|2|3|4)>/i unless const_defined?(:HEADING_RE)
688
  
689
  # Headings and TOC
690
  # Adds ids and links to headings and renders the TOC if needed unless options[:headings] is set to false
691
  def parse_headings(text, project, obj, attr, only_path, options)
692
    headings = []
693
    text.gsub!(HEADING_RE) do
694
      level, attrs, content = $1.to_i, $2, $3
695
      item = strip_tags(content).strip
696
      anchor = item.gsub(%r{[^\w\s\-]}, '').gsub(%r{\s+(\-+\s*)?}, '-')
697
      headings << [level, anchor, item]
698
      "<h#{level} #{attrs} id=\"#{anchor}\">#{content}<a href=\"##{anchor}\" class=\"wiki-anchor\">&para;</a></h#{level}>"
699
    end unless options[:headings] == false
700
    
701
    text.gsub!(TOC_RE) do
702
      if headings.empty?
703
        ''
704
      else
705
        div_class = 'toc'
706
        div_class << ' right' if $1 == '>'
707
        div_class << ' left' if $1 == '<'
708
        out = "<ul class=\"#{div_class}\"><li>"
709
        root = headings.map(&:first).min
710
        current = root
711
        started = false
712
        headings.each do |level, anchor, item|
713
          if level > current
714
            out << '<ul><li>' * (level - current)
715
          elsif level < current
716
            out << "</li></ul>\n" * (current - level) + "</li><li>"
717
          elsif started
718
            out << '</li><li>'
719
          end
720
          out << "<a href=\"##{anchor}\">#{item}</a>"
721
          current = level
722
          started = true
723
        end
724
        out << '</li></ul>' * (current - root)
725
        out << '</li></ul>'
726
      end
727
    end
728
  end
729

    
730
  # Same as Rails' simple_format helper without using paragraphs
731
  def simple_format_without_paragraph(text)
732
    text.to_s.
733
      gsub(/\r\n?/, "\n").                    # \r\n and \r -> \n
734
      gsub(/\n\n+/, "<br /><br />").          # 2+ newline  -> 2 br
735
      gsub(/([^\n]\n)(?=[^\n])/, '\1<br />')  # 1 newline   -> br
736
  end
737

    
738
  def lang_options_for_select(blank=true)
739
    (blank ? [["(auto)", ""]] : []) +
740
      valid_languages.collect{|lang| [ ll(lang.to_s, :general_lang_name), lang.to_s]}.sort{|x,y| x.last <=> y.last }
741
  end
742

    
743
  def label_tag_for(name, option_tags = nil, options = {})
744
    label_text = l(("field_"+field.to_s.gsub(/\_id$/, "")).to_sym) + (options.delete(:required) ? @template.content_tag("span", " *", :class => "required"): "")
745
    content_tag("label", label_text)
746
  end
747

    
748
  def labelled_tabular_form_for(name, object, options, &proc)
749
    options[:html] ||= {}
750
    options[:html][:class] = 'tabular' unless options[:html].has_key?(:class)
751
    form_for(name, object, options.merge({ :builder => TabularFormBuilder, :lang => current_language}), &proc)
752
  end
753

    
754
  def back_url_hidden_field_tag
755
    back_url = params[:back_url] || request.env['HTTP_REFERER']
756
    back_url = CGI.unescape(back_url.to_s)
757
    hidden_field_tag('back_url', CGI.escape(back_url)) unless back_url.blank?
758
  end
759

    
760
  def check_all_links(form_name)
761
    link_to_function(l(:button_check_all), "checkAll('#{form_name}', true)") +
762
    " | " +
763
    link_to_function(l(:button_uncheck_all), "checkAll('#{form_name}', false)")
764
  end
765

    
766
  def progress_bar(pcts, options={})
767
    pcts = [pcts, pcts] unless pcts.is_a?(Array)
768
    pcts = pcts.collect(&:round)
769
    pcts[1] = pcts[1] - pcts[0]
770
    pcts << (100 - pcts[1] - pcts[0])
771
    width = options[:width] || '100px;'
772
    legend = options[:legend] || ''
773
    content_tag('table',
774
      content_tag('tr',
775
        (pcts[0] > 0 ? content_tag('td', '', :style => "width: #{pcts[0]}%;", :class => 'closed') : '') +
776
        (pcts[1] > 0 ? content_tag('td', '', :style => "width: #{pcts[1]}%;", :class => 'done') : '') +
777
        (pcts[2] > 0 ? content_tag('td', '', :style => "width: #{pcts[2]}%;", :class => 'todo') : '')
778
      ), :class => 'progress', :style => "width: #{width};") +
779
      content_tag('p', legend, :class => 'pourcent')
780
  end
781
  
782
  def checked_image(checked=true)
783
    if checked
784
      image_tag 'toggle_check.png'
785
    end
786
  end
787
  
788
  def context_menu(url)
789
    unless @context_menu_included
790
      content_for :header_tags do
791
        javascript_include_tag('context_menu') +
792
          stylesheet_link_tag('context_menu')
793
      end
794
      if l(:direction) == 'rtl'
795
        content_for :header_tags do
796
          stylesheet_link_tag('context_menu_rtl')
797
        end
798
      end
799
      @context_menu_included = true
800
    end
801
    javascript_tag "new ContextMenu('#{ url_for(url) }')"
802
  end
803

    
804
  def context_menu_link(name, url, options={})
805
    options[:class] ||= ''
806
    if options.delete(:selected)
807
      options[:class] << ' icon-checked disabled'
808
      options[:disabled] = true
809
    end
810
    if options.delete(:disabled)
811
      options.delete(:method)
812
      options.delete(:confirm)
813
      options.delete(:onclick)
814
      options[:class] << ' disabled'
815
      url = '#'
816
    end
817
    link_to name, url, options
818
  end
819

    
820
  def calendar_for(field_id)
821
    include_calendar_headers_tags
822
    image_tag("calendar.png", {:id => "#{field_id}_trigger",:class => "calendar-trigger"}) +
823
    javascript_tag("Calendar.setup({inputField : '#{field_id}', ifFormat : '%Y-%m-%d', button : '#{field_id}_trigger' });")
824
  end
825

    
826
  def include_calendar_headers_tags
827
    unless @calendar_headers_tags_included
828
      @calendar_headers_tags_included = true
829
      content_for :header_tags do
830
        start_of_week = case Setting.start_of_week.to_i
831
        when 1
832
          'Calendar._FD = 1;' # Monday
833
        when 7
834
          'Calendar._FD = 0;' # Sunday
835
        else
836
          '' # use language
837
        end
838
        
839
        javascript_include_tag('calendar/calendar') +
840
        javascript_include_tag("calendar/lang/calendar-#{current_language.to_s.downcase}.js") +
841
        javascript_tag(start_of_week) +  
842
        javascript_include_tag('calendar/calendar-setup') +
843
        stylesheet_link_tag('calendar')
844
      end
845
    end
846
  end
847

    
848
  def content_for(name, content = nil, &block)
849
    @has_content ||= {}
850
    @has_content[name] = true
851
    super(name, content, &block)
852
  end
853

    
854
  def has_content?(name)
855
    (@has_content && @has_content[name]) || false
856
  end
857

    
858
  # Returns the avatar image tag for the given +user+ if avatars are enabled
859
  # +user+ can be a User or a string that will be scanned for an email address (eg. 'joe <joe@foo.bar>')
860
  def avatar(user, options = { })
861
    if Setting.gravatar_enabled?
862
      options.merge!({:ssl => (defined?(request) && request.ssl?), :default => Setting.gravatar_default})
863
      email = nil
864
      if user.respond_to?(:mail)
865
        email = user.mail
866
      elsif user.to_s =~ %r{<(.+?)>}
867
        email = $1
868
      end
869
      return gravatar(email.to_s.downcase, options) unless email.blank? rescue nil
870
    else
871
      ''
872
    end
873
  end
874

    
875
  def favicon
876
    "<link rel='shortcut icon' href='#{image_path('/favicon.ico')}' />"
877
  end
878

    
879
  private
880

    
881
  def wiki_helper
882
    helper = Redmine::WikiFormatting.helper_for(Setting.text_formatting)
883
    extend helper
884
    return self
885
  end
886
  
887
  def link_to_remote_content_update(text, url_params)
888
    link_to_remote(text,
889
      {:url => url_params, :method => :get, :update => 'content', :complete => 'window.scrollTo(0,0)'},
890
      {:href => url_for(:params => url_params)}
891
    )
892
  end
893
  
894
end