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

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