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

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