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