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