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 36KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966
  1. # Redmine - project management software
  2. # Copyright (C) 2006-2011 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 "#{h(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(h(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, options={})
  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 => (options[:timestamp] && page.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, options) 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.html_safe
  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. return unless User.current.logged?
  201. projects = User.current.memberships.collect(&:project).compact.uniq
  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.html_safe
  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.html_safe
  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.html_safe
  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.html_safe
  263. end
  264. # Returns a string for users/groups option tags
  265. def principals_options_for_select(collection, selected=nil)
  266. s = ''
  267. groups = ''
  268. collection.sort.each do |element|
  269. selected_attribute = ' selected="selected"' if option_value_selected?(element, selected)
  270. (element.is_a?(Group) ? groups : s) << %(<option value="#{element.id}"#{selected_attribute}>#{h element.name}</option>)
  271. end
  272. unless groups.empty?
  273. s << %(<optgroup label="#{h(l(:label_group_plural))}">#{groups}</optgroup>)
  274. end
  275. s
  276. end
  277. # Truncates and returns the string as a single line
  278. def truncate_single_line(string, *args)
  279. truncate(string.to_s, *args).gsub(%r{[\r\n]+}m, ' ')
  280. end
  281. # Truncates at line break after 250 characters or options[:length]
  282. def truncate_lines(string, options={})
  283. length = options[:length] || 250
  284. if string.to_s =~ /\A(.{#{length}}.*?)$/m
  285. "#{$1}..."
  286. else
  287. string
  288. end
  289. end
  290. def html_hours(text)
  291. text.gsub(%r{(\d+)\.(\d+)}, '<span class="hours hours-int">\1</span><span class="hours hours-dec">.\2</span>').html_safe
  292. end
  293. def authoring(created, author, options={})
  294. l(options[:label] || :label_added_time_by, :author => link_to_user(author), :age => time_tag(created)).html_safe
  295. end
  296. def time_tag(time)
  297. text = distance_of_time_in_words(Time.now, time)
  298. if @project
  299. link_to(text, {:controller => 'activities', :action => 'index', :id => @project, :from => time.to_date}, :title => format_time(time))
  300. else
  301. content_tag('acronym', text, :title => format_time(time))
  302. end
  303. end
  304. def syntax_highlight(name, content)
  305. Redmine::SyntaxHighlighting.highlight_by_filename(content, name)
  306. end
  307. def to_path_param(path)
  308. path.to_s.split(%r{[/\\]}).select {|p| !p.blank?}
  309. end
  310. def pagination_links_full(paginator, count=nil, options={})
  311. page_param = options.delete(:page_param) || :page
  312. per_page_links = options.delete(:per_page_links)
  313. url_param = params.dup
  314. html = ''
  315. if paginator.current.previous
  316. # \xc2\xab(utf-8) = &#171;
  317. html << link_to_content_update(
  318. "\xc2\xab " + l(:label_previous),
  319. url_param.merge(page_param => paginator.current.previous)) + ' '
  320. end
  321. html << (pagination_links_each(paginator, options) do |n|
  322. link_to_content_update(n.to_s, url_param.merge(page_param => n))
  323. end || '')
  324. if paginator.current.next
  325. # \xc2\xbb(utf-8) = &#187;
  326. html << ' ' + link_to_content_update(
  327. (l(:label_next) + " \xc2\xbb"),
  328. url_param.merge(page_param => paginator.current.next))
  329. end
  330. unless count.nil?
  331. html << " (#{paginator.current.first_item}-#{paginator.current.last_item}/#{count})"
  332. if per_page_links != false && links = per_page_links(paginator.items_per_page)
  333. html << " | #{links}"
  334. end
  335. end
  336. html.html_safe
  337. end
  338. def per_page_links(selected=nil)
  339. links = Setting.per_page_options_array.collect do |n|
  340. n == selected ? n : link_to_content_update(n, params.merge(:per_page => n))
  341. end
  342. links.size > 1 ? l(:label_display_per_page, links.join(', ')) : nil
  343. end
  344. def reorder_links(name, url)
  345. link_to(image_tag('2uparrow.png', :alt => l(:label_sort_highest)), url.merge({"#{name}[move_to]" => 'highest'}), :method => :post, :title => l(:label_sort_highest)) +
  346. link_to(image_tag('1uparrow.png', :alt => l(:label_sort_higher)), url.merge({"#{name}[move_to]" => 'higher'}), :method => :post, :title => l(:label_sort_higher)) +
  347. link_to(image_tag('1downarrow.png', :alt => l(:label_sort_lower)), url.merge({"#{name}[move_to]" => 'lower'}), :method => :post, :title => l(:label_sort_lower)) +
  348. link_to(image_tag('2downarrow.png', :alt => l(:label_sort_lowest)), url.merge({"#{name}[move_to]" => 'lowest'}), :method => :post, :title => l(:label_sort_lowest))
  349. end
  350. def breadcrumb(*args)
  351. elements = args.flatten
  352. elements.any? ? content_tag('p', (args.join(" \xc2\xbb ") + " \xc2\xbb ").html_safe, :class => 'breadcrumb') : nil
  353. end
  354. def other_formats_links(&block)
  355. concat('<p class="other-formats">' + l(:label_export_to))
  356. yield Redmine::Views::OtherFormatsBuilder.new(self)
  357. concat('</p>')
  358. end
  359. def page_header_title
  360. if @project.nil? || @project.new_record?
  361. h(Setting.app_title)
  362. else
  363. b = []
  364. ancestors = (@project.root? ? [] : @project.ancestors.visible.all)
  365. if ancestors.any?
  366. root = ancestors.shift
  367. b << link_to_project(root, {:jump => current_menu_item}, :class => 'root')
  368. if ancestors.size > 2
  369. b << '&#8230;'
  370. ancestors = ancestors[-2, 2]
  371. end
  372. b += ancestors.collect {|p| link_to_project(p, {:jump => current_menu_item}, :class => 'ancestor') }
  373. end
  374. b << h(@project)
  375. b.join(' &#187; ')
  376. end
  377. end
  378. def html_title(*args)
  379. if args.empty?
  380. title = []
  381. title << h(@project.name) if @project
  382. title += @html_title if @html_title
  383. title << Setting.app_title
  384. title.select {|t| !t.blank? }.join(' - ')
  385. else
  386. @html_title ||= []
  387. @html_title += args
  388. end
  389. end
  390. # Returns the theme, controller name, and action as css classes for the
  391. # HTML body.
  392. def body_css_classes
  393. css = []
  394. if theme = Redmine::Themes.theme(Setting.ui_theme)
  395. css << 'theme-' + theme.name
  396. end
  397. css << 'controller-' + params[:controller]
  398. css << 'action-' + params[:action]
  399. css.join(' ')
  400. end
  401. def accesskey(s)
  402. Redmine::AccessKeys.key_for s
  403. end
  404. # Formats text according to system settings.
  405. # 2 ways to call this method:
  406. # * with a String: textilizable(text, options)
  407. # * with an object and one of its attribute: textilizable(issue, :description, options)
  408. def textilizable(*args)
  409. options = args.last.is_a?(Hash) ? args.pop : {}
  410. case args.size
  411. when 1
  412. obj = options[:object]
  413. text = args.shift
  414. when 2
  415. obj = args.shift
  416. attr = args.shift
  417. text = obj.send(attr).to_s
  418. else
  419. raise ArgumentError, 'invalid arguments to textilizable'
  420. end
  421. return '' if text.blank?
  422. project = options[:project] || @project || (obj && obj.respond_to?(:project) ? obj.project : nil)
  423. only_path = options.delete(:only_path) == false ? false : true
  424. text = Redmine::WikiFormatting.to_html(Setting.text_formatting, text, :object => obj, :attribute => attr) { |macro, args| exec_macro(macro, obj, args) }
  425. @parsed_headings = []
  426. text = parse_non_pre_blocks(text) do |text|
  427. [:parse_inline_attachments, :parse_wiki_links, :parse_redmine_links, :parse_headings].each do |method_name|
  428. send method_name, text, project, obj, attr, only_path, options
  429. end
  430. end
  431. if @parsed_headings.any?
  432. replace_toc(text, @parsed_headings)
  433. end
  434. text
  435. end
  436. def parse_non_pre_blocks(text)
  437. s = StringScanner.new(text)
  438. tags = []
  439. parsed = ''
  440. while !s.eos?
  441. s.scan(/(.*?)(<(\/)?(pre|code)(.*?)>|\z)/im)
  442. text, full_tag, closing, tag = s[1], s[2], s[3], s[4]
  443. if tags.empty?
  444. yield text
  445. end
  446. parsed << text
  447. if tag
  448. if closing
  449. if tags.last == tag.downcase
  450. tags.pop
  451. end
  452. else
  453. tags << tag.downcase
  454. end
  455. parsed << full_tag
  456. end
  457. end
  458. # Close any non closing tags
  459. while tag = tags.pop
  460. parsed << "</#{tag}>"
  461. end
  462. parsed.html_safe
  463. end
  464. def parse_inline_attachments(text, project, obj, attr, only_path, options)
  465. # when using an image link, try to use an attachment, if possible
  466. if options[:attachments] || (obj && obj.respond_to?(:attachments))
  467. attachments = nil
  468. text.gsub!(/src="([^\/"]+\.(bmp|gif|jpg|jpeg|png))"(\s+alt="([^"]*)")?/i) do |m|
  469. filename, ext, alt, alttext = $1.downcase, $2, $3, $4
  470. attachments ||= (options[:attachments] || obj.attachments).sort_by(&:created_on).reverse
  471. # search for the picture in attachments
  472. if found = attachments.detect { |att| att.filename.downcase == filename }
  473. image_url = url_for :only_path => only_path, :controller => 'attachments', :action => 'download', :id => found
  474. desc = found.description.to_s.gsub('"', '')
  475. if !desc.blank? && alttext.blank?
  476. alt = " title=\"#{desc}\" alt=\"#{desc}\""
  477. end
  478. "src=\"#{image_url}\"#{alt}".html_safe
  479. else
  480. m.html_safe
  481. end
  482. end
  483. end
  484. end
  485. # Wiki links
  486. #
  487. # Examples:
  488. # [[mypage]]
  489. # [[mypage|mytext]]
  490. # wiki links can refer other project wikis, using project name or identifier:
  491. # [[project:]] -> wiki starting page
  492. # [[project:|mytext]]
  493. # [[project:mypage]]
  494. # [[project:mypage|mytext]]
  495. def parse_wiki_links(text, project, obj, attr, only_path, options)
  496. text.gsub!(/(!)?(\[\[([^\]\n\|]+)(\|([^\]\n\|]+))?\]\])/) do |m|
  497. link_project = project
  498. esc, all, page, title = $1, $2, $3, $5
  499. if esc.nil?
  500. if page =~ /^([^\:]+)\:(.*)$/
  501. link_project = Project.find_by_identifier($1) || Project.find_by_name($1)
  502. page = $2
  503. title ||= $1 if page.blank?
  504. end
  505. if link_project && link_project.wiki
  506. # extract anchor
  507. anchor = nil
  508. if page =~ /^(.+?)\#(.+)$/
  509. page, anchor = $1, $2
  510. end
  511. # check if page exists
  512. wiki_page = link_project.wiki.find_page(page)
  513. url = case options[:wiki_links]
  514. when :local; "#{title}.html"
  515. when :anchor; "##{title}" # used for single-file wiki export
  516. else
  517. wiki_page_id = page.present? ? Wiki.titleize(page) : nil
  518. url_for(:only_path => only_path, :controller => 'wiki', :action => 'show', :project_id => link_project, :id => wiki_page_id, :anchor => anchor)
  519. end
  520. link_to(h(title || page), url, :class => ('wiki-page' + (wiki_page ? '' : ' new')))
  521. else
  522. # project or wiki doesn't exist
  523. all.html_safe
  524. end
  525. else
  526. all.html_safe
  527. end
  528. end
  529. end
  530. # Redmine links
  531. #
  532. # Examples:
  533. # Issues:
  534. # #52 -> Link to issue #52
  535. # Changesets:
  536. # r52 -> Link to revision 52
  537. # commit:a85130f -> Link to scmid starting with a85130f
  538. # Documents:
  539. # document#17 -> Link to document with id 17
  540. # document:Greetings -> Link to the document with title "Greetings"
  541. # document:"Some document" -> Link to the document with title "Some document"
  542. # Versions:
  543. # version#3 -> Link to version with id 3
  544. # version:1.0.0 -> Link to version named "1.0.0"
  545. # version:"1.0 beta 2" -> Link to version named "1.0 beta 2"
  546. # Attachments:
  547. # attachment:file.zip -> Link to the attachment of the current object named file.zip
  548. # Source files:
  549. # source:some/file -> Link to the file located at /some/file in the project's repository
  550. # source:some/file@52 -> Link to the file's revision 52
  551. # source:some/file#L120 -> Link to line 120 of the file
  552. # source:some/file@52#L120 -> Link to line 120 of the file's revision 52
  553. # export:some/file -> Force the download of the file
  554. # Forum messages:
  555. # message#1218 -> Link to message with id 1218
  556. #
  557. # Links can refer other objects from other projects, using project identifier:
  558. # identifier:r52
  559. # identifier:document:"Some document"
  560. # identifier:version:1.0.0
  561. # identifier:source:some/file
  562. def parse_redmine_links(text, project, obj, attr, only_path, options)
  563. text.gsub!(%r{([\s\(,\-\[\>]|^)(!)?(([a-z0-9\-]+):)?(attachment|document|version|commit|source|export|message|project)?((#|r)(\d+)|(:)([^"\s<>][^\s<>]*?|"[^"]+?"))(?=(?=[[:punct:]]\W)|,|\s|\]|<|$)}) do |m|
  564. leading, esc, project_prefix, project_identifier, prefix, sep, identifier = $1, $2, $3, $4, $5, $7 || $9, $8 || $10
  565. link = nil
  566. if project_identifier
  567. project = Project.visible.find_by_identifier(project_identifier)
  568. end
  569. if esc.nil?
  570. if prefix.nil? && sep == 'r'
  571. # project.changesets.visible raises an SQL error because of a double join on repositories
  572. if project && project.repository && (changeset = Changeset.visible.find_by_repository_id_and_revision(project.repository.id, identifier))
  573. link = link_to(h("#{project_prefix}r#{identifier}"), {:only_path => only_path, :controller => 'repositories', :action => 'revision', :id => project, :rev => changeset.revision},
  574. :class => 'changeset',
  575. :title => truncate_single_line(changeset.comments, :length => 100))
  576. end
  577. elsif sep == '#'
  578. oid = identifier.to_i
  579. case prefix
  580. when nil
  581. if issue = Issue.visible.find_by_id(oid, :include => :status)
  582. link = link_to("##{oid}", {:only_path => only_path, :controller => 'issues', :action => 'show', :id => oid},
  583. :class => issue.css_classes,
  584. :title => "#{truncate(issue.subject, :length => 100)} (#{issue.status.name})")
  585. end
  586. when 'document'
  587. if document = Document.visible.find_by_id(oid)
  588. link = link_to h(document.title), {:only_path => only_path, :controller => 'documents', :action => 'show', :id => document},
  589. :class => 'document'
  590. end
  591. when 'version'
  592. if version = Version.visible.find_by_id(oid)
  593. link = link_to h(version.name), {:only_path => only_path, :controller => 'versions', :action => 'show', :id => version},
  594. :class => 'version'
  595. end
  596. when 'message'
  597. if message = Message.visible.find_by_id(oid, :include => :parent)
  598. link = link_to_message(message, {:only_path => only_path}, :class => 'message')
  599. end
  600. when 'project'
  601. if p = Project.visible.find_by_id(oid)
  602. link = link_to_project(p, {:only_path => only_path}, :class => 'project')
  603. end
  604. end
  605. elsif sep == ':'
  606. # removes the double quotes if any
  607. name = identifier.gsub(%r{^"(.*)"$}, "\\1")
  608. case prefix
  609. when 'document'
  610. if project && document = project.documents.visible.find_by_title(name)
  611. link = link_to h(document.title), {:only_path => only_path, :controller => 'documents', :action => 'show', :id => document},
  612. :class => 'document'
  613. end
  614. when 'version'
  615. if project && version = project.versions.visible.find_by_name(name)
  616. link = link_to h(version.name), {:only_path => only_path, :controller => 'versions', :action => 'show', :id => version},
  617. :class => 'version'
  618. end
  619. when 'commit'
  620. if project && project.repository && (changeset = Changeset.visible.find(:first, :conditions => ["repository_id = ? AND scmid LIKE ?", project.repository.id, "#{name}%"]))
  621. link = link_to h("#{project_prefix}#{name}"), {:only_path => only_path, :controller => 'repositories', :action => 'revision', :id => project, :rev => changeset.identifier},
  622. :class => 'changeset',
  623. :title => truncate_single_line(h(changeset.comments), :length => 100)
  624. end
  625. when 'source', 'export'
  626. if project && project.repository && User.current.allowed_to?(:browse_repository, project)
  627. name =~ %r{^[/\\]*(.*?)(@([0-9a-f]+))?(#(L\d+))?$}
  628. path, rev, anchor = $1, $3, $5
  629. link = link_to h("#{project_prefix}#{prefix}:#{name}"), {:controller => 'repositories', :action => 'entry', :id => project,
  630. :path => to_path_param(path),
  631. :rev => rev,
  632. :anchor => anchor,
  633. :format => (prefix == 'export' ? 'raw' : nil)},
  634. :class => (prefix == 'export' ? 'source download' : 'source')
  635. end
  636. when 'attachment'
  637. attachments = options[:attachments] || (obj && obj.respond_to?(:attachments) ? obj.attachments : nil)
  638. if attachments && attachment = attachments.detect {|a| a.filename == name }
  639. link = link_to h(attachment.filename), {:only_path => only_path, :controller => 'attachments', :action => 'download', :id => attachment},
  640. :class => 'attachment'
  641. end
  642. when 'project'
  643. if p = Project.visible.find(:first, :conditions => ["identifier = :s OR LOWER(name) = :s", {:s => name.downcase}])
  644. link = link_to_project(p, {:only_path => only_path}, :class => 'project')
  645. end
  646. end
  647. end
  648. end
  649. (leading + (link || "#{project_prefix}#{prefix}#{sep}#{identifier}")).html_safe
  650. end
  651. end
  652. HEADING_RE = /<h(1|2|3|4)( [^>]+)?>(.+?)<\/h(1|2|3|4)>/i unless const_defined?(:HEADING_RE)
  653. # Headings and TOC
  654. # Adds ids and links to headings unless options[:headings] is set to false
  655. def parse_headings(text, project, obj, attr, only_path, options)
  656. return if options[:headings] == false
  657. text.gsub!(HEADING_RE) do
  658. level, attrs, content = $1.to_i, $2, $3
  659. item = strip_tags(content).strip
  660. anchor = item.gsub(%r{[^\w\s\-]}, '').gsub(%r{\s+(\-+\s*)?}, '-')
  661. @parsed_headings << [level, anchor, item]
  662. "<a name=\"#{anchor}\"></a>\n<h#{level} #{attrs}>#{content}<a href=\"##{anchor}\" class=\"wiki-anchor\">&para;</a></h#{level}>"
  663. end
  664. end
  665. TOC_RE = /<p>\{\{([<>]?)toc\}\}<\/p>/i unless const_defined?(:TOC_RE)
  666. # Renders the TOC with given headings
  667. def replace_toc(text, headings)
  668. text.gsub!(TOC_RE) do
  669. if headings.empty?
  670. ''
  671. else
  672. div_class = 'toc'
  673. div_class << ' right' if $1 == '>'
  674. div_class << ' left' if $1 == '<'
  675. out = "<ul class=\"#{div_class}\"><li>"
  676. root = headings.map(&:first).min
  677. current = root
  678. started = false
  679. headings.each do |level, anchor, item|
  680. if level > current
  681. out << '<ul><li>' * (level - current)
  682. elsif level < current
  683. out << "</li></ul>\n" * (current - level) + "</li><li>"
  684. elsif started
  685. out << '</li><li>'
  686. end
  687. out << "<a href=\"##{anchor}\">#{item}</a>"
  688. current = level
  689. started = true
  690. end
  691. out << '</li></ul>' * (current - root)
  692. out << '</li></ul>'
  693. end
  694. end
  695. end
  696. # Same as Rails' simple_format helper without using paragraphs
  697. def simple_format_without_paragraph(text)
  698. text.to_s.
  699. gsub(/\r\n?/, "\n"). # \r\n and \r -> \n
  700. gsub(/\n\n+/, "<br /><br />"). # 2+ newline -> 2 br
  701. gsub(/([^\n]\n)(?=[^\n])/, '\1<br />') # 1 newline -> br
  702. end
  703. def lang_options_for_select(blank=true)
  704. (blank ? [["(auto)", ""]] : []) +
  705. valid_languages.collect{|lang| [ ll(lang.to_s, :general_lang_name), lang.to_s]}.sort{|x,y| x.last <=> y.last }
  706. end
  707. def label_tag_for(name, option_tags = nil, options = {})
  708. label_text = l(("field_"+field.to_s.gsub(/\_id$/, "")).to_sym) + (options.delete(:required) ? @template.content_tag("span", " *", :class => "required"): "")
  709. content_tag("label", label_text)
  710. end
  711. def labelled_tabular_form_for(name, object, options, &proc)
  712. options[:html] ||= {}
  713. options[:html][:class] = 'tabular' unless options[:html].has_key?(:class)
  714. form_for(name, object, options.merge({ :builder => TabularFormBuilder, :lang => current_language}), &proc)
  715. end
  716. def back_url_hidden_field_tag
  717. back_url = params[:back_url] || request.env['HTTP_REFERER']
  718. back_url = CGI.unescape(back_url.to_s)
  719. hidden_field_tag('back_url', CGI.escape(back_url)) unless back_url.blank?
  720. end
  721. def check_all_links(form_name)
  722. link_to_function(l(:button_check_all), "checkAll('#{form_name}', true)") +
  723. " | ".html_safe +
  724. link_to_function(l(:button_uncheck_all), "checkAll('#{form_name}', false)")
  725. end
  726. def progress_bar(pcts, options={})
  727. pcts = [pcts, pcts] unless pcts.is_a?(Array)
  728. pcts = pcts.collect(&:round)
  729. pcts[1] = pcts[1] - pcts[0]
  730. pcts << (100 - pcts[1] - pcts[0])
  731. width = options[:width] || '100px;'
  732. legend = options[:legend] || ''
  733. content_tag('table',
  734. content_tag('tr',
  735. (pcts[0] > 0 ? content_tag('td', '', :style => "width: #{pcts[0]}%;", :class => 'closed') : ''.html_safe) +
  736. (pcts[1] > 0 ? content_tag('td', '', :style => "width: #{pcts[1]}%;", :class => 'done') : ''.html_safe) +
  737. (pcts[2] > 0 ? content_tag('td', '', :style => "width: #{pcts[2]}%;", :class => 'todo') : ''.html_safe)
  738. ), :class => 'progress', :style => "width: #{width};").html_safe +
  739. content_tag('p', legend, :class => 'pourcent').html_safe
  740. end
  741. def checked_image(checked=true)
  742. if checked
  743. image_tag 'toggle_check.png'
  744. end
  745. end
  746. def context_menu(url)
  747. unless @context_menu_included
  748. content_for :header_tags do
  749. javascript_include_tag('context_menu') +
  750. stylesheet_link_tag('context_menu')
  751. end
  752. if l(:direction) == 'rtl'
  753. content_for :header_tags do
  754. stylesheet_link_tag('context_menu_rtl')
  755. end
  756. end
  757. @context_menu_included = true
  758. end
  759. javascript_tag "new ContextMenu('#{ url_for(url) }')"
  760. end
  761. def context_menu_link(name, url, options={})
  762. options[:class] ||= ''
  763. if options.delete(:selected)
  764. options[:class] << ' icon-checked disabled'
  765. options[:disabled] = true
  766. end
  767. if options.delete(:disabled)
  768. options.delete(:method)
  769. options.delete(:confirm)
  770. options.delete(:onclick)
  771. options[:class] << ' disabled'
  772. url = '#'
  773. end
  774. link_to h(name), url, options
  775. end
  776. def calendar_for(field_id)
  777. include_calendar_headers_tags
  778. image_tag("calendar.png", {:id => "#{field_id}_trigger",:class => "calendar-trigger"}) +
  779. javascript_tag("Calendar.setup({inputField : '#{field_id}', ifFormat : '%Y-%m-%d', button : '#{field_id}_trigger' });")
  780. end
  781. def include_calendar_headers_tags
  782. unless @calendar_headers_tags_included
  783. @calendar_headers_tags_included = true
  784. content_for :header_tags do
  785. start_of_week = case Setting.start_of_week.to_i
  786. when 1
  787. 'Calendar._FD = 1;' # Monday
  788. when 7
  789. 'Calendar._FD = 0;' # Sunday
  790. when 6
  791. 'Calendar._FD = 6;' # Saturday
  792. else
  793. '' # use language
  794. end
  795. javascript_include_tag('calendar/calendar') +
  796. javascript_include_tag("calendar/lang/calendar-#{current_language.to_s.downcase}.js") +
  797. javascript_tag(start_of_week) +
  798. javascript_include_tag('calendar/calendar-setup') +
  799. stylesheet_link_tag('calendar')
  800. end
  801. end
  802. end
  803. def content_for(name, content = nil, &block)
  804. @has_content ||= {}
  805. @has_content[name] = true
  806. super(name, content, &block)
  807. end
  808. def has_content?(name)
  809. (@has_content && @has_content[name]) || false
  810. end
  811. def email_delivery_enabled?
  812. !!ActionMailer::Base.perform_deliveries
  813. end
  814. # Returns the avatar image tag for the given +user+ if avatars are enabled
  815. # +user+ can be a User or a string that will be scanned for an email address (eg. 'joe <joe@foo.bar>')
  816. def avatar(user, options = { })
  817. if Setting.gravatar_enabled?
  818. options.merge!({:ssl => (defined?(request) && request.ssl?), :default => Setting.gravatar_default})
  819. email = nil
  820. if user.respond_to?(:mail)
  821. email = user.mail
  822. elsif user.to_s =~ %r{<(.+?)>}
  823. email = $1
  824. end
  825. return gravatar(email.to_s.downcase, options) unless email.blank? rescue nil
  826. else
  827. ''
  828. end
  829. end
  830. # Returns the javascript tags that are included in the html layout head
  831. def javascript_heads
  832. tags = javascript_include_tag(:defaults)
  833. unless User.current.pref.warn_on_leaving_unsaved == '0'
  834. tags << "\n".html_safe + javascript_tag("Event.observe(window, 'load', function(){ new WarnLeavingUnsaved('#{escape_javascript( l(:text_warn_on_leaving_unsaved) )}'); });")
  835. end
  836. tags
  837. end
  838. def favicon
  839. "<link rel='shortcut icon' href='#{image_path('/favicon.ico')}' />".html_safe
  840. end
  841. def robot_exclusion_tag
  842. '<meta name="robots" content="noindex,follow,noarchive" />'
  843. end
  844. # Returns true if arg is expected in the API response
  845. def include_in_api_response?(arg)
  846. unless @included_in_api_response
  847. param = params[:include]
  848. @included_in_api_response = param.is_a?(Array) ? param.collect(&:to_s) : param.to_s.split(',')
  849. @included_in_api_response.collect!(&:strip)
  850. end
  851. @included_in_api_response.include?(arg.to_s)
  852. end
  853. # Returns options or nil if nometa param or X-Redmine-Nometa header
  854. # was set in the request
  855. def api_meta(options)
  856. if params[:nometa].present? || request.headers['X-Redmine-Nometa']
  857. # compatibility mode for activeresource clients that raise
  858. # an error when unserializing an array with attributes
  859. nil
  860. else
  861. options
  862. end
  863. end
  864. private
  865. def wiki_helper
  866. helper = Redmine::WikiFormatting.helper_for(Setting.text_formatting)
  867. extend helper
  868. return self
  869. end
  870. def link_to_content_update(text, url_params = {}, html_options = {})
  871. link_to(text, url_params, html_options)
  872. end
  873. end