You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

application_helper.rb 22KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517
  1. # redMine - project management software
  2. # Copyright (C) 2006-2007 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. module ApplicationHelper
  18. include Redmine::WikiFormatting::Macros::Definitions
  19. def current_role
  20. @current_role ||= User.current.role_for_project(@project)
  21. end
  22. # Return true if user is authorized for controller/action, otherwise false
  23. def authorize_for(controller, action)
  24. User.current.allowed_to?({:controller => controller, :action => action}, @project)
  25. end
  26. # Display a link if user is authorized
  27. def link_to_if_authorized(name, options = {}, html_options = nil, *parameters_for_method_reference)
  28. link_to(name, options, html_options, *parameters_for_method_reference) if authorize_for(options[:controller] || params[:controller], options[:action])
  29. end
  30. # Display a link to user's account page
  31. def link_to_user(user)
  32. user ? link_to(user, :controller => 'account', :action => 'show', :id => user) : 'Anonymous'
  33. end
  34. def link_to_issue(issue, options={})
  35. link_to "#{issue.tracker.name} ##{issue.id}", {:controller => "issues", :action => "show", :id => issue}, options
  36. end
  37. def toggle_link(name, id, options={})
  38. onclick = "Element.toggle('#{id}'); "
  39. onclick << (options[:focus] ? "Form.Element.focus('#{options[:focus]}'); " : "this.blur(); ")
  40. onclick << "return false;"
  41. link_to(name, "#", :onclick => onclick)
  42. end
  43. def show_and_goto_link(name, id, options={})
  44. onclick = "Element.show('#{id}'); "
  45. onclick << (options[:focus] ? "Form.Element.focus('#{options[:focus]}'); " : "this.blur(); ")
  46. onclick << "Element.scrollTo('#{id}'); "
  47. onclick << "return false;"
  48. link_to(name, "#", options.merge(:onclick => onclick))
  49. end
  50. def image_to_function(name, function, html_options = {})
  51. html_options.symbolize_keys!
  52. tag(:input, html_options.merge({
  53. :type => "image", :src => image_path(name),
  54. :onclick => (html_options[:onclick] ? "#{html_options[:onclick]}; " : "") + "#{function};"
  55. }))
  56. end
  57. def prompt_to_remote(name, text, param, url, html_options = {})
  58. html_options[:onclick] = "promptToRemote('#{text}', '#{param}', '#{url_for(url)}'); return false;"
  59. link_to name, {}, html_options
  60. end
  61. def format_date(date)
  62. return nil unless date
  63. # "Setting.date_format.size < 2" is a temporary fix (content of date_format setting changed)
  64. @date_format ||= (Setting.date_format.blank? || Setting.date_format.size < 2 ? l(:general_fmt_date) : Setting.date_format)
  65. date.strftime(@date_format)
  66. end
  67. def format_time(time, include_date = true)
  68. return nil unless time
  69. time = time.to_time if time.is_a?(String)
  70. zone = User.current.time_zone
  71. if time.utc?
  72. local = zone ? zone.adjust(time) : time.getlocal
  73. else
  74. local = zone ? zone.adjust(time.getutc) : time
  75. end
  76. @date_format ||= (Setting.date_format.blank? || Setting.date_format.size < 2 ? l(:general_fmt_date) : Setting.date_format)
  77. @time_format ||= (Setting.time_format.blank? ? l(:general_fmt_time) : Setting.time_format)
  78. include_date ? local.strftime("#{@date_format} #{@time_format}") : local.strftime(@time_format)
  79. end
  80. # Truncates and returns the string as a single line
  81. def truncate_single_line(string, *args)
  82. truncate(string, *args).gsub(%r{[\r\n]+}m, ' ')
  83. end
  84. def html_hours(text)
  85. text.gsub(%r{(\d+)\.(\d+)}, '<span class="hours hours-int">\1</span><span class="hours hours-dec">.\2</span>')
  86. end
  87. def authoring(created, author)
  88. time_tag = content_tag('acronym', distance_of_time_in_words(Time.now, created), :title => format_time(created))
  89. l(:label_added_time_by, author || 'Anonymous', time_tag)
  90. end
  91. def l_or_humanize(s)
  92. l_has_string?("label_#{s}".to_sym) ? l("label_#{s}".to_sym) : s.to_s.humanize
  93. end
  94. def day_name(day)
  95. l(:general_day_names).split(',')[day-1]
  96. end
  97. def month_name(month)
  98. l(:actionview_datehelper_select_month_names).split(',')[month-1]
  99. end
  100. def pagination_links_full(paginator, count=nil, options={})
  101. page_param = options.delete(:page_param) || :page
  102. url_param = params.dup
  103. # don't reuse params if filters are present
  104. url_param.clear if url_param.has_key?(:set_filter)
  105. html = ''
  106. html << link_to_remote(('&#171; ' + l(:label_previous)),
  107. {:update => 'content',
  108. :url => url_param.merge(page_param => paginator.current.previous),
  109. :complete => 'window.scrollTo(0,0)'},
  110. {:href => url_for(:params => url_param.merge(page_param => paginator.current.previous))}) + ' ' if paginator.current.previous
  111. html << (pagination_links_each(paginator, options) do |n|
  112. link_to_remote(n.to_s,
  113. {:url => {:params => url_param.merge(page_param => n)},
  114. :update => 'content',
  115. :complete => 'window.scrollTo(0,0)'},
  116. {:href => url_for(:params => url_param.merge(page_param => n))})
  117. end || '')
  118. html << ' ' + link_to_remote((l(:label_next) + ' &#187;'),
  119. {:update => 'content',
  120. :url => url_param.merge(page_param => paginator.current.next),
  121. :complete => 'window.scrollTo(0,0)'},
  122. {:href => url_for(:params => url_param.merge(page_param => paginator.current.next))}) if paginator.current.next
  123. unless count.nil?
  124. html << [" (#{paginator.current.first_item}-#{paginator.current.last_item}/#{count})", per_page_links(paginator.items_per_page)].compact.join(' | ')
  125. end
  126. html
  127. end
  128. def per_page_links(selected=nil)
  129. url_param = params.dup
  130. url_param.clear if url_param.has_key?(:set_filter)
  131. links = Setting.per_page_options_array.collect do |n|
  132. n == selected ? n : link_to_remote(n, {:update => "content", :url => params.dup.merge(:per_page => n)},
  133. {:href => url_for(url_param.merge(:per_page => n))})
  134. end
  135. links.size > 1 ? l(:label_display_per_page, links.join(', ')) : nil
  136. end
  137. def breadcrumb(*args)
  138. content_tag('p', args.join(' &#187; ') + ' &#187; ', :class => 'breadcrumb')
  139. end
  140. def html_title(*args)
  141. if args.empty?
  142. title = []
  143. title << @project.name if @project
  144. title += @html_title if @html_title
  145. title << Setting.app_title
  146. title.compact.join(' - ')
  147. else
  148. @html_title ||= []
  149. @html_title += args
  150. end
  151. end
  152. def accesskey(s)
  153. Redmine::AccessKeys.key_for s
  154. end
  155. # Formats text according to system settings.
  156. # 2 ways to call this method:
  157. # * with a String: textilizable(text, options)
  158. # * with an object and one of its attribute: textilizable(issue, :description, options)
  159. def textilizable(*args)
  160. options = args.last.is_a?(Hash) ? args.pop : {}
  161. case args.size
  162. when 1
  163. obj = nil
  164. text = args.shift
  165. when 2
  166. obj = args.shift
  167. text = obj.send(args.shift).to_s
  168. else
  169. raise ArgumentError, 'invalid arguments to textilizable'
  170. end
  171. return '' if text.blank?
  172. only_path = options.delete(:only_path) == false ? false : true
  173. # when using an image link, try to use an attachment, if possible
  174. attachments = options[:attachments] || (obj && obj.respond_to?(:attachments) ? obj.attachments : nil)
  175. if attachments
  176. text = text.gsub(/!((\<|\=|\>)?(\([^\)]+\))?(\[[^\]]+\])?(\{[^\}]+\})?)(\S+\.(gif|jpg|jpeg|png))!/) do |m|
  177. style = $1
  178. filename = $6
  179. rf = Regexp.new(filename, Regexp::IGNORECASE)
  180. # search for the picture in attachments
  181. if found = attachments.detect { |att| att.filename =~ rf }
  182. image_url = url_for :only_path => only_path, :controller => 'attachments', :action => 'download', :id => found
  183. desc = found.description.to_s.gsub(/^([^\(\)]*).*$/, "\\1")
  184. alt = desc.blank? ? nil : "(#{desc})"
  185. "!#{style}#{image_url}#{alt}!"
  186. else
  187. "!#{style}#{filename}!"
  188. end
  189. end
  190. end
  191. text = (Setting.text_formatting == 'textile') ?
  192. Redmine::WikiFormatting.to_html(text) { |macro, args| exec_macro(macro, obj, args) } :
  193. simple_format(auto_link(h(text)))
  194. # different methods for formatting wiki links
  195. case options[:wiki_links]
  196. when :local
  197. # used for local links to html files
  198. format_wiki_link = Proc.new {|project, title| "#{title}.html" }
  199. when :anchor
  200. # used for single-file wiki export
  201. format_wiki_link = Proc.new {|project, title| "##{title}" }
  202. else
  203. format_wiki_link = Proc.new {|project, title| url_for(:only_path => only_path, :controller => 'wiki', :action => 'index', :id => project, :page => title) }
  204. end
  205. project = options[:project] || @project || (obj && obj.respond_to?(:project) ? obj.project : nil)
  206. # Wiki links
  207. #
  208. # Examples:
  209. # [[mypage]]
  210. # [[mypage|mytext]]
  211. # wiki links can refer other project wikis, using project name or identifier:
  212. # [[project:]] -> wiki starting page
  213. # [[project:|mytext]]
  214. # [[project:mypage]]
  215. # [[project:mypage|mytext]]
  216. text = text.gsub(/(!)?(\[\[([^\]\n\|]+)(\|([^\]\n\|]+))?\]\])/) do |m|
  217. link_project = project
  218. esc, all, page, title = $1, $2, $3, $5
  219. if esc.nil?
  220. if page =~ /^([^\:]+)\:(.*)$/
  221. link_project = Project.find_by_name($1) || Project.find_by_identifier($1)
  222. page = $2
  223. title ||= $1 if page.blank?
  224. end
  225. if link_project && link_project.wiki
  226. # check if page exists
  227. wiki_page = link_project.wiki.find_page(page)
  228. link_to((title || page), format_wiki_link.call(link_project, Wiki.titleize(page)),
  229. :class => ('wiki-page' + (wiki_page ? '' : ' new')))
  230. else
  231. # project or wiki doesn't exist
  232. title || page
  233. end
  234. else
  235. all
  236. end
  237. end
  238. # Redmine links
  239. #
  240. # Examples:
  241. # Issues:
  242. # #52 -> Link to issue #52
  243. # Changesets:
  244. # r52 -> Link to revision 52
  245. # commit:a85130f -> Link to scmid starting with a85130f
  246. # Documents:
  247. # document#17 -> Link to document with id 17
  248. # document:Greetings -> Link to the document with title "Greetings"
  249. # document:"Some document" -> Link to the document with title "Some document"
  250. # Versions:
  251. # version#3 -> Link to version with id 3
  252. # version:1.0.0 -> Link to version named "1.0.0"
  253. # version:"1.0 beta 2" -> Link to version named "1.0 beta 2"
  254. # Attachments:
  255. # attachment:file.zip -> Link to the attachment of the current object named file.zip
  256. # Source files:
  257. # source:some/file -> Link to the file located at /some/file in the project's repository
  258. # source:some/file@52 -> Link to the file's revision 52
  259. # source:some/file#L120 -> Link to line 120 of the file
  260. # source:some/file@52#L120 -> Link to line 120 of the file's revision 52
  261. # export:some/file -> Force the download of the file
  262. text = text.gsub(%r{([\s\(,\-\>]|^)(!)?(attachment|document|version|commit|source|export)?((#|r)(\d+)|(:)([^"\s<>][^\s<>]*|"[^"]+"))(?=[[:punct:]]|\s|<|$)}) do |m|
  263. leading, esc, prefix, sep, oid = $1, $2, $3, $5 || $7, $6 || $8
  264. link = nil
  265. if esc.nil?
  266. if prefix.nil? && sep == 'r'
  267. if project && (changeset = project.changesets.find_by_revision(oid))
  268. link = link_to("r#{oid}", {:only_path => only_path, :controller => 'repositories', :action => 'revision', :id => project, :rev => oid},
  269. :class => 'changeset',
  270. :title => truncate_single_line(changeset.comments, 100))
  271. end
  272. elsif sep == '#'
  273. oid = oid.to_i
  274. case prefix
  275. when nil
  276. if issue = Issue.find_by_id(oid, :include => [:project, :status], :conditions => Project.visible_by(User.current))
  277. link = link_to("##{oid}", {:only_path => only_path, :controller => 'issues', :action => 'show', :id => oid},
  278. :class => (issue.closed? ? 'issue closed' : 'issue'),
  279. :title => "#{truncate(issue.subject, 100)} (#{issue.status.name})")
  280. link = content_tag('del', link) if issue.closed?
  281. end
  282. when 'document'
  283. if document = Document.find_by_id(oid, :include => [:project], :conditions => Project.visible_by(User.current))
  284. link = link_to h(document.title), {:only_path => only_path, :controller => 'documents', :action => 'show', :id => document},
  285. :class => 'document'
  286. end
  287. when 'version'
  288. if version = Version.find_by_id(oid, :include => [:project], :conditions => Project.visible_by(User.current))
  289. link = link_to h(version.name), {:only_path => only_path, :controller => 'versions', :action => 'show', :id => version},
  290. :class => 'version'
  291. end
  292. end
  293. elsif sep == ':'
  294. # removes the double quotes if any
  295. name = oid.gsub(%r{^"(.*)"$}, "\\1")
  296. case prefix
  297. when 'document'
  298. if project && document = project.documents.find_by_title(name)
  299. link = link_to h(document.title), {:only_path => only_path, :controller => 'documents', :action => 'show', :id => document},
  300. :class => 'document'
  301. end
  302. when 'version'
  303. if project && version = project.versions.find_by_name(name)
  304. link = link_to h(version.name), {:only_path => only_path, :controller => 'versions', :action => 'show', :id => version},
  305. :class => 'version'
  306. end
  307. when 'commit'
  308. if project && (changeset = project.changesets.find(:first, :conditions => ["scmid LIKE ?", "#{name}%"]))
  309. link = link_to h("#{name}"), {:only_path => only_path, :controller => 'repositories', :action => 'revision', :id => project, :rev => changeset.revision},
  310. :class => 'changeset',
  311. :title => truncate_single_line(changeset.comments, 100)
  312. end
  313. when 'source', 'export'
  314. if project && project.repository
  315. name =~ %r{^[/\\]*(.*?)(@([0-9a-f]+))?(#(L\d+))?$}
  316. path, rev, anchor = $1, $3, $5
  317. link = link_to h("#{prefix}:#{name}"), {:controller => 'repositories', :action => 'entry', :id => project, :path => path,
  318. :rev => rev,
  319. :anchor => anchor,
  320. :format => (prefix == 'export' ? 'raw' : nil)},
  321. :class => (prefix == 'export' ? 'source download' : 'source')
  322. end
  323. when 'attachment'
  324. if attachments && attachment = attachments.detect {|a| a.filename == name }
  325. link = link_to h(attachment.filename), {:only_path => only_path, :controller => 'attachments', :action => 'download', :id => attachment},
  326. :class => 'attachment'
  327. end
  328. end
  329. end
  330. end
  331. leading + (link || "#{prefix}#{sep}#{oid}")
  332. end
  333. text
  334. end
  335. # Same as Rails' simple_format helper without using paragraphs
  336. def simple_format_without_paragraph(text)
  337. text.to_s.
  338. gsub(/\r\n?/, "\n"). # \r\n and \r -> \n
  339. gsub(/\n\n+/, "<br /><br />"). # 2+ newline -> 2 br
  340. gsub(/([^\n]\n)(?=[^\n])/, '\1<br />') # 1 newline -> br
  341. end
  342. def error_messages_for(object_name, options = {})
  343. options = options.symbolize_keys
  344. object = instance_variable_get("@#{object_name}")
  345. if object && !object.errors.empty?
  346. # build full_messages here with controller current language
  347. full_messages = []
  348. object.errors.each do |attr, msg|
  349. next if msg.nil?
  350. msg = msg.first if msg.is_a? Array
  351. if attr == "base"
  352. full_messages << l(msg)
  353. else
  354. full_messages << "&#171; " + (l_has_string?("field_" + attr) ? l("field_" + attr) : object.class.human_attribute_name(attr)) + " &#187; " + l(msg) unless attr == "custom_values"
  355. end
  356. end
  357. # retrieve custom values error messages
  358. if object.errors[:custom_values]
  359. object.custom_values.each do |v|
  360. v.errors.each do |attr, msg|
  361. next if msg.nil?
  362. msg = msg.first if msg.is_a? Array
  363. full_messages << "&#171; " + v.custom_field.name + " &#187; " + l(msg)
  364. end
  365. end
  366. end
  367. content_tag("div",
  368. content_tag(
  369. options[:header_tag] || "span", lwr(:gui_validation_error, full_messages.length) + ":"
  370. ) +
  371. content_tag("ul", full_messages.collect { |msg| content_tag("li", msg) }),
  372. "id" => options[:id] || "errorExplanation", "class" => options[:class] || "errorExplanation"
  373. )
  374. else
  375. ""
  376. end
  377. end
  378. def lang_options_for_select(blank=true)
  379. (blank ? [["(auto)", ""]] : []) +
  380. GLoc.valid_languages.collect{|lang| [ ll(lang.to_s, :general_lang_name), lang.to_s]}.sort{|x,y| x.last <=> y.last }
  381. end
  382. def label_tag_for(name, option_tags = nil, options = {})
  383. label_text = l(("field_"+field.to_s.gsub(/\_id$/, "")).to_sym) + (options.delete(:required) ? @template.content_tag("span", " *", :class => "required"): "")
  384. content_tag("label", label_text)
  385. end
  386. def labelled_tabular_form_for(name, object, options, &proc)
  387. options[:html] ||= {}
  388. options[:html][:class] = 'tabular' unless options[:html].has_key?(:class)
  389. form_for(name, object, options.merge({ :builder => TabularFormBuilder, :lang => current_language}), &proc)
  390. end
  391. def back_url_hidden_field_tag
  392. hidden_field_tag 'back_url', (params[:back_url] || request.env['HTTP_REFERER'])
  393. end
  394. def check_all_links(form_name)
  395. link_to_function(l(:button_check_all), "checkAll('#{form_name}', true)") +
  396. " | " +
  397. link_to_function(l(:button_uncheck_all), "checkAll('#{form_name}', false)")
  398. end
  399. def progress_bar(pcts, options={})
  400. pcts = [pcts, pcts] unless pcts.is_a?(Array)
  401. pcts[1] = pcts[1] - pcts[0]
  402. pcts << (100 - pcts[1] - pcts[0])
  403. width = options[:width] || '100px;'
  404. legend = options[:legend] || ''
  405. content_tag('table',
  406. content_tag('tr',
  407. (pcts[0] > 0 ? content_tag('td', '', :width => "#{pcts[0].floor}%;", :class => 'closed') : '') +
  408. (pcts[1] > 0 ? content_tag('td', '', :width => "#{pcts[1].floor}%;", :class => 'done') : '') +
  409. (pcts[2] > 0 ? content_tag('td', '', :width => "#{pcts[2].floor}%;", :class => 'todo') : '')
  410. ), :class => 'progress', :style => "width: #{width};") +
  411. content_tag('p', legend, :class => 'pourcent')
  412. end
  413. def context_menu_link(name, url, options={})
  414. options[:class] ||= ''
  415. if options.delete(:selected)
  416. options[:class] << ' icon-checked disabled'
  417. options[:disabled] = true
  418. end
  419. if options.delete(:disabled)
  420. options.delete(:method)
  421. options.delete(:confirm)
  422. options.delete(:onclick)
  423. options[:class] << ' disabled'
  424. url = '#'
  425. end
  426. link_to name, url, options
  427. end
  428. def calendar_for(field_id)
  429. include_calendar_headers_tags
  430. image_tag("calendar.png", {:id => "#{field_id}_trigger",:class => "calendar-trigger"}) +
  431. javascript_tag("Calendar.setup({inputField : '#{field_id}', ifFormat : '%Y-%m-%d', button : '#{field_id}_trigger' });")
  432. end
  433. def include_calendar_headers_tags
  434. unless @calendar_headers_tags_included
  435. @calendar_headers_tags_included = true
  436. content_for :header_tags do
  437. javascript_include_tag('calendar/calendar') +
  438. javascript_include_tag("calendar/lang/calendar-#{current_language}.js") +
  439. javascript_include_tag('calendar/calendar-setup') +
  440. stylesheet_link_tag('calendar')
  441. end
  442. end
  443. end
  444. def wikitoolbar_for(field_id)
  445. return '' unless Setting.text_formatting == 'textile'
  446. help_link = l(:setting_text_formatting) + ': ' +
  447. link_to(l(:label_help), compute_public_path('wiki_syntax', 'help', 'html'),
  448. :onclick => "window.open(\"#{ compute_public_path('wiki_syntax', 'help', 'html') }\", \"\", \"resizable=yes, location=no, width=300, height=640, menubar=no, status=no, scrollbars=yes\"); return false;")
  449. javascript_include_tag('jstoolbar/jstoolbar') +
  450. javascript_include_tag("jstoolbar/lang/jstoolbar-#{current_language}") +
  451. javascript_tag("var toolbar = new jsToolBar($('#{field_id}')); toolbar.setHelpLink('#{help_link}'); toolbar.draw();")
  452. end
  453. def content_for(name, content = nil, &block)
  454. @has_content ||= {}
  455. @has_content[name] = true
  456. super(name, content, &block)
  457. end
  458. def has_content?(name)
  459. (@has_content && @has_content[name]) || false
  460. end
  461. end