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

application_helper.rb 59KB

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