##// END OF EJS Templates
Fixed: Pound (#) followed by number with leading zero (0) removes leading zero when rendered in wiki (#4872)....
Jean-Philippe Lang -
r3337:d18fba4ffe90
parent child
Show More
@@ -1,744 +1,744
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, :selected => ((project == options[:selected]) ? 'selected' : nil)}
209 209 tag_options.merge!(yield(project)) if block_given?
210 210 s << content_tag('option', name_prefix + h(project), tag_options)
211 211 end
212 212 s
213 213 end
214 214
215 215 # Yields the given block for each project with its level in the tree
216 216 def project_tree(projects, &block)
217 217 ancestors = []
218 218 projects.sort_by(&:lft).each do |project|
219 219 while (ancestors.any? && !project.is_descendant_of?(ancestors.last))
220 220 ancestors.pop
221 221 end
222 222 yield project, ancestors.size
223 223 ancestors << project
224 224 end
225 225 end
226 226
227 227 def project_nested_ul(projects, &block)
228 228 s = ''
229 229 if projects.any?
230 230 ancestors = []
231 231 projects.sort_by(&:lft).each do |project|
232 232 if (ancestors.empty? || project.is_descendant_of?(ancestors.last))
233 233 s << "<ul>\n"
234 234 else
235 235 ancestors.pop
236 236 s << "</li>"
237 237 while (ancestors.any? && !project.is_descendant_of?(ancestors.last))
238 238 ancestors.pop
239 239 s << "</ul></li>\n"
240 240 end
241 241 end
242 242 s << "<li>"
243 243 s << yield(project).to_s
244 244 ancestors << project
245 245 end
246 246 s << ("</li></ul>\n" * ancestors.size)
247 247 end
248 248 s
249 249 end
250 250
251 251 def principals_check_box_tags(name, principals)
252 252 s = ''
253 253 principals.sort.each do |principal|
254 254 s << "<label>#{ check_box_tag name, principal.id, false } #{h principal}</label>\n"
255 255 end
256 256 s
257 257 end
258 258
259 259 # Truncates and returns the string as a single line
260 260 def truncate_single_line(string, *args)
261 261 truncate(string.to_s, *args).gsub(%r{[\r\n]+}m, ' ')
262 262 end
263 263
264 264 def html_hours(text)
265 265 text.gsub(%r{(\d+)\.(\d+)}, '<span class="hours hours-int">\1</span><span class="hours hours-dec">.\2</span>')
266 266 end
267 267
268 268 def authoring(created, author, options={})
269 269 l(options[:label] || :label_added_time_by, :author => link_to_user(author), :age => time_tag(created))
270 270 end
271 271
272 272 def time_tag(time)
273 273 text = distance_of_time_in_words(Time.now, time)
274 274 if @project
275 275 link_to(text, {:controller => 'projects', :action => 'activity', :id => @project, :from => time.to_date}, :title => format_time(time))
276 276 else
277 277 content_tag('acronym', text, :title => format_time(time))
278 278 end
279 279 end
280 280
281 281 def syntax_highlight(name, content)
282 282 type = CodeRay::FileType[name]
283 283 type ? CodeRay.scan(content, type).html : h(content)
284 284 end
285 285
286 286 def to_path_param(path)
287 287 path.to_s.split(%r{[/\\]}).select {|p| !p.blank?}
288 288 end
289 289
290 290 def pagination_links_full(paginator, count=nil, options={})
291 291 page_param = options.delete(:page_param) || :page
292 292 per_page_links = options.delete(:per_page_links)
293 293 url_param = params.dup
294 294 # don't reuse query params if filters are present
295 295 url_param.merge!(:fields => nil, :values => nil, :operators => nil) if url_param.delete(:set_filter)
296 296
297 297 html = ''
298 298 if paginator.current.previous
299 299 html << link_to_remote_content_update('&#171; ' + l(:label_previous), url_param.merge(page_param => paginator.current.previous)) + ' '
300 300 end
301 301
302 302 html << (pagination_links_each(paginator, options) do |n|
303 303 link_to_remote_content_update(n.to_s, url_param.merge(page_param => n))
304 304 end || '')
305 305
306 306 if paginator.current.next
307 307 html << ' ' + link_to_remote_content_update((l(:label_next) + ' &#187;'), url_param.merge(page_param => paginator.current.next))
308 308 end
309 309
310 310 unless count.nil?
311 311 html << " (#{paginator.current.first_item}-#{paginator.current.last_item}/#{count})"
312 312 if per_page_links != false && links = per_page_links(paginator.items_per_page)
313 313 html << " | #{links}"
314 314 end
315 315 end
316 316
317 317 html
318 318 end
319 319
320 320 def per_page_links(selected=nil)
321 321 url_param = params.dup
322 322 url_param.clear if url_param.has_key?(:set_filter)
323 323
324 324 links = Setting.per_page_options_array.collect do |n|
325 325 n == selected ? n : link_to_remote(n, {:update => "content",
326 326 :url => params.dup.merge(:per_page => n),
327 327 :method => :get},
328 328 {:href => url_for(url_param.merge(:per_page => n))})
329 329 end
330 330 links.size > 1 ? l(:label_display_per_page, links.join(', ')) : nil
331 331 end
332 332
333 333 def reorder_links(name, url)
334 334 link_to(image_tag('2uparrow.png', :alt => l(:label_sort_highest)), url.merge({"#{name}[move_to]" => 'highest'}), :method => :post, :title => l(:label_sort_highest)) +
335 335 link_to(image_tag('1uparrow.png', :alt => l(:label_sort_higher)), url.merge({"#{name}[move_to]" => 'higher'}), :method => :post, :title => l(:label_sort_higher)) +
336 336 link_to(image_tag('1downarrow.png', :alt => l(:label_sort_lower)), url.merge({"#{name}[move_to]" => 'lower'}), :method => :post, :title => l(:label_sort_lower)) +
337 337 link_to(image_tag('2downarrow.png', :alt => l(:label_sort_lowest)), url.merge({"#{name}[move_to]" => 'lowest'}), :method => :post, :title => l(:label_sort_lowest))
338 338 end
339 339
340 340 def breadcrumb(*args)
341 341 elements = args.flatten
342 342 elements.any? ? content_tag('p', args.join(' &#187; ') + ' &#187; ', :class => 'breadcrumb') : nil
343 343 end
344 344
345 345 def other_formats_links(&block)
346 346 concat('<p class="other-formats">' + l(:label_export_to))
347 347 yield Redmine::Views::OtherFormatsBuilder.new(self)
348 348 concat('</p>')
349 349 end
350 350
351 351 def page_header_title
352 352 if @project.nil? || @project.new_record?
353 353 h(Setting.app_title)
354 354 else
355 355 b = []
356 356 ancestors = (@project.root? ? [] : @project.ancestors.visible)
357 357 if ancestors.any?
358 358 root = ancestors.shift
359 359 b << link_to(h(root), {:controller => 'projects', :action => 'show', :id => root, :jump => current_menu_item}, :class => 'root')
360 360 if ancestors.size > 2
361 361 b << '&#8230;'
362 362 ancestors = ancestors[-2, 2]
363 363 end
364 364 b += ancestors.collect {|p| link_to(h(p), {:controller => 'projects', :action => 'show', :id => p, :jump => current_menu_item}, :class => 'ancestor') }
365 365 end
366 366 b << h(@project)
367 367 b.join(' &#187; ')
368 368 end
369 369 end
370 370
371 371 def html_title(*args)
372 372 if args.empty?
373 373 title = []
374 374 title << @project.name if @project
375 375 title += @html_title if @html_title
376 376 title << Setting.app_title
377 377 title.select {|t| !t.blank? }.join(' - ')
378 378 else
379 379 @html_title ||= []
380 380 @html_title += args
381 381 end
382 382 end
383 383
384 384 def accesskey(s)
385 385 Redmine::AccessKeys.key_for s
386 386 end
387 387
388 388 # Formats text according to system settings.
389 389 # 2 ways to call this method:
390 390 # * with a String: textilizable(text, options)
391 391 # * with an object and one of its attribute: textilizable(issue, :description, options)
392 392 def textilizable(*args)
393 393 options = args.last.is_a?(Hash) ? args.pop : {}
394 394 case args.size
395 395 when 1
396 396 obj = options[:object]
397 397 text = args.shift
398 398 when 2
399 399 obj = args.shift
400 400 attr = args.shift
401 401 text = obj.send(attr).to_s
402 402 else
403 403 raise ArgumentError, 'invalid arguments to textilizable'
404 404 end
405 405 return '' if text.blank?
406 406
407 407 text = Redmine::WikiFormatting.to_html(Setting.text_formatting, text, :object => obj, :attribute => attr) { |macro, args| exec_macro(macro, obj, args) }
408 408
409 409 only_path = options.delete(:only_path) == false ? false : true
410 410
411 411 # when using an image link, try to use an attachment, if possible
412 412 attachments = options[:attachments] || (obj && obj.respond_to?(:attachments) ? obj.attachments : nil)
413 413
414 414 if attachments
415 415 attachments = attachments.sort_by(&:created_on).reverse
416 416 text.gsub!(/src="([^\/"]+\.(bmp|gif|jpg|jpeg|png))"(\s+alt="([^"]*)")?/i) do |m|
417 417 filename, ext, alt, alttext = $1.downcase, $2, $3, $4
418 418
419 419 # search for the picture in attachments
420 420 if found = attachments.detect { |att| att.filename.downcase == filename }
421 421 image_url = url_for :only_path => only_path, :controller => 'attachments', :action => 'download', :id => found
422 422 desc = found.description.to_s.gsub('"', '')
423 423 if !desc.blank? && alttext.blank?
424 424 alt = " title=\"#{desc}\" alt=\"#{desc}\""
425 425 end
426 426 "src=\"#{image_url}\"#{alt}"
427 427 else
428 428 m
429 429 end
430 430 end
431 431 end
432 432
433 433
434 434 # different methods for formatting wiki links
435 435 case options[:wiki_links]
436 436 when :local
437 437 # used for local links to html files
438 438 format_wiki_link = Proc.new {|project, title, anchor| "#{title}.html" }
439 439 when :anchor
440 440 # used for single-file wiki export
441 441 format_wiki_link = Proc.new {|project, title, anchor| "##{title}" }
442 442 else
443 443 format_wiki_link = Proc.new {|project, title, anchor| url_for(:only_path => only_path, :controller => 'wiki', :action => 'index', :id => project, :page => title, :anchor => anchor) }
444 444 end
445 445
446 446 project = options[:project] || @project || (obj && obj.respond_to?(:project) ? obj.project : nil)
447 447
448 448 # Wiki links
449 449 #
450 450 # Examples:
451 451 # [[mypage]]
452 452 # [[mypage|mytext]]
453 453 # wiki links can refer other project wikis, using project name or identifier:
454 454 # [[project:]] -> wiki starting page
455 455 # [[project:|mytext]]
456 456 # [[project:mypage]]
457 457 # [[project:mypage|mytext]]
458 458 text = text.gsub(/(!)?(\[\[([^\]\n\|]+)(\|([^\]\n\|]+))?\]\])/) do |m|
459 459 link_project = project
460 460 esc, all, page, title = $1, $2, $3, $5
461 461 if esc.nil?
462 462 if page =~ /^([^\:]+)\:(.*)$/
463 463 link_project = Project.find_by_name($1) || Project.find_by_identifier($1)
464 464 page = $2
465 465 title ||= $1 if page.blank?
466 466 end
467 467
468 468 if link_project && link_project.wiki
469 469 # extract anchor
470 470 anchor = nil
471 471 if page =~ /^(.+?)\#(.+)$/
472 472 page, anchor = $1, $2
473 473 end
474 474 # check if page exists
475 475 wiki_page = link_project.wiki.find_page(page)
476 476 link_to((title || page), format_wiki_link.call(link_project, Wiki.titleize(page), anchor),
477 477 :class => ('wiki-page' + (wiki_page ? '' : ' new')))
478 478 else
479 479 # project or wiki doesn't exist
480 480 all
481 481 end
482 482 else
483 483 all
484 484 end
485 485 end
486 486
487 487 # Redmine links
488 488 #
489 489 # Examples:
490 490 # Issues:
491 491 # #52 -> Link to issue #52
492 492 # Changesets:
493 493 # r52 -> Link to revision 52
494 494 # commit:a85130f -> Link to scmid starting with a85130f
495 495 # Documents:
496 496 # document#17 -> Link to document with id 17
497 497 # document:Greetings -> Link to the document with title "Greetings"
498 498 # document:"Some document" -> Link to the document with title "Some document"
499 499 # Versions:
500 500 # version#3 -> Link to version with id 3
501 501 # version:1.0.0 -> Link to version named "1.0.0"
502 502 # version:"1.0 beta 2" -> Link to version named "1.0 beta 2"
503 503 # Attachments:
504 504 # attachment:file.zip -> Link to the attachment of the current object named file.zip
505 505 # Source files:
506 506 # source:some/file -> Link to the file located at /some/file in the project's repository
507 507 # source:some/file@52 -> Link to the file's revision 52
508 508 # source:some/file#L120 -> Link to line 120 of the file
509 509 # source:some/file@52#L120 -> Link to line 120 of the file's revision 52
510 510 # export:some/file -> Force the download of the file
511 511 # Forum messages:
512 512 # message#1218 -> Link to message with id 1218
513 513 text = text.gsub(%r{([\s\(,\-\>]|^)(!)?(attachment|document|version|commit|source|export|message|project)?((#|r)(\d+)|(:)([^"\s<>][^\s<>]*?|"[^"]+?"))(?=(?=[[:punct:]]\W)|,|\s|<|$)}) do |m|
514 leading, esc, prefix, sep, oid = $1, $2, $3, $5 || $7, $6 || $8
514 leading, esc, prefix, sep, identifier = $1, $2, $3, $5 || $7, $6 || $8
515 515 link = nil
516 516 if esc.nil?
517 517 if prefix.nil? && sep == 'r'
518 if project && (changeset = project.changesets.find_by_revision(oid))
519 link = link_to("r#{oid}", {:only_path => only_path, :controller => 'repositories', :action => 'revision', :id => project, :rev => oid},
518 if project && (changeset = project.changesets.find_by_revision(identifier))
519 link = link_to("r#{identifier}", {:only_path => only_path, :controller => 'repositories', :action => 'revision', :id => project, :rev => changeset.revision},
520 520 :class => 'changeset',
521 521 :title => truncate_single_line(changeset.comments, :length => 100))
522 522 end
523 523 elsif sep == '#'
524 oid = oid.to_i
524 oid = identifier.to_i
525 525 case prefix
526 526 when nil
527 527 if issue = Issue.visible.find_by_id(oid, :include => :status)
528 528 link = link_to("##{oid}", {:only_path => only_path, :controller => 'issues', :action => 'show', :id => oid},
529 529 :class => issue.css_classes,
530 530 :title => "#{truncate(issue.subject, :length => 100)} (#{issue.status.name})")
531 531 end
532 532 when 'document'
533 533 if document = Document.find_by_id(oid, :include => [:project], :conditions => Project.visible_by(User.current))
534 534 link = link_to h(document.title), {:only_path => only_path, :controller => 'documents', :action => 'show', :id => document},
535 535 :class => 'document'
536 536 end
537 537 when 'version'
538 538 if version = Version.find_by_id(oid, :include => [:project], :conditions => Project.visible_by(User.current))
539 539 link = link_to h(version.name), {:only_path => only_path, :controller => 'versions', :action => 'show', :id => version},
540 540 :class => 'version'
541 541 end
542 542 when 'message'
543 543 if message = Message.find_by_id(oid, :include => [:parent, {:board => :project}], :conditions => Project.visible_by(User.current))
544 544 link = link_to h(truncate(message.subject, :length => 60)), {:only_path => only_path,
545 545 :controller => 'messages',
546 546 :action => 'show',
547 547 :board_id => message.board,
548 548 :id => message.root,
549 549 :anchor => (message.parent ? "message-#{message.id}" : nil)},
550 550 :class => 'message'
551 551 end
552 552 when 'project'
553 553 if p = Project.visible.find_by_id(oid)
554 554 link = link_to h(p.name), {:only_path => only_path, :controller => 'projects', :action => 'show', :id => p},
555 555 :class => 'project'
556 556 end
557 557 end
558 558 elsif sep == ':'
559 559 # removes the double quotes if any
560 name = oid.gsub(%r{^"(.*)"$}, "\\1")
560 name = identifier.gsub(%r{^"(.*)"$}, "\\1")
561 561 case prefix
562 562 when 'document'
563 563 if project && document = project.documents.find_by_title(name)
564 564 link = link_to h(document.title), {:only_path => only_path, :controller => 'documents', :action => 'show', :id => document},
565 565 :class => 'document'
566 566 end
567 567 when 'version'
568 568 if project && version = project.versions.find_by_name(name)
569 569 link = link_to h(version.name), {:only_path => only_path, :controller => 'versions', :action => 'show', :id => version},
570 570 :class => 'version'
571 571 end
572 572 when 'commit'
573 573 if project && (changeset = project.changesets.find(:first, :conditions => ["scmid LIKE ?", "#{name}%"]))
574 574 link = link_to h("#{name}"), {:only_path => only_path, :controller => 'repositories', :action => 'revision', :id => project, :rev => changeset.revision},
575 575 :class => 'changeset',
576 576 :title => truncate_single_line(changeset.comments, :length => 100)
577 577 end
578 578 when 'source', 'export'
579 579 if project && project.repository
580 580 name =~ %r{^[/\\]*(.*?)(@([0-9a-f]+))?(#(L\d+))?$}
581 581 path, rev, anchor = $1, $3, $5
582 582 link = link_to h("#{prefix}:#{name}"), {:controller => 'repositories', :action => 'entry', :id => project,
583 583 :path => to_path_param(path),
584 584 :rev => rev,
585 585 :anchor => anchor,
586 586 :format => (prefix == 'export' ? 'raw' : nil)},
587 587 :class => (prefix == 'export' ? 'source download' : 'source')
588 588 end
589 589 when 'attachment'
590 590 if attachments && attachment = attachments.detect {|a| a.filename == name }
591 591 link = link_to h(attachment.filename), {:only_path => only_path, :controller => 'attachments', :action => 'download', :id => attachment},
592 592 :class => 'attachment'
593 593 end
594 594 when 'project'
595 595 if p = Project.visible.find(:first, :conditions => ["identifier = :s OR LOWER(name) = :s", {:s => name.downcase}])
596 596 link = link_to h(p.name), {:only_path => only_path, :controller => 'projects', :action => 'show', :id => p},
597 597 :class => 'project'
598 598 end
599 599 end
600 600 end
601 601 end
602 leading + (link || "#{prefix}#{sep}#{oid}")
602 leading + (link || "#{prefix}#{sep}#{identifier}")
603 603 end
604 604
605 605 text
606 606 end
607 607
608 608 # Same as Rails' simple_format helper without using paragraphs
609 609 def simple_format_without_paragraph(text)
610 610 text.to_s.
611 611 gsub(/\r\n?/, "\n"). # \r\n and \r -> \n
612 612 gsub(/\n\n+/, "<br /><br />"). # 2+ newline -> 2 br
613 613 gsub(/([^\n]\n)(?=[^\n])/, '\1<br />') # 1 newline -> br
614 614 end
615 615
616 616 def lang_options_for_select(blank=true)
617 617 (blank ? [["(auto)", ""]] : []) +
618 618 valid_languages.collect{|lang| [ ll(lang.to_s, :general_lang_name), lang.to_s]}.sort{|x,y| x.last <=> y.last }
619 619 end
620 620
621 621 def label_tag_for(name, option_tags = nil, options = {})
622 622 label_text = l(("field_"+field.to_s.gsub(/\_id$/, "")).to_sym) + (options.delete(:required) ? @template.content_tag("span", " *", :class => "required"): "")
623 623 content_tag("label", label_text)
624 624 end
625 625
626 626 def labelled_tabular_form_for(name, object, options, &proc)
627 627 options[:html] ||= {}
628 628 options[:html][:class] = 'tabular' unless options[:html].has_key?(:class)
629 629 form_for(name, object, options.merge({ :builder => TabularFormBuilder, :lang => current_language}), &proc)
630 630 end
631 631
632 632 def back_url_hidden_field_tag
633 633 back_url = params[:back_url] || request.env['HTTP_REFERER']
634 634 back_url = CGI.unescape(back_url.to_s)
635 635 hidden_field_tag('back_url', CGI.escape(back_url)) unless back_url.blank?
636 636 end
637 637
638 638 def check_all_links(form_name)
639 639 link_to_function(l(:button_check_all), "checkAll('#{form_name}', true)") +
640 640 " | " +
641 641 link_to_function(l(:button_uncheck_all), "checkAll('#{form_name}', false)")
642 642 end
643 643
644 644 def progress_bar(pcts, options={})
645 645 pcts = [pcts, pcts] unless pcts.is_a?(Array)
646 646 pcts = pcts.collect(&:round)
647 647 pcts[1] = pcts[1] - pcts[0]
648 648 pcts << (100 - pcts[1] - pcts[0])
649 649 width = options[:width] || '100px;'
650 650 legend = options[:legend] || ''
651 651 content_tag('table',
652 652 content_tag('tr',
653 653 (pcts[0] > 0 ? content_tag('td', '', :style => "width: #{pcts[0]}%;", :class => 'closed') : '') +
654 654 (pcts[1] > 0 ? content_tag('td', '', :style => "width: #{pcts[1]}%;", :class => 'done') : '') +
655 655 (pcts[2] > 0 ? content_tag('td', '', :style => "width: #{pcts[2]}%;", :class => 'todo') : '')
656 656 ), :class => 'progress', :style => "width: #{width};") +
657 657 content_tag('p', legend, :class => 'pourcent')
658 658 end
659 659
660 660 def context_menu_link(name, url, options={})
661 661 options[:class] ||= ''
662 662 if options.delete(:selected)
663 663 options[:class] << ' icon-checked disabled'
664 664 options[:disabled] = true
665 665 end
666 666 if options.delete(:disabled)
667 667 options.delete(:method)
668 668 options.delete(:confirm)
669 669 options.delete(:onclick)
670 670 options[:class] << ' disabled'
671 671 url = '#'
672 672 end
673 673 link_to name, url, options
674 674 end
675 675
676 676 def calendar_for(field_id)
677 677 include_calendar_headers_tags
678 678 image_tag("calendar.png", {:id => "#{field_id}_trigger",:class => "calendar-trigger"}) +
679 679 javascript_tag("Calendar.setup({inputField : '#{field_id}', ifFormat : '%Y-%m-%d', button : '#{field_id}_trigger' });")
680 680 end
681 681
682 682 def include_calendar_headers_tags
683 683 unless @calendar_headers_tags_included
684 684 @calendar_headers_tags_included = true
685 685 content_for :header_tags do
686 686 start_of_week = case Setting.start_of_week.to_i
687 687 when 1
688 688 'Calendar._FD = 1;' # Monday
689 689 when 7
690 690 'Calendar._FD = 0;' # Sunday
691 691 else
692 692 '' # use language
693 693 end
694 694
695 695 javascript_include_tag('calendar/calendar') +
696 696 javascript_include_tag("calendar/lang/calendar-#{current_language.to_s.downcase}.js") +
697 697 javascript_tag(start_of_week) +
698 698 javascript_include_tag('calendar/calendar-setup') +
699 699 stylesheet_link_tag('calendar')
700 700 end
701 701 end
702 702 end
703 703
704 704 def content_for(name, content = nil, &block)
705 705 @has_content ||= {}
706 706 @has_content[name] = true
707 707 super(name, content, &block)
708 708 end
709 709
710 710 def has_content?(name)
711 711 (@has_content && @has_content[name]) || false
712 712 end
713 713
714 714 # Returns the avatar image tag for the given +user+ if avatars are enabled
715 715 # +user+ can be a User or a string that will be scanned for an email address (eg. 'joe <joe@foo.bar>')
716 716 def avatar(user, options = { })
717 717 if Setting.gravatar_enabled?
718 718 options.merge!({:ssl => Setting.protocol == 'https', :default => Setting.gravatar_default})
719 719 email = nil
720 720 if user.respond_to?(:mail)
721 721 email = user.mail
722 722 elsif user.to_s =~ %r{<(.+?)>}
723 723 email = $1
724 724 end
725 725 return gravatar(email.to_s.downcase, options) unless email.blank? rescue nil
726 726 end
727 727 end
728 728
729 729 private
730 730
731 731 def wiki_helper
732 732 helper = Redmine::WikiFormatting.helper_for(Setting.text_formatting)
733 733 extend helper
734 734 return self
735 735 end
736 736
737 737 def link_to_remote_content_update(text, url_params)
738 738 link_to_remote(text,
739 739 {:url => url_params, :method => :get, :update => 'content', :complete => 'window.scrollTo(0,0)'},
740 740 {:href => url_for(:params => url_params)}
741 741 )
742 742 end
743 743
744 744 end
@@ -1,539 +1,541
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 # not found
204 '#0123456789' => '#0123456789',
203 205 # invalid expressions
204 206 'source:' => 'source:',
205 207 # url hash
206 208 "http://foo.bar/FAQ#3" => '<a class="external" href="http://foo.bar/FAQ#3">http://foo.bar/FAQ#3</a>',
207 209 }
208 210 @project = Project.find(1)
209 211 to_test.each { |text, result| assert_equal "<p>#{result}</p>", textilizable(text), "#{text} failed" }
210 212 end
211 213
212 214 def test_wiki_links
213 215 to_test = {
214 216 '[[CookBook documentation]]' => '<a href="/projects/ecookbook/wiki/CookBook_documentation" class="wiki-page">CookBook documentation</a>',
215 217 '[[Another page|Page]]' => '<a href="/projects/ecookbook/wiki/Another_page" class="wiki-page">Page</a>',
216 218 # link with anchor
217 219 '[[CookBook documentation#One-section]]' => '<a href="/projects/ecookbook/wiki/CookBook_documentation#One-section" class="wiki-page">CookBook documentation</a>',
218 220 '[[Another page#anchor|Page]]' => '<a href="/projects/ecookbook/wiki/Another_page#anchor" class="wiki-page">Page</a>',
219 221 # page that doesn't exist
220 222 '[[Unknown page]]' => '<a href="/projects/ecookbook/wiki/Unknown_page" class="wiki-page new">Unknown page</a>',
221 223 '[[Unknown page|404]]' => '<a href="/projects/ecookbook/wiki/Unknown_page" class="wiki-page new">404</a>',
222 224 # link to another project wiki
223 225 '[[onlinestore:]]' => '<a href="/projects/onlinestore/wiki/" class="wiki-page">onlinestore</a>',
224 226 '[[onlinestore:|Wiki]]' => '<a href="/projects/onlinestore/wiki/" class="wiki-page">Wiki</a>',
225 227 '[[onlinestore:Start page]]' => '<a href="/projects/onlinestore/wiki/Start_page" class="wiki-page">Start page</a>',
226 228 '[[onlinestore:Start page|Text]]' => '<a href="/projects/onlinestore/wiki/Start_page" class="wiki-page">Text</a>',
227 229 '[[onlinestore:Unknown page]]' => '<a href="/projects/onlinestore/wiki/Unknown_page" class="wiki-page new">Unknown page</a>',
228 230 # striked through link
229 231 '-[[Another page|Page]]-' => '<del><a href="/projects/ecookbook/wiki/Another_page" class="wiki-page">Page</a></del>',
230 232 '-[[Another page|Page]] link-' => '<del><a href="/projects/ecookbook/wiki/Another_page" class="wiki-page">Page</a> link</del>',
231 233 # escaping
232 234 '![[Another page|Page]]' => '[[Another page|Page]]',
233 235 # project does not exist
234 236 '[[unknowproject:Start]]' => '[[unknowproject:Start]]',
235 237 '[[unknowproject:Start|Page title]]' => '[[unknowproject:Start|Page title]]',
236 238 }
237 239 @project = Project.find(1)
238 240 to_test.each { |text, result| assert_equal "<p>#{result}</p>", textilizable(text) }
239 241 end
240 242
241 243 def test_html_tags
242 244 to_test = {
243 245 "<div>content</div>" => "<p>&lt;div&gt;content&lt;/div&gt;</p>",
244 246 "<div class=\"bold\">content</div>" => "<p>&lt;div class=\"bold\"&gt;content&lt;/div&gt;</p>",
245 247 "<script>some script;</script>" => "<p>&lt;script&gt;some script;&lt;/script&gt;</p>",
246 248 # do not escape pre/code tags
247 249 "<pre>\nline 1\nline2</pre>" => "<pre>\nline 1\nline2</pre>",
248 250 "<pre><code>\nline 1\nline2</code></pre>" => "<pre><code>\nline 1\nline2</code></pre>",
249 251 "<pre><div>content</div></pre>" => "<pre>&lt;div&gt;content&lt;/div&gt;</pre>",
250 252 "HTML comment: <!-- no comments -->" => "<p>HTML comment: &lt;!-- no comments --&gt;</p>",
251 253 "<!-- opening comment" => "<p>&lt;!-- opening comment</p>",
252 254 # remove attributes except class
253 255 "<pre class='foo'>some text</pre>" => "<pre class='foo'>some text</pre>",
254 256 "<pre onmouseover='alert(1)'>some text</pre>" => "<pre>some text</pre>",
255 257 }
256 258 to_test.each { |text, result| assert_equal result, textilizable(text) }
257 259 end
258 260
259 261 def test_allowed_html_tags
260 262 to_test = {
261 263 "<pre>preformatted text</pre>" => "<pre>preformatted text</pre>",
262 264 "<notextile>no *textile* formatting</notextile>" => "no *textile* formatting",
263 265 "<notextile>this is <tag>a tag</tag></notextile>" => "this is &lt;tag&gt;a tag&lt;/tag&gt;"
264 266 }
265 267 to_test.each { |text, result| assert_equal result, textilizable(text) }
266 268 end
267 269
268 270 def test_pre_tags
269 271 raw = <<-RAW
270 272 Before
271 273
272 274 <pre>
273 275 <prepared-statement-cache-size>32</prepared-statement-cache-size>
274 276 </pre>
275 277
276 278 After
277 279 RAW
278 280
279 281 expected = <<-EXPECTED
280 282 <p>Before</p>
281 283 <pre>
282 284 &lt;prepared-statement-cache-size&gt;32&lt;/prepared-statement-cache-size&gt;
283 285 </pre>
284 286 <p>After</p>
285 287 EXPECTED
286 288
287 289 assert_equal expected.gsub(%r{[\r\n\t]}, ''), textilizable(raw).gsub(%r{[\r\n\t]}, '')
288 290 end
289 291
290 292 def test_syntax_highlight
291 293 raw = <<-RAW
292 294 <pre><code class="ruby">
293 295 # Some ruby code here
294 296 </pre></code>
295 297 RAW
296 298
297 299 expected = <<-EXPECTED
298 300 <pre><code class="ruby CodeRay"><span class="no">1</span> <span class="c"># Some ruby code here</span>
299 301 </pre></code>
300 302 EXPECTED
301 303
302 304 assert_equal expected.gsub(%r{[\r\n\t]}, ''), textilizable(raw).gsub(%r{[\r\n\t]}, '')
303 305 end
304 306
305 307 def test_wiki_links_in_tables
306 308 to_test = {"|[[Page|Link title]]|[[Other Page|Other title]]|\n|Cell 21|[[Last page]]|" =>
307 309 '<tr><td><a href="/projects/ecookbook/wiki/Page" class="wiki-page new">Link title</a></td>' +
308 310 '<td><a href="/projects/ecookbook/wiki/Other_Page" class="wiki-page new">Other title</a></td>' +
309 311 '</tr><tr><td>Cell 21</td><td><a href="/projects/ecookbook/wiki/Last_page" class="wiki-page new">Last page</a></td></tr>'
310 312 }
311 313 @project = Project.find(1)
312 314 to_test.each { |text, result| assert_equal "<table>#{result}</table>", textilizable(text).gsub(/[\t\n]/, '') }
313 315 end
314 316
315 317 def test_text_formatting
316 318 to_test = {'*_+bold, italic and underline+_*' => '<strong><em><ins>bold, italic and underline</ins></em></strong>',
317 319 '(_text within parentheses_)' => '(<em>text within parentheses</em>)',
318 320 'a *Humane Web* Text Generator' => 'a <strong>Humane Web</strong> Text Generator',
319 321 '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>',
320 322 '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',
321 323 }
322 324 to_test.each { |text, result| assert_equal "<p>#{result}</p>", textilizable(text) }
323 325 end
324 326
325 327 def test_wiki_horizontal_rule
326 328 assert_equal '<hr />', textilizable('---')
327 329 assert_equal '<p>Dashes: ---</p>', textilizable('Dashes: ---')
328 330 end
329 331
330 332 def test_acronym
331 333 assert_equal '<p>This is an acronym: <acronym title="American Civil Liberties Union">ACLU</acronym>.</p>',
332 334 textilizable('This is an acronym: ACLU(American Civil Liberties Union).')
333 335 end
334 336
335 337 def test_footnotes
336 338 raw = <<-RAW
337 339 This is some text[1].
338 340
339 341 fn1. This is the foot note
340 342 RAW
341 343
342 344 expected = <<-EXPECTED
343 345 <p>This is some text<sup><a href=\"#fn1\">1</a></sup>.</p>
344 346 <p id="fn1" class="footnote"><sup>1</sup> This is the foot note</p>
345 347 EXPECTED
346 348
347 349 assert_equal expected.gsub(%r{[\r\n\t]}, ''), textilizable(raw).gsub(%r{[\r\n\t]}, '')
348 350 end
349 351
350 352 def test_table_of_content
351 353 raw = <<-RAW
352 354 {{toc}}
353 355
354 356 h1. Title
355 357
356 358 Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Maecenas sed libero.
357 359
358 360 h2. Subtitle with a [[Wiki]] link
359 361
360 362 Nullam commodo metus accumsan nulla. Curabitur lobortis dui id dolor.
361 363
362 364 h2. Subtitle with [[Wiki|another Wiki]] link
363 365
364 366 h2. Subtitle with %{color:red}red text%
365 367
366 368 h1. Another title
367 369
368 370 RAW
369 371
370 372 expected = '<ul class="toc">' +
371 373 '<li class="heading1"><a href="#Title">Title</a></li>' +
372 374 '<li class="heading2"><a href="#Subtitle-with-a-Wiki-link">Subtitle with a Wiki link</a></li>' +
373 375 '<li class="heading2"><a href="#Subtitle-with-another-Wiki-link">Subtitle with another Wiki link</a></li>' +
374 376 '<li class="heading2"><a href="#Subtitle-with-red-text">Subtitle with red text</a></li>' +
375 377 '<li class="heading1"><a href="#Another-title">Another title</a></li>' +
376 378 '</ul>'
377 379
378 380 assert textilizable(raw).gsub("\n", "").include?(expected)
379 381 end
380 382
381 383 def test_blockquote
382 384 # orig raw text
383 385 raw = <<-RAW
384 386 John said:
385 387 > Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Maecenas sed libero.
386 388 > Nullam commodo metus accumsan nulla. Curabitur lobortis dui id dolor.
387 389 > * Donec odio lorem,
388 390 > * sagittis ac,
389 391 > * malesuada in,
390 392 > * adipiscing eu, dolor.
391 393 >
392 394 > >Nulla varius pulvinar diam. Proin id arcu id lorem scelerisque condimentum. Proin vehicula turpis vitae lacus.
393 395 > Proin a tellus. Nam vel neque.
394 396
395 397 He's right.
396 398 RAW
397 399
398 400 # expected html
399 401 expected = <<-EXPECTED
400 402 <p>John said:</p>
401 403 <blockquote>
402 404 Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Maecenas sed libero.
403 405 Nullam commodo metus accumsan nulla. Curabitur lobortis dui id dolor.
404 406 <ul>
405 407 <li>Donec odio lorem,</li>
406 408 <li>sagittis ac,</li>
407 409 <li>malesuada in,</li>
408 410 <li>adipiscing eu, dolor.</li>
409 411 </ul>
410 412 <blockquote>
411 413 <p>Nulla varius pulvinar diam. Proin id arcu id lorem scelerisque condimentum. Proin vehicula turpis vitae lacus.</p>
412 414 </blockquote>
413 415 <p>Proin a tellus. Nam vel neque.</p>
414 416 </blockquote>
415 417 <p>He's right.</p>
416 418 EXPECTED
417 419
418 420 assert_equal expected.gsub(%r{\s+}, ''), textilizable(raw).gsub(%r{\s+}, '')
419 421 end
420 422
421 423 def test_table
422 424 raw = <<-RAW
423 425 This is a table with empty cells:
424 426
425 427 |cell11|cell12||
426 428 |cell21||cell23|
427 429 |cell31|cell32|cell33|
428 430 RAW
429 431
430 432 expected = <<-EXPECTED
431 433 <p>This is a table with empty cells:</p>
432 434
433 435 <table>
434 436 <tr><td>cell11</td><td>cell12</td><td></td></tr>
435 437 <tr><td>cell21</td><td></td><td>cell23</td></tr>
436 438 <tr><td>cell31</td><td>cell32</td><td>cell33</td></tr>
437 439 </table>
438 440 EXPECTED
439 441
440 442 assert_equal expected.gsub(%r{\s+}, ''), textilizable(raw).gsub(%r{\s+}, '')
441 443 end
442 444
443 445 def test_table_with_line_breaks
444 446 raw = <<-RAW
445 447 This is a table with line breaks:
446 448
447 449 |cell11
448 450 continued|cell12||
449 451 |-cell21-||cell23
450 452 cell23 line2
451 453 cell23 *line3*|
452 454 |cell31|cell32
453 455 cell32 line2|cell33|
454 456
455 457 RAW
456 458
457 459 expected = <<-EXPECTED
458 460 <p>This is a table with line breaks:</p>
459 461
460 462 <table>
461 463 <tr>
462 464 <td>cell11<br />continued</td>
463 465 <td>cell12</td>
464 466 <td></td>
465 467 </tr>
466 468 <tr>
467 469 <td><del>cell21</del></td>
468 470 <td></td>
469 471 <td>cell23<br/>cell23 line2<br/>cell23 <strong>line3</strong></td>
470 472 </tr>
471 473 <tr>
472 474 <td>cell31</td>
473 475 <td>cell32<br/>cell32 line2</td>
474 476 <td>cell33</td>
475 477 </tr>
476 478 </table>
477 479 EXPECTED
478 480
479 481 assert_equal expected.gsub(%r{\s+}, ''), textilizable(raw).gsub(%r{\s+}, '')
480 482 end
481 483
482 484 def test_textile_should_not_mangle_brackets
483 485 assert_equal '<p>[msg1][msg2]</p>', textilizable('[msg1][msg2]')
484 486 end
485 487
486 488 def test_default_formatter
487 489 Setting.text_formatting = 'unknown'
488 490 text = 'a *link*: http://www.example.net/'
489 491 assert_equal '<p>a *link*: <a href="http://www.example.net/">http://www.example.net/</a></p>', textilizable(text)
490 492 Setting.text_formatting = 'textile'
491 493 end
492 494
493 495 def test_due_date_distance_in_words
494 496 to_test = { Date.today => 'Due in 0 days',
495 497 Date.today + 1 => 'Due in 1 day',
496 498 Date.today + 100 => 'Due in about 3 months',
497 499 Date.today + 20000 => 'Due in over 54 years',
498 500 Date.today - 1 => '1 day late',
499 501 Date.today - 100 => 'about 3 months late',
500 502 Date.today - 20000 => 'over 54 years late',
501 503 }
502 504 to_test.each do |date, expected|
503 505 assert_equal expected, due_date_distance_in_words(date)
504 506 end
505 507 end
506 508
507 509 def test_avatar
508 510 # turn on avatars
509 511 Setting.gravatar_enabled = '1'
510 512 assert avatar(User.find_by_mail('jsmith@somenet.foo')).include?(Digest::MD5.hexdigest('jsmith@somenet.foo'))
511 513 assert avatar('jsmith <jsmith@somenet.foo>').include?(Digest::MD5.hexdigest('jsmith@somenet.foo'))
512 514 assert_nil avatar('jsmith')
513 515 assert_nil avatar(nil)
514 516
515 517 # turn off avatars
516 518 Setting.gravatar_enabled = '0'
517 519 assert_nil avatar(User.find_by_mail('jsmith@somenet.foo'))
518 520 end
519 521
520 522 def test_link_to_user
521 523 user = User.find(2)
522 524 t = link_to_user(user)
523 525 assert_equal "<a href=\"/users/2\">#{ user.name }</a>", t
524 526 end
525 527
526 528 def test_link_to_user_should_not_link_to_locked_user
527 529 user = User.find(5)
528 530 assert user.locked?
529 531 t = link_to_user(user)
530 532 assert_equal user.name, t
531 533 end
532 534
533 535 def test_link_to_user_should_not_link_to_anonymous
534 536 user = User.anonymous
535 537 assert user.anonymous?
536 538 t = link_to_user(user)
537 539 assert_equal ::I18n.t(:label_user_anonymous), t
538 540 end
539 541 end
General Comments 0
You need to be logged in to leave comments. Login now