PageRenderTime 65ms CodeModel.GetById 27ms RepoModel.GetById 1ms app.codeStats 0ms

/app/helpers/application_helper.rb

https://github.com/redrick/chiliheroku
Ruby | 947 lines | 725 code | 92 blank | 130 comment | 142 complexity | 941b2e4883bab1bafed8fbfc7df84df2 MD5 | raw file
Possible License(s): GPL-2.0, LGPL-2.1, BSD-3-Clause
  1. # Redmine - project management software
  2. # Copyright (C) 2006-2010 Jean-Philippe Lang
  3. #
  4. # This program is free software; you can redistribute it and/or
  5. # modify it under the terms of the GNU General Public License
  6. # as published by the Free Software Foundation; either version 2
  7. # of the License, or (at your option) any later version.
  8. #
  9. # This program is distributed in the hope that it will be useful,
  10. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. # GNU General Public License for more details.
  13. #
  14. # You should have received a copy of the GNU General Public License
  15. # along with this program; if not, write to the Free Software
  16. # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  17. require 'forwardable'
  18. require 'cgi'
  19. module ApplicationHelper
  20. include Redmine::WikiFormatting::Macros::Definitions
  21. include Redmine::I18n
  22. include GravatarHelper::PublicMethods
  23. extend Forwardable
  24. def_delegators :wiki_helper, :wikitoolbar_for, :heads_for_wiki_formatter
  25. # Return true if user is authorized for controller/action, otherwise false
  26. def authorize_for(controller, action)
  27. User.current.allowed_to?({:controller => controller, :action => action}, @project)
  28. end
  29. # Display a link if user is authorized
  30. #
  31. # @param [String] name Anchor text (passed to link_to)
  32. # @param [Hash] options Hash params. This will checked by authorize_for to see if the user is authorized
  33. # @param [optional, Hash] html_options Options passed to link_to
  34. # @param [optional, Hash] parameters_for_method_reference Extra parameters for link_to
  35. def link_to_if_authorized(name, options = {}, html_options = nil, *parameters_for_method_reference)
  36. link_to(name, options, html_options, *parameters_for_method_reference) if authorize_for(options[:controller] || params[:controller], options[:action])
  37. end
  38. # Display a link to remote if user is authorized
  39. def link_to_remote_if_authorized(name, options = {}, html_options = nil)
  40. url = options[:url] || {}
  41. link_to_remote(name, options, html_options) if authorize_for(url[:controller] || params[:controller], url[:action])
  42. end
  43. # Displays a link to user's account page if active
  44. def link_to_user(user, options={})
  45. if user.is_a?(User)
  46. name = h(user.name(options[:format]))
  47. if user.active?
  48. link_to name, :controller => 'users', :action => 'show', :id => user
  49. else
  50. name
  51. end
  52. else
  53. h(user.to_s)
  54. end
  55. end
  56. # Displays a link to +issue+ with its subject.
  57. # Examples:
  58. #
  59. # link_to_issue(issue) # => Defect #6: This is the subject
  60. # link_to_issue(issue, :truncate => 6) # => Defect #6: This i...
  61. # link_to_issue(issue, :subject => false) # => Defect #6
  62. # link_to_issue(issue, :project => true) # => Foo - Defect #6
  63. #
  64. def link_to_issue(issue, options={})
  65. title = nil
  66. subject = nil
  67. if options[:subject] == false
  68. title = truncate(issue.subject, :length => 60)
  69. else
  70. subject = issue.subject
  71. if options[:truncate]
  72. subject = truncate(subject, :length => options[:truncate])
  73. end
  74. end
  75. s = link_to "#{issue.tracker} ##{issue.id}", {:controller => "issues", :action => "show", :id => issue},
  76. :class => issue.css_classes,
  77. :title => title
  78. s << ": #{h subject}" if subject
  79. s = "#{h issue.project} - " + s if options[:project]
  80. s
  81. end
  82. # Generates a link to an attachment.
  83. # Options:
  84. # * :text - Link text (default to attachment filename)
  85. # * :download - Force download (default: false)
  86. def link_to_attachment(attachment, options={})
  87. text = options.delete(:text) || attachment.filename
  88. action = options.delete(:download) ? 'download' : 'show'
  89. link_to(h(text), {:controller => 'attachments', :action => action, :id => attachment, :filename => attachment.filename }, options)
  90. end
  91. # Generates a link to a SCM revision
  92. # Options:
  93. # * :text - Link text (default to the formatted revision)
  94. def link_to_revision(revision, project, options={})
  95. text = options.delete(:text) || format_revision(revision)
  96. rev = revision.respond_to?(:identifier) ? revision.identifier : revision
  97. link_to(text, {:controller => 'repositories', :action => 'revision', :id => project, :rev => rev},
  98. :title => l(:label_revision_id, format_revision(revision)))
  99. end
  100. # Generates a link to a message
  101. def link_to_message(message, options={}, html_options = nil)
  102. link_to(
  103. h(truncate(message.subject, :length => 60)),
  104. { :controller => 'messages', :action => 'show',
  105. :board_id => message.board_id,
  106. :id => message.root,
  107. :r => (message.parent_id && message.id),
  108. :anchor => (message.parent_id ? "message-#{message.id}" : nil)
  109. }.merge(options),
  110. html_options
  111. )
  112. end
  113. # Generates a link to a project if active
  114. # Examples:
  115. #
  116. # link_to_project(project) # => link to the specified project overview
  117. # link_to_project(project, :action=>'settings') # => link to project settings
  118. # link_to_project(project, {:only_path => false}, :class => "project") # => 3rd arg adds html options
  119. # link_to_project(project, {}, :class => "project") # => html options with default url (project overview)
  120. #
  121. def link_to_project(project, options={}, html_options = nil)
  122. if project.active?
  123. url = {:controller => 'projects', :action => 'show', :id => project}.merge(options)
  124. link_to(h(project), url, html_options)
  125. else
  126. h(project)
  127. end
  128. end
  129. def toggle_link(name, id, options={})
  130. onclick = "Element.toggle('#{id}'); "
  131. onclick << (options[:focus] ? "Form.Element.focus('#{options[:focus]}'); " : "this.blur(); ")
  132. onclick << "return false;"
  133. link_to(name, "#", :onclick => onclick)
  134. end
  135. def image_to_function(name, function, html_options = {})
  136. html_options.symbolize_keys!
  137. tag(:input, html_options.merge({
  138. :type => "image", :src => image_path(name),
  139. :onclick => (html_options[:onclick] ? "#{html_options[:onclick]}; " : "") + "#{function};"
  140. }))
  141. end
  142. def prompt_to_remote(name, text, param, url, html_options = {})
  143. html_options[:onclick] = "promptToRemote('#{text}', '#{param}', '#{url_for(url)}'); return false;"
  144. link_to name, {}, html_options
  145. end
  146. def format_activity_title(text)
  147. h(truncate_single_line(text, :length => 100))
  148. end
  149. def format_activity_day(date)
  150. date == Date.today ? l(:label_today).titleize : format_date(date)
  151. end
  152. def format_activity_description(text)
  153. h(truncate(text.to_s, :length => 120).gsub(%r{[\r\n]*<(pre|code)>.*$}m, '...')).gsub(/[\r\n]+/, "<br />")
  154. end
  155. def format_version_name(version)
  156. if version.project == @project
  157. h(version)
  158. else
  159. h("#{version.project} - #{version}")
  160. end
  161. end
  162. def due_date_distance_in_words(date)
  163. if date
  164. l((date < Date.today ? :label_roadmap_overdue : :label_roadmap_due_in), distance_of_date_in_words(Date.today, date))
  165. end
  166. end
  167. def render_page_hierarchy(pages, node=nil)
  168. content = ''
  169. if pages[node]
  170. content << "<ul class=\"pages-hierarchy\">\n"
  171. pages[node].each do |page|
  172. content << "<li>"
  173. content << link_to(h(page.pretty_title), {:controller => 'wiki', :action => 'show', :project_id => page.project, :id => page.title},
  174. :title => (page.respond_to?(:updated_on) ? l(:label_updated_time, distance_of_time_in_words(Time.now, page.updated_on)) : nil))
  175. content << "\n" + render_page_hierarchy(pages, page.id) if pages[page.id]
  176. content << "</li>\n"
  177. end
  178. content << "</ul>\n"
  179. end
  180. content
  181. end
  182. # Renders flash messages
  183. def render_flash_messages
  184. s = ''
  185. flash.each do |k,v|
  186. s << content_tag('div', v, :class => "flash #{k}")
  187. end
  188. s
  189. end
  190. # Renders tabs and their content
  191. def render_tabs(tabs)
  192. if tabs.any?
  193. render :partial => 'common/tabs', :locals => {:tabs => tabs}
  194. else
  195. content_tag 'p', l(:label_no_data), :class => "nodata"
  196. end
  197. end
  198. # Renders the project quick-jump box
  199. def render_project_jump_box
  200. # Retrieve them now to avoid a COUNT query
  201. projects = User.current.projects.all
  202. if projects.any?
  203. s = '<select onchange="if (this.value != \'\') { window.location = this.value; }">' +
  204. "<option value=''>#{ l(:label_jump_to_a_project) }</option>" +
  205. '<option value="" disabled="disabled">---</option>'
  206. s << project_tree_options_for_select(projects, :selected => @project) do |p|
  207. { :value => url_for(:controller => 'projects', :action => 'show', :id => p, :jump => current_menu_item) }
  208. end
  209. s << '</select>'
  210. s
  211. end
  212. end
  213. def project_tree_options_for_select(projects, options = {})
  214. s = ''
  215. project_tree(projects) do |project, level|
  216. name_prefix = (level > 0 ? ('&nbsp;' * 2 * level + '&#187; ') : '')
  217. tag_options = {:value => project.id}
  218. if project == options[:selected] || (options[:selected].respond_to?(:include?) && options[:selected].include?(project))
  219. tag_options[:selected] = 'selected'
  220. else
  221. tag_options[:selected] = nil
  222. end
  223. tag_options.merge!(yield(project)) if block_given?
  224. s << content_tag('option', name_prefix + h(project), tag_options)
  225. end
  226. s
  227. end
  228. # Yields the given block for each project with its level in the tree
  229. #
  230. # Wrapper for Project#project_tree
  231. def project_tree(projects, &block)
  232. Project.project_tree(projects, &block)
  233. end
  234. def project_nested_ul(projects, &block)
  235. s = ''
  236. if projects.any?
  237. ancestors = []
  238. projects.sort_by(&:lft).each do |project|
  239. if (ancestors.empty? || project.is_descendant_of?(ancestors.last))
  240. s << "<ul>\n"
  241. else
  242. ancestors.pop
  243. s << "</li>"
  244. while (ancestors.any? && !project.is_descendant_of?(ancestors.last))
  245. ancestors.pop
  246. s << "</ul></li>\n"
  247. end
  248. end
  249. s << "<li>"
  250. s << yield(project).to_s
  251. ancestors << project
  252. end
  253. s << ("</li></ul>\n" * ancestors.size)
  254. end
  255. s
  256. end
  257. def principals_check_box_tags(name, principals)
  258. s = ''
  259. principals.sort.each do |principal|
  260. s << "<label>#{ check_box_tag name, principal.id, false } #{h principal}</label>\n"
  261. end
  262. s
  263. end
  264. # Truncates and returns the string as a single line
  265. def truncate_single_line(string, *args)
  266. truncate(string.to_s, *args).gsub(%r{[\r\n]+}m, ' ')
  267. end
  268. # Truncates at line break after 250 characters or options[:length]
  269. def truncate_lines(string, options={})
  270. length = options[:length] || 250
  271. if string.to_s =~ /\A(.{#{length}}.*?)$/m
  272. "#{$1}..."
  273. else
  274. string
  275. end
  276. end
  277. def html_hours(text)
  278. text.gsub(%r{(\d+)\.(\d+)}, '<span class="hours hours-int">\1</span><span class="hours hours-dec">.\2</span>')
  279. end
  280. def authoring(created, author, options={})
  281. l(options[:label] || :label_added_time_by, :author => link_to_user(author), :age => time_tag(created))
  282. end
  283. def time_tag(time)
  284. text = distance_of_time_in_words(Time.now, time)
  285. if @project
  286. link_to(text, {:controller => 'activities', :action => 'index', :id => @project, :from => time.to_date}, :title => format_time(time))
  287. else
  288. content_tag('acronym', text, :title => format_time(time))
  289. end
  290. end
  291. def syntax_highlight(name, content)
  292. Redmine::SyntaxHighlighting.highlight_by_filename(content, name)
  293. end
  294. def to_path_param(path)
  295. path.to_s.split(%r{[/\\]}).select {|p| !p.blank?}
  296. end
  297. def pagination_links_full(paginator, count=nil, options={})
  298. page_param = options.delete(:page_param) || :page
  299. per_page_links = options.delete(:per_page_links)
  300. url_param = params.dup
  301. # don't reuse query params if filters are present
  302. url_param.merge!(:fields => nil, :values => nil, :operators => nil) if url_param.delete(:set_filter)
  303. html = ''
  304. if paginator.current.previous
  305. html << link_to_remote_content_update('&#171; ' + l(:label_previous), url_param.merge(page_param => paginator.current.previous)) + ' '
  306. end
  307. html << (pagination_links_each(paginator, options) do |n|
  308. link_to_remote_content_update(n.to_s, url_param.merge(page_param => n))
  309. end || '')
  310. if paginator.current.next
  311. html << ' ' + link_to_remote_content_update((l(:label_next) + ' &#187;'), url_param.merge(page_param => paginator.current.next))
  312. end
  313. unless count.nil?
  314. html << " (#{paginator.current.first_item}-#{paginator.current.last_item}/#{count})"
  315. if per_page_links != false && links = per_page_links(paginator.items_per_page)
  316. html << " | #{links}"
  317. end
  318. end
  319. html
  320. end
  321. def per_page_links(selected=nil)
  322. url_param = params.dup
  323. url_param.clear if url_param.has_key?(:set_filter)
  324. links = Setting.per_page_options_array.collect do |n|
  325. n == selected ? n : link_to_remote(n, {:update => "content",
  326. :url => params.dup.merge(:per_page => n),
  327. :method => :get},
  328. {:href => url_for(url_param.merge(:per_page => n))})
  329. end
  330. links.size > 1 ? l(:label_display_per_page, links.join(', ')) : nil
  331. end
  332. def reorder_links(name, url)
  333. link_to(image_tag('2uparrow.png', :alt => l(:label_sort_highest)), url.merge({"#{name}[move_to]" => 'highest'}), :method => :post, :title => l(:label_sort_highest)) +
  334. link_to(image_tag('1uparrow.png', :alt => l(:label_sort_higher)), url.merge({"#{name}[move_to]" => 'higher'}), :method => :post, :title => l(:label_sort_higher)) +
  335. link_to(image_tag('1downarrow.png', :alt => l(:label_sort_lower)), url.merge({"#{name}[move_to]" => 'lower'}), :method => :post, :title => l(:label_sort_lower)) +
  336. link_to(image_tag('2downarrow.png', :alt => l(:label_sort_lowest)), url.merge({"#{name}[move_to]" => 'lowest'}), :method => :post, :title => l(:label_sort_lowest))
  337. end
  338. def breadcrumb(*args)
  339. elements = args.flatten
  340. elements.any? ? content_tag('p', args.join(' &#187; ') + ' &#187; ', :class => 'breadcrumb') : nil
  341. end
  342. def other_formats_links(&block)
  343. concat('<p class="other-formats">' + l(:label_export_to))
  344. yield Redmine::Views::OtherFormatsBuilder.new(self)
  345. concat('</p>')
  346. end
  347. def page_header_title
  348. if @project.nil? || @project.new_record?
  349. h(Setting.app_title)
  350. else
  351. b = []
  352. ancestors = (@project.root? ? [] : @project.ancestors.visible)
  353. if ancestors.any?
  354. root = ancestors.shift
  355. b << link_to_project(root, {:jump => current_menu_item}, :class => 'root')
  356. if ancestors.size > 2
  357. b << '&#8230;'
  358. ancestors = ancestors[-2, 2]
  359. end
  360. b += ancestors.collect {|p| link_to_project(p, {:jump => current_menu_item}, :class => 'ancestor') }
  361. end
  362. b << h(@project)
  363. b.join(' &#187; ')
  364. end
  365. end
  366. def html_title(*args)
  367. if args.empty?
  368. title = []
  369. title << @project.name if @project
  370. title += @html_title if @html_title
  371. title << Setting.app_title
  372. title.select {|t| !t.blank? }.join(' - ')
  373. else
  374. @html_title ||= []
  375. @html_title += args
  376. end
  377. end
  378. # Returns the theme, controller name, and action as css classes for the
  379. # HTML body.
  380. def body_css_classes
  381. css = []
  382. if theme = Redmine::Themes.theme(Setting.ui_theme)
  383. css << 'theme-' + theme.name
  384. end
  385. css << 'controller-' + params[:controller]
  386. css << 'action-' + params[:action]
  387. css.join(' ')
  388. end
  389. def accesskey(s)
  390. Redmine::AccessKeys.key_for s
  391. end
  392. # Formats text according to system settings.
  393. # 2 ways to call this method:
  394. # * with a String: textilizable(text, options)
  395. # * with an object and one of its attribute: textilizable(issue, :description, options)
  396. def textilizable(*args)
  397. options = args.last.is_a?(Hash) ? args.pop : {}
  398. case args.size
  399. when 1
  400. obj = options[:object]
  401. text = args.shift
  402. when 2
  403. obj = args.shift
  404. attr = args.shift
  405. text = obj.send(attr).to_s
  406. else
  407. raise ArgumentError, 'invalid arguments to textilizable'
  408. end
  409. return '' if text.blank?
  410. project = options[:project] || @project || (obj && obj.respond_to?(:project) ? obj.project : nil)
  411. only_path = options.delete(:only_path) == false ? false : true
  412. text = Redmine::WikiFormatting.to_html(Setting.text_formatting, text, :object => obj, :attribute => attr) { |macro, args| exec_macro(macro, obj, args) }
  413. @parsed_headings = []
  414. text = parse_non_pre_blocks(text) do |text|
  415. [:parse_inline_attachments, :parse_wiki_links, :parse_redmine_links, :parse_headings].each do |method_name|
  416. send method_name, text, project, obj, attr, only_path, options
  417. end
  418. end
  419. if @parsed_headings.any?
  420. replace_toc(text, @parsed_headings)
  421. end
  422. text
  423. end
  424. def parse_non_pre_blocks(text)
  425. s = StringScanner.new(text)
  426. tags = []
  427. parsed = ''
  428. while !s.eos?
  429. s.scan(/(.*?)(<(\/)?(pre|code)(.*?)>|\z)/im)
  430. text, full_tag, closing, tag = s[1], s[2], s[3], s[4]
  431. if tags.empty?
  432. yield text
  433. end
  434. parsed << text
  435. if tag
  436. if closing
  437. if tags.last == tag.downcase
  438. tags.pop
  439. end
  440. else
  441. tags << tag.downcase
  442. end
  443. parsed << full_tag
  444. end
  445. end
  446. # Close any non closing tags
  447. while tag = tags.pop
  448. parsed << "</#{tag}>"
  449. end
  450. parsed
  451. end
  452. def parse_inline_attachments(text, project, obj, attr, only_path, options)
  453. # when using an image link, try to use an attachment, if possible
  454. if options[:attachments] || (obj && obj.respond_to?(:attachments))
  455. attachments = nil
  456. text.gsub!(/src="([^\/"]+\.(bmp|gif|jpg|jpeg|png))"(\s+alt="([^"]*)")?/i) do |m|
  457. filename, ext, alt, alttext = $1.downcase, $2, $3, $4
  458. attachments ||= (options[:attachments] || obj.attachments).sort_by(&:created_on).reverse
  459. # search for the picture in attachments
  460. if found = attachments.detect { |att| att.filename.downcase == filename }
  461. image_url = url_for :only_path => only_path, :controller => 'attachments', :action => 'download', :id => found
  462. desc = found.description.to_s.gsub('"', '')
  463. if !desc.blank? && alttext.blank?
  464. alt = " title=\"#{desc}\" alt=\"#{desc}\""
  465. end
  466. "src=\"#{image_url}\"#{alt}"
  467. else
  468. m
  469. end
  470. end
  471. end
  472. end
  473. # Wiki links
  474. #
  475. # Examples:
  476. # [[mypage]]
  477. # [[mypage|mytext]]
  478. # wiki links can refer other project wikis, using project name or identifier:
  479. # [[project:]] -> wiki starting page
  480. # [[project:|mytext]]
  481. # [[project:mypage]]
  482. # [[project:mypage|mytext]]
  483. def parse_wiki_links(text, project, obj, attr, only_path, options)
  484. text.gsub!(/(!)?(\[\[([^\]\n\|]+)(\|([^\]\n\|]+))?\]\])/) do |m|
  485. link_project = project
  486. esc, all, page, title = $1, $2, $3, $5
  487. if esc.nil?
  488. if page =~ /^([^\:]+)\:(.*)$/
  489. link_project = Project.find_by_identifier($1) || Project.find_by_name($1)
  490. page = $2
  491. title ||= $1 if page.blank?
  492. end
  493. if link_project && link_project.wiki
  494. # extract anchor
  495. anchor = nil
  496. if page =~ /^(.+?)\#(.+)$/
  497. page, anchor = $1, $2
  498. end
  499. # check if page exists
  500. wiki_page = link_project.wiki.find_page(page)
  501. url = case options[:wiki_links]
  502. when :local; "#{title}.html"
  503. when :anchor; "##{title}" # used for single-file wiki export
  504. else
  505. wiki_page_id = page.present? ? Wiki.titleize(page) : nil
  506. url_for(:only_path => only_path, :controller => 'wiki', :action => 'show', :project_id => link_project, :id => wiki_page_id, :anchor => anchor)
  507. end
  508. link_to((title || page), url, :class => ('wiki-page' + (wiki_page ? '' : ' new')))
  509. else
  510. # project or wiki doesn't exist
  511. all
  512. end
  513. else
  514. all
  515. end
  516. end
  517. end
  518. # Redmine links
  519. #
  520. # Examples:
  521. # Issues:
  522. # #52 -> Link to issue #52
  523. # Changesets:
  524. # r52 -> Link to revision 52
  525. # commit:a85130f -> Link to scmid starting with a85130f
  526. # Documents:
  527. # document#17 -> Link to document with id 17
  528. # document:Greetings -> Link to the document with title "Greetings"
  529. # document:"Some document" -> Link to the document with title "Some document"
  530. # Versions:
  531. # version#3 -> Link to version with id 3
  532. # version:1.0.0 -> Link to version named "1.0.0"
  533. # version:"1.0 beta 2" -> Link to version named "1.0 beta 2"
  534. # Attachments:
  535. # attachment:file.zip -> Link to the attachment of the current object named file.zip
  536. # Source files:
  537. # source:some/file -> Link to the file located at /some/file in the project's repository
  538. # source:some/file@52 -> Link to the file's revision 52
  539. # source:some/file#L120 -> Link to line 120 of the file
  540. # source:some/file@52#L120 -> Link to line 120 of the file's revision 52
  541. # export:some/file -> Force the download of the file
  542. # Forum messages:
  543. # message#1218 -> Link to message with id 1218
  544. #
  545. # Links can refer other objects from other projects, using project identifier:
  546. # identifier:r52
  547. # identifier:document:"Some document"
  548. # identifier:version:1.0.0
  549. # identifier:source:some/file
  550. def parse_redmine_links(text, project, obj, attr, only_path, options)
  551. text.gsub!(%r{([\s\(,\-\[\>]|^)(!)?(([a-z0-9\-]+):)?(attachment|document|version|commit|source|export|message|project)?((#|r)(\d+)|(:)([^"\s<>][^\s<>]*?|"[^"]+?"))(?=(?=[[:punct:]]\W)|,|\s|\]|<|$)}) do |m|
  552. leading, esc, project_prefix, project_identifier, prefix, sep, identifier = $1, $2, $3, $4, $5, $7 || $9, $8 || $10
  553. link = nil
  554. if project_identifier
  555. project = Project.visible.find_by_identifier(project_identifier)
  556. end
  557. if esc.nil?
  558. if prefix.nil? && sep == 'r'
  559. # project.changesets.visible raises an SQL error because of a double join on repositories
  560. if project && project.repository && (changeset = Changeset.visible.find_by_repository_id_and_revision(project.repository.id, identifier))
  561. link = link_to("#{project_prefix}r#{identifier}", {:only_path => only_path, :controller => 'repositories', :action => 'revision', :id => project, :rev => changeset.revision},
  562. :class => 'changeset',
  563. :title => truncate_single_line(changeset.comments, :length => 100))
  564. end
  565. elsif sep == '#'
  566. oid = identifier.to_i
  567. case prefix
  568. when nil
  569. if issue = Issue.visible.find_by_id(oid, :include => :status)
  570. link = link_to("##{oid}", {:only_path => only_path, :controller => 'issues', :action => 'show', :id => oid},
  571. :class => issue.css_classes,
  572. :title => "#{truncate(issue.subject, :length => 100)} (#{issue.status.name})")
  573. end
  574. when 'document'
  575. if document = Document.visible.find_by_id(oid)
  576. link = link_to h(document.title), {:only_path => only_path, :controller => 'documents', :action => 'show', :id => document},
  577. :class => 'document'
  578. end
  579. when 'version'
  580. if version = Version.visible.find_by_id(oid)
  581. link = link_to h(version.name), {:only_path => only_path, :controller => 'versions', :action => 'show', :id => version},
  582. :class => 'version'
  583. end
  584. when 'message'
  585. if message = Message.visible.find_by_id(oid, :include => :parent)
  586. link = link_to_message(message, {:only_path => only_path}, :class => 'message')
  587. end
  588. when 'project'
  589. if p = Project.visible.find_by_id(oid)
  590. link = link_to_project(p, {:only_path => only_path}, :class => 'project')
  591. end
  592. end
  593. elsif sep == ':'
  594. # removes the double quotes if any
  595. name = identifier.gsub(%r{^"(.*)"$}, "\\1")
  596. case prefix
  597. when 'document'
  598. if project && document = project.documents.visible.find_by_title(name)
  599. link = link_to h(document.title), {:only_path => only_path, :controller => 'documents', :action => 'show', :id => document},
  600. :class => 'document'
  601. end
  602. when 'version'
  603. if project && version = project.versions.visible.find_by_name(name)
  604. link = link_to h(version.name), {:only_path => only_path, :controller => 'versions', :action => 'show', :id => version},
  605. :class => 'version'
  606. end
  607. when 'commit'
  608. if project && project.repository && (changeset = Changeset.visible.find(:first, :conditions => ["repository_id = ? AND scmid LIKE ?", project.repository.id, "#{name}%"]))
  609. link = link_to h("#{project_prefix}#{name}"), {:only_path => only_path, :controller => 'repositories', :action => 'revision', :id => project, :rev => changeset.identifier},
  610. :class => 'changeset',
  611. :title => truncate_single_line(changeset.comments, :length => 100)
  612. end
  613. when 'source', 'export'
  614. if project && project.repository && User.current.allowed_to?(:browse_repository, project)
  615. name =~ %r{^[/\\]*(.*?)(@([0-9a-f]+))?(#(L\d+))?$}
  616. path, rev, anchor = $1, $3, $5
  617. link = link_to h("#{project_prefix}#{prefix}:#{name}"), {:controller => 'repositories', :action => 'entry', :id => project,
  618. :path => to_path_param(path),
  619. :rev => rev,
  620. :anchor => anchor,
  621. :format => (prefix == 'export' ? 'raw' : nil)},
  622. :class => (prefix == 'export' ? 'source download' : 'source')
  623. end
  624. when 'attachment'
  625. attachments = options[:attachments] || (obj && obj.respond_to?(:attachments) ? obj.attachments : nil)
  626. if attachments && attachment = attachments.detect {|a| a.filename == name }
  627. link = link_to h(attachment.filename), {:only_path => only_path, :controller => 'attachments', :action => 'download', :id => attachment},
  628. :class => 'attachment'
  629. end
  630. when 'project'
  631. if p = Project.visible.find(:first, :conditions => ["identifier = :s OR LOWER(name) = :s", {:s => name.downcase}])
  632. link = link_to_project(p, {:only_path => only_path}, :class => 'project')
  633. end
  634. end
  635. end
  636. end
  637. leading + (link || "#{project_prefix}#{prefix}#{sep}#{identifier}")
  638. end
  639. end
  640. HEADING_RE = /<h(1|2|3|4)( [^>]+)?>(.+?)<\/h(1|2|3|4)>/i unless const_defined?(:HEADING_RE)
  641. # Headings and TOC
  642. # Adds ids and links to headings unless options[:headings] is set to false
  643. def parse_headings(text, project, obj, attr, only_path, options)
  644. return if options[:headings] == false
  645. text.gsub!(HEADING_RE) do
  646. level, attrs, content = $1.to_i, $2, $3
  647. item = strip_tags(content).strip
  648. anchor = item.gsub(%r{[^\w\s\-]}, '').gsub(%r{\s+(\-+\s*)?}, '-')
  649. @parsed_headings << [level, anchor, item]
  650. "<h#{level} #{attrs} id=\"#{anchor}\">#{content}<a href=\"##{anchor}\" class=\"wiki-anchor\">&para;</a></h#{level}>"
  651. end
  652. end
  653. TOC_RE = /<p>\{\{([<>]?)toc\}\}<\/p>/i unless const_defined?(:TOC_RE)
  654. # Renders the TOC with given headings
  655. def replace_toc(text, headings)
  656. text.gsub!(TOC_RE) do
  657. if headings.empty?
  658. ''
  659. else
  660. div_class = 'toc'
  661. div_class << ' right' if $1 == '>'
  662. div_class << ' left' if $1 == '<'
  663. out = "<ul class=\"#{div_class}\"><li>"
  664. root = headings.map(&:first).min
  665. current = root
  666. started = false
  667. headings.each do |level, anchor, item|
  668. if level > current
  669. out << '<ul><li>' * (level - current)
  670. elsif level < current
  671. out << "</li></ul>\n" * (current - level) + "</li><li>"
  672. elsif started
  673. out << '</li><li>'
  674. end
  675. out << "<a href=\"##{anchor}\">#{item}</a>"
  676. current = level
  677. started = true
  678. end
  679. out << '</li></ul>' * (current - root)
  680. out << '</li></ul>'
  681. end
  682. end
  683. end
  684. # Same as Rails' simple_format helper without using paragraphs
  685. def simple_format_without_paragraph(text)
  686. text.to_s.
  687. gsub(/\r\n?/, "\n"). # \r\n and \r -> \n
  688. gsub(/\n\n+/, "<br /><br />"). # 2+ newline -> 2 br
  689. gsub(/([^\n]\n)(?=[^\n])/, '\1<br />') # 1 newline -> br
  690. end
  691. def lang_options_for_select(blank=true)
  692. (blank ? [["(auto)", ""]] : []) +
  693. valid_languages.collect{|lang| [ ll(lang.to_s, :general_lang_name), lang.to_s]}.sort{|x,y| x.last <=> y.last }
  694. end
  695. def label_tag_for(name, option_tags = nil, options = {})
  696. label_text = l(("field_"+field.to_s.gsub(/\_id$/, "")).to_sym) + (options.delete(:required) ? @template.content_tag("span", " *", :class => "required"): "")
  697. content_tag("label", label_text)
  698. end
  699. def labelled_tabular_form_for(name, object, options, &proc)
  700. options[:html] ||= {}
  701. options[:html][:class] = 'tabular' unless options[:html].has_key?(:class)
  702. form_for(name, object, options.merge({ :builder => TabularFormBuilder, :lang => current_language}), &proc)
  703. end
  704. def back_url_hidden_field_tag
  705. back_url = params[:back_url] || request.env['HTTP_REFERER']
  706. back_url = CGI.unescape(back_url.to_s)
  707. hidden_field_tag('back_url', CGI.escape(back_url)) unless back_url.blank?
  708. end
  709. def check_all_links(form_name)
  710. link_to_function(l(:button_check_all), "checkAll('#{form_name}', true)") +
  711. " | " +
  712. link_to_function(l(:button_uncheck_all), "checkAll('#{form_name}', false)")
  713. end
  714. def progress_bar(pcts, options={})
  715. pcts = [pcts, pcts] unless pcts.is_a?(Array)
  716. pcts = pcts.collect(&:round)
  717. pcts[1] = pcts[1] - pcts[0]
  718. pcts << (100 - pcts[1] - pcts[0])
  719. width = options[:width] || '100px;'
  720. legend = options[:legend] || ''
  721. content_tag('table',
  722. content_tag('tr',
  723. (pcts[0] > 0 ? content_tag('td', '', :style => "width: #{pcts[0]}%;", :class => 'closed') : '') +
  724. (pcts[1] > 0 ? content_tag('td', '', :style => "width: #{pcts[1]}%;", :class => 'done') : '') +
  725. (pcts[2] > 0 ? content_tag('td', '', :style => "width: #{pcts[2]}%;", :class => 'todo') : '')
  726. ), :class => 'progress', :style => "width: #{width};") +
  727. content_tag('p', legend, :class => 'pourcent')
  728. end
  729. def checked_image(checked=true)
  730. if checked
  731. image_tag 'toggle_check.png'
  732. end
  733. end
  734. def context_menu(url)
  735. unless @context_menu_included
  736. content_for :header_tags do
  737. javascript_include_tag('context_menu') +
  738. stylesheet_link_tag('context_menu')
  739. end
  740. if l(:direction) == 'rtl'
  741. content_for :header_tags do
  742. stylesheet_link_tag('context_menu_rtl')
  743. end
  744. end
  745. @context_menu_included = true
  746. end
  747. javascript_tag "new ContextMenu('#{ url_for(url) }')"
  748. end
  749. def context_menu_link(name, url, options={})
  750. options[:class] ||= ''
  751. if options.delete(:selected)
  752. options[:class] << ' icon-checked disabled'
  753. options[:disabled] = true
  754. end
  755. if options.delete(:disabled)
  756. options.delete(:method)
  757. options.delete(:confirm)
  758. options.delete(:onclick)
  759. options[:class] << ' disabled'
  760. url = '#'
  761. end
  762. link_to name, url, options
  763. end
  764. def calendar_for(field_id)
  765. include_calendar_headers_tags
  766. image_tag("calendar.png", {:id => "#{field_id}_trigger",:class => "calendar-trigger"}) +
  767. javascript_tag("Calendar.setup({inputField : '#{field_id}', ifFormat : '%Y-%m-%d', button : '#{field_id}_trigger' });")
  768. end
  769. def include_calendar_headers_tags
  770. unless @calendar_headers_tags_included
  771. @calendar_headers_tags_included = true
  772. content_for :header_tags do
  773. start_of_week = case Setting.start_of_week.to_i
  774. when 1
  775. 'Calendar._FD = 1;' # Monday
  776. when 7
  777. 'Calendar._FD = 0;' # Sunday
  778. else
  779. '' # use language
  780. end
  781. javascript_include_tag('calendar/calendar') +
  782. javascript_include_tag("calendar/lang/calendar-#{current_language.to_s.downcase}.js") +
  783. javascript_tag(start_of_week) +
  784. javascript_include_tag('calendar/calendar-setup') +
  785. stylesheet_link_tag('calendar')
  786. end
  787. end
  788. end
  789. def content_for(name, content = nil, &block)
  790. @has_content ||= {}
  791. @has_content[name] = true
  792. super(name, content, &block)
  793. end
  794. def has_content?(name)
  795. (@has_content && @has_content[name]) || false
  796. end
  797. # Returns the avatar image tag for the given +user+ if avatars are enabled
  798. # +user+ can be a User or a string that will be scanned for an email address (eg. 'joe <joe@foo.bar>')
  799. def avatar(user, options = { })
  800. if Setting.gravatar_enabled?
  801. options.merge!({:ssl => (defined?(request) && request.ssl?), :default => Setting.gravatar_default})
  802. email = nil
  803. if user.respond_to?(:mail)
  804. email = user.mail
  805. elsif user.to_s =~ %r{<(.+?)>}
  806. email = $1
  807. end
  808. return gravatar(email.to_s.downcase, options) unless email.blank? rescue nil
  809. else
  810. ''
  811. end
  812. end
  813. def favicon
  814. "<link rel='shortcut icon' href='#{image_path('/favicon.ico')}' />"
  815. end
  816. # Add a HTML meta tag to control robots (web spiders)
  817. #
  818. # @param [optional, String] content the content of the ROBOTS tag.
  819. # defaults to no index, follow, and no archive
  820. def robot_exclusion_tag(content="NOINDEX,FOLLOW,NOARCHIVE")
  821. "<meta name='ROBOTS' content='#{h(content)}' />"
  822. end
  823. # Returns true if arg is expected in the API response
  824. def include_in_api_response?(arg)
  825. unless @included_in_api_response
  826. param = params[:include]
  827. @included_in_api_response = param.is_a?(Array) ? param.collect(&:to_s) : param.to_s.split(',')
  828. @included_in_api_response.collect!(&:strip)
  829. end
  830. @included_in_api_response.include?(arg.to_s)
  831. end
  832. # Returns options or nil if nometa param or X-ChiliProject-Nometa header
  833. # was set in the request
  834. def api_meta(options)
  835. if params[:nometa].present? || request.headers['X-ChiliProject-Nometa']
  836. # compatibility mode for activeresource clients that raise
  837. # an error when unserializing an array with attributes
  838. nil
  839. else
  840. options
  841. end
  842. end
  843. private
  844. def wiki_helper
  845. helper = Redmine::WikiFormatting.helper_for(Setting.text_formatting)
  846. extend helper
  847. return self
  848. end
  849. def link_to_remote_content_update(text, url_params)
  850. link_to_remote(text,
  851. {:url => url_params, :method => :get, :update => 'content', :complete => 'window.scrollTo(0,0)'},
  852. {:href => url_for(:params => url_params)}
  853. )
  854. end
  855. end