Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

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