##// END OF EJS Templates
Optimization: load attachments when needed....
Jean-Philippe Lang -
r3467:2f5c17a0f6ea
parent child
Show More
@@ -1,760 +1,759
1 1 # redMine - project management software
2 2 # Copyright (C) 2006-2007 Jean-Philippe Lang
3 3 #
4 4 # This program is free software; you can redistribute it and/or
5 5 # modify it under the terms of the GNU General Public License
6 6 # as published by the Free Software Foundation; either version 2
7 7 # of the License, or (at your option) any later version.
8 8 #
9 9 # This program is distributed in the hope that it will be useful,
10 10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 12 # GNU General Public License for more details.
13 13 #
14 14 # You should have received a copy of the GNU General Public License
15 15 # along with this program; if not, write to the Free Software
16 16 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17 17
18 18 require 'coderay'
19 19 require 'coderay/helpers/file_type'
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
28 28 extend Forwardable
29 29 def_delegators :wiki_helper, :wikitoolbar_for, :heads_for_wiki_formatter
30 30
31 31 # Return true if user is authorized for controller/action, otherwise false
32 32 def authorize_for(controller, action)
33 33 User.current.allowed_to?({:controller => controller, :action => action}, @project)
34 34 end
35 35
36 36 # Display a link if user is authorized
37 37 def link_to_if_authorized(name, options = {}, html_options = nil, *parameters_for_method_reference)
38 38 link_to(name, options, html_options, *parameters_for_method_reference) if authorize_for(options[:controller] || params[:controller], options[:action])
39 39 end
40 40
41 41 # Display a link to remote if user is authorized
42 42 def link_to_remote_if_authorized(name, options = {}, html_options = nil)
43 43 url = options[:url] || {}
44 44 link_to_remote(name, options, html_options) if authorize_for(url[:controller] || params[:controller], url[: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?
52 52 link_to name, :controller => 'users', :action => 'show', :id => user
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 #
69 69 def link_to_issue(issue, options={})
70 70 title = nil
71 71 subject = nil
72 72 if options[:subject] == false
73 73 title = truncate(issue.subject, :length => 60)
74 74 else
75 75 subject = issue.subject
76 76 if options[:truncate]
77 77 subject = truncate(subject, :length => options[:truncate])
78 78 end
79 79 end
80 80 s = link_to "#{issue.tracker} ##{issue.id}", {:controller => "issues", :action => "show", :id => issue},
81 81 :class => issue.css_classes,
82 82 :title => title
83 83 s << ": #{h subject}" if subject
84 84 s = "#{h issue.project} - " + s if options[:project]
85 85 s
86 86 end
87 87
88 88 # Generates a link to an attachment.
89 89 # Options:
90 90 # * :text - Link text (default to attachment filename)
91 91 # * :download - Force download (default: false)
92 92 def link_to_attachment(attachment, options={})
93 93 text = options.delete(:text) || attachment.filename
94 94 action = options.delete(:download) ? 'download' : 'show'
95 95
96 96 link_to(h(text), {:controller => 'attachments', :action => action, :id => attachment, :filename => attachment.filename }, options)
97 97 end
98 98
99 99 # Generates a link to a SCM revision
100 100 # Options:
101 101 # * :text - Link text (default to the formatted revision)
102 102 def link_to_revision(revision, project, options={})
103 103 text = options.delete(:text) || format_revision(revision)
104 104
105 105 link_to(text, {:controller => 'repositories', :action => 'revision', :id => project, :rev => revision}, :title => l(:label_revision_id, revision))
106 106 end
107 107
108 108 def toggle_link(name, id, options={})
109 109 onclick = "Element.toggle('#{id}'); "
110 110 onclick << (options[:focus] ? "Form.Element.focus('#{options[:focus]}'); " : "this.blur(); ")
111 111 onclick << "return false;"
112 112 link_to(name, "#", :onclick => onclick)
113 113 end
114 114
115 115 def image_to_function(name, function, html_options = {})
116 116 html_options.symbolize_keys!
117 117 tag(:input, html_options.merge({
118 118 :type => "image", :src => image_path(name),
119 119 :onclick => (html_options[:onclick] ? "#{html_options[:onclick]}; " : "") + "#{function};"
120 120 }))
121 121 end
122 122
123 123 def prompt_to_remote(name, text, param, url, html_options = {})
124 124 html_options[:onclick] = "promptToRemote('#{text}', '#{param}', '#{url_for(url)}'); return false;"
125 125 link_to name, {}, html_options
126 126 end
127 127
128 128 def format_activity_title(text)
129 129 h(truncate_single_line(text, :length => 100))
130 130 end
131 131
132 132 def format_activity_day(date)
133 133 date == Date.today ? l(:label_today).titleize : format_date(date)
134 134 end
135 135
136 136 def format_activity_description(text)
137 137 h(truncate(text.to_s, :length => 120).gsub(%r{[\r\n]*<(pre|code)>.*$}m, '...')).gsub(/[\r\n]+/, "<br />")
138 138 end
139 139
140 140 def format_version_name(version)
141 141 if version.project == @project
142 142 h(version)
143 143 else
144 144 h("#{version.project} - #{version}")
145 145 end
146 146 end
147 147
148 148 def due_date_distance_in_words(date)
149 149 if date
150 150 l((date < Date.today ? :label_roadmap_overdue : :label_roadmap_due_in), distance_of_date_in_words(Date.today, date))
151 151 end
152 152 end
153 153
154 154 def render_page_hierarchy(pages, node=nil)
155 155 content = ''
156 156 if pages[node]
157 157 content << "<ul class=\"pages-hierarchy\">\n"
158 158 pages[node].each do |page|
159 159 content << "<li>"
160 160 content << link_to(h(page.pretty_title), {:controller => 'wiki', :action => 'index', :id => page.project, :page => page.title},
161 161 :title => (page.respond_to?(:updated_on) ? l(:label_updated_time, distance_of_time_in_words(Time.now, page.updated_on)) : nil))
162 162 content << "\n" + render_page_hierarchy(pages, page.id) if pages[page.id]
163 163 content << "</li>\n"
164 164 end
165 165 content << "</ul>\n"
166 166 end
167 167 content
168 168 end
169 169
170 170 # Renders flash messages
171 171 def render_flash_messages
172 172 s = ''
173 173 flash.each do |k,v|
174 174 s << content_tag('div', v, :class => "flash #{k}")
175 175 end
176 176 s
177 177 end
178 178
179 179 # Renders tabs and their content
180 180 def render_tabs(tabs)
181 181 if tabs.any?
182 182 render :partial => 'common/tabs', :locals => {:tabs => tabs}
183 183 else
184 184 content_tag 'p', l(:label_no_data), :class => "nodata"
185 185 end
186 186 end
187 187
188 188 # Renders the project quick-jump box
189 189 def render_project_jump_box
190 190 # Retrieve them now to avoid a COUNT query
191 191 projects = User.current.projects.all
192 192 if projects.any?
193 193 s = '<select onchange="if (this.value != \'\') { window.location = this.value; }">' +
194 194 "<option value=''>#{ l(:label_jump_to_a_project) }</option>" +
195 195 '<option value="" disabled="disabled">---</option>'
196 196 s << project_tree_options_for_select(projects, :selected => @project) do |p|
197 197 { :value => url_for(:controller => 'projects', :action => 'show', :id => p, :jump => current_menu_item) }
198 198 end
199 199 s << '</select>'
200 200 s
201 201 end
202 202 end
203 203
204 204 def project_tree_options_for_select(projects, options = {})
205 205 s = ''
206 206 project_tree(projects) do |project, level|
207 207 name_prefix = (level > 0 ? ('&nbsp;' * 2 * level + '&#187; ') : '')
208 208 tag_options = {:value => project.id}
209 209 if project == options[:selected] || (options[:selected].respond_to?(:include?) && options[:selected].include?(project))
210 210 tag_options[:selected] = 'selected'
211 211 else
212 212 tag_options[:selected] = nil
213 213 end
214 214 tag_options.merge!(yield(project)) if block_given?
215 215 s << content_tag('option', name_prefix + h(project), tag_options)
216 216 end
217 217 s
218 218 end
219 219
220 220 # Yields the given block for each project with its level in the tree
221 221 def project_tree(projects, &block)
222 222 ancestors = []
223 223 projects.sort_by(&:lft).each do |project|
224 224 while (ancestors.any? && !project.is_descendant_of?(ancestors.last))
225 225 ancestors.pop
226 226 end
227 227 yield project, ancestors.size
228 228 ancestors << project
229 229 end
230 230 end
231 231
232 232 def project_nested_ul(projects, &block)
233 233 s = ''
234 234 if projects.any?
235 235 ancestors = []
236 236 projects.sort_by(&:lft).each do |project|
237 237 if (ancestors.empty? || project.is_descendant_of?(ancestors.last))
238 238 s << "<ul>\n"
239 239 else
240 240 ancestors.pop
241 241 s << "</li>"
242 242 while (ancestors.any? && !project.is_descendant_of?(ancestors.last))
243 243 ancestors.pop
244 244 s << "</ul></li>\n"
245 245 end
246 246 end
247 247 s << "<li>"
248 248 s << yield(project).to_s
249 249 ancestors << project
250 250 end
251 251 s << ("</li></ul>\n" * ancestors.size)
252 252 end
253 253 s
254 254 end
255 255
256 256 def principals_check_box_tags(name, principals)
257 257 s = ''
258 258 principals.sort.each do |principal|
259 259 s << "<label>#{ check_box_tag name, principal.id, false } #{h principal}</label>\n"
260 260 end
261 261 s
262 262 end
263 263
264 264 # Truncates and returns the string as a single line
265 265 def truncate_single_line(string, *args)
266 266 truncate(string.to_s, *args).gsub(%r{[\r\n]+}m, ' ')
267 267 end
268 268
269 269 def html_hours(text)
270 270 text.gsub(%r{(\d+)\.(\d+)}, '<span class="hours hours-int">\1</span><span class="hours hours-dec">.\2</span>')
271 271 end
272 272
273 273 def authoring(created, author, options={})
274 274 l(options[:label] || :label_added_time_by, :author => link_to_user(author), :age => time_tag(created))
275 275 end
276 276
277 277 def time_tag(time)
278 278 text = distance_of_time_in_words(Time.now, time)
279 279 if @project
280 280 link_to(text, {:controller => 'projects', :action => 'activity', :id => @project, :from => time.to_date}, :title => format_time(time))
281 281 else
282 282 content_tag('acronym', text, :title => format_time(time))
283 283 end
284 284 end
285 285
286 286 def syntax_highlight(name, content)
287 287 type = CodeRay::FileType[name]
288 288 type ? CodeRay.scan(content, type).html : h(content)
289 289 end
290 290
291 291 def to_path_param(path)
292 292 path.to_s.split(%r{[/\\]}).select {|p| !p.blank?}
293 293 end
294 294
295 295 def pagination_links_full(paginator, count=nil, options={})
296 296 page_param = options.delete(:page_param) || :page
297 297 per_page_links = options.delete(:per_page_links)
298 298 url_param = params.dup
299 299 # don't reuse query params if filters are present
300 300 url_param.merge!(:fields => nil, :values => nil, :operators => nil) if url_param.delete(:set_filter)
301 301
302 302 html = ''
303 303 if paginator.current.previous
304 304 html << link_to_remote_content_update('&#171; ' + l(:label_previous), url_param.merge(page_param => paginator.current.previous)) + ' '
305 305 end
306 306
307 307 html << (pagination_links_each(paginator, options) do |n|
308 308 link_to_remote_content_update(n.to_s, url_param.merge(page_param => n))
309 309 end || '')
310 310
311 311 if paginator.current.next
312 312 html << ' ' + link_to_remote_content_update((l(:label_next) + ' &#187;'), url_param.merge(page_param => paginator.current.next))
313 313 end
314 314
315 315 unless count.nil?
316 316 html << " (#{paginator.current.first_item}-#{paginator.current.last_item}/#{count})"
317 317 if per_page_links != false && links = per_page_links(paginator.items_per_page)
318 318 html << " | #{links}"
319 319 end
320 320 end
321 321
322 322 html
323 323 end
324 324
325 325 def per_page_links(selected=nil)
326 326 url_param = params.dup
327 327 url_param.clear if url_param.has_key?(:set_filter)
328 328
329 329 links = Setting.per_page_options_array.collect do |n|
330 330 n == selected ? n : link_to_remote(n, {:update => "content",
331 331 :url => params.dup.merge(:per_page => n),
332 332 :method => :get},
333 333 {:href => url_for(url_param.merge(:per_page => n))})
334 334 end
335 335 links.size > 1 ? l(:label_display_per_page, links.join(', ')) : nil
336 336 end
337 337
338 338 def reorder_links(name, url)
339 339 link_to(image_tag('2uparrow.png', :alt => l(:label_sort_highest)), url.merge({"#{name}[move_to]" => 'highest'}), :method => :post, :title => l(:label_sort_highest)) +
340 340 link_to(image_tag('1uparrow.png', :alt => l(:label_sort_higher)), url.merge({"#{name}[move_to]" => 'higher'}), :method => :post, :title => l(:label_sort_higher)) +
341 341 link_to(image_tag('1downarrow.png', :alt => l(:label_sort_lower)), url.merge({"#{name}[move_to]" => 'lower'}), :method => :post, :title => l(:label_sort_lower)) +
342 342 link_to(image_tag('2downarrow.png', :alt => l(:label_sort_lowest)), url.merge({"#{name}[move_to]" => 'lowest'}), :method => :post, :title => l(:label_sort_lowest))
343 343 end
344 344
345 345 def breadcrumb(*args)
346 346 elements = args.flatten
347 347 elements.any? ? content_tag('p', args.join(' &#187; ') + ' &#187; ', :class => 'breadcrumb') : nil
348 348 end
349 349
350 350 def other_formats_links(&block)
351 351 concat('<p class="other-formats">' + l(:label_export_to))
352 352 yield Redmine::Views::OtherFormatsBuilder.new(self)
353 353 concat('</p>')
354 354 end
355 355
356 356 def page_header_title
357 357 if @project.nil? || @project.new_record?
358 358 h(Setting.app_title)
359 359 else
360 360 b = []
361 361 ancestors = (@project.root? ? [] : @project.ancestors.visible)
362 362 if ancestors.any?
363 363 root = ancestors.shift
364 364 b << link_to(h(root), {:controller => 'projects', :action => 'show', :id => root, :jump => current_menu_item}, :class => 'root')
365 365 if ancestors.size > 2
366 366 b << '&#8230;'
367 367 ancestors = ancestors[-2, 2]
368 368 end
369 369 b += ancestors.collect {|p| link_to(h(p), {:controller => 'projects', :action => 'show', :id => p, :jump => current_menu_item}, :class => 'ancestor') }
370 370 end
371 371 b << h(@project)
372 372 b.join(' &#187; ')
373 373 end
374 374 end
375 375
376 376 def html_title(*args)
377 377 if args.empty?
378 378 title = []
379 379 title << @project.name if @project
380 380 title += @html_title if @html_title
381 381 title << Setting.app_title
382 382 title.select {|t| !t.blank? }.join(' - ')
383 383 else
384 384 @html_title ||= []
385 385 @html_title += args
386 386 end
387 387 end
388 388
389 389 def accesskey(s)
390 390 Redmine::AccessKeys.key_for s
391 391 end
392 392
393 393 # Formats text according to system settings.
394 394 # 2 ways to call this method:
395 395 # * with a String: textilizable(text, options)
396 396 # * with an object and one of its attribute: textilizable(issue, :description, options)
397 397 def textilizable(*args)
398 398 options = args.last.is_a?(Hash) ? args.pop : {}
399 399 case args.size
400 400 when 1
401 401 obj = options[:object]
402 402 text = args.shift
403 403 when 2
404 404 obj = args.shift
405 405 attr = args.shift
406 406 text = obj.send(attr).to_s
407 407 else
408 408 raise ArgumentError, 'invalid arguments to textilizable'
409 409 end
410 410 return '' if text.blank?
411 411
412 412 text = Redmine::WikiFormatting.to_html(Setting.text_formatting, text, :object => obj, :attribute => attr) { |macro, args| exec_macro(macro, obj, args) }
413 413
414 414 only_path = options.delete(:only_path) == false ? false : true
415 415
416 416 # when using an image link, try to use an attachment, if possible
417 attachments = options[:attachments] || (obj && obj.respond_to?(:attachments) ? obj.attachments : nil)
418
419 if attachments
420 attachments = attachments.sort_by(&:created_on).reverse
417 if options[:attachments] || (obj && obj.respond_to?(:attachments))
418 attachments = nil
421 419 text.gsub!(/src="([^\/"]+\.(bmp|gif|jpg|jpeg|png))"(\s+alt="([^"]*)")?/i) do |m|
422 420 filename, ext, alt, alttext = $1.downcase, $2, $3, $4
423
421 attachments ||= (options[:attachments] || obj.attachments).sort_by(&:created_on).reverse
424 422 # search for the picture in attachments
425 423 if found = attachments.detect { |att| att.filename.downcase == filename }
426 424 image_url = url_for :only_path => only_path, :controller => 'attachments', :action => 'download', :id => found
427 425 desc = found.description.to_s.gsub('"', '')
428 426 if !desc.blank? && alttext.blank?
429 427 alt = " title=\"#{desc}\" alt=\"#{desc}\""
430 428 end
431 429 "src=\"#{image_url}\"#{alt}"
432 430 else
433 431 m
434 432 end
435 433 end
436 434 end
437 435
438 436
439 437 # different methods for formatting wiki links
440 438 case options[:wiki_links]
441 439 when :local
442 440 # used for local links to html files
443 441 format_wiki_link = Proc.new {|project, title, anchor| "#{title}.html" }
444 442 when :anchor
445 443 # used for single-file wiki export
446 444 format_wiki_link = Proc.new {|project, title, anchor| "##{title}" }
447 445 else
448 446 format_wiki_link = Proc.new {|project, title, anchor| url_for(:only_path => only_path, :controller => 'wiki', :action => 'index', :id => project, :page => title, :anchor => anchor) }
449 447 end
450 448
451 449 project = options[:project] || @project || (obj && obj.respond_to?(:project) ? obj.project : nil)
452 450
453 451 # Wiki links
454 452 #
455 453 # Examples:
456 454 # [[mypage]]
457 455 # [[mypage|mytext]]
458 456 # wiki links can refer other project wikis, using project name or identifier:
459 457 # [[project:]] -> wiki starting page
460 458 # [[project:|mytext]]
461 459 # [[project:mypage]]
462 460 # [[project:mypage|mytext]]
463 461 text = text.gsub(/(!)?(\[\[([^\]\n\|]+)(\|([^\]\n\|]+))?\]\])/) do |m|
464 462 link_project = project
465 463 esc, all, page, title = $1, $2, $3, $5
466 464 if esc.nil?
467 465 if page =~ /^([^\:]+)\:(.*)$/
468 466 link_project = Project.find_by_name($1) || Project.find_by_identifier($1)
469 467 page = $2
470 468 title ||= $1 if page.blank?
471 469 end
472 470
473 471 if link_project && link_project.wiki
474 472 # extract anchor
475 473 anchor = nil
476 474 if page =~ /^(.+?)\#(.+)$/
477 475 page, anchor = $1, $2
478 476 end
479 477 # check if page exists
480 478 wiki_page = link_project.wiki.find_page(page)
481 479 link_to((title || page), format_wiki_link.call(link_project, Wiki.titleize(page), anchor),
482 480 :class => ('wiki-page' + (wiki_page ? '' : ' new')))
483 481 else
484 482 # project or wiki doesn't exist
485 483 all
486 484 end
487 485 else
488 486 all
489 487 end
490 488 end
491 489
492 490 # Redmine links
493 491 #
494 492 # Examples:
495 493 # Issues:
496 494 # #52 -> Link to issue #52
497 495 # Changesets:
498 496 # r52 -> Link to revision 52
499 497 # commit:a85130f -> Link to scmid starting with a85130f
500 498 # Documents:
501 499 # document#17 -> Link to document with id 17
502 500 # document:Greetings -> Link to the document with title "Greetings"
503 501 # document:"Some document" -> Link to the document with title "Some document"
504 502 # Versions:
505 503 # version#3 -> Link to version with id 3
506 504 # version:1.0.0 -> Link to version named "1.0.0"
507 505 # version:"1.0 beta 2" -> Link to version named "1.0 beta 2"
508 506 # Attachments:
509 507 # attachment:file.zip -> Link to the attachment of the current object named file.zip
510 508 # Source files:
511 509 # source:some/file -> Link to the file located at /some/file in the project's repository
512 510 # source:some/file@52 -> Link to the file's revision 52
513 511 # source:some/file#L120 -> Link to line 120 of the file
514 512 # source:some/file@52#L120 -> Link to line 120 of the file's revision 52
515 513 # export:some/file -> Force the download of the file
516 514 # Forum messages:
517 515 # message#1218 -> Link to message with id 1218
518 516 text = text.gsub(%r{([\s\(,\-\>]|^)(!)?(attachment|document|version|commit|source|export|message|project)?((#|r)(\d+)|(:)([^"\s<>][^\s<>]*?|"[^"]+?"))(?=(?=[[:punct:]]\W)|,|\s|<|$)}) do |m|
519 517 leading, esc, prefix, sep, identifier = $1, $2, $3, $5 || $7, $6 || $8
520 518 link = nil
521 519 if esc.nil?
522 520 if prefix.nil? && sep == 'r'
523 521 if project && (changeset = project.changesets.find_by_revision(identifier))
524 522 link = link_to("r#{identifier}", {:only_path => only_path, :controller => 'repositories', :action => 'revision', :id => project, :rev => changeset.revision},
525 523 :class => 'changeset',
526 524 :title => truncate_single_line(changeset.comments, :length => 100))
527 525 end
528 526 elsif sep == '#'
529 527 oid = identifier.to_i
530 528 case prefix
531 529 when nil
532 530 if issue = Issue.visible.find_by_id(oid, :include => :status)
533 531 link = link_to("##{oid}", {:only_path => only_path, :controller => 'issues', :action => 'show', :id => oid},
534 532 :class => issue.css_classes,
535 533 :title => "#{truncate(issue.subject, :length => 100)} (#{issue.status.name})")
536 534 end
537 535 when 'document'
538 536 if document = Document.find_by_id(oid, :include => [:project], :conditions => Project.visible_by(User.current))
539 537 link = link_to h(document.title), {:only_path => only_path, :controller => 'documents', :action => 'show', :id => document},
540 538 :class => 'document'
541 539 end
542 540 when 'version'
543 541 if version = Version.find_by_id(oid, :include => [:project], :conditions => Project.visible_by(User.current))
544 542 link = link_to h(version.name), {:only_path => only_path, :controller => 'versions', :action => 'show', :id => version},
545 543 :class => 'version'
546 544 end
547 545 when 'message'
548 546 if message = Message.find_by_id(oid, :include => [:parent, {:board => :project}], :conditions => Project.visible_by(User.current))
549 547 link = link_to h(truncate(message.subject, :length => 60)), {:only_path => only_path,
550 548 :controller => 'messages',
551 549 :action => 'show',
552 550 :board_id => message.board,
553 551 :id => message.root,
554 552 :anchor => (message.parent ? "message-#{message.id}" : nil)},
555 553 :class => 'message'
556 554 end
557 555 when 'project'
558 556 if p = Project.visible.find_by_id(oid)
559 557 link = link_to h(p.name), {:only_path => only_path, :controller => 'projects', :action => 'show', :id => p},
560 558 :class => 'project'
561 559 end
562 560 end
563 561 elsif sep == ':'
564 562 # removes the double quotes if any
565 563 name = identifier.gsub(%r{^"(.*)"$}, "\\1")
566 564 case prefix
567 565 when 'document'
568 566 if project && document = project.documents.find_by_title(name)
569 567 link = link_to h(document.title), {:only_path => only_path, :controller => 'documents', :action => 'show', :id => document},
570 568 :class => 'document'
571 569 end
572 570 when 'version'
573 571 if project && version = project.versions.find_by_name(name)
574 572 link = link_to h(version.name), {:only_path => only_path, :controller => 'versions', :action => 'show', :id => version},
575 573 :class => 'version'
576 574 end
577 575 when 'commit'
578 576 if project && (changeset = project.changesets.find(:first, :conditions => ["scmid LIKE ?", "#{name}%"]))
579 577 link = link_to h("#{name}"), {:only_path => only_path, :controller => 'repositories', :action => 'revision', :id => project, :rev => changeset.revision},
580 578 :class => 'changeset',
581 579 :title => truncate_single_line(changeset.comments, :length => 100)
582 580 end
583 581 when 'source', 'export'
584 582 if project && project.repository
585 583 name =~ %r{^[/\\]*(.*?)(@([0-9a-f]+))?(#(L\d+))?$}
586 584 path, rev, anchor = $1, $3, $5
587 585 link = link_to h("#{prefix}:#{name}"), {:controller => 'repositories', :action => 'entry', :id => project,
588 586 :path => to_path_param(path),
589 587 :rev => rev,
590 588 :anchor => anchor,
591 589 :format => (prefix == 'export' ? 'raw' : nil)},
592 590 :class => (prefix == 'export' ? 'source download' : 'source')
593 591 end
594 592 when 'attachment'
593 attachments = options[:attachments] || (obj && obj.respond_to?(:attachments) ? obj.attachments : nil)
595 594 if attachments && attachment = attachments.detect {|a| a.filename == name }
596 595 link = link_to h(attachment.filename), {:only_path => only_path, :controller => 'attachments', :action => 'download', :id => attachment},
597 596 :class => 'attachment'
598 597 end
599 598 when 'project'
600 599 if p = Project.visible.find(:first, :conditions => ["identifier = :s OR LOWER(name) = :s", {:s => name.downcase}])
601 600 link = link_to h(p.name), {:only_path => only_path, :controller => 'projects', :action => 'show', :id => p},
602 601 :class => 'project'
603 602 end
604 603 end
605 604 end
606 605 end
607 606 leading + (link || "#{prefix}#{sep}#{identifier}")
608 607 end
609 608
610 609 text
611 610 end
612 611
613 612 # Same as Rails' simple_format helper without using paragraphs
614 613 def simple_format_without_paragraph(text)
615 614 text.to_s.
616 615 gsub(/\r\n?/, "\n"). # \r\n and \r -> \n
617 616 gsub(/\n\n+/, "<br /><br />"). # 2+ newline -> 2 br
618 617 gsub(/([^\n]\n)(?=[^\n])/, '\1<br />') # 1 newline -> br
619 618 end
620 619
621 620 def lang_options_for_select(blank=true)
622 621 (blank ? [["(auto)", ""]] : []) +
623 622 valid_languages.collect{|lang| [ ll(lang.to_s, :general_lang_name), lang.to_s]}.sort{|x,y| x.last <=> y.last }
624 623 end
625 624
626 625 def label_tag_for(name, option_tags = nil, options = {})
627 626 label_text = l(("field_"+field.to_s.gsub(/\_id$/, "")).to_sym) + (options.delete(:required) ? @template.content_tag("span", " *", :class => "required"): "")
628 627 content_tag("label", label_text)
629 628 end
630 629
631 630 def labelled_tabular_form_for(name, object, options, &proc)
632 631 options[:html] ||= {}
633 632 options[:html][:class] = 'tabular' unless options[:html].has_key?(:class)
634 633 form_for(name, object, options.merge({ :builder => TabularFormBuilder, :lang => current_language}), &proc)
635 634 end
636 635
637 636 def back_url_hidden_field_tag
638 637 back_url = params[:back_url] || request.env['HTTP_REFERER']
639 638 back_url = CGI.unescape(back_url.to_s)
640 639 hidden_field_tag('back_url', CGI.escape(back_url)) unless back_url.blank?
641 640 end
642 641
643 642 def check_all_links(form_name)
644 643 link_to_function(l(:button_check_all), "checkAll('#{form_name}', true)") +
645 644 " | " +
646 645 link_to_function(l(:button_uncheck_all), "checkAll('#{form_name}', false)")
647 646 end
648 647
649 648 def progress_bar(pcts, options={})
650 649 pcts = [pcts, pcts] unless pcts.is_a?(Array)
651 650 pcts = pcts.collect(&:round)
652 651 pcts[1] = pcts[1] - pcts[0]
653 652 pcts << (100 - pcts[1] - pcts[0])
654 653 width = options[:width] || '100px;'
655 654 legend = options[:legend] || ''
656 655 content_tag('table',
657 656 content_tag('tr',
658 657 (pcts[0] > 0 ? content_tag('td', '', :style => "width: #{pcts[0]}%;", :class => 'closed') : '') +
659 658 (pcts[1] > 0 ? content_tag('td', '', :style => "width: #{pcts[1]}%;", :class => 'done') : '') +
660 659 (pcts[2] > 0 ? content_tag('td', '', :style => "width: #{pcts[2]}%;", :class => 'todo') : '')
661 660 ), :class => 'progress', :style => "width: #{width};") +
662 661 content_tag('p', legend, :class => 'pourcent')
663 662 end
664 663
665 664 def context_menu(url)
666 665 unless @context_menu_included
667 666 content_for :header_tags do
668 667 javascript_include_tag('context_menu') +
669 668 stylesheet_link_tag('context_menu')
670 669 end
671 670 @context_menu_included = true
672 671 end
673 672 javascript_tag "new ContextMenu('#{ url_for(url) }')"
674 673 end
675 674
676 675 def context_menu_link(name, url, options={})
677 676 options[:class] ||= ''
678 677 if options.delete(:selected)
679 678 options[:class] << ' icon-checked disabled'
680 679 options[:disabled] = true
681 680 end
682 681 if options.delete(:disabled)
683 682 options.delete(:method)
684 683 options.delete(:confirm)
685 684 options.delete(:onclick)
686 685 options[:class] << ' disabled'
687 686 url = '#'
688 687 end
689 688 link_to name, url, options
690 689 end
691 690
692 691 def calendar_for(field_id)
693 692 include_calendar_headers_tags
694 693 image_tag("calendar.png", {:id => "#{field_id}_trigger",:class => "calendar-trigger"}) +
695 694 javascript_tag("Calendar.setup({inputField : '#{field_id}', ifFormat : '%Y-%m-%d', button : '#{field_id}_trigger' });")
696 695 end
697 696
698 697 def include_calendar_headers_tags
699 698 unless @calendar_headers_tags_included
700 699 @calendar_headers_tags_included = true
701 700 content_for :header_tags do
702 701 start_of_week = case Setting.start_of_week.to_i
703 702 when 1
704 703 'Calendar._FD = 1;' # Monday
705 704 when 7
706 705 'Calendar._FD = 0;' # Sunday
707 706 else
708 707 '' # use language
709 708 end
710 709
711 710 javascript_include_tag('calendar/calendar') +
712 711 javascript_include_tag("calendar/lang/calendar-#{current_language.to_s.downcase}.js") +
713 712 javascript_tag(start_of_week) +
714 713 javascript_include_tag('calendar/calendar-setup') +
715 714 stylesheet_link_tag('calendar')
716 715 end
717 716 end
718 717 end
719 718
720 719 def content_for(name, content = nil, &block)
721 720 @has_content ||= {}
722 721 @has_content[name] = true
723 722 super(name, content, &block)
724 723 end
725 724
726 725 def has_content?(name)
727 726 (@has_content && @has_content[name]) || false
728 727 end
729 728
730 729 # Returns the avatar image tag for the given +user+ if avatars are enabled
731 730 # +user+ can be a User or a string that will be scanned for an email address (eg. 'joe <joe@foo.bar>')
732 731 def avatar(user, options = { })
733 732 if Setting.gravatar_enabled?
734 733 options.merge!({:ssl => Setting.protocol == 'https', :default => Setting.gravatar_default})
735 734 email = nil
736 735 if user.respond_to?(:mail)
737 736 email = user.mail
738 737 elsif user.to_s =~ %r{<(.+?)>}
739 738 email = $1
740 739 end
741 740 return gravatar(email.to_s.downcase, options) unless email.blank? rescue nil
742 741 end
743 742 end
744 743
745 744 private
746 745
747 746 def wiki_helper
748 747 helper = Redmine::WikiFormatting.helper_for(Setting.text_formatting)
749 748 extend helper
750 749 return self
751 750 end
752 751
753 752 def link_to_remote_content_update(text, url_params)
754 753 link_to_remote(text,
755 754 {:url => url_params, :method => :get, :update => 'content', :complete => 'window.scrollTo(0,0)'},
756 755 {:href => url_for(:params => url_params)}
757 756 )
758 757 end
759 758
760 759 end
@@ -1,541 +1,549
1 1 # Redmine - project management software
2 2 # Copyright (C) 2006-2009 Jean-Philippe Lang
3 3 #
4 4 # This program is free software; you can redistribute it and/or
5 5 # modify it under the terms of the GNU General Public License
6 6 # as published by the Free Software Foundation; either version 2
7 7 # of the License, or (at your option) any later version.
8 8 #
9 9 # This program is distributed in the hope that it will be useful,
10 10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 12 # GNU General Public License for more details.
13 13 #
14 14 # You should have received a copy of the GNU General Public License
15 15 # along with this program; if not, write to the Free Software
16 16 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17 17
18 18 require File.dirname(__FILE__) + '/../../test_helper'
19 19
20 20 class ApplicationHelperTest < HelperTestCase
21 21 include ApplicationHelper
22 22 include ActionView::Helpers::TextHelper
23 23 include ActionView::Helpers::DateHelper
24 24
25 25 fixtures :projects, :roles, :enabled_modules, :users,
26 26 :repositories, :changesets,
27 27 :trackers, :issue_statuses, :issues, :versions, :documents,
28 28 :wikis, :wiki_pages, :wiki_contents,
29 29 :boards, :messages,
30 30 :attachments,
31 31 :enumerations
32 32
33 33 def setup
34 34 super
35 35 end
36 36
37 37 def test_auto_links
38 38 to_test = {
39 39 'http://foo.bar' => '<a class="external" href="http://foo.bar">http://foo.bar</a>',
40 40 'http://foo.bar/~user' => '<a class="external" href="http://foo.bar/~user">http://foo.bar/~user</a>',
41 41 'http://foo.bar.' => '<a class="external" href="http://foo.bar">http://foo.bar</a>.',
42 42 'https://foo.bar.' => '<a class="external" href="https://foo.bar">https://foo.bar</a>.',
43 43 'This is a link: http://foo.bar.' => 'This is a link: <a class="external" href="http://foo.bar">http://foo.bar</a>.',
44 44 'A link (eg. http://foo.bar).' => 'A link (eg. <a class="external" href="http://foo.bar">http://foo.bar</a>).',
45 45 'http://foo.bar/foo.bar#foo.bar.' => '<a class="external" href="http://foo.bar/foo.bar#foo.bar">http://foo.bar/foo.bar#foo.bar</a>.',
46 46 'http://www.foo.bar/Test_(foobar)' => '<a class="external" href="http://www.foo.bar/Test_(foobar)">http://www.foo.bar/Test_(foobar)</a>',
47 47 '(see inline link : http://www.foo.bar/Test_(foobar))' => '(see inline link : <a class="external" href="http://www.foo.bar/Test_(foobar)">http://www.foo.bar/Test_(foobar)</a>)',
48 48 '(see inline link : http://www.foo.bar/Test)' => '(see inline link : <a class="external" href="http://www.foo.bar/Test">http://www.foo.bar/Test</a>)',
49 49 '(see inline link : http://www.foo.bar/Test).' => '(see inline link : <a class="external" href="http://www.foo.bar/Test">http://www.foo.bar/Test</a>).',
50 50 '(see "inline link":http://www.foo.bar/Test_(foobar))' => '(see <a href="http://www.foo.bar/Test_(foobar)" class="external">inline link</a>)',
51 51 '(see "inline link":http://www.foo.bar/Test)' => '(see <a href="http://www.foo.bar/Test" class="external">inline link</a>)',
52 52 '(see "inline link":http://www.foo.bar/Test).' => '(see <a href="http://www.foo.bar/Test" class="external">inline link</a>).',
53 53 'www.foo.bar' => '<a class="external" href="http://www.foo.bar">www.foo.bar</a>',
54 54 'http://foo.bar/page?p=1&t=z&s=' => '<a class="external" href="http://foo.bar/page?p=1&#38;t=z&#38;s=">http://foo.bar/page?p=1&#38;t=z&#38;s=</a>',
55 55 'http://foo.bar/page#125' => '<a class="external" href="http://foo.bar/page#125">http://foo.bar/page#125</a>',
56 56 'http://foo@www.bar.com' => '<a class="external" href="http://foo@www.bar.com">http://foo@www.bar.com</a>',
57 57 'http://foo:bar@www.bar.com' => '<a class="external" href="http://foo:bar@www.bar.com">http://foo:bar@www.bar.com</a>',
58 58 'ftp://foo.bar' => '<a class="external" href="ftp://foo.bar">ftp://foo.bar</a>',
59 59 'ftps://foo.bar' => '<a class="external" href="ftps://foo.bar">ftps://foo.bar</a>',
60 60 'sftp://foo.bar' => '<a class="external" href="sftp://foo.bar">sftp://foo.bar</a>',
61 61 # two exclamation marks
62 62 'http://example.net/path!602815048C7B5C20!302.html' => '<a class="external" href="http://example.net/path!602815048C7B5C20!302.html">http://example.net/path!602815048C7B5C20!302.html</a>',
63 63 }
64 64 to_test.each { |text, result| assert_equal "<p>#{result}</p>", textilizable(text) }
65 65 end
66 66
67 67 def test_auto_mailto
68 68 assert_equal '<p><a href="mailto:test@foo.bar" class="email">test@foo.bar</a></p>',
69 69 textilizable('test@foo.bar')
70 70 end
71 71
72 72 def test_inline_images
73 73 to_test = {
74 74 '!http://foo.bar/image.jpg!' => '<img src="http://foo.bar/image.jpg" alt="" />',
75 75 'floating !>http://foo.bar/image.jpg!' => 'floating <div style="float:right"><img src="http://foo.bar/image.jpg" alt="" /></div>',
76 76 'with class !(some-class)http://foo.bar/image.jpg!' => 'with class <img src="http://foo.bar/image.jpg" class="some-class" alt="" />',
77 77 # inline styles should be stripped
78 78 'with style !{width:100px;height100px}http://foo.bar/image.jpg!' => 'with style <img src="http://foo.bar/image.jpg" alt="" />',
79 79 'with title !http://foo.bar/image.jpg(This is a title)!' => 'with title <img src="http://foo.bar/image.jpg" title="This is a title" alt="This is a title" />',
80 80 'with title !http://foo.bar/image.jpg(This is a double-quoted "title")!' => 'with title <img src="http://foo.bar/image.jpg" title="This is a double-quoted &quot;title&quot;" alt="This is a double-quoted &quot;title&quot;" />',
81 81 }
82 82 to_test.each { |text, result| assert_equal "<p>#{result}</p>", textilizable(text) }
83 83 end
84 84
85 85 def test_inline_images_inside_tags
86 86 raw = <<-RAW
87 87 h1. !foo.png! Heading
88 88
89 89 Centered image:
90 90
91 91 p=. !bar.gif!
92 92 RAW
93 93
94 94 assert textilizable(raw).include?('<img src="foo.png" alt="" />')
95 95 assert textilizable(raw).include?('<img src="bar.gif" alt="" />')
96 96 end
97 97
98 98 def test_acronyms
99 99 to_test = {
100 100 'this is an acronym: GPL(General Public License)' => 'this is an acronym: <acronym title="General Public License">GPL</acronym>',
101 101 'GPL(This is a double-quoted "title")' => '<acronym title="This is a double-quoted &quot;title&quot;">GPL</acronym>',
102 102 }
103 103 to_test.each { |text, result| assert_equal "<p>#{result}</p>", textilizable(text) }
104 104
105 105 end
106 106
107 107 def test_attached_images
108 108 to_test = {
109 109 'Inline image: !logo.gif!' => 'Inline image: <img src="/attachments/download/3" title="This is a logo" alt="This is a logo" />',
110 110 'Inline image: !logo.GIF!' => 'Inline image: <img src="/attachments/download/3" title="This is a logo" alt="This is a logo" />',
111 111 'No match: !ogo.gif!' => 'No match: <img src="ogo.gif" alt="" />',
112 112 'No match: !ogo.GIF!' => 'No match: <img src="ogo.GIF" alt="" />',
113 113 # link image
114 114 '!logo.gif!:http://foo.bar/' => '<a href="http://foo.bar/"><img src="/attachments/download/3" title="This is a logo" alt="This is a logo" /></a>',
115 115 }
116 116 attachments = Attachment.find(:all)
117 117 to_test.each { |text, result| assert_equal "<p>#{result}</p>", textilizable(text, :attachments => attachments) }
118 118 end
119 119
120 120 def test_textile_external_links
121 121 to_test = {
122 122 'This is a "link":http://foo.bar' => 'This is a <a href="http://foo.bar" class="external">link</a>',
123 123 'This is an intern "link":/foo/bar' => 'This is an intern <a href="/foo/bar">link</a>',
124 124 '"link (Link title)":http://foo.bar' => '<a href="http://foo.bar" title="Link title" class="external">link</a>',
125 125 '"link (Link title with "double-quotes")":http://foo.bar' => '<a href="http://foo.bar" title="Link title with &quot;double-quotes&quot;" class="external">link</a>',
126 126 "This is not a \"Link\":\n\nAnother paragraph" => "This is not a \"Link\":</p>\n\n\n\t<p>Another paragraph",
127 127 # no multiline link text
128 128 "This is a double quote \"on the first line\nand another on a second line\":test" => "This is a double quote \"on the first line<br />and another on a second line\":test",
129 129 # mailto link
130 130 "\"system administrator\":mailto:sysadmin@example.com?subject=redmine%20permissions" => "<a href=\"mailto:sysadmin@example.com?subject=redmine%20permissions\">system administrator</a>",
131 131 # two exclamation marks
132 132 '"a link":http://example.net/path!602815048C7B5C20!302.html' => '<a href="http://example.net/path!602815048C7B5C20!302.html" class="external">a link</a>',
133 133 }
134 134 to_test.each { |text, result| assert_equal "<p>#{result}</p>", textilizable(text) }
135 135 end
136 136
137 137 def test_redmine_links
138 138 issue_link = link_to('#3', {:controller => 'issues', :action => 'show', :id => 3},
139 139 :class => 'issue status-1 priority-1 overdue', :title => 'Error 281 when updating a recipe (New)')
140 140
141 141 changeset_link = link_to('r1', {:controller => 'repositories', :action => 'revision', :id => 'ecookbook', :rev => 1},
142 142 :class => 'changeset', :title => 'My very first commit')
143 143 changeset_link2 = link_to('r2', {:controller => 'repositories', :action => 'revision', :id => 'ecookbook', :rev => 2},
144 144 :class => 'changeset', :title => 'This commit fixes #1, #2 and references #1 & #3')
145 145
146 146 document_link = link_to('Test document', {:controller => 'documents', :action => 'show', :id => 1},
147 147 :class => 'document')
148 148
149 149 version_link = link_to('1.0', {:controller => 'versions', :action => 'show', :id => 2},
150 150 :class => 'version')
151 151
152 152 message_url = {:controller => 'messages', :action => 'show', :board_id => 1, :id => 4}
153 153
154 154 project_url = {:controller => 'projects', :action => 'show', :id => 'subproject1'}
155 155
156 156 source_url = {:controller => 'repositories', :action => 'entry', :id => 'ecookbook', :path => ['some', 'file']}
157 157 source_url_with_ext = {:controller => 'repositories', :action => 'entry', :id => 'ecookbook', :path => ['some', 'file.ext']}
158 158
159 159 to_test = {
160 160 # tickets
161 161 '#3, #3 and #3.' => "#{issue_link}, #{issue_link} and #{issue_link}.",
162 162 # changesets
163 163 'r1' => changeset_link,
164 164 'r1.' => "#{changeset_link}.",
165 165 'r1, r2' => "#{changeset_link}, #{changeset_link2}",
166 166 'r1,r2' => "#{changeset_link},#{changeset_link2}",
167 167 # documents
168 168 'document#1' => document_link,
169 169 'document:"Test document"' => document_link,
170 170 # versions
171 171 'version#2' => version_link,
172 172 'version:1.0' => version_link,
173 173 'version:"1.0"' => version_link,
174 174 # source
175 175 'source:/some/file' => link_to('source:/some/file', source_url, :class => 'source'),
176 176 'source:/some/file.' => link_to('source:/some/file', source_url, :class => 'source') + ".",
177 177 'source:/some/file.ext.' => link_to('source:/some/file.ext', source_url_with_ext, :class => 'source') + ".",
178 178 'source:/some/file. ' => link_to('source:/some/file', source_url, :class => 'source') + ".",
179 179 'source:/some/file.ext. ' => link_to('source:/some/file.ext', source_url_with_ext, :class => 'source') + ".",
180 180 'source:/some/file, ' => link_to('source:/some/file', source_url, :class => 'source') + ",",
181 181 'source:/some/file@52' => link_to('source:/some/file@52', source_url.merge(:rev => 52), :class => 'source'),
182 182 'source:/some/file.ext@52' => link_to('source:/some/file.ext@52', source_url_with_ext.merge(:rev => 52), :class => 'source'),
183 183 'source:/some/file#L110' => link_to('source:/some/file#L110', source_url.merge(:anchor => 'L110'), :class => 'source'),
184 184 'source:/some/file.ext#L110' => link_to('source:/some/file.ext#L110', source_url_with_ext.merge(:anchor => 'L110'), :class => 'source'),
185 185 'source:/some/file@52#L110' => link_to('source:/some/file@52#L110', source_url.merge(:rev => 52, :anchor => 'L110'), :class => 'source'),
186 186 'export:/some/file' => link_to('export:/some/file', source_url.merge(:format => 'raw'), :class => 'source download'),
187 187 # message
188 188 'message#4' => link_to('Post 2', message_url, :class => 'message'),
189 189 'message#5' => link_to('RE: post 2', message_url.merge(:anchor => 'message-5'), :class => 'message'),
190 190 # project
191 191 'project#3' => link_to('eCookbook Subproject 1', project_url, :class => 'project'),
192 192 'project:subproject1' => link_to('eCookbook Subproject 1', project_url, :class => 'project'),
193 193 'project:"eCookbook subProject 1"' => link_to('eCookbook Subproject 1', project_url, :class => 'project'),
194 194 # escaping
195 195 '!#3.' => '#3.',
196 196 '!r1' => 'r1',
197 197 '!document#1' => 'document#1',
198 198 '!document:"Test document"' => 'document:"Test document"',
199 199 '!version#2' => 'version#2',
200 200 '!version:1.0' => 'version:1.0',
201 201 '!version:"1.0"' => 'version:"1.0"',
202 202 '!source:/some/file' => 'source:/some/file',
203 203 # not found
204 204 '#0123456789' => '#0123456789',
205 205 # invalid expressions
206 206 'source:' => 'source:',
207 207 # url hash
208 208 "http://foo.bar/FAQ#3" => '<a class="external" href="http://foo.bar/FAQ#3">http://foo.bar/FAQ#3</a>',
209 209 }
210 210 @project = Project.find(1)
211 211 to_test.each { |text, result| assert_equal "<p>#{result}</p>", textilizable(text), "#{text} failed" }
212 212 end
213 213
214 def test_attachment_links
215 attachment_link = link_to('error281.txt', {:controller => 'attachments', :action => 'download', :id => '1'}, :class => 'attachment')
216 to_test = {
217 'attachment:error281.txt' => attachment_link
218 }
219 to_test.each { |text, result| assert_equal "<p>#{result}</p>", textilizable(text, :attachments => Issue.find(3).attachments), "#{text} failed" }
220 end
221
214 222 def test_wiki_links
215 223 to_test = {
216 224 '[[CookBook documentation]]' => '<a href="/projects/ecookbook/wiki/CookBook_documentation" class="wiki-page">CookBook documentation</a>',
217 225 '[[Another page|Page]]' => '<a href="/projects/ecookbook/wiki/Another_page" class="wiki-page">Page</a>',
218 226 # link with anchor
219 227 '[[CookBook documentation#One-section]]' => '<a href="/projects/ecookbook/wiki/CookBook_documentation#One-section" class="wiki-page">CookBook documentation</a>',
220 228 '[[Another page#anchor|Page]]' => '<a href="/projects/ecookbook/wiki/Another_page#anchor" class="wiki-page">Page</a>',
221 229 # page that doesn't exist
222 230 '[[Unknown page]]' => '<a href="/projects/ecookbook/wiki/Unknown_page" class="wiki-page new">Unknown page</a>',
223 231 '[[Unknown page|404]]' => '<a href="/projects/ecookbook/wiki/Unknown_page" class="wiki-page new">404</a>',
224 232 # link to another project wiki
225 233 '[[onlinestore:]]' => '<a href="/projects/onlinestore/wiki/" class="wiki-page">onlinestore</a>',
226 234 '[[onlinestore:|Wiki]]' => '<a href="/projects/onlinestore/wiki/" class="wiki-page">Wiki</a>',
227 235 '[[onlinestore:Start page]]' => '<a href="/projects/onlinestore/wiki/Start_page" class="wiki-page">Start page</a>',
228 236 '[[onlinestore:Start page|Text]]' => '<a href="/projects/onlinestore/wiki/Start_page" class="wiki-page">Text</a>',
229 237 '[[onlinestore:Unknown page]]' => '<a href="/projects/onlinestore/wiki/Unknown_page" class="wiki-page new">Unknown page</a>',
230 238 # striked through link
231 239 '-[[Another page|Page]]-' => '<del><a href="/projects/ecookbook/wiki/Another_page" class="wiki-page">Page</a></del>',
232 240 '-[[Another page|Page]] link-' => '<del><a href="/projects/ecookbook/wiki/Another_page" class="wiki-page">Page</a> link</del>',
233 241 # escaping
234 242 '![[Another page|Page]]' => '[[Another page|Page]]',
235 243 # project does not exist
236 244 '[[unknowproject:Start]]' => '[[unknowproject:Start]]',
237 245 '[[unknowproject:Start|Page title]]' => '[[unknowproject:Start|Page title]]',
238 246 }
239 247 @project = Project.find(1)
240 248 to_test.each { |text, result| assert_equal "<p>#{result}</p>", textilizable(text) }
241 249 end
242 250
243 251 def test_html_tags
244 252 to_test = {
245 253 "<div>content</div>" => "<p>&lt;div&gt;content&lt;/div&gt;</p>",
246 254 "<div class=\"bold\">content</div>" => "<p>&lt;div class=\"bold\"&gt;content&lt;/div&gt;</p>",
247 255 "<script>some script;</script>" => "<p>&lt;script&gt;some script;&lt;/script&gt;</p>",
248 256 # do not escape pre/code tags
249 257 "<pre>\nline 1\nline2</pre>" => "<pre>\nline 1\nline2</pre>",
250 258 "<pre><code>\nline 1\nline2</code></pre>" => "<pre><code>\nline 1\nline2</code></pre>",
251 259 "<pre><div>content</div></pre>" => "<pre>&lt;div&gt;content&lt;/div&gt;</pre>",
252 260 "HTML comment: <!-- no comments -->" => "<p>HTML comment: &lt;!-- no comments --&gt;</p>",
253 261 "<!-- opening comment" => "<p>&lt;!-- opening comment</p>",
254 262 # remove attributes except class
255 263 "<pre class='foo'>some text</pre>" => "<pre class='foo'>some text</pre>",
256 264 "<pre onmouseover='alert(1)'>some text</pre>" => "<pre>some text</pre>",
257 265 }
258 266 to_test.each { |text, result| assert_equal result, textilizable(text) }
259 267 end
260 268
261 269 def test_allowed_html_tags
262 270 to_test = {
263 271 "<pre>preformatted text</pre>" => "<pre>preformatted text</pre>",
264 272 "<notextile>no *textile* formatting</notextile>" => "no *textile* formatting",
265 273 "<notextile>this is <tag>a tag</tag></notextile>" => "this is &lt;tag&gt;a tag&lt;/tag&gt;"
266 274 }
267 275 to_test.each { |text, result| assert_equal result, textilizable(text) }
268 276 end
269 277
270 278 def test_pre_tags
271 279 raw = <<-RAW
272 280 Before
273 281
274 282 <pre>
275 283 <prepared-statement-cache-size>32</prepared-statement-cache-size>
276 284 </pre>
277 285
278 286 After
279 287 RAW
280 288
281 289 expected = <<-EXPECTED
282 290 <p>Before</p>
283 291 <pre>
284 292 &lt;prepared-statement-cache-size&gt;32&lt;/prepared-statement-cache-size&gt;
285 293 </pre>
286 294 <p>After</p>
287 295 EXPECTED
288 296
289 297 assert_equal expected.gsub(%r{[\r\n\t]}, ''), textilizable(raw).gsub(%r{[\r\n\t]}, '')
290 298 end
291 299
292 300 def test_syntax_highlight
293 301 raw = <<-RAW
294 302 <pre><code class="ruby">
295 303 # Some ruby code here
296 304 </pre></code>
297 305 RAW
298 306
299 307 expected = <<-EXPECTED
300 308 <pre><code class="ruby CodeRay"><span class="no">1</span> <span class="c"># Some ruby code here</span>
301 309 </pre></code>
302 310 EXPECTED
303 311
304 312 assert_equal expected.gsub(%r{[\r\n\t]}, ''), textilizable(raw).gsub(%r{[\r\n\t]}, '')
305 313 end
306 314
307 315 def test_wiki_links_in_tables
308 316 to_test = {"|[[Page|Link title]]|[[Other Page|Other title]]|\n|Cell 21|[[Last page]]|" =>
309 317 '<tr><td><a href="/projects/ecookbook/wiki/Page" class="wiki-page new">Link title</a></td>' +
310 318 '<td><a href="/projects/ecookbook/wiki/Other_Page" class="wiki-page new">Other title</a></td>' +
311 319 '</tr><tr><td>Cell 21</td><td><a href="/projects/ecookbook/wiki/Last_page" class="wiki-page new">Last page</a></td></tr>'
312 320 }
313 321 @project = Project.find(1)
314 322 to_test.each { |text, result| assert_equal "<table>#{result}</table>", textilizable(text).gsub(/[\t\n]/, '') }
315 323 end
316 324
317 325 def test_text_formatting
318 326 to_test = {'*_+bold, italic and underline+_*' => '<strong><em><ins>bold, italic and underline</ins></em></strong>',
319 327 '(_text within parentheses_)' => '(<em>text within parentheses</em>)',
320 328 'a *Humane Web* Text Generator' => 'a <strong>Humane Web</strong> Text Generator',
321 329 'a H *umane* W *eb* T *ext* G *enerator*' => 'a H <strong>umane</strong> W <strong>eb</strong> T <strong>ext</strong> G <strong>enerator</strong>',
322 330 'a *H* umane *W* eb *T* ext *G* enerator' => 'a <strong>H</strong> umane <strong>W</strong> eb <strong>T</strong> ext <strong>G</strong> enerator',
323 331 }
324 332 to_test.each { |text, result| assert_equal "<p>#{result}</p>", textilizable(text) }
325 333 end
326 334
327 335 def test_wiki_horizontal_rule
328 336 assert_equal '<hr />', textilizable('---')
329 337 assert_equal '<p>Dashes: ---</p>', textilizable('Dashes: ---')
330 338 end
331 339
332 340 def test_acronym
333 341 assert_equal '<p>This is an acronym: <acronym title="American Civil Liberties Union">ACLU</acronym>.</p>',
334 342 textilizable('This is an acronym: ACLU(American Civil Liberties Union).')
335 343 end
336 344
337 345 def test_footnotes
338 346 raw = <<-RAW
339 347 This is some text[1].
340 348
341 349 fn1. This is the foot note
342 350 RAW
343 351
344 352 expected = <<-EXPECTED
345 353 <p>This is some text<sup><a href=\"#fn1\">1</a></sup>.</p>
346 354 <p id="fn1" class="footnote"><sup>1</sup> This is the foot note</p>
347 355 EXPECTED
348 356
349 357 assert_equal expected.gsub(%r{[\r\n\t]}, ''), textilizable(raw).gsub(%r{[\r\n\t]}, '')
350 358 end
351 359
352 360 def test_table_of_content
353 361 raw = <<-RAW
354 362 {{toc}}
355 363
356 364 h1. Title
357 365
358 366 Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Maecenas sed libero.
359 367
360 368 h2. Subtitle with a [[Wiki]] link
361 369
362 370 Nullam commodo metus accumsan nulla. Curabitur lobortis dui id dolor.
363 371
364 372 h2. Subtitle with [[Wiki|another Wiki]] link
365 373
366 374 h2. Subtitle with %{color:red}red text%
367 375
368 376 h1. Another title
369 377
370 378 RAW
371 379
372 380 expected = '<ul class="toc">' +
373 381 '<li class="heading1"><a href="#Title">Title</a></li>' +
374 382 '<li class="heading2"><a href="#Subtitle-with-a-Wiki-link">Subtitle with a Wiki link</a></li>' +
375 383 '<li class="heading2"><a href="#Subtitle-with-another-Wiki-link">Subtitle with another Wiki link</a></li>' +
376 384 '<li class="heading2"><a href="#Subtitle-with-red-text">Subtitle with red text</a></li>' +
377 385 '<li class="heading1"><a href="#Another-title">Another title</a></li>' +
378 386 '</ul>'
379 387
380 388 assert textilizable(raw).gsub("\n", "").include?(expected)
381 389 end
382 390
383 391 def test_blockquote
384 392 # orig raw text
385 393 raw = <<-RAW
386 394 John said:
387 395 > Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Maecenas sed libero.
388 396 > Nullam commodo metus accumsan nulla. Curabitur lobortis dui id dolor.
389 397 > * Donec odio lorem,
390 398 > * sagittis ac,
391 399 > * malesuada in,
392 400 > * adipiscing eu, dolor.
393 401 >
394 402 > >Nulla varius pulvinar diam. Proin id arcu id lorem scelerisque condimentum. Proin vehicula turpis vitae lacus.
395 403 > Proin a tellus. Nam vel neque.
396 404
397 405 He's right.
398 406 RAW
399 407
400 408 # expected html
401 409 expected = <<-EXPECTED
402 410 <p>John said:</p>
403 411 <blockquote>
404 412 Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Maecenas sed libero.
405 413 Nullam commodo metus accumsan nulla. Curabitur lobortis dui id dolor.
406 414 <ul>
407 415 <li>Donec odio lorem,</li>
408 416 <li>sagittis ac,</li>
409 417 <li>malesuada in,</li>
410 418 <li>adipiscing eu, dolor.</li>
411 419 </ul>
412 420 <blockquote>
413 421 <p>Nulla varius pulvinar diam. Proin id arcu id lorem scelerisque condimentum. Proin vehicula turpis vitae lacus.</p>
414 422 </blockquote>
415 423 <p>Proin a tellus. Nam vel neque.</p>
416 424 </blockquote>
417 425 <p>He's right.</p>
418 426 EXPECTED
419 427
420 428 assert_equal expected.gsub(%r{\s+}, ''), textilizable(raw).gsub(%r{\s+}, '')
421 429 end
422 430
423 431 def test_table
424 432 raw = <<-RAW
425 433 This is a table with empty cells:
426 434
427 435 |cell11|cell12||
428 436 |cell21||cell23|
429 437 |cell31|cell32|cell33|
430 438 RAW
431 439
432 440 expected = <<-EXPECTED
433 441 <p>This is a table with empty cells:</p>
434 442
435 443 <table>
436 444 <tr><td>cell11</td><td>cell12</td><td></td></tr>
437 445 <tr><td>cell21</td><td></td><td>cell23</td></tr>
438 446 <tr><td>cell31</td><td>cell32</td><td>cell33</td></tr>
439 447 </table>
440 448 EXPECTED
441 449
442 450 assert_equal expected.gsub(%r{\s+}, ''), textilizable(raw).gsub(%r{\s+}, '')
443 451 end
444 452
445 453 def test_table_with_line_breaks
446 454 raw = <<-RAW
447 455 This is a table with line breaks:
448 456
449 457 |cell11
450 458 continued|cell12||
451 459 |-cell21-||cell23
452 460 cell23 line2
453 461 cell23 *line3*|
454 462 |cell31|cell32
455 463 cell32 line2|cell33|
456 464
457 465 RAW
458 466
459 467 expected = <<-EXPECTED
460 468 <p>This is a table with line breaks:</p>
461 469
462 470 <table>
463 471 <tr>
464 472 <td>cell11<br />continued</td>
465 473 <td>cell12</td>
466 474 <td></td>
467 475 </tr>
468 476 <tr>
469 477 <td><del>cell21</del></td>
470 478 <td></td>
471 479 <td>cell23<br/>cell23 line2<br/>cell23 <strong>line3</strong></td>
472 480 </tr>
473 481 <tr>
474 482 <td>cell31</td>
475 483 <td>cell32<br/>cell32 line2</td>
476 484 <td>cell33</td>
477 485 </tr>
478 486 </table>
479 487 EXPECTED
480 488
481 489 assert_equal expected.gsub(%r{\s+}, ''), textilizable(raw).gsub(%r{\s+}, '')
482 490 end
483 491
484 492 def test_textile_should_not_mangle_brackets
485 493 assert_equal '<p>[msg1][msg2]</p>', textilizable('[msg1][msg2]')
486 494 end
487 495
488 496 def test_default_formatter
489 497 Setting.text_formatting = 'unknown'
490 498 text = 'a *link*: http://www.example.net/'
491 499 assert_equal '<p>a *link*: <a href="http://www.example.net/">http://www.example.net/</a></p>', textilizable(text)
492 500 Setting.text_formatting = 'textile'
493 501 end
494 502
495 503 def test_due_date_distance_in_words
496 504 to_test = { Date.today => 'Due in 0 days',
497 505 Date.today + 1 => 'Due in 1 day',
498 506 Date.today + 100 => 'Due in about 3 months',
499 507 Date.today + 20000 => 'Due in over 54 years',
500 508 Date.today - 1 => '1 day late',
501 509 Date.today - 100 => 'about 3 months late',
502 510 Date.today - 20000 => 'over 54 years late',
503 511 }
504 512 to_test.each do |date, expected|
505 513 assert_equal expected, due_date_distance_in_words(date)
506 514 end
507 515 end
508 516
509 517 def test_avatar
510 518 # turn on avatars
511 519 Setting.gravatar_enabled = '1'
512 520 assert avatar(User.find_by_mail('jsmith@somenet.foo')).include?(Digest::MD5.hexdigest('jsmith@somenet.foo'))
513 521 assert avatar('jsmith <jsmith@somenet.foo>').include?(Digest::MD5.hexdigest('jsmith@somenet.foo'))
514 522 assert_nil avatar('jsmith')
515 523 assert_nil avatar(nil)
516 524
517 525 # turn off avatars
518 526 Setting.gravatar_enabled = '0'
519 527 assert_nil avatar(User.find_by_mail('jsmith@somenet.foo'))
520 528 end
521 529
522 530 def test_link_to_user
523 531 user = User.find(2)
524 532 t = link_to_user(user)
525 533 assert_equal "<a href=\"/users/2\">#{ user.name }</a>", t
526 534 end
527 535
528 536 def test_link_to_user_should_not_link_to_locked_user
529 537 user = User.find(5)
530 538 assert user.locked?
531 539 t = link_to_user(user)
532 540 assert_equal user.name, t
533 541 end
534 542
535 543 def test_link_to_user_should_not_link_to_anonymous
536 544 user = User.anonymous
537 545 assert user.anonymous?
538 546 t = link_to_user(user)
539 547 assert_equal ::I18n.t(:label_user_anonymous), t
540 548 end
541 549 end
General Comments 0
You need to be logged in to leave comments. Login now