選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

application_helper.rb 58KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612
  1. # frozen_string_literal: true
  2. # Redmine - project management software
  3. # Copyright (C) 2006-2017 Jean-Philippe Lang
  4. #
  5. # This program is free software; you can redistribute it and/or
  6. # modify it under the terms of the GNU General Public License
  7. # as published by the Free Software Foundation; either version 2
  8. # of the License, or (at your option) any later version.
  9. #
  10. # This program is distributed in the hope that it will be useful,
  11. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. # GNU General Public License for more details.
  14. #
  15. # You should have received a copy of the GNU General Public License
  16. # along with this program; if not, write to the Free Software
  17. # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  18. require 'forwardable'
  19. require 'cgi'
  20. module ApplicationHelper
  21. include Redmine::WikiFormatting::Macros::Definitions
  22. include Redmine::I18n
  23. include GravatarHelper::PublicMethods
  24. include Redmine::Pagination::Helper
  25. include Redmine::SudoMode::Helper
  26. include Redmine::Themes::Helper
  27. include Redmine::Hook::Helper
  28. include Redmine::Helpers::URL
  29. extend Forwardable
  30. def_delegators :wiki_helper, :wikitoolbar_for, :heads_for_wiki_formatter
  31. # Return true if user is authorized for controller/action, otherwise false
  32. def authorize_for(controller, action)
  33. User.current.allowed_to?({:controller => controller, :action => action}, @project)
  34. end
  35. # Display a link if user is authorized
  36. #
  37. # @param [String] name Anchor text (passed to link_to)
  38. # @param [Hash] options Hash params. This will checked by authorize_for to see if the user is authorized
  39. # @param [optional, Hash] html_options Options passed to link_to
  40. # @param [optional, Hash] parameters_for_method_reference Extra parameters for link_to
  41. def link_to_if_authorized(name, options = {}, html_options = nil, *parameters_for_method_reference)
  42. link_to(name, options, html_options, *parameters_for_method_reference) if authorize_for(options[:controller] || params[:controller], options[:action])
  43. end
  44. # Displays a link to user's account page if active
  45. def link_to_user(user, options={})
  46. if user.is_a?(User)
  47. name = h(user.name(options[:format]))
  48. if user.active? || (User.current.admin? && user.logged?)
  49. only_path = options[:only_path].nil? ? true : options[:only_path]
  50. link_to name, user_url(user, :only_path => only_path), :class => user.css_classes
  51. else
  52. name
  53. end
  54. else
  55. h(user.to_s)
  56. end
  57. end
  58. # Displays a link to edit group page if current user is admin
  59. # Otherwise display only the group name
  60. def link_to_group(group, options={})
  61. if group.is_a?(Group)
  62. name = h(group.name)
  63. if (User.current.admin?)
  64. only_path = options[:only_path].nil? ? true : options[:only_path]
  65. link_to name, edit_group_path(group, :only_path => only_path)
  66. else
  67. name
  68. end
  69. end
  70. end
  71. # Displays a link to +issue+ with its subject.
  72. # Examples:
  73. #
  74. # link_to_issue(issue) # => Defect #6: This is the subject
  75. # link_to_issue(issue, :truncate => 6) # => Defect #6: This i...
  76. # link_to_issue(issue, :subject => false) # => Defect #6
  77. # link_to_issue(issue, :project => true) # => Foo - Defect #6
  78. # link_to_issue(issue, :subject => false, :tracker => false) # => #6
  79. #
  80. def link_to_issue(issue, options={})
  81. title = nil
  82. subject = nil
  83. text = options[:tracker] == false ? "##{issue.id}" : "#{issue.tracker} ##{issue.id}"
  84. if options[:subject] == false
  85. title = issue.subject.truncate(60)
  86. else
  87. subject = issue.subject
  88. if truncate_length = options[:truncate]
  89. subject = subject.truncate(truncate_length)
  90. end
  91. end
  92. only_path = options[:only_path].nil? ? true : options[:only_path]
  93. s = link_to(text, issue_url(issue, :only_path => only_path),
  94. :class => issue.css_classes, :title => title)
  95. s << h(": #{subject}") if subject
  96. s = h("#{issue.project} - ") + s if options[:project]
  97. s
  98. end
  99. # Generates a link to an attachment.
  100. # Options:
  101. # * :text - Link text (default to attachment filename)
  102. # * :download - Force download (default: false)
  103. def link_to_attachment(attachment, options={})
  104. text = options.delete(:text) || attachment.filename
  105. if options.delete(:download)
  106. route_method = :download_named_attachment_url
  107. options[:filename] = attachment.filename
  108. else
  109. route_method = :attachment_url
  110. # make sure we don't have an extraneous :filename in the options
  111. options.delete(:filename)
  112. end
  113. html_options = options.slice!(:only_path, :filename)
  114. options[:only_path] = true unless options.key?(:only_path)
  115. url = send(route_method, attachment, options)
  116. link_to text, url, html_options
  117. end
  118. # Generates a link to a SCM revision
  119. # Options:
  120. # * :text - Link text (default to the formatted revision)
  121. def link_to_revision(revision, repository, options={})
  122. if repository.is_a?(Project)
  123. repository = repository.repository
  124. end
  125. text = options.delete(:text) || format_revision(revision)
  126. rev = revision.respond_to?(:identifier) ? revision.identifier : revision
  127. link_to(
  128. h(text),
  129. {:controller => 'repositories', :action => 'revision', :id => repository.project, :repository_id => repository.identifier_param, :rev => rev},
  130. :title => l(:label_revision_id, format_revision(revision)),
  131. :accesskey => options[:accesskey]
  132. )
  133. end
  134. # Generates a link to a message
  135. def link_to_message(message, options={}, html_options = nil)
  136. link_to(
  137. message.subject.truncate(60),
  138. board_message_url(message.board_id, message.parent_id || message.id, {
  139. :r => (message.parent_id && message.id),
  140. :anchor => (message.parent_id ? "message-#{message.id}" : nil),
  141. :only_path => true
  142. }.merge(options)),
  143. html_options
  144. )
  145. end
  146. # Generates a link to a project if active
  147. # Examples:
  148. #
  149. # link_to_project(project) # => link to the specified project overview
  150. # link_to_project(project, {:only_path => false}, :class => "project") # => 3rd arg adds html options
  151. # link_to_project(project, {}, :class => "project") # => html options with default url (project overview)
  152. #
  153. def link_to_project(project, options={}, html_options = nil)
  154. if project.archived?
  155. h(project.name)
  156. else
  157. link_to project.name,
  158. project_url(project, {:only_path => true}.merge(options)),
  159. html_options
  160. end
  161. end
  162. # Generates a link to a project settings if active
  163. def link_to_project_settings(project, options={}, html_options=nil)
  164. if project.active?
  165. link_to project.name, settings_project_path(project, options), html_options
  166. elsif project.archived?
  167. h(project.name)
  168. else
  169. link_to project.name, project_path(project, options), html_options
  170. end
  171. end
  172. # Generates a link to a version
  173. def link_to_version(version, options = {})
  174. return '' unless version && version.is_a?(Version)
  175. options = {:title => format_date(version.effective_date)}.merge(options)
  176. link_to_if version.visible?, format_version_name(version), version_path(version), options
  177. end
  178. RECORD_LINK = {
  179. 'CustomValue' => -> (custom_value) { link_to_record(custom_value.customized) },
  180. 'Document' => -> (document) { link_to(document.title, document_path(document)) },
  181. 'Group' => -> (group) { link_to(group.name, group_path(group)) },
  182. 'Issue' => -> (issue) { link_to_issue(issue, :subject => false) },
  183. 'Message' => -> (message) { link_to_message(message) },
  184. 'News' => -> (news) { link_to(news.title, news_path(news)) },
  185. 'Project' => -> (project) { link_to_project(project) },
  186. 'User' => -> (user) { link_to_user(user) },
  187. 'Version' => -> (version) { link_to_version(version) },
  188. 'WikiPage' => -> (wiki_page) { link_to(wiki_page.pretty_title, project_wiki_page_path(wiki_page.project, wiki_page.title)) }
  189. }
  190. def link_to_record(record)
  191. if link = RECORD_LINK[record.class.name]
  192. self.instance_exec(record, &link)
  193. end
  194. end
  195. ATTACHMENT_CONTAINER_LINK = {
  196. # Custom list, since project/version attachments are listed in the files
  197. # view and not in the project/milestone view
  198. 'Project' => -> (project) { link_to(l(:project_module_files), project_files_path(project)) },
  199. 'Version' => -> (version) { link_to(l(:project_module_files), project_files_path(version.project)) },
  200. }
  201. def link_to_attachment_container(attachment_container)
  202. if link = ATTACHMENT_CONTAINER_LINK[attachment_container.class.name] ||
  203. RECORD_LINK[attachment_container.class.name]
  204. self.instance_exec(attachment_container, &link)
  205. end
  206. end
  207. # Helper that formats object for html or text rendering
  208. def format_object(object, html=true, &block)
  209. if block_given?
  210. object = yield object
  211. end
  212. case object.class.name
  213. when 'Array'
  214. formatted_objects = object.map {|o| format_object(o, html)}
  215. html ? safe_join(formatted_objects, ', ') : formatted_objects.join(', ')
  216. when 'Time'
  217. format_time(object)
  218. when 'Date'
  219. format_date(object)
  220. when 'Fixnum'
  221. object.to_s
  222. when 'Float'
  223. sprintf "%.2f", object
  224. when 'User'
  225. html ? link_to_user(object) : object.to_s
  226. when 'Project'
  227. html ? link_to_project(object) : object.to_s
  228. when 'Version'
  229. html ? link_to_version(object) : object.to_s
  230. when 'TrueClass'
  231. l(:general_text_Yes)
  232. when 'FalseClass'
  233. l(:general_text_No)
  234. when 'Issue'
  235. object.visible? && html ? link_to_issue(object) : "##{object.id}"
  236. when 'Attachment'
  237. html ? link_to_attachment(object) : object.filename
  238. when 'CustomValue', 'CustomFieldValue'
  239. if object.custom_field
  240. f = object.custom_field.format.formatted_custom_value(self, object, html)
  241. if f.nil? || f.is_a?(String)
  242. f
  243. else
  244. format_object(f, html, &block)
  245. end
  246. else
  247. object.value.to_s
  248. end
  249. else
  250. html ? h(object) : object.to_s
  251. end
  252. end
  253. def wiki_page_path(page, options={})
  254. url_for({:controller => 'wiki', :action => 'show', :project_id => page.project, :id => page.title}.merge(options))
  255. end
  256. def thumbnail_tag(attachment)
  257. thumbnail_size = Setting.thumbnails_size.to_i
  258. link_to(
  259. image_tag(
  260. thumbnail_path(attachment),
  261. :srcset => "#{thumbnail_path(attachment, :size => thumbnail_size * 2)} 2x",
  262. :style => "max-width: #{thumbnail_size}px; max-height: #{thumbnail_size}px;"
  263. ),
  264. attachment_path(
  265. attachment
  266. ),
  267. :title => attachment.filename
  268. )
  269. end
  270. def toggle_link(name, id, options={})
  271. onclick = +"$('##{id}').toggle(); "
  272. onclick << (options[:focus] ? "$('##{options[:focus]}').focus(); " : "this.blur(); ")
  273. onclick << "$(window).scrollTop($('##{options[:focus]}').position().top); " if options[:scroll]
  274. onclick << "return false;"
  275. link_to(name, "#", :onclick => onclick)
  276. end
  277. # Used to format item titles on the activity view
  278. def format_activity_title(text)
  279. text
  280. end
  281. def format_activity_day(date)
  282. date == User.current.today ? l(:label_today).titleize : format_date(date)
  283. end
  284. def format_activity_description(text)
  285. h(text.to_s.truncate(120).gsub(%r{[\r\n]*<(pre|code)>.*$}m, '...')
  286. ).gsub(/[\r\n]+/, "<br />").html_safe
  287. end
  288. def format_version_name(version)
  289. if version.project == @project
  290. h(version)
  291. else
  292. h("#{version.project} - #{version}")
  293. end
  294. end
  295. def format_changeset_comments(changeset, options={})
  296. method = options[:short] ? :short_comments : :comments
  297. textilizable changeset, method, :formatting => Setting.commit_logs_formatting?
  298. end
  299. def due_date_distance_in_words(date)
  300. if date
  301. l((date < User.current.today ? :label_roadmap_overdue : :label_roadmap_due_in), distance_of_date_in_words(User.current.today, date))
  302. end
  303. end
  304. # Renders a tree of projects as a nested set of unordered lists
  305. # The given collection may be a subset of the whole project tree
  306. # (eg. some intermediate nodes are private and can not be seen)
  307. def render_project_nested_lists(projects, &block)
  308. s = +''
  309. if projects.any?
  310. ancestors = []
  311. original_project = @project
  312. projects.sort_by(&:lft).each do |project|
  313. # set the project environment to please macros.
  314. @project = project
  315. if (ancestors.empty? || project.is_descendant_of?(ancestors.last))
  316. s << "<ul class='projects #{ ancestors.empty? ? 'root' : nil}'>\n"
  317. else
  318. ancestors.pop
  319. s << "</li>"
  320. while (ancestors.any? && !project.is_descendant_of?(ancestors.last))
  321. ancestors.pop
  322. s << "</ul></li>\n"
  323. end
  324. end
  325. classes = (ancestors.empty? ? 'root' : 'child')
  326. s << "<li class='#{classes}'><div class='#{classes}'>"
  327. s << h(block_given? ? capture(project, &block) : project.name)
  328. s << "</div>\n"
  329. ancestors << project
  330. end
  331. s << ("</li></ul>\n" * ancestors.size)
  332. @project = original_project
  333. end
  334. s.html_safe
  335. end
  336. def render_page_hierarchy(pages, node=nil, options={})
  337. content = +''
  338. if pages[node]
  339. content << "<ul class=\"pages-hierarchy\">\n"
  340. pages[node].each do |page|
  341. content << "<li>"
  342. content << link_to(h(page.pretty_title), {:controller => 'wiki', :action => 'show', :project_id => page.project, :id => page.title, :version => nil},
  343. :title => (options[:timestamp] && page.updated_on ? l(:label_updated_time, distance_of_time_in_words(Time.now, page.updated_on)) : nil))
  344. content << "\n" + render_page_hierarchy(pages, page.id, options) if pages[page.id]
  345. content << "</li>\n"
  346. end
  347. content << "</ul>\n"
  348. end
  349. content.html_safe
  350. end
  351. # Renders flash messages
  352. def render_flash_messages
  353. s = +''
  354. flash.each do |k,v|
  355. s << content_tag('div', v.html_safe, :class => "flash #{k}", :id => "flash_#{k}")
  356. end
  357. s.html_safe
  358. end
  359. # Renders tabs and their content
  360. def render_tabs(tabs, selected=params[:tab])
  361. if tabs.any?
  362. unless tabs.detect {|tab| tab[:name] == selected}
  363. selected = nil
  364. end
  365. selected ||= tabs.first[:name]
  366. render :partial => 'common/tabs', :locals => {:tabs => tabs, :selected_tab => selected}
  367. else
  368. content_tag 'p', l(:label_no_data), :class => "nodata"
  369. end
  370. end
  371. # Returns the default scope for the quick search form
  372. # Could be 'all', 'my_projects', 'subprojects' or nil (current project)
  373. def default_search_project_scope
  374. if @project && !@project.leaf?
  375. 'subprojects'
  376. end
  377. end
  378. # Returns an array of projects that are displayed in the quick-jump box
  379. def projects_for_jump_box(user=User.current)
  380. if user.logged?
  381. user.projects.active.select(:id, :name, :identifier, :lft, :rgt).to_a
  382. else
  383. []
  384. end
  385. end
  386. def render_projects_for_jump_box(projects, selected=nil)
  387. jump = params[:jump].presence || current_menu_item
  388. s = (+'').html_safe
  389. project_tree(projects) do |project, level|
  390. padding = level * 16
  391. text = content_tag('span', project.name, :style => "padding-left:#{padding}px;")
  392. s << link_to(text, project_path(project, :jump => jump), :title => project.name, :class => (project == selected ? 'selected' : nil))
  393. end
  394. s
  395. end
  396. # Renders the project quick-jump box
  397. def render_project_jump_box
  398. projects = projects_for_jump_box(User.current)
  399. if @project && @project.persisted?
  400. text = @project.name_was
  401. end
  402. text ||= l(:label_jump_to_a_project)
  403. url = autocomplete_projects_path(:format => 'js', :jump => current_menu_item)
  404. trigger = content_tag('span', text, :class => 'drdn-trigger')
  405. q = text_field_tag('q', '', :id => 'projects-quick-search', :class => 'autocomplete', :data => {:automcomplete_url => url}, :autocomplete => 'off')
  406. all = link_to(l(:label_project_all), projects_path(:jump => current_menu_item), :class => (@project.nil? && controller.class.main_menu ? 'selected' : nil))
  407. content = content_tag('div',
  408. content_tag('div', q, :class => 'quick-search') +
  409. content_tag('div', render_projects_for_jump_box(projects, @project), :class => 'drdn-items projects selection') +
  410. content_tag('div', all, :class => 'drdn-items all-projects selection'),
  411. :class => 'drdn-content'
  412. )
  413. content_tag('div', trigger + content, :id => "project-jump", :class => "drdn")
  414. end
  415. def project_tree_options_for_select(projects, options = {})
  416. s = ''.html_safe
  417. if blank_text = options[:include_blank]
  418. if blank_text == true
  419. blank_text = '&nbsp;'.html_safe
  420. end
  421. s << content_tag('option', blank_text, :value => '')
  422. end
  423. project_tree(projects) do |project, level|
  424. name_prefix = (level > 0 ? '&nbsp;' * 2 * level + '&#187; ' : '').html_safe
  425. tag_options = {:value => project.id}
  426. if project == options[:selected] || (options[:selected].respond_to?(:include?) && options[:selected].include?(project))
  427. tag_options[:selected] = 'selected'
  428. else
  429. tag_options[:selected] = nil
  430. end
  431. tag_options.merge!(yield(project)) if block_given?
  432. s << content_tag('option', name_prefix + h(project), tag_options)
  433. end
  434. s.html_safe
  435. end
  436. # Yields the given block for each project with its level in the tree
  437. #
  438. # Wrapper for Project#project_tree
  439. def project_tree(projects, options={}, &block)
  440. Project.project_tree(projects, options, &block)
  441. end
  442. def principals_check_box_tags(name, principals)
  443. s = +''
  444. principals.each do |principal|
  445. s << "<label>#{ check_box_tag name, principal.id, false, :id => nil } #{h principal}</label>\n"
  446. end
  447. s.html_safe
  448. end
  449. # Returns a string for users/groups option tags
  450. def principals_options_for_select(collection, selected=nil)
  451. s = +''
  452. if collection.include?(User.current)
  453. s << content_tag('option', "<< #{l(:label_me)} >>", :value => User.current.id)
  454. end
  455. groups = +''
  456. collection.sort.each do |element|
  457. selected_attribute = ' selected="selected"' if option_value_selected?(element, selected) || element.id.to_s == selected
  458. (element.is_a?(Group) ? groups : s) << %(<option value="#{element.id}"#{selected_attribute}>#{h element.name}</option>)
  459. end
  460. unless groups.empty?
  461. s << %(<optgroup label="#{h(l(:label_group_plural))}">#{groups}</optgroup>)
  462. end
  463. s.html_safe
  464. end
  465. def option_tag(name, text, value, selected=nil, options={})
  466. content_tag 'option', value, options.merge(:value => value, :selected => (value == selected))
  467. end
  468. def truncate_single_line_raw(string, length)
  469. string.to_s.truncate(length).gsub(%r{[\r\n]+}m, ' ')
  470. end
  471. # Truncates at line break after 250 characters or options[:length]
  472. def truncate_lines(string, options={})
  473. length = options[:length] || 250
  474. if string.to_s =~ /\A(.{#{length}}.*?)$/m
  475. "#{$1}..."
  476. else
  477. string
  478. end
  479. end
  480. def anchor(text)
  481. text.to_s.tr(' ', '_')
  482. end
  483. def html_hours(text)
  484. text.gsub(%r{(\d+)([\.:])(\d+)}, '<span class="hours hours-int">\1</span><span class="hours hours-dec">\2\3</span>').html_safe
  485. end
  486. def authoring(created, author, options={})
  487. l(options[:label] || :label_added_time_by, :author => link_to_user(author), :age => time_tag(created)).html_safe
  488. end
  489. def time_tag(time)
  490. text = distance_of_time_in_words(Time.now, time)
  491. if @project
  492. link_to(text, project_activity_path(@project, :from => User.current.time_to_date(time)), :title => format_time(time))
  493. else
  494. content_tag('abbr', text, :title => format_time(time))
  495. end
  496. end
  497. def syntax_highlight_lines(name, content)
  498. syntax_highlight(name, content).each_line.to_a
  499. end
  500. def syntax_highlight(name, content)
  501. Redmine::SyntaxHighlighting.highlight_by_filename(content, name)
  502. end
  503. def to_path_param(path)
  504. str = path.to_s.split(%r{[/\\]}).select{|p| !p.blank?}.join("/")
  505. str.blank? ? nil : str
  506. end
  507. def reorder_handle(object, options={})
  508. data = {
  509. :reorder_url => options[:url] || url_for(object),
  510. :reorder_param => options[:param] || object.class.name.underscore
  511. }
  512. content_tag('span', '',
  513. :class => "sort-handle",
  514. :data => data,
  515. :title => l(:button_sort))
  516. end
  517. def breadcrumb(*args)
  518. elements = args.flatten
  519. elements.any? ? content_tag('p', (args.join(" \xc2\xbb ") + " \xc2\xbb ").html_safe, :class => 'breadcrumb') : nil
  520. end
  521. def other_formats_links(&block)
  522. concat('<p class="other-formats">'.html_safe + l(:label_export_to))
  523. yield Redmine::Views::OtherFormatsBuilder.new(self)
  524. concat('</p>'.html_safe)
  525. end
  526. def page_header_title
  527. if @project.nil? || @project.new_record?
  528. h(Setting.app_title)
  529. else
  530. b = []
  531. ancestors = (@project.root? ? [] : @project.ancestors.visible.to_a)
  532. if ancestors.any?
  533. root = ancestors.shift
  534. b << link_to_project(root, {:jump => current_menu_item}, :class => 'root')
  535. if ancestors.size > 2
  536. b << "\xe2\x80\xa6"
  537. ancestors = ancestors[-2, 2]
  538. end
  539. b += ancestors.collect {|p| link_to_project(p, {:jump => current_menu_item}, :class => 'ancestor') }
  540. end
  541. b << content_tag(:span, h(@project), class: 'current-project')
  542. if b.size > 1
  543. separator = content_tag(:span, ' &raquo; '.html_safe, class: 'separator')
  544. path = safe_join(b[0..-2], separator) + separator
  545. b = [content_tag(:span, path.html_safe, class: 'breadcrumbs'), b[-1]]
  546. end
  547. safe_join b
  548. end
  549. end
  550. # Returns a h2 tag and sets the html title with the given arguments
  551. def title(*args)
  552. strings = args.map do |arg|
  553. if arg.is_a?(Array) && arg.size >= 2
  554. link_to(*arg)
  555. else
  556. h(arg.to_s)
  557. end
  558. end
  559. html_title args.reverse.map {|s| (s.is_a?(Array) ? s.first : s).to_s}
  560. content_tag('h2', strings.join(' &#187; ').html_safe)
  561. end
  562. # Sets the html title
  563. # Returns the html title when called without arguments
  564. # Current project name and app_title and automatically appended
  565. # Exemples:
  566. # html_title 'Foo', 'Bar'
  567. # html_title # => 'Foo - Bar - My Project - Redmine'
  568. def html_title(*args)
  569. if args.empty?
  570. title = @html_title || []
  571. title << @project.name if @project
  572. title << Setting.app_title unless Setting.app_title == title.last
  573. title.reject(&:blank?).join(' - ')
  574. else
  575. @html_title ||= []
  576. @html_title += args
  577. end
  578. end
  579. def actions_dropdown(&block)
  580. content = capture(&block)
  581. if content.present?
  582. trigger = content_tag('span', l(:button_actions), :class => 'icon-only icon-actions', :title => l(:button_actions))
  583. trigger = content_tag('span', trigger, :class => 'drdn-trigger')
  584. content = content_tag('div', content, :class => 'drdn-items')
  585. content = content_tag('div', content, :class => 'drdn-content')
  586. content_tag('span', trigger + content, :class => 'drdn')
  587. end
  588. end
  589. # Returns the theme, controller name, and action as css classes for the
  590. # HTML body.
  591. def body_css_classes
  592. css = []
  593. if theme = Redmine::Themes.theme(Setting.ui_theme)
  594. css << 'theme-' + theme.name
  595. end
  596. css << 'project-' + @project.identifier if @project && @project.identifier.present?
  597. css << 'has-main-menu' if display_main_menu?(@project)
  598. css << 'controller-' + controller_name
  599. css << 'action-' + action_name
  600. css << 'avatars-' + (Setting.gravatar_enabled? ? 'on' : 'off')
  601. if UserPreference::TEXTAREA_FONT_OPTIONS.include?(User.current.pref.textarea_font)
  602. css << "textarea-#{User.current.pref.textarea_font}"
  603. end
  604. css.join(' ')
  605. end
  606. def accesskey(s)
  607. @used_accesskeys ||= []
  608. key = Redmine::AccessKeys.key_for(s)
  609. return nil if @used_accesskeys.include?(key)
  610. @used_accesskeys << key
  611. key
  612. end
  613. # Formats text according to system settings.
  614. # 2 ways to call this method:
  615. # * with a String: textilizable(text, options)
  616. # * with an object and one of its attribute: textilizable(issue, :description, options)
  617. def textilizable(*args)
  618. options = args.last.is_a?(Hash) ? args.pop : {}
  619. case args.size
  620. when 1
  621. obj = options[:object]
  622. text = args.shift
  623. when 2
  624. obj = args.shift
  625. attr = args.shift
  626. text = obj.send(attr).to_s
  627. else
  628. raise ArgumentError, 'invalid arguments to textilizable'
  629. end
  630. return '' if text.blank?
  631. project = options[:project] || @project || (obj && obj.respond_to?(:project) ? obj.project : nil)
  632. @only_path = only_path = options.delete(:only_path) == false ? false : true
  633. text = text.dup
  634. macros = catch_macros(text)
  635. if options[:formatting] == false
  636. text = h(text)
  637. else
  638. formatting = Setting.text_formatting
  639. text = Redmine::WikiFormatting.to_html(formatting, text, :object => obj, :attribute => attr)
  640. end
  641. @parsed_headings = []
  642. @heading_anchors = {}
  643. @current_section = 0 if options[:edit_section_links]
  644. parse_sections(text, project, obj, attr, only_path, options)
  645. text = parse_non_pre_blocks(text, obj, macros) do |text|
  646. [:parse_inline_attachments, :parse_hires_images, :parse_wiki_links, :parse_redmine_links].each do |method_name|
  647. send method_name, text, project, obj, attr, only_path, options
  648. end
  649. end
  650. parse_headings(text, project, obj, attr, only_path, options)
  651. if @parsed_headings.any?
  652. replace_toc(text, @parsed_headings)
  653. end
  654. text.html_safe
  655. end
  656. def parse_non_pre_blocks(text, obj, macros)
  657. s = StringScanner.new(text)
  658. tags = []
  659. parsed = +''
  660. while !s.eos?
  661. s.scan(/(.*?)(<(\/)?(pre|code)(.*?)>|\z)/im)
  662. text, full_tag, closing, tag = s[1], s[2], s[3], s[4]
  663. if tags.empty?
  664. yield text
  665. inject_macros(text, obj, macros) if macros.any?
  666. else
  667. inject_macros(text, obj, macros, false) if macros.any?
  668. end
  669. parsed << text
  670. if tag
  671. if closing
  672. if tags.last && tags.last.casecmp(tag) == 0
  673. tags.pop
  674. end
  675. else
  676. tags << tag.downcase
  677. end
  678. parsed << full_tag
  679. end
  680. end
  681. # Close any non closing tags
  682. while tag = tags.pop
  683. parsed << "</#{tag}>"
  684. end
  685. parsed
  686. end
  687. # add srcset attribute to img tags if filename includes @2x, @3x, etc.
  688. # to support hires displays
  689. def parse_hires_images(text, project, obj, attr, only_path, options)
  690. text.gsub!(/src="([^"]+@(\dx)\.(bmp|gif|jpg|jpe|jpeg|png))"/i) do |m|
  691. filename, dpr = $1, $2
  692. m + " srcset=\"#{filename} #{dpr}\""
  693. end
  694. end
  695. def parse_inline_attachments(text, project, obj, attr, only_path, options)
  696. return if options[:inline_attachments] == false
  697. # when using an image link, try to use an attachment, if possible
  698. attachments = options[:attachments] || []
  699. attachments += obj.attachments if obj.respond_to?(:attachments)
  700. if attachments.present?
  701. text.gsub!(/src="([^\/"]+\.(bmp|gif|jpg|jpe|jpeg|png))"(\s+alt="([^"]*)")?/i) do |m|
  702. filename, ext, alt, alttext = $1, $2, $3, $4
  703. # search for the picture in attachments
  704. if found = Attachment.latest_attach(attachments, CGI.unescape(filename))
  705. image_url = download_named_attachment_url(found, found.filename, :only_path => only_path)
  706. desc = found.description.to_s.gsub('"', '')
  707. if !desc.blank? && alttext.blank?
  708. alt = " title=\"#{desc}\" alt=\"#{desc}\""
  709. end
  710. "src=\"#{image_url}\"#{alt}"
  711. else
  712. m
  713. end
  714. end
  715. end
  716. end
  717. # Wiki links
  718. #
  719. # Examples:
  720. # [[mypage]]
  721. # [[mypage|mytext]]
  722. # wiki links can refer other project wikis, using project name or identifier:
  723. # [[project:]] -> wiki starting page
  724. # [[project:|mytext]]
  725. # [[project:mypage]]
  726. # [[project:mypage|mytext]]
  727. def parse_wiki_links(text, project, obj, attr, only_path, options)
  728. text.gsub!(/(!)?(\[\[([^\n\|]+?)(\|([^\n\|]+?))?\]\])/) do |m|
  729. link_project = project
  730. esc, all, page, title = $1, $2, $3, $5
  731. if esc.nil?
  732. page = CGI.unescapeHTML(page)
  733. if page =~ /^\#(.+)$/
  734. anchor = sanitize_anchor_name($1)
  735. url = "##{anchor}"
  736. next link_to(title.present? ? title.html_safe : h(page), url, :class => 'wiki-page')
  737. end
  738. if page =~ /^([^\:]+)\:(.*)$/
  739. identifier, page = $1, $2
  740. link_project = Project.find_by_identifier(identifier) || Project.find_by_name(identifier)
  741. title ||= identifier if page.blank?
  742. end
  743. if link_project && link_project.wiki && User.current.allowed_to?(:view_wiki_pages, link_project)
  744. # extract anchor
  745. anchor = nil
  746. if page =~ /^(.+?)\#(.+)$/
  747. page, anchor = $1, $2
  748. end
  749. anchor = sanitize_anchor_name(anchor) if anchor.present?
  750. # check if page exists
  751. wiki_page = link_project.wiki.find_page(page)
  752. url = if anchor.present? && wiki_page.present? && (obj.is_a?(WikiContent) || obj.is_a?(WikiContent::Version)) && obj.page == wiki_page
  753. "##{anchor}"
  754. else
  755. case options[:wiki_links]
  756. when :local; "#{page.present? ? Wiki.titleize(page) : ''}.html" + (anchor.present? ? "##{anchor}" : '')
  757. when :anchor; "##{page.present? ? Wiki.titleize(page) : title}" + (anchor.present? ? "_#{anchor}" : '') # used for single-file wiki export
  758. else
  759. wiki_page_id = page.present? ? Wiki.titleize(page) : nil
  760. parent = wiki_page.nil? && obj.is_a?(WikiContent) && obj.page && project == link_project ? obj.page.title : nil
  761. url_for(:only_path => only_path, :controller => 'wiki', :action => 'show', :project_id => link_project,
  762. :id => wiki_page_id, :version => nil, :anchor => anchor, :parent => parent)
  763. end
  764. end
  765. link_to(title.present? ? title.html_safe : h(page), url, :class => ('wiki-page' + (wiki_page ? '' : ' new')))
  766. else
  767. # project or wiki doesn't exist
  768. all
  769. end
  770. else
  771. all
  772. end
  773. end
  774. end
  775. # Redmine links
  776. #
  777. # Examples:
  778. # Issues:
  779. # #52 -> Link to issue #52
  780. # ##52 -> Link to issue #52, including the issue's subject
  781. # Changesets:
  782. # r52 -> Link to revision 52
  783. # commit:a85130f -> Link to scmid starting with a85130f
  784. # Documents:
  785. # document#17 -> Link to document with id 17
  786. # document:Greetings -> Link to the document with title "Greetings"
  787. # document:"Some document" -> Link to the document with title "Some document"
  788. # Versions:
  789. # version#3 -> Link to version with id 3
  790. # version:1.0.0 -> Link to version named "1.0.0"
  791. # version:"1.0 beta 2" -> Link to version named "1.0 beta 2"
  792. # Attachments:
  793. # attachment:file.zip -> Link to the attachment of the current object named file.zip
  794. # Source files:
  795. # source:some/file -> Link to the file located at /some/file in the project's repository
  796. # source:some/file@52 -> Link to the file's revision 52
  797. # source:some/file#L120 -> Link to line 120 of the file
  798. # source:some/file@52#L120 -> Link to line 120 of the file's revision 52
  799. # export:some/file -> Force the download of the file
  800. # Forums:
  801. # forum#1 -> Link to forum with id 1
  802. # forum:Support -> Link to forum named "Support"
  803. # forum:"Technical Support" -> Link to forum named "Technical Support"
  804. # Forum messages:
  805. # message#1218 -> Link to message with id 1218
  806. # Projects:
  807. # project:someproject -> Link to project named "someproject"
  808. # project#3 -> Link to project with id 3
  809. # News:
  810. # news#2 -> Link to news item with id 1
  811. # news:Greetings -> Link to news item named "Greetings"
  812. # news:"First Release" -> Link to news item named "First Release"
  813. # Users:
  814. # user:jsmith -> Link to user with login jsmith
  815. # @jsmith -> Link to user with login jsmith
  816. # user#2 -> Link to user with id 2
  817. #
  818. # Links can refer other objects from other projects, using project identifier:
  819. # identifier:r52
  820. # identifier:document:"Some document"
  821. # identifier:version:1.0.0
  822. # identifier:source:some/file
  823. def parse_redmine_links(text, default_project, obj, attr, only_path, options)
  824. text.gsub!(LINKS_RE) do |_|
  825. tag_content = $~[:tag_content]
  826. leading = $~[:leading]
  827. esc = $~[:esc]
  828. project_prefix = $~[:project_prefix]
  829. project_identifier = $~[:project_identifier]
  830. prefix = $~[:prefix]
  831. repo_prefix = $~[:repo_prefix]
  832. repo_identifier = $~[:repo_identifier]
  833. sep = $~[:sep1] || $~[:sep2] || $~[:sep3] || $~[:sep4]
  834. identifier = $~[:identifier1] || $~[:identifier2] || $~[:identifier3]
  835. comment_suffix = $~[:comment_suffix]
  836. comment_id = $~[:comment_id]
  837. if tag_content
  838. $&
  839. else
  840. link = nil
  841. project = default_project
  842. if project_identifier
  843. project = Project.visible.find_by_identifier(project_identifier)
  844. end
  845. if esc.nil?
  846. if prefix.nil? && sep == 'r'
  847. if project
  848. repository = nil
  849. if repo_identifier
  850. repository = project.repositories.detect {|repo| repo.identifier == repo_identifier}
  851. else
  852. repository = project.repository
  853. end
  854. # project.changesets.visible raises an SQL error because of a double join on repositories
  855. if repository &&
  856. (changeset = Changeset.visible.
  857. find_by_repository_id_and_revision(repository.id, identifier))
  858. link = link_to(h("#{project_prefix}#{repo_prefix}r#{identifier}"),
  859. {:only_path => only_path, :controller => 'repositories',
  860. :action => 'revision', :id => project,
  861. :repository_id => repository.identifier_param,
  862. :rev => changeset.revision},
  863. :class => 'changeset',
  864. :title => truncate_single_line_raw(changeset.comments, 100))
  865. end
  866. end
  867. elsif sep == '#' || sep == '##'
  868. oid = identifier.to_i
  869. case prefix
  870. when nil
  871. if oid.to_s == identifier &&
  872. issue = Issue.visible.find_by_id(oid)
  873. anchor = comment_id ? "note-#{comment_id}" : nil
  874. url = issue_url(issue, :only_path => only_path, :anchor => anchor)
  875. link = if sep == '##'
  876. link_to("#{issue.tracker.name} ##{oid}#{comment_suffix}",
  877. url,
  878. :class => issue.css_classes,
  879. :title => "#{issue.tracker.name}: #{issue.subject.truncate(100)} (#{issue.status.name})") + ": #{issue.subject}"
  880. else
  881. link_to("##{oid}#{comment_suffix}",
  882. url,
  883. :class => issue.css_classes,
  884. :title => "#{issue.tracker.name}: #{issue.subject.truncate(100)} (#{issue.status.name})")
  885. end
  886. elsif identifier == 'note'
  887. link = link_to("#note-#{comment_id}", "#note-#{comment_id}")
  888. end
  889. when 'document'
  890. if document = Document.visible.find_by_id(oid)
  891. link = link_to(document.title, document_url(document, :only_path => only_path), :class => 'document')
  892. end
  893. when 'version'
  894. if version = Version.visible.find_by_id(oid)
  895. link = link_to(version.name, version_url(version, :only_path => only_path), :class => 'version')
  896. end
  897. when 'message'
  898. if message = Message.visible.find_by_id(oid)
  899. link = link_to_message(message, {:only_path => only_path}, :class => 'message')
  900. end
  901. when 'forum'
  902. if board = Board.visible.find_by_id(oid)
  903. link = link_to(board.name, project_board_url(board.project, board, :only_path => only_path), :class => 'board')
  904. end
  905. when 'news'
  906. if news = News.visible.find_by_id(oid)
  907. link = link_to(news.title, news_url(news, :only_path => only_path), :class => 'news')
  908. end
  909. when 'project'
  910. if p = Project.visible.find_by_id(oid)
  911. link = link_to_project(p, {:only_path => only_path}, :class => 'project')
  912. end
  913. when 'user'
  914. u = User.visible.find_by(:id => oid, :type => 'User')
  915. link = link_to_user(u, :only_path => only_path) if u
  916. end
  917. elsif sep == ':'
  918. name = remove_double_quotes(identifier)
  919. case prefix
  920. when 'document'
  921. if project && document = project.documents.visible.find_by_title(name)
  922. link = link_to(document.title, document_url(document, :only_path => only_path), :class => 'document')
  923. end
  924. when 'version'
  925. if project && version = project.versions.visible.find_by_name(name)
  926. link = link_to(version.name, version_url(version, :only_path => only_path), :class => 'version')
  927. end
  928. when 'forum'
  929. if project && board = project.boards.visible.find_by_name(name)
  930. link = link_to(board.name, project_board_url(board.project, board, :only_path => only_path), :class => 'board')
  931. end
  932. when 'news'
  933. if project && news = project.news.visible.find_by_title(name)
  934. link = link_to(news.title, news_url(news, :only_path => only_path), :class => 'news')
  935. end
  936. when 'commit', 'source', 'export'
  937. if project
  938. repository = nil
  939. if name =~ %r{^(([a-z0-9\-_]+)\|)(.+)$}
  940. repo_prefix, repo_identifier, name = $1, $2, $3
  941. repository = project.repositories.detect {|repo| repo.identifier == repo_identifier}
  942. else
  943. repository = project.repository
  944. end
  945. if prefix == 'commit'
  946. if repository && (changeset = Changeset.visible.where("repository_id = ? AND scmid LIKE ?", repository.id, "#{name}%").first)
  947. 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},
  948. :class => 'changeset',
  949. :title => truncate_single_line_raw(changeset.comments, 100)
  950. end
  951. else
  952. if repository && User.current.allowed_to?(:browse_repository, project)
  953. name =~ %r{^[/\\]*(.*?)(@([^/\\@]+?))?(#(L\d+))?$}
  954. path, rev, anchor = $1, $3, $5
  955. link = link_to h("#{project_prefix}#{prefix}:#{repo_prefix}#{name}"), {:only_path => only_path, :controller => 'repositories', :action => (prefix == 'export' ? 'raw' : 'entry'), :id => project, :repository_id => repository.identifier_param,
  956. :path => to_path_param(path),
  957. :rev => rev,
  958. :anchor => anchor},
  959. :class => (prefix == 'export' ? 'source download' : 'source')
  960. end
  961. end
  962. repo_prefix = nil
  963. end
  964. when 'attachment'
  965. attachments = options[:attachments] || []
  966. attachments += obj.attachments if obj.respond_to?(:attachments)
  967. if attachments && attachment = Attachment.latest_attach(attachments, name)
  968. link = link_to_attachment(attachment, :only_path => only_path, :class => 'attachment')
  969. end
  970. when 'project'
  971. if p = Project.visible.where("identifier = :s OR LOWER(name) = :s", :s => name.downcase).first
  972. link = link_to_project(p, {:only_path => only_path}, :class => 'project')
  973. end
  974. when 'user'
  975. u = User.visible.find_by("LOWER(login) = :s AND type = 'User'", :s => name.downcase)
  976. link = link_to_user(u, :only_path => only_path) if u
  977. end
  978. elsif sep == "@"
  979. name = remove_double_quotes(identifier)
  980. u = User.visible.find_by("LOWER(login) = :s AND type = 'User'", :s => name.downcase)
  981. link = link_to_user(u, :only_path => only_path) if u
  982. end
  983. end
  984. (leading + (link || "#{project_prefix}#{prefix}#{repo_prefix}#{sep}#{identifier}#{comment_suffix}"))
  985. end
  986. end
  987. end
  988. LINKS_RE =
  989. %r{
  990. <a( [^>]+?)?>(?<tag_content>.*?)</a>|
  991. (?<leading>[\s\(,\-\[\>]|^)
  992. (?<esc>!)?
  993. (?<project_prefix>(?<project_identifier>[a-z0-9\-_]+):)?
  994. (?<prefix>attachment|document|version|forum|news|message|project|commit|source|export|user)?
  995. (
  996. (
  997. (?<sep1>\#\#?)|
  998. (
  999. (?<repo_prefix>(?<repo_identifier>[a-z0-9\-_]+)\|)?
  1000. (?<sep2>r)
  1001. )
  1002. )
  1003. (
  1004. (?<identifier1>((\d)+|(note)))
  1005. (?<comment_suffix>
  1006. (\#note)?
  1007. -(?<comment_id>\d+)
  1008. )?
  1009. )|
  1010. (
  1011. (?<sep3>:)
  1012. (?<identifier2>[^"\s<>][^\s<>]*?|"[^"]+?")
  1013. )|
  1014. (
  1015. (?<sep4>@)
  1016. (?<identifier3>[A-Za-z0-9_\-@\.]*)
  1017. )
  1018. )
  1019. (?=
  1020. (?=[[:punct:]][^A-Za-z0-9_/])|
  1021. ,|
  1022. \s|
  1023. \]|
  1024. <|
  1025. $)
  1026. }x
  1027. HEADING_RE = /(<h(\d)( [^>]+)?>(.+?)<\/h(\d)>)/i unless const_defined?(:HEADING_RE)
  1028. def parse_sections(text, project, obj, attr, only_path, options)
  1029. return unless options[:edit_section_links]
  1030. text.gsub!(HEADING_RE) do
  1031. heading, level = $1, $2
  1032. @current_section += 1
  1033. if @current_section > 1
  1034. content_tag('div',
  1035. link_to(l(:button_edit_section), options[:edit_section_links].merge(:section => @current_section),
  1036. :class => 'icon-only icon-edit'),
  1037. :class => "contextual heading-#{level}",
  1038. :title => l(:button_edit_section),
  1039. :id => "section-#{@current_section}") + heading.html_safe
  1040. else
  1041. heading
  1042. end
  1043. end
  1044. end
  1045. # Headings and TOC
  1046. # Adds ids and links to headings unless options[:headings] is set to false
  1047. def parse_headings(text, project, obj, attr, only_path, options)
  1048. return if options[:headings] == false
  1049. text.gsub!(HEADING_RE) do
  1050. level, attrs, content = $2.to_i, $3, $4
  1051. item = strip_tags(content).strip
  1052. anchor = sanitize_anchor_name(item)
  1053. # used for single-file wiki export
  1054. anchor = "#{obj.page.title}_#{anchor}" if options[:wiki_links] == :anchor && (obj.is_a?(WikiContent) || obj.is_a?(WikiContent::Version))
  1055. @heading_anchors[anchor] ||= 0
  1056. idx = (@heading_anchors[anchor] += 1)
  1057. if idx > 1
  1058. anchor = "#{anchor}-#{idx}"
  1059. end
  1060. @parsed_headings << [level, anchor, item]
  1061. "<a name=\"#{anchor}\"></a>\n<h#{level} #{attrs}>#{content}<a href=\"##{anchor}\" class=\"wiki-anchor\">&para;</a></h#{level}>"
  1062. end
  1063. end
  1064. MACROS_RE = /(
  1065. (!)? # escaping
  1066. (
  1067. \{\{ # opening tag
  1068. ([\w]+) # macro name
  1069. (\(([^\n\r]*?)\))? # optional arguments
  1070. ([\n\r].*?[\n\r])? # optional block of text
  1071. \}\} # closing tag
  1072. )
  1073. )/mx unless const_defined?(:MACROS_RE)
  1074. MACRO_SUB_RE = /(
  1075. \{\{
  1076. macro\((\d+)\)
  1077. \}\}
  1078. )/x unless const_defined?(:MACRO_SUB_RE)
  1079. # Extracts macros from text
  1080. def catch_macros(text)
  1081. macros = {}
  1082. text.gsub!(MACROS_RE) do
  1083. all, macro = $1, $4.downcase
  1084. if macro_exists?(macro) || all =~ MACRO_SUB_RE
  1085. index = macros.size
  1086. macros[index] = all
  1087. "{{macro(#{index})}}"
  1088. else
  1089. all
  1090. end
  1091. end
  1092. macros
  1093. end
  1094. # Executes and replaces macros in text
  1095. def inject_macros(text, obj, macros, execute=true)
  1096. text.gsub!(MACRO_SUB_RE) do
  1097. all, index = $1, $2.to_i
  1098. orig = macros.delete(index)
  1099. if execute && orig && orig =~ MACROS_RE
  1100. esc, all, macro, args, block = $2, $3, $4.downcase, $6.to_s, $7.try(:strip)
  1101. if esc.nil?
  1102. h(exec_macro(macro, obj, args, block) || all)
  1103. else
  1104. h(all)
  1105. end
  1106. elsif orig
  1107. h(orig)
  1108. else
  1109. h(all)
  1110. end
  1111. end
  1112. end
  1113. TOC_RE = /<p>\{\{((<|&lt;)|(>|&gt;))?toc\}\}<\/p>/i unless const_defined?(:TOC_RE)
  1114. # Renders the TOC with given headings
  1115. def replace_toc(text, headings)
  1116. text.gsub!(TOC_RE) do
  1117. left_align, right_align = $2, $3
  1118. # Keep only the 4 first levels
  1119. headings = headings.select{|level, anchor, item| level <= 4}
  1120. if headings.empty?
  1121. ''
  1122. else
  1123. div_class = +'toc'
  1124. div_class << ' right' if right_align
  1125. div_class << ' left' if left_align
  1126. out = +"<ul class=\"#{div_class}\"><li><strong>#{l :label_table_of_contents}</strong></li><li>"
  1127. root = headings.map(&:first).min
  1128. current = root
  1129. started = false
  1130. headings.each do |level, anchor, item|
  1131. if level > current
  1132. out << '<ul><li>' * (level - current)
  1133. elsif level < current
  1134. out << "</li></ul>\n" * (current - level) + "</li><li>"
  1135. elsif started
  1136. out << '</li><li>'
  1137. end
  1138. out << "<a href=\"##{anchor}\">#{item}</a>"
  1139. current = level
  1140. started = true
  1141. end
  1142. out << '</li></ul>' * (current - root)
  1143. out << '</li></ul>'
  1144. end
  1145. end
  1146. end
  1147. # Same as Rails' simple_format helper without using paragraphs
  1148. def simple_format_without_paragraph(text)
  1149. text.to_s.
  1150. gsub(/\r\n?/, "\n"). # \r\n and \r -> \n
  1151. gsub(/\n\n+/, "<br /><br />"). # 2+ newline -> 2 br
  1152. gsub(/([^\n]\n)(?=[^\n])/, '\1<br />'). # 1 newline -> br
  1153. html_safe
  1154. end
  1155. def lang_options_for_select(blank=true)
  1156. (blank ? [["(auto)", ""]] : []) + languages_options
  1157. end
  1158. def labelled_form_for(*args, &proc)
  1159. args << {} unless args.last.is_a?(Hash)
  1160. options = args.last
  1161. if args.first.is_a?(Symbol)
  1162. options.merge!(:as => args.shift)
  1163. end
  1164. options.merge!({:builder => Redmine::Views::LabelledFormBuilder})
  1165. form_for(*args, &proc)
  1166. end
  1167. def labelled_fields_for(*args, &proc)
  1168. args << {} unless args.last.is_a?(Hash)
  1169. options = args.last
  1170. options.merge!({:builder => Redmine::Views::LabelledFormBuilder})
  1171. fields_for(*args, &proc)
  1172. end
  1173. # Render the error messages for the given objects
  1174. def error_messages_for(*objects)
  1175. objects = objects.map {|o| o.is_a?(String) ? instance_variable_get("@#{o}") : o}.compact
  1176. errors = objects.map {|o| o.errors.full_messages}.flatten
  1177. render_error_messages(errors)
  1178. end
  1179. # Renders a list of error messages
  1180. def render_error_messages(errors)
  1181. html = +""
  1182. if errors.present?
  1183. html << "<div id='errorExplanation'><ul>\n"
  1184. errors.each do |error|
  1185. html << "<li>#{h error}</li>\n"
  1186. end
  1187. html << "</ul></div>\n"
  1188. end
  1189. html.html_safe
  1190. end
  1191. def delete_link(url, options={})
  1192. options = {
  1193. :method => :delete,
  1194. :data => {:confirm => l(:text_are_you_sure)},
  1195. :class => 'icon icon-del'
  1196. }.merge(options)
  1197. link_to l(:button_delete), url, options
  1198. end
  1199. def link_to_function(name, function, html_options={})
  1200. content_tag(:a, name, {:href => '#', :onclick => "#{function}; return false;"}.merge(html_options))
  1201. end
  1202. def link_to_context_menu
  1203. link_to l(:button_actions), '#', title: l(:button_actions), class: 'icon-only icon-actions js-contextmenu'
  1204. end
  1205. # Helper to render JSON in views
  1206. def raw_json(arg)
  1207. arg.to_json.to_s.gsub('/', '\/').html_safe
  1208. end
  1209. def back_url
  1210. url = params[:back_url]
  1211. if url.nil? && referer = request.env['HTTP_REFERER']
  1212. url = CGI.unescape(referer.to_s)
  1213. # URLs that contains the utf8=[checkmark] parameter added by Rails are
  1214. # parsed as invalid by URI.parse so the redirect to the back URL would
  1215. # not be accepted (ApplicationController#validate_back_url would return
  1216. # false)
  1217. url.gsub!(/(\?|&)utf8=\u2713&?/, '\1')
  1218. end
  1219. url
  1220. end
  1221. def back_url_hidden_field_tag
  1222. url = back_url
  1223. hidden_field_tag('back_url', url, :id => nil) unless url.blank?
  1224. end
  1225. def cancel_button_tag(fallback_url)
  1226. url = back_url.blank? ? fallback_url : back_url
  1227. link_to l(:button_cancel), url
  1228. end
  1229. def check_all_links(form_name)
  1230. link_to_function(l(:button_check_all), "checkAll('#{form_name}', true)") +
  1231. " | ".html_safe +
  1232. link_to_function(l(:button_uncheck_all), "checkAll('#{form_name}', false)")
  1233. end
  1234. def toggle_checkboxes_link(selector)
  1235. link_to_function '',
  1236. "toggleCheckboxesBySelector('#{selector}')",
  1237. :title => "#{l(:button_check_all)} / #{l(:button_uncheck_all)}",
  1238. :class => 'icon icon-checked'
  1239. end
  1240. def progress_bar(pcts, options={})
  1241. pcts = [pcts, pcts] unless pcts.is_a?(Array)
  1242. pcts = pcts.collect(&:round)
  1243. pcts[1] = pcts[1] - pcts[0]
  1244. pcts << (100 - pcts[1] - pcts[0])
  1245. titles = options[:titles].to_a
  1246. titles[0] = "#{pcts[0]}%" if titles[0].blank?
  1247. legend = options[:legend] || ''
  1248. content_tag('table',
  1249. content_tag('tr',
  1250. (pcts[0] > 0 ? content_tag('td', '', :style => "width: #{pcts[0]}%;", :class => 'closed', :title => titles[0]) : ''.html_safe) +
  1251. (pcts[1] > 0 ? content_tag('td', '', :style => "width: #{pcts[1]}%;", :class => 'done', :title => titles[1]) : ''.html_safe) +
  1252. (pcts[2] > 0 ? content_tag('td', '', :style => "width: #{pcts[2]}%;", :class => 'todo', :title => titles[2]) : ''.html_safe)
  1253. ), :class => "progress progress-#{pcts[0]}").html_safe +
  1254. content_tag('p', legend, :class => 'percent').html_safe
  1255. end
  1256. def checked_image(checked=true)
  1257. if checked
  1258. @checked_image_tag ||= content_tag(:span, nil, :class => 'icon-only icon-checked')
  1259. end
  1260. end
  1261. def context_menu
  1262. unless @context_menu_included
  1263. content_for :header_tags do
  1264. javascript_include_tag('context_menu') +
  1265. stylesheet_link_tag('context_menu')
  1266. end
  1267. if l(:direction) == 'rtl'
  1268. content_for :header_tags do
  1269. stylesheet_link_tag('context_menu_rtl')
  1270. end
  1271. end
  1272. @context_menu_included = true
  1273. end
  1274. nil
  1275. end
  1276. def calendar_for(field_id)
  1277. include_calendar_headers_tags
  1278. javascript_tag("$(function() { $('##{field_id}').addClass('date').datepickerFallback(datepickerOptions); });")
  1279. end
  1280. def include_calendar_headers_tags
  1281. unless @calendar_headers_tags_included
  1282. tags = ''.html_safe
  1283. @calendar_headers_tags_included = true
  1284. content_for :header_tags do
  1285. start_of_week = Setting.start_of_week
  1286. start_of_week = l(:general_first_day_of_week, :default => '1') if start_of_week.blank?
  1287. # Redmine uses 1..7 (monday..sunday) in settings and locales
  1288. # JQuery uses 0..6 (sunday..saturday), 7 needs to be changed to 0
  1289. start_of_week = start_of_week.to_i % 7
  1290. tags << javascript_tag(
  1291. "var datepickerOptions={dateFormat: 'yy-mm-dd', firstDay: #{start_of_week}, " +
  1292. "showOn: 'button', buttonImageOnly: true, buttonImage: '" +
  1293. path_to_image('/images/calendar.png') +
  1294. "', showButtonPanel: true, showWeek: true, showOtherMonths: true, " +
  1295. "selectOtherMonths: true, changeMonth: true, changeYear: true, " +
  1296. "beforeShow: beforeShowDatePicker};")
  1297. jquery_locale = l('jquery.locale', :default => current_language.to_s)
  1298. unless jquery_locale == 'en'
  1299. tags << javascript_include_tag("i18n/datepicker-#{jquery_locale}.js")
  1300. end
  1301. tags
  1302. end
  1303. end
  1304. end
  1305. # Overrides Rails' stylesheet_link_tag with themes and plugins support.
  1306. # Examples:
  1307. # stylesheet_link_tag('styles') # => picks styles.css from the current theme or defaults
  1308. # stylesheet_link_tag('styles', :plugin => 'foo) # => picks styles.css from plugin's assets
  1309. #
  1310. def stylesheet_link_tag(*sources)
  1311. options = sources.last.is_a?(Hash) ? sources.pop : {}
  1312. plugin = options.delete(:plugin)
  1313. sources = sources.map do |source|
  1314. if plugin
  1315. "/plugin_assets/#{plugin}/stylesheets/#{source}"
  1316. elsif current_theme && current_theme.stylesheets.include?(source)
  1317. current_theme.stylesheet_path(source)
  1318. else
  1319. source
  1320. end
  1321. end
  1322. super *sources, options
  1323. end
  1324. # Overrides Rails' image_tag with themes and plugins support.
  1325. # Examples:
  1326. # image_tag('image.png') # => picks image.png from the current theme or defaults
  1327. # image_tag('image.png', :plugin => 'foo) # => picks image.png from plugin's assets
  1328. #
  1329. def image_tag(source, options={})
  1330. if plugin = options.delete(:plugin)
  1331. source = "/plugin_assets/#{plugin}/images/#{source}"
  1332. elsif current_theme && current_theme.images.include?(source)
  1333. source = current_theme.image_path(source)
  1334. end
  1335. super source, options
  1336. end
  1337. # Overrides Rails' javascript_include_tag with plugins support
  1338. # Examples:
  1339. # javascript_include_tag('scripts') # => picks scripts.js from defaults
  1340. # javascript_include_tag('scripts', :plugin => 'foo) # => picks scripts.js from plugin's assets
  1341. #
  1342. def javascript_include_tag(*sources)
  1343. options = sources.last.is_a?(Hash) ? sources.pop : {}
  1344. if plugin = options.delete(:plugin)
  1345. sources = sources.map do |source|
  1346. if plugin
  1347. "/plugin_assets/#{plugin}/javascripts/#{source}"
  1348. else
  1349. source
  1350. end
  1351. end
  1352. end
  1353. super *sources, options
  1354. end
  1355. def sidebar_content?
  1356. content_for?(:sidebar) || view_layouts_base_sidebar_hook_response.present?
  1357. end
  1358. def view_layouts_base_sidebar_hook_response
  1359. @view_layouts_base_sidebar_hook_response ||= call_hook(:view_layouts_base_sidebar)
  1360. end
  1361. def email_delivery_enabled?
  1362. !!ActionMailer::Base.perform_deliveries
  1363. end
  1364. # Returns the avatar image tag for the given +user+ if avatars are enabled
  1365. # +user+ can be a User or a string that will be scanned for an email address (eg. 'joe <joe@foo.bar>')
  1366. def avatar(user, options = { })
  1367. if Setting.gravatar_enabled?
  1368. options.merge!(:default => Setting.gravatar_default)
  1369. email = nil
  1370. if user.respond_to?(:mail)
  1371. email = user.mail
  1372. elsif user.to_s =~ %r{<(.+?)>}
  1373. email = $1
  1374. end
  1375. if email.present?
  1376. gravatar(email.to_s.downcase, options) rescue nil
  1377. elsif user.is_a?(AnonymousUser)
  1378. image_tag 'anonymous.png',
  1379. GravatarHelper::DEFAULT_OPTIONS
  1380. .except(:default, :rating, :ssl).merge(options)
  1381. else
  1382. nil
  1383. end
  1384. else
  1385. ''
  1386. end
  1387. end
  1388. # Returns a link to edit user's avatar if avatars are enabled
  1389. def avatar_edit_link(user, options={})
  1390. if Setting.gravatar_enabled?
  1391. url = "https://gravatar.com"
  1392. link_to avatar(user, {:title => l(:button_edit)}.merge(options)), url, :target => '_blank'
  1393. end
  1394. end
  1395. def sanitize_anchor_name(anchor)
  1396. anchor.gsub(%r{[^\s\-\p{Word}]}, '').gsub(%r{\s+(\-+\s*)?}, '-')
  1397. end
  1398. # Returns the javascript tags that are included in the html layout head
  1399. def javascript_heads
  1400. tags = javascript_include_tag('jquery-1.11.1-ui-1.11.0-ujs-5.2.3', 'application', 'responsive')
  1401. unless User.current.pref.warn_on_leaving_unsaved == '0'
  1402. tags << "\n".html_safe + javascript_tag("$(window).load(function(){ warnLeavingUnsaved('#{escape_javascript l(:text_warn_on_leaving_unsaved)}'); });")
  1403. end
  1404. tags
  1405. end
  1406. def favicon
  1407. "<link rel='shortcut icon' href='#{favicon_path}' />".html_safe
  1408. end
  1409. # Returns the path to the favicon
  1410. def favicon_path
  1411. icon = (current_theme && current_theme.favicon?) ? current_theme.favicon_path : '/favicon.ico'
  1412. image_path(icon)
  1413. end
  1414. # Returns the full URL to the favicon
  1415. def favicon_url
  1416. # TODO: use #image_url introduced in Rails4
  1417. path = favicon_path
  1418. base = url_for(:controller => 'welcome', :action => 'index', :only_path => false)
  1419. base.sub(%r{/+$},'') + '/' + path.sub(%r{^/+},'')
  1420. end
  1421. def robot_exclusion_tag
  1422. '<meta name="robots" content="noindex,follow,noarchive" />'.html_safe
  1423. end
  1424. # Returns true if arg is expected in the API response
  1425. def include_in_api_response?(arg)
  1426. unless @included_in_api_response
  1427. param = params[:include]
  1428. @included_in_api_response = param.is_a?(Array) ? param.collect(&:to_s) : param.to_s.split(',')
  1429. @included_in_api_response.collect!(&:strip)
  1430. end
  1431. @included_in_api_response.include?(arg.to_s)
  1432. end
  1433. # Returns options or nil if nometa param or X-Redmine-Nometa header
  1434. # was set in the request
  1435. def api_meta(options)
  1436. if params[:nometa].present? || request.headers['X-Redmine-Nometa']
  1437. # compatibility mode for activeresource clients that raise
  1438. # an error when deserializing an array with attributes
  1439. nil
  1440. else
  1441. options
  1442. end
  1443. end
  1444. def export_csv_encoding_select_tag
  1445. return if l(:general_csv_encoding).casecmp('UTF-8') == 0
  1446. options = [l(:general_csv_encoding), 'UTF-8']
  1447. content_tag(:p) do
  1448. concat(
  1449. content_tag(:label) do
  1450. concat l(:label_encoding) + ' '
  1451. concat select_tag('encoding', options_for_select(options, l(:general_csv_encoding)))
  1452. end
  1453. )
  1454. end
  1455. end
  1456. # Returns an array of error messages for bulk edited items (issues, time entries)
  1457. def bulk_edit_error_messages(items)
  1458. messages = {}
  1459. items.each do |item|
  1460. item.errors.full_messages.each do |message|
  1461. messages[message] ||= []
  1462. messages[message] << item
  1463. end
  1464. end
  1465. messages.map { |message, items|
  1466. "#{message}: " + items.map {|i| "##{i.id}"}.join(', ')
  1467. }
  1468. end
  1469. private
  1470. def wiki_helper
  1471. helper = Redmine::WikiFormatting.helper_for(Setting.text_formatting)
  1472. extend helper
  1473. return self
  1474. end
  1475. # remove double quotes if any
  1476. def remove_double_quotes(identifier)
  1477. name = identifier.gsub(%r{^"(.*)"$}, "\\1")
  1478. return CGI.unescapeHTML(name)
  1479. end
  1480. end