Compare commits

..

23 Commits
2.2.3 ... 2.0.2

Author SHA1 Message Date
Jean-Philippe Lang
b83ed5a040 tagged version 2.0.2
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/tags/2.0.2@9774 e93f8b46-1217-0410-a6f0-8f06a7374b81
2012-06-05 17:23:43 +00:00
Jean-Philippe Lang
c4736ed42b Merged r9770 from trunk.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/2.0-stable@9771 e93f8b46-1217-0410-a6f0-8f06a7374b81
2012-06-05 17:19:37 +00:00
Jean-Philippe Lang
47fb2eb998 Merged r9768 from trunk.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/2.0-stable@9769 e93f8b46-1217-0410-a6f0-8f06a7374b81
2012-06-05 17:11:06 +00:00
Jean-Philippe Lang
e9813791cb Merged r9759 to r9764.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/2.0-stable@9766 e93f8b46-1217-0410-a6f0-8f06a7374b81
2012-06-03 16:32:21 +00:00
Jean-Philippe Lang
5f23ebc31c Merged r9755 from trunk.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/2.0-stable@9756 e93f8b46-1217-0410-a6f0-8f06a7374b81
2012-06-03 08:50:26 +00:00
Jean-Philippe Lang
b88c95b0fb Merged r9740 and r9741 from trunk.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/2.0-stable@9753 e93f8b46-1217-0410-a6f0-8f06a7374b81
2012-06-03 08:10:00 +00:00
Jean-Philippe Lang
93d8f99884 Merged r9742 from trunk.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/2.0-stable@9751 e93f8b46-1217-0410-a6f0-8f06a7374b81
2012-06-03 08:07:07 +00:00
Toshi MARUYAMA
07edb10518 Merged r9734 from trunk (#11032)
fix project list is not shown on Email notifications.

git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/2.0-stable@9739 e93f8b46-1217-0410-a6f0-8f06a7374b81
2012-05-28 10:31:19 +00:00
Jean-Philippe Lang
0512a30368 Updates for 2.0.1 release.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/2.0-stable@9732 e93f8b46-1217-0410-a6f0-8f06a7374b81
2012-05-28 07:24:38 +00:00
Jean-Philippe Lang
bc945d78a6 Merged r9719, r9726, r9727 from trunk.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/2.0-stable@9729 e93f8b46-1217-0410-a6f0-8f06a7374b81
2012-05-27 19:39:26 +00:00
Jean-Philippe Lang
8cd0626075 Merged r9701 from trunk.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/2.0-stable@9728 e93f8b46-1217-0410-a6f0-8f06a7374b81
2012-05-27 19:25:30 +00:00
Jean-Philippe Lang
035bd65a5a Merged r9710 from trunk.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/2.0-stable@9725 e93f8b46-1217-0410-a6f0-8f06a7374b81
2012-05-26 09:50:51 +00:00
Jean-Philippe Lang
955d2b134d Merged r9711 from trunk.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/2.0-stable@9724 e93f8b46-1217-0410-a6f0-8f06a7374b81
2012-05-26 09:50:01 +00:00
Jean-Philippe Lang
743b55a3f9 Merged r9718 from trunk.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/2.0-stable@9723 e93f8b46-1217-0410-a6f0-8f06a7374b81
2012-05-26 09:49:19 +00:00
Jean-Philippe Lang
881595f7f0 Merged r9712 from trunk.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/2.0-stable@9722 e93f8b46-1217-0410-a6f0-8f06a7374b81
2012-05-26 09:48:37 +00:00
Jean-Philippe Lang
7f51bab0fc Merged r9709 from trunk.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/2.0-stable@9721 e93f8b46-1217-0410-a6f0-8f06a7374b81
2012-05-26 09:47:48 +00:00
Jean-Philippe Lang
84d5092508 Merged r9699 from trunk.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/2.0-stable@9720 e93f8b46-1217-0410-a6f0-8f06a7374b81
2012-05-26 09:40:31 +00:00
Jean-Philippe Lang
352d177f7e Merged r9703 from trunk.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/2.0-stable@9706 e93f8b46-1217-0410-a6f0-8f06a7374b81
2012-05-21 19:00:26 +00:00
Jean-Philippe Lang
821ea2a757 Merged r9702 from trunk.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/2.0-stable@9705 e93f8b46-1217-0410-a6f0-8f06a7374b81
2012-05-21 18:59:31 +00:00
Jean-Philippe Lang
7cd7b1bd8b Merged r9700 from trunk.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/2.0-stable@9704 e93f8b46-1217-0410-a6f0-8f06a7374b81
2012-05-21 18:58:29 +00:00
Jean-Philippe Lang
cf139e25a7 Merged r9696 from trunk. Updates for 2.0.0 release.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/2.0-stable@9697 e93f8b46-1217-0410-a6f0-8f06a7374b81
2012-05-14 22:19:13 +00:00
Jean-Philippe Lang
8b09f5d27d Set version to stable.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/2.0-stable@9695 e93f8b46-1217-0410-a6f0-8f06a7374b81
2012-05-14 17:02:27 +00:00
Jean-Philippe Lang
d138df5241 Added 2.0-stable branch.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/2.0-stable@9694 e93f8b46-1217-0410-a6f0-8f06a7374b81
2012-05-14 16:48:29 +00:00
721 changed files with 27362 additions and 23444 deletions

2
.gitignore vendored
View File

@@ -19,11 +19,9 @@
/public/plugin_assets
/tmp/*
/tmp/cache/*
/tmp/pdf/*
/tmp/sessions/*
/tmp/sockets/*
/tmp/test/*
/tmp/thumbnails/*
/vendor/cache
/vendor/rails
*.rbc

View File

@@ -21,11 +21,9 @@ public/dispatch.*
public/plugin_assets
tmp/*
tmp/cache/*
tmp/pdf/*
tmp/sessions/*
tmp/sockets/*
tmp/test/*
tmp/thumbnails/*
vendor/cache
vendor/rails
*.rbc

15
Gemfile
View File

@@ -1,11 +1,11 @@
source 'http://rubygems.org'
gem 'rails', '3.2.12'
gem "jquery-rails", "~> 2.0.2"
gem 'rails', '3.2.5'
gem 'prototype-rails', '3.2.1'
gem "i18n", "~> 0.6.0"
gem "coderay", "~> 1.0.6"
gem "fastercsv", "~> 1.5.0", :platforms => [:mri_18, :mingw_18, :jruby]
gem "builder", "3.0.0"
gem "builder"
# Optional gem for LDAP authentication
group :ldap do
@@ -41,7 +41,7 @@ end
platforms :mri_18, :mingw_18 do
group :mysql do
gem "mysql", "~> 2.8.1"
gem "mysql"
end
end
@@ -74,12 +74,7 @@ end
group :test do
gem "shoulda", "~> 2.11"
# Shoulda does not work nice on Ruby 1.9.3 and JRuby 1.7.
# It seems to need test-unit explicitely.
platforms = [:mri_19]
platforms << :jruby if defined?(JRUBY_VERSION) && JRUBY_VERSION >= "1.7"
gem "test-unit", :platforms => platforms
gem "mocha", "0.12.3"
gem "mocha"
end
local_gemfile = File.join(File.dirname(__FILE__), "Gemfile.local")

View File

@@ -40,26 +40,19 @@ class AccountController < ApplicationController
redirect_to home_url
end
# Lets user choose a new password
# Enable user to choose a new password
def lost_password
redirect_to(home_url) && return unless Setting.lost_password?
if params[:token]
@token = Token.find_by_action_and_value("recovery", params[:token].to_s)
if @token.nil? || @token.expired?
redirect_to home_url
return
end
@token = Token.find_by_action_and_value("recovery", params[:token])
redirect_to(home_url) && return unless @token and !@token.expired?
@user = @token.user
unless @user && @user.active?
redirect_to home_url
return
end
if request.post?
@user.password, @user.password_confirmation = params[:new_password], params[:new_password_confirmation]
if @user.save
@token.destroy
flash[:notice] = l(:notice_account_password_updated)
redirect_to signin_path
redirect_to :action => 'login'
return
end
end
@@ -67,23 +60,17 @@ class AccountController < ApplicationController
return
else
if request.post?
user = User.find_by_mail(params[:mail].to_s)
# user not found or not active
unless user && user.active?
flash.now[:error] = l(:notice_account_unknown_email)
return
end
# user cannot change its password
unless user.change_password_allowed?
flash.now[:error] = l(:notice_can_t_change_password)
return
end
user = User.find_by_mail(params[:mail])
# user not found in db
(flash.now[:error] = l(:notice_account_unknown_email); return) unless user
# user uses an external authentification
(flash.now[:error] = l(:notice_can_t_change_password); return) if user.auth_source_id
# create a new token for password recovery
token = Token.new(:user => user, :action => "recovery")
if token.save
Mailer.lost_password(token).deliver
flash[:notice] = l(:notice_account_lost_email_sent)
redirect_to signin_path
redirect_to :action => 'login'
return
end
end
@@ -97,9 +84,8 @@ class AccountController < ApplicationController
session[:auth_source_registration] = nil
@user = User.new(:language => Setting.default_language)
else
user_params = params[:user] || {}
@user = User.new
@user.safe_attributes = user_params
@user.safe_attributes = params[:user]
@user.admin = false
@user.register
if session[:auth_source_registration]
@@ -114,9 +100,7 @@ class AccountController < ApplicationController
end
else
@user.login = params[:user][:login]
unless user_params[:identity_url].present? && user_params[:password].blank? && user_params[:password_confirmation].blank?
@user.password, @user.password_confirmation = user_params[:password], user_params[:password_confirmation]
end
@user.password, @user.password_confirmation = params[:user][:password], params[:user][:password_confirmation]
case Setting.self_registration
when '1'
@@ -142,7 +126,7 @@ class AccountController < ApplicationController
token.destroy
flash[:notice] = l(:notice_account_activated)
end
redirect_to signin_path
redirect_to :action => 'login'
end
private
@@ -210,7 +194,6 @@ class AccountController < ApplicationController
end
def successful_authentication(user)
logger.info "Successful authentication for '#{user.login}' from #{request.remote_ip} at #{Time.now.utc}"
# Valid user
self.logged_user = user
# generate a key and set cookie if autologin
@@ -254,7 +237,7 @@ class AccountController < ApplicationController
if user.save and token.save
Mailer.register(token).deliver
flash[:notice] = l(:notice_account_register_done)
redirect_to signin_path
redirect_to :action => 'login'
else
yield if block_given?
end
@@ -291,6 +274,6 @@ class AccountController < ApplicationController
def account_pending
flash[:notice] = l(:notice_account_pending)
redirect_to signin_path
redirect_to :action => 'login'
end
end

View File

@@ -40,7 +40,7 @@ class ActivitiesController < ApplicationController
events = @activity.events(@date_from, @date_to)
if events.empty? || stale?(:etag => [@activity.scope, @date_to, @date_from, @with_subprojects, @author, events.first, events.size, User.current, current_language])
if events.empty? || stale?(:etag => [@activity.scope, @date_to, @date_from, @with_subprojects, @author, events.first, User.current, current_language])
respond_to do |format|
format.html {
@events_by_day = events.group_by {|event| User.current.time_to_date(event.event_datetime)}

View File

@@ -22,7 +22,7 @@ class Unauthorized < Exception; end
class ApplicationController < ActionController::Base
include Redmine::I18n
class_attribute :accept_api_auth_actions
class_attribute :accept_rss_auth_actions
class_attribute :model_object
@@ -35,104 +35,46 @@ class ApplicationController < ActionController::Base
cookies.delete(:autologin)
end
before_filter :session_expiration, :user_setup, :check_if_login_required, :set_localization
before_filter :user_setup, :check_if_login_required, :set_localization
rescue_from ActionController::InvalidAuthenticityToken, :with => :invalid_authenticity_token
rescue_from ::Unauthorized, :with => :deny_access
rescue_from ::ActionView::MissingTemplate, :with => :missing_template
include Redmine::Search::Controller
include Redmine::MenuManager::MenuController
helper Redmine::MenuManager::MenuHelper
def session_expiration
if session[:user_id]
if session_expired? && !try_to_autologin
reset_session
flash[:error] = l(:error_session_expired)
redirect_to signin_url
else
session[:atime] = Time.now.utc.to_i
end
end
end
def session_expired?
if Setting.session_lifetime?
unless session[:ctime] && (Time.now.utc.to_i - session[:ctime].to_i <= Setting.session_lifetime.to_i * 60)
return true
end
end
if Setting.session_timeout?
unless session[:atime] && (Time.now.utc.to_i - session[:atime].to_i <= Setting.session_timeout.to_i * 60)
return true
end
end
false
end
def start_user_session(user)
session[:user_id] = user.id
session[:ctime] = Time.now.utc.to_i
session[:atime] = Time.now.utc.to_i
end
def user_setup
# Check the settings cache for each request
Setting.check_cache
# Find the current user
User.current = find_current_user
logger.info(" Current user: " + (User.current.logged? ? "#{User.current.login} (id=#{User.current.id})" : "anonymous")) if logger
end
# Returns the current user or nil if no user is logged in
# and starts a session if needed
def find_current_user
user = nil
unless api_request?
if session[:user_id]
# existing session
user = (User.active.find(session[:user_id]) rescue nil)
elsif autologin_user = try_to_autologin
user = autologin_user
elsif params[:format] == 'atom' && params[:key] && request.get? && accept_rss_auth?
# RSS key authentication does not start a session
user = User.find_by_rss_key(params[:key])
end
end
if user.nil? && Setting.rest_api_enabled? && accept_api_auth?
if session[:user_id]
# existing session
(User.active.find(session[:user_id]) rescue nil)
elsif cookies[:autologin] && Setting.autologin?
# auto-login feature starts a new session
user = User.try_to_autologin(cookies[:autologin])
session[:user_id] = user.id if user
user
elsif params[:format] == 'atom' && params[:key] && request.get? && accept_rss_auth?
# RSS key authentication does not start a session
User.find_by_rss_key(params[:key])
elsif Setting.rest_api_enabled? && accept_api_auth?
if (key = api_key_from_request)
# Use API key
user = User.find_by_api_key(key)
User.find_by_api_key(key)
else
# HTTP Basic, either username/password or API key/random
authenticate_with_http_basic do |username, password|
user = User.try_to_login(username, password) || User.find_by_api_key(username)
User.try_to_login(username, password) || User.find_by_api_key(username)
end
end
# Switch user if requested by an admin user
if user && user.admin? && (username = api_switch_user_from_request)
su = User.find_by_login(username)
if su && su.active?
logger.info(" User switched by: #{user.login} (id=#{user.id})") if logger
user = su
else
render_error :message => 'Invalid X-Redmine-Switch-User header', :status => 412
end
end
end
user
end
def try_to_autologin
if cookies[:autologin] && Setting.autologin?
# auto-login feature starts a new session
user = User.try_to_autologin(cookies[:autologin])
if user
reset_session
start_user_session(user)
end
user
end
end
@@ -141,7 +83,7 @@ class ApplicationController < ActionController::Base
reset_session
if user && user.is_a?(User)
User.current = user
start_user_session(user)
session[:user_id] = user.id
else
User.current = User.anonymous
end
@@ -276,24 +218,14 @@ class ApplicationController < ActionController::Base
self.model_object = model
end
# Find the issue whose id is the :id parameter
# Raises a Unauthorized exception if the issue is not visible
def find_issue
# Issue.visible.find(...) can not be used to redirect user to the login form
# if the issue actually exists but requires authentication
@issue = Issue.find(params[:id])
raise Unauthorized unless @issue.visible?
@project = @issue.project
rescue ActiveRecord::RecordNotFound
render_404
end
# Find issues with a single :id param or :ids array param
# Raises a Unauthorized exception if one of the issues is not visible
# Filter for bulk issue operations
def find_issues
@issues = Issue.find_all_by_id(params[:id] || params[:ids])
raise ActiveRecord::RecordNotFound if @issues.empty?
raise Unauthorized unless @issues.all?(&:visible?)
if @issues.detect {|issue| !issue.visible?}
deny_access
return
end
@projects = @issues.collect(&:project).compact.uniq
@project = @projects.first if @projects.size == 1
rescue ActiveRecord::RecordNotFound
@@ -303,7 +235,7 @@ class ApplicationController < ActionController::Base
# make sure that the user is a member of the project (or admin) if project is private
# used as a before_filter for actions that do not require any particular permission on the project
def check_project_privacy
if @project && !@project.archived?
if @project && @project.active?
if @project.visible?
true
else
@@ -317,16 +249,12 @@ class ApplicationController < ActionController::Base
end
def back_url
url = params[:back_url]
if url.nil? && referer = request.env['HTTP_REFERER']
url = CGI.unescape(referer.to_s)
end
url
params[:back_url] || request.env['HTTP_REFERER']
end
def redirect_back_or_default(default)
back_url = params[:back_url].to_s
if back_url.present?
back_url = CGI.unescape(params[:back_url].to_s)
if !back_url.blank?
begin
uri = URI.parse(back_url)
# do not redirect user to another host or to the login or register page
@@ -335,7 +263,6 @@ class ApplicationController < ActionController::Base
return
end
rescue URI::InvalidURIError
logger.warn("Could not redirect to invalid URL #{back_url}")
# redirect to default
end
end
@@ -379,17 +306,13 @@ class ApplicationController < ActionController::Base
format.html {
render :template => 'common/error', :layout => use_layout, :status => @status
}
format.any { head @status }
format.atom { head @status }
format.xml { head @status }
format.js { head @status }
format.json { head @status }
end
end
# Handler for ActionView::MissingTemplate exception
def missing_template
logger.warn "Missing template, responding with 404"
@project = nil
render_404
end
# Filter for actions that provide an API response
# but have no HTML representation for non admin users
def require_admin_or_api_request
@@ -422,7 +345,7 @@ class ApplicationController < ActionController::Base
@items.sort! {|x,y| y.event_datetime <=> x.event_datetime }
@items = @items.slice(0, Setting.feeds_limit.to_i)
@title = options[:title] || Setting.app_title
render :template => "common/feed", :formats => [:atom], :layout => false,
render :template => "common/feed.atom", :layout => false,
:content_type => 'application/atom+xml'
end
@@ -522,17 +445,12 @@ class ApplicationController < ActionController::Base
# Returns the API key present in the request
def api_key_from_request
if params[:key].present?
params[:key].to_s
params[:key]
elsif request.headers["X-Redmine-API-Key"].present?
request.headers["X-Redmine-API-Key"].to_s
request.headers["X-Redmine-API-Key"]
end
end
# Returns the API 'switch user' value if present
def api_switch_user_from_request
request.headers["X-Redmine-Switch-User"].to_s.presence
end
# Renders a warning flash if obj has unsaved attachments
def render_attachment_warning_if_needed(obj)
flash[:warning] = l(:warning_attachments_not_saved, obj.unsaved_attachments.size) if obj.unsaved_attachments.present?
@@ -561,17 +479,6 @@ class ApplicationController < ActionController::Base
render_error "An error occurred while executing the query and has been logged. Please report this error to your Redmine administrator."
end
# Renders a 200 response for successfull updates or deletions via the API
def render_api_ok
render_api_head :ok
end
# Renders a head API response
def render_api_head(status)
# #head would return a response body with one space
render :text => '', :status => status, :layout => nil
end
# Renders API response on validation failure
def render_validation_errors(objects)
if objects.is_a?(Array)

View File

@@ -17,7 +17,7 @@
class AttachmentsController < ApplicationController
before_filter :find_project, :except => :upload
before_filter :file_readable, :read_authorize, :only => [:show, :download, :thumbnail]
before_filter :file_readable, :read_authorize, :only => [:show, :download]
before_filter :delete_authorize, :only => :destroy
before_filter :authorize_global, :only => :upload
@@ -52,26 +52,11 @@ class AttachmentsController < ApplicationController
@attachment.increment_download
end
if stale?(:etag => @attachment.digest)
# images are sent inline
send_file @attachment.diskfile, :filename => filename_for_content_disposition(@attachment.filename),
:type => detect_content_type(@attachment),
:disposition => (@attachment.image? ? 'inline' : 'attachment')
end
end
# images are sent inline
send_file @attachment.diskfile, :filename => filename_for_content_disposition(@attachment.filename),
:type => detect_content_type(@attachment),
:disposition => (@attachment.image? ? 'inline' : 'attachment')
def thumbnail
if @attachment.thumbnailable? && thumbnail = @attachment.thumbnail(:size => params[:size])
if stale?(:etag => thumbnail)
send_file thumbnail,
:filename => filename_for_content_disposition(@attachment.filename),
:type => detect_content_type(@attachment),
:disposition => 'inline'
end
else
# No thumbnail for the attachment or thumbnail could not be created
render :nothing => true, :status => 404
end
end
def upload
@@ -84,7 +69,7 @@ class AttachmentsController < ApplicationController
@attachment = Attachment.new(:file => request.raw_post)
@attachment.author = User.current
@attachment.filename = params[:filename].presence || Redmine::Utils.random_hex(16)
@attachment.filename = Redmine::Utils.random_hex(16)
if @attachment.save
respond_to do |format|

View File

@@ -20,25 +20,25 @@ class AutoCompletesController < ApplicationController
def issues
@issues = []
q = (params[:q] || params[:term]).to_s.strip
if q.present?
scope = (params[:scope] == "all" || @project.nil? ? Issue : @project.issues).visible
if q.match(/^\d+$/)
@issues << scope.find_by_id(q.to_i)
end
@issues += scope.where("LOWER(#{Issue.table_name}.subject) LIKE ?", "%#{q.downcase}%").order("#{Issue.table_name}.id DESC").limit(10).all
@issues.compact!
q = params[:q].to_s
query = (params[:scope] == "all" && Setting.cross_project_issue_relations?) ? Issue : @project.issues
if q.match(/^\d+$/)
@issues << query.visible.find_by_id(q.to_i)
end
unless q.blank?
@issues += query.visible.find(:all, :conditions => ["LOWER(#{Issue.table_name}.subject) LIKE ?", "%#{q.downcase}%"], :limit => 10)
end
@issues.compact!
render :layout => false
end
private
def find_project
if params[:project_id].present?
@project = Project.find(params[:project_id])
end
project_id = (params[:issue] && params[:issue][:project_id]) || params[:project_id]
@project = Project.find(project_id)
rescue ActiveRecord::RecordNotFound
render_404
end
end

View File

@@ -25,7 +25,7 @@ class BoardsController < ApplicationController
helper :watchers
def index
@boards = @project.boards.includes(:last_message => :author).all
@boards = @project.boards
# show the board if there is only one
if @boards.size == 1
@board = @boards.first
@@ -43,10 +43,10 @@ class BoardsController < ApplicationController
@topic_count = @board.topics.count
@topic_pages = Paginator.new self, @topic_count, per_page_option, params['page']
@topics = @board.topics.reorder("#{Message.table_name}.sticky DESC").order(sort_clause).all(
@topics = @board.topics.find :all, :order => ["#{Message.table_name}.sticky DESC", sort_clause].compact.join(', '),
:include => [:author, {:last_reply => :author}],
:limit => @topic_pages.items_per_page,
:offset => @topic_pages.current.offset)
:offset => @topic_pages.current.offset
@message = Message.new(:board => @board)
render :action => 'show', :layout => !request.xhr?
}

View File

@@ -24,7 +24,6 @@ class ContextMenusController < ApplicationController
if (@issues.size == 1)
@issue = @issues.first
end
@issue_ids = @issues.map(&:id).sort
@allowed_statuses = @issues.map(&:new_statuses_allowed_to).reduce(:&)
@projects = @issues.collect(&:project).compact.uniq
@@ -49,7 +48,6 @@ class ContextMenusController < ApplicationController
@assignables = @projects.map(&:assignable_users).reduce(:&)
@trackers = @projects.map(&:trackers).reduce(:&)
end
@versions = @projects.map {|p| p.shared_versions.open}.reduce(:&)
@priorities = IssuePriority.active.reverse
@back = back_url
@@ -67,7 +65,6 @@ class ContextMenusController < ApplicationController
end
end
@safe_attributes = @issues.map(&:safe_attribute_names).reduce(:&)
render :layout => false
end

View File

@@ -18,26 +18,13 @@
class EnumerationsController < ApplicationController
layout 'admin'
before_filter :require_admin, :except => :index
before_filter :require_admin_or_api_request, :only => :index
before_filter :require_admin
before_filter :build_new_enumeration, :only => [:new, :create]
before_filter :find_enumeration, :only => [:edit, :update, :destroy]
accept_api_auth :index
helper :custom_fields
def index
respond_to do |format|
format.html
format.api {
@klass = Enumeration.get_subclass(params[:type])
if @klass
@enumerations = @klass.shared.sorted.all
else
render_404
end
}
end
end
def new
@@ -46,7 +33,7 @@ class EnumerationsController < ApplicationController
def create
if request.post? && @enumeration.save
flash[:notice] = l(:notice_successful_create)
redirect_to :action => 'index'
redirect_to :action => 'index', :type => @enumeration.type
else
render :action => 'new'
end
@@ -58,7 +45,7 @@ class EnumerationsController < ApplicationController
def update
if request.put? && @enumeration.update_attributes(params[:enumeration])
flash[:notice] = l(:notice_successful_update)
redirect_to :action => 'index'
redirect_to :action => 'index', :type => @enumeration.type
else
render :action => 'edit'
end

View File

@@ -19,34 +19,51 @@ class GroupsController < ApplicationController
layout 'admin'
before_filter :require_admin
before_filter :find_group, :except => [:index, :new, :create]
accept_api_auth :index, :show, :create, :update, :destroy, :add_users, :remove_user
helper :custom_fields
# GET /groups
# GET /groups.xml
def index
@groups = Group.sorted.all
@groups = Group.find(:all, :order => 'lastname')
respond_to do |format|
format.html
format.api
format.html # index.html.erb
format.xml { render :xml => @groups }
end
end
# GET /groups/1
# GET /groups/1.xml
def show
@group = Group.find(params[:id])
respond_to do |format|
format.html
format.api
format.html # show.html.erb
format.xml { render :xml => @group }
end
end
# GET /groups/new
# GET /groups/new.xml
def new
@group = Group.new
respond_to do |format|
format.html # new.html.erb
format.xml { render :xml => @group }
end
end
# GET /groups/1/edit
def edit
@group = Group.find(params[:id], :include => :projects)
end
# POST /groups
# POST /groups.xml
def create
@group = Group.new
@group.safe_attributes = params[:group]
@group = Group.new(params[:group])
respond_to do |format|
if @group.save
@@ -54,87 +71,102 @@ class GroupsController < ApplicationController
flash[:notice] = l(:notice_successful_create)
redirect_to(params[:continue] ? new_group_path : groups_path)
}
format.api { render :action => 'show', :status => :created, :location => group_url(@group) }
format.xml { render :xml => @group, :status => :created, :location => @group }
else
format.html { render :action => "new" }
format.api { render_validation_errors(@group) }
format.xml { render :xml => @group.errors, :status => :unprocessable_entity }
end
end
end
def edit
end
# PUT /groups/1
# PUT /groups/1.xml
def update
@group.safe_attributes = params[:group]
@group = Group.find(params[:id])
respond_to do |format|
if @group.save
if @group.update_attributes(params[:group])
flash[:notice] = l(:notice_successful_update)
format.html { redirect_to(groups_path) }
format.api { render_api_ok }
format.xml { head :ok }
else
format.html { render :action => "edit" }
format.api { render_validation_errors(@group) }
format.xml { render :xml => @group.errors, :status => :unprocessable_entity }
end
end
end
# DELETE /groups/1
# DELETE /groups/1.xml
def destroy
@group = Group.find(params[:id])
@group.destroy
respond_to do |format|
format.html { redirect_to(groups_url) }
format.api { render_api_ok }
format.xml { head :ok }
end
end
def add_users
@users = User.find_all_by_id(params[:user_id] || params[:user_ids])
@group.users << @users if request.post?
@group = Group.find(params[:id])
users = User.find_all_by_id(params[:user_ids])
@group.users << users if request.post?
respond_to do |format|
format.html { redirect_to :controller => 'groups', :action => 'edit', :id => @group, :tab => 'users' }
format.js
format.api { render_api_ok }
format.js {
render(:update) {|page|
page.replace_html "tab-content-users", :partial => 'groups/users'
users.each {|user| page.visual_effect(:highlight, "user-#{user.id}") }
}
}
end
end
def remove_user
@group = Group.find(params[:id])
@group.users.delete(User.find(params[:user_id])) if request.delete?
respond_to do |format|
format.html { redirect_to :controller => 'groups', :action => 'edit', :id => @group, :tab => 'users' }
format.js
format.api { render_api_ok }
format.js { render(:update) {|page| page.replace_html "tab-content-users", :partial => 'groups/users'} }
end
end
def autocomplete_for_user
@group = Group.find(params[:id])
@users = User.active.not_in_group(@group).like(params[:q]).all(:limit => 100)
render :layout => false
end
def edit_membership
@group = Group.find(params[:id])
@membership = Member.edit_membership(params[:membership_id], params[:membership], @group)
@membership.save if request.post?
respond_to do |format|
format.html { redirect_to :controller => 'groups', :action => 'edit', :id => @group, :tab => 'memberships' }
format.js
if @membership.valid?
format.html { redirect_to :controller => 'groups', :action => 'edit', :id => @group, :tab => 'memberships' }
format.js {
render(:update) {|page|
page.replace_html "tab-content-memberships", :partial => 'groups/memberships'
page.visual_effect(:highlight, "member-#{@membership.id}")
}
}
else
format.js {
render(:update) {|page|
page.alert(l(:notice_failed_to_save_members, :errors => @membership.errors.full_messages.join(', ')))
}
}
end
end
end
def destroy_membership
@group = Group.find(params[:id])
Member.find(params[:membership_id]).destroy if request.post?
respond_to do |format|
format.html { redirect_to :controller => 'groups', :action => 'edit', :id => @group, :tab => 'memberships' }
format.js
format.js { render(:update) {|page| page.replace_html "tab-content-memberships", :partial => 'groups/memberships'} }
end
end
private
def find_group
@group = Group.find(params[:id])
rescue ActiveRecord::RecordNotFound
render_404
end
end

View File

@@ -23,7 +23,7 @@ class IssueCategoriesController < ApplicationController
before_filter :find_project_by_project_id, :only => [:index, :new, :create]
before_filter :authorize
accept_api_auth :index, :show, :create, :update, :destroy
def index
respond_to do |format|
format.html { redirect_to :controller => 'projects', :action => 'settings', :tab => 'categories', :id => @project }
@@ -41,11 +41,6 @@ class IssueCategoriesController < ApplicationController
def new
@category = @project.issue_categories.build
@category.safe_attributes = params[:issue_category]
respond_to do |format|
format.html
format.js
end
end
def create
@@ -57,13 +52,20 @@ class IssueCategoriesController < ApplicationController
flash[:notice] = l(:notice_successful_create)
redirect_to :controller => 'projects', :action => 'settings', :tab => 'categories', :id => @project
end
format.js
format.js do
# IE doesn't support the replace_html rjs method for select box options
render(:update) {|page| page.replace "issue_category_id",
content_tag('select', content_tag('option') + options_from_collection_for_select(@project.issue_categories, 'id', 'name', @category.id), :id => 'issue_category_id', :name => 'issue[category_id]')
}
end
format.api { render :action => 'show', :status => :created, :location => issue_category_path(@category) }
end
else
respond_to do |format|
format.html { render :action => 'new'}
format.js { render :action => 'new'}
format.js do
render(:update) {|page| page.alert(@category.errors.full_messages.join('\n')) }
end
format.api { render_validation_errors(@category) }
end
end
@@ -80,7 +82,7 @@ class IssueCategoriesController < ApplicationController
flash[:notice] = l(:notice_successful_update)
redirect_to :controller => 'projects', :action => 'settings', :tab => 'categories', :id => @project
}
format.api { render_api_ok }
format.api { head :ok }
end
else
respond_to do |format|
@@ -92,7 +94,7 @@ class IssueCategoriesController < ApplicationController
def destroy
@issue_count = @category.issues.size
if @issue_count == 0 || params[:todo] || api_request?
if @issue_count == 0 || params[:todo] || api_request?
reassign_to = nil
if params[:reassign_to_id] && (params[:todo] == 'reassign' || params[:todo].blank?)
reassign_to = @project.issue_categories.find_by_id(params[:reassign_to_id])
@@ -100,7 +102,7 @@ class IssueCategoriesController < ApplicationController
@category.destroy(reassign_to)
respond_to do |format|
format.html { redirect_to :controller => 'projects', :action => 'settings', :id => @project, :tab => 'categories' }
format.api { render_api_ok }
format.api { head :ok }
end
return
end

View File

@@ -49,9 +49,16 @@ class IssueRelationsController < ApplicationController
respond_to do |format|
format.html { redirect_to :controller => 'issues', :action => 'show', :id => @issue }
format.js {
format.js do
@relations = @issue.relations.select {|r| r.other_issue(@issue) && r.other_issue(@issue).visible? }
}
render :update do |page|
page.replace_html "relations", :partial => 'issues/relations'
if @relation.errors.empty?
page << "$('relation_delay').value = ''"
page << "$('relation_issue_to_id').value = ''"
end
end
end
format.api {
if saved
render :action => 'show', :status => :created, :location => relation_url(@relation)
@@ -68,8 +75,8 @@ class IssueRelationsController < ApplicationController
respond_to do |format|
format.html { redirect_to issue_path } # TODO : does this really work since @issue is always nil? What is it useful to?
format.js
format.api { render_api_ok }
format.js { render(:update) {|page| page.remove "relation-#{@relation.id}"} }
format.api { head :ok }
end
end

View File

@@ -50,13 +50,13 @@ class IssuesController < ApplicationController
include SortHelper
include IssuesHelper
helper :timelog
helper :gantt
include Redmine::Export::PDF
def index
retrieve_query
sort_init(@query.sort_criteria.empty? ? [['id', 'desc']] : @query.sort_criteria)
sort_update(@query.sortable_columns)
@query.sort_criteria = sort_criteria.to_a
if @query.valid?
case params[:format]
@@ -82,7 +82,7 @@ class IssuesController < ApplicationController
respond_to do |format|
format.html { render :template => 'issues/index', :layout => !request.xhr? }
format.api {
Issue.load_visible_relations(@issues) if include_in_api_response?('relations')
Issue.load_relations(@issues) if include_in_api_response?('relations')
}
format.atom { render_feed(@issues, :title => "#{@project || Setting.app_title}: #{l(:label_issue_plural)}") }
format.csv { send_data(issues_to_csv(@issues, @project, @query, params), :type => 'text/csv; header=present', :filename => 'export.csv') }
@@ -100,9 +100,8 @@ class IssuesController < ApplicationController
end
def show
@journals = @issue.journals.includes(:user, :details).reorder("#{Journal.table_name}.id ASC").all
@journals = @issue.journals.find(:all, :include => [:user, :details], :order => "#{Journal.table_name}.created_on ASC")
@journals.each_with_index {|j,i| j.indice = i+1}
@journals.reject!(&:private_notes?) unless User.current.allowed_to?(:view_private_notes, @issue.project)
@journals.reverse! if User.current.wants_comments_in_reverse_order?
@changesets = @issue.changesets.visible.all
@@ -120,10 +119,7 @@ class IssuesController < ApplicationController
}
format.api
format.atom { render :template => 'journals/index', :layout => false, :content_type => 'application/atom+xml' }
format.pdf {
pdf = issue_to_pdf(@issue, :journals => @journals)
send_data(pdf, :type => 'application/pdf', :filename => "#{@project.identifier}-#{@issue.id}.pdf")
}
format.pdf { send_data(issue_to_pdf(@issue), :type => 'application/pdf', :filename => "#{@project.identifier}-#{@issue.id}.pdf") }
end
end
@@ -132,7 +128,17 @@ class IssuesController < ApplicationController
def new
respond_to do |format|
format.html { render :action => 'new', :layout => !request.xhr? }
format.js { render :partial => 'update_form' }
format.js {
render(:update) { |page|
if params[:project_change]
page.replace_html 'all_attributes', :partial => 'form'
else
page.replace_html 'attributes', :partial => 'attributes'
end
m = User.current.allowed_to?(:log_time, @issue.project) ? 'show' : 'hide'
page << "if ($('log_time')) {Element.#{m}('log_time');}"
}
}
end
end
@@ -144,7 +150,7 @@ class IssuesController < ApplicationController
respond_to do |format|
format.html {
render_attachment_warning_if_needed(@issue)
flash[:notice] = l(:notice_issue_successful_create, :id => view_context.link_to("##{@issue.id}", issue_path(@issue), :title => @issue.subject))
flash[:notice] = l(:notice_issue_successful_create, :id => "<a href='#{issue_path(@issue)}'>##{@issue.id}</a>")
redirect_to(params[:continue] ? { :action => 'new', :project_id => @issue.project, :issue => {:tracker_id => @issue.tracker, :parent_issue_id => @issue.parent_issue_id}.reject {|k,v| v.nil?} } :
{ :action => 'show', :id => @issue })
}
@@ -177,8 +183,12 @@ class IssuesController < ApplicationController
rescue ActiveRecord::StaleObjectError
@conflict = true
if params[:last_journal_id]
@conflict_journals = @issue.journals_after(params[:last_journal_id]).all
@conflict_journals.reject!(&:private_notes?) unless User.current.allowed_to?(:view_private_notes, @issue.project)
if params[:last_journal_id].present?
last_journal_id = params[:last_journal_id].to_i
@conflict_journals = @issue.journals.all(:conditions => ["#{Journal.table_name}.id > ?", last_journal_id])
else
@conflict_journals = @issue.journals.all
end
end
end
@@ -188,7 +198,7 @@ class IssuesController < ApplicationController
respond_to do |format|
format.html { redirect_back_or_default({:action => 'show', :id => @issue}) }
format.api { render_api_ok }
format.api { head :ok }
end
else
respond_to do |format|
@@ -227,7 +237,6 @@ class IssuesController < ApplicationController
@categories = target_projects.map {|p| p.issue_categories}.reduce(:&)
if @copy
@attachments_present = @issues.detect {|i| i.attachments.any?}.present?
@subtasks_present = @issues.detect {|i| !i.leaf?}.present?
end
@safe_attributes = @issues.map(&:safe_attribute_names).reduce(:&)
@@ -241,20 +250,10 @@ class IssuesController < ApplicationController
unsaved_issue_ids = []
moved_issues = []
if @copy && params[:copy_subtasks].present?
# Descendant issues will be copied with the parent task
# Don't copy them twice
@issues.reject! {|issue| @issues.detect {|other| issue.is_descendant_of?(other)}}
end
@issues.each do |issue|
issue.reload
if @copy
issue = issue.copy({},
:attachments => params[:copy_attachments].present?,
:subtasks => params[:copy_subtasks].present?
)
issue = issue.copy({}, :attachments => params[:copy_attachments].present?)
end
journal = issue.init_journal(User.current, params[:notes])
issue.safe_attributes = attributes
@@ -309,11 +308,23 @@ class IssuesController < ApplicationController
end
respond_to do |format|
format.html { redirect_back_or_default(:action => 'index', :project_id => @project) }
format.api { render_api_ok }
format.api { head :ok }
end
end
private
private
def find_issue
# Issue.visible.find(...) can not be used to redirect user to the login form
# if the issue actually exists but requires authentication
@issue = Issue.find(params[:id], :include => [:project, :tracker, :status, :author, :priority, :category])
unless @issue.visible?
deny_access
return
end
@project = @issue.project
rescue ActiveRecord::RecordNotFound
render_404
end
def find_project
project_id = params[:project_id] || (params[:issue] && params[:issue][:project_id])
@@ -348,7 +359,8 @@ class IssuesController < ApplicationController
@time_entry = TimeEntry.new(:issue => @issue, :project => @issue.project)
@time_entry.attributes = params[:time_entry]
@issue.init_journal(User.current)
@notes = params[:notes] || (params[:issue].present? ? params[:issue][:notes] : nil)
@issue.init_journal(User.current, @notes)
issue_attributes = params[:issue]
if issue_attributes && params[:conflict_resolution]
@@ -357,7 +369,7 @@ class IssuesController < ApplicationController
issue_attributes = issue_attributes.dup
issue_attributes.delete(:lock_version)
when 'add_notes'
issue_attributes = issue_attributes.slice(:notes)
issue_attributes = {}
when 'cancel'
redirect_to issue_path(@issue)
return false
@@ -378,8 +390,7 @@ class IssuesController < ApplicationController
begin
@copy_from = Issue.visible.find(params[:copy_from])
@copy_attachments = params[:copy_attachments].present? || request.get?
@copy_subtasks = params[:copy_subtasks].present? || request.get?
@issue.copy_from(@copy_from, :attachments => @copy_attachments, :subtasks => @copy_subtasks)
@issue.copy_from(@copy_from, :attachments => @copy_attachments)
rescue ActiveRecord::RecordNotFound
render_404
return
@@ -391,7 +402,7 @@ class IssuesController < ApplicationController
end
@issue.project = @project
@issue.author ||= User.current
@issue.author = User.current
# Tracker must be set before custom field values
@issue.tracker ||= @project.trackers.find((params[:issue] && params[:issue][:tracker_id]) || params[:tracker_id] || :first)
if @issue.tracker.nil?

View File

@@ -57,20 +57,26 @@ class JournalsController < ApplicationController
end
def new
@journal = Journal.visible.find(params[:journal_id]) if params[:journal_id]
if @journal
user = @journal.user
text = @journal.notes
journal = Journal.find(params[:journal_id]) if params[:journal_id]
if journal
user = journal.user
text = journal.notes
else
user = @issue.author
text = @issue.description
end
# Replaces pre blocks with [...]
text = text.to_s.strip.gsub(%r{<pre>((.|\s)*?)</pre>}m, '[...]')
@content = "#{ll(Setting.default_language, :text_user_wrote, user)}\n> "
@content << text.gsub(/(\r?\n|\r\n?)/, "\n> ") + "\n\n"
rescue ActiveRecord::RecordNotFound
render_404
content = "#{ll(Setting.default_language, :text_user_wrote, user)}\n> "
content << text.gsub(/(\r?\n|\r\n?)/, "\n> ") + "\n\n"
render(:update) { |page|
page.<< "$('notes').value = \"#{escape_javascript content}\";"
page.show 'update'
page << "Form.Element.focus('notes');"
page << "Element.scrollTo('update');"
page << "$('notes').scrollTop = $('notes').scrollHeight - $('notes').clientHeight;"
}
end
def edit
@@ -97,9 +103,17 @@ class JournalsController < ApplicationController
private
def find_journal
@journal = Journal.visible.find(params[:id])
@journal = Journal.find(params[:id])
@project = @journal.journalized.project
rescue ActiveRecord::RecordNotFound
render_404
end
# TODO: duplicated in IssuesController
def find_issue
@issue = Issue.find(params[:id], :include => [:project, :tracker, :status, :author, :priority, :category])
@project = @issue.project
rescue ActiveRecord::RecordNotFound
render_404
end
end

View File

@@ -63,16 +63,31 @@ class MembersController < ApplicationController
end
respond_to do |format|
format.html { redirect_to :controller => 'projects', :action => 'settings', :tab => 'members', :id => @project }
format.js { @members = members }
format.api {
@member = members.first
if @member.valid?
if members.present? && members.all? {|m| m.valid? }
format.html { redirect_to :controller => 'projects', :action => 'settings', :tab => 'members', :id => @project }
format.js {
render(:update) {|page|
page.replace_html "tab-content-members", :partial => 'projects/settings/members'
page << 'hideOnLoad()'
members.each {|member| page.visual_effect(:highlight, "member-#{member.id}") }
}
}
format.api {
@member = members.first
render :action => 'show', :status => :created, :location => membership_url(@member)
else
render_validation_errors(@member)
end
}
}
else
format.js {
render(:update) {|page|
errors = members.collect {|m|
m.errors.full_messages
}.flatten.uniq
page.alert(l(:notice_failed_to_save_members, :errors => errors.join(', ')))
}
}
format.api { render_validation_errors(members.first) }
end
end
end
@@ -83,10 +98,16 @@ class MembersController < ApplicationController
saved = @member.save
respond_to do |format|
format.html { redirect_to :controller => 'projects', :action => 'settings', :tab => 'members', :id => @project }
format.js
format.js {
render(:update) {|page|
page.replace_html "tab-content-members", :partial => 'projects/settings/members'
page << 'hideOnLoad()'
page.visual_effect(:highlight, "member-#{@member.id}")
}
}
format.api {
if saved
render_api_ok
head :ok
else
render_validation_errors(@member)
end
@@ -100,10 +121,14 @@ class MembersController < ApplicationController
end
respond_to do |format|
format.html { redirect_to :controller => 'projects', :action => 'settings', :tab => 'members', :id => @project }
format.js
format.js { render(:update) {|page|
page.replace_html "tab-content-members", :partial => 'projects/settings/members'
page << 'hideOnLoad()'
}
}
format.api {
if @member.destroyed?
render_api_ok
head :ok
else
head :unprocessable_entity
end
@@ -115,4 +140,5 @@ class MembersController < ApplicationController
@principals = Principal.active.not_member_of(@project).like(params[:q]).all(:limit => 100)
render :layout => false
end
end

View File

@@ -22,7 +22,6 @@ class MessagesController < ApplicationController
before_filter :find_message, :except => [:new, :preview]
before_filter :authorize, :except => [:preview, :edit, :destroy]
helper :boards
helper :watchers
helper :attachments
include AttachmentsHelper
@@ -60,7 +59,7 @@ class MessagesController < ApplicationController
if @message.save
call_hook(:controller_messages_new_after_save, { :params => params, :message => @message})
render_attachment_warning_if_needed(@message)
redirect_to board_message_path(@board, @message)
redirect_to :action => 'show', :id => @message
end
end
end
@@ -77,7 +76,7 @@ class MessagesController < ApplicationController
attachments = Attachment.attach_files(@reply, params[:attachments])
render_attachment_warning_if_needed(@reply)
end
redirect_to board_message_path(@board, @topic, :r => @reply)
redirect_to :action => 'show', :id => @topic, :r => @reply
end
# Edit a message
@@ -89,7 +88,7 @@ class MessagesController < ApplicationController
render_attachment_warning_if_needed(@message)
flash[:notice] = l(:notice_successful_update)
@message.reload
redirect_to board_message_path(@message.board, @message.root, :r => (@message.parent_id && @message.id))
redirect_to :action => 'show', :board_id => @message.board, :id => @message.root, :r => (@message.parent_id && @message.id)
end
end
@@ -98,26 +97,32 @@ class MessagesController < ApplicationController
(render_403; return false) unless @message.destroyable_by?(User.current)
r = @message.to_param
@message.destroy
if @message.parent
redirect_to board_message_path(@board, @message.parent, :r => r)
else
redirect_to project_board_path(@project, @board)
end
redirect_to @message.parent.nil? ?
{ :controller => 'boards', :action => 'show', :project_id => @project, :id => @board } :
{ :action => 'show', :id => @message.parent, :r => r }
end
def quote
@subject = @message.subject
@subject = "RE: #{@subject}" unless @subject.starts_with?('RE:')
@content = "#{ll(Setting.default_language, :text_user_wrote, @message.author)}\n> "
@content << @message.content.to_s.strip.gsub(%r{<pre>((.|\s)*?)</pre>}m, '[...]').gsub(/(\r?\n|\r\n?)/, "\n> ") + "\n\n"
user = @message.author
text = @message.content
subject = @message.subject.gsub('"', '\"')
subject = "RE: #{subject}" unless subject.starts_with?('RE:')
content = "#{ll(Setting.default_language, :text_user_wrote, user)}\\n> "
content << text.to_s.strip.gsub(%r{<pre>((.|\s)*?)</pre>}m, '[...]').gsub('"', '\"').gsub(/(\r?\n|\r\n?)/, "\\n> ") + "\\n\\n"
render(:update) { |page|
page << "$('message_subject').value = \"#{subject}\";"
page.<< "$('message_content').value = \"#{content}\";"
page.show 'reply'
page << "Form.Element.focus('message_content');"
page << "Element.scrollTo('reply');"
page << "$('message_content').scrollTop = $('message_content').scrollHeight - $('message_content').clientHeight;"
}
end
def preview
message = @board.messages.find_by_id(params[:id])
@attachements = message.attachments if message
@text = (params[:message] || params[:reply])[:content]
@previewed = message
render :partial => 'common/preview'
end

View File

@@ -135,11 +135,7 @@ class MyController < ApplicationController
@user = User.current
@blocks = @user.pref[:my_page_layout] || DEFAULT_LAYOUT.dup
@block_options = []
BLOCKS.each do |k, v|
unless %w(top left right).detect {|f| (@blocks[f] ||= []).include?(k)}
@block_options << [l("my.blocks.#{v}", :default => [v, v.to_s.humanize]), k.dasherize]
end
end
BLOCKS.each {|k, v| @block_options << [l("my.blocks.#{v}", :default => [v, v.to_s.humanize]), k.dasherize]}
end
# Add a block to user's page
@@ -147,17 +143,16 @@ class MyController < ApplicationController
# params[:block] : id of the block to add
def add_block
block = params[:block].to_s.underscore
if block.present? && BLOCKS.key?(block)
@user = User.current
layout = @user.pref[:my_page_layout] || {}
# remove if already present in a group
%w(top left right).each {|f| (layout[f] ||= []).delete block }
# add it on top
layout['top'].unshift block
@user.pref[:my_page_layout] = layout
@user.pref.save
end
redirect_to :action => 'page_layout'
(render :nothing => true; return) unless block && (BLOCKS.keys.include? block)
@user = User.current
layout = @user.pref[:my_page_layout] || {}
# remove if already present in a group
%w(top left right).each {|f| (layout[f] ||= []).delete block }
# add it on top
layout['top'].unshift block
@user.pref[:my_page_layout] = layout
@user.pref.save
render :partial => "block", :locals => {:user => @user, :block_name => block}
end
# Remove a block to user's page
@@ -170,7 +165,7 @@ class MyController < ApplicationController
%w(top left right).each {|f| (layout[f] ||= []).delete block }
@user.pref[:my_page_layout] = layout
@user.pref.save
redirect_to :action => 'page_layout'
render :nothing => true
end
# Change blocks order on user's page
@@ -180,8 +175,7 @@ class MyController < ApplicationController
group = params[:group]
@user = User.current
if group.is_a?(String)
group_items = (params["blocks"] || []).collect(&:underscore)
group_items.each {|s| s.sub!(/^block_/, '')}
group_items = (params["list-#{group}"] || []).collect(&:underscore)
if group_items and group_items.is_a? Array
layout = @user.pref[:my_page_layout] || {}
# remove group blocks if they are presents in other groups

View File

@@ -26,8 +26,7 @@ class PreviewsController < ApplicationController
if @description && @description.gsub(/(\r?\n|\n\r?)/, "\n") == @issue.description.to_s.gsub(/(\r?\n|\n\r?)/, "\n")
@description = nil
end
# params[:notes] is useful for preview of notes in issue history
@notes = params[:notes] || (params[:issue] ? params[:issue][:notes] : nil)
@notes = params[:notes]
else
@description = (params[:issue] ? params[:issue][:description] : nil)
end
@@ -35,10 +34,6 @@ class PreviewsController < ApplicationController
end
def news
if params[:id].present? && news = News.visible.find_by_id(params[:id])
@previewed = news
@attachments = news.attachments
end
@text = (params[:news] ? params[:news][:description] : nil)
render :partial => 'common/preview'
end

View File

@@ -48,11 +48,7 @@ class ProjectsController < ApplicationController
def index
respond_to do |format|
format.html {
scope = Project
unless params[:closed]
scope = scope.active
end
@projects = scope.visible.order('lft').all
@projects = Project.visible.find(:all, :order => 'lft')
}
format.api {
@offset, @limit = api_offset_and_limit
@@ -69,14 +65,14 @@ class ProjectsController < ApplicationController
def new
@issue_custom_fields = IssueCustomField.find(:all, :order => "#{CustomField.table_name}.position")
@trackers = Tracker.sorted.all
@trackers = Tracker.all
@project = Project.new
@project.safe_attributes = params[:project]
end
def create
@issue_custom_fields = IssueCustomField.find(:all, :order => "#{CustomField.table_name}.position")
@trackers = Tracker.sorted.all
@trackers = Tracker.all
@project = Project.new
@project.safe_attributes = params[:project]
@@ -109,14 +105,18 @@ class ProjectsController < ApplicationController
def copy
@issue_custom_fields = IssueCustomField.find(:all, :order => "#{CustomField.table_name}.position")
@trackers = Tracker.sorted.all
@trackers = Tracker.all
@root_projects = Project.find(:all,
:conditions => "parent_id IS NULL AND status = #{Project::STATUS_ACTIVE}",
:order => 'name')
@source_project = Project.find(params[:id])
if request.get?
@project = Project.copy_from(@source_project)
@project.identifier = Project.next_identifier if Setting.sequential_project_identifiers?
if @project
@project.identifier = Project.next_identifier if Setting.sequential_project_identifiers?
else
redirect_to :controller => 'admin', :action => 'projects'
end
else
Mailer.with_deliveries(params[:notifications] == '1') do
@project = Project.new
@@ -135,8 +135,7 @@ class ProjectsController < ApplicationController
end
end
rescue ActiveRecord::RecordNotFound
# source_project not found
render_404
redirect_to :controller => 'admin', :action => 'projects'
end
# Show @project
@@ -153,8 +152,12 @@ class ProjectsController < ApplicationController
cond = @project.project_condition(Setting.display_subprojects_issues?)
@open_issues_by_tracker = Issue.visible.open.where(cond).count(:group => :tracker)
@total_issues_by_tracker = Issue.visible.where(cond).count(:group => :tracker)
@open_issues_by_tracker = Issue.visible.count(:group => :tracker,
:include => [:project, :status, :tracker],
:conditions => ["(#{cond}) AND #{IssueStatus.table_name}.is_closed=?", false])
@total_issues_by_tracker = Issue.visible.count(:group => :tracker,
:include => [:project, :status, :tracker],
:conditions => cond)
if User.current.allowed_to?(:view_time_entries, @project)
@total_hours = TimeEntry.visible.sum(:hours, :include => :project, :conditions => cond).to_f
@@ -172,7 +175,7 @@ class ProjectsController < ApplicationController
@issue_custom_fields = IssueCustomField.find(:all, :order => "#{CustomField.table_name}.position")
@issue_category ||= IssueCategory.new
@member ||= @project.members.new
@trackers = Tracker.sorted.all
@trackers = Tracker.all
@wiki ||= @project.wiki
end
@@ -188,7 +191,7 @@ class ProjectsController < ApplicationController
flash[:notice] = l(:notice_successful_update)
redirect_to :action => 'settings', :id => @project
}
format.api { render_api_ok }
format.api { head :ok }
end
else
respond_to do |format|
@@ -221,16 +224,6 @@ class ProjectsController < ApplicationController
redirect_to(url_for(:controller => 'admin', :action => 'projects', :status => params[:status]))
end
def close
@project.close
redirect_to project_path(@project)
end
def reopen
@project.reopen
redirect_to project_path(@project)
end
# Delete @project
def destroy
@project_to_destroy = @project
@@ -238,7 +231,7 @@ class ProjectsController < ApplicationController
@project_to_destroy.destroy
respond_to do |format|
format.html { redirect_to :controller => 'admin', :action => 'projects' }
format.api { render_api_ok }
format.api { head :ok }
end
end
# hide project in layout

View File

@@ -22,7 +22,7 @@ class ReportsController < ApplicationController
def issue_report
@trackers = @project.trackers
@versions = @project.shared_versions.sort
@priorities = IssuePriority.all.reverse
@priorities = IssuePriority.all
@categories = @project.issue_categories
@assignees = (Setting.issue_group_assignment? ? @project.principals : @project.users).sort
@authors = @project.users.sort
@@ -53,7 +53,7 @@ class ReportsController < ApplicationController
@report_title = l(:field_version)
when "priority"
@field = "priority_id"
@rows = IssuePriority.all.reverse
@rows = IssuePriority.all
@data = Issue.by_priority(@project)
@report_title = l(:field_priority)
when "category"

View File

@@ -42,12 +42,12 @@ class RepositoriesController < ApplicationController
@repository = Repository.factory(scm)
@repository.is_default = @project.repository.nil?
@repository.project = @project
render :layout => !request.xhr?
end
def create
attrs = pickup_extra_info
@repository = Repository.factory(params[:repository_scm])
@repository.safe_attributes = params[:repository]
@repository = Repository.factory(params[:repository_scm], attrs[:attrs])
if attrs[:attrs_extra].keys.any?
@repository.merge_extra_info(attrs[:attrs_extra])
end
@@ -64,7 +64,7 @@ class RepositoriesController < ApplicationController
def update
attrs = pickup_extra_info
@repository.safe_attributes = attrs[:attrs]
@repository.attributes = attrs[:attrs]
if attrs[:attrs_extra].keys.any?
@repository.merge_extra_info(attrs[:attrs_extra])
end
@@ -176,7 +176,6 @@ class RepositoriesController < ApplicationController
send_opt = { :filename => filename_for_content_disposition(@path.split('/').last) }
send_type = Redmine::MimeType.of(@path)
send_opt[:type] = send_type.to_s if send_type
send_opt[:disposition] = (Redmine::MimeType.is_type?('image', @path) && !is_raw ? 'inline' : 'attachment')
send_data @content, send_opt
else
# Prevent empty lines when displaying a file with Windows style eol
@@ -235,6 +234,22 @@ class RepositoriesController < ApplicationController
if @issue
@changeset.issues << @issue
respond_to do |format|
format.js {
render :update do |page|
page.replace_html "related-issues", :partial => "related_issues"
page.visual_effect :highlight, "related-issue-#{@issue.id}"
end
}
end
else
respond_to do |format|
format.js {
render :update do |page|
page.alert(l(:label_issue) + ' ' + l('activerecord.errors.messages.invalid'))
end
}
end
end
end
@@ -242,9 +257,17 @@ class RepositoriesController < ApplicationController
# DELETE /projects/:project_id/repository/(:repository_id/)revisions/:rev/issues/:issue_id
def remove_related_issue
@issue = Issue.visible.find_by_id(params[:issue_id])
if @issue
if @issue
@changeset.issues.delete(@issue)
end
respond_to do |format|
format.js {
render :update do |page|
page.remove "related-issue-#{@issue.id}"
end if @issue
}
end
end
def diff
@@ -431,3 +454,4 @@ class RepositoriesController < ApplicationController
graph.burn
end
end

View File

@@ -18,10 +18,10 @@
class RolesController < ApplicationController
layout 'admin'
before_filter :require_admin, :except => [:index, :show]
before_filter :require_admin_or_api_request, :only => [:index, :show]
before_filter :find_role, :only => [:show, :edit, :update, :destroy]
accept_api_auth :index, :show
before_filter :require_admin, :except => :index
before_filter :require_admin_or_api_request, :only => :index
before_filter :find_role, :only => [:edit, :update, :destroy]
accept_api_auth :index
def index
respond_to do |format|
@@ -35,18 +35,9 @@ class RolesController < ApplicationController
end
end
def show
respond_to do |format|
format.api
end
end
def new
# Prefills the form with 'Non member' role permissions by default
# Prefills the form with 'Non member' role permissions
@role = Role.new(params[:role] || {:permissions => Role.non_member.permissions})
if params[:copy].present? && @copy_from = Role.find_by_id(params[:copy])
@role.copy_from(@copy_from)
end
@roles = Role.sorted.all
end
@@ -55,7 +46,7 @@ class RolesController < ApplicationController
if request.post? && @role.save
# workflow copy
if !params[:copy_workflow_from].blank? && (copy_from = Role.find_by_id(params[:copy_workflow_from]))
@role.workflow_rules.copy(copy_from)
@role.workflows.copy(copy_from)
end
flash[:notice] = l(:notice_successful_create)
redirect_to :action => 'index'

View File

@@ -39,8 +39,7 @@ class SettingsController < ApplicationController
redirect_to :action => 'edit', :tab => params[:tab]
else
@options = {}
user_format = User::USER_FORMATS.collect{|key, value| [key, value[:setting_order]]}.sort{|a, b| a[1] <=> b[1]}
@options[:user_format] = user_format.collect{|f| [User.current.name(f[0]), f[0].to_s]}
@options[:user_format] = User::USER_FORMATS.keys.collect {|f| [User.current.name(f), f.to_s] }
@deliveries = ActionMailer::Base.perform_deliveries
@guessed_host_and_path = request.host_with_port.dup

View File

@@ -39,7 +39,7 @@ class TimelogController < ApplicationController
def index
sort_init 'spent_on', 'desc'
sort_update 'spent_on' => ['spent_on', "#{TimeEntry.table_name}.created_on"],
sort_update 'spent_on' => 'spent_on',
'user' => 'user_id',
'activity' => 'activity_id',
'project' => "#{Project.table_name}.name",
@@ -138,7 +138,7 @@ class TimelogController < ApplicationController
:time_entry => {:issue_id => @time_entry.issue_id, :activity_id => @time_entry.activity_id},
:back_url => params[:back_url]
else
redirect_to :action => 'new',
redirect_to :action => 'new',
:time_entry => {:project_id => @time_entry.project_id, :issue_id => @time_entry.issue_id, :activity_id => @time_entry.activity_id},
:back_url => params[:back_url]
end
@@ -171,7 +171,7 @@ class TimelogController < ApplicationController
flash[:notice] = l(:notice_successful_update)
redirect_back_or_default :action => 'index', :project_id => @time_entry.project
}
format.api { render_api_ok }
format.api { head :ok }
end
else
respond_to do |format|
@@ -223,7 +223,7 @@ class TimelogController < ApplicationController
}
format.api {
if destroyed
render_api_ok
head :ok
else
render_validation_errors(@time_entries)
end
@@ -308,9 +308,6 @@ private
when 'last_week'
@from = Date.today - 7 - (Date.today.cwday - 1)%7
@to = @from + 6
when 'last_2_weeks'
@from = Date.today - 14 - (Date.today.cwday - 1)%7
@to = @from + 13
when '7_days'
@from = Date.today - 7
@to = Date.today

View File

@@ -29,7 +29,7 @@ class TrackersController < ApplicationController
render :action => "index", :layout => false if request.xhr?
}
format.api {
@trackers = Tracker.sorted.all
@trackers = Tracker.all
}
end
end
@@ -45,7 +45,7 @@ class TrackersController < ApplicationController
if request.post? and @tracker.save
# workflow copy
if !params[:copy_workflow_from].blank? && (copy_from = Tracker.find_by_id(params[:copy_workflow_from]))
@tracker.workflow_rules.copy(copy_from)
@tracker.workflows.copy(copy_from)
end
flash[:notice] = l(:notice_successful_create)
redirect_to :action => 'index'
@@ -59,7 +59,7 @@ class TrackersController < ApplicationController
@tracker ||= Tracker.find(params[:id])
@projects = Project.find(:all)
end
def update
@tracker = Tracker.find(params[:id])
if request.put? and @tracker.update_attributes(params[:tracker])
@@ -80,22 +80,4 @@ class TrackersController < ApplicationController
end
redirect_to :action => 'index'
end
def fields
if request.post? && params[:trackers]
params[:trackers].each do |tracker_id, tracker_params|
tracker = Tracker.find_by_id(tracker_id)
if tracker
tracker.core_fields = tracker_params[:core_fields]
tracker.custom_field_ids = tracker_params[:custom_field_ids]
tracker.save
end
end
flash[:notice] = l(:notice_successful_update)
redirect_to :action => 'fields'
return
end
@trackers = Tracker.sorted.all
@custom_fields = IssueCustomField.all.sort
end
end

View File

@@ -103,7 +103,7 @@ class UsersController < ApplicationController
respond_to do |format|
format.html {
flash[:notice] = l(:notice_user_successful_create, :id => view_context.link_to(@user.login, user_path(@user)))
flash[:notice] = l(:notice_successful_create)
redirect_to(params[:continue] ?
{:controller => 'users', :action => 'new'} :
{:controller => 'users', :action => 'edit', :id => @user}
@@ -156,7 +156,7 @@ class UsersController < ApplicationController
flash[:notice] = l(:notice_successful_update)
redirect_to_referer_or edit_user_path(@user)
}
format.api { render_api_ok }
format.api { head :ok }
end
else
@auth_sources = AuthSource.find(:all)
@@ -174,8 +174,8 @@ class UsersController < ApplicationController
def destroy
@user.destroy
respond_to do |format|
format.html { redirect_back_or_default(users_url) }
format.api { render_api_ok }
format.html { redirect_to_referer_or(users_url) }
format.api { head :ok }
end
end
@@ -183,8 +183,21 @@ class UsersController < ApplicationController
@membership = Member.edit_membership(params[:membership_id], params[:membership], @user)
@membership.save
respond_to do |format|
format.html { redirect_to :controller => 'users', :action => 'edit', :id => @user, :tab => 'memberships' }
format.js
if @membership.valid?
format.html { redirect_to :controller => 'users', :action => 'edit', :id => @user, :tab => 'memberships' }
format.js {
render(:update) {|page|
page.replace_html "tab-content-memberships", :partial => 'users/memberships'
page.visual_effect(:highlight, "member-#{@membership.id}")
}
}
else
format.js {
render(:update) {|page|
page.alert(l(:notice_failed_to_save_members, :errors => @membership.errors.full_messages.join(', ')))
}
}
end
end
end
@@ -195,7 +208,7 @@ class UsersController < ApplicationController
end
respond_to do |format|
format.html { redirect_to :controller => 'users', :action => 'edit', :id => @user, :tab => 'memberships' }
format.js
format.js { render(:update) {|page| page.replace_html "tab-content-memberships", :partial => 'users/memberships'} }
end
end

View File

@@ -20,7 +20,7 @@ class VersionsController < ApplicationController
model_object Version
before_filter :find_model_object, :except => [:index, :new, :create, :close_completed]
before_filter :find_project_from_association, :except => [:index, :new, :create, :close_completed]
before_filter :find_project_by_project_id, :only => [:index, :new, :create, :close_completed]
before_filter :find_project, :only => [:index, :new, :create, :close_completed]
before_filter :authorize
accept_api_auth :index, :show, :create, :update, :destroy
@@ -78,7 +78,13 @@ class VersionsController < ApplicationController
respond_to do |format|
format.html
format.js
format.js do
render :update do |page|
page.replace_html 'ajax-modal', :partial => 'versions/new_modal'
page << "showModal('ajax-modal', '600px');"
page << "Form.Element.focus('version_name');"
end
end
end
end
@@ -97,7 +103,14 @@ class VersionsController < ApplicationController
flash[:notice] = l(:notice_successful_create)
redirect_back_or_default :controller => 'projects', :action => 'settings', :tab => 'versions', :id => @project
end
format.js
format.js do
render(:update) {|page|
page << 'hideModal();'
# IE doesn't support the replace_html rjs method for select box options
page.replace "issue_fixed_version_id",
content_tag('select', content_tag('option') + version_options_for_select(@project.shared_versions.open, @version), :id => 'issue_fixed_version_id', :name => 'issue[fixed_version_id]')
}
end
format.api do
render :action => 'show', :status => :created, :location => version_url(@version)
end
@@ -105,7 +118,12 @@ class VersionsController < ApplicationController
else
respond_to do |format|
format.html { render :action => 'new' }
format.js { render :action => 'new' }
format.js do
render :update do |page|
page.replace_html 'ajax-modal', :partial => 'versions/new_modal'
page << "Form.Element.focus('version_name');"
end
end
format.api { render_validation_errors(@version) }
end
end
@@ -126,7 +144,7 @@ class VersionsController < ApplicationController
flash[:notice] = l(:notice_successful_update)
redirect_back_or_default :controller => 'projects', :action => 'settings', :tab => 'versions', :id => @project
}
format.api { render_api_ok }
format.api { head :ok }
end
else
respond_to do |format|
@@ -149,7 +167,7 @@ class VersionsController < ApplicationController
@version.destroy
respond_to do |format|
format.html { redirect_back_or_default :controller => 'projects', :action => 'settings', :tab => 'versions', :id => @project }
format.api { render_api_ok }
format.api { head :ok }
end
else
respond_to do |format|
@@ -165,11 +183,16 @@ class VersionsController < ApplicationController
def status_by
respond_to do |format|
format.html { render :action => 'show' }
format.js
format.js { render(:update) {|page| page.replace_html 'status_by', render_issue_status_by(@version, params[:status_by])} }
end
end
private
private
def find_project
@project = Project.find(params[:project_id])
rescue ActiveRecord::RecordNotFound
render_404
end
def retrieve_selected_tracker_ids(selectable_trackers, default_trackers=nil)
if ids = params[:tracker_ids]
@@ -178,4 +201,5 @@ class VersionsController < ApplicationController
@selected_tracker_ids = (default_trackers || selectable_trackers).collect {|t| t.id.to_s }
end
end
end

View File

@@ -33,6 +33,15 @@ class WatchersController < ApplicationController
end
def new
respond_to do |format|
format.js do
render :update do |page|
page.replace_html 'ajax-modal', :partial => 'watchers/new', :locals => {:watched => @watched}
page << "showModal('ajax-modal', '400px');"
page << "$('ajax-modal').addClassName('new-watcher');"
end
end
end
end
def create
@@ -44,14 +53,29 @@ class WatchersController < ApplicationController
end
respond_to do |format|
format.html { redirect_to_referer_or {render :text => 'Watcher added.', :layout => true}}
format.js
format.js do
render :update do |page|
page.replace_html 'ajax-modal', :partial => 'watchers/new', :locals => {:watched => @watched}
page.replace_html 'watchers', :partial => 'watchers/watchers', :locals => {:watched => @watched}
end
end
end
end
def append
if params[:watcher].is_a?(Hash)
user_ids = params[:watcher][:user_ids] || [params[:watcher][:user_id]]
@users = User.active.find_all_by_id(user_ids)
users = User.active.find_all_by_id(user_ids)
respond_to do |format|
format.js do
render :update do |page|
users.each do |user|
page << %|$$("#issue_watcher_user_ids_#{user.id}").each(function(el){el.remove();});|
end
page.insert_html :bottom, 'watchers_inputs', :text => watchers_checkboxes(nil, users, true)
end
end
end
end
end
@@ -59,7 +83,11 @@ class WatchersController < ApplicationController
@watched.set_watcher(User.find(params[:user_id]), false) if request.post?
respond_to do |format|
format.html { redirect_to :back }
format.js
format.js do
render :update do |page|
page.replace_html 'watchers', :partial => 'watchers/watchers', :locals => {:watched => @watched}
end
end
end
end
@@ -89,7 +117,12 @@ private
@watched.set_watcher(user, watching)
respond_to do |format|
format.html { redirect_to_referer_or {render :text => (watching ? 'Watcher added.' : 'Watcher removed.'), :layout => true}}
format.js { render :partial => 'set_watcher', :locals => {:user => user, :watched => @watched} }
format.js do
render(:update) do |page|
c = watcher_css(@watched)
page << %|$$(".#{c}").each(function(el){el.innerHTML="#{escape_javascript watcher_link(@watched, user)}"});|
end
end
end
end
end

View File

@@ -35,8 +35,7 @@ class WikiController < ApplicationController
default_search_scope :wiki_pages
before_filter :find_wiki, :authorize
before_filter :find_existing_or_new_page, :only => [:show, :edit, :update]
before_filter :find_existing_page, :only => [:rename, :protect, :history, :diff, :annotate, :add_attachment, :destroy, :destroy_version]
accept_api_auth :index, :show, :update, :destroy
before_filter :find_existing_page, :only => [:rename, :protect, :history, :diff, :annotate, :add_attachment, :destroy]
helper :attachments
include AttachmentsHelper
@@ -46,13 +45,7 @@ class WikiController < ApplicationController
# List of pages, sorted alphabetically and by parent (hierarchy)
def index
load_pages_for_index
respond_to do |format|
format.html {
@pages_by_parent_id = @pages.group_by(&:parent_id)
}
format.api
end
@pages_by_parent_id = @pages.group_by(&:parent_id)
end
# List of page, by last update
@@ -64,7 +57,7 @@ class WikiController < ApplicationController
# display a page (in editing mode if it doesn't exist)
def show
if @page.new_record?
if User.current.allowed_to?(:edit_wiki_pages, @project) && editable? && !api_request?
if User.current.allowed_to?(:edit_wiki_pages, @project) && editable?
edit
render :action => 'edit'
else
@@ -73,7 +66,8 @@ class WikiController < ApplicationController
return
end
if params[:version] && !User.current.allowed_to?(:view_wiki_edits, @project)
deny_access
# Redirects user to the current version if he's not allowed to view previous versions
redirect_to :version => nil
return
end
@content = @page.content_for_version(params[:version])
@@ -95,10 +89,7 @@ class WikiController < ApplicationController
@content.current_version? &&
Redmine::WikiFormatting.supports_section_edit?
respond_to do |format|
format.html
format.api
end
render :action => 'show'
end
# edit an existing page or a new one
@@ -118,7 +109,7 @@ class WikiController < ApplicationController
# To prevent StaleObjectError exception when reverting to a previous version
@content.version = @page.content.version
@text = @content.text
if params[:section].present? && Redmine::WikiFormatting.supports_section_edit?
@section = params[:section].to_i
@@ -130,65 +121,50 @@ class WikiController < ApplicationController
# Creates a new page or updates an existing one
def update
return render_403 unless editable?
was_new_page = @page.new_record?
@page.content = WikiContent.new(:page => @page) if @page.new_record?
@page.safe_attributes = params[:wiki_page]
@content = @page.content
content_params = params[:content]
if content_params.nil? && params[:wiki_page].is_a?(Hash)
content_params = params[:wiki_page].slice(:text, :comments, :version)
end
content_params ||= {}
@content = @page.content_for_version(params[:version])
@content.text = initial_page_content(@page) if @content.text.blank?
# don't keep previous comment
@content.comments = nil
@content.comments = content_params[:comments]
@text = content_params[:text]
if !@page.new_record? && params[:content].present? && @content.text == params[:content][:text]
attachments = Attachment.attach_files(@page, params[:attachments])
render_attachment_warning_if_needed(@page)
# don't save content if text wasn't changed
@page.save
redirect_to :action => 'show', :project_id => @project, :id => @page.title
return
end
@content.comments = params[:content][:comments]
@text = params[:content][:text]
if params[:section].present? && Redmine::WikiFormatting.supports_section_edit?
@section = params[:section].to_i
@section_hash = params[:section_hash]
@content.text = Redmine::WikiFormatting.formatter.new(@content.text).update_section(params[:section].to_i, @text, @section_hash)
else
@content.version = content_params[:version] if content_params[:version]
@content.version = params[:content][:version]
@content.text = @text
end
@content.author = User.current
if @page.save_with_content
@page.content = @content
if @page.save
attachments = Attachment.attach_files(@page, params[:attachments])
render_attachment_warning_if_needed(@page)
call_hook(:controller_wiki_edit_after_save, { :params => params, :page => @page})
respond_to do |format|
format.html { redirect_to :action => 'show', :project_id => @project, :id => @page.title }
format.api {
if was_new_page
render :action => 'show', :status => :created, :location => url_for(:controller => 'wiki', :action => 'show', :project_id => @project, :id => @page.title)
else
render_api_ok
end
}
end
redirect_to :action => 'show', :project_id => @project, :id => @page.title
else
respond_to do |format|
format.html { render :action => 'edit' }
format.api { render_validation_errors(@content) }
end
render :action => 'edit'
end
rescue ActiveRecord::StaleObjectError, Redmine::WikiFormatting::StaleSectionError
# Optimistic locking exception
respond_to do |format|
format.html {
flash.now[:error] = l(:notice_locking_conflict)
render :action => 'edit'
}
format.api { render_api_head :conflict }
end
flash.now[:error] = l(:notice_locking_conflict)
render :action => 'edit'
rescue ActiveRecord::RecordNotSaved
respond_to do |format|
format.html { render :action => 'edit' }
format.api { render_validation_errors(@content) }
end
render :action => 'edit'
end
# rename a page
@@ -211,7 +187,7 @@ class WikiController < ApplicationController
# show page history
def history
@version_count = @page.content.versions.count
@version_pages = Paginator.new self, @version_count, per_page_option, params['page']
@version_pages = Paginator.new self, @version_count, per_page_option, params['p']
# don't load text
@versions = @page.content.versions.find :all,
:select => "id, author_id, comments, updated_on, version",
@@ -254,28 +230,16 @@ class WikiController < ApplicationController
end
else
@reassignable_to = @wiki.pages - @page.self_and_descendants
# display the destroy form if it's a user request
return unless api_request?
return
end
end
@page.destroy
respond_to do |format|
format.html { redirect_to :action => 'index', :project_id => @project }
format.api { render_api_ok }
end
end
def destroy_version
return render_403 unless editable?
@content = @page.content_for_version(params[:version])
@content.destroy
redirect_to_referer_or :action => 'history', :id => @page.title, :project_id => @project
redirect_to :action => 'index', :project_id => @project
end
# Export wiki to a single pdf or html file
def export
@pages = @wiki.pages.all(:order => 'title', :include => [:content, {:attachments => :author}])
@pages = @wiki.pages.all(:order => 'title', :include => [:content, :attachments], :limit => 75)
respond_to do |format|
format.html {
export = render_to_string :action => 'export_multiple', :layout => false
@@ -349,6 +313,6 @@ private
end
def load_pages_for_index
@pages = @wiki.pages.with_updated_on.order("#{WikiPage.table_name}.title").includes(:wiki => :project).includes(:parent).all
@pages = @wiki.pages.with_updated_on.all(:order => 'title', :include => {:wiki => :project})
end
end

View File

@@ -24,6 +24,7 @@ class WikisController < ApplicationController
@wiki = @project.wiki || Wiki.new(:project => @project)
@wiki.safe_attributes = params[:wiki]
@wiki.save if request.post?
render(:update) {|page| page.replace_html "tab-content-wiki", :partial => 'projects/settings/wiki'}
end
# Delete a project's wiki

View File

@@ -18,27 +18,30 @@
class WorkflowsController < ApplicationController
layout 'admin'
before_filter :require_admin, :find_roles, :find_trackers
before_filter :require_admin
before_filter :find_roles
before_filter :find_trackers
def index
@workflow_counts = WorkflowTransition.count_by_tracker_and_role
@workflow_counts = Workflow.count_by_tracker_and_role
end
def edit
@role = Role.find_by_id(params[:role_id]) if params[:role_id]
@tracker = Tracker.find_by_id(params[:tracker_id]) if params[:tracker_id]
@role = Role.find_by_id(params[:role_id])
@tracker = Tracker.find_by_id(params[:tracker_id])
if request.post?
WorkflowTransition.destroy_all( ["role_id=? and tracker_id=?", @role.id, @tracker.id])
Workflow.destroy_all( ["role_id=? and tracker_id=?", @role.id, @tracker.id])
(params[:issue_status] || []).each { |status_id, transitions|
transitions.each { |new_status_id, options|
author = options.is_a?(Array) && options.include?('author') && !options.include?('always')
assignee = options.is_a?(Array) && options.include?('assignee') && !options.include?('always')
WorkflowTransition.create(:role_id => @role.id, :tracker_id => @tracker.id, :old_status_id => status_id, :new_status_id => new_status_id, :author => author, :assignee => assignee)
@role.workflows.build(:tracker_id => @tracker.id, :old_status_id => status_id, :new_status_id => new_status_id, :author => author, :assignee => assignee)
}
}
if @role.save
redirect_to :action => 'edit', :role_id => @role, :tracker_id => @tracker, :used_statuses_only => params[:used_statuses_only]
flash[:notice] = l(:notice_successful_update)
redirect_to :action => 'edit', :role_id => @role, :tracker_id => @tracker
return
end
end
@@ -47,10 +50,10 @@ class WorkflowsController < ApplicationController
if @tracker && @used_statuses_only && @tracker.issue_statuses.any?
@statuses = @tracker.issue_statuses
end
@statuses ||= IssueStatus.sorted.all
@statuses ||= IssueStatus.find(:all, :order => 'position')
if @tracker && @role && @statuses.any?
workflows = WorkflowTransition.where(:role_id => @role.id, :tracker_id => @tracker.id).all
workflows = Workflow.all(:conditions => {:role_id => @role.id, :tracker_id => @tracker.id})
@workflows = {}
@workflows['always'] = workflows.select {|w| !w.author && !w.assignee}
@workflows['author'] = workflows.select {|w| w.author}
@@ -58,35 +61,6 @@ class WorkflowsController < ApplicationController
end
end
def permissions
@role = Role.find_by_id(params[:role_id]) if params[:role_id]
@tracker = Tracker.find_by_id(params[:tracker_id]) if params[:tracker_id]
if request.post? && @role && @tracker
WorkflowPermission.replace_permissions(@tracker, @role, params[:permissions] || {})
redirect_to :action => 'permissions', :role_id => @role, :tracker_id => @tracker, :used_statuses_only => params[:used_statuses_only]
return
end
@used_statuses_only = (params[:used_statuses_only] == '0' ? false : true)
if @tracker && @used_statuses_only && @tracker.issue_statuses.any?
@statuses = @tracker.issue_statuses
end
@statuses ||= IssueStatus.sorted.all
if @role && @tracker
@fields = (Tracker::CORE_FIELDS_ALL - @tracker.disabled_core_fields).map {|field| [field, l("field_"+field.sub(/_id$/, ''))]}
@custom_fields = @tracker.custom_fields
@permissions = WorkflowPermission.where(:tracker_id => @tracker.id, :role_id => @role.id).all.inject({}) do |h, w|
h[w.old_status_id] ||= {}
h[w.old_status_id][w.field_name] = w.rule
h
end
@statuses.each {|status| @permissions[status.id] ||= {}}
end
end
def copy
if params[:source_tracker_id].blank? || params[:source_tracker_id] == 'any'
@@ -109,7 +83,7 @@ class WorkflowsController < ApplicationController
elsif @target_trackers.nil? || @target_roles.nil?
flash.now[:error] = l(:error_workflow_copy_target)
else
WorkflowRule.copy(@source_tracker, @source_role, @target_trackers, @target_roles)
Workflow.copy(@source_tracker, @source_role, @target_trackers, @target_roles)
flash[:notice] = l(:notice_successful_update)
redirect_to :action => 'copy', :source_tracker_id => @source_tracker, :source_role_id => @source_role
end
@@ -119,10 +93,10 @@ class WorkflowsController < ApplicationController
private
def find_roles
@roles = Role.sorted.all
@roles = Role.find(:all, :order => 'builtin, position')
end
def find_trackers
@trackers = Tracker.sorted.all
@trackers = Tracker.find(:all, :order => 'position')
end
end

View File

@@ -20,8 +20,6 @@
module AdminHelper
def project_status_options_for_select(selected)
options_for_select([[l(:label_all), ''],
[l(:project_status_active), '1'],
[l(:project_status_closed), '5'],
[l(:project_status_archived), '9']], selected.to_s)
[l(:status_active), '1']], selected.to_s)
end
end

View File

@@ -43,12 +43,18 @@ module ApplicationHelper
link_to(name, options, html_options, *parameters_for_method_reference) if authorize_for(options[:controller] || params[:controller], options[:action])
end
# Display a link to remote if user is authorized
def link_to_remote_if_authorized(name, options = {}, html_options = nil)
url = options[:url] || {}
link_to_remote(name, options, html_options) if authorize_for(url[:controller] || params[:controller], url[:action])
end
# Displays a link to user's account page if active
def link_to_user(user, options={})
if user.is_a?(User)
name = h(user.name(options[:format]))
if user.active? || (User.current.admin? && user.logged?)
link_to name, user_path(user), :class => user.css_classes
if user.active?
link_to name, :controller => 'users', :action => 'show', :id => user
else
name
end
@@ -64,12 +70,10 @@ module ApplicationHelper
# link_to_issue(issue, :truncate => 6) # => Defect #6: This i...
# link_to_issue(issue, :subject => false) # => Defect #6
# link_to_issue(issue, :project => true) # => Foo - Defect #6
# link_to_issue(issue, :subject => false, :tracker => false) # => #6
#
def link_to_issue(issue, options={})
title = nil
subject = nil
text = options[:tracker] == false ? "##{issue.id}" : "#{issue.tracker} ##{issue.id}"
if options[:subject] == false
title = truncate(issue.subject, :length => 60)
else
@@ -78,7 +82,9 @@ module ApplicationHelper
subject = truncate(subject, :length => options[:truncate])
end
end
s = link_to text, issue_path(issue), :class => issue.css_classes, :title => title
s = link_to "#{h(issue.tracker)} ##{issue.id}", {:controller => "issues", :action => "show", :id => issue},
:class => issue.css_classes,
:title => title
s << h(": #{subject}") if subject
s = h("#{issue.project} - ") + s if options[:project]
s
@@ -122,7 +128,7 @@ module ApplicationHelper
h(truncate(message.subject, :length => 60)),
{ :controller => 'messages', :action => 'show',
:board_id => message.board_id,
:id => (message.parent_id || message.id),
:id => message.root,
:r => (message.parent_id && message.id),
:anchor => (message.parent_id ? "message-#{message.id}" : nil)
}.merge(options),
@@ -139,27 +145,17 @@ module ApplicationHelper
# link_to_project(project, {}, :class => "project") # => html options with default url (project overview)
#
def link_to_project(project, options={}, html_options = nil)
if project.archived?
h(project)
else
if project.active?
url = {:controller => 'projects', :action => 'show', :id => project}.merge(options)
link_to(h(project), url, html_options)
else
h(project)
end
end
def wiki_page_path(page, options={})
url_for({:controller => 'wiki', :action => 'show', :project_id => page.project, :id => page.title}.merge(options))
end
def thumbnail_tag(attachment)
link_to image_tag(url_for(:controller => 'attachments', :action => 'thumbnail', :id => attachment)),
{:controller => 'attachments', :action => 'show', :id => attachment, :filename => attachment.filename},
:title => attachment.filename
end
def toggle_link(name, id, options={})
onclick = "$('##{id}').toggle(); "
onclick << (options[:focus] ? "$('##{options[:focus]}').focus(); " : "this.blur(); ")
onclick = "Element.toggle('#{id}'); "
onclick << (options[:focus] ? "Form.Element.focus('#{options[:focus]}'); " : "this.blur(); ")
onclick << "return false;"
link_to(name, "#", :onclick => onclick)
end
@@ -172,6 +168,11 @@ module ApplicationHelper
}))
end
def prompt_to_remote(name, text, param, url, html_options = {})
html_options[:onclick] = "promptToRemote('#{text}', '#{param}', '#{url_for(url)}'); return false;"
link_to name, {}, html_options
end
def format_activity_title(text)
h(truncate_single_line(text, :length => 100))
end
@@ -199,46 +200,13 @@ module ApplicationHelper
end
end
# Renders a tree of projects as a nested set of unordered lists
# The given collection may be a subset of the whole project tree
# (eg. some intermediate nodes are private and can not be seen)
def render_project_nested_lists(projects)
s = ''
if projects.any?
ancestors = []
original_project = @project
projects.sort_by(&:lft).each do |project|
# set the project environment to please macros.
@project = project
if (ancestors.empty? || project.is_descendant_of?(ancestors.last))
s << "<ul class='projects #{ ancestors.empty? ? 'root' : nil}'>\n"
else
ancestors.pop
s << "</li>"
while (ancestors.any? && !project.is_descendant_of?(ancestors.last))
ancestors.pop
s << "</ul></li>\n"
end
end
classes = (ancestors.empty? ? 'root' : 'child')
s << "<li class='#{classes}'><div class='#{classes}'>"
s << h(block_given? ? yield(project) : project.name)
s << "</div>\n"
ancestors << project
end
s << ("</li></ul>\n" * ancestors.size)
@project = original_project
end
s.html_safe
end
def render_page_hierarchy(pages, node=nil, options={})
content = ''
if pages[node]
content << "<ul class=\"pages-hierarchy\">\n"
pages[node].each do |page|
content << "<li>"
content << link_to(h(page.pretty_title), {:controller => 'wiki', :action => 'show', :project_id => page.project, :id => page.title, :version => nil},
content << link_to(h(page.pretty_title), {:controller => 'wiki', :action => 'show', :project_id => page.project, :id => page.title},
:title => (options[:timestamp] && page.updated_on ? l(:label_updated_time, distance_of_time_in_words(Time.now, page.updated_on)) : nil))
content << "\n" + render_page_hierarchy(pages, page.id, options) if pages[page.id]
content << "</li>\n"
@@ -269,24 +237,23 @@ module ApplicationHelper
# Renders the project quick-jump box
def render_project_jump_box
return unless User.current.logged?
projects = User.current.memberships.collect(&:project).compact.select(&:active?).uniq
projects = User.current.memberships.collect(&:project).compact.uniq
if projects.any?
options =
("<option value=''>#{ l(:label_jump_to_a_project) }</option>" +
'<option value="" disabled="disabled">---</option>').html_safe
options << project_tree_options_for_select(projects, :selected => @project) do |p|
{ :value => project_path(:id => p, :jump => current_menu_item) }
s = '<select onchange="if (this.value != \'\') { window.location = this.value; }">' +
"<option value=''>#{ l(:label_jump_to_a_project) }</option>" +
'<option value="" disabled="disabled">---</option>'
s << project_tree_options_for_select(projects, :selected => @project) do |p|
{ :value => url_for(:controller => 'projects', :action => 'show', :id => p, :jump => current_menu_item) }
end
select_tag('project_quick_jump_box', options, :onchange => 'if (this.value != \'\') { window.location = this.value; }')
s << '</select>'
s.html_safe
end
end
def project_tree_options_for_select(projects, options = {})
s = ''
project_tree(projects) do |project, level|
name_prefix = (level > 0 ? '&nbsp;' * 2 * level + '&#187; ' : '').html_safe
name_prefix = (level > 0 ? ('&nbsp;' * 2 * level + '&#187; ').html_safe : '')
tag_options = {:value => project.id}
if project == options[:selected] || (options[:selected].respond_to?(:include?) && options[:selected].include?(project))
tag_options[:selected] = 'selected'
@@ -306,6 +273,30 @@ module ApplicationHelper
Project.project_tree(projects, &block)
end
def project_nested_ul(projects, &block)
s = ''
if projects.any?
ancestors = []
projects.sort_by(&:lft).each do |project|
if (ancestors.empty? || project.is_descendant_of?(ancestors.last))
s << "<ul>\n"
else
ancestors.pop
s << "</li>"
while (ancestors.any? && !project.is_descendant_of?(ancestors.last))
ancestors.pop
s << "</ul></li>\n"
end
end
s << "<li>"
s << yield(project).to_s
ancestors << project
end
s << ("</li></ul>\n" * ancestors.size)
end
s.html_safe
end
def principals_check_box_tags(name, principals)
s = ''
principals.sort.each do |principal|
@@ -318,7 +309,7 @@ module ApplicationHelper
def principals_options_for_select(collection, selected=nil)
s = ''
if collection.include?(User.current)
s << content_tag('option', "<< #{l(:label_me)} >>", :value => User.current.id)
s << content_tag('option', "<< #{l(:label_me)} >>".html_safe, :value => User.current.id)
end
groups = ''
collection.sort.each do |element|
@@ -331,15 +322,6 @@ module ApplicationHelper
s.html_safe
end
# Options for the new membership projects combo-box
def options_for_membership_project_select(principal, projects)
options = content_tag('option', "--- #{l(:actionview_instancetag_blank_option)} ---")
options << project_tree_options_for_select(projects) do |p|
{:disabled => principal.projects.include?(p)}
end
options
end
# Truncates and returns the string as a single line
def truncate_single_line(string, *args)
truncate(string.to_s, *args).gsub(%r{[\r\n]+}m, ' ')
@@ -540,8 +522,6 @@ module ApplicationHelper
project = options[:project] || @project || (obj && obj.respond_to?(:project) ? obj.project : nil)
only_path = options.delete(:only_path) == false ? false : true
text = text.dup
macros = catch_macros(text)
text = Redmine::WikiFormatting.to_html(Setting.text_formatting, text, :object => obj, :attribute => attr)
@parsed_headings = []
@@ -549,8 +529,8 @@ module ApplicationHelper
@current_section = 0 if options[:edit_section_links]
parse_sections(text, project, obj, attr, only_path, options)
text = parse_non_pre_blocks(text, obj, macros) do |text|
[:parse_inline_attachments, :parse_wiki_links, :parse_redmine_links].each do |method_name|
text = parse_non_pre_blocks(text) do |text|
[:parse_inline_attachments, :parse_wiki_links, :parse_redmine_links, :parse_macros].each do |method_name|
send method_name, text, project, obj, attr, only_path, options
end
end
@@ -563,7 +543,7 @@ module ApplicationHelper
text.html_safe
end
def parse_non_pre_blocks(text, obj, macros)
def parse_non_pre_blocks(text)
s = StringScanner.new(text)
tags = []
parsed = ''
@@ -572,9 +552,6 @@ module ApplicationHelper
text, full_tag, closing, tag = s[1], s[2], s[3], s[4]
if tags.empty?
yield text
inject_macros(text, obj, macros) if macros.any?
else
inject_macros(text, obj, macros, false) if macros.any?
end
parsed << text
if tag
@@ -597,9 +574,8 @@ module ApplicationHelper
def parse_inline_attachments(text, project, obj, attr, only_path, options)
# when using an image link, try to use an attachment, if possible
attachments = options[:attachments] || []
attachments += obj.attachments if obj.respond_to?(:attachments)
if attachments.present?
if options[:attachments] || (obj && obj.respond_to?(:attachments))
attachments = options[:attachments] || obj.attachments
text.gsub!(/src="([^\/"]+\.(bmp|gif|jpg|jpe|jpeg|png))"(\s+alt="([^"]*)")?/i) do |m|
filename, ext, alt, alttext = $1.downcase, $2, $3, $4
# search for the picture in attachments
@@ -658,7 +634,7 @@ module ApplicationHelper
wiki_page_id = page.present? ? Wiki.titleize(page) : nil
parent = wiki_page.nil? && obj.is_a?(WikiContent) && obj.page && project == link_project ? obj.page.title : nil
url_for(:only_path => only_path, :controller => 'wiki', :action => 'show', :project_id => link_project,
:id => wiki_page_id, :version => nil, :anchor => anchor, :parent => parent)
:id => wiki_page_id, :anchor => anchor, :parent => parent)
end
end
link_to(title.present? ? title.html_safe : h(page), url, :class => ('wiki-page' + (wiki_page ? '' : ' new')))
@@ -704,11 +680,10 @@ module ApplicationHelper
# identifier:document:"Some document"
# identifier:version:1.0.0
# identifier:source:some/file
def parse_redmine_links(text, default_project, obj, attr, only_path, options)
text.gsub!(%r{([\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|
def parse_redmine_links(text, project, obj, attr, only_path, options)
text.gsub!(%r{([\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|
leading, esc, project_prefix, project_identifier, prefix, repo_prefix, repo_identifier, sep, identifier, comment_suffix, comment_id = $1, $2, $3, $4, $5, $10, $11, $8 || $12 || $18, $14 || $19, $15, $17
link = nil
project = default_project
if project_identifier
project = Project.visible.find_by_identifier(project_identifier)
end
@@ -732,7 +707,7 @@ module ApplicationHelper
oid = identifier.to_i
case prefix
when nil
if oid.to_s == identifier && issue = Issue.visible.find_by_id(oid, :include => :status)
if issue = Issue.visible.find_by_id(oid, :include => :status)
anchor = comment_id ? "note-#{comment_id}" : nil
link = link_to("##{oid}", {:only_path => only_path, :controller => 'issues', :action => 'show', :id => oid, :anchor => anchor},
:class => issue.css_classes,
@@ -794,7 +769,7 @@ module ApplicationHelper
when 'commit', 'source', 'export'
if project
repository = nil
if name =~ %r{^(([a-z0-9\-_]+)\|)(.+)$}
if name =~ %r{^(([a-z0-9\-]+)\|)(.+)$}
repo_prefix, repo_identifier, name = $1, $2, $3
repository = project.repositories.detect {|repo| repo.identifier == repo_identifier}
else
@@ -810,10 +785,11 @@ module ApplicationHelper
if repository && User.current.allowed_to?(:browse_repository, project)
name =~ %r{^[/\\]*(.*?)(@([0-9a-f]+))?(#(L\d+))?$}
path, rev, anchor = $1, $3, $5
link = link_to h("#{project_prefix}#{prefix}:#{repo_prefix}#{name}"), {:controller => 'repositories', :action => (prefix == 'export' ? 'raw' : 'entry'), :id => project, :repository_id => repository.identifier_param,
link = link_to h("#{project_prefix}#{prefix}:#{repo_prefix}#{name}"), {:controller => 'repositories', :action => 'entry', :id => project, :repository_id => repository.identifier_param,
:path => to_path_param(path),
:rev => rev,
:anchor => anchor},
:anchor => anchor,
:format => (prefix == 'export' ? 'raw' : nil)},
:class => (prefix == 'export' ? 'source download' : 'source')
end
end
@@ -821,7 +797,7 @@ module ApplicationHelper
end
when 'attachment'
attachments = options[:attachments] || (obj && obj.respond_to?(:attachments) ? obj.attachments : nil)
if attachments && attachment = Attachment.latest_attach(attachments, name)
if attachments && attachment = attachments.detect {|a| a.filename == name }
link = link_to h(attachment.filename), {:only_path => only_path, :controller => 'attachments', :action => 'download', :id => attachment},
:class => 'attachment'
end
@@ -836,7 +812,7 @@ module ApplicationHelper
end
end
HEADING_RE = /(<h(\d)( [^>]+)?>(.+?)<\/h(\d)>)/i unless const_defined?(:HEADING_RE)
HEADING_RE = /(<h(1|2|3|4)( [^>]+)?>(.+?)<\/h(1|2|3|4)>)/i unless const_defined?(:HEADING_RE)
def parse_sections(text, project, obj, attr, only_path, options)
return unless options[:edit_section_links]
@@ -875,57 +851,31 @@ module ApplicationHelper
end
end
MACROS_RE = /(
MACROS_RE = /
(!)? # escaping
(
\{\{ # opening tag
([\w]+) # macro name
(\(([^\n\r]*?)\))? # optional arguments
([\n\r].*?[\n\r])? # optional block of text
(\(([^\}]*)\))? # optional arguments
\}\} # closing tag
)
)/mx unless const_defined?(:MACROS_RE)
/x unless const_defined?(:MACROS_RE)
MACRO_SUB_RE = /(
\{\{
macro\((\d+)\)
\}\}
)/x unless const_defined?(:MACRO_SUB_RE)
# Extracts macros from text
def catch_macros(text)
macros = {}
# Macros substitution
def parse_macros(text, project, obj, attr, only_path, options)
text.gsub!(MACROS_RE) do
all, macro = $1, $4.downcase
if macro_exists?(macro) || all =~ MACRO_SUB_RE
index = macros.size
macros[index] = all
"{{macro(#{index})}}"
esc, all, macro = $1, $2, $3.downcase
args = ($5 || '').split(',').each(&:strip)
if esc.nil?
begin
exec_macro(macro, obj, args)
rescue => e
"<div class=\"flash error\">Error executing the <strong>#{macro}</strong> macro (#{e})</div>"
end || all
else
all
end
end
macros
end
# Executes and replaces macros in text
def inject_macros(text, obj, macros, execute=true)
text.gsub!(MACRO_SUB_RE) do
all, index = $1, $2.to_i
orig = macros.delete(index)
if execute && orig && orig =~ MACROS_RE
esc, all, macro, args, block = $2, $3, $4.downcase, $6.to_s, $7.try(:strip)
if esc.nil?
h(exec_macro(macro, obj, args, block) || all)
else
h(all)
end
elsif orig
h(orig)
else
h(all)
end
end
end
TOC_RE = /<p>\{\{([<>]?)toc\}\}<\/p>/i unless const_defined?(:TOC_RE)
@@ -933,8 +883,6 @@ module ApplicationHelper
# Renders the TOC with given headings
def replace_toc(text, headings)
text.gsub!(TOC_RE) do
# Keep only the 4 first levels
headings = headings.select{|level, anchor, item| level <= 4}
if headings.empty?
''
else
@@ -973,7 +921,8 @@ module ApplicationHelper
end
def lang_options_for_select(blank=true)
(blank ? [["(auto)", ""]] : []) + languages_options
(blank ? [["(auto)", ""]] : []) +
valid_languages.collect{|lang| [ ll(lang.to_s, :general_lang_name), lang.to_s]}.sort{|x,y| x.last <=> y.last }
end
def label_tag_for(name, option_tags = nil, options = {})
@@ -981,6 +930,16 @@ module ApplicationHelper
content_tag("label", label_text)
end
def labelled_tabular_form_for(*args, &proc)
ActiveSupport::Deprecation.warn "ApplicationHelper#labelled_tabular_form_for is deprecated and will be removed in Redmine 1.5. Use #labelled_form_for instead."
args << {} unless args.last.is_a?(Hash)
options = args.last
options[:html] ||= {}
options[:html][:class] = 'tabular' unless options[:html].has_key?(:class)
options.merge!({:builder => Redmine::Views::LabelledFormBuilder})
form_for(*args, &proc)
end
def labelled_form_for(*args, &proc)
args << {} unless args.last.is_a?(Hash)
options = args.last
@@ -999,7 +958,6 @@ module ApplicationHelper
end
def labelled_remote_form_for(*args, &proc)
ActiveSupport::Deprecation.warn "ApplicationHelper#labelled_remote_form_for is deprecated and will be removed in Redmine 2.2."
args << {} unless args.last.is_a?(Hash)
options = args.last
options.merge!({:builder => Redmine::Views::LabelledFormBuilder, :remote => true})
@@ -1020,44 +978,10 @@ module ApplicationHelper
html.html_safe
end
def delete_link(url, options={})
options = {
:method => :delete,
:data => {:confirm => l(:text_are_you_sure)},
:class => 'icon icon-del'
}.merge(options)
link_to l(:button_delete), url, options
end
def preview_link(url, form, target='preview', options={})
content_tag 'a', l(:label_preview), {
:href => "#",
:onclick => %|submitPreview("#{escape_javascript url_for(url)}", "#{escape_javascript form}", "#{escape_javascript target}"); return false;|,
:accesskey => accesskey(:preview)
}.merge(options)
end
def link_to_function(name, function, html_options={})
content_tag(:a, name, {:href => '#', :onclick => "#{function}; return false;"}.merge(html_options))
end
# Helper to render JSON in views
def raw_json(arg)
arg.to_json.to_s.gsub('/', '\/').html_safe
end
def back_url
url = params[:back_url]
if url.nil? && referer = request.env['HTTP_REFERER']
url = CGI.unescape(referer.to_s)
end
url
end
def back_url_hidden_field_tag
url = back_url
hidden_field_tag('back_url', url, :id => nil) unless url.blank?
back_url = params[:back_url] || request.env['HTTP_REFERER']
back_url = CGI.unescape(back_url.to_s)
hidden_field_tag('back_url', CGI.escape(back_url), :id => nil) unless back_url.blank?
end
def check_all_links(form_name)
@@ -1101,34 +1025,35 @@ module ApplicationHelper
end
@context_menu_included = true
end
javascript_tag "contextMenuInit('#{ url_for(url) }')"
javascript_tag "new ContextMenu('#{ url_for(url) }')"
end
def calendar_for(field_id)
include_calendar_headers_tags
javascript_tag("$(function() { $('##{field_id}').datepicker(datepickerOptions); });")
image_tag("calendar.png", {:id => "#{field_id}_trigger",:class => "calendar-trigger"}) +
javascript_tag("Calendar.setup({inputField : '#{field_id}', ifFormat : '%Y-%m-%d', button : '#{field_id}_trigger' });")
end
def include_calendar_headers_tags
unless @calendar_headers_tags_included
@calendar_headers_tags_included = true
content_for :header_tags do
start_of_week = Setting.start_of_week
start_of_week = l(:general_first_day_of_week, :default => '1') if start_of_week.blank?
# Redmine uses 1..7 (monday..sunday) in settings and locales
# JQuery uses 0..6 (sunday..saturday), 7 needs to be changed to 0
start_of_week = start_of_week.to_i % 7
tags = javascript_tag(
"var datepickerOptions={dateFormat: 'yy-mm-dd', firstDay: #{start_of_week}, " +
"showOn: 'button', buttonImageOnly: true, buttonImage: '" +
path_to_image('/images/calendar.png') +
"', showButtonPanel: true};")
jquery_locale = l('jquery.locale', :default => current_language.to_s)
unless jquery_locale == 'en'
tags << javascript_include_tag("i18n/jquery.ui.datepicker-#{jquery_locale}.js")
start_of_week = case Setting.start_of_week.to_i
when 1
'Calendar._FD = 1;' # Monday
when 7
'Calendar._FD = 0;' # Sunday
when 6
'Calendar._FD = 6;' # Saturday
else
'' # use language
end
tags
javascript_include_tag('calendar/calendar') +
javascript_include_tag("calendar/lang/calendar-#{current_language.to_s.downcase}.js") +
javascript_tag(start_of_week) +
javascript_include_tag('calendar/calendar-setup') +
stylesheet_link_tag('calendar')
end
end
end
@@ -1226,19 +1151,14 @@ module ApplicationHelper
end
def sanitize_anchor_name(anchor)
if ''.respond_to?(:encoding) || RUBY_PLATFORM == 'java'
anchor.gsub(%r{[^\p{Word}\s\-]}, '').gsub(%r{\s+(\-+\s*)?}, '-')
else
# TODO: remove when ruby1.8 is no longer supported
anchor.gsub(%r{[^\w\s\-]}, '').gsub(%r{\s+(\-+\s*)?}, '-')
end
anchor.gsub(%r{[^\w\s\-]}, '').gsub(%r{\s+(\-+\s*)?}, '-')
end
# Returns the javascript tags that are included in the html layout head
def javascript_heads
tags = javascript_include_tag('jquery-1.7.2-ui-1.8.21-ujs-2.0.3', 'application')
tags = javascript_include_tag('prototype', 'effects', 'dragdrop', 'controls', 'rails', 'application')
unless User.current.pref.warn_on_leaving_unsaved == '0'
tags << "\n".html_safe + javascript_tag("$(window).load(function(){ warnLeavingUnsaved('#{escape_javascript l(:text_warn_on_leaving_unsaved)}'); });")
tags << "\n".html_safe + javascript_tag("Event.observe(window, 'load', function(){ new WarnLeavingUnsaved('#{escape_javascript( l(:text_warn_on_leaving_unsaved) )}'); });")
end
tags
end

View File

@@ -21,14 +21,12 @@ module AttachmentsHelper
# Displays view/delete links to the attachments of the given object
# Options:
# :author -- author names are not displayed if set to false
# :thumbails -- display thumbnails if enabled in settings
def link_to_attachments(container, options = {})
options.assert_valid_keys(:author, :thumbnails)
options.assert_valid_keys(:author)
if container.attachments.any?
options = {:deletable => container.attachments_deletable?, :author => true}.merge(options)
render :partial => 'attachments/links',
:locals => {:attachments => container.attachments, :options => options, :thumbnails => (options[:thumbnails] && Setting.thumbnails_enabled?)}
render :partial => 'attachments/links', :locals => {:attachments => container.attachments, :options => options}
end
end

View File

@@ -18,24 +18,4 @@
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
module BoardsHelper
def board_breadcrumb(item)
board = item.is_a?(Message) ? item.board : item
links = [link_to(l(:label_board_plural), project_boards_path(item.project))]
boards = board.ancestors.reverse
if item.is_a?(Message)
boards << board
end
links += boards.map {|ancestor| link_to(h(ancestor.name), project_board_path(ancestor.project, ancestor))}
breadcrumb links
end
def boards_options_for_select(boards)
options = []
Board.board_tree(boards) do |board, level|
label = (level > 0 ? '&nbsp;' * 2 * level + '&#187; ' : '').html_safe
label << board.name
options << [label, board.id]
end
options
end
end

View File

@@ -26,8 +26,8 @@ module ContextMenusHelper
end
if options.delete(:disabled)
options.delete(:method)
options.delete(:data)
options[:onclick] = 'return false;'
options.delete(:confirm)
options.delete(:onclick)
options[:class] << ' disabled'
url = '#'
end
@@ -36,7 +36,7 @@ module ContextMenusHelper
def bulk_update_custom_field_context_menu_link(field, text, value)
context_menu_link h(text),
{:controller => 'issues', :action => 'bulk_update', :ids => @issue_ids, :issue => {'custom_field_values' => {field.id => value}}, :back_url => @back},
{:controller => 'issues', :action => 'bulk_update', :ids => @issues.collect(&:id), :issue => {'custom_field_values' => {field.id => value}}, :back_url => @back},
:method => :post,
:selected => (@issue && @issue.custom_field_value(field) == value)
end

View File

@@ -20,7 +20,16 @@
module CustomFieldsHelper
def custom_fields_tabs
CustomField::CUSTOM_FIELDS_TABS
tabs = [{:name => 'IssueCustomField', :partial => 'custom_fields/index', :label => :label_issue_plural},
{:name => 'TimeEntryCustomField', :partial => 'custom_fields/index', :label => :label_spent_time},
{:name => 'ProjectCustomField', :partial => 'custom_fields/index', :label => :label_project_plural},
{:name => 'VersionCustomField', :partial => 'custom_fields/index', :label => :label_version_plural},
{:name => 'UserCustomField', :partial => 'custom_fields/index', :label => :label_user_plural},
{:name => 'GroupCustomField', :partial => 'custom_fields/index', :label => :label_group_plural},
{:name => 'TimeEntryActivityCustomField', :partial => 'custom_fields/index', :label => TimeEntryActivity::OptionName},
{:name => 'IssuePriorityCustomField', :partial => 'custom_fields/index', :label => IssuePriority::OptionName},
{:name => 'DocumentCategoryCustomField', :partial => 'custom_fields/index', :label => DocumentCategory::OptionName}
]
end
# Return custom field html tag corresponding to its format
@@ -64,17 +73,15 @@ module CustomFieldsHelper
end
# Return custom field label tag
def custom_field_label_tag(name, custom_value, options={})
required = options[:required] || custom_value.custom_field.is_required?
def custom_field_label_tag(name, custom_value)
content_tag "label", h(custom_value.custom_field.name) +
(required ? " <span class=\"required\">*</span>".html_safe : ""),
:for => "#{name}_custom_field_values_#{custom_value.custom_field.id}"
(custom_value.custom_field.is_required? ? " <span class=\"required\">*</span>".html_safe : ""),
:for => "#{name}_custom_field_values_#{custom_value.custom_field.id}"
end
# Return custom field tag with its label tag
def custom_field_tag_with_label(name, custom_value, options={})
custom_field_label_tag(name, custom_value, options) + custom_field_tag(name, custom_value)
def custom_field_tag_with_label(name, custom_value)
custom_field_label_tag(name, custom_value) + custom_field_tag(name, custom_value)
end
def custom_field_tag_for_bulk_edit(name, custom_field, projects=nil)

View File

@@ -18,6 +18,15 @@
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
module GroupsHelper
# Options for the new membership projects combo-box
def options_for_membership_project_select(user, projects)
options = content_tag('option', "--- #{l(:actionview_instancetag_blank_option)} ---")
options << project_tree_options_for_select(projects) do |p|
{:disabled => (user.projects.include?(p))}
end
options
end
def group_settings_tabs
tabs = [{:name => 'general', :partial => 'groups/general', :label => :label_general},
{:name => 'users', :partial => 'groups/users', :label => :label_user_plural},

View File

@@ -65,7 +65,7 @@ module IssuesHelper
s = ''
ancestors = issue.root? ? [] : issue.ancestors.visible.all
ancestors.each do |ancestor|
s << '<div>' + content_tag('p', link_to_issue(ancestor, :project => (issue.project_id != ancestor.project_id)))
s << '<div>' + content_tag('p', link_to_issue(ancestor))
end
s << '<div>'
subject = h(issue.subject)
@@ -80,71 +80,18 @@ module IssuesHelper
def render_descendants_tree(issue)
s = '<form><table class="list issues">'
issue_list(issue.descendants.visible.sort_by(&:lft)) do |child, level|
css = "issue issue-#{child.id} hascontextmenu"
css << " idnt idnt-#{level}" if level > 0
s << content_tag('tr',
content_tag('td', check_box_tag("ids[]", child.id, false, :id => nil), :class => 'checkbox') +
content_tag('td', link_to_issue(child, :truncate => 60, :project => (issue.project_id != child.project_id)), :class => 'subject') +
content_tag('td', link_to_issue(child, :truncate => 60), :class => 'subject') +
content_tag('td', h(child.status)) +
content_tag('td', link_to_user(child.assigned_to)) +
content_tag('td', progress_bar(child.done_ratio, :width => '80px')),
:class => css)
:class => "issue issue-#{child.id} hascontextmenu #{level > 0 ? "idnt idnt-#{level}" : nil}")
end
s << '</table></form>'
s.html_safe
end
# Returns a link for adding a new subtask to the given issue
def link_to_new_subtask(issue)
attrs = {
:tracker_id => issue.tracker,
:parent_issue_id => issue
}
link_to(l(:button_add), new_project_issue_path(issue.project, :issue => attrs))
end
class IssueFieldsRows
include ActionView::Helpers::TagHelper
def initialize
@left = []
@right = []
end
def left(*args)
args.any? ? @left << cells(*args) : @left
end
def right(*args)
args.any? ? @right << cells(*args) : @right
end
def size
@left.size > @right.size ? @left.size : @right.size
end
def to_html
html = ''.html_safe
blank = content_tag('th', '') + content_tag('td', '')
size.times do |i|
left = @left[i] || blank
right = @right[i] || blank
html << content_tag('tr', left + right)
end
html
end
def cells(label, text, options={})
content_tag('th', "#{label}:", options) + content_tag('td', text, options)
end
end
def issue_fields_rows
r = IssueFieldsRows.new
yield r
r.to_html
end
def render_custom_fields_rows(issue)
return if issue.custom_field_values.empty?
ordered_values = []
@@ -301,7 +248,7 @@ module IssuesHelper
unless no_html
label = content_tag('strong', label)
old_value = content_tag("i", h(old_value)) if detail.old_value
old_value = content_tag("del", old_value) if detail.old_value and detail.value.blank?
old_value = content_tag("strike", old_value) if detail.old_value and detail.value.blank?
if detail.property == 'attachment' && !value.blank? && atta = Attachment.find_by_id(detail.prop_key)
# Link to the attachment if it has not been removed
value = link_to_attachment(atta, :download => true, :only_path => options[:only_path])
@@ -371,16 +318,12 @@ module IssuesHelper
def issues_to_csv(issues, project, query, options={})
decimal_separator = l(:general_csv_decimal_separator)
encoding = l(:general_csv_encoding)
columns = (options[:columns] == 'all' ? query.available_inline_columns : query.inline_columns)
if options[:description]
if description = query.available_columns.detect {|q| q.name == :description}
columns << description
end
end
columns = (options[:columns] == 'all' ? query.available_columns : query.columns)
export = FCSV.generate(:col_sep => l(:general_csv_separator)) do |csv|
# csv header fields
csv << [ "#" ] + columns.collect {|c| Redmine::CodesetUtil.from_utf8(c.caption.to_s, encoding) }
csv << [ "#" ] + columns.collect {|c| Redmine::CodesetUtil.from_utf8(c.caption.to_s, encoding) } +
(options[:description] ? [Redmine::CodesetUtil.from_utf8(l(:field_description), encoding)] : [])
# csv lines
issues.each do |issue|
@@ -402,7 +345,8 @@ module IssuesHelper
end
s.to_s
end
csv << [ issue.id.to_s ] + col_values.collect {|c| Redmine::CodesetUtil.from_utf8(c.to_s, encoding) }
csv << [ issue.id.to_s ] + col_values.collect {|c| Redmine::CodesetUtil.from_utf8(c.to_s, encoding) } +
(options[:description] ? [Redmine::CodesetUtil.from_utf8(issue.description, encoding)] : [])
end
end
export

View File

@@ -23,13 +23,11 @@ module JournalsHelper
editable = User.current.logged? && (User.current.allowed_to?(:edit_issue_notes, issue.project) || (journal.user == User.current && User.current.allowed_to?(:edit_own_issue_notes, issue.project)))
links = []
if !journal.notes.blank?
links << link_to(image_tag('comment.png'),
{:controller => 'journals', :action => 'new', :id => issue, :journal_id => journal},
:remote => true,
:method => 'post',
:title => l(:button_quote)) if options[:reply_links]
links << link_to_remote(image_tag('comment.png'),
{ :url => {:controller => 'journals', :action => 'new', :id => issue, :journal_id => journal} },
:title => l(:button_quote)) if options[:reply_links]
links << link_to_in_place_notes_editor(image_tag('edit.png'), "journal-#{journal.id}-notes",
{ :controller => 'journals', :action => 'edit', :id => journal, :format => 'js' },
{ :controller => 'journals', :action => 'edit', :id => journal },
:title => l(:button_edit)) if editable
end
content << content_tag('div', links.join(' ').html_safe, :class => 'contextual') unless links.empty?
@@ -40,7 +38,7 @@ module JournalsHelper
end
def link_to_in_place_notes_editor(text, field_id, url, options={})
onclick = "$.ajax({url: '#{url_for(url)}', type: 'get'}); return false;"
onclick = "new Ajax.Request('#{url_for(url)}', {asynchronous:true, evalScripts:true, method:'get'}); return false;"
link_to text, '#', options.merge(:onclick => onclick)
end
end

View File

@@ -51,15 +51,38 @@ module ProjectsHelper
content_tag('select', options.html_safe, :name => 'project[parent_id]', :id => 'project_parent_id')
end
# Renders the projects index
# Renders a tree of projects as a nested set of unordered lists
# The given collection may be a subset of the whole project tree
# (eg. some intermediate nodes are private and can not be seen)
def render_project_hierarchy(projects)
render_project_nested_lists(projects) do |project|
s = link_to_project(project, {}, :class => "#{project.css_classes} #{User.current.member_of?(project) ? 'my-project' : nil}")
if project.description.present?
s << content_tag('div', textilizable(project.short_description, :project => project), :class => 'wiki description')
s = ''
if projects.any?
ancestors = []
original_project = @project
projects.each do |project|
# set the project environment to please macros.
@project = project
if (ancestors.empty? || project.is_descendant_of?(ancestors.last))
s << "<ul class='projects #{ ancestors.empty? ? 'root' : nil}'>\n"
else
ancestors.pop
s << "</li>"
while (ancestors.any? && !project.is_descendant_of?(ancestors.last))
ancestors.pop
s << "</ul></li>\n"
end
end
classes = (ancestors.empty? ? 'root' : 'child')
s << "<li class='#{classes}'><div class='#{classes}'>" +
link_to_project(project, {}, :class => "project #{User.current.member_of?(project) ? 'my-project' : nil}")
s << "<div class='wiki description'>#{textilizable(project.short_description, :project => project)}</div>" unless project.description.blank?
s << "</div>\n"
ancestors << project
end
s
s << ("</li></ul>\n" * ancestors.size)
@project = original_project
end
s.html_safe
end
# Returns a set of options for a select field, grouped by project.
@@ -68,6 +91,10 @@ module ProjectsHelper
versions.each do |version|
grouped[version.project.name] << [version.name, version.id]
end
# Add in the selected
if selected && !versions.include?(selected)
grouped[selected.project.name] << [selected.name, selected.id]
end
if grouped.keys.size > 1
grouped_options_for_select(grouped, selected && selected.id)

View File

@@ -18,44 +18,9 @@
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
module QueriesHelper
def filters_options_for_select(query)
options_for_select(filters_options(query))
end
def filters_options(query)
options = [[]]
sorted_options = query.available_filters.sort do |a, b|
ord = 0
if !(a[1][:order] == 20 && b[1][:order] == 20)
ord = a[1][:order] <=> b[1][:order]
else
cn = (CustomField::CUSTOM_FIELDS_NAMES.index(a[1][:field].class.name) <=>
CustomField::CUSTOM_FIELDS_NAMES.index(b[1][:field].class.name))
if cn != 0
ord = cn
else
f = (a[1][:field] <=> b[1][:field])
if f != 0
ord = f
else
# assigned_to or author
ord = (a[0] <=> b[0])
end
end
end
ord
end
options += sorted_options.map do |field, field_options|
[field_options[:name], field]
end
end
def available_block_columns_tags(query)
tags = ''.html_safe
query.available_block_columns.each do |column|
tags << content_tag('label', check_box_tag('c[]', column.name.to_s, query.has_column?(column)) + " #{column.caption}", :class => 'inline')
end
tags
def operators_for_select(filter_type)
Query.operators_by_filter_type[filter_type].collect {|o| [l(Query.operators[o]), o]}
end
def column_header(column)
@@ -67,7 +32,7 @@ module QueriesHelper
def column_content(column, issue)
value = column.value(issue)
if value.is_a?(Array)
value.collect {|v| column_value(column, issue, v)}.compact.join(', ').html_safe
value.collect {|v| column_value(column, issue, v)}.compact.sort.join(', ').html_safe
else
column_value(column, issue, value)
end
@@ -78,8 +43,6 @@ module QueriesHelper
when 'String'
if column.name == :subject
link_to(h(value), :controller => 'issues', :action => 'show', :id => issue)
elsif column.name == :description
issue.description? ? content_tag('div', textilizable(issue, :description), :class => "wiki") : ''
else
h(value)
end
@@ -87,14 +50,14 @@ module QueriesHelper
format_time(value)
when 'Date'
format_date(value)
when 'Fixnum'
when 'Fixnum', 'Float'
if column.name == :done_ratio
progress_bar(value, :width => '80px')
elsif column.name == :spent_hours
sprintf "%.2f", value
else
value.to_s
h(value.to_s)
end
when 'Float'
sprintf "%.2f", value
when 'User'
link_to_user value
when 'Project'
@@ -107,11 +70,6 @@ module QueriesHelper
l(:general_text_No)
when 'Issue'
link_to_issue(value, :subject => false)
when 'IssueRelation'
other = value.other_issue(issue)
content_tag('span',
(l(value.label_for(issue)) + " " + link_to_issue(other, :subject => false, :tracker => false)).html_safe,
:class => value.css_classes_for(issue))
else
h(value)
end

View File

@@ -17,6 +17,9 @@
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
require 'iconv'
require 'redmine/codeset_util'
module RepositoriesHelper
def format_revision(revision)
if revision.respond_to? :format_identifier
@@ -138,7 +141,12 @@ module RepositoriesHelper
select_tag('repository_scm',
options_for_select(scm_options, repository.class.name.demodulize),
:disabled => (repository && !repository.new_record?),
:data => {:remote => true, :method => 'get'})
:onchange => remote_function(
:url => new_project_repository_path(@project),
:method => :get,
:update => 'content',
:with => "Form.serialize(this.form)")
)
end
def with_leading_slash(path)
@@ -151,7 +159,7 @@ module RepositoriesHelper
def subversion_field_tags(form, repository)
content_tag('p', form.text_field(:url, :size => 60, :required => true,
:disabled => !repository.safe_attribute?('url')) +
:disabled => (repository && !repository.root_url.blank?)) +
'<br />'.html_safe +
'(file:///, http://, https://, svn://, svn+[tunnelscheme]://)') +
content_tag('p', form.text_field(:login, :size => 30)) +
@@ -166,7 +174,7 @@ module RepositoriesHelper
content_tag('p', form.text_field(
:url, :label => l(:field_path_to_repository),
:size => 60, :required => true,
:disabled => !repository.safe_attribute?('url'))) +
:disabled => (repository && !repository.new_record?))) +
content_tag('p', form.select(
:log_encoding, [nil] + Setting::ENCODINGS,
:label => l(:field_commit_logs_encoding), :required => true))
@@ -176,7 +184,7 @@ module RepositoriesHelper
content_tag('p', form.text_field(
:url, :label => l(:field_path_to_repository),
:size => 60, :required => true,
:disabled => !repository.safe_attribute?('url')
:disabled => (repository && !repository.root_url.blank?)
) +
'<br />'.html_safe + l(:text_mercurial_repository_note)) +
content_tag('p', form.select(
@@ -190,7 +198,7 @@ module RepositoriesHelper
content_tag('p', form.text_field(
:url, :label => l(:field_path_to_repository),
:size => 60, :required => true,
:disabled => !repository.safe_attribute?('url')
:disabled => (repository && !repository.root_url.blank?)
) +
'<br />'.html_safe +
l(:text_git_repository_note)) +
@@ -210,12 +218,12 @@ module RepositoriesHelper
:root_url,
:label => l(:field_cvsroot),
:size => 60, :required => true,
:disabled => !repository.safe_attribute?('root_url'))) +
:disabled => !repository.new_record?)) +
content_tag('p', form.text_field(
:url,
:label => l(:field_cvs_module),
:size => 30, :required => true,
:disabled => !repository.safe_attribute?('url'))) +
:disabled => !repository.new_record?)) +
content_tag('p', form.select(
:log_encoding, [nil] + Setting::ENCODINGS,
:label => l(:field_commit_logs_encoding), :required => true)) +
@@ -230,7 +238,7 @@ module RepositoriesHelper
content_tag('p', form.text_field(
:url, :label => l(:field_path_to_repository),
:size => 60, :required => true,
:disabled => !repository.safe_attribute?('url'))) +
:disabled => (repository && !repository.new_record?))) +
content_tag('p', form.select(
:log_encoding, [nil] + Setting::ENCODINGS,
:label => l(:field_commit_logs_encoding), :required => true))
@@ -240,7 +248,7 @@ module RepositoriesHelper
content_tag('p', form.text_field(
:url, :label => l(:field_root_directory),
:size => 60, :required => true,
:disabled => !repository.safe_attribute?('url'))) +
:disabled => (repository && !repository.root_url.blank?))) +
content_tag('p', form.select(
:path_encoding, [nil] + Setting::ENCODINGS,
:label => l(:field_scm_path_encoding)
@@ -250,13 +258,16 @@ module RepositoriesHelper
def index_commits(commits, heads)
return nil if commits.nil? or commits.first.parents.nil?
refs_map = {}
heads.each do |head|
refs_map[head.scmid] ||= []
refs_map[head.scmid] << head
end
commits_by_scmid = {}
commits.reverse.each_with_index do |commit, commit_index|
commits_by_scmid[commit.scmid] = {
:parent_scmids => commit.parents.collect { |parent| parent.scmid },
:rdmid => commit_index,
@@ -265,28 +276,38 @@ module RepositoriesHelper
:href => block_given? ? yield(commit.scmid) : commit.scmid
}
end
heads.sort! { |head1, head2| head1.to_s <=> head2.to_s }
space = nil
heads.each do |head|
if commits_by_scmid.include? head.scmid
space = index_head((space || -1) + 1, head, commits_by_scmid)
end
end
# when no head matched anything use first commit
space ||= index_head(0, commits.first, commits_by_scmid)
return commits_by_scmid, space
end
def index_head(space, commit, commits_by_scmid)
stack = [[space, commits_by_scmid[commit.scmid]]]
max_space = space
until stack.empty?
space, commit = stack.pop
commit[:space] = space if commit[:space].nil?
space -= 1
commit[:parent_scmids].each_with_index do |parent_scmid, parent_index|
parent_commit = commits_by_scmid[parent_scmid]
if parent_commit and parent_commit[:space].nil?
stack.unshift [space += 1, parent_commit]
end
end

View File

@@ -44,7 +44,7 @@ module SettingsHelper
setting_values = Setting.send(setting)
setting_values = [] unless setting_values.is_a?(Array)
content_tag("label", l(options[:label] || "setting_#{setting}")) +
setting_label(setting, options).html_safe +
hidden_field_tag("settings[#{setting}][]", '').html_safe +
choices.collect do |choice|
text, value = (choice.is_a?(Array) ? choice : [choice, choice])
@@ -53,10 +53,9 @@ module SettingsHelper
check_box_tag(
"settings[#{setting}][]",
value,
Setting.send(setting).include?(value),
:id => nil
Setting.send(setting).include?(value)
) + text.to_s,
:class => (options[:inline] ? 'inline' : 'block')
:class => 'block'
)
end.join.html_safe
end
@@ -73,13 +72,13 @@ module SettingsHelper
def setting_check_box(setting, options={})
setting_label(setting, options).html_safe +
hidden_field_tag("settings[#{setting}]", 0, :id => nil).html_safe +
hidden_field_tag("settings[#{setting}]", 0).html_safe +
check_box_tag("settings[#{setting}]", 1, Setting.send("#{setting}?"), options).html_safe
end
def setting_label(setting, options={})
label = options.delete(:label)
label != false ? label_tag("settings_#{setting}", l(label || "setting_#{setting}")).html_safe : ''
label != false ? content_tag("label", l(label || "setting_#{setting}")).html_safe : ''
end
# Renders a notification field for a Redmine::Notifiable option
@@ -87,20 +86,8 @@ module SettingsHelper
return content_tag(:label,
check_box_tag('settings[notified_events][]',
notifiable.name,
Setting.notified_events.include?(notifiable.name), :id => nil).html_safe +
Setting.notified_events.include?(notifiable.name)).html_safe +
l_or_humanize(notifiable.name, :prefix => 'label_').html_safe,
:class => notifiable.parent.present? ? "parent" : '').html_safe
end
def cross_project_subtasks_options
options = [
[:label_disabled, ''],
[:label_cross_project_system, 'system'],
[:label_cross_project_tree, 'tree'],
[:label_cross_project_hierarchy, 'hierarchy'],
[:label_cross_project_descendants, 'descendants']
]
options.map {|label, value| [l(label), value.to_s]}
end
end

View File

@@ -89,10 +89,6 @@ module SortHelper
sql.blank? ? nil : sql
end
def to_a
@criteria.dup
end
def add!(key, asc)
@criteria.delete_if {|k,o| k == key}
@criteria = [[key, asc]] + @criteria
@@ -186,10 +182,6 @@ module SortHelper
@sort_criteria.to_sql
end
def sort_criteria
@sort_criteria
end
# Returns a link which sorts by the named column.
#
# - column is the name of an attribute in the sorted record collection.

View File

@@ -77,7 +77,6 @@ module TimelogHelper
[l(:label_yesterday), 'yesterday'],
[l(:label_this_week), 'current_week'],
[l(:label_last_week), 'last_week'],
[l(:label_last_n_weeks, 2), 'last_2_weeks'],
[l(:label_last_n_days, 7), '7_days'],
[l(:label_this_month), 'current_month'],
[l(:label_last_month), 'last_month'],

View File

@@ -26,6 +26,15 @@ module UsersHelper
["#{l(:status_locked)} (#{user_count_by_status[3].to_i})", '3']], selected.to_s)
end
# Options for the new membership projects combo-box
def options_for_membership_project_select(user, projects)
options = content_tag('option', "--- #{l(:actionview_instancetag_blank_option)} ---")
options << project_tree_options_for_select(projects) do |p|
{:disabled => (user.projects.include?(p))}
end
options
end
def user_mail_notification_options(user)
user.valid_notification_options.collect {|o| [l(o.last), o.first]}
end

View File

@@ -19,18 +19,10 @@
module VersionsHelper
def version_anchor(version)
if @project == version.project
anchor version.name
else
anchor "#{version.project.try(:identifier)}-#{version.name}"
end
end
STATUS_BY_CRITERIAS = %w(tracker status priority author assigned_to category)
STATUS_BY_CRITERIAS = %w(category tracker status priority author assigned_to)
def render_issue_status_by(version, criteria)
criteria = 'tracker' unless STATUS_BY_CRITERIAS.include?(criteria)
criteria = 'category' unless STATUS_BY_CRITERIAS.include?(criteria)
h = Hash.new {|k,v| k[v] = [0, 0]}
begin
@@ -44,8 +36,7 @@ module VersionsHelper
rescue ActiveRecord::RecordNotFound
# When grouping by an association, Rails throws this exception if there's no result (bug)
end
# Sort with nil keys in last position
counts = h.keys.sort {|a,b| a.nil? ? 1 : (b.nil? ? -1 : a <=> b)}.collect {|k| {:group => k, :total => h[k][0], :open => h[k][1], :closed => (h[k][0] - h[k][1])}}
counts = h.keys.compact.sort.collect {|k| {:group => k, :total => h[k][0], :open => h[k][1], :closed => (h[k][0] - h[k][1])}}
max = counts.collect {|c| c[:total]}.max
render :partial => 'issue_counts', :locals => {:version => version, :criteria => criteria, :counts => counts, :max => max}

View File

@@ -30,8 +30,10 @@ module WatchersHelper
:action => (watched ? 'unwatch' : 'watch'),
:object_type => object.class.to_s.underscore,
:object_id => object.id}
link_to((watched ? l(:button_unwatch) : l(:button_watch)), url,
:remote => true, :method => 'post', :class => (watched ? 'icon icon-fav' : 'icon icon-fav-off'))
link_to_remote((watched ? l(:button_unwatch) : l(:button_watch)),
{:url => url},
:href => url_for(url),
:class => (watched ? 'icon icon-fav' : 'icon icon-fav-off'))
end
@@ -55,8 +57,11 @@ module WatchersHelper
:object_id => object.id,
:user_id => user}
s << ' '
s << link_to(image_tag('delete.png'), url,
:remote => true, :method => 'post', :style => "vertical-align: middle", :class => "delete")
s << link_to_remote(image_tag('delete.png'),
{:url => url},
:href => url_for(url),
:style => "vertical-align: middle",
:class => "delete")
end
content << content_tag('li', s)
end

View File

@@ -37,7 +37,7 @@ module WikiHelper
def wiki_page_breadcrumb(page)
breadcrumb(page.ancestors.reverse.collect {|parent|
link_to(h(parent.pretty_title), {:controller => 'wiki', :action => 'show', :id => parent.title, :project_id => parent.project, :version => nil})
link_to(h(parent.pretty_title), {:controller => 'wiki', :action => 'show', :id => parent.title, :project_id => parent.project})
})
end
end

View File

@@ -18,15 +18,4 @@
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
module WorkflowsHelper
def field_required?(field)
field.is_a?(CustomField) ? field.is_required? : %w(project_id tracker_id subject priority_id is_private).include?(field)
end
def field_permission_tag(permissions, status, field)
name = field.is_a?(CustomField) ? field.id.to_s : field
options = [["", ""], [l(:label_readonly), "readonly"]]
options << [l(:label_required), "required"] unless field_required?(field)
select_tag("permissions[#{name}][#{status.id}]", options_for_select(options, permissions[status.id][name]))
end
end

View File

@@ -24,7 +24,6 @@ class Attachment < ActiveRecord::Base
validates_presence_of :filename, :author
validates_length_of :filename, :maximum => 255
validates_length_of :disk_filename, :maximum => 255
validates_length_of :description, :maximum => 255
validate :validate_max_file_size
acts_as_event :title => :filename,
@@ -47,9 +46,6 @@ class Attachment < ActiveRecord::Base
cattr_accessor :storage_path
@@storage_path = Redmine::Configuration['attachments_storage_path'] || File.join(Rails.root, "files")
cattr_accessor :thumbnails_storage_path
@@thumbnails_storage_path = File.join(Rails.root, "tmp", "thumbnails")
before_save :files_to_final_location
after_destroy :delete_from_disk
@@ -127,7 +123,7 @@ class Attachment < ActiveRecord::Base
# Deletes the file from the file system if it's not referenced by other attachments
def delete_from_disk
if Attachment.where("disk_filename = ? AND id <> ?", disk_filename, id).empty?
if Attachment.first(:conditions => ["disk_filename = ? AND id <> ?", disk_filename, id]).nil?
delete_from_disk!
end
end
@@ -137,14 +133,6 @@ class Attachment < ActiveRecord::Base
File.join(self.class.storage_path, disk_filename.to_s)
end
def title
title = filename.to_s
if description.present?
title << " (#{description})"
end
title
end
def increment_download
increment!(:downloads)
end
@@ -162,43 +150,7 @@ class Attachment < ActiveRecord::Base
end
def image?
!!(self.filename =~ /\.(bmp|gif|jpg|jpe|jpeg|png)$/i)
end
def thumbnailable?
image?
end
# Returns the full path the attachment thumbnail, or nil
# if the thumbnail cannot be generated.
def thumbnail(options={})
if thumbnailable? && readable?
size = options[:size].to_i
if size > 0
# Limit the number of thumbnails per image
size = (size / 50) * 50
# Maximum thumbnail size
size = 800 if size > 800
else
size = Setting.thumbnails_size.to_i
end
size = 100 unless size > 0
target = File.join(self.class.thumbnails_storage_path, "#{id}_#{digest}_#{size}.thumb")
begin
Redmine::Thumbnail.generate(self.diskfile, target, size)
rescue => e
logger.error "An error occured while generating thumbnail for #{disk_filename} to #{target}\nException was: #{e.message}" if logger
return nil
end
end
end
# Deletes all thumbnails
def self.clear_thumbnails
Dir.glob(File.join(thumbnails_storage_path, "*.thumb")).each do |file|
File.delete file
end
self.filename =~ /\.(bmp|gif|jpg|jpe|jpeg|png)$/i
end
def is_text?
@@ -223,7 +175,7 @@ class Attachment < ActiveRecord::Base
def self.find_by_token(token)
if token.to_s =~ /^(\d+)\.([0-9a-f]+)$/
attachment_id, attachment_digest = $1, $2
attachment = Attachment.where(:id => attachment_id, :digest => attachment_digest).first
attachment = Attachment.first(:conditions => {:id => attachment_id, :digest => attachment_digest})
if attachment && attachment.container.nil?
attachment
end
@@ -248,7 +200,8 @@ class Attachment < ActiveRecord::Base
end
def self.prune(age=1.day)
Attachment.where("created_on < ? AND (container_type IS NULL OR container_type = '')", Time.now - age).destroy_all
attachments = Attachment.all(:conditions => ["created_on < ? AND (container_type IS NULL OR container_type = '')", Time.now - age])
attachments.each(&:destroy)
end
private

View File

@@ -18,7 +18,6 @@
# Generic exception for when the AuthSource can not be reached
# (eg. can not connect to the LDAP)
class AuthSourceException < Exception; end
class AuthSourceTimeoutException < AuthSourceException; end
class AuthSource < ActiveRecord::Base
include Redmine::SubclassFactory
@@ -59,7 +58,7 @@ class AuthSource < ActiveRecord::Base
# Try to authenticate a user not yet registered against available sources
def self.authenticate(login, password)
AuthSource.where(:onthefly_register => true).all.each do |source|
AuthSource.find(:all, :conditions => ["onthefly_register=?", true]).each do |source|
begin
logger.debug "Authenticating '#{login}' against '#{source.name}'" if logger && logger.debug?
attrs = source.authenticate(login, password)

View File

@@ -18,7 +18,6 @@
require 'iconv'
require 'net/ldap'
require 'net/ldap/dn'
require 'timeout'
class AuthSourceLdap < AuthSource
validates_presence_of :host, :port, :attr_login
@@ -26,11 +25,18 @@ class AuthSourceLdap < AuthSource
validates_length_of :account, :account_password, :base_dn, :filter, :maximum => 255, :allow_blank => true
validates_length_of :attr_login, :attr_firstname, :attr_lastname, :attr_mail, :maximum => 30, :allow_nil => true
validates_numericality_of :port, :only_integer => true
validates_numericality_of :timeout, :only_integer => true, :allow_blank => true
validate :validate_filter
before_validation :strip_ldap_attributes
def self.human_attribute_name(attribute_key_name, *args)
attr_name = attribute_key_name.to_s
if attr_name == "filter"
attr_name = "ldap_filter"
end
super(attr_name, *args)
end
def initialize(attributes=nil, *args)
super
self.port = 389 if self.port == 0
@@ -38,26 +44,22 @@ class AuthSourceLdap < AuthSource
def authenticate(login, password)
return nil if login.blank? || password.blank?
attrs = get_user_dn(login, password)
with_timeout do
attrs = get_user_dn(login, password)
if attrs && attrs[:dn] && authenticate_dn(attrs[:dn], password)
logger.debug "Authentication successful for '#{login}'" if logger && logger.debug?
return attrs.except(:dn)
end
if attrs && attrs[:dn] && authenticate_dn(attrs[:dn], password)
logger.debug "Authentication successful for '#{login}'" if logger && logger.debug?
return attrs.except(:dn)
end
rescue Net::LDAP::LdapError => e
rescue Net::LDAP::LdapError => e
raise AuthSourceException.new(e.message)
end
# test the connection to the LDAP
def test_connection
with_timeout do
ldap_con = initialize_ldap_con(self.account, self.account_password)
ldap_con.open { }
end
rescue Net::LDAP::LdapError => e
raise AuthSourceException.new(e.message)
ldap_con = initialize_ldap_con(self.account, self.account_password)
ldap_con.open { }
rescue Net::LDAP::LdapError => e
raise "LdapError: " + e.message
end
def auth_method_name
@@ -66,16 +68,6 @@ class AuthSourceLdap < AuthSource
private
def with_timeout(&block)
timeout = self.timeout
timeout = 20 unless timeout && timeout > 0
Timeout.timeout(timeout) do
return yield
end
rescue Timeout::Error => e
raise AuthSourceTimeoutException.new(e.message)
end
def ldap_filter
if filter.present?
Net::LDAP::Filter.construct(filter)

View File

@@ -21,37 +21,26 @@ class Board < ActiveRecord::Base
has_many :topics, :class_name => 'Message', :conditions => "#{Message.table_name}.parent_id IS NULL", :order => "#{Message.table_name}.created_on DESC"
has_many :messages, :dependent => :destroy, :order => "#{Message.table_name}.created_on DESC"
belongs_to :last_message, :class_name => 'Message', :foreign_key => :last_message_id
acts_as_tree :dependent => :nullify
acts_as_list :scope => '(project_id = #{project_id} AND parent_id #{parent_id ? "= #{parent_id}" : "IS NULL"})'
acts_as_list :scope => :project_id
acts_as_watchable
validates_presence_of :name, :description
validates_length_of :name, :maximum => 30
validates_length_of :description, :maximum => 255
validate :validate_board
scope :visible, lambda {|*args| { :include => :project,
:conditions => Project.allowed_to_condition(args.shift || User.current, :view_messages, *args) } }
safe_attributes 'name', 'description', 'parent_id', 'move_to'
safe_attributes 'name', 'description', 'move_to'
def visible?(user=User.current)
!user.nil? && user.allowed_to?(:view_messages, project)
end
def reload(*args)
@valid_parents = nil
super
end
def to_s
name
end
def valid_parents
@valid_parents ||= project.boards - self_and_descendants
end
def reset_counters!
self.class.reset_counters!(id)
end
@@ -64,26 +53,4 @@ class Board < ActiveRecord::Base
" last_message_id = (SELECT MAX(id) FROM #{Message.table_name} WHERE board_id=#{board_id})",
["id = ?", board_id])
end
def self.board_tree(boards, parent_id=nil, level=0)
tree = []
boards.select {|board| board.parent_id == parent_id}.sort_by(&:position).each do |board|
tree << [board, level]
tree += board_tree(boards, board.id, level+1)
end
if block_given?
tree.each do |board, level|
yield board, level
end
end
tree
end
protected
def validate_board
if parent_id && parent_id_changed?
errors.add(:parent_id, :invalid) unless valid_parents.include?(parent)
end
end
end

View File

@@ -162,7 +162,7 @@ class Changeset < ActiveRecord::Base
tag = "#{repository.identifier}|#{tag}"
end
if ref_project && project && ref_project != project
tag = "#{project.identifier}:#{tag}"
tag = "#{project.identifier}:#{tag}"
end
tag
end
@@ -176,12 +176,18 @@ class Changeset < ActiveRecord::Base
# Returns the previous changeset
def previous
@previous ||= Changeset.where(["id < ? AND repository_id = ?", id, repository_id]).order('id DESC').first
@previous ||= Changeset.find(:first,
:conditions => ['id < ? AND repository_id = ?',
self.id, self.repository_id],
:order => 'id DESC')
end
# Returns the next changeset
def next
@next ||= Changeset.where(["id > ? AND repository_id = ?", id, repository_id]).order('id ASC').first
@next ||= Changeset.find(:first,
:conditions => ['id > ? AND repository_id = ?',
self.id, self.repository_id],
:order => 'id ASC')
end
# Creates a new Change from it's common parameters

View File

@@ -30,32 +30,9 @@ class CustomField < ActiveRecord::Base
validate :validate_custom_field
before_validation :set_searchable
CUSTOM_FIELDS_TABS = [
{:name => 'IssueCustomField', :partial => 'custom_fields/index',
:label => :label_issue_plural},
{:name => 'TimeEntryCustomField', :partial => 'custom_fields/index',
:label => :label_spent_time},
{:name => 'ProjectCustomField', :partial => 'custom_fields/index',
:label => :label_project_plural},
{:name => 'VersionCustomField', :partial => 'custom_fields/index',
:label => :label_version_plural},
{:name => 'UserCustomField', :partial => 'custom_fields/index',
:label => :label_user_plural},
{:name => 'GroupCustomField', :partial => 'custom_fields/index',
:label => :label_group_plural},
{:name => 'TimeEntryActivityCustomField', :partial => 'custom_fields/index',
:label => TimeEntryActivity::OptionName},
{:name => 'IssuePriorityCustomField', :partial => 'custom_fields/index',
:label => IssuePriority::OptionName},
{:name => 'DocumentCategoryCustomField', :partial => 'custom_fields/index',
:label => DocumentCategory::OptionName}
]
CUSTOM_FIELDS_NAMES = CUSTOM_FIELDS_TABS.collect{|v| v[:name]}
def field_format=(arg)
# cannot change format of a saved custom field
super if new_record?
def initialize(attributes=nil, *args)
super
self.possible_values ||= []
end
def set_searchable
@@ -120,7 +97,7 @@ class CustomField < ActiveRecord::Base
value.force_encoding('UTF-8') if value.respond_to?(:force_encoding)
end
end
values || []
values
end
end
@@ -154,32 +131,16 @@ class CustomField < ActiveRecord::Base
casted
end
def value_from_keyword(keyword, customized)
possible_values_options = possible_values_options(customized)
if possible_values_options.present?
keyword = keyword.to_s.downcase
if v = possible_values_options.detect {|text, id| text.downcase == keyword}
if v.is_a?(Array)
v.last
else
v
end
end
else
keyword
end
end
# Returns a ORDER BY clause that can used to sort customized
# objects by their value of the custom field.
# Returns nil if the custom field can not be used for sorting.
# Returns false, if the custom field can not be used for sorting.
def order_statement
return nil if multiple?
case field_format
when 'string', 'text', 'list', 'date', 'bool'
# COALESCE is here to make sure that blank and NULL values are sorted equally
"COALESCE((SELECT cv_sort.value FROM #{CustomValue.table_name} cv_sort" +
" WHERE cv_sort.customized_type='#{self.class.customized_class.base_class.name}'" +
" WHERE cv_sort.customized_type='#{self.class.customized_class.name}'" +
" AND cv_sort.customized_id=#{self.class.customized_class.table_name}.id" +
" AND cv_sort.custom_field_id=#{id} LIMIT 1), '')"
when 'int', 'float'
@@ -187,74 +148,18 @@ class CustomField < ActiveRecord::Base
# Postgresql will raise an error if a value can not be casted!
# CustomValue validations should ensure that it doesn't occur
"(SELECT CAST(cv_sort.value AS decimal(60,3)) FROM #{CustomValue.table_name} cv_sort" +
" WHERE cv_sort.customized_type='#{self.class.customized_class.base_class.name}'" +
" WHERE cv_sort.customized_type='#{self.class.customized_class.name}'" +
" AND cv_sort.customized_id=#{self.class.customized_class.table_name}.id" +
" AND cv_sort.custom_field_id=#{id} AND cv_sort.value <> '' AND cv_sort.value IS NOT NULL LIMIT 1)"
when 'user', 'version'
value_class.fields_for_order_statement(value_join_alias)
else
nil
end
end
# Returns a GROUP BY clause that can used to group by custom value
# Returns nil if the custom field can not be used for grouping.
def group_statement
return nil if multiple?
case field_format
when 'list', 'date', 'bool', 'int'
order_statement
when 'user', 'version'
"COALESCE((SELECT cv_sort.value FROM #{CustomValue.table_name} cv_sort" +
" WHERE cv_sort.customized_type='#{self.class.customized_class.base_class.name}'" +
" AND cv_sort.customized_id=#{self.class.customized_class.table_name}.id" +
" AND cv_sort.custom_field_id=#{id} LIMIT 1), '')"
else
nil
end
end
def join_for_order_statement
case field_format
when 'user', 'version'
"LEFT OUTER JOIN #{CustomValue.table_name} #{join_alias}" +
" ON #{join_alias}.customized_type = '#{self.class.customized_class.base_class.name}'" +
" AND #{join_alias}.customized_id = #{self.class.customized_class.table_name}.id" +
" AND #{join_alias}.custom_field_id = #{id}" +
" AND #{join_alias}.value <> ''" +
" AND #{join_alias}.id = (SELECT max(#{join_alias}_2.id) FROM #{CustomValue.table_name} #{join_alias}_2" +
" WHERE #{join_alias}_2.customized_type = #{join_alias}.customized_type" +
" AND #{join_alias}_2.customized_id = #{join_alias}.customized_id" +
" AND #{join_alias}_2.custom_field_id = #{join_alias}.custom_field_id)" +
" LEFT OUTER JOIN #{value_class.table_name} #{value_join_alias}" +
" ON CAST(#{join_alias}.value as decimal(60,0)) = #{value_join_alias}.id"
else
nil
end
end
def join_alias
"cf_#{id}"
end
def value_join_alias
join_alias + "_" + field_format
end
def <=>(field)
position <=> field.position
end
# Returns the class that values represent
def value_class
case field_format
when 'user', 'version'
field_format.classify.constantize
else
nil
end
end
def self.customized_class
self.name =~ /^(.+)CustomField$/
begin; $1.constantize; rescue nil; end
@@ -295,10 +200,6 @@ class CustomField < ActiveRecord::Base
validate_field_value(value).empty?
end
def format_in?(*args)
args.include?(field_format)
end
protected
# Returns the error message for the given value regarding its format

View File

@@ -31,10 +31,4 @@ class DocumentCategory < Enumeration
def transfer_relations(to)
documents.update_all("category_id = #{to.id}")
end
def self.default
d = super
d = first if d.nil?
d
end
end

View File

@@ -35,20 +35,19 @@ class Enumeration < ActiveRecord::Base
validates_uniqueness_of :name, :scope => [:type, :project_id]
validates_length_of :name, :maximum => 30
scope :shared, where(:project_id => nil)
scope :sorted, order("#{table_name}.position ASC")
scope :active, where(:active => true)
scope :named, lambda {|arg| where("LOWER(#{table_name}.name) = LOWER(?)", arg.to_s.strip)}
scope :shared, :conditions => { :project_id => nil }
scope :active, :conditions => { :active => true }
scope :named, lambda {|arg| { :conditions => ["LOWER(#{table_name}.name) = LOWER(?)", arg.to_s.strip]}}
def self.default
# Creates a fake default scope so Enumeration.default will check
# it's type. STI subclasses will automatically add their own
# types to the finder.
if self.descends_from_active_record?
where(:is_default => true, :type => 'Enumeration').first
find(:first, :conditions => { :is_default => true, :type => 'Enumeration' })
else
# STI classes are
where(:is_default => true).first
find(:first, :conditions => { :is_default => true })
end
end
@@ -59,7 +58,7 @@ class Enumeration < ActiveRecord::Base
def check_default
if is_default? && is_default_changed?
Enumeration.update_all({:is_default => false}, {:type => type})
Enumeration.update_all("is_default = #{connection.quoted_false}", {:type => type})
end
end

View File

@@ -16,8 +16,6 @@
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
class Group < Principal
include Redmine::SafeAttributes
has_and_belongs_to_many :users, :after_add => :user_added,
:after_remove => :user_removed
@@ -29,25 +27,11 @@ class Group < Principal
before_destroy :remove_references_before_destroy
scope :sorted, order("#{table_name}.lastname ASC")
safe_attributes 'name',
'user_ids',
'custom_field_values',
'custom_fields',
:if => lambda {|group, user| user.admin?}
def to_s
lastname.to_s
end
def name
lastname
end
def name=(arg)
self.lastname = arg
end
alias :name :to_s
def user_added(user)
members.each do |member|

View File

@@ -17,7 +17,6 @@
class Issue < ActiveRecord::Base
include Redmine::SafeAttributes
include Redmine::Utils::DateCalculation
belongs_to :project
belongs_to :tracker
@@ -29,14 +28,6 @@ class Issue < ActiveRecord::Base
belongs_to :category, :class_name => 'IssueCategory', :foreign_key => 'category_id'
has_many :journals, :as => :journalized, :dependent => :destroy
has_many :visible_journals,
:class_name => 'Journal',
:as => :journalized,
:conditions => Proc.new {
["(#{Journal.table_name}.private_notes = ? OR (#{Project.allowed_to_condition(User.current, :view_private_notes)}))", false]
},
:readonly => true
has_many :time_entries, :dependent => :delete_all
has_and_belongs_to_many :changesets, :order => "#{Changeset.table_name}.committed_on ASC, #{Changeset.table_name}.id ASC"
@@ -48,7 +39,7 @@ class Issue < ActiveRecord::Base
acts_as_customizable
acts_as_watchable
acts_as_searchable :columns => ['subject', "#{table_name}.description", "#{Journal.table_name}.notes"],
:include => [:project, :visible_journals],
:include => [:project, :journals],
# sort by id so that limited eager loading doesn't break with postgresql
:order_column => "#{table_name}.id"
acts_as_event :title => Proc.new {|o| "#{o.tracker.name} ##{o.id} (#{o.status}): #{o.subject}"},
@@ -61,14 +52,13 @@ class Issue < ActiveRecord::Base
DONE_RATIO_OPTIONS = %w(issue_field issue_status)
attr_reader :current_journal
delegate :notes, :notes=, :private_notes, :private_notes=, :to => :current_journal, :allow_nil => true
validates_presence_of :subject, :priority, :project, :tracker, :author, :status
validates_length_of :subject, :maximum => 255
validates_inclusion_of :done_ratio, :in => 0..100
validates_numericality_of :estimated_hours, :allow_nil => true
validate :validate_issue, :validate_required_fields
validate :validate_issue
scope :visible,
lambda {|*args| { :include => :project,
@@ -80,6 +70,7 @@ class Issue < ActiveRecord::Base
}
scope :recently_updated, :order => "#{Issue.table_name}.updated_on DESC"
scope :with_limit, lambda { |limit| { :limit => limit} }
scope :on_active_project, :include => [:status, :project, :tracker],
:conditions => ["#{Project.table_name}.status=#{Project::STATUS_ACTIVE}"]
@@ -87,28 +78,22 @@ class Issue < ActiveRecord::Base
before_save :close_duplicates, :update_done_ratio_from_issue_status, :force_updated_on_change
after_save {|issue| issue.send :after_project_change if !issue.id_changed? && issue.project_id_changed?}
after_save :reschedule_following_issues, :update_nested_set_attributes, :update_parent_attributes, :create_journal
# Should be after_create but would be called before previous after_save callbacks
after_save :after_create_from_copy
after_destroy :update_parent_attributes
# Returns a SQL conditions string used to find all issues visible by the specified user
def self.visible_condition(user, options={})
Project.allowed_to_condition(user, :view_issues, options) do |role, user|
if user.logged?
case role.issues_visibility
when 'all'
nil
when 'default'
user_ids = [user.id] + user.groups.map(&:id)
"(#{table_name}.is_private = #{connection.quoted_false} OR #{table_name}.author_id = #{user.id} OR #{table_name}.assigned_to_id IN (#{user_ids.join(',')}))"
when 'own'
user_ids = [user.id] + user.groups.map(&:id)
"(#{table_name}.author_id = #{user.id} OR #{table_name}.assigned_to_id IN (#{user_ids.join(',')}))"
else
'1=0'
end
case role.issues_visibility
when 'all'
nil
when 'default'
user_ids = [user.id] + user.groups.map(&:id)
"(#{table_name}.is_private = #{connection.quoted_false} OR #{table_name}.author_id = #{user.id} OR #{table_name}.assigned_to_id IN (#{user_ids.join(',')}))"
when 'own'
user_ids = [user.id] + user.groups.map(&:id)
"(#{table_name}.author_id = #{user.id} OR #{table_name}.assigned_to_id IN (#{user_ids.join(',')}))"
else
"(#{table_name}.is_private = #{connection.quoted_false})"
'1=0'
end
end
end
@@ -116,19 +101,15 @@ class Issue < ActiveRecord::Base
# Returns true if usr or current user is allowed to view the issue
def visible?(usr=nil)
(usr || User.current).allowed_to?(:view_issues, self.project) do |role, user|
if user.logged?
case role.issues_visibility
when 'all'
true
when 'default'
!self.is_private? || (self.author == user || user.is_or_belongs_to?(assigned_to))
when 'own'
self.author == user || user.is_or_belongs_to?(assigned_to)
else
false
end
case role.issues_visibility
when 'all'
true
when 'default'
!self.is_private? || self.author == user || user.is_or_belongs_to?(assigned_to)
when 'own'
self.author == user || user.is_or_belongs_to?(assigned_to)
else
!self.is_private?
false
end
end
end
@@ -143,34 +124,6 @@ class Issue < ActiveRecord::Base
end
end
# AR#Persistence#destroy would raise and RecordNotFound exception
# if the issue was already deleted or updated (non matching lock_version).
# This is a problem when bulk deleting issues or deleting a project
# (because an issue may already be deleted if its parent was deleted
# first).
# The issue is reloaded by the nested_set before being deleted so
# the lock_version condition should not be an issue but we handle it.
def destroy
super
rescue ActiveRecord::RecordNotFound
# Stale or already deleted
begin
reload
rescue ActiveRecord::RecordNotFound
# The issue was actually already deleted
@destroyed = true
return freeze
end
# The issue was stale, retry to destroy
super
end
def reload(*args)
@workflow_rule_by_attribute = nil
@assignable_versions = nil
super
end
# Overrides Redmine::Acts::Customizable::InstanceMethods#available_custom_fields
def available_custom_fields
(project && tracker) ? (project.all_issue_custom_fields & tracker.custom_fields.all) : []
@@ -189,7 +142,6 @@ class Issue < ActiveRecord::Base
end
end
@copied_from = issue
@copy_options = options
self
end
@@ -234,9 +186,7 @@ class Issue < ActiveRecord::Base
def status_id=(sid)
self.status = nil
result = write_attribute(:status_id, sid)
@workflow_rule_by_attribute = nil
result
write_attribute(:status_id, sid)
end
def priority_id=(pid)
@@ -258,7 +208,6 @@ class Issue < ActiveRecord::Base
self.tracker = nil
result = write_attribute(:tracker_id, tid)
@custom_field_values = nil
@workflow_rule_by_attribute = nil
result
end
@@ -273,8 +222,6 @@ class Issue < ActiveRecord::Base
write_attribute(:project_id, project ? project.id : nil)
association_instance_set('project', project)
if project_was && project && project_was != project
@assignable_versions = nil
unless keep_tracker || project.trackers.include?(tracker)
self.tracker = project.trackers.first
end
@@ -286,8 +233,7 @@ class Issue < ActiveRecord::Base
if fixed_version && fixed_version.project != project && !project.shared_versions.include?(fixed_version)
self.fixed_version = nil
end
# Clear the parent task if it's no longer valid
unless valid_parent_project?
if parent && parent.project_id != project_id
self.parent_issue_id = nil
end
@custom_field_values = nil
@@ -346,7 +292,6 @@ class Issue < ActiveRecord::Base
'custom_field_values',
'custom_fields',
'lock_version',
'notes',
:if => lambda {|issue, user| issue.new_record? || user.allowed_to?(:edit_issues, issue.project) }
safe_attributes 'status_id',
@@ -354,15 +299,8 @@ class Issue < ActiveRecord::Base
'fixed_version_id',
'done_ratio',
'lock_version',
'notes',
:if => lambda {|issue, user| issue.new_statuses_allowed_to(user).any? }
safe_attributes 'notes',
:if => lambda {|issue, user| user.allowed_to?(:add_issue_notes, issue.project)}
safe_attributes 'private_notes',
:if => lambda {|issue, user| !issue.new_record? && user.allowed_to?(:set_notes_private, issue.project)}
safe_attributes 'watcher_user_ids',
:if => lambda {|issue, user| issue.new_record? && user.allowed_to?(:add_issue_watchers, issue.project)}
@@ -376,13 +314,6 @@ class Issue < ActiveRecord::Base
:if => lambda {|issue, user| (issue.new_record? || user.allowed_to?(:edit_issues, issue.project)) &&
user.allowed_to?(:manage_subtasks, issue.project)}
def safe_attribute_names(user=nil)
names = super
names -= disabled_core_fields
names -= read_only_attribute_names(user)
names
end
# Safely sets attributes
# Should be called from controllers instead of #attributes=
# attr_accessible is too rough because we still want things like
@@ -390,125 +321,39 @@ class Issue < ActiveRecord::Base
def safe_attributes=(attrs, user=User.current)
return unless attrs.is_a?(Hash)
attrs = attrs.dup
# User can change issue attributes only if he has :edit permission or if a workflow transition is allowed
attrs = delete_unsafe_attributes(attrs, user)
return if attrs.empty?
# Project and Tracker must be set before since new_statuses_allowed_to depends on it.
if (p = attrs.delete('project_id')) && safe_attribute?('project_id')
if p = attrs.delete('project_id')
if allowed_target_projects(user).collect(&:id).include?(p.to_i)
self.project_id = p
end
end
if (t = attrs.delete('tracker_id')) && safe_attribute?('tracker_id')
if t = attrs.delete('tracker_id')
self.tracker_id = t
end
if (s = attrs.delete('status_id')) && safe_attribute?('status_id')
if new_statuses_allowed_to(user).collect(&:id).include?(s.to_i)
self.status_id = s
if attrs['status_id']
unless new_statuses_allowed_to(user).collect(&:id).include?(attrs['status_id'].to_i)
attrs.delete('status_id')
end
end
attrs = delete_unsafe_attributes(attrs, user)
return if attrs.empty?
unless leaf?
attrs.reject! {|k,v| %w(priority_id done_ratio start_date due_date estimated_hours).include?(k)}
end
if attrs['parent_issue_id'].present?
s = attrs['parent_issue_id'].to_s
unless (m = s.match(%r{\A#?(\d+)\z})) && (m[1] == parent_id.to_s || Issue.visible(user).exists?(m[1]))
@invalid_parent_issue_id = attrs.delete('parent_issue_id')
end
end
if attrs['custom_field_values'].present?
attrs['custom_field_values'] = attrs['custom_field_values'].reject {|k, v| read_only_attribute_names(user).include? k.to_s}
end
if attrs['custom_fields'].present?
attrs['custom_fields'] = attrs['custom_fields'].reject {|c| read_only_attribute_names(user).include? c['id'].to_s}
attrs.delete('parent_issue_id') unless Issue.visible(user).exists?(attrs['parent_issue_id'].to_i)
end
# mass-assignment security bypass
assign_attributes attrs, :without_protection => true
end
def disabled_core_fields
tracker ? tracker.disabled_core_fields : []
end
# Returns the custom_field_values that can be edited by the given user
def editable_custom_field_values(user=nil)
custom_field_values.reject do |value|
read_only_attribute_names(user).include?(value.custom_field_id.to_s)
end
end
# Returns the names of attributes that are read-only for user or the current user
# For users with multiple roles, the read-only fields are the intersection of
# read-only fields of each role
# The result is an array of strings where sustom fields are represented with their ids
#
# Examples:
# issue.read_only_attribute_names # => ['due_date', '2']
# issue.read_only_attribute_names(user) # => []
def read_only_attribute_names(user=nil)
workflow_rule_by_attribute(user).reject {|attr, rule| rule != 'readonly'}.keys
end
# Returns the names of required attributes for user or the current user
# For users with multiple roles, the required fields are the intersection of
# required fields of each role
# The result is an array of strings where sustom fields are represented with their ids
#
# Examples:
# issue.required_attribute_names # => ['due_date', '2']
# issue.required_attribute_names(user) # => []
def required_attribute_names(user=nil)
workflow_rule_by_attribute(user).reject {|attr, rule| rule != 'required'}.keys
end
# Returns true if the attribute is required for user
def required_attribute?(name, user=nil)
required_attribute_names(user).include?(name.to_s)
end
# Returns a hash of the workflow rule by attribute for the given user
#
# Examples:
# issue.workflow_rule_by_attribute # => {'due_date' => 'required', 'start_date' => 'readonly'}
def workflow_rule_by_attribute(user=nil)
return @workflow_rule_by_attribute if @workflow_rule_by_attribute && user.nil?
user_real = user || User.current
roles = user_real.admin ? Role.all : user_real.roles_for_project(project)
return {} if roles.empty?
result = {}
workflow_permissions = WorkflowPermission.where(:tracker_id => tracker_id, :old_status_id => status_id, :role_id => roles.map(&:id)).all
if workflow_permissions.any?
workflow_rules = workflow_permissions.inject({}) do |h, wp|
h[wp.field_name] ||= []
h[wp.field_name] << wp.rule
h
end
workflow_rules.each do |attr, rules|
next if rules.size < roles.size
uniq_rules = rules.uniq
if uniq_rules.size == 1
result[attr] = uniq_rules.first
else
result[attr] = 'required'
end
end
end
@workflow_rule_by_attribute = result if user.nil?
result
end
private :workflow_rule_by_attribute
def done_ratio
if Issue.use_status_for_done_ratio? && status && status.default_done_ratio
status.default_done_ratio
@@ -526,15 +371,11 @@ class Issue < ActiveRecord::Base
end
def validate_issue
if due_date.nil? && @attributes['due_date'].present?
if self.due_date.nil? && @attributes['due_date'] && !@attributes['due_date'].empty?
errors.add :due_date, :not_a_date
end
if start_date.nil? && @attributes['start_date'].present?
errors.add :start_date, :not_a_date
end
if due_date && start_date && due_date < start_date
if self.due_date and self.start_date and self.due_date < self.start_date
errors.add :due_date, :greater_than_start_date
end
@@ -558,11 +399,9 @@ class Issue < ActiveRecord::Base
end
# Checks parent issue assignment
if @invalid_parent_issue_id.present?
errors.add :parent_issue_id, :invalid
elsif @parent_issue
if !valid_parent_project?(@parent_issue)
errors.add :parent_issue_id, :invalid
if @parent_issue
if @parent_issue.project_id != project_id
errors.add :parent_issue_id, :not_same_project
elsif !new_record?
# moving an existing issue
if @parent_issue.root_id != root_id
@@ -570,26 +409,7 @@ class Issue < ActiveRecord::Base
elsif move_possible?(@parent_issue)
# move accepted inside tree
else
errors.add :parent_issue_id, :invalid
end
end
end
end
# Validates the issue against additional workflow requirements
def validate_required_fields
user = new_record? ? author : current_journal.try(:user)
required_attribute_names(user).each do |attribute|
if attribute =~ /^\d+$/
attribute = attribute.to_i
v = custom_field_values.detect {|v| v.custom_field_id == attribute }
if v && v.value.blank?
errors.add :base, v.custom_field.name + ' ' + l('activerecord.errors.messages.blank')
end
else
if respond_to?(attribute) && send(attribute).blank?
errors.add attribute, :blank
errors.add :parent_issue_id, :not_a_valid_parent
end
end
end
@@ -620,19 +440,10 @@ class Issue < ActiveRecord::Base
if new_record?
nil
else
journals.maximum(:id)
journals.first(:order => "#{Journal.table_name}.id DESC").try(:id)
end
end
# Returns a scope for journals that have an id greater than journal_id
def journals_after(journal_id)
scope = journals.reorder("#{Journal.table_name}.id ASC")
if journal_id.present?
scope = scope.where("#{Journal.table_name}.id > ?", journal_id.to_i)
end
scope
end
# Return true if the issue is closed, otherwise false
def closed?
self.status.is_closed?
@@ -689,21 +500,7 @@ class Issue < ActiveRecord::Base
# Versions that the issue can be assigned to
def assignable_versions
return @assignable_versions if @assignable_versions
versions = project.shared_versions.open.all
if fixed_version
if fixed_version_id_changed?
# nothing to do
elsif project_id_changed?
if project.shared_versions.include?(fixed_version)
versions << fixed_version
end
else
versions << fixed_version
end
end
@assignable_versions = versions.uniq.sort
@assignable_versions ||= (project.shared_versions.open + [Version.find_by_id(fixed_version_id_was)]).compact.uniq.sort
end
# Returns true if this issue is blocked by another issue that is still open
@@ -743,8 +540,8 @@ class Issue < ActiveRecord::Base
end
end
# Returns the users that should be notified
def notified_users
# Returns the mail adresses of users that should be notified
def recipients
notified = []
# Author and assignee are always notified unless they have been
# locked or don't want to be notified
@@ -761,12 +558,7 @@ class Issue < ActiveRecord::Base
notified.uniq!
# Remove users that can not view the issue
notified.reject! {|user| !visible?(user)}
notified
end
# Returns the email addresses that should be notified
def recipients
notified_users.collect(&:mail)
notified.collect(&:mail)
end
# Returns the number of hours spent on this issue
@@ -785,7 +577,7 @@ class Issue < ActiveRecord::Base
end
def relations
@relations ||= IssueRelations.new(self, (relations_from + relations_to).sort)
@relations ||= (relations_from + relations_to).sort
end
# Preloads relations for a collection of issues
@@ -808,25 +600,6 @@ class Issue < ActiveRecord::Base
end
end
# Preloads visible relations for a collection of issues
def self.load_visible_relations(issues, user=User.current)
if issues.any?
issue_ids = issues.map(&:id)
# Relations with issue_from in given issues and visible issue_to
relations_from = IssueRelation.includes(:issue_to => [:status, :project]).where(visible_condition(user)).where(:issue_from_id => issue_ids).all
# Relations with issue_to in given issues and visible issue_from
relations_to = IssueRelation.includes(:issue_from => [:status, :project]).where(visible_condition(user)).where(:issue_to_id => issue_ids).all
issues.each do |issue|
relations =
relations_from.select {|relation| relation.issue_from_id == issue.id} +
relations_to.select {|relation| relation.issue_to_id == issue.id}
issue.instance_variable_set "@relations", IssueRelations.new(issue, relations.sort)
end
end
end
# Finds an issue relation given its id.
def find_relation(relation_id)
IssueRelation.find(relation_id, :conditions => ["issue_to_id = ? OR issue_from_id = ?", id, id])
@@ -864,58 +637,29 @@ class Issue < ActiveRecord::Base
(start_date && due_date) ? due_date - start_date : 0
end
# Returns the duration in working days
def working_duration
(start_date && due_date) ? working_days(start_date, due_date) : 0
end
def soonest_start(reload=false)
@soonest_start = nil if reload
def soonest_start
@soonest_start ||= (
relations_to(reload).collect{|relation| relation.successor_soonest_start} +
relations_to.collect{|relation| relation.successor_soonest_start} +
ancestors.collect(&:soonest_start)
).compact.max
end
# Sets start_date on the given date or the next working day
# and changes due_date to keep the same working duration.
def reschedule_on(date)
wd = working_duration
date = next_working_date(date)
self.start_date = date
self.due_date = add_working_days(date, wd)
end
# Reschedules the issue on the given date or the next working day and saves the record.
# If the issue is a parent task, this is done by rescheduling its subtasks.
def reschedule_on!(date)
def reschedule_after(date)
return if date.nil?
if leaf?
if start_date.nil? || start_date != date
if start_date && start_date > date
# Issue can not be moved earlier than its soonest start date
date = [soonest_start(true), date].compact.max
end
reschedule_on(date)
if start_date.nil? || start_date < date
self.start_date, self.due_date = date, date + duration
begin
save
rescue ActiveRecord::StaleObjectError
reload
reschedule_on(date)
self.start_date, self.due_date = date, date + duration
save
end
end
else
leaves.each do |leaf|
if leaf.start_date
# Only move subtask if it starts at the same date as the parent
# or if it starts before the given date
if start_date == leaf.start_date || date > leaf.start_date
leaf.reschedule_on!(date)
end
else
leaf.reschedule_on!(date)
end
leaf.reschedule_after(date)
end
end
end
@@ -936,7 +680,7 @@ class Issue < ActiveRecord::Base
# Returns a string of css classes that apply to the issue
def css_classes
s = "issue status-#{status_id} #{priority.try(:css_classes)}"
s = "issue status-#{status.position} priority-#{priority.position}"
s << ' closed' if closed?
s << ' overdue' if overdue?
s << ' child' if child?
@@ -986,44 +730,23 @@ class Issue < ActiveRecord::Base
end
def parent_issue_id=(arg)
s = arg.to_s.strip.presence
if s && (m = s.match(%r{\A#?(\d+)\z})) && (@parent_issue = Issue.find_by_id(m[1]))
parent_issue_id = arg.blank? ? nil : arg.to_i
if parent_issue_id && @parent_issue = Issue.find_by_id(parent_issue_id)
@parent_issue.id
else
@parent_issue = nil
@invalid_parent_issue_id = arg
nil
end
end
def parent_issue_id
if @invalid_parent_issue_id
@invalid_parent_issue_id
elsif instance_variable_defined? :@parent_issue
if instance_variable_defined? :@parent_issue
@parent_issue.nil? ? nil : @parent_issue.id
else
parent_id
end
end
# Returns true if issue's project is a valid
# parent issue project
def valid_parent_project?(issue=parent)
return true if issue.nil? || issue.project_id == project_id
case Setting.cross_project_subtasks
when 'system'
true
when 'tree'
issue.project.root == project.root
when 'hierarchy'
issue.project.is_or_is_ancestor_of?(project) || issue.project.is_descendant_of?(project)
when 'descendants'
issue.project.is_or_is_ancestor_of?(project)
else
false
end
end
# Extracted from the ReportsController.
def self.by_tracker(project)
count_and_group_by(:project => project,
@@ -1103,9 +826,8 @@ class Issue < ActiveRecord::Base
relations_to.clear
end
# Move subtasks that were in the same project
# Move subtasks
children.each do |child|
next unless child.project_id == project_id_was
# Change project and keep project
child.send :project=, project, true
unless child.save
@@ -1114,39 +836,6 @@ class Issue < ActiveRecord::Base
end
end
# Callback for after the creation of an issue by copy
# * adds a "copied to" relation with the copied issue
# * copies subtasks from the copied issue
def after_create_from_copy
return unless copy? && !@after_create_from_copy_handled
if (@copied_from.project_id == project_id || Setting.cross_project_issue_relations?) && @copy_options[:link] != false
relation = IssueRelation.new(:issue_from => @copied_from, :issue_to => self, :relation_type => IssueRelation::TYPE_COPIED_TO)
unless relation.save
logger.error "Could not create relation while copying ##{@copied_from.id} to ##{id} due to validation errors: #{relation.errors.full_messages.join(', ')}" if logger
end
end
unless @copied_from.leaf? || @copy_options[:subtasks] == false
@copied_from.children.each do |child|
unless child.visible?
# Do not copy subtasks that are not visible to avoid potential disclosure of private data
logger.error "Subtask ##{child.id} was not copied during ##{@copied_from.id} copy because it is not visible to the current user" if logger
next
end
copy = Issue.new.copy_from(child, @copy_options)
copy.author = author
copy.project = project
copy.parent_issue_id = id
# Children subtasks are copied recursively
unless copy.save
logger.error "Could not copy subtask ##{child.id} while copying ##{@copied_from.id} to ##{id} due to validation errors: #{copy.errors.full_messages.join(', ')}" if logger
end
end
end
@after_create_from_copy_handled = true
end
def update_nested_set_attributes
if root_id.nil?
# issue was just created
@@ -1255,7 +944,7 @@ class Issue < ActiveRecord::Base
end
end
# Callback on file attachment
# Callback on attachment deletion
def attachment_added(obj)
if @current_journal && !obj.new_record?
@current_journal.details << JournalDetail.new(:property => 'attachment', :prop_key => obj.id, :value => obj.filename)

View File

@@ -27,7 +27,7 @@ class IssueCategory < ActiveRecord::Base
safe_attributes 'name', 'assigned_to_id'
scope :named, lambda {|arg| where("LOWER(#{table_name}.name) = LOWER(?)", arg.to_s.strip)}
scope :named, lambda {|arg| { :conditions => ["LOWER(#{table_name}.name) = LOWER(?)", arg.to_s.strip]}}
alias :destroy_without_reassign :destroy

View File

@@ -18,9 +18,6 @@
class IssuePriority < Enumeration
has_many :issues, :foreign_key => 'priority_id'
after_destroy {|priority| priority.class.compute_position_names}
after_save {|priority| priority.class.compute_position_names if priority.position_changed? && priority.position}
OptionName = :enumeration_issue_priorities
def option_name
@@ -34,35 +31,4 @@ class IssuePriority < Enumeration
def transfer_relations(to)
issues.update_all("priority_id = #{to.id}")
end
def css_classes
"priority-#{id} priority-#{position_name}"
end
# Clears position_name for all priorities
# Called from migration 20121026003537_populate_enumerations_position_name
def self.clear_position_names
update_all :position_name => nil
end
# Updates position_name for active priorities
# Called from migration 20121026003537_populate_enumerations_position_name
def self.compute_position_names
priorities = where(:active => true).all.sort_by(&:position)
if priorities.any?
default = priorities.detect(&:is_default?) || priorities[(priorities.size - 1) / 2]
priorities.each_with_index do |priority, index|
name = case
when priority.position == default.position
"default"
when priority.position < default.position
index == 0 ? "lowest" : "low#{index+1}"
else
index == (priorities.size - 1) ? "highest" : "high#{priorities.size - index}"
end
update_all({:position_name => name}, :id => priority.id)
end
end
end
end

View File

@@ -15,20 +15,6 @@
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
# Class used to represent the relations of an issue
class IssueRelations < Array
include Redmine::I18n
def initialize(issue, *args)
@issue = issue
super(*args)
end
def to_s(*args)
map {|relation| "#{l(relation.label_for(@issue))} ##{relation.other_issue(@issue).id}"}.join(', ')
end
end
class IssueRelation < ActiveRecord::Base
belongs_to :issue_from, :class_name => 'Issue', :foreign_key => 'issue_from_id'
belongs_to :issue_to, :class_name => 'Issue', :foreign_key => 'issue_to_id'
@@ -40,37 +26,25 @@ class IssueRelation < ActiveRecord::Base
TYPE_BLOCKED = "blocked"
TYPE_PRECEDES = "precedes"
TYPE_FOLLOWS = "follows"
TYPE_COPIED_TO = "copied_to"
TYPE_COPIED_FROM = "copied_from"
TYPES = {
TYPE_RELATES => { :name => :label_relates_to, :sym_name => :label_relates_to,
:order => 1, :sym => TYPE_RELATES },
TYPE_DUPLICATES => { :name => :label_duplicates, :sym_name => :label_duplicated_by,
:order => 2, :sym => TYPE_DUPLICATED },
TYPE_DUPLICATED => { :name => :label_duplicated_by, :sym_name => :label_duplicates,
:order => 3, :sym => TYPE_DUPLICATES, :reverse => TYPE_DUPLICATES },
TYPE_BLOCKS => { :name => :label_blocks, :sym_name => :label_blocked_by,
:order => 4, :sym => TYPE_BLOCKED },
TYPE_BLOCKED => { :name => :label_blocked_by, :sym_name => :label_blocks,
:order => 5, :sym => TYPE_BLOCKS, :reverse => TYPE_BLOCKS },
TYPE_PRECEDES => { :name => :label_precedes, :sym_name => :label_follows,
:order => 6, :sym => TYPE_FOLLOWS },
TYPE_FOLLOWS => { :name => :label_follows, :sym_name => :label_precedes,
:order => 7, :sym => TYPE_PRECEDES, :reverse => TYPE_PRECEDES },
TYPE_COPIED_TO => { :name => :label_copied_to, :sym_name => :label_copied_from,
:order => 8, :sym => TYPE_COPIED_FROM },
TYPE_COPIED_FROM => { :name => :label_copied_from, :sym_name => :label_copied_to,
:order => 9, :sym => TYPE_COPIED_TO, :reverse => TYPE_COPIED_TO }
}.freeze
TYPES = { TYPE_RELATES => { :name => :label_relates_to, :sym_name => :label_relates_to, :order => 1, :sym => TYPE_RELATES },
TYPE_DUPLICATES => { :name => :label_duplicates, :sym_name => :label_duplicated_by, :order => 2, :sym => TYPE_DUPLICATED },
TYPE_DUPLICATED => { :name => :label_duplicated_by, :sym_name => :label_duplicates, :order => 3, :sym => TYPE_DUPLICATES, :reverse => TYPE_DUPLICATES },
TYPE_BLOCKS => { :name => :label_blocks, :sym_name => :label_blocked_by, :order => 4, :sym => TYPE_BLOCKED },
TYPE_BLOCKED => { :name => :label_blocked_by, :sym_name => :label_blocks, :order => 5, :sym => TYPE_BLOCKS, :reverse => TYPE_BLOCKS },
TYPE_PRECEDES => { :name => :label_precedes, :sym_name => :label_follows, :order => 6, :sym => TYPE_FOLLOWS },
TYPE_FOLLOWS => { :name => :label_follows, :sym_name => :label_precedes, :order => 7, :sym => TYPE_PRECEDES, :reverse => TYPE_PRECEDES }
}.freeze
validates_presence_of :issue_from, :issue_to, :relation_type
validates_inclusion_of :relation_type, :in => TYPES.keys
validates_numericality_of :delay, :allow_nil => true
validates_uniqueness_of :issue_to_id, :scope => :issue_from_id
validate :validate_issue_relation
attr_protected :issue_from_id, :issue_to_id
before_save :handle_issue_order
def visible?(user=User.current)
@@ -95,19 +69,14 @@ class IssueRelation < ActiveRecord::Base
def validate_issue_relation
if issue_from && issue_to
errors.add :issue_to_id, :invalid if issue_from_id == issue_to_id
unless issue_from.project_id == issue_to.project_id ||
Setting.cross_project_issue_relations?
errors.add :issue_to_id, :not_same_project
end
# detect circular dependencies depending wether the relation should be reversed
errors.add :issue_to_id, :not_same_project unless issue_from.project_id == issue_to.project_id || Setting.cross_project_issue_relations?
#detect circular dependencies depending wether the relation should be reversed
if TYPES.has_key?(relation_type) && TYPES[relation_type][:reverse]
errors.add :base, :circular_dependency if issue_from.all_dependent_issues.include? issue_to
else
errors.add :base, :circular_dependency if issue_to.all_dependent_issues.include? issue_from
end
if issue_from.is_descendant_of?(issue_to) || issue_from.is_ancestor_of?(issue_to)
errors.add :base, :cant_link_an_issue_with_a_descendant
end
errors.add :base, :cant_link_an_issue_with_a_descendant if issue_from.is_descendant_of?(issue_to) || issue_from.is_ancestor_of?(issue_to)
end
end
@@ -127,13 +96,7 @@ class IssueRelation < ActiveRecord::Base
end
def label_for(issue)
TYPES[relation_type] ?
TYPES[relation_type][(self.issue_from_id == issue.id) ? :name : :sym_name] :
:unknow
end
def css_classes_for(issue)
"rel-#{relation_type_for(issue)}"
TYPES[relation_type] ? TYPES[relation_type][(self.issue_from_id == issue.id) ? :name : :sym_name] : :unknow
end
def handle_issue_order
@@ -150,20 +113,18 @@ class IssueRelation < ActiveRecord::Base
def set_issue_to_dates
soonest_start = self.successor_soonest_start
if soonest_start && issue_to
issue_to.reschedule_on!(soonest_start)
issue_to.reschedule_after(soonest_start)
end
end
def successor_soonest_start
if (TYPE_PRECEDES == self.relation_type) && delay && issue_from &&
(issue_from.start_date || issue_from.due_date)
if (TYPE_PRECEDES == self.relation_type) && delay && issue_from && (issue_from.start_date || issue_from.due_date)
(issue_from.due_date || issue_from.start_date) + 1 + delay
end
end
def <=>(relation)
r = TYPES[self.relation_type][:order] <=> TYPES[relation.relation_type][:order]
r == 0 ? id <=> relation.id : r
TYPES[self.relation_type][:order] <=> TYPES[relation.relation_type][:order]
end
private

View File

@@ -17,10 +17,10 @@
class IssueStatus < ActiveRecord::Base
before_destroy :check_integrity
has_many :workflows, :class_name => 'WorkflowTransition', :foreign_key => "old_status_id"
has_many :workflows, :foreign_key => "old_status_id"
acts_as_list
before_destroy :delete_workflow_rules
before_destroy :delete_workflows
after_save :update_default
validates_presence_of :name
@@ -28,23 +28,23 @@ class IssueStatus < ActiveRecord::Base
validates_length_of :name, :maximum => 30
validates_inclusion_of :default_done_ratio, :in => 0..100, :allow_nil => true
scope :sorted, order("#{table_name}.position ASC")
scope :named, lambda {|arg| where("LOWER(#{table_name}.name) = LOWER(?)", arg.to_s.strip)}
scope :named, lambda {|arg| { :conditions => ["LOWER(#{table_name}.name) = LOWER(?)", arg.to_s.strip]}}
def update_default
IssueStatus.update_all({:is_default => false}, ['id <> ?', id]) if self.is_default?
IssueStatus.update_all("is_default=#{connection.quoted_false}", ['id <> ?', id]) if self.is_default?
end
# Returns the default status for new issues
def self.default
where(:is_default => true).first
find(:first, :conditions =>["is_default=?", true])
end
# Update all the +Issues+ setting their done_ratio to the value of their +IssueStatus+
def self.update_issue_done_ratios
if Issue.use_status_for_done_ratio?
IssueStatus.where("default_done_ratio >= 0").all.each do |status|
Issue.update_all({:done_ratio => status.default_done_ratio}, {:status_id => status.id})
IssueStatus.find(:all, :conditions => ["default_done_ratio >= 0"]).each do |status|
Issue.update_all(["done_ratio = ?", status.default_done_ratio],
["status_id = ?", status.id])
end
end
@@ -61,7 +61,7 @@ class IssueStatus < ActiveRecord::Base
w.tracker_id == tracker.id &&
((!w.author && !w.assignee) || (author && w.author) || (assignee && w.assignee))
end
transitions.map(&:new_status).compact.sort
transitions.collect{|w| w.new_status}.compact.sort
else
[]
end
@@ -75,12 +75,12 @@ class IssueStatus < ActiveRecord::Base
conditions << " OR author = :true" if author
conditions << " OR assignee = :true" if assignee
workflows.
includes(:new_status).
where(["role_id IN (:role_ids) AND tracker_id = :tracker_id AND (#{conditions})",
workflows.find(:all,
:include => :new_status,
:conditions => ["role_id IN (:role_ids) AND tracker_id = :tracker_id AND (#{conditions})",
{:role_ids => roles.collect(&:id), :tracker_id => tracker.id, :true => true, :false => false}
]).all.
map(&:new_status).compact.sort
]
).collect{|w| w.new_status}.compact.sort
else
[]
end
@@ -92,14 +92,13 @@ class IssueStatus < ActiveRecord::Base
def to_s; name end
private
private
def check_integrity
raise "Can't delete status" if Issue.where(:status_id => id).any?
raise "Can't delete status" if Issue.find(:first, :conditions => ["status_id=?", self.id])
end
# Deletes associated workflows
def delete_workflow_rules
WorkflowRule.delete_all(["old_status_id = :id OR new_status_id = :id", {:id => id}])
def delete_workflows
Workflow.delete_all(["old_status_id = :id OR new_status_id = :id", {:id => id}])
end
end

View File

@@ -37,15 +37,10 @@ class Journal < ActiveRecord::Base
:conditions => "#{Journal.table_name}.journalized_type = 'Issue' AND" +
" (#{JournalDetail.table_name}.prop_key = 'status_id' OR #{Journal.table_name}.notes <> '')"}
before_create :split_private_notes
scope :visible, lambda {|*args|
user = args.shift || User.current
includes(:issue => :project).
where(Issue.visible_condition(user, *args)).
where("(#{Journal.table_name}.private_notes = ? OR (#{Project.allowed_to_condition(user, :view_private_notes, *args)}))", false)
}
scope :visible, lambda {|*args| {
:include => {:issue => :project},
:conditions => Issue.visible_condition(args.shift || User.current, *args)
}}
def save(*args)
# Do not save an empty journal
@@ -80,7 +75,6 @@ class Journal < ActiveRecord::Base
s = 'journal'
s << ' has-notes' unless notes.blank?
s << ' has-details' unless details.blank?
s << ' private-notes' if private_notes?
s
end
@@ -91,41 +85,4 @@ class Journal < ActiveRecord::Base
def notify=(arg)
@notify = arg
end
def recipients
notified = journalized.notified_users
if private_notes?
notified = notified.select {|user| user.allowed_to?(:view_private_notes, journalized.project)}
end
notified.map(&:mail)
end
def watcher_recipients
notified = journalized.notified_watchers
if private_notes?
notified = notified.select {|user| user.allowed_to?(:view_private_notes, journalized.project)}
end
notified.map(&:mail)
end
private
def split_private_notes
if private_notes?
if notes.present?
if details.any?
# Split the journal (notes/changes) so we don't have half-private journals
journal = Journal.new(:journalized => journalized, :user => user, :notes => nil, :private_notes => false)
journal.details = details
journal.save
self.details = []
self.created_on = journal.created_on
end
else
# Blank notes should not be private
self.private_notes = false
end
end
true
end
end

View File

@@ -50,8 +50,8 @@ class MailHandler < ActionMailer::Base
cattr_accessor :ignored_emails_headers
@@ignored_emails_headers = {
'X-Auto-Response-Suppress' => 'oof',
'Auto-Submitted' => /^auto-/
'X-Auto-Response-Suppress' => 'OOF',
'Auto-Submitted' => 'auto-replied'
}
# Processes incoming emails
@@ -69,14 +69,11 @@ class MailHandler < ActionMailer::Base
# Ignore auto generated emails
self.class.ignored_emails_headers.each do |key, ignored_value|
value = email.header[key]
if value
value = value.to_s.downcase
if (ignored_value.is_a?(Regexp) && value.match(ignored_value)) || value == ignored_value
if logger && logger.info
logger.info "MailHandler: ignoring email with #{key}:#{value} header"
end
return false
if value && value.to_s.downcase == ignored_value.downcase
if logger && logger.info
logger.info "MailHandler: ignoring email with #{key}:#{value} header"
end
return false
end
end
@user = User.find_by_mail(sender_email) if sender_email.present?
@@ -124,7 +121,6 @@ class MailHandler < ActionMailer::Base
def dispatch
headers = [email.in_reply_to, email.references].flatten.compact
subject = email.subject.to_s
if headers.detect {|h| h.to_s =~ MESSAGE_ID_RE}
klass, object_id = $1, $2.to_i
method_name = "receive_#{klass}_reply"
@@ -133,9 +129,9 @@ class MailHandler < ActionMailer::Base
else
# ignoring it
end
elsif m = subject.match(ISSUE_REPLY_SUBJECT_RE)
elsif m = email.subject.match(ISSUE_REPLY_SUBJECT_RE)
receive_issue_reply(m[1].to_i)
elsif m = subject.match(MESSAGE_REPLY_SUBJECT_RE)
elsif m = email.subject.match(MESSAGE_REPLY_SUBJECT_RE)
receive_message_reply(m[1].to_i)
else
dispatch_to_default
@@ -167,7 +163,7 @@ class MailHandler < ActionMailer::Base
issue = Issue.new(:author => user, :project => project)
issue.safe_attributes = issue_attributes_from_keywords(issue)
issue.safe_attributes = {'custom_field_values' => custom_field_values_from_keywords(issue)}
issue.subject = cleaned_up_subject
issue.subject = email.subject.to_s.chomp[0,255]
if issue.subject.blank?
issue.subject = '(no subject)'
end
@@ -182,7 +178,7 @@ class MailHandler < ActionMailer::Base
end
# Adds a note to an existing issue
def receive_issue_reply(issue_id, from_journal=nil)
def receive_issue_reply(issue_id)
issue = Issue.find_by_id(issue_id)
return unless issue
# check permission
@@ -197,10 +193,6 @@ class MailHandler < ActionMailer::Base
@@handler_options[:issue].clear
journal = issue.init_journal(user)
if from_journal && from_journal.private_notes?
# If the received email was a reply to a private note, make the added note private
issue.private_notes = true
end
issue.safe_attributes = issue_attributes_from_keywords(issue)
issue.safe_attributes = {'custom_field_values' => custom_field_values_from_keywords(issue)}
journal.notes = cleaned_up_text_body
@@ -216,7 +208,7 @@ class MailHandler < ActionMailer::Base
def receive_journal_reply(journal_id)
journal = Journal.find_by_id(journal_id)
if journal && journal.journalized_type == 'Issue'
receive_issue_reply(journal.journalized_id, journal)
receive_issue_reply(journal.journalized_id)
end
end
@@ -231,7 +223,7 @@ class MailHandler < ActionMailer::Base
end
if !message.locked?
reply = Message.new(:subject => cleaned_up_subject.gsub(%r{^.*msg\d+\]}, '').strip,
reply = Message.new(:subject => email.subject.gsub(%r{^.*msg\d+\]}, '').strip,
:content => cleaned_up_text_body)
reply.author = user
reply.board = message.board
@@ -249,26 +241,9 @@ class MailHandler < ActionMailer::Base
def add_attachments(obj)
if email.attachments && email.attachments.any?
email.attachments.each do |attachment|
filename = attachment.filename
unless filename.respond_to?(:encoding)
# try to reencode to utf8 manually with ruby1.8
h = attachment.header['Content-Disposition']
unless h.nil?
begin
if m = h.value.match(/filename\*[0-9\*]*=([^=']+)'/)
filename = Redmine::CodesetUtil.to_utf8(filename, m[1])
elsif m = h.value.match(/filename=.*=\?([^\?]+)\?[BbQq]\?/)
# http://tools.ietf.org/html/rfc2047#section-4
filename = Redmine::CodesetUtil.to_utf8(filename, m[1])
end
rescue
# nop
end
end
end
obj.attachments << Attachment.create(:container => obj,
:file => attachment.decoded,
:filename => filename,
:filename => attachment.filename,
:author => user,
:content_type => attachment.mime_type)
end
@@ -364,8 +339,8 @@ class MailHandler < ActionMailer::Base
# Returns a Hash of issue custom field values extracted from keywords in the email body
def custom_field_values_from_keywords(customized)
customized.custom_field_values.inject({}) do |h, v|
if keyword = get_keyword(v.custom_field.name, :override => true)
h[v.custom_field.id.to_s] = v.custom_field.value_from_keyword(keyword, customized)
if value = get_keyword(v.custom_field.name, :override => true)
h[v.custom_field.id.to_s] = value
end
h
end
@@ -389,24 +364,6 @@ class MailHandler < ActionMailer::Base
cleanup_body(plain_text_body)
end
def cleaned_up_subject
subject = email.subject.to_s
unless subject.respond_to?(:encoding)
# try to reencode to utf8 manually with ruby1.8
begin
if h = email.header[:subject]
# http://tools.ietf.org/html/rfc2047#section-4
if m = h.value.match(/=\?([^\?]+)\?[BbQq]\?/)
subject = Redmine::CodesetUtil.to_utf8(subject, m[1])
end
end
rescue
# nop
end
end
subject.strip[0,255]
end
def self.full_sanitizer
@full_sanitizer ||= HTML::FullSanitizer.new
end
@@ -491,7 +448,7 @@ class MailHandler < ActionMailer::Base
}
end
if assignee.nil?
assignee ||= assignable.detect {|a| a.name.downcase == keyword}
assignee ||= assignable.detect {|a| a.is_a?(Group) && a.name.downcase == keyword}
end
assignee
end

View File

@@ -62,9 +62,9 @@ class Mailer < ActionMailer::Base
message_id journal
references issue
@author = journal.user
recipients = journal.recipients
recipients = issue.recipients
# Watchers in cc
cc = journal.watcher_recipients - recipients
cc = issue.watcher_recipients - recipients
s = "[#{issue.project.name} - #{issue.tracker.name} ##{issue.id}] "
s << "(#{issue.status.name}) " if journal.new_value_for('status_id')
s << issue.subject
@@ -327,31 +327,22 @@ class Mailer < ActionMailer::Base
# * :days => how many days in the future to remind about (defaults to 7)
# * :tracker => id of tracker for filtering issues (defaults to all trackers)
# * :project => id or identifier of project to process (defaults to all projects)
# * :users => array of user/group ids who should be reminded
# * :users => array of user ids who should be reminded
def self.reminders(options={})
days = options[:days] || 7
project = options[:project] ? Project.find(options[:project]) : nil
tracker = options[:tracker] ? Tracker.find(options[:tracker]) : nil
user_ids = options[:users]
scope = Issue.open.where("#{Issue.table_name}.assigned_to_id IS NOT NULL" +
scope = Issue.open.scoped(:conditions => ["#{Issue.table_name}.assigned_to_id IS NOT NULL" +
" AND #{Project.table_name}.status = #{Project::STATUS_ACTIVE}" +
" AND #{Issue.table_name}.due_date <= ?", days.day.from_now.to_date
" AND #{Issue.table_name}.due_date <= ?", days.day.from_now.to_date]
)
scope = scope.where(:assigned_to_id => user_ids) if user_ids.present?
scope = scope.where(:project_id => project.id) if project
scope = scope.where(:tracker_id => tracker.id) if tracker
issues_by_assignee = scope.includes(:status, :assigned_to, :project, :tracker).all.group_by(&:assigned_to)
issues_by_assignee.keys.each do |assignee|
if assignee.is_a?(Group)
assignee.users.each do |user|
issues_by_assignee[user] ||= []
issues_by_assignee[user] += issues_by_assignee[assignee]
end
end
end
scope = scope.scoped(:conditions => {:assigned_to_id => user_ids}) if user_ids.present?
scope = scope.scoped(:conditions => {:project_id => project.id}) if project
scope = scope.scoped(:conditions => {:tracker_id => tracker.id}) if tracker
issues_by_assignee = scope.all(:include => [:status, :assigned_to, :project, :tracker]).group_by(&:assigned_to)
issues_by_assignee.each do |assignee, issues|
reminder(assignee, issues, days).deliver if assignee.is_a?(User) && assignee.active?
end
@@ -370,9 +361,7 @@ class Mailer < ActionMailer::Base
def self.with_synched_deliveries(&block)
saved_method = ActionMailer::Base.delivery_method
if m = saved_method.to_s.match(%r{^async_(.+)$})
synched_method = m[1]
ActionMailer::Base.delivery_method = synched_method.to_sym
ActionMailer::Base.send "#{synched_method}_settings=", ActionMailer::Base.send("async_#{synched_method}_settings")
ActionMailer::Base.delivery_method = m[1].to_sym
end
yield
ensure

View File

@@ -41,9 +41,9 @@ class Message < ActiveRecord::Base
validates_length_of :subject, :maximum => 255
validate :cannot_reply_to_locked_topic, :on => :create
after_create :add_author_as_watcher, :reset_counters!
after_create :add_author_as_watcher, :update_parent_last_reply
after_update :update_messages_board
after_destroy :reset_counters!
after_destroy :reset_board_counters
scope :visible, lambda {|*args| { :include => {:board => :project},
:conditions => Project.allowed_to_condition(args.shift || User.current, :view_messages, *args) } }
@@ -63,6 +63,13 @@ class Message < ActiveRecord::Base
errors.add :base, 'Topic is locked' if root.locked? && self != root
end
def update_parent_last_reply
if parent
parent.reload.update_attribute(:last_reply_id, self.id)
end
board.reset_counters!
end
def update_messages_board
if board_id_changed?
Message.update_all("board_id = #{board_id}", ["id = ? OR parent_id = ?", root.id, root.id])
@@ -71,10 +78,7 @@ class Message < ActiveRecord::Base
end
end
def reset_counters!
if parent && parent.id
Message.update_all({:last_reply_id => parent.children.maximum(:id)}, {:id => parent.id})
end
def reset_board_counters
board.reset_counters!
end

View File

@@ -19,7 +19,7 @@ class Principal < ActiveRecord::Base
self.table_name = "#{table_name_prefix}users#{table_name_suffix}"
has_many :members, :foreign_key => 'user_id', :dependent => :destroy
has_many :memberships, :class_name => 'Member', :foreign_key => 'user_id', :include => [ :project, :roles ], :conditions => "#{Project.table_name}.status<>#{Project::STATUS_ARCHIVED}", :order => "#{Project.table_name}.name"
has_many :memberships, :class_name => 'Member', :foreign_key => 'user_id', :include => [ :project, :roles ], :conditions => "#{Project.table_name}.status=#{Project::STATUS_ACTIVE}", :order => "#{Project.table_name}.name"
has_many :projects, :through => :memberships
has_many :issue_categories, :foreign_key => 'assigned_to_id', :dependent => :nullify
@@ -27,20 +27,19 @@ class Principal < ActiveRecord::Base
scope :active, :conditions => "#{Principal.table_name}.status = 1"
scope :like, lambda {|q|
q = q.to_s
if q.blank?
where({})
{}
else
q = q.to_s.downcase
pattern = "%#{q}%"
sql = %w(login firstname lastname mail).map {|column| "LOWER(#{table_name}.#{column}) LIKE LOWER(:p)"}.join(" OR ")
sql = "LOWER(login) LIKE :p OR LOWER(firstname) LIKE :p OR LOWER(lastname) LIKE :p OR LOWER(mail) LIKE :p"
params = {:p => pattern}
if q =~ /^(.+)\s+(.+)$/
a, b = "#{$1}%", "#{$2}%"
sql << " OR (LOWER(#{table_name}.firstname) LIKE LOWER(:a) AND LOWER(#{table_name}.lastname) LIKE LOWER(:b))"
sql << " OR (LOWER(#{table_name}.firstname) LIKE LOWER(:b) AND LOWER(#{table_name}.lastname) LIKE LOWER(:a))"
sql << " OR (LOWER(firstname) LIKE :a AND LOWER(lastname) LIKE :b) OR (LOWER(firstname) LIKE :b AND LOWER(lastname) LIKE :a)"
params.merge!(:a => a, :b => b)
end
where(sql, params)
{:conditions => [sql, params]}
end
}
@@ -48,20 +47,20 @@ class Principal < ActiveRecord::Base
scope :member_of, lambda {|projects|
projects = [projects] unless projects.is_a?(Array)
if projects.empty?
where("1=0")
{:conditions => "1=0"}
else
ids = projects.map(&:id)
where("#{Principal.table_name}.status = 1 AND #{Principal.table_name}.id IN (SELECT DISTINCT user_id FROM #{Member.table_name} WHERE project_id IN (?))", ids)
{:conditions => ["#{Principal.table_name}.status = 1 AND #{Principal.table_name}.id IN (SELECT DISTINCT user_id FROM #{Member.table_name} WHERE project_id IN (?))", ids]}
end
}
# Principals that are not members of projects
scope :not_member_of, lambda {|projects|
projects = [projects] unless projects.is_a?(Array)
if projects.empty?
where("1=0")
{:conditions => "1=0"}
else
ids = projects.map(&:id)
where("#{Principal.table_name}.id NOT IN (SELECT DISTINCT user_id FROM #{Member.table_name} WHERE project_id IN (?))", ids)
{:conditions => ["#{Principal.table_name}.id NOT IN (SELECT DISTINCT user_id FROM #{Member.table_name} WHERE project_id IN (?))", ids]}
end
}

View File

@@ -20,7 +20,6 @@ class Project < ActiveRecord::Base
# Project statuses
STATUS_ACTIVE = 1
STATUS_CLOSED = 5
STATUS_ARCHIVED = 9
# Maximum length for project identifiers
@@ -28,7 +27,7 @@ class Project < ActiveRecord::Base
# Specific overidden Activities
has_many :time_entry_activities
has_many :members, :include => [:principal, :roles], :conditions => "#{User.table_name}.type='User' AND #{User.table_name}.status=#{User::STATUS_ACTIVE}"
has_many :members, :include => [:user, :roles], :conditions => "#{User.table_name}.type='User' AND #{User.table_name}.status=#{User::STATUS_ACTIVE}"
has_many :memberships, :class_name => 'Member'
has_many :member_principals, :class_name => 'Member',
:include => :principal,
@@ -81,7 +80,6 @@ class Project < ActiveRecord::Base
# reserved words
validates_exclusion_of :identifier, :in => %w( new )
after_save :update_position_under_parent, :if => Proc.new {|project| project.name_changed?}
before_destroy :delete_all_members
scope :has_module, lambda { |mod| { :conditions => ["#{Project.table_name}.id IN (SELECT em.project_id FROM #{EnabledModule.table_name} em WHERE em.name=?)", mod.to_s] } }
@@ -123,7 +121,7 @@ class Project < ActiveRecord::Base
self.enabled_module_names = Setting.default_projects_modules
end
if !initialized.key?('trackers') && !initialized.key?('tracker_ids')
self.trackers = Tracker.sorted.all
self.trackers = Tracker.all
end
end
@@ -163,11 +161,12 @@ class Project < ActiveRecord::Base
# * :with_subprojects => limit the condition to project and its subprojects
# * :member => limit the condition to the user projects
def self.allowed_to_condition(user, permission, options={})
perm = Redmine::AccessControl.permission(permission)
base_statement = (perm && perm.read? ? "#{Project.table_name}.status <> #{Project::STATUS_ARCHIVED}" : "#{Project.table_name}.status = #{Project::STATUS_ACTIVE}")
if perm && perm.project_module
# If the permission belongs to a project module, make sure the module is enabled
base_statement << " AND #{Project.table_name}.id IN (SELECT em.project_id FROM #{EnabledModule.table_name} em WHERE em.name='#{perm.project_module}')"
base_statement = "#{Project.table_name}.status=#{Project::STATUS_ACTIVE}"
if perm = Redmine::AccessControl.permission(permission)
unless perm.project_module.nil?
# If the permission belongs to a project module, make sure the module is enabled
base_statement << " AND #{Project.table_name}.id IN (SELECT em.project_id FROM #{EnabledModule.table_name} em WHERE em.name='#{perm.project_module}')"
end
end
if options[:project]
project_statement = "#{Project.table_name}.id = #{options[:project].id}"
@@ -187,7 +186,7 @@ class Project < ActiveRecord::Base
end
if user.logged?
user.projects_by_role.each do |role, projects|
if role.allowed_to?(permission) && projects.any?
if role.allowed_to?(permission)
statement_by_role[role] = "#{Project.table_name}.id IN (#{projects.collect(&:id).join(',')})"
end
end
@@ -326,14 +325,6 @@ class Project < ActiveRecord::Base
update_attribute :status, STATUS_ACTIVE
end
def close
self_and_descendants.status(STATUS_ACTIVE).update_all :status => STATUS_CLOSED
end
def reopen
self_and_descendants.status(STATUS_CLOSED).update_all :status => STATUS_ACTIVE
end
# Returns an array of projects the project can be moved to
# by the current user
def allowed_parents
@@ -384,7 +375,22 @@ class Project < ActiveRecord::Base
# Nothing to do
true
elsif p.nil? || (p.active? && move_possible?(p))
set_or_update_position_under(p)
# Insert the project so that target's children or root projects stay alphabetically sorted
sibs = (p.nil? ? self.class.roots : p.children)
to_be_inserted_before = sibs.detect {|c| c.name.to_s.downcase > name.to_s.downcase }
if to_be_inserted_before
move_to_left_of(to_be_inserted_before)
elsif p.nil?
if sibs.empty?
# move_to_root adds the project in first (ie. left) position
move_to_root
else
move_to_right_of(sibs.last) unless self == sibs.last
end
else
# move_to_child_of adds the project in last (ie.right) position
move_to_child_of(p)
end
Issue.update_versions_from_hierarchy_change(self)
true
else
@@ -393,22 +399,12 @@ class Project < ActiveRecord::Base
end
end
# Recalculates all lft and rgt values based on project names
# Unlike Project.rebuild!, these values are recalculated even if the tree "looks" valid
# Used in BuildProjectsTree migration
def self.rebuild_tree!
transaction do
update_all "lft = NULL, rgt = NULL"
rebuild!(false)
end
end
# Returns an array of the trackers used by the project and its active sub projects
def rolled_up_trackers
@rolled_up_trackers ||=
Tracker.find(:all, :joins => :projects,
:select => "DISTINCT #{Tracker.table_name}.*",
:conditions => ["#{Project.table_name}.lft >= ? AND #{Project.table_name}.rgt <= ? AND #{Project.table_name}.status <> #{STATUS_ARCHIVED}", lft, rgt],
:conditions => ["#{Project.table_name}.lft >= ? AND #{Project.table_name}.rgt <= ? AND #{Project.table_name}.status = #{STATUS_ACTIVE}", lft, rgt],
:order => "#{Tracker.table_name}.position")
end
@@ -427,20 +423,20 @@ class Project < ActiveRecord::Base
def rolled_up_versions
@rolled_up_versions ||=
Version.scoped(:include => :project,
:conditions => ["#{Project.table_name}.lft >= ? AND #{Project.table_name}.rgt <= ? AND #{Project.table_name}.status <> #{STATUS_ARCHIVED}", lft, rgt])
:conditions => ["#{Project.table_name}.lft >= ? AND #{Project.table_name}.rgt <= ? AND #{Project.table_name}.status = #{STATUS_ACTIVE}", lft, rgt])
end
# Returns a scope of the Versions used by the project
def shared_versions
if new_record?
Version.scoped(:include => :project,
:conditions => "#{Project.table_name}.status <> #{Project::STATUS_ARCHIVED} AND #{Version.table_name}.sharing = 'system'")
:conditions => "#{Project.table_name}.status = #{Project::STATUS_ACTIVE} AND #{Version.table_name}.sharing = 'system'")
else
@shared_versions ||= begin
r = root? ? self : root
Version.scoped(:include => :project,
:conditions => "#{Project.table_name}.id = #{id}" +
" OR (#{Project.table_name}.status <> #{Project::STATUS_ARCHIVED} AND (" +
" OR (#{Project.table_name}.status = #{Project::STATUS_ACTIVE} AND (" +
" #{Version.table_name}.sharing = 'system'" +
" OR (#{Project.table_name}.lft >= #{r.lft} AND #{Project.table_name}.rgt <= #{r.rgt} AND #{Version.table_name}.sharing = 'tree')" +
" OR (#{Project.table_name}.lft < #{lft} AND #{Project.table_name}.rgt > #{rgt} AND #{Version.table_name}.sharing IN ('hierarchy', 'descendants'))" +
@@ -482,7 +478,7 @@ class Project < ActiveRecord::Base
# Returns the users that should be notified on project events
def notified_users
# TODO: User part should be extracted to User#notify_about?
members.select {|m| m.principal.present? && (m.mail_notification? || m.principal.mail_notification == 'all')}.collect {|m| m.principal}
members.select {|m| m.mail_notification? || m.user.mail_notification == 'all'}.collect {|m| m.user}
end
# Returns an array of all custom fields enabled for project issues
@@ -519,13 +515,6 @@ class Project < ActiveRecord::Base
s << ' root' if root?
s << ' child' if child?
s << (leaf? ? ' leaf' : ' parent')
unless active?
if archived?
s << ' archived'
else
s << ' closed'
end
end
s
end
@@ -569,20 +558,11 @@ class Project < ActiveRecord::Base
end
end
# Return true if this project allows to do the specified action.
# Return true if this project is allowed to do the specified action.
# action can be:
# * a parameter-like Hash (eg. :controller => 'projects', :action => 'edit')
# * a permission Symbol (eg. :edit_project)
def allows_to?(action)
if archived?
# No action allowed on archived projects
return false
end
unless active? || Redmine::AccessControl.read_action?(action)
# No write action allowed on closed projects
return false
end
# No action allowed on disabled modules
if action.is_a? Hash
allowed_actions.include? "#{action[:controller]}/#{action[:action]}"
else
@@ -731,7 +711,7 @@ class Project < ActiveRecord::Base
def copy_wiki(project)
# Check that the source project has a wiki first
unless project.wiki.nil?
wiki = self.wiki || Wiki.new
self.wiki ||= Wiki.new
wiki.attributes = project.wiki.attributes.dup.except("id", "project_id")
wiki_pages_map = {}
project.wiki.pages.each do |page|
@@ -743,8 +723,6 @@ class Project < ActiveRecord::Base
wiki.pages << new_wiki_page
wiki_pages_map[page.id] = new_wiki_page
end
self.wiki = wiki
wiki.save
# Reproduce page hierarchy
project.wiki.pages.each do |page|
@@ -775,30 +753,27 @@ class Project < ActiveRecord::Base
end
# Copies issues from +project+
# Note: issues assigned to a closed version won't be copied due to validation rules
def copy_issues(project)
# Stores the source issue id as a key and the copied issues as the
# value. Used to map the two togeather for issue relations.
issues_map = {}
# Store status and reopen locked/closed versions
version_statuses = versions.reject(&:open?).map {|version| [version, version.status]}
version_statuses.each do |version, status|
version.update_attribute :status, 'open'
end
# Get issues sorted by root_id, lft so that parent issues
# get copied before their children
project.issues.find(:all, :order => 'root_id, lft').each do |issue|
new_issue = Issue.new
new_issue.copy_from(issue, :subtasks => false, :link => false)
new_issue.copy_from(issue)
new_issue.project = self
# Reassign fixed_versions by name, since names are unique per project
if issue.fixed_version && issue.fixed_version.project == project
new_issue.fixed_version = self.versions.detect {|v| v.name == issue.fixed_version.name}
# Reassign fixed_versions by name, since names are unique per
# project and the versions for self are not yet saved
if issue.fixed_version
new_issue.fixed_version = self.versions.select {|v| v.name == issue.fixed_version.name}.first
end
# Reassign the category by name, since names are unique per project
# Reassign the category by name, since names are unique per
# project and the categories for self are not yet saved
if issue.category
new_issue.category = self.issue_categories.detect {|c| c.name == issue.category.name}
new_issue.category = self.issue_categories.select {|c| c.name == issue.category.name}.first
end
# Parent issue
if issue.parent_id
@@ -815,11 +790,6 @@ class Project < ActiveRecord::Base
end
end
# Restore locked/closed version statuses
version_statuses.each do |version, status|
version.update_attribute :status, status
end
# Relations after in case issues related each other
project.issues.each do |issue|
new_issue = issues_map[issue.id]
@@ -949,28 +919,4 @@ class Project < ActiveRecord::Base
end
update_attribute :status, STATUS_ARCHIVED
end
def update_position_under_parent
set_or_update_position_under(parent)
end
# Inserts/moves the project so that target's children or root projects stay alphabetically sorted
def set_or_update_position_under(target_parent)
sibs = (target_parent.nil? ? self.class.roots : target_parent.children)
to_be_inserted_before = sibs.sort_by {|c| c.name.to_s.downcase}.detect {|c| c.name.to_s.downcase > name.to_s.downcase }
if to_be_inserted_before
move_to_left_of(to_be_inserted_before)
elsif target_parent.nil?
if sibs.empty?
# move_to_root adds the project in first (ie. left) position
move_to_root
else
move_to_right_of(sibs.last) unless self == sibs.last
end
else
# move_to_child_of adds the project in last (ie.right) position
move_to_child_of(target_parent)
end
end
end

View File

@@ -27,7 +27,6 @@ class QueryColumn
self.groupable = name.to_s
end
self.default_order = options[:default_order]
@inline = options.key?(:inline) ? options[:inline] : true
@caption_key = options[:caption] || "field_#{name}"
end
@@ -39,15 +38,11 @@ class QueryColumn
def sortable?
!@sortable.nil?
end
def sortable
@sortable.is_a?(Proc) ? @sortable.call : @sortable
end
def inline?
@inline
end
def value(issue)
issue.send name
end
@@ -62,8 +57,10 @@ class QueryCustomFieldColumn < QueryColumn
def initialize(custom_field)
self.name = "cf_#{custom_field.id}".to_sym
self.sortable = custom_field.order_statement || false
self.groupable = custom_field.group_statement || false
@inline = true
if %w(list date bool int).include?(custom_field.field_format) && !custom_field.multiple?
self.groupable = custom_field.order_statement
end
self.groupable ||= false
@cf = custom_field
end
@@ -77,7 +74,7 @@ class QueryCustomFieldColumn < QueryColumn
def value(issue)
cv = issue.custom_values.select {|v| v.custom_field_id == @cf.id}.collect {|v| @cf.cast_value(v.value)}
cv.size > 1 ? cv.sort {|a,b| a.to_s <=> b.to_s} : cv.first
cv.size > 1 ? cv : cv.first
end
def css_classes
@@ -106,25 +103,20 @@ class Query < ActiveRecord::Base
"o" => :label_open_issues,
"c" => :label_closed_issues,
"!*" => :label_none,
"*" => :label_any,
"*" => :label_all,
">=" => :label_greater_or_equal,
"<=" => :label_less_or_equal,
"><" => :label_between,
"<t+" => :label_in_less_than,
">t+" => :label_in_more_than,
"><t+"=> :label_in_the_next_days,
"t+" => :label_in,
"t" => :label_today,
"w" => :label_this_week,
">t-" => :label_less_than_ago,
"<t-" => :label_more_than_ago,
"><t-"=> :label_in_the_past_days,
"t-" => :label_ago,
"~" => :label_contains,
"!~" => :label_not_contains,
"=p" => :label_any_issues_in_project,
"=!p" => :label_any_issues_not_in_project,
"!p" => :label_no_issues_in_project}
"!~" => :label_not_contains }
cattr_reader :operators
@@ -132,13 +124,12 @@ class Query < ActiveRecord::Base
:list_status => [ "o", "=", "!", "c", "*" ],
:list_optional => [ "=", "!", "!*", "*" ],
:list_subprojects => [ "*", "!*", "=" ],
:date => [ "=", ">=", "<=", "><", "<t+", ">t+", "><t+", "t+", "t", "w", ">t-", "<t-", "><t-", "t-", "!*", "*" ],
:date_past => [ "=", ">=", "<=", "><", ">t-", "<t-", "><t-", "t-", "t", "w", "!*", "*" ],
:date => [ "=", ">=", "<=", "><", "<t+", ">t+", "t+", "t", "w", ">t-", "<t-", "t-", "!*", "*" ],
:date_past => [ "=", ">=", "<=", "><", ">t-", "<t-", "t-", "t", "w", "!*", "*" ],
:string => [ "=", "~", "!", "!~", "!*", "*" ],
:text => [ "~", "!~", "!*", "*" ],
:integer => [ "=", ">=", "<=", "><", "!*", "*" ],
:float => [ "=", ">=", "<=", "><", "!*", "*" ],
:relation => ["=", "=p", "=!p", "!p", "!*", "*"]}
:float => [ "=", ">=", "<=", "><", "!*", "*" ] }
cattr_reader :operators_by_filter_type
@@ -153,14 +144,12 @@ class Query < ActiveRecord::Base
QueryColumn.new(:assigned_to, :sortable => lambda {User.fields_for_order_statement}, :groupable => true),
QueryColumn.new(:updated_on, :sortable => "#{Issue.table_name}.updated_on", :default_order => 'desc'),
QueryColumn.new(:category, :sortable => "#{IssueCategory.table_name}.name", :groupable => true),
QueryColumn.new(:fixed_version, :sortable => lambda {Version.fields_for_order_statement}, :groupable => true),
QueryColumn.new(:fixed_version, :sortable => ["#{Version.table_name}.effective_date", "#{Version.table_name}.name"], :default_order => 'desc', :groupable => true),
QueryColumn.new(:start_date, :sortable => "#{Issue.table_name}.start_date"),
QueryColumn.new(:due_date, :sortable => "#{Issue.table_name}.due_date"),
QueryColumn.new(:estimated_hours, :sortable => "#{Issue.table_name}.estimated_hours"),
QueryColumn.new(:done_ratio, :sortable => "#{Issue.table_name}.done_ratio", :groupable => true),
QueryColumn.new(:created_on, :sortable => "#{Issue.table_name}.created_on", :default_order => 'desc'),
QueryColumn.new(:relations, :caption => :label_related_issues),
QueryColumn.new(:description, :inline => false)
]
cattr_reader :available_columns
@@ -185,14 +174,14 @@ class Query < ActiveRecord::Base
if values_for(field)
case type_for(field)
when :integer
add_filter_error(field, :invalid) if values_for(field).detect {|v| v.present? && !v.match(/^[+-]?\d+$/) }
add_filter_error(field, :invalid) if values_for(field).detect {|v| v.present? && !v.match(/^\d+$/) }
when :float
add_filter_error(field, :invalid) if values_for(field).detect {|v| v.present? && !v.match(/^[+-]?\d+(\.\d*)?$/) }
add_filter_error(field, :invalid) if values_for(field).detect {|v| v.present? && !v.match(/^\d+(\.\d*)?$/) }
when :date, :date_past
case operator_for(field)
when "=", ">=", "<=", "><"
add_filter_error(field, :invalid) if values_for(field).detect {|v| v.present? && (!v.match(/^\d{4}-\d{2}-\d{2}$/) || (Date.parse(v) rescue nil).nil?) }
when ">t-", "<t-", "t-", ">t+", "<t+", "t+", "><t+", "><t-"
when ">t-", "<t-", "t-"
add_filter_error(field, :invalid) if values_for(field).detect {|v| v.present? && !v.match(/^\d+$/) }
end
end
@@ -224,68 +213,48 @@ class Query < ActiveRecord::Base
is_public && !@is_for_all && user.allowed_to?(:manage_public_queries, project)
end
def trackers
@trackers ||= project.nil? ? Tracker.find(:all, :order => 'position') : project.rolled_up_trackers
end
# Returns a hash of localized labels for all filter operators
def self.operators_labels
operators.inject({}) {|h, operator| h[operator.first] = l(operator.last); h}
end
def available_filters
return @available_filters if @available_filters
@available_filters = {
"status_id" => {
:type => :list_status, :order => 0,
:values => IssueStatus.find(:all, :order => 'position').collect{|s| [s.name, s.id.to_s] }
},
"tracker_id" => {
:type => :list, :order => 2, :values => trackers.collect{|s| [s.name, s.id.to_s] }
},
"priority_id" => {
:type => :list, :order => 3, :values => IssuePriority.all.collect{|s| [s.name, s.id.to_s] }
},
"subject" => { :type => :text, :order => 8 },
"created_on" => { :type => :date_past, :order => 9 },
"updated_on" => { :type => :date_past, :order => 10 },
"start_date" => { :type => :date, :order => 11 },
"due_date" => { :type => :date, :order => 12 },
"estimated_hours" => { :type => :float, :order => 13 },
"done_ratio" => { :type => :integer, :order => 14 }
}
IssueRelation::TYPES.each do |relation_type, options|
@available_filters[relation_type] = {
:type => :relation, :order => @available_filters.size + 100,
:label => options[:name]
}
end
trackers = project.nil? ? Tracker.find(:all, :order => 'position') : project.rolled_up_trackers
@available_filters = { "status_id" => { :type => :list_status, :order => 1, :values => IssueStatus.find(:all, :order => 'position').collect{|s| [s.name, s.id.to_s] } },
"tracker_id" => { :type => :list, :order => 2, :values => trackers.collect{|s| [s.name, s.id.to_s] } },
"priority_id" => { :type => :list, :order => 3, :values => IssuePriority.all.collect{|s| [s.name, s.id.to_s] } },
"subject" => { :type => :text, :order => 8 },
"created_on" => { :type => :date_past, :order => 9 },
"updated_on" => { :type => :date_past, :order => 10 },
"start_date" => { :type => :date, :order => 11 },
"due_date" => { :type => :date, :order => 12 },
"estimated_hours" => { :type => :float, :order => 13 },
"done_ratio" => { :type => :integer, :order => 14 }}
principals = []
if project
principals += project.principals.sort
unless project.leaf?
subprojects = project.descendants.visible.all
if subprojects.any?
@available_filters["subproject_id"] = {
:type => :list_subprojects, :order => 13,
:values => subprojects.collect{|s| [s.name, s.id.to_s] }
}
@available_filters["subproject_id"] = { :type => :list_subprojects, :order => 13, :values => subprojects.collect{|s| [s.name, s.id.to_s] } }
principals += Principal.member_of(subprojects)
end
end
else
all_projects = Project.visible.all
if all_projects.any?
# members of visible projects
principals += Principal.member_of(all_projects)
# project filter
project_values = []
if User.current.logged? && User.current.memberships.any?
project_values << ["<< #{l(:label_my_projects).downcase} >>", "mine"]
end
project_values += all_projects_values
@available_filters["project_id"] = {
:type => :list, :order => 1, :values => project_values
} unless project_values.empty?
Project.project_tree(all_projects) do |p, level|
prefix = (level > 0 ? ('--' * level + ' ') : '')
project_values << ["#{prefix}#{p.name}", p.id.to_s]
end
@available_filters["project_id"] = { :type => :list, :order => 1, :values => project_values} unless project_values.empty?
end
end
principals.uniq!
@@ -294,111 +263,46 @@ class Query < ActiveRecord::Base
assigned_to_values = []
assigned_to_values << ["<< #{l(:label_me)} >>", "me"] if User.current.logged?
assigned_to_values += (Setting.issue_group_assignment? ?
principals : users).collect{|s| [s.name, s.id.to_s] }
@available_filters["assigned_to_id"] = {
:type => :list_optional, :order => 4, :values => assigned_to_values
} unless assigned_to_values.empty?
assigned_to_values += (Setting.issue_group_assignment? ? principals : users).collect{|s| [s.name, s.id.to_s] }
@available_filters["assigned_to_id"] = { :type => :list_optional, :order => 4, :values => assigned_to_values } unless assigned_to_values.empty?
author_values = []
author_values << ["<< #{l(:label_me)} >>", "me"] if User.current.logged?
author_values += users.collect{|s| [s.name, s.id.to_s] }
@available_filters["author_id"] = {
:type => :list, :order => 5, :values => author_values
} unless author_values.empty?
@available_filters["author_id"] = { :type => :list, :order => 5, :values => author_values } unless author_values.empty?
group_values = Group.all.collect {|g| [g.name, g.id.to_s] }
@available_filters["member_of_group"] = {
:type => :list_optional, :order => 6, :values => group_values
} unless group_values.empty?
@available_filters["member_of_group"] = { :type => :list_optional, :order => 6, :values => group_values } unless group_values.empty?
role_values = Role.givable.collect {|r| [r.name, r.id.to_s] }
@available_filters["assigned_to_role"] = {
:type => :list_optional, :order => 7, :values => role_values
} unless role_values.empty?
@available_filters["assigned_to_role"] = { :type => :list_optional, :order => 7, :values => role_values } unless role_values.empty?
if User.current.logged?
@available_filters["watcher_id"] = {
:type => :list, :order => 15, :values => [["<< #{l(:label_me)} >>", "me"]]
}
@available_filters["watcher_id"] = { :type => :list, :order => 15, :values => [["<< #{l(:label_me)} >>", "me"]] }
end
if project
# project specific filters
categories = project.issue_categories.all
unless categories.empty?
@available_filters["category_id"] = {
:type => :list_optional, :order => 6,
:values => categories.collect{|s| [s.name, s.id.to_s] }
}
@available_filters["category_id"] = { :type => :list_optional, :order => 6, :values => categories.collect{|s| [s.name, s.id.to_s] } }
end
versions = project.shared_versions.all
unless versions.empty?
@available_filters["fixed_version_id"] = {
:type => :list_optional, :order => 7,
:values => versions.sort.collect{|s| ["#{s.project.name} - #{s.name}", s.id.to_s] }
}
@available_filters["fixed_version_id"] = { :type => :list_optional, :order => 7, :values => versions.sort.collect{|s| ["#{s.project.name} - #{s.name}", s.id.to_s] } }
end
add_custom_fields_filters(project.all_issue_custom_fields)
else
# global filters for cross project issue list
system_shared_versions = Version.visible.find_all_by_sharing('system')
unless system_shared_versions.empty?
@available_filters["fixed_version_id"] = {
:type => :list_optional, :order => 7,
:values => system_shared_versions.sort.collect{|s|
["#{s.project.name} - #{s.name}", s.id.to_s]
}
}
@available_filters["fixed_version_id"] = { :type => :list_optional, :order => 7, :values => system_shared_versions.sort.collect{|s| ["#{s.project.name} - #{s.name}", s.id.to_s] } }
end
add_custom_fields_filters(
IssueCustomField.find(:all,
:conditions => {
:is_filter => true,
:is_for_all => true
}))
end
add_associations_custom_fields_filters :project, :author, :assigned_to, :fixed_version
if User.current.allowed_to?(:set_issues_private, nil, :global => true) ||
User.current.allowed_to?(:set_own_issues_private, nil, :global => true)
@available_filters["is_private"] = {
:type => :list, :order => 16,
:values => [[l(:general_text_yes), "1"], [l(:general_text_no), "0"]]
}
end
Tracker.disabled_core_fields(trackers).each {|field|
@available_filters.delete field
}
@available_filters.each do |field, options|
options[:name] ||= l(options[:label] || "field_#{field}".gsub(/_id$/, ''))
add_custom_fields_filters(IssueCustomField.find(:all, :conditions => {:is_filter => true, :is_for_all => true}))
end
@available_filters
end
# Returns a representation of the available filters for JSON serialization
def available_filters_as_json
json = {}
available_filters.each do |field, options|
json[field] = options.slice(:type, :name, :values).stringify_keys
end
json
end
def all_projects
@all_projects ||= Project.visible.all
end
def all_projects_values
return @all_projects_values if @all_projects_values
values = []
Project.project_tree(all_projects) do |p, level|
prefix = (level > 0 ? ('--' * level + ' ') : '')
values << ["#{prefix}#{p.name}", p.id.to_s]
end
@all_projects_values = values
end
def add_filter(field, operator, values)
# values must be an array
return unless values.nil? || values.is_a?(Array)
@@ -476,17 +380,6 @@ class Query < ActiveRecord::Base
:caption => :label_spent_time
)
end
if User.current.allowed_to?(:set_issues_private, nil, :global => true) ||
User.current.allowed_to?(:set_own_issues_private, nil, :global => true)
@available_columns << QueryColumn.new(:is_private, :sortable => "#{Issue.table_name}.is_private")
end
disabled_fields = Tracker.disabled_core_fields(trackers).map {|field| field.sub(/_id$/, '')}
@available_columns.reject! {|column|
disabled_fields.include?(column.name.to_s)
}
@available_columns
end
@@ -518,22 +411,6 @@ class Query < ActiveRecord::Base
end.compact
end
def inline_columns
columns.select(&:inline?)
end
def block_columns
columns.reject(&:inline?)
end
def available_inline_columns
available_columns.select(&:inline?)
end
def available_block_columns
available_columns.reject(&:inline?)
end
def default_columns_names
@default_columns_names ||= begin
default_columns = Setting.issue_list_default_columns.map(&:to_sym)
@@ -567,7 +444,7 @@ class Query < ActiveRecord::Base
if arg.is_a?(Hash)
arg = arg.keys.sort.collect {|k| arg[k]}
end
c = arg.select {|k,o| !k.to_s.blank?}.slice(0,3).collect {|k,o| [k.to_s, (o == 'desc' || o == false) ? 'desc' : 'asc']}
c = arg.select {|k,o| !k.to_s.blank?}.slice(0,3).collect {|k,o| [k.to_s, o == 'desc' ? o : 'asc']}
write_attribute(:sort_criteria, c)
end
@@ -583,17 +460,12 @@ class Query < ActiveRecord::Base
sort_criteria && sort_criteria[arg] && sort_criteria[arg].last
end
def sort_criteria_order_for(key)
sort_criteria.detect {|k, order| key.to_s == k}.try(:last)
end
# Returns the SQL sort order that should be prepended for grouping
def group_by_sort_order
if grouped? && (column = group_by_column)
order = sort_criteria_order_for(column.name) || column.default_order
column.sortable.is_a?(Array) ?
column.sortable.collect {|s| "#{s} #{order}"}.join(',') :
"#{column.sortable} #{order}"
column.sortable.collect {|s| "#{s} #{column.default_order}"}.join(',') :
"#{column.sortable} #{column.default_order}"
end
end
@@ -662,7 +534,7 @@ class Query < ActiveRecord::Base
end
end
if field =~ /cf_(\d+)$/
if field =~ /^cf_(\d+)$/
# custom field
filters_clauses << sql_for_custom_field(field, operator, v, $1)
elsif respond_to?("sql_for_#{field}_field")
@@ -712,20 +584,19 @@ class Query < ActiveRecord::Base
def issues(options={})
order_option = [group_by_sort_order, options[:order]].reject {|s| s.blank?}.join(',')
order_option = nil if order_option.blank?
joins = (order_option && order_option.include?('authors')) ? "LEFT OUTER JOIN users authors ON authors.id = #{Issue.table_name}.author_id" : nil
issues = Issue.visible.scoped(:conditions => options[:conditions]).find :all, :include => ([:status, :project] + (options[:include] || [])).uniq,
:conditions => statement,
:order => order_option,
:joins => joins_for_order_statement(order_option),
:joins => joins,
:limit => options[:limit],
:offset => options[:offset]
if has_column?(:spent_hours)
Issue.load_visible_spent_hours(issues)
end
if has_column?(:relations)
Issue.load_visible_relations(issues)
end
issues
rescue ::ActiveRecord::StatementInvalid => e
raise StatementInvalid.new(e.message)
@@ -735,11 +606,13 @@ class Query < ActiveRecord::Base
def issue_ids(options={})
order_option = [group_by_sort_order, options[:order]].reject {|s| s.blank?}.join(',')
order_option = nil if order_option.blank?
joins = (order_option && order_option.include?('authors')) ? "LEFT OUTER JOIN users authors ON authors.id = #{Issue.table_name}.author_id" : nil
Issue.visible.scoped(:conditions => options[:conditions]).scoped(:include => ([:status, :project] + (options[:include] || [])).uniq,
:conditions => statement,
:order => order_option,
:joins => joins_for_order_statement(order_option),
:joins => joins,
:limit => options[:limit],
:offset => options[:offset]).find_ids
rescue ::ActiveRecord::StatementInvalid => e
@@ -802,10 +675,10 @@ class Query < ActiveRecord::Base
"(#{nl} #{Issue.table_name}.assigned_to_id #{sw} IN (SELECT DISTINCT #{Member.table_name}.user_id FROM #{Member.table_name}" +
" WHERE #{Member.table_name}.project_id = #{Issue.table_name}.project_id))"
when "=", "!"
role_cond = value.any? ?
role_cond = value.any? ?
"#{MemberRole.table_name}.role_id IN (" + value.collect{|val| "'#{connection.quote_string(val)}'"}.join(",") + ")" :
"1=0"
sw = operator == "!" ? 'NOT' : ''
nl = operator == "!" ? "#{Issue.table_name}.assigned_to_id IS NULL OR" : ''
"(#{nl} #{Issue.table_name}.assigned_to_id #{sw} IN (SELECT DISTINCT #{Member.table_name}.user_id FROM #{Member.table_name}, #{MemberRole.table_name}" +
@@ -813,57 +686,13 @@ class Query < ActiveRecord::Base
end
end
def sql_for_is_private_field(field, operator, value)
op = (operator == "=" ? 'IN' : 'NOT IN')
va = value.map {|v| v == '0' ? connection.quoted_false : connection.quoted_true}.uniq.join(',')
"#{Issue.table_name}.is_private #{op} (#{va})"
end
def sql_for_relations(field, operator, value, options={})
relation_options = IssueRelation::TYPES[field]
return relation_options unless relation_options
relation_type = field
join_column, target_join_column = "issue_from_id", "issue_to_id"
if relation_options[:reverse] || options[:reverse]
relation_type = relation_options[:reverse] || relation_type
join_column, target_join_column = target_join_column, join_column
end
sql = case operator
when "*", "!*"
op = (operator == "*" ? 'IN' : 'NOT IN')
"#{Issue.table_name}.id #{op} (SELECT DISTINCT #{IssueRelation.table_name}.#{join_column} FROM #{IssueRelation.table_name} WHERE #{IssueRelation.table_name}.relation_type = '#{connection.quote_string(relation_type)}')"
when "=", "!"
op = (operator == "=" ? 'IN' : 'NOT IN')
"#{Issue.table_name}.id #{op} (SELECT DISTINCT #{IssueRelation.table_name}.#{join_column} FROM #{IssueRelation.table_name} WHERE #{IssueRelation.table_name}.relation_type = '#{connection.quote_string(relation_type)}' AND #{IssueRelation.table_name}.#{target_join_column} = #{value.first.to_i})"
when "=p", "=!p", "!p"
op = (operator == "!p" ? 'NOT IN' : 'IN')
comp = (operator == "=!p" ? '<>' : '=')
"#{Issue.table_name}.id #{op} (SELECT DISTINCT #{IssueRelation.table_name}.#{join_column} FROM #{IssueRelation.table_name}, #{Issue.table_name} relissues WHERE #{IssueRelation.table_name}.relation_type = '#{connection.quote_string(relation_type)}' AND #{IssueRelation.table_name}.#{target_join_column} = relissues.id AND relissues.project_id #{comp} #{value.first.to_i})"
end
if relation_options[:sym] == field && !options[:reverse]
sqls = [sql, sql_for_relations(field, operator, value, :reverse => true)]
sqls.join(["!", "!*", "!p"].include?(operator) ? " AND " : " OR ")
else
sql
end
end
IssueRelation::TYPES.keys.each do |relation_type|
alias_method "sql_for_#{relation_type}_field".to_sym, :sql_for_relations
end
private
def sql_for_custom_field(field, operator, value, custom_field_id)
db_table = CustomValue.table_name
db_field = 'value'
filter = @available_filters[field]
return nil unless filter
if filter[:format] == 'user'
if filter && filter[:format] == 'user'
if value.delete('me')
value.push User.current.id.to_s
end
@@ -874,15 +703,7 @@ class Query < ActiveRecord::Base
operator = '='
not_in = 'NOT'
end
customized_key = "id"
customized_class = Issue
if field =~ /^(.+)\.cf_/
assoc = $1
customized_key = "#{assoc}_id"
customized_class = Issue.reflect_on_association(assoc.to_sym).klass.base_class rescue nil
raise "Unknown Issue association #{assoc}" unless customized_class
end
"#{Issue.table_name}.#{customized_key} #{not_in} IN (SELECT #{customized_class.table_name}.id FROM #{customized_class.table_name} LEFT OUTER JOIN #{db_table} ON #{db_table}.customized_type='#{customized_class}' AND #{db_table}.customized_id=#{customized_class.table_name}.id AND #{db_table}.custom_field_id=#{custom_field_id} WHERE " +
"#{Issue.table_name}.id #{not_in} IN (SELECT #{Issue.table_name}.id FROM #{Issue.table_name} LEFT OUTER JOIN #{db_table} ON #{db_table}.customized_type='Issue' AND #{db_table}.customized_id=#{Issue.table_name}.id AND #{db_table}.custom_field_id=#{custom_field_id} WHERE " +
sql_for_field(field, operator, value, db_table, db_field, true) + ')'
end
@@ -961,35 +782,21 @@ class Query < ActiveRecord::Base
sql = "#{Issue.table_name}.status_id IN (SELECT id FROM #{IssueStatus.table_name} WHERE is_closed=#{connection.quoted_false})" if field == "status_id"
when "c"
sql = "#{Issue.table_name}.status_id IN (SELECT id FROM #{IssueStatus.table_name} WHERE is_closed=#{connection.quoted_true})" if field == "status_id"
when "><t-"
# between today - n days and today
sql = relative_date_clause(db_table, db_field, - value.first.to_i, 0)
when ">t-"
# >= today - n days
sql = relative_date_clause(db_table, db_field, - value.first.to_i, nil)
sql = relative_date_clause(db_table, db_field, - value.first.to_i, 0)
when "<t-"
# <= today - n days
sql = relative_date_clause(db_table, db_field, nil, - value.first.to_i)
when "t-"
# = n days in past
sql = relative_date_clause(db_table, db_field, - value.first.to_i, - value.first.to_i)
when "><t+"
# between today and today + n days
sql = relative_date_clause(db_table, db_field, 0, value.first.to_i)
when ">t+"
# >= today + n days
sql = relative_date_clause(db_table, db_field, value.first.to_i, nil)
when "<t+"
# <= today + n days
sql = relative_date_clause(db_table, db_field, nil, value.first.to_i)
sql = relative_date_clause(db_table, db_field, 0, value.first.to_i)
when "t+"
# = today + n days
sql = relative_date_clause(db_table, db_field, value.first.to_i, value.first.to_i)
when "t"
# = today
sql = relative_date_clause(db_table, db_field, 0, 0)
when "w"
# = this week
first_day_of_week = l(:general_first_day_of_week).to_i
day_of_week = Date.today.cwday
days_ago = (day_of_week >= first_day_of_week ? day_of_week - first_day_of_week : day_of_week + 7 - first_day_of_week)
@@ -1005,8 +812,7 @@ class Query < ActiveRecord::Base
return sql
end
def add_custom_fields_filters(custom_fields, assoc=nil)
return unless custom_fields.present?
def add_custom_fields_filters(custom_fields)
@available_filters ||= {}
custom_fields.select(&:is_filter?).each do |field|
@@ -1033,29 +839,7 @@ class Query < ActiveRecord::Base
else
options = { :type => :string, :order => 20 }
end
filter_id = "cf_#{field.id}"
filter_name = field.name
if assoc.present?
filter_id = "#{assoc}.#{filter_id}"
filter_name = l("label_attribute_of_#{assoc}", :name => filter_name)
end
@available_filters[filter_id] = options.merge({
:name => filter_name,
:format => field.field_format,
:field => field
})
end
end
def add_associations_custom_fields_filters(*associations)
fields_by_class = CustomField.where(:is_filter => true).group_by(&:class)
associations.each do |assoc|
association_klass = Issue.reflect_on_association(assoc).klass
fields_by_class.each do |field_class, fields|
if field_class.customized_class <= association_klass
add_custom_fields_filters(fields, assoc)
end
end
@available_filters["cf_#{field.id}"] = options.merge({ :name => field.name, :format => field.field_format })
end
end
@@ -1084,24 +868,4 @@ class Query < ActiveRecord::Base
def relative_date_clause(table, field, days_from, days_to)
date_clause(table, field, (days_from ? Date.today + days_from : nil), (days_to ? Date.today + days_to : nil))
end
# Additional joins required for the given sort options
def joins_for_order_statement(order_options)
joins = []
if order_options
if order_options.include?('authors')
joins << "LEFT OUTER JOIN #{User.table_name} authors ON authors.id = #{Issue.table_name}.author_id"
end
order_options.scan(/cf_\d+/).uniq.each do |name|
column = available_columns.detect {|c| c.name.to_s == name}
join = column && column.custom_field.join_for_order_statement
if join
joins << join
end
end
end
joins.any? ? joins.join(' ') : nil
end
end

View File

@@ -19,10 +19,6 @@ class ScmFetchError < Exception; end
class Repository < ActiveRecord::Base
include Redmine::Ciphering
include Redmine::SafeAttributes
# Maximum length for repository identifiers
IDENTIFIER_MAX_LENGTH = 255
belongs_to :project
has_many :changesets, :order => "#{Changeset.table_name}.committed_on DESC, #{Changeset.table_name}.id DESC"
@@ -37,25 +33,15 @@ class Repository < ActiveRecord::Base
before_destroy :clear_changesets
validates_length_of :password, :maximum => 255, :allow_nil => true
validates_length_of :identifier, :maximum => IDENTIFIER_MAX_LENGTH, :allow_blank => true
validates_length_of :identifier, :maximum => 255, :allow_blank => true
validates_presence_of :identifier, :unless => Proc.new { |r| r.is_default? || r.set_as_default? }
validates_uniqueness_of :identifier, :scope => :project_id, :allow_blank => true
validates_exclusion_of :identifier, :in => %w(show entry raw changes annotate diff show stats graph)
# donwcase letters, digits, dashes, underscores but not digits only
validates_format_of :identifier, :with => /^(?!\d+$)[a-z0-9\-_]*$/, :allow_blank => true
# donwcase letters, digits, dashes but not digits only
validates_format_of :identifier, :with => /^(?!\d+$)[a-z0-9\-]*$/, :allow_blank => true
# Checks if the SCM is enabled when creating a repository
validate :repo_create_validation, :on => :create
safe_attributes 'identifier',
'login',
'password',
'path_encoding',
'log_encoding',
'is_default'
safe_attributes 'url',
:if => lambda {|repository, user| repository.new_record?}
def repo_create_validation
unless Setting.enabled_scm.include?(self.class.name.demodulize)
errors.add(:type, :invalid)
@@ -117,14 +103,6 @@ class Repository < ActiveRecord::Base
end
end
def identifier=(identifier)
super unless identifier_frozen?
end
def identifier_frozen?
errors[:identifier].blank? && !(new_record? || identifier.blank?)
end
def identifier_param
if is_default?
nil
@@ -189,9 +167,7 @@ class Repository < ActiveRecord::Base
end
def entries(path=nil, identifier=nil)
entries = scm.entries(path, identifier)
load_entries_changesets(entries)
entries
scm.entries(path, identifier)
end
def branches
@@ -404,21 +380,11 @@ class Repository < ActiveRecord::Base
end
end
def load_entries_changesets(entries)
if entries
entries.each do |entry|
if entry.lastrev && entry.lastrev.identifier
entry.changeset = find_changeset_by_name(entry.lastrev.identifier)
end
end
end
end
private
# Deletes repository data
def clear_changesets
cs = Changeset.table_name
cs = Changeset.table_name
ch = Change.table_name
ci = "#{table_name_prefix}changesets_issues#{table_name_suffix}"
cp = "#{table_name_prefix}changeset_parents#{table_name_suffix}"
@@ -427,9 +393,5 @@ class Repository < ActiveRecord::Base
connection.delete("DELETE FROM #{ci} WHERE #{ci}.changeset_id IN (SELECT #{cs}.id FROM #{cs} WHERE #{cs}.repository_id = #{id})")
connection.delete("DELETE FROM #{cp} WHERE #{cp}.changeset_id IN (SELECT #{cs}.id FROM #{cs} WHERE #{cs}.repository_id = #{id})")
connection.delete("DELETE FROM #{cs} WHERE #{cs}.repository_id = #{id}")
clear_extra_info_of_changesets
end
def clear_extra_info_of_changesets
end
end

View File

@@ -37,28 +37,7 @@ class Repository::Bazaar < Repository
'Bazaar'
end
def entry(path=nil, identifier=nil)
scm.bzr_path_encodig = log_encoding
scm.entry(path, identifier)
end
def cat(path, identifier=nil)
scm.bzr_path_encodig = log_encoding
scm.cat(path, identifier)
end
def annotate(path, identifier=nil)
scm.bzr_path_encodig = log_encoding
scm.annotate(path, identifier)
end
def diff(path, rev, rev_to)
scm.bzr_path_encodig = log_encoding
scm.diff(path, rev, rev_to)
end
def entries(path=nil, identifier=nil)
scm.bzr_path_encodig = log_encoding
entries = scm.entries(path, identifier)
if entries
entries.each do |e|
@@ -84,12 +63,9 @@ class Repository::Bazaar < Repository
end
end
end
load_entries_changesets(entries)
entries
end
def fetch_changesets
scm.bzr_path_encodig = log_encoding
scm_info = scm.info
if scm_info
# latest revision found in database
@@ -102,7 +78,7 @@ class Repository::Bazaar < Repository
while (identifier_from <= scm_revision)
# loads changesets by batches of 200
identifier_to = [identifier_from + 199, scm_revision].min
revisions = scm.revisions('', identifier_to, identifier_from)
revisions = scm.revisions('', identifier_to, identifier_from, :with_paths => true)
transaction do
revisions.reverse_each do |revision|
changeset = Changeset.create(:repository => self,

View File

@@ -21,9 +21,6 @@ require 'digest/sha1'
class Repository::Cvs < Repository
validates_presence_of :url, :root_url, :log_encoding
safe_attributes 'root_url',
:if => lambda {|repository, user| repository.new_record?}
def self.human_attribute_name(attribute_key_name, *args)
attr_name = attribute_key_name.to_s
if attr_name == "root_url"
@@ -69,7 +66,6 @@ class Repository::Cvs < Repository
end
end
end
load_entries_changesets(entries)
entries
end

View File

@@ -66,7 +66,6 @@ class Repository::Darcs < Repository
end
end
end
load_entries_changesets(entries)
entries
end

View File

@@ -44,6 +44,10 @@ class Repository::Filesystem < Repository
false
end
def entries(path=nil, identifier=nil)
scm.entries(path, identifier)
end
def fetch_changesets
nil
end

View File

@@ -87,16 +87,16 @@ class Repository::Git < Repository
end
def find_changeset_by_name(name)
if name.present?
changesets.where(:revision => name.to_s).first ||
changesets.where('scmid LIKE ?', "#{name}%").first
end
return nil if name.nil? || name.empty?
e = changesets.find(:first, :conditions => ['revision = ?', name.to_s])
return e if e
changesets.find(:first, :conditions => ['scmid LIKE ?', "#{name}%"])
end
def entries(path=nil, identifier=nil)
entries = scm.entries(path, identifier, :report_last_commit => extra_report_last_commit)
load_entries_changesets(entries)
entries
scm.entries(path,
identifier,
options = {:report_last_commit => extra_report_last_commit})
end
# With SCMs that have a sequential commit numbering,
@@ -255,15 +255,4 @@ class Repository::Git < Repository
:order => 'committed_on DESC'
)
end
def clear_extra_info_of_changesets
return if extra_info.nil?
v = extra_info["extra_report_last_commit"]
write_attribute(:extra_info, nil)
h = {}
h["extra_report_last_commit"] = v
merge_extra_info(h)
self.save
end
private :clear_extra_info_of_changesets
end

View File

@@ -76,12 +76,12 @@ class Repository::Mercurial < Repository
return nil if name.blank?
s = name.to_s
if /[^\d]/ =~ s or s.size > 8
cs = changesets.where(:scmid => s).first
e = changesets.find(:first, :conditions => ['scmid = ?', s])
else
cs = changesets.where(:revision => s).first
e = changesets.find(:first, :conditions => ['revision = ?', s])
end
return cs if cs
changesets.where('scmid LIKE ?', "#{s}%").first
return e if e
changesets.find(:first, :conditions => ['scmid LIKE ?', "#{s}%"]) # last ditch
end
# Returns the latest changesets for +path+; sorted by revision number

View File

@@ -40,12 +40,7 @@ class Repository::Subversion < Repository
def latest_changesets(path, rev, limit=10)
revisions = scm.revisions(path, rev, nil, :limit => limit)
if revisions
identifiers = revisions.collect(&:identifier).compact
changesets.where(:revision => identifiers).reorder("committed_on DESC").includes(:repository, :user).all
else
[]
end
revisions ? changesets.find_all_by_revision(revisions.collect(&:identifier), :order => "committed_on DESC", :include => :user) : []
end
# Returns a path relative to the url of the repository
@@ -86,24 +81,6 @@ class Repository::Subversion < Repository
end
end
protected
def load_entries_changesets(entries)
return unless entries
entries_with_identifier = entries.select {|entry| entry.lastrev && entry.lastrev.identifier.present?}
identifiers = entries_with_identifier.map {|entry| entry.lastrev.identifier}.compact.uniq
if identifiers.any?
changesets_by_identifier = changesets.where(:revision => identifiers).includes(:user, :repository).all.group_by(&:revision)
entries_with_identifier.each do |entry|
if m = changesets_by_identifier[entry.lastrev.identifier]
entry.changeset = m.first
end
end
end
end
private
# Returns the relative url of the repository

View File

@@ -16,19 +16,6 @@
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
class Role < ActiveRecord::Base
# Custom coder for the permissions attribute that should be an
# array of symbols. Rails 3 uses Psych which can be *unbelievably*
# slow on some platforms (eg. mingw32).
class PermissionsAttributeCoder
def self.load(str)
str.to_s.scan(/:([a-z0-9_]+)/).flatten.map(&:to_sym)
end
def self.dump(value)
YAML.dump(value)
end
end
# Built-in roles
BUILTIN_NON_MEMBER = 1
BUILTIN_ANONYMOUS = 2
@@ -39,17 +26,17 @@ class Role < ActiveRecord::Base
['own', :label_issues_visibility_own]
]
scope :sorted, order("#{table_name}.builtin ASC, #{table_name}.position ASC")
scope :givable, order("#{table_name}.position ASC").where(:builtin => 0)
scope :sorted, {:order => 'builtin, position'}
scope :givable, { :conditions => "builtin = 0", :order => 'position' }
scope :builtin, lambda { |*args|
compare = (args.first == true ? 'not' : '')
where("#{compare} builtin = 0")
compare = 'not' if args.first == true
{ :conditions => "#{compare} builtin = 0" }
}
before_destroy :check_deletable
has_many :workflow_rules, :dependent => :delete_all do
has_many :workflows, :dependent => :delete_all do
def copy(source_role)
WorkflowRule.copy(nil, source_role, nil, proxy_association.owner)
Workflow.copy(nil, source_role, nil, proxy_association.owner)
end
end
@@ -57,7 +44,7 @@ class Role < ActiveRecord::Base
has_many :members, :through => :member_roles
acts_as_list
serialize :permissions, ::Role::PermissionsAttributeCoder
serialize :permissions, Array
attr_protected :builtin
validates_presence_of :name
@@ -67,13 +54,8 @@ class Role < ActiveRecord::Base
:in => ISSUES_VISIBILITY_OPTIONS.collect(&:first),
:if => lambda {|role| role.respond_to?(:issues_visibility)}
# Copies attributes from another role, arg can be an id or a Role
def copy_from(arg, options={})
return unless arg.present?
role = arg.is_a?(Role) ? arg : Role.find_by_id(arg.to_s)
self.attributes = role.attributes.dup.except("id", "name", "position", "builtin", "permissions")
self.permissions = role.permissions.dup
self
def permissions
read_attribute(:permissions) || []
end
def permissions=(perms)
@@ -105,15 +87,7 @@ class Role < ActiveRecord::Base
end
def <=>(role)
if role
if builtin == role.builtin
position <=> role.position
else
builtin <=> role.builtin
end
else
-1
end
role ? position <=> role.position : -1
end
def to_s
@@ -133,11 +107,6 @@ class Role < ActiveRecord::Base
self.builtin != 0
end
# Return true if the role is the anonymous role
def anonymous?
builtin == 2
end
# Return true if the role is a project member role
def member?
!self.builtin?
@@ -165,7 +134,7 @@ class Role < ActiveRecord::Base
# Find all the roles that can be given to a project member
def self.find_all_givable
Role.givable.all
find(:all, :conditions => {:builtin => 0}, :order => 'position')
end
# Return the builtin 'non member' role. If the role doesn't exist,
@@ -196,7 +165,7 @@ private
end
def self.find_or_create_system_role(builtin, name)
role = where(:builtin => builtin).first
role = first(:conditions => {:builtin => builtin})
if role.nil?
role = create(:name => name, :position => 0) do |r|
r.builtin = builtin

View File

@@ -66,7 +66,7 @@ class TimeEntry < ActiveRecord::Base
end
}
safe_attributes 'hours', 'comments', 'issue_id', 'activity_id', 'spent_on', 'custom_field_values', 'custom_fields'
safe_attributes 'hours', 'comments', 'issue_id', 'activity_id', 'spent_on', 'custom_field_values'
def initialize(attributes=nil, *args)
super

View File

@@ -16,18 +16,11 @@
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
class Tracker < ActiveRecord::Base
CORE_FIELDS_UNDISABLABLE = %w(project_id tracker_id subject description priority_id is_private).freeze
# Fields that can be disabled
# Other (future) fields should be appended, not inserted!
CORE_FIELDS = %w(assigned_to_id category_id fixed_version_id parent_issue_id start_date due_date estimated_hours done_ratio).freeze
CORE_FIELDS_ALL = (CORE_FIELDS_UNDISABLABLE + CORE_FIELDS).freeze
before_destroy :check_integrity
has_many :issues
has_many :workflow_rules, :dependent => :delete_all do
has_many :workflows, :dependent => :delete_all do
def copy(source_tracker)
WorkflowRule.copy(source_tracker, nil, proxy_association.owner, nil)
Workflow.copy(source_tracker, nil, proxy_association.owner, nil)
end
end
@@ -35,14 +28,11 @@ class Tracker < ActiveRecord::Base
has_and_belongs_to_many :custom_fields, :class_name => 'IssueCustomField', :join_table => "#{table_name_prefix}custom_fields_trackers#{table_name_suffix}", :association_foreign_key => 'custom_field_id'
acts_as_list
attr_protected :field_bits
validates_presence_of :name
validates_uniqueness_of :name
validates_length_of :name, :maximum => 30
scope :sorted, order("#{table_name}.position ASC")
scope :named, lambda {|arg| where("LOWER(#{table_name}.name) = LOWER(?)", arg.to_s.strip)}
scope :named, lambda {|arg| { :conditions => ["LOWER(#{table_name}.name) = LOWER(?)", arg.to_s.strip]}}
def to_s; name end
@@ -50,6 +40,10 @@ class Tracker < ActiveRecord::Base
position <=> tracker.position
end
def self.all
find(:all, :order => 'position')
end
# Returns an array of IssueStatus that are used
# in the tracker's workflows
def issue_statuses
@@ -59,57 +53,16 @@ class Tracker < ActiveRecord::Base
return []
end
ids = WorkflowTransition.
connection.select_rows("SELECT DISTINCT old_status_id, new_status_id FROM #{WorkflowTransition.table_name} WHERE tracker_id = #{id} AND type = 'WorkflowTransition'").
ids = Workflow.
connection.select_rows("SELECT DISTINCT old_status_id, new_status_id FROM #{Workflow.table_name} WHERE tracker_id = #{id}").
flatten.
uniq
@issue_statuses = IssueStatus.find_all_by_id(ids).sort
end
def disabled_core_fields
i = -1
@disabled_core_fields ||= CORE_FIELDS.select { i += 1; (fields_bits || 0) & (2 ** i) != 0}
end
def core_fields
CORE_FIELDS - disabled_core_fields
end
def core_fields=(fields)
raise ArgumentError.new("Tracker.core_fields takes an array") unless fields.is_a?(Array)
bits = 0
CORE_FIELDS.each_with_index do |field, i|
unless fields.include?(field)
bits |= 2 ** i
end
end
self.fields_bits = bits
@disabled_core_fields = nil
core_fields
end
# Returns the fields that are disabled for all the given trackers
def self.disabled_core_fields(trackers)
if trackers.present?
trackers.uniq.map(&:disabled_core_fields).reduce(:&)
else
[]
end
end
# Returns the fields that are enabled for one tracker at least
def self.core_fields(trackers)
if trackers.present?
trackers.uniq.map(&:core_fields).reduce(:|)
else
CORE_FIELDS.dup
end
end
private
def check_integrity
raise Exception.new("Can't delete tracker") if Issue.where(:tracker_id => self.id).any?
raise "Can't delete tracker" if Issue.find(:first, :conditions => ["tracker_id=?", self.id])
end
end

View File

@@ -28,41 +28,11 @@ class User < Principal
# Different ways of displaying/sorting users
USER_FORMATS = {
:firstname_lastname => {
:string => '#{firstname} #{lastname}',
:order => %w(firstname lastname id),
:setting_order => 1
},
:firstname_lastinitial => {
:string => '#{firstname} #{lastname.to_s.chars.first}.',
:order => %w(firstname lastname id),
:setting_order => 2
},
:firstname => {
:string => '#{firstname}',
:order => %w(firstname id),
:setting_order => 3
},
:lastname_firstname => {
:string => '#{lastname} #{firstname}',
:order => %w(lastname firstname id),
:setting_order => 4
},
:lastname_coma_firstname => {
:string => '#{lastname}, #{firstname}',
:order => %w(lastname firstname id),
:setting_order => 5
},
:lastname => {
:string => '#{lastname}',
:order => %w(lastname id),
:setting_order => 6
},
:username => {
:string => '#{login}',
:order => %w(login id),
:setting_order => 7
},
:firstname_lastname => {:string => '#{firstname} #{lastname}', :order => %w(firstname lastname id)},
:firstname => {:string => '#{firstname}', :order => %w(firstname id)},
:lastname_firstname => {:string => '#{lastname} #{firstname}', :order => %w(lastname firstname id)},
:lastname_coma_firstname => {:string => '#{lastname}, #{firstname}', :order => %w(lastname firstname id)},
:username => {:string => '#{login}', :order => %w(login id)},
}
MAIL_NOTIFICATION_OPTIONS = [
@@ -82,6 +52,8 @@ class User < Principal
has_one :api_token, :class_name => 'Token', :conditions => "action='api'"
belongs_to :auth_source
# Active non-anonymous users scope
scope :active, :conditions => "#{User.table_name}.status = #{STATUS_ACTIVE}"
scope :logged, :conditions => "#{User.table_name}.status <> #{STATUS_ANONYMOUS}"
scope :status, lambda {|arg| arg.blank? ? {} : {:conditions => {:status => arg.to_i}} }
@@ -97,7 +69,7 @@ class User < Principal
validates_presence_of :login, :firstname, :lastname, :mail, :if => Proc.new { |user| !user.is_a?(AnonymousUser) }
validates_uniqueness_of :login, :if => Proc.new { |user| user.login_changed? && user.login.present? }, :case_sensitive => false
validates_uniqueness_of :mail, :if => Proc.new { |user| user.mail_changed? && user.mail.present? }, :case_sensitive => false
validates_uniqueness_of :mail, :if => Proc.new { |user| !user.mail.blank? }, :case_sensitive => false
# Login must contain lettres, numbers, underscores only
validates_format_of :login, :with => /^[a-z0-9_\-@\.]*$/i
validates_length_of :login, :maximum => LOGIN_LENGTH_LIMIT
@@ -114,11 +86,11 @@ class User < Principal
scope :in_group, lambda {|group|
group_id = group.is_a?(Group) ? group.id : group.to_i
where("#{User.table_name}.id IN (SELECT gu.user_id FROM #{table_name_prefix}groups_users#{table_name_suffix} gu WHERE gu.group_id = ?)", group_id)
{ :conditions => ["#{User.table_name}.id IN (SELECT gu.user_id FROM #{table_name_prefix}groups_users#{table_name_suffix} gu WHERE gu.group_id = ?)", group_id] }
}
scope :not_in_group, lambda {|group|
group_id = group.is_a?(Group) ? group.id : group.to_i
where("#{User.table_name}.id NOT IN (SELECT gu.user_id FROM #{table_name_prefix}groups_users#{table_name_suffix} gu WHERE gu.group_id = ?)", group_id)
{ :conditions => ["#{User.table_name}.id NOT IN (SELECT gu.user_id FROM #{table_name_prefix}groups_users#{table_name_suffix} gu WHERE gu.group_id = ?)", group_id] }
}
def set_mail_notification
@@ -158,11 +130,8 @@ class User < Principal
# Returns the user that matches provided login and password, or nil
def self.try_to_login(login, password)
login = login.to_s
password = password.to_s
# Make sure no one can sign in with an empty password
return nil if password.empty?
return nil if password.to_s.empty?
user = find_by_login(login)
if user
# user is already in local database
@@ -195,7 +164,7 @@ class User < Principal
# Returns the user who matches the given autologin +key+ or nil
def self.try_to_autologin(key)
tokens = Token.find_all_by_action_and_value('autologin', key.to_s)
tokens = Token.find_all_by_action_and_value('autologin', key)
# Make sure there's only 1 token that matches the key
if tokens.size == 1
token = tokens.first
@@ -360,27 +329,27 @@ class User < Principal
# version. Exact matches will be given priority.
def self.find_by_login(login)
# First look for an exact match
user = where(:login => login).all.detect {|u| u.login == login}
user = all(:conditions => {:login => login}).detect {|u| u.login == login}
unless user
# Fail over to case-insensitive if none was found
user = where("LOWER(login) = ?", login.to_s.downcase).first
user = first(:conditions => ["LOWER(login) = ?", login.to_s.downcase])
end
user
end
def self.find_by_rss_key(key)
token = Token.find_by_action_and_value('feeds', key.to_s)
token = Token.find_by_value(key)
token && token.user.active? ? token.user : nil
end
def self.find_by_api_key(key)
token = Token.find_by_action_and_value('api', key.to_s)
token = Token.find_by_action_and_value('api', key)
token && token.user.active? ? token.user : nil
end
# Makes find_by_mail case-insensitive
def self.find_by_mail(mail)
where("LOWER(mail) = ?", mail.to_s.downcase).first
find(:first, :conditions => ["LOWER(mail) = ?", mail.to_s.downcase])
end
# Returns true if the default admin account can no longer be used
@@ -392,17 +361,6 @@ class User < Principal
name
end
CSS_CLASS_BY_STATUS = {
STATUS_ANONYMOUS => 'anon',
STATUS_ACTIVE => 'active',
STATUS_REGISTERED => 'registered',
STATUS_LOCKED => 'locked'
}
def css_classes
"user #{CSS_CLASS_BY_STATUS[status]}"
end
# Returns the current day according to user's time zone
def today
if time_zone.nil?
@@ -433,7 +391,7 @@ class User < Principal
def roles_for_project(project)
roles = []
# No role on archived projects
return roles if project.nil? || project.archived?
return roles unless project && project.active?
if logged?
# Find project membership
membership = memberships.detect {|m| m.project_id == project.id}
@@ -459,13 +417,10 @@ class User < Principal
def projects_by_role
return @projects_by_role if @projects_by_role
@projects_by_role = Hash.new([])
@projects_by_role = Hash.new {|h,k| h[k]=[]}
memberships.each do |membership|
if membership.project
membership.roles.each do |role|
@projects_by_role[role] = [] unless @projects_by_role.key?(role)
@projects_by_role[role] << membership.project
end
membership.roles.each do |role|
@projects_by_role[role] << membership.project if membership.project
end
end
@projects_by_role.each do |role, projects|
@@ -497,23 +452,26 @@ class User < Principal
# or falls back to Non Member / Anonymous permissions depending if the user is logged
def allowed_to?(action, context, options={}, &block)
if context && context.is_a?(Project)
# No action allowed on archived projects
return false unless context.active?
# No action allowed on disabled modules
return false unless context.allows_to?(action)
# Admin users are authorized for anything else
return true if admin?
roles = roles_for_project(context)
return false unless roles
roles.any? {|role|
roles.detect {|role|
(context.is_public? || role.member?) &&
role.allowed_to?(action) &&
(block_given? ? yield(role, self) : true)
}
elsif context && context.is_a?(Array)
if context.empty?
false
else
# Authorize if user is authorized on every element of the array
context.map {|project| allowed_to?(action, project, options, &block)}.reduce(:&)
# Authorize if user is authorized on every element of the array
context.map do |project|
allowed_to?(action, project, options, &block)
end.inject do |memo,allowed|
memo && allowed
end
elsif options[:global]
# Admin users are always authorized
@@ -522,7 +480,7 @@ class User < Principal
# authorize if user has at least one role that has this permission
roles = memberships.collect {|m| m.roles}.flatten.uniq
roles << (self.logged? ? Role.non_member : Role.anonymous)
roles.any? {|role|
roles.detect {|role|
role.allowed_to?(action) &&
(block_given? ? yield(role, self) : true)
}
@@ -540,7 +498,7 @@ class User < Principal
# Returns true if the user is allowed to delete his own account
def own_account_deletable?
Setting.unsubscribe? &&
(!admin? || User.active.where("admin = ? AND id <> ?", true, id).exists?)
(!admin? || User.active.first(:conditions => ["admin = ? AND id <> ?", true, id]).present?)
end
safe_attributes 'login',
@@ -611,7 +569,7 @@ class User < Principal
# Returns the anonymous user. If the anonymous user does not exist, it is created. There can be only
# one anonymous user per database.
def self.anonymous
anonymous_user = AnonymousUser.first
anonymous_user = AnonymousUser.find(:first)
if anonymous_user.nil?
anonymous_user = AnonymousUser.create(:lastname => 'Anonymous', :firstname => '', :mail => '', :login => '', :status => 0)
raise 'Unable to create the anonymous user.' if anonymous_user.new_record?
@@ -624,11 +582,11 @@ class User < Principal
# This method is used in the SaltPasswords migration and is to be kept as is
def self.salt_unsalted_passwords!
transaction do
User.where("salt IS NULL OR salt = ''").find_each do |user|
User.find_each(:conditions => "salt IS NULL OR salt = ''") do |user|
next if user.hashed_password.blank?
salt = User.generate_salt
hashed_password = User.hash_password("#{salt}#{user.hashed_password}")
User.where(:id => user.id).update_all(:salt => salt, :hashed_password => hashed_password)
User.update_all("salt = '#{salt}', hashed_password = '#{hashed_password}'", ["id = ?", user.id] )
end
end
end
@@ -701,10 +659,6 @@ class AnonymousUser < User
def time_zone; nil end
def rss_key; nil end
def pref
UserPreference.new(:user => self)
end
# Anonymous user can not be destroyed
def destroy
false

View File

@@ -44,7 +44,7 @@ class UserPreference < ActiveRecord::Base
if attribute_present? attr_name
super
else
h = (read_attribute(:others) || {}).dup
h = read_attribute(:others).dup || {}
h.update(attr_name => value)
write_attribute(:others, h)
value

View File

@@ -33,13 +33,11 @@ class Version < ActiveRecord::Base
validates_format_of :effective_date, :with => /^\d{4}-\d{2}-\d{2}$/, :message => :not_a_date, :allow_nil => true
validates_inclusion_of :status, :in => VERSION_STATUSES
validates_inclusion_of :sharing, :in => VERSION_SHARINGS
validate :validate_version
scope :named, lambda {|arg| where("LOWER(#{table_name}.name) = LOWER(?)", arg.to_s.strip)}
scope :open, where(:status => 'open')
scope :visible, lambda {|*args|
includes(:project).where(Project.allowed_to_condition(args.first || User.current, :view_issues))
}
scope :named, lambda {|arg| { :conditions => ["LOWER(#{table_name}.name) = LOWER(?)", arg.to_s.strip]}}
scope :open, :conditions => {:status => 'open'}
scope :visible, lambda {|*args| { :include => :project,
:conditions => Project.allowed_to_condition(args.first || User.current, :view_issues) } }
safe_attributes 'name',
'description',
@@ -80,7 +78,7 @@ class Version < ActiveRecord::Base
# Returns the total reported time for this version
def spent_hours
@spent_hours ||= TimeEntry.joins(:issue).where("#{Issue.table_name}.fixed_version_id = ?", id).sum(:hours).to_f
@spent_hours ||= TimeEntry.sum(:hours, :joins => :issue, :conditions => ["#{Issue.table_name}.fixed_version_id = ?", id]).to_f
end
def closed?
@@ -93,7 +91,7 @@ class Version < ActiveRecord::Base
# Returns true if the version is completed: due date reached and no open issues
def completed?
effective_date && (effective_date < Date.today) && (open_issues_count == 0)
effective_date && (effective_date <= Date.today) && (open_issues_count == 0)
end
def behind_schedule?
@@ -164,13 +162,13 @@ class Version < ActiveRecord::Base
"#{project} - #{name}"
end
# Versions are sorted by effective_date and name
# Those with no effective_date are at the end, sorted by name
# Versions are sorted by effective_date and "Project Name - Version name"
# Those with no effective_date are at the end, sorted by "Project Name - Version name"
def <=>(version)
if self.effective_date
if version.effective_date
if self.effective_date == version.effective_date
name == version.name ? id <=> version.id : name <=> version.name
"#{self.project.name} - #{self.name}" <=> "#{version.project.name} - #{version.name}"
else
self.effective_date <=> version.effective_date
end
@@ -181,18 +179,11 @@ class Version < ActiveRecord::Base
if version.effective_date
1
else
name == version.name ? id <=> version.id : name <=> version.name
"#{self.project.name} - #{self.name}" <=> "#{version.project.name} - #{version.name}"
end
end
end
def self.fields_for_order_statement(table=nil)
table ||= table_name
["(CASE WHEN #{table}.effective_date IS NULL THEN 1 ELSE 0 END)", "#{table}.effective_date", "#{table}.name", "#{table}.id"]
end
scope :sorted, order(fields_for_order_statement)
# Returns the sharings that +user+ can set the version to
def allowed_sharings(user = User.current)
VERSION_SHARINGS.select do |s|
@@ -269,16 +260,12 @@ class Version < ActiveRecord::Base
if issues_count > 0
ratio = open ? 'done_ratio' : 100
done = fixed_issues.open(open).sum("COALESCE(estimated_hours, #{estimated_average}) * #{ratio}").to_f
done = fixed_issues.sum("COALESCE(estimated_hours, #{estimated_average}) * #{ratio}",
:joins => :status,
:conditions => ["#{IssueStatus.table_name}.is_closed = ?", !open]).to_f
progress = done / (estimated_average * issues_count)
end
progress
end
end
def validate_version
if effective_date.nil? && @attributes['effective_date'].present?
errors.add :effective_date, :not_a_date
end
end
end

View File

@@ -73,8 +73,6 @@ class WikiContent < ActiveRecord::Base
"LEFT JOIN #{Wiki.table_name} ON #{Wiki.table_name}.id = #{WikiPage.table_name}.wiki_id " +
"LEFT JOIN #{Project.table_name} ON #{Project.table_name}.id = #{Wiki.table_name}.project_id"}
after_destroy :page_update_after_destroy
def text=(plain)
case Setting.wiki_compression
when 'gzip'
@@ -117,31 +115,10 @@ class WikiContent < ActiveRecord::Base
# Returns the previous version or nil
def previous
@previous ||= WikiContent::Version.
reorder('version DESC').
includes(:author).
where("wiki_content_id = ? AND version < ?", wiki_content_id, version).first
end
# Returns the next version or nil
def next
@next ||= WikiContent::Version.
reorder('version ASC').
includes(:author).
where("wiki_content_id = ? AND version > ?", wiki_content_id, version).first
end
private
# Updates page's content if the latest version is removed
# or destroys the page if it was the only version
def page_update_after_destroy
latest = page.content.versions.reorder("#{self.class.table_name}.version DESC").first
if latest && page.content.version != latest.version
raise ActiveRecord::Rollback unless page.content.revert_to!(latest)
elsif latest.nil?
raise ActiveRecord::Rollback unless page.destroy
end
@previous ||= WikiContent::Version.find(:first,
:order => 'version DESC',
:include => :author,
:conditions => ["wiki_content_id = ? AND version < ?", wiki_content_id, version])
end
end
end

View File

@@ -50,14 +50,14 @@ class WikiPage < ActiveRecord::Base
# eager load information about last updates, without loading text
scope :with_updated_on, {
:select => "#{WikiPage.table_name}.*, #{WikiContent.table_name}.updated_on, #{WikiContent.table_name}.version",
:select => "#{WikiPage.table_name}.*, #{WikiContent.table_name}.updated_on",
:joins => "LEFT JOIN #{WikiContent.table_name} ON #{WikiContent.table_name}.page_id = #{WikiPage.table_name}.id"
}
# Wiki pages that are protected by default
DEFAULT_PROTECTED_PAGES = %w(sidebar)
safe_attributes 'parent_id', 'parent_title',
safe_attributes 'parent_id',
:if => lambda {|page, user| page.new_record? || user.allowed_to?(:rename_wiki_pages, page.project)}
def initialize(attributes=nil, *args)
@@ -111,13 +111,11 @@ class WikiPage < ActiveRecord::Base
def diff(version_to=nil, version_from=nil)
version_to = version_to ? version_to.to_i : self.content.version
content_to = content.versions.find_by_version(version_to)
content_from = version_from ? content.versions.find_by_version(version_from.to_i) : content_to.try(:previous)
return nil unless content_to && content_from
version_from = version_from ? version_from.to_i : version_to - 1
version_to, version_from = version_from, version_to unless version_from < version_to
if content_from.version > content_to.version
content_to, content_from = content_from, content_to
end
content_to = content.versions.find_by_version(version_to)
content_from = content.versions.find_by_version(version_from)
(content_to && content_from) ? WikiDiff.new(content_to, content_from) : nil
end
@@ -174,21 +172,6 @@ class WikiPage < ActiveRecord::Base
self.parent = parent_page
end
# Saves the page and its content if text was changed
def save_with_content
ret = nil
transaction do
if new_record?
# Rails automatically saves associated content
ret = save
else
ret = save && (content.text_changed? ? content.save : true)
end
raise ActiveRecord::Rollback unless ret
end
ret
end
protected
def validate_parent_title

View File

@@ -15,15 +15,31 @@
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
class WorkflowRule < ActiveRecord::Base
self.table_name = "#{table_name_prefix}workflows#{table_name_suffix}"
class Workflow < ActiveRecord::Base
belongs_to :role
belongs_to :tracker
belongs_to :old_status, :class_name => 'IssueStatus', :foreign_key => 'old_status_id'
belongs_to :new_status, :class_name => 'IssueStatus', :foreign_key => 'new_status_id'
validates_presence_of :role, :tracker, :old_status
validates_presence_of :role, :old_status, :new_status
# Returns workflow transitions count by tracker and role
def self.count_by_tracker_and_role
counts = connection.select_all("SELECT role_id, tracker_id, count(id) AS c FROM #{Workflow.table_name} GROUP BY role_id, tracker_id")
roles = Role.find(:all, :order => 'builtin, position')
trackers = Tracker.find(:all, :order => 'position')
result = []
trackers.each do |tracker|
t = []
roles.each do |role|
row = counts.detect {|c| c['role_id'].to_s == role.id.to_s && c['tracker_id'].to_s == tracker.id.to_s}
t << [role, (row.nil? ? 0 : row['c'].to_i)]
end
result << [tracker, t]
end
result
end
# Copies workflows from source to targets
def self.copy(source_tracker, source_role, target_trackers, target_roles)
@@ -34,7 +50,7 @@ class WorkflowRule < ActiveRecord::Base
target_trackers = [target_trackers].flatten.compact
target_roles = [target_roles].flatten.compact
target_trackers = Tracker.sorted.all if target_trackers.empty?
target_trackers = Tracker.all if target_trackers.empty?
target_roles = Role.all if target_roles.empty?
target_trackers.each do |target_tracker|
@@ -62,9 +78,9 @@ class WorkflowRule < ActiveRecord::Base
else
transaction do
delete_all :tracker_id => target_tracker.id, :role_id => target_role.id
connection.insert "INSERT INTO #{WorkflowRule.table_name} (tracker_id, role_id, old_status_id, new_status_id, author, assignee, field_name, rule, type)" +
" SELECT #{target_tracker.id}, #{target_role.id}, old_status_id, new_status_id, author, assignee, field_name, rule, type" +
" FROM #{WorkflowRule.table_name}" +
connection.insert "INSERT INTO #{Workflow.table_name} (tracker_id, role_id, old_status_id, new_status_id, author, assignee)" +
" SELECT #{target_tracker.id}, #{target_role.id}, old_status_id, new_status_id, author, assignee" +
" FROM #{Workflow.table_name}" +
" WHERE tracker_id = #{source_tracker.id} AND role_id = #{source_role.id}"
end
true

View File

@@ -1,45 +0,0 @@
# Redmine - project management software
# Copyright (C) 2006-2012 Jean-Philippe Lang
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
class WorkflowPermission < WorkflowRule
validates_inclusion_of :rule, :in => %w(readonly required)
validate :validate_field_name
# Replaces the workflow permissions for the given tracker and role
#
# Example:
# WorkflowPermission.replace_permissions role, tracker, {'due_date' => {'1' => 'readonly', '2' => 'required'}}
def self.replace_permissions(tracker, role, permissions)
destroy_all(:tracker_id => tracker.id, :role_id => role.id)
permissions.each { |field, rule_by_status_id|
rule_by_status_id.each { |status_id, rule|
if rule.present?
WorkflowPermission.create(:role_id => role.id, :tracker_id => tracker.id, :old_status_id => status_id, :field_name => field, :rule => rule)
end
}
}
end
protected
def validate_field_name
unless Tracker::CORE_FIELDS_ALL.include?(field_name) || field_name.to_s.match(/^\d+$/)
errors.add :field_name, :invalid
end
end
end

View File

@@ -1,39 +0,0 @@
# Redmine - project management software
# Copyright (C) 2006-2012 Jean-Philippe Lang
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
class WorkflowTransition < WorkflowRule
validates_presence_of :new_status
# Returns workflow transitions count by tracker and role
def self.count_by_tracker_and_role
counts = connection.select_all("SELECT role_id, tracker_id, count(id) AS c FROM #{table_name} WHERE type = 'WorkflowTransition' GROUP BY role_id, tracker_id")
roles = Role.sorted.all
trackers = Tracker.sorted.all
result = []
trackers.each do |tracker|
t = []
roles.each do |role|
row = counts.detect {|c| c['role_id'].to_s == role.id.to_s && c['tracker_id'].to_s == tracker.id.to_s}
t << [role, (row.nil? ? 0 : row['c'].to_i)]
end
result << [tracker, t]
end
result
end
end

View File

@@ -1,11 +1,11 @@
<%= call_hook :view_account_login_top %>
<div id="login-form">
<%= form_tag(signin_path) do %>
<%= form_tag({:action=> "login"}) do %>
<%= back_url_hidden_field_tag %>
<table>
<tr>
<td align="right"><label for="username"><%=l(:field_login)%>:</label></td>
<td align="left"><%= text_field_tag 'username', params[:username], :tabindex => '1' %></td>
<td align="left"><%= text_field_tag 'username', nil, :tabindex => '1' %></td>
</tr>
<tr>
<td align="right"><label for="password"><%=l(:field_password)%>:</label></td>
@@ -28,7 +28,7 @@
<tr>
<td align="left">
<% if Setting.lost_password? %>
<%= link_to l(:label_password_lost), lost_password_path %>
<%= link_to l(:label_password_lost), :controller => 'account', :action => 'lost_password' %>
<% end %>
</td>
<td align="right">
@@ -36,12 +36,7 @@
</td>
</tr>
</table>
<%= javascript_tag "Form.Element.focus('username');" %>
<% end %>
</div>
<%= call_hook :view_account_login_bottom %>
<% if params[:username].present? %>
<%= javascript_tag "$('#password').focus();" %>
<% else %>
<%= javascript_tag "$('#username').focus();" %>
<% end %>

View File

@@ -1,11 +1,11 @@
<h2><%=l(:label_password_lost)%></h2>
<%= form_tag(lost_password_path) do %>
<div class="box tabular">
<p>
<label for="mail"><%=l(:field_mail)%> <span class="required">*</span></label>
<%= text_field_tag 'mail', nil, :size => 40 %>
<%= submit_tag l(:button_submit) %>
</p>
</div>
<div class="box">
<%= form_tag({:action=> "lost_password"}, :class => "tabular") do %>
<p><label for="mail"><%=l(:field_mail)%> <span class="required">*</span></label>
<%= text_field_tag 'mail', nil, :size => 40 %>
<%= submit_tag l(:button_submit) %></p>
<% end %>
</div>

View File

@@ -2,19 +2,14 @@
<%= error_messages_for 'user' %>
<%= form_tag(lost_password_path) do %>
<%= hidden_field_tag 'token', @token.value %>
<div class="box tabular">
<p>
<label for="new_password"><%=l(:field_new_password)%> <span class="required">*</span></label>
<%= password_field_tag 'new_password', nil, :size => 25 %>
<em class="info"><%= l(:text_caracters_minimum, :count => Setting.password_min_length) %></em>
</p>
<%= form_tag({:token => @token.value}) do %>
<div class="box tabular">
<p><label for="new_password"><%=l(:field_new_password)%> <span class="required">*</span></label>
<%= password_field_tag 'new_password', nil, :size => 25 %>
<em class="info"><%= l(:text_caracters_minimum, :count => Setting.password_min_length) %></em></p>
<p>
<label for="new_password_confirmation"><%=l(:field_password_confirmation)%> <span class="required">*</span></label>
<%= password_field_tag 'new_password_confirmation', nil, :size => 25 %>
</p>
</div>
<p><%= submit_tag l(:button_save) %></p>
<p><label for="new_password_confirmation"><%=l(:field_password_confirmation)%> <span class="required">*</span></label>
<%= password_field_tag 'new_password_confirmation', nil, :size => 25 %></p>
</div>
<p><%= submit_tag l(:button_save) %></p>
<% end %>

View File

@@ -1,6 +1,6 @@
<h2><%=l(:label_register)%> <%=link_to l(:label_login_with_open_id_option), signin_url if Setting.openid? %></h2>
<%= labelled_form_for @user, :url => register_path do |f| %>
<%= labelled_form_for @user, :url => {:action => 'register'} do |f| %>
<%= error_messages_for 'user' %>
<div class="box tabular">

View File

@@ -1,4 +1,4 @@
<h2><%= @author.nil? ? l(:label_activity) : l(:label_user_activity, link_to_user(@author)).html_safe %></h2>
<h2><%= @author.nil? ? l(:label_activity) : l(:label_user_activity, link_to_user(@author)) %></h2>
<p class="subtitle"><%= l(:label_date_from_to, :start => format_date(@date_to - @days), :end => format_date(@date_to-1)) %></p>
<div id="activity">

View File

@@ -1,3 +1,5 @@
<div id="admin-menu">
<%= render_menu :admin_menu %>
<ul>
<%= render_menu :admin_menu %>
</ul>
</div>

View File

@@ -27,12 +27,12 @@
<tbody>
<% project_tree(@projects) do |project, level| %>
<tr class="<%= cycle("odd", "even") %> <%= project.css_classes %> <%= level > 0 ? "idnt idnt-#{level}" : nil %>">
<td class="name"><span><%= link_to_project(project, {:action => (project.active? ? 'settings' : 'show')}, :title => project.short_description) %></span></td>
<td class="name"><span><%= link_to_project(project, {:action => 'settings'}, :title => project.short_description) %></span></td>
<td align="center"><%= checked_image project.is_public? %></td>
<td align="center"><%= format_date(project.created_on) %></td>
<td class="buttons">
<%= link_to(l(:button_archive), { :controller => 'projects', :action => 'archive', :id => project, :status => params[:status] }, :data => {:confirm => l(:text_are_you_sure)}, :method => :post, :class => 'icon icon-lock') unless project.archived? %>
<%= link_to(l(:button_unarchive), { :controller => 'projects', :action => 'unarchive', :id => project, :status => params[:status] }, :method => :post, :class => 'icon icon-unlock') if project.archived? && (project.parent.nil? || !project.parent.archived?) %>
<%= link_to(l(:button_archive), { :controller => 'projects', :action => 'archive', :id => project, :status => params[:status] }, :confirm => l(:text_are_you_sure), :method => :post, :class => 'icon icon-lock') if project.active? %>
<%= link_to(l(:button_unarchive), { :controller => 'projects', :action => 'unarchive', :id => project, :status => params[:status] }, :method => :post, :class => 'icon icon-unlock') if !project.active? && (project.parent.nil? || project.parent.active?) %>
<%= link_to(l(:button_copy), { :controller => 'projects', :action => 'copy', :id => project }, :class => 'icon icon-copy') %>
<%= link_to(l(:button_delete), project_path(project), :method => :delete, :class => 'icon icon-del') %>
</td>

Some files were not shown because too many files have changed in this diff Show More