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