PageRenderTime 62ms CodeModel.GetById 22ms RepoModel.GetById 0ms app.codeStats 0ms

/app/helpers/application_helper.rb

https://github.com/oss92/redmine
Ruby | 1353 lines | 1066 code | 114 blank | 173 comment | 194 complexity | f00fdcaf04fc4d1d837b0f64b620b0bd MD5 | raw file
Possible License(s): GPL-2.0
  1. # encoding: utf-8
  2. #
  3. # Redmine - project management software
  4. # Copyright (C) 2006-2014 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. include Redmine::Pagination::Helper
  26. extend Forwardable
  27. def_delegators :wiki_helper, :wikitoolbar_for, :heads_for_wiki_formatter
  28. # Return true if user is authorized for controller/action, otherwise false
  29. def authorize_for(controller, action)
  30. User.current.allowed_to?({:controller => controller, :action => action}, @project)
  31. end
  32. # Display a link if user is authorized
  33. #
  34. # @param [String] name Anchor text (passed to link_to)
  35. # @param [Hash] options Hash params. This will checked by authorize_for to see if the user is authorized
  36. # @param [optional, Hash] html_options Options passed to link_to
  37. # @param [optional, Hash] parameters_for_method_reference Extra parameters for link_to
  38. def link_to_if_authorized(name, options = {}, html_options = nil, *parameters_for_method_reference)
  39. link_to(name, options, html_options, *parameters_for_method_reference) if authorize_for(options[:controller] || params[:controller], options[:action])
  40. end
  41. # Displays a link to user's account page if active
  42. def link_to_user(user, options={})
  43. if user.is_a?(User)
  44. name = h(user.name(options[:format]))
  45. if user.active? || (User.current.admin? && user.logged?)
  46. link_to name, user_path(user), :class => user.css_classes
  47. else
  48. name
  49. end
  50. else
  51. h(user.to_s)
  52. end
  53. end
  54. # Displays a link to +issue+ with its subject.
  55. # Examples:
  56. #
  57. # link_to_issue(issue) # => Defect #6: This is the subject
  58. # link_to_issue(issue, :truncate => 6) # => Defect #6: This i...
  59. # link_to_issue(issue, :subject => false) # => Defect #6
  60. # link_to_issue(issue, :project => true) # => Foo - Defect #6
  61. # link_to_issue(issue, :subject => false, :tracker => false) # => #6
  62. #
  63. def link_to_issue(issue, options={})
  64. title = nil
  65. subject = nil
  66. text = options[:tracker] == false ? "##{issue.id}" : "#{issue.tracker} ##{issue.id}"
  67. if options[:subject] == false
  68. title = issue.subject.truncate(60)
  69. else
  70. subject = issue.subject
  71. if truncate_length = options[:truncate]
  72. subject = subject.truncate(truncate_length)
  73. end
  74. end
  75. only_path = options[:only_path].nil? ? true : options[:only_path]
  76. s = link_to(text, issue_path(issue, :only_path => only_path),
  77. :class => issue.css_classes, :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. route_method = options.delete(:download) ? :download_named_attachment_path : :named_attachment_path
  89. html_options = options.slice!(:only_path)
  90. url = send(route_method, attachment, attachment.filename, options)
  91. link_to text, url, html_options
  92. end
  93. # Generates a link to a SCM revision
  94. # Options:
  95. # * :text - Link text (default to the formatted revision)
  96. def link_to_revision(revision, repository, options={})
  97. if repository.is_a?(Project)
  98. repository = repository.repository
  99. end
  100. text = options.delete(:text) || format_revision(revision)
  101. rev = revision.respond_to?(:identifier) ? revision.identifier : revision
  102. link_to(
  103. h(text),
  104. {:controller => 'repositories', :action => 'revision', :id => repository.project, :repository_id => repository.identifier_param, :rev => rev},
  105. :title => l(:label_revision_id, format_revision(revision))
  106. )
  107. end
  108. # Generates a link to a message
  109. def link_to_message(message, options={}, html_options = nil)
  110. link_to(
  111. message.subject.truncate(60),
  112. board_message_path(message.board_id, message.parent_id || message.id, {
  113. :r => (message.parent_id && message.id),
  114. :anchor => (message.parent_id ? "message-#{message.id}" : nil)
  115. }.merge(options)),
  116. html_options
  117. )
  118. end
  119. # Generates a link to a project if active
  120. # Examples:
  121. #
  122. # link_to_project(project) # => link to the specified project overview
  123. # link_to_project(project, {:only_path => false}, :class => "project") # => 3rd arg adds html options
  124. # link_to_project(project, {}, :class => "project") # => html options with default url (project overview)
  125. #
  126. def link_to_project(project, options={}, html_options = nil)
  127. if project.archived?
  128. h(project.name)
  129. elsif options.key?(:action)
  130. ActiveSupport::Deprecation.warn "#link_to_project with :action option is deprecated and will be removed in Redmine 3.0."
  131. url = {:controller => 'projects', :action => 'show', :id => project}.merge(options)
  132. link_to project.name, url, html_options
  133. else
  134. link_to project.name, project_path(project, options), html_options
  135. end
  136. end
  137. # Generates a link to a project settings if active
  138. def link_to_project_settings(project, options={}, html_options=nil)
  139. if project.active?
  140. link_to project.name, settings_project_path(project, options), html_options
  141. elsif project.archived?
  142. h(project.name)
  143. else
  144. link_to project.name, project_path(project, options), html_options
  145. end
  146. end
  147. # Helper that formats object for html or text rendering
  148. def format_object(object, html=true, &block)
  149. if block_given?
  150. object = yield object
  151. end
  152. case object.class.name
  153. when 'Array'
  154. object.map {|o| format_object(o, html)}.join(', ').html_safe
  155. when 'Time'
  156. format_time(object)
  157. when 'Date'
  158. format_date(object)
  159. when 'Fixnum'
  160. object.to_s
  161. when 'Float'
  162. sprintf "%.2f", object
  163. when 'User'
  164. html ? link_to_user(object) : object.to_s
  165. when 'Project'
  166. html ? link_to_project(object) : object.to_s
  167. when 'Version'
  168. html ? link_to(object.name, version_path(object)) : object.to_s
  169. when 'TrueClass'
  170. l(:general_text_Yes)
  171. when 'FalseClass'
  172. l(:general_text_No)
  173. when 'Issue'
  174. object.visible? && html ? link_to_issue(object) : "##{object.id}"
  175. when 'CustomValue', 'CustomFieldValue'
  176. if object.custom_field
  177. f = object.custom_field.format.formatted_custom_value(self, object, html)
  178. if f.nil? || f.is_a?(String)
  179. f
  180. else
  181. format_object(f, html, &block)
  182. end
  183. else
  184. object.value.to_s
  185. end
  186. else
  187. html ? h(object) : object.to_s
  188. end
  189. end
  190. def wiki_page_path(page, options={})
  191. url_for({:controller => 'wiki', :action => 'show', :project_id => page.project, :id => page.title}.merge(options))
  192. end
  193. def thumbnail_tag(attachment)
  194. link_to image_tag(thumbnail_path(attachment)),
  195. named_attachment_path(attachment, attachment.filename),
  196. :title => attachment.filename
  197. end
  198. def toggle_link(name, id, options={})
  199. onclick = "$('##{id}').toggle(); "
  200. onclick << (options[:focus] ? "$('##{options[:focus]}').focus(); " : "this.blur(); ")
  201. onclick << "return false;"
  202. link_to(name, "#", :onclick => onclick)
  203. end
  204. def image_to_function(name, function, html_options = {})
  205. html_options.symbolize_keys!
  206. tag(:input, html_options.merge({
  207. :type => "image", :src => image_path(name),
  208. :onclick => (html_options[:onclick] ? "#{html_options[:onclick]}; " : "") + "#{function};"
  209. }))
  210. end
  211. def format_activity_title(text)
  212. h(truncate_single_line_raw(text, 100))
  213. end
  214. def format_activity_day(date)
  215. date == User.current.today ? l(:label_today).titleize : format_date(date)
  216. end
  217. def format_activity_description(text)
  218. h(text.to_s.truncate(120).gsub(%r{[\r\n]*<(pre|code)>.*$}m, '...')
  219. ).gsub(/[\r\n]+/, "<br />").html_safe
  220. end
  221. def format_version_name(version)
  222. if version.project == @project
  223. h(version)
  224. else
  225. h("#{version.project} - #{version}")
  226. end
  227. end
  228. def due_date_distance_in_words(date)
  229. if date
  230. l((date < Date.today ? :label_roadmap_overdue : :label_roadmap_due_in), distance_of_date_in_words(Date.today, date))
  231. end
  232. end
  233. # Renders a tree of projects as a nested set of unordered lists
  234. # The given collection may be a subset of the whole project tree
  235. # (eg. some intermediate nodes are private and can not be seen)
  236. def render_project_nested_lists(projects)
  237. s = ''
  238. if projects.any?
  239. ancestors = []
  240. original_project = @project
  241. projects.sort_by(&:lft).each do |project|
  242. # set the project environment to please macros.
  243. @project = project
  244. if (ancestors.empty? || project.is_descendant_of?(ancestors.last))
  245. s << "<ul class='projects #{ ancestors.empty? ? 'root' : nil}'>\n"
  246. else
  247. ancestors.pop
  248. s << "</li>"
  249. while (ancestors.any? && !project.is_descendant_of?(ancestors.last))
  250. ancestors.pop
  251. s << "</ul></li>\n"
  252. end
  253. end
  254. classes = (ancestors.empty? ? 'root' : 'child')
  255. s << "<li class='#{classes}'><div class='#{classes}'>"
  256. s << h(block_given? ? yield(project) : project.name)
  257. s << "</div>\n"
  258. ancestors << project
  259. end
  260. s << ("</li></ul>\n" * ancestors.size)
  261. @project = original_project
  262. end
  263. s.html_safe
  264. end
  265. def render_page_hierarchy(pages, node=nil, options={})
  266. content = ''
  267. if pages[node]
  268. content << "<ul class=\"pages-hierarchy\">\n"
  269. pages[node].each do |page|
  270. content << "<li>"
  271. content << link_to(h(page.pretty_title), {:controller => 'wiki', :action => 'show', :project_id => page.project, :id => page.title, :version => nil},
  272. :title => (options[:timestamp] && page.updated_on ? l(:label_updated_time, distance_of_time_in_words(Time.now, page.updated_on)) : nil))
  273. content << "\n" + render_page_hierarchy(pages, page.id, options) if pages[page.id]
  274. content << "</li>\n"
  275. end
  276. content << "</ul>\n"
  277. end
  278. content.html_safe
  279. end
  280. # Renders flash messages
  281. def render_flash_messages
  282. s = ''
  283. flash.each do |k,v|
  284. s << content_tag('div', v.html_safe, :class => "flash #{k}", :id => "flash_#{k}")
  285. end
  286. s.html_safe
  287. end
  288. # Renders tabs and their content
  289. def render_tabs(tabs, selected=params[:tab])
  290. if tabs.any?
  291. unless tabs.detect {|tab| tab[:name] == selected}
  292. selected = nil
  293. end
  294. selected ||= tabs.first[:name]
  295. render :partial => 'common/tabs', :locals => {:tabs => tabs, :selected_tab => selected}
  296. else
  297. content_tag 'p', l(:label_no_data), :class => "nodata"
  298. end
  299. end
  300. # Renders the project quick-jump box
  301. def render_project_jump_box
  302. return unless User.current.logged?
  303. projects = User.current.memberships.collect(&:project).compact.select(&:active?).uniq
  304. if projects.any?
  305. options =
  306. ("<option value=''>#{ l(:label_jump_to_a_project) }</option>" +
  307. '<option value="" disabled="disabled">---</option>').html_safe
  308. options << project_tree_options_for_select(projects, :selected => @project) do |p|
  309. { :value => project_path(:id => p, :jump => current_menu_item) }
  310. end
  311. select_tag('project_quick_jump_box', options, :onchange => 'if (this.value != \'\') { window.location = this.value; }')
  312. end
  313. end
  314. def project_tree_options_for_select(projects, options = {})
  315. s = ''
  316. project_tree(projects) do |project, level|
  317. name_prefix = (level > 0 ? '&nbsp;' * 2 * level + '&#187; ' : '').html_safe
  318. tag_options = {:value => project.id}
  319. if project == options[:selected] || (options[:selected].respond_to?(:include?) && options[:selected].include?(project))
  320. tag_options[:selected] = 'selected'
  321. else
  322. tag_options[:selected] = nil
  323. end
  324. tag_options.merge!(yield(project)) if block_given?
  325. s << content_tag('option', name_prefix + h(project), tag_options)
  326. end
  327. s.html_safe
  328. end
  329. # Yields the given block for each project with its level in the tree
  330. #
  331. # Wrapper for Project#project_tree
  332. def project_tree(projects, &block)
  333. Project.project_tree(projects, &block)
  334. end
  335. def principals_check_box_tags(name, principals)
  336. s = ''
  337. principals.each do |principal|
  338. s << "<label>#{ check_box_tag name, principal.id, false, :id => nil } #{h principal}</label>\n"
  339. end
  340. s.html_safe
  341. end
  342. # Returns a string for users/groups option tags
  343. def principals_options_for_select(collection, selected=nil)
  344. s = ''
  345. if collection.include?(User.current)
  346. s << content_tag('option', "<< #{l(:label_me)} >>", :value => User.current.id)
  347. end
  348. groups = ''
  349. collection.sort.each do |element|
  350. selected_attribute = ' selected="selected"' if option_value_selected?(element, selected) || element.id.to_s == selected
  351. (element.is_a?(Group) ? groups : s) << %(<option value="#{element.id}"#{selected_attribute}>#{h element.name}</option>)
  352. end
  353. unless groups.empty?
  354. s << %(<optgroup label="#{h(l(:label_group_plural))}">#{groups}</optgroup>)
  355. end
  356. s.html_safe
  357. end
  358. # Options for the new membership projects combo-box
  359. def options_for_membership_project_select(principal, projects)
  360. options = content_tag('option', "--- #{l(:actionview_instancetag_blank_option)} ---")
  361. options << project_tree_options_for_select(projects) do |p|
  362. {:disabled => principal.projects.to_a.include?(p)}
  363. end
  364. options
  365. end
  366. def option_tag(name, text, value, selected=nil, options={})
  367. content_tag 'option', value, options.merge(:value => value, :selected => (value == selected))
  368. end
  369. # Truncates and returns the string as a single line
  370. def truncate_single_line(string, *args)
  371. ActiveSupport::Deprecation.warn(
  372. "ApplicationHelper#truncate_single_line is deprecated and will be removed in Rails 4 poring")
  373. # Rails 4 ActionView::Helpers::TextHelper#truncate escapes.
  374. # So, result is broken.
  375. truncate(string.to_s, *args).gsub(%r{[\r\n]+}m, ' ')
  376. end
  377. def truncate_single_line_raw(string, length)
  378. string.truncate(length).gsub(%r{[\r\n]+}m, ' ')
  379. end
  380. # Truncates at line break after 250 characters or options[:length]
  381. def truncate_lines(string, options={})
  382. length = options[:length] || 250
  383. if string.to_s =~ /\A(.{#{length}}.*?)$/m
  384. "#{$1}..."
  385. else
  386. string
  387. end
  388. end
  389. def anchor(text)
  390. text.to_s.gsub(' ', '_')
  391. end
  392. def html_hours(text)
  393. text.gsub(%r{(\d+)\.(\d+)}, '<span class="hours hours-int">\1</span><span class="hours hours-dec">.\2</span>').html_safe
  394. end
  395. def authoring(created, author, options={})
  396. l(options[:label] || :label_added_time_by, :author => link_to_user(author), :age => time_tag(created)).html_safe
  397. end
  398. def time_tag(time)
  399. text = distance_of_time_in_words(Time.now, time)
  400. if @project
  401. link_to(text, {:controller => 'activities', :action => 'index', :id => @project, :from => User.current.time_to_date(time)}, :title => format_time(time))
  402. else
  403. content_tag('abbr', text, :title => format_time(time))
  404. end
  405. end
  406. def syntax_highlight_lines(name, content)
  407. lines = []
  408. syntax_highlight(name, content).each_line { |line| lines << line }
  409. lines
  410. end
  411. def syntax_highlight(name, content)
  412. Redmine::SyntaxHighlighting.highlight_by_filename(content, name)
  413. end
  414. def to_path_param(path)
  415. str = path.to_s.split(%r{[/\\]}).select{|p| !p.blank?}.join("/")
  416. str.blank? ? nil : str
  417. end
  418. def reorder_links(name, url, method = :post)
  419. link_to(image_tag('2uparrow.png', :alt => l(:label_sort_highest)),
  420. url.merge({"#{name}[move_to]" => 'highest'}),
  421. :method => method, :title => l(:label_sort_highest)) +
  422. link_to(image_tag('1uparrow.png', :alt => l(:label_sort_higher)),
  423. url.merge({"#{name}[move_to]" => 'higher'}),
  424. :method => method, :title => l(:label_sort_higher)) +
  425. link_to(image_tag('1downarrow.png', :alt => l(:label_sort_lower)),
  426. url.merge({"#{name}[move_to]" => 'lower'}),
  427. :method => method, :title => l(:label_sort_lower)) +
  428. link_to(image_tag('2downarrow.png', :alt => l(:label_sort_lowest)),
  429. url.merge({"#{name}[move_to]" => 'lowest'}),
  430. :method => method, :title => l(:label_sort_lowest))
  431. end
  432. def breadcrumb(*args)
  433. elements = args.flatten
  434. elements.any? ? content_tag('p', (args.join(" \xc2\xbb ") + " \xc2\xbb ").html_safe, :class => 'breadcrumb') : nil
  435. end
  436. def other_formats_links(&block)
  437. concat('<p class="other-formats">'.html_safe + l(:label_export_to))
  438. yield Redmine::Views::OtherFormatsBuilder.new(self)
  439. concat('</p>'.html_safe)
  440. end
  441. def page_header_title
  442. if @project.nil? || @project.new_record?
  443. h(Setting.app_title)
  444. else
  445. b = []
  446. ancestors = (@project.root? ? [] : @project.ancestors.visible.all)
  447. if ancestors.any?
  448. root = ancestors.shift
  449. b << link_to_project(root, {:jump => current_menu_item}, :class => 'root')
  450. if ancestors.size > 2
  451. b << "\xe2\x80\xa6"
  452. ancestors = ancestors[-2, 2]
  453. end
  454. b += ancestors.collect {|p| link_to_project(p, {:jump => current_menu_item}, :class => 'ancestor') }
  455. end
  456. b << h(@project)
  457. b.join(" \xc2\xbb ").html_safe
  458. end
  459. end
  460. # Returns a h2 tag and sets the html title with the given arguments
  461. def title(*args)
  462. strings = args.map do |arg|
  463. if arg.is_a?(Array) && arg.size >= 2
  464. link_to(*arg)
  465. else
  466. h(arg.to_s)
  467. end
  468. end
  469. html_title args.reverse.map {|s| (s.is_a?(Array) ? s.first : s).to_s}
  470. content_tag('h2', strings.join(' &#187; ').html_safe)
  471. end
  472. # Sets the html title
  473. # Returns the html title when called without arguments
  474. # Current project name and app_title and automatically appended
  475. # Exemples:
  476. # html_title 'Foo', 'Bar'
  477. # html_title # => 'Foo - Bar - My Project - Redmine'
  478. def html_title(*args)
  479. if args.empty?
  480. title = @html_title || []
  481. title << @project.name if @project
  482. title << Setting.app_title unless Setting.app_title == title.last
  483. title.reject(&:blank?).join(' - ')
  484. else
  485. @html_title ||= []
  486. @html_title += args
  487. end
  488. end
  489. # Returns the theme, controller name, and action as css classes for the
  490. # HTML body.
  491. def body_css_classes
  492. css = []
  493. if theme = Redmine::Themes.theme(Setting.ui_theme)
  494. css << 'theme-' + theme.name
  495. end
  496. css << 'project-' + @project.identifier if @project && @project.identifier.present?
  497. css << 'controller-' + controller_name
  498. css << 'action-' + action_name
  499. css.join(' ')
  500. end
  501. def accesskey(s)
  502. @used_accesskeys ||= []
  503. key = Redmine::AccessKeys.key_for(s)
  504. return nil if @used_accesskeys.include?(key)
  505. @used_accesskeys << key
  506. key
  507. end
  508. # Formats text according to system settings.
  509. # 2 ways to call this method:
  510. # * with a String: textilizable(text, options)
  511. # * with an object and one of its attribute: textilizable(issue, :description, options)
  512. def textilizable(*args)
  513. options = args.last.is_a?(Hash) ? args.pop : {}
  514. case args.size
  515. when 1
  516. obj = options[:object]
  517. text = args.shift
  518. when 2
  519. obj = args.shift
  520. attr = args.shift
  521. text = obj.send(attr).to_s
  522. else
  523. raise ArgumentError, 'invalid arguments to textilizable'
  524. end
  525. return '' if text.blank?
  526. project = options[:project] || @project || (obj && obj.respond_to?(:project) ? obj.project : nil)
  527. only_path = options.delete(:only_path) == false ? false : true
  528. text = text.dup
  529. macros = catch_macros(text)
  530. text = Redmine::WikiFormatting.to_html(Setting.text_formatting, text, :object => obj, :attribute => attr)
  531. @parsed_headings = []
  532. @heading_anchors = {}
  533. @current_section = 0 if options[:edit_section_links]
  534. parse_sections(text, project, obj, attr, only_path, options)
  535. text = parse_non_pre_blocks(text, obj, macros) do |text|
  536. [:parse_inline_attachments, :parse_wiki_links, :parse_redmine_links].each do |method_name|
  537. send method_name, text, project, obj, attr, only_path, options
  538. end
  539. end
  540. parse_headings(text, project, obj, attr, only_path, options)
  541. if @parsed_headings.any?
  542. replace_toc(text, @parsed_headings)
  543. end
  544. text.html_safe
  545. end
  546. def parse_non_pre_blocks(text, obj, macros)
  547. s = StringScanner.new(text)
  548. tags = []
  549. parsed = ''
  550. while !s.eos?
  551. s.scan(/(.*?)(<(\/)?(pre|code)(.*?)>|\z)/im)
  552. text, full_tag, closing, tag = s[1], s[2], s[3], s[4]
  553. if tags.empty?
  554. yield text
  555. inject_macros(text, obj, macros) if macros.any?
  556. else
  557. inject_macros(text, obj, macros, false) if macros.any?
  558. end
  559. parsed << text
  560. if tag
  561. if closing
  562. if tags.last == tag.downcase
  563. tags.pop
  564. end
  565. else
  566. tags << tag.downcase
  567. end
  568. parsed << full_tag
  569. end
  570. end
  571. # Close any non closing tags
  572. while tag = tags.pop
  573. parsed << "</#{tag}>"
  574. end
  575. parsed
  576. end
  577. def parse_inline_attachments(text, project, obj, attr, only_path, options)
  578. # when using an image link, try to use an attachment, if possible
  579. attachments = options[:attachments] || []
  580. attachments += obj.attachments if obj.respond_to?(:attachments)
  581. if attachments.present?
  582. text.gsub!(/src="([^\/"]+\.(bmp|gif|jpg|jpe|jpeg|png))"(\s+alt="([^"]*)")?/i) do |m|
  583. filename, ext, alt, alttext = $1.downcase, $2, $3, $4
  584. # search for the picture in attachments
  585. if found = Attachment.latest_attach(attachments, filename)
  586. image_url = download_named_attachment_path(found, found.filename, :only_path => only_path)
  587. desc = found.description.to_s.gsub('"', '')
  588. if !desc.blank? && alttext.blank?
  589. alt = " title=\"#{desc}\" alt=\"#{desc}\""
  590. end
  591. "src=\"#{image_url}\"#{alt}"
  592. else
  593. m
  594. end
  595. end
  596. end
  597. end
  598. # Wiki links
  599. #
  600. # Examples:
  601. # [[mypage]]
  602. # [[mypage|mytext]]
  603. # wiki links can refer other project wikis, using project name or identifier:
  604. # [[project:]] -> wiki starting page
  605. # [[project:|mytext]]
  606. # [[project:mypage]]
  607. # [[project:mypage|mytext]]
  608. def parse_wiki_links(text, project, obj, attr, only_path, options)
  609. text.gsub!(/(!)?(\[\[([^\]\n\|]+)(\|([^\]\n\|]+))?\]\])/) do |m|
  610. link_project = project
  611. esc, all, page, title = $1, $2, $3, $5
  612. if esc.nil?
  613. if page =~ /^([^\:]+)\:(.*)$/
  614. identifier, page = $1, $2
  615. link_project = Project.find_by_identifier(identifier) || Project.find_by_name(identifier)
  616. title ||= identifier if page.blank?
  617. end
  618. if link_project && link_project.wiki
  619. # extract anchor
  620. anchor = nil
  621. if page =~ /^(.+?)\#(.+)$/
  622. page, anchor = $1, $2
  623. end
  624. anchor = sanitize_anchor_name(anchor) if anchor.present?
  625. # check if page exists
  626. wiki_page = link_project.wiki.find_page(page)
  627. url = if anchor.present? && wiki_page.present? && (obj.is_a?(WikiContent) || obj.is_a?(WikiContent::Version)) && obj.page == wiki_page
  628. "##{anchor}"
  629. else
  630. case options[:wiki_links]
  631. when :local; "#{page.present? ? Wiki.titleize(page) : ''}.html" + (anchor.present? ? "##{anchor}" : '')
  632. when :anchor; "##{page.present? ? Wiki.titleize(page) : title}" + (anchor.present? ? "_#{anchor}" : '') # used for single-file wiki export
  633. else
  634. wiki_page_id = page.present? ? Wiki.titleize(page) : nil
  635. parent = wiki_page.nil? && obj.is_a?(WikiContent) && obj.page && project == link_project ? obj.page.title : nil
  636. url_for(:only_path => only_path, :controller => 'wiki', :action => 'show', :project_id => link_project,
  637. :id => wiki_page_id, :version => nil, :anchor => anchor, :parent => parent)
  638. end
  639. end
  640. link_to(title.present? ? title.html_safe : h(page), url, :class => ('wiki-page' + (wiki_page ? '' : ' new')))
  641. else
  642. # project or wiki doesn't exist
  643. all
  644. end
  645. else
  646. all
  647. end
  648. end
  649. end
  650. # Redmine links
  651. #
  652. # Examples:
  653. # Issues:
  654. # #52 -> Link to issue #52
  655. # Changesets:
  656. # r52 -> Link to revision 52
  657. # commit:a85130f -> Link to scmid starting with a85130f
  658. # Documents:
  659. # document#17 -> Link to document with id 17
  660. # document:Greetings -> Link to the document with title "Greetings"
  661. # document:"Some document" -> Link to the document with title "Some document"
  662. # Versions:
  663. # version#3 -> Link to version with id 3
  664. # version:1.0.0 -> Link to version named "1.0.0"
  665. # version:"1.0 beta 2" -> Link to version named "1.0 beta 2"
  666. # Attachments:
  667. # attachment:file.zip -> Link to the attachment of the current object named file.zip
  668. # Source files:
  669. # source:some/file -> Link to the file located at /some/file in the project's repository
  670. # source:some/file@52 -> Link to the file's revision 52
  671. # source:some/file#L120 -> Link to line 120 of the file
  672. # source:some/file@52#L120 -> Link to line 120 of the file's revision 52
  673. # export:some/file -> Force the download of the file
  674. # Forum messages:
  675. # message#1218 -> Link to message with id 1218
  676. # Projects:
  677. # project:someproject -> Link to project named "someproject"
  678. # project#3 -> Link to project with id 3
  679. #
  680. # Links can refer other objects from other projects, using project identifier:
  681. # identifier:r52
  682. # identifier:document:"Some document"
  683. # identifier:version:1.0.0
  684. # identifier:source:some/file
  685. def parse_redmine_links(text, default_project, obj, attr, only_path, options)
  686. 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|
  687. 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
  688. link = nil
  689. project = default_project
  690. if project_identifier
  691. project = Project.visible.find_by_identifier(project_identifier)
  692. end
  693. if esc.nil?
  694. if prefix.nil? && sep == 'r'
  695. if project
  696. repository = nil
  697. if repo_identifier
  698. repository = project.repositories.detect {|repo| repo.identifier == repo_identifier}
  699. else
  700. repository = project.repository
  701. end
  702. # project.changesets.visible raises an SQL error because of a double join on repositories
  703. if repository &&
  704. (changeset = Changeset.visible.
  705. find_by_repository_id_and_revision(repository.id, identifier))
  706. link = link_to(h("#{project_prefix}#{repo_prefix}r#{identifier}"),
  707. {:only_path => only_path, :controller => 'repositories',
  708. :action => 'revision', :id => project,
  709. :repository_id => repository.identifier_param,
  710. :rev => changeset.revision},
  711. :class => 'changeset',
  712. :title => truncate_single_line_raw(changeset.comments, 100))
  713. end
  714. end
  715. elsif sep == '#'
  716. oid = identifier.to_i
  717. case prefix
  718. when nil
  719. if oid.to_s == identifier &&
  720. issue = Issue.visible.includes(:status).find_by_id(oid)
  721. anchor = comment_id ? "note-#{comment_id}" : nil
  722. link = link_to(h("##{oid}#{comment_suffix}"),
  723. {:only_path => only_path, :controller => 'issues',
  724. :action => 'show', :id => oid, :anchor => anchor},
  725. :class => issue.css_classes,
  726. :title => "#{issue.subject.truncate(100)} (#{issue.status.name})")
  727. end
  728. when 'document'
  729. if document = Document.visible.find_by_id(oid)
  730. link = link_to h(document.title), {:only_path => only_path, :controller => 'documents', :action => 'show', :id => document},
  731. :class => 'document'
  732. end
  733. when 'version'
  734. if version = Version.visible.find_by_id(oid)
  735. link = link_to h(version.name), {:only_path => only_path, :controller => 'versions', :action => 'show', :id => version},
  736. :class => 'version'
  737. end
  738. when 'message'
  739. if message = Message.visible.includes(:parent).find_by_id(oid)
  740. link = link_to_message(message, {:only_path => only_path}, :class => 'message')
  741. end
  742. when 'forum'
  743. if board = Board.visible.find_by_id(oid)
  744. link = link_to h(board.name), {:only_path => only_path, :controller => 'boards', :action => 'show', :id => board, :project_id => board.project},
  745. :class => 'board'
  746. end
  747. when 'news'
  748. if news = News.visible.find_by_id(oid)
  749. link = link_to h(news.title), {:only_path => only_path, :controller => 'news', :action => 'show', :id => news},
  750. :class => 'news'
  751. end
  752. when 'project'
  753. if p = Project.visible.find_by_id(oid)
  754. link = link_to_project(p, {:only_path => only_path}, :class => 'project')
  755. end
  756. end
  757. elsif sep == ':'
  758. # removes the double quotes if any
  759. name = identifier.gsub(%r{^"(.*)"$}, "\\1")
  760. name = CGI.unescapeHTML(name)
  761. case prefix
  762. when 'document'
  763. if project && document = project.documents.visible.find_by_title(name)
  764. link = link_to h(document.title), {:only_path => only_path, :controller => 'documents', :action => 'show', :id => document},
  765. :class => 'document'
  766. end
  767. when 'version'
  768. if project && version = project.versions.visible.find_by_name(name)
  769. link = link_to h(version.name), {:only_path => only_path, :controller => 'versions', :action => 'show', :id => version},
  770. :class => 'version'
  771. end
  772. when 'forum'
  773. if project && board = project.boards.visible.find_by_name(name)
  774. link = link_to h(board.name), {:only_path => only_path, :controller => 'boards', :action => 'show', :id => board, :project_id => board.project},
  775. :class => 'board'
  776. end
  777. when 'news'
  778. if project && news = project.news.visible.find_by_title(name)
  779. link = link_to h(news.title), {:only_path => only_path, :controller => 'news', :action => 'show', :id => news},
  780. :class => 'news'
  781. end
  782. when 'commit', 'source', 'export'
  783. if project
  784. repository = nil
  785. if name =~ %r{^(([a-z0-9\-_]+)\|)(.+)$}
  786. repo_prefix, repo_identifier, name = $1, $2, $3
  787. repository = project.repositories.detect {|repo| repo.identifier == repo_identifier}
  788. else
  789. repository = project.repository
  790. end
  791. if prefix == 'commit'
  792. if repository && (changeset = Changeset.visible.where("repository_id = ? AND scmid LIKE ?", repository.id, "#{name}%").first)
  793. 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},
  794. :class => 'changeset',
  795. :title => truncate_single_line_raw(changeset.comments, 100)
  796. end
  797. else
  798. if repository && User.current.allowed_to?(:browse_repository, project)
  799. name =~ %r{^[/\\]*(.*?)(@([^/\\@]+?))?(#(L\d+))?$}
  800. path, rev, anchor = $1, $3, $5
  801. link = link_to h("#{project_prefix}#{prefix}:#{repo_prefix}#{name}"), {:controller => 'repositories', :action => (prefix == 'export' ? 'raw' : 'entry'), :id => project, :repository_id => repository.identifier_param,
  802. :path => to_path_param(path),
  803. :rev => rev,
  804. :anchor => anchor},
  805. :class => (prefix == 'export' ? 'source download' : 'source')
  806. end
  807. end
  808. repo_prefix = nil
  809. end
  810. when 'attachment'
  811. attachments = options[:attachments] || []
  812. attachments += obj.attachments if obj.respond_to?(:attachments)
  813. if attachments && attachment = Attachment.latest_attach(attachments, name)
  814. link = link_to_attachment(attachment, :only_path => only_path, :download => true, :class => 'attachment')
  815. end
  816. when 'project'
  817. if p = Project.visible.where("identifier = :s OR LOWER(name) = :s", :s => name.downcase).first
  818. link = link_to_project(p, {:only_path => only_path}, :class => 'project')
  819. end
  820. end
  821. end
  822. end
  823. (leading + (link || "#{project_prefix}#{prefix}#{repo_prefix}#{sep}#{identifier}#{comment_suffix}"))
  824. end
  825. end
  826. HEADING_RE = /(<h(\d)( [^>]+)?>(.+?)<\/h(\d)>)/i unless const_defined?(:HEADING_RE)
  827. def parse_sections(text, project, obj, attr, only_path, options)
  828. return unless options[:edit_section_links]
  829. text.gsub!(HEADING_RE) do
  830. heading = $1
  831. @current_section += 1
  832. if @current_section > 1
  833. content_tag('div',
  834. link_to(image_tag('edit.png'), options[:edit_section_links].merge(:section => @current_section)),
  835. :class => 'contextual',
  836. :title => l(:button_edit_section),
  837. :id => "section-#{@current_section}") + heading.html_safe
  838. else
  839. heading
  840. end
  841. end
  842. end
  843. # Headings and TOC
  844. # Adds ids and links to headings unless options[:headings] is set to false
  845. def parse_headings(text, project, obj, attr, only_path, options)
  846. return if options[:headings] == false
  847. text.gsub!(HEADING_RE) do
  848. level, attrs, content = $2.to_i, $3, $4
  849. item = strip_tags(content).strip
  850. anchor = sanitize_anchor_name(item)
  851. # used for single-file wiki export
  852. anchor = "#{obj.page.title}_#{anchor}" if options[:wiki_links] == :anchor && (obj.is_a?(WikiContent) || obj.is_a?(WikiContent::Version))
  853. @heading_anchors[anchor] ||= 0
  854. idx = (@heading_anchors[anchor] += 1)
  855. if idx > 1
  856. anchor = "#{anchor}-#{idx}"
  857. end
  858. @parsed_headings << [level, anchor, item]
  859. "<a name=\"#{anchor}\"></a>\n<h#{level} #{attrs}>#{content}<a href=\"##{anchor}\" class=\"wiki-anchor\">&para;</a></h#{level}>"
  860. end
  861. end
  862. MACROS_RE = /(
  863. (!)? # escaping
  864. (
  865. \{\{ # opening tag
  866. ([\w]+) # macro name
  867. (\(([^\n\r]*?)\))? # optional arguments
  868. ([\n\r].*?[\n\r])? # optional block of text
  869. \}\} # closing tag
  870. )
  871. )/mx unless const_defined?(:MACROS_RE)
  872. MACRO_SUB_RE = /(
  873. \{\{
  874. macro\((\d+)\)
  875. \}\}
  876. )/x unless const_defined?(:MACRO_SUB_RE)
  877. # Extracts macros from text
  878. def catch_macros(text)
  879. macros = {}
  880. text.gsub!(MACROS_RE) do
  881. all, macro = $1, $4.downcase
  882. if macro_exists?(macro) || all =~ MACRO_SUB_RE
  883. index = macros.size
  884. macros[index] = all
  885. "{{macro(#{index})}}"
  886. else
  887. all
  888. end
  889. end
  890. macros
  891. end
  892. # Executes and replaces macros in text
  893. def inject_macros(text, obj, macros, execute=true)
  894. text.gsub!(MACRO_SUB_RE) do
  895. all, index = $1, $2.to_i
  896. orig = macros.delete(index)
  897. if execute && orig && orig =~ MACROS_RE
  898. esc, all, macro, args, block = $2, $3, $4.downcase, $6.to_s, $7.try(:strip)
  899. if esc.nil?
  900. h(exec_macro(macro, obj, args, block) || all)
  901. else
  902. h(all)
  903. end
  904. elsif orig
  905. h(orig)
  906. else
  907. h(all)
  908. end
  909. end
  910. end
  911. TOC_RE = /<p>\{\{((<|&lt;)|(>|&gt;))?toc\}\}<\/p>/i unless const_defined?(:TOC_RE)
  912. # Renders the TOC with given headings
  913. def replace_toc(text, headings)
  914. text.gsub!(TOC_RE) do
  915. left_align, right_align = $2, $3
  916. # Keep only the 4 first levels
  917. headings = headings.select{|level, anchor, item| level <= 4}
  918. if headings.empty?
  919. ''
  920. else
  921. div_class = 'toc'
  922. div_class << ' right' if right_align
  923. div_class << ' left' if left_align
  924. out = "<ul class=\"#{div_class}\"><li>"
  925. root = headings.map(&:first).min
  926. current = root
  927. started = false
  928. headings.each do |level, anchor, item|
  929. if level > current
  930. out << '<ul><li>' * (level - current)
  931. elsif level < current
  932. out << "</li></ul>\n" * (current - level) + "</li><li>"
  933. elsif started
  934. out << '</li><li>'
  935. end
  936. out << "<a href=\"##{anchor}\">#{item}</a>"
  937. current = level
  938. started = true
  939. end
  940. out << '</li></ul>' * (current - root)
  941. out << '</li></ul>'
  942. end
  943. end
  944. end
  945. # Same as Rails' simple_format helper without using paragraphs
  946. def simple_format_without_paragraph(text)
  947. text.to_s.
  948. gsub(/\r\n?/, "\n"). # \r\n and \r -> \n
  949. gsub(/\n\n+/, "<br /><br />"). # 2+ newline -> 2 br
  950. gsub(/([^\n]\n)(?=[^\n])/, '\1<br />'). # 1 newline -> br
  951. html_safe
  952. end
  953. def lang_options_for_select(blank=true)
  954. (blank ? [["(auto)", ""]] : []) + languages_options
  955. end
  956. def label_tag_for(name, option_tags = nil, options = {})
  957. label_text = l(("field_"+field.to_s.gsub(/\_id$/, "")).to_sym) + (options.delete(:required) ? @template.content_tag("span", " *", :class => "required"): "")
  958. content_tag("label", label_text)
  959. end
  960. def labelled_form_for(*args, &proc)
  961. args << {} unless args.last.is_a?(Hash)
  962. options = args.last
  963. if args.first.is_a?(Symbol)
  964. options.merge!(:as => args.shift)
  965. end
  966. options.merge!({:builder => Redmine::Views::LabelledFormBuilder})
  967. form_for(*args, &proc)
  968. end
  969. def labelled_fields_for(*args, &proc)
  970. args << {} unless args.last.is_a?(Hash)
  971. options = args.last
  972. options.merge!({:builder => Redmine::Views::LabelledFormBuilder})
  973. fields_for(*args, &proc)
  974. end
  975. def labelled_remote_form_for(*args, &proc)
  976. ActiveSupport::Deprecation.warn "ApplicationHelper#labelled_remote_form_for is deprecated and will be removed in Redmine 2.2."
  977. args << {} unless args.last.is_a?(Hash)
  978. options = args.last
  979. options.merge!({:builder => Redmine::Views::LabelledFormBuilder, :remote => true})
  980. form_for(*args, &proc)
  981. end
  982. def error_messages_for(*objects)
  983. html = ""
  984. objects = objects.map {|o| o.is_a?(String) ? instance_variable_get("@#{o}") : o}.compact
  985. errors = objects.map {|o| o.errors.full_messages}.flatten
  986. if errors.any?
  987. html << "<div id='errorExplanation'><ul>\n"
  988. errors.each do |error|
  989. html << "<li>#{h error}</li>\n"
  990. end
  991. html << "</ul></div>\n"
  992. end
  993. html.html_safe
  994. end
  995. def delete_link(url, options={})
  996. options = {
  997. :method => :delete,
  998. :data => {:confirm => l(:text_are_you_sure)},
  999. :class => 'icon icon-del'
  1000. }.merge(options)
  1001. link_to l(:button_delete), url, options
  1002. end
  1003. def preview_link(url, form, target='preview', options={})
  1004. content_tag 'a', l(:label_preview), {
  1005. :href => "#",
  1006. :onclick => %|submitPreview("#{escape_javascript url_for(url)}", "#{escape_javascript form}", "#{escape_javascript target}"); return false;|,
  1007. :accesskey => accesskey(:preview)
  1008. }.merge(options)
  1009. end
  1010. def link_to_function(name, function, html_options={})
  1011. content_tag(:a, name, {:href => '#', :onclick => "#{function}; return false;"}.merge(html_options))
  1012. end
  1013. # Helper to render JSON in views
  1014. def raw_json(arg)
  1015. arg.to_json.to_s.gsub('/', '\/').html_safe
  1016. end
  1017. def back_url
  1018. url = params[:back_url]
  1019. if url.nil? && referer = request.env['HTTP_REFERER']
  1020. url = CGI.unescape(referer.to_s)
  1021. end
  1022. url
  1023. end
  1024. def back_url_hidden_field_tag
  1025. url = back_url
  1026. hidden_field_tag('back_url', url, :id => nil) unless url.blank?
  1027. end
  1028. def check_all_links(form_name)
  1029. link_to_function(l(:button_check_all), "checkAll('#{form_name}', true)") +
  1030. " | ".html_safe +
  1031. link_to_function(l(:button_uncheck_all), "checkAll('#{form_name}', false)")
  1032. end
  1033. def progress_bar(pcts, options={})
  1034. pcts = [pcts, pcts] unless pcts.is_a?(Array)
  1035. pcts = pcts.collect(&:round)
  1036. pcts[1] = pcts[1] - pcts[0]
  1037. pcts << (100 - pcts[1] - pcts[0])
  1038. width = options[:width] || '100px;'
  1039. legend = options[:legend] || ''
  1040. content_tag('table',
  1041. content_tag('tr',
  1042. (pcts[0] > 0 ? content_tag('td', '', :style => "width: #{pcts[0]}%;", :class => 'closed') : ''.html_safe) +
  1043. (pcts[1] > 0 ? content_tag('td', '', :style => "width: #{pcts[1]}%;", :class => 'done') : ''.html_safe) +
  1044. (pcts[2] > 0 ? content_tag('td', '', :style => "width: #{pcts[2]}%;", :class => 'todo') : ''.html_safe)
  1045. ), :class => "progress progress-#{pcts[0]}", :style => "width: #{width};").html_safe +
  1046. content_tag('p', legend, :class => 'percent').html_safe
  1047. end
  1048. def checked_image(checked=true)
  1049. if checked
  1050. image_tag 'toggle_check.png'
  1051. end
  1052. end
  1053. def context_menu(url)
  1054. unless @context_menu_included
  1055. content_for :header_tags do
  1056. javascript_include_tag('context_menu') +
  1057. stylesheet_link_tag('context_menu')
  1058. end
  1059. if l(:direction) == 'rtl'
  1060. content_for :header_tags do
  1061. stylesheet_link_tag('context_menu_rtl')
  1062. end
  1063. end
  1064. @context_menu_included = true
  1065. end
  1066. javascript_tag "contextMenuInit('#{ url_for(url) }')"
  1067. end
  1068. def calendar_for(field_id)
  1069. include_calendar_headers_tags
  1070. javascript_tag("$(function() { $('##{field_id}').datepicker(datepickerOptions); });")
  1071. end
  1072. def include_calendar_headers_tags
  1073. unless @calendar_headers_tags_included
  1074. tags = javascript_include_tag("datepicker")
  1075. @calendar_headers_tags_included = true
  1076. content_for :header_tags do
  1077. start_of_week = Setting.start_of_week
  1078. start_of_week = l(:general_first_day_of_week, :default => '1') if start_of_week.blank?
  1079. # Redmine uses 1..7 (monday..sunday) in settings and locales
  1080. # JQuery uses 0..6 (sunday..saturday), 7 needs to be changed to 0
  1081. start_of_week = start_of_week.to_i % 7
  1082. tags << javascript_tag(
  1083. "var datepickerOptions={dateFormat: 'yy-mm-dd', firstDay: #{start_of_week}, " +
  1084. "showOn: 'button', buttonImageOnly: true, buttonImage: '" +
  1085. path_to_image('/images/calendar.png') +
  1086. "', showButtonPanel: true, showWeek: true, showOtherMonths: true, " +
  1087. "selectOtherMonths: true, changeMonth: true, changeYear: true, " +
  1088. "beforeShow: beforeShowDatePicker};")
  1089. jquery_locale = l('jquery.locale', :default => current_language.to_s)
  1090. unless jquery_locale == 'en'
  1091. tags << javascript_include_tag("i18n/jquery.ui.datepicker-#{jquery_locale}.js")
  1092. end
  1093. tags
  1094. end
  1095. end
  1096. end
  1097. # Overrides Rails' stylesheet_link_tag with themes and plugins support.
  1098. # Examples:
  1099. # stylesheet_link_tag('styles') # => picks styles.css from the current theme or defaults
  1100. # stylesheet_link_tag('styles', :plugin => 'foo) # => picks styles.css from plugin's assets
  1101. #
  1102. def stylesheet_link_tag(*sources)
  1103. options = sources.last.is_a?(Hash) ? sources.pop : {}
  1104. plugin = options.delete(:plugin)
  1105. sources = sources.map do |source|
  1106. if plugin
  1107. "/plugin_assets/#{plugin}/stylesheets/#{source}"
  1108. elsif current_theme && current_theme.stylesheets.include?(source)
  1109. current_theme.stylesheet_path(source)
  1110. else
  1111. source
  1112. end
  1113. end
  1114. super sources, options
  1115. end
  1116. # Overrides Rails' image_tag with themes and plugins support.
  1117. # Examples:
  1118. # image_tag('image.png') # => picks image.png from the current theme or defaults
  1119. # image_tag('image.png', :plugin => 'foo) # => picks image.png from plugin's assets
  1120. #
  1121. def image_tag(source, options={})
  1122. if plugin = options.delete(:plugin)
  1123. source = "/plugin_assets/#{plugin}/images/#{source}"
  1124. elsif current_theme && current_theme.images.include?(source)
  1125. source = current_theme.image_path(source)
  1126. end
  1127. super source, options
  1128. end
  1129. # Overrides Rails' javascript_include_tag with plugins support
  1130. # Examples:
  1131. # javascript_include_tag('scripts') # => picks scripts.js from defaults
  1132. # javascript_include_tag('scripts', :plugin => 'foo) # => picks scripts.js from plugin's assets
  1133. #
  1134. def javascript_include_tag(*sources)
  1135. options = sources.last.is_a?(Hash) ? sources.pop : {}
  1136. if plugin = options.delete(:plugin)
  1137. sources = sources.map do |source|
  1138. if plugin
  1139. "/plugin_assets/#{plugin}/javascripts/#{source}"
  1140. else
  1141. source
  1142. end
  1143. end
  1144. end
  1145. super sources, options
  1146. end
  1147. # TODO: remove this in 2.5.0
  1148. def has_content?(name)
  1149. content_for?(name)
  1150. end
  1151. def sidebar_content?
  1152. content_for?(:sidebar) || view_layouts_base_sidebar_hook_response.present?
  1153. end
  1154. def view_layouts_base_sidebar_hook_response
  1155. @view_layouts_base_sidebar_hook_response ||= call_hook(:view_layouts_base_sidebar)
  1156. end
  1157. def email_delivery_enabled?
  1158. !!ActionMailer::Base.perform_deliveries
  1159. end
  1160. # Returns the avatar image tag for the given +user+ if avatars are enabled
  1161. # +user+ can be a User or a string that will be scanned for an email address (eg. 'joe <joe@foo.bar>')
  1162. def avatar(user, options = { })
  1163. if Setting.gravatar_enabled?
  1164. options.merge!({:ssl => (request && request.ssl?), :default => Setting.gravatar_default})
  1165. email = nil
  1166. if user.respond_to?(:mail)
  1167. email = user.mail
  1168. elsif user.to_s =~ %r{<(.+?)>}
  1169. email = $1
  1170. end
  1171. return gravatar(email.to_s.downcase, options) unless email.blank? rescue nil
  1172. else
  1173. ''
  1174. end
  1175. end
  1176. def sanitize_anchor_name(anchor)
  1177. if ''.respond_to?(:encoding) || RUBY_PLATFORM == 'java'
  1178. anchor.gsub(%r{[^\s\-\p{Word}]}, '').gsub(%r{\s+(\-+\s*)?}, '-')
  1179. else
  1180. # TODO: remove when ruby1.8 is no longer supported
  1181. anchor.gsub(%r{[^\w\s\-]}, '').gsub(%r{\s+(\-+\s*)?}, '-')
  1182. end
  1183. end
  1184. # Returns the javascript tags that are included in the html layout head
  1185. def javascript_heads
  1186. tags = javascript_include_tag('jquery-1.8.3-ui-1.9.2-ujs-2.0.3', 'application')
  1187. unless User.current.pref.warn_on_leaving_unsaved == '0'
  1188. tags << "\n".html_safe + javascript_tag("$(window).load(function(){ warnLeavingUnsaved('#{escape_javascript l(:text_warn_on_leaving_unsaved)}'); });")
  1189. end
  1190. tags
  1191. end
  1192. def favicon
  1193. "<link rel='shortcut icon' href='#{favicon_path}' />".html_safe
  1194. end
  1195. # Returns the path to the favicon
  1196. def favicon_path
  1197. icon = (current_theme && current_theme.favicon?) ? current_theme.favicon_path : '/favicon.ico'
  1198. image_path(icon)
  1199. end
  1200. # Returns the full URL to the favicon
  1201. def favicon_url
  1202. # TODO: use #image_url introduced in Rails4
  1203. path = favicon_path
  1204. base = url_for(:controller => 'welcome', :action => 'index', :only_path => false)
  1205. base.sub(%r{/+$},'') + '/' + path.sub(%r{^/+},'')
  1206. end
  1207. def robot_exclusion_tag
  1208. '<meta name="robots" content="noindex,follow,noarchive" />'.html_safe
  1209. end
  1210. # Returns true if arg is expected in the API response
  1211. def include_in_api_response?(arg)
  1212. unless @included_in_api_response
  1213. param = params[:include]
  1214. @included_in_api_response = param.is_a?(Array) ? param.collect(&:to_s) : param.to_s.split(',')
  1215. @included_in_api_response.collect!(&:strip)
  1216. end
  1217. @included_in_api_response.include?(arg.to_s)
  1218. end
  1219. # Returns options or nil if nometa param or X-Redmine-Nometa header
  1220. # was set in the request
  1221. def api_meta(options)
  1222. if params[:nometa].present? || request.headers['X-Redmine-Nometa']
  1223. # compatibility mode for activeresource clients that raise
  1224. # an error when deserializing an array with attributes
  1225. nil
  1226. else
  1227. options
  1228. end
  1229. end
  1230. private
  1231. def wiki_helper
  1232. helper = Redmine::WikiFormatting.helper_for(Setting.text_formatting)
  1233. extend helper
  1234. return self
  1235. end
  1236. def link_to_content_update(text, url_params = {}, html_options = {})
  1237. link_to(text, url_params, html_options)
  1238. end
  1239. end