Merge branch 'develop' into ouyangxuhua

Conflicts:
	app/views/projects/settings/_new_repositories.html.erb
szzh
ouyangxuhua 10 years ago
commit fa08935f68

1
.gitignore vendored

@ -29,3 +29,4 @@ vendor/cache
/public/images/avatars /public/images/avatars
/public/files /public/files
/tags /tags
/config/initializers/gitlab_config.rb

@ -1,4 +1,4 @@
source 'http://ruby.taobao.org' source 'https://ruby.taobao.org'
#source 'http://ruby.sdutlinux.org/' #source 'http://ruby.sdutlinux.org/'
unless RUBY_PLATFORM =~ /w32/ unless RUBY_PLATFORM =~ /w32/
@ -6,6 +6,8 @@ unless RUBY_PLATFORM =~ /w32/
gem 'iconv' gem 'iconv'
end end
gem 'grack', path:'lib/grack'
gem 'gitlab', path: 'lib/gitlab-cli'
gem 'rest-client' gem 'rest-client'
gem "mysql2", "= 0.3.18" gem "mysql2", "= 0.3.18"
gem 'redis-rails' gem 'redis-rails'
@ -27,20 +29,36 @@ gem 'ruby-ole'
gem 'rails_kindeditor',path:'lib/rails_kindeditor' gem 'rails_kindeditor',path:'lib/rails_kindeditor'
#gem "rmagick", ">= 2.0.0" #gem "rmagick", ">= 2.0.0"
gem 'binding_of_caller' gem 'binding_of_caller'
gem 'chinese_pinyin'
# gem 'sunspot_rails', '~> 1.3.3'
# gem 'sunspot_solr'
# gem 'sunspot'
# gem 'progress_bar'
gem 'ansi'
gem 'kaminari'
gem 'elasticsearch-model'
gem 'elasticsearch-rails'
group :development do group :development do
gem 'grape-swagger' gem 'grape-swagger'
gem 'better_errors', '~> 1.1.0' gem 'better_errors', '~> 1.1.0'
gem 'rack-mini-profiler', '~> 0.9.3' gem 'rack-mini-profiler', '~> 0.9.3'
if RUBY_PLATFORM =~ /w32/
gem 'win32console'
end
end end
group :development, :test do group :development, :test do
unless RUBY_PLATFORM =~ /w32/ unless RUBY_PLATFORM =~ /w32/
gem 'pry-rails' gem 'pry-rails'
if RUBY_VERSION >= '2.0.0' if RUBY_VERSION >= '2.0.0'
gem 'pry-byebug' gem 'pry-byebug'
end end
gem 'pry-stack_explorer' gem 'pry-stack_explorer'
if RUBY_PLATFORM =~ /darwin/
gem 'puma'
end
end end
gem 'rspec-rails', '~> 3.0' gem 'rspec-rails', '~> 3.0'
@ -54,7 +72,7 @@ group :assets do
gem 'coffee-rails', '~> 3.2.1' gem 'coffee-rails', '~> 3.2.1'
# See https://github.com/sstephenson/execjs#readme for more supported runtimes # See https://github.com/sstephenson/execjs#readme for more supported runtimes
gem 'therubyracer', :platforms => :ruby gem 'therubyracer', :platforms => :ruby
gem 'uglifier', '>= 1.0.3' gem 'uglifier', '>= 1.0.3'
end end

@ -272,7 +272,7 @@ module Mobile
params do params do
requires :token,type:String requires :token,type:String
requires :course_id,type:Integer,desc: '课程id' requires :course_id,type:Integer,desc: '课程id'
optional :name,type:String,desc:'学生的姓名或者昵称或者学号可能包含的字符' optional :name,type:String,desc:'学生的姓名或者登录名或者学号可能包含的字符'
end end
get ":course_id/members" do get ":course_id/members" do
cs = CoursesService.new cs = CoursesService.new

@ -82,7 +82,7 @@ module Mobile
desc "用户搜索" desc "用户搜索"
params do params do
requires :name, type: String, desc: '用户名关键字' requires :name, type: String, desc: '用户名关键字'
requires :search_by, type: String,desc: '搜索依据0 昵称1 用户名2 邮箱,3 昵称和姓名' requires :search_by, type: String,desc: '搜索依据0 登录名1 用户名2 邮箱,3 登录名和姓名'
optional :is_search_assitant,type:Integer,desc:'是否搜索注册用户来作为助教' optional :is_search_assitant,type:Integer,desc:'是否搜索注册用户来作为助教'
optional :course_id,type:Integer,desc: '课程id搜索注册用户不为该课程教师的其他用户' optional :course_id,type:Integer,desc: '课程id搜索注册用户不为该课程教师的其他用户'
optional :user_id,type:Integer,desc:'用户id' optional :user_id,type:Integer,desc:'用户id'

@ -0,0 +1,3 @@
# Place all the behaviors and hooks related to the matching controller here.
# All this logic will automatically be available in application.js.
# You can use CoffeeScript in this file: http://jashkenas.github.com/coffee-script/

@ -0,0 +1,3 @@
# Place all the behaviors and hooks related to the matching controller here.
# All this logic will automatically be available in application.js.
# You can use CoffeeScript in this file: http://jashkenas.github.com/coffee-script/

@ -0,0 +1,3 @@
# Place all the behaviors and hooks related to the matching controller here.
# All this logic will automatically be available in application.js.
# You can use CoffeeScript in this file: http://jashkenas.github.com/coffee-script/

@ -0,0 +1,3 @@
# Place all the behaviors and hooks related to the matching controller here.
# All this logic will automatically be available in application.js.
# You can use CoffeeScript in this file: http://jashkenas.github.com/coffee-script/

@ -0,0 +1,3 @@
# Place all the behaviors and hooks related to the matching controller here.
# All this logic will automatically be available in application.js.
# You can use CoffeeScript in this file: http://jashkenas.github.com/coffee-script/

@ -0,0 +1,3 @@
# Place all the behaviors and hooks related to the matching controller here.
# All this logic will automatically be available in application.js.
# You can use CoffeeScript in this file: http://jashkenas.github.com/coffee-script/

@ -0,0 +1,3 @@
# Place all the behaviors and hooks related to the matching controller here.
# All this logic will automatically be available in application.js.
# You can use CoffeeScript in this file: http://jashkenas.github.com/coffee-script/

@ -0,0 +1,3 @@
# Place all the behaviors and hooks related to the matching controller here.
# All this logic will automatically be available in application.js.
# You can use CoffeeScript in this file: http://jashkenas.github.com/coffee-script/

@ -0,0 +1,3 @@
# Place all the behaviors and hooks related to the matching controller here.
# All this logic will automatically be available in application.js.
# You can use CoffeeScript in this file: http://jashkenas.github.com/coffee-script/

@ -0,0 +1,3 @@
// Place all the styles related to the org_courses controller here.
// They will automatically be included in application.css.
// You can use Sass (SCSS) here: http://sass-lang.com/

@ -0,0 +1,3 @@
// Place all the styles related to the org_document_comment controller here.
// They will automatically be included in application.css.
// You can use Sass (SCSS) here: http://sass-lang.com/

@ -0,0 +1,3 @@
// Place all the styles related to the OrgMember controller here.
// They will automatically be included in application.css.
// You can use Sass (SCSS) here: http://sass-lang.com/

@ -0,0 +1,3 @@
// Place all the styles related to the org_projects controller here.
// They will automatically be included in application.css.
// You can use Sass (SCSS) here: http://sass-lang.com/

@ -0,0 +1,3 @@
// Place all the styles related to the org_subfields controller here.
// They will automatically be included in application.css.
// You can use Sass (SCSS) here: http://sass-lang.com/

@ -0,0 +1,3 @@
// Place all the styles related to the organizations controller here.
// They will automatically be included in application.css.
// You can use Sass (SCSS) here: http://sass-lang.com/

@ -0,0 +1,3 @@
// Place all the styles related to the shield_activities controller here.
// They will automatically be included in application.css.
// You can use Sass (SCSS) here: http://sass-lang.com/

@ -0,0 +1,3 @@
// Place all the styles related to the subfield_subdomain_dirs controller here.
// They will automatically be included in application.css.
// You can use Sass (SCSS) here: http://sass-lang.com/

@ -0,0 +1,3 @@
// Place all the styles related to the SystemMessages controller here.
// They will automatically be included in application.css.
// You can use Sass (SCSS) here: http://sass-lang.com/

@ -21,25 +21,36 @@ class AccountController < ApplicationController
# prevents login action to be filtered by check_if_login_required application scope filter # prevents login action to be filtered by check_if_login_required application scope filter
skip_before_filter :check_if_login_required skip_before_filter :check_if_login_required
# Login request and validation # Login request and validation
def login def login
if request.get? if request.get?
@login = params[:login] || true
if User.current.logged? if User.current.logged?
redirect_to home_url redirect_to user_path(User.current)
else
render :layout => 'login'
end end
else else
authenticate_user authenticate_user
end end
end end
# 服务协议
def agreement
render :layout => 'static_base'
end
def about_us
render :layout => 'static_base'
end
# Log out current user and redirect to welcome page # Log out current user and redirect to welcome page
def logout def logout
if User.current.anonymous? if User.current.anonymous?
redirect_to home_url redirect_to signin_path
elsif request.post? elsif request.post?
logout_user logout_user
redirect_to home_url redirect_to signin_path
end end
# display the logout form # display the logout form
end end
@ -50,16 +61,16 @@ class AccountController < ApplicationController
# Lets user choose a new password # Lets user choose a new password
def lost_password def lost_password
(redirect_to(home_url); return) unless Setting.lost_password? (redirect_to(signin_path); return) unless Setting.lost_password?
if params[:token] if params[:token]
@token = Token.find_token("recovery", params[:token].to_s) @token = Token.find_token("recovery", params[:token].to_s)
if @token.nil? || @token.expired? if @token.nil? || @token.expired?
redirect_to home_url redirect_to signin_path
return return
end end
@user = @token.user @user = @token.user
unless @user && @user.active? unless @user && @user.active?
redirect_to home_url redirect_to signin_path
return return
end end
if request.post? if request.post?
@ -71,7 +82,7 @@ class AccountController < ApplicationController
return return
end end
end end
render :template => "account/password_recovery" render :template => "account/password_recovery"
return return
else else
if request.post? if request.post?
@ -79,6 +90,7 @@ class AccountController < ApplicationController
# user not found or not active # user not found or not active
unless user && user.active? unless user && user.active?
flash.now[:error] = l(:notice_account_unknown_email) flash.now[:error] = l(:notice_account_unknown_email)
render :layout => 'static_base'
return return
end end
# user cannot change its password # user cannot change its password
@ -91,16 +103,17 @@ class AccountController < ApplicationController
if token.save if token.save
Mailer.run.lost_password(token) Mailer.run.lost_password(token)
flash[:notice] = l(:notice_account_lost_email_sent) flash[:notice] = l(:notice_account_lost_email_sent)
redirect_to signin_url redirect_to lost_password_path
return return
end end
end end
render :layout => 'static_base'
end end
end end
# User self-registration # User self-registration
def register def register
(redirect_to(home_url); return) unless Setting.self_registration? || session[:auth_source_registration] (redirect_to(signin_path); return) unless Setting.self_registration? || session[:auth_source_registration]
if request.get? if request.get?
session[:auth_source_registration] = nil session[:auth_source_registration] = nil
@user = User.new(:language => current_language.to_s) @user = User.new(:language => current_language.to_s)
@ -128,10 +141,12 @@ class AccountController < ApplicationController
end end
when '3' when '3'
#register_automatically(@user) #register_automatically(@user)
unless @user.new_record? if !@user.new_record?
self.logged_user = @user self.logged_user = @user
flash[:notice] = l(:notice_account_activated) flash[:notice] = l(:notice_account_activated)
redirect_to my_account_url redirect_to my_account_url
else
redirect_to signin_path
end end
else else
#register_manually_by_administrator(@user) #register_manually_by_administrator(@user)
@ -175,11 +190,11 @@ class AccountController < ApplicationController
# Token based account activation # Token based account activation
def activate def activate
(redirect_to(home_url); return) unless Setting.self_registration? && params[:token].present? (redirect_to(signin_path); return) unless Setting.self_registration? && params[:token].present?
token = Token.find_token('register', params[:token].to_s) token = Token.find_token('register', params[:token].to_s)
(redirect_to(home_url); return) unless token and !token.expired? (redirect_to(signin_path); return) unless token and !token.expired?
user = token.user user = token.user
(redirect_to(home_url); return) unless user.registered? (redirect_to(signin_path); return) unless user.registered?
user.activate user.activate
if user.save if user.save
token.destroy token.destroy
@ -266,7 +281,7 @@ class AccountController < ApplicationController
user = User.find_or_initialize_by_identity_url(identity_url) user = User.find_or_initialize_by_identity_url(identity_url)
if user.new_record? if user.new_record?
# Self-registration off # Self-registration off
(redirect_to(home_url); return) unless Setting.self_registration? (redirect_to(signin_path); return) unless Setting.self_registration?
# Create on the fly # Create on the fly
user.login = registration['nickname'] unless registration['nickname'].nil? user.login = registration['nickname'] unless registration['nickname'].nil?
@ -353,12 +368,15 @@ class AccountController < ApplicationController
def invalid_credentials def invalid_credentials
logger.warn "Failed login for '#{params[:username]}' from #{request.remote_ip} at #{Time.now.utc}" logger.warn "Failed login for '#{params[:username]}' from #{request.remote_ip} at #{Time.now.utc}"
flash.now[:error] = l(:notice_account_invalid_creditentials) flash[:error] = l(:notice_account_invalid_creditentials)
# render :layout => 'login'
redirect_to signin_path(:login=>true)
end end
def invalid_credentials_new def invalid_credentials_new
logger.warn "Failed login for '#{params[:username]}' from #{request.remote_ip} at #{Time.now.utc}" logger.warn "Failed login for '#{params[:username]}' from #{request.remote_ip} at #{Time.now.utc}"
flash.now[:error] = l(:notice_account_invalid_creditentials_new) flash[:error] = l(:notice_account_invalid_creditentials_new)
render signin_path(:login=>true)
end end
# Register a user for email activation. # Register a user for email activation.

@ -79,6 +79,11 @@ class AdminController < ApplicationController
end end
end end
# 系统消息
def messages
@admin_messages = SystemMessage.new
end
def plugins def plugins
@plugins = Redmine::Plugin.all @plugins = Redmine::Plugin.all
end end
@ -341,11 +346,16 @@ class AdminController < ApplicationController
#学校列表 #学校列表
def schools def schools
@school_name = params[:school_name] @school_name = params[:school_name]
if @school_name if @school_name && @school_name != ''
@schools = School.where("name like '%#{@school_name}%'") @schools = School.where("name like '%#{@school_name}%'")
else elsif @school_name.nil?
@schools = School.all @schools = []
else @school_name && @school_name == ' '
@schools = School.where('1=1')
end end
@school_count = @schools.count
@school_pages = Paginator.new @school_count, 100, params['page'] || 1
@schools = paginateHelper @schools,100
respond_to do |format| respond_to do |format|
format.html format.html
end end
@ -395,4 +405,78 @@ class AdminController < ApplicationController
end end
#留言列表
def leave_messages
@jour = JournalsForMessage.find_by_sql("SELECT * FROM journals_for_messages AS j1
WHERE j1.jour_type IN ('Course','Principal') AND (j1.m_parent_id IS NULL OR (j1.m_parent_id IN (SELECT id FROM journals_for_messages WHERE jour_type IN ('Course','Principal')))) order by created_on desc")
@jour = paginateHelper @jour,30
@page = (params['page'] || 1).to_i - 1
respond_to do |format|
format.html
end
end
#帖子
def messages_list
@memo = Memo.reorder("created_at desc")
@memo = paginateHelper @memo,30
@page = (params['page'] || 1).to_i - 1
respond_to do |format|
format.html
end
end
#课程讨论区的帖子
def course_messages
@course_ms=Message.joins("join boards on messages.board_id=boards.id where boards.course_id is not NULL").reorder('created_on desc')
@course_ms = paginateHelper @course_ms,30
@page = (params['page'] || 1).to_i - 1
respond_to do |format|
format.html
end
end
#项目讨论区的帖子
def project_messages
@project_ms=Message.joins("join boards on messages.board_id=boards.id where boards.project_id != -1").reorder('created_on desc')
@project_ms = paginateHelper @project_ms,30
@page = (params['page'] || 1).to_i - 1
respond_to do |format|
format.html
end
end
#通知
def notices
@news = News.where('course_id is not NULL').order('created_on desc')
@news = paginateHelper @news,30
@page = (params['page'] || 1).to_i - 1
respond_to do |format|
format.html
end
end
#最近登录用户列表
def latest_login_users
scope = User.order('last_login_on desc')
scope = scope.where("last_login_on>= '#{params[:startdate]} 00:00:00'") if params[:startdate].present?
scope =scope.where("last_login_on <= '#{params[:enddate]} 23:59:59'") if params[:enddate].present?
@users = scope
@users = paginateHelper @users,30
@page = (params['page'] || 1).to_i - 1
respond_to do |format|
format.html
end
end
#作业
def homework
@homework = HomeworkCommon.order('end_time desc')
@homework = paginateHelper @homework,30
@page = (params['page'] || 1).to_i - 1
respond_to do |format|
format.html
end
end
end end

@ -38,7 +38,8 @@ class ApplicationController < ActionController::Base
protect_from_forgery protect_from_forgery
def handle_unverified_request def handle_unverified_request
super super
cookies.delete(autologin_cookie_name) raise(ActionController::InvalidAuthenticityToken)
# cookies.delete(autologin_cookie_name)
end end
before_filter :find_first_page before_filter :find_first_page
@ -311,7 +312,8 @@ class ApplicationController < ActionController::Base
elsif @course elsif @course
allowed = User.current.allowed_to?({:controller => ctrl, :action => action}, @course || @courses, :global => global) allowed = User.current.allowed_to?({:controller => ctrl, :action => action}, @course || @courses, :global => global)
else else
allowed = User.current.allowed_to?({:controller => ctrl, :action => action}, @project || @projects, :global => global) # allowed = User.current.allowed_to?({:controller => ctrl, :action => action}, @project || @projects, :global => global)
allowed = true
end end
allowed allowed
end end
@ -381,6 +383,11 @@ class ApplicationController < ActionController::Base
if allowed if allowed
true true
else else
if params[:action] == 'show'
#更新申请结果反馈消息的状态
messages = CourseMessage.where("course_message_type =? and course_id =? and user_id =? and viewed =?", 'CourseRequestDealResult', @course.id, User.current.id, false)
messages.update_all(:viewed => true)
end
if @course && @course.archived? if @course && @course.archived?
render_403 :message => :notice_not_authorized_archived_project render_403 :message => :notice_not_authorized_archived_project
else else
@ -412,6 +419,8 @@ class ApplicationController < ActionController::Base
@project = Project.find(params[:project_id]) @project = Project.find(params[:project_id])
elsif params[:course_id] elsif params[:course_id]
@course = Course.find(params[:course_id]) @course = Course.find(params[:course_id])
elsif params[:org_subfield_id]
@org_subfield = OrgSubfield.find(params[:org_subfield_id])
end end
rescue ActiveRecord::RecordNotFound rescue ActiveRecord::RecordNotFound
render_404 render_404
@ -557,12 +566,13 @@ class ApplicationController < ActionController::Base
end end
def redirect_back_or_default(default, options={}) def redirect_back_or_default(default, options={})
back_url = params[:back_url].to_s back_url = '' #params[:back_url].to_s
if back_url.present? if back_url.present?
begin begin
uri = URI.parse(back_url) uri = URI.parse(back_url)
# do not redirect user to another host or to the login or register page # do not redirect user to another host or to the login or register page
if (uri.relative? || (uri.host == request.host)) && !uri.path.match(%r{/(login|account/register)}) if (uri.relative? || (uri.host == request.host)) && !uri.path.match(%r{/(login|account/register)})
back_url = back_url.gsub(%r{\/users\/(\d+)},"/users/"+default.id.to_s) if default.is_a?(:User)
redirect_to(back_url) redirect_to(back_url)
return return
end end
@ -656,7 +666,8 @@ class ApplicationController < ActionController::Base
if api_request? if api_request?
logger.error "Form authenticity token is missing or is invalid. API calls must include a proper Content-type header (text/xml or text/json)." logger.error "Form authenticity token is missing or is invalid. API calls must include a proper Content-type header (text/xml or text/json)."
end end
render_error "Invalid form authenticity token." #render_error "Invalid form authenticity token."
redirect_to signin_path(:login=>true)
end end
def render_feed(items, options={}) def render_feed(items, options={})
@ -755,10 +766,11 @@ class ApplicationController < ActionController::Base
# Returns a string that can be used as filename value in Content-Disposition header # Returns a string that can be used as filename value in Content-Disposition header
def filename_for_content_disposition(name) def filename_for_content_disposition(name)
request.env['HTTP_USER_AGENT'] =~ %r{MSIE} ? ERB::Util.url_encode(name) : name request.env['HTTP_USER_AGENT'] =~ %r{MSIE|Trident} ? ERB::Util.url_encode(name) : name
end end
def api_request? def api_request?
return false if params[:controller] == 'at'
%w(xml json).include? params[:format] %w(xml json).include? params[:format]
end end

@ -0,0 +1,164 @@
#coding=utf-8
class AtController < ApplicationController
respond_to :json
def show
@logger = Logger.new(Rails.root.join('log', 'at.log').to_s)
users = find_at_users(params[:type], params[:id])
@users = users
@users = users.uniq { |u| u.id }.delete_if { |u| u.id == User.current.id }.sort{|x,y| to_pinyin(x.show_name) <=> to_pinyin(y.show_name)} if users
end
private
def to_pinyin(s)
Pinyin.t(s).downcase
end
def find_at_users(type, id)
@logger.info("#{type}, #{id}")
case type
when "Issue"
find_issue(id)
when 'Project'
find_project(id)
when 'Course'
find_course(id)
when 'Activity', 'CourseActivity', 'ForgeActivity','UserActivity', 'OrgActivity','PrincipalActivity'
find_activity(id, type)
when 'Attachment'
find_attachment(id)
when 'Message'
find_message(id)
when 'HomeworkCommon'
find_homework(id)
when 'Topic'
find_topic(id)
when 'JournalsForMessage'
find_journals_for_message(id)
when 'Principal'
find_principal(id)
when 'All'
nil
else
nil
end
end
def find_topic(id)
end
def find_issue(id)
#1. issues list persons
#2. project persons
issue = Issue.find(id)
journals = issue.journals
at_persons = journals.map(&:user) + issue.project.users
at_persons.uniq { |u| u.id }.delete_if { |u| u.id == User.current.id }
end
def find_project(id)
return [] if id<0
at_persons = Project.find(id).users
at_persons.delete_if { |u| u.id == User.current.id }
end
def find_course(id)
at_persons = Course.find(id).users
at_persons.delete_if { |u| u.id == User.current.id }
end
def find_activity(id, type)
## 基本上是本类型中的 加上所属类型的用户
case type
when 'Activity'
activity = Activity.find(id)
(find_at_users(activity.act_type, activity.act_id) ||[]) +
(find_at_users(activity.activity_container_type, activity.activity_container_id) || [])
when 'CourseActivity'
activity = CourseActivity.find(id)
(find_at_users(activity.course_act_type, activity.course_act_id) || []) + (find_course(activity.course.id) || [])
when 'ForgeActivity'
activity = ForgeActivity.find(id)
(find_at_users(activity.forge_act_type, activity.forge_act_id) ||[]) +
(find_project(activity.project_id) || [])
when 'UserActivity'
activity = UserActivity.find(id)
(find_at_users(activity.act_type, activity.act_id) || []) +
(find_at_users(activity.container_type, activity.container_id) || [])
when 'OrgActivity'
activity = OrgActivity.find(id)
(find_at_users(activity.org_act_type, activity.org_act_id) || []) +
(find_at_users(activity.container_type, activity.container_id) || [])
when 'PrincipalActivity'
activity = PrincipalActivity.find(id)
find_at_users(activity.principal_act_type, activity.principal_act_id)
else
nil
end
end
#作业应该是关联课程,取课程的用户列表
def find_homework(id)
homework = HomeworkCommon.find(id)
find_course(homework.course_id)
end
def find_attachment(id)
attachment = Attachment.find(id)
find_at_users(attachment.container_type, attachment.container_id)
end
#Message
def find_message(id)
message = Message.find(id)
at_persons = message.board.messages.map(&:author)
(at_persons || []) + (find_project(message.board.project_id)||[])
end
#News
def find_news(id)
find_project(News.find(id).project_id)
end
#JournalsForMessage
def find_journals_for_message(id)
jounrnal = JournalsForMessage.find(id)
if jounrnal.jour_type == 'Principal'
[jounrnal.user] + (JournalsForMessage.where(m_reply_id: id).map(&:user) || [])
else
find_at_users(jounrnal.jour_type, jounrnal.jour_id)
end
end
#Poll
def find_poll(id)
end
#Journal
def find_journal(id)
end
#Document
def find_document(id)
find_project(Document.find(id).project_id)
end
#ProjectCreateInfo
def find_project_create_info(id)
end
#Principal
def find_principal(id)
end
#BlogComment
def find_blog_comment(id)
blog = BlogComment.find(id).blog
blog.users
end
end

@ -185,7 +185,6 @@ class AttachmentsController < ApplicationController
end end
@attachment.filename = params[:filename].presence || Redmine::Utils.random_hex(16) @attachment.filename = params[:filename].presence || Redmine::Utils.random_hex(16)
saved = @attachment.save saved = @attachment.save
respond_to do |format| respond_to do |format|
format.js format.js
format.api { format.api {
@ -198,12 +197,43 @@ class AttachmentsController < ApplicationController
end end
end end
def upload_attachment_version
@flag = false
Attachment.transaction do
@old_attachment = Attachment.find params[:old_attachment_id]
#取出当前上传的文件
@attachment = Attachment.find(params[:attachments ].first[1][:attachment_id])
#将需要修改的记录保存到历史记录
@history = AttachmentHistory.new
@history.attributes = @old_attachment.attributes.dup.except("id")
@history.attachment_id = params[:old_attachment_id]
#需要更新版本号,需要拿到原来该文件最大的历史版本号
@old_history = @old_attachment.attachment_histories.reorder('version desc').first
@history.version = @old_history.nil? ? 1 : @old_history.version + 1
@history.save #历史记录保存完毕
#将最新保存的记录 数据替换到 需要修改的文件记录
@old_attachment.attributes = @attachment.attributes.dup.except("id","container_id","container_type","is_public")
@old_attachment.save
#删除当前记录
@attachment.delete
@flag = true
end
respond_to do |format|
format.js
end
end
def destroy def destroy
if @attachment.container.respond_to?(:init_journal) if @attachment.container.respond_to?(:init_journal)
@attachment.container.init_journal(User.current) @attachment.container.init_journal(User.current)
end end
if @attachment.container if @attachment.container
@attachment.container.attachments.delete(@attachment) if @attachment.container_type == "Issue"
@attachment.destroy
else
@attachment.container.attachments.delete(@attachment)
end
else else
@attachment.destroy @attachment.destroy
end end
@ -227,6 +257,8 @@ class AttachmentsController < ApplicationController
format.js format.js
elsif @attachment.container.is_a?(Message) elsif @attachment.container.is_a?(Message)
format.html { redirect_to_referer_or new_board_message_path(@attachment.container) } format.html { redirect_to_referer_or new_board_message_path(@attachment.container) }
elsif @attachment.container.is_a?(BlogComment)
format.html { redirect_to_referer_or user_blog_blog_comment_path(:user_id=>@attachment.container.author.id,:blog_id=>@attachment.container.blog_id,:id=>@attachment.container.id)}
elsif @course.nil? elsif @course.nil?
format.html { redirect_to_referer_or forum_memo_path(@attachment.container.forum, @attachment.container) } format.html { redirect_to_referer_or forum_memo_path(@attachment.container.forum, @attachment.container) }
else else
@ -238,6 +270,10 @@ class AttachmentsController < ApplicationController
format.html { redirect_to_referer_or respond_path(@attachment.container) } format.html { redirect_to_referer_or respond_path(@attachment.container) }
elsif !@attachment.container.nil? && @attachment.container.is_a?(PhoneAppVersion) elsif !@attachment.container.nil? && @attachment.container.is_a?(PhoneAppVersion)
format.html { redirect_to_referer_or mobile_version_path } format.html { redirect_to_referer_or mobile_version_path }
elsif !@attachment.container.nil? && @attachment.container.is_a?(OrgSubfield)
format.html {redirect_to_referer_or org_subfield_files_path(@attachment.container)}
elsif !@attachment.container.nil? && @attachment.container.is_a?(OrgDocumentComment)
format.html {redirect_to_referer_or org_document_comment_path(@attachment.container)}
else else
if @project.nil? if @project.nil?
format.html { redirect_to_referer_or forum_memo_path(@attachment.container.forum, @attachment.container) } format.html { redirect_to_referer_or forum_memo_path(@attachment.container.forum, @attachment.container) }
@ -249,7 +285,7 @@ class AttachmentsController < ApplicationController
format.js format.js
end end
end end
def delete_homework def delete_homework
@bid = @attachment.container.bid @bid = @attachment.container.bid
# Make sure association callbacks are called # Make sure association callbacks are called
@ -312,13 +348,13 @@ class AttachmentsController < ApplicationController
end end
respond_to do |format| respond_to do |format|
format.js format.js
end end
rescue NoMethodError rescue NoMethodError
@save_flag = false @save_flag = false
@save_message = [] << l(:error_attachment_empty) @save_message = [] << l(:error_attachment_empty)
respond_to do |format| respond_to do |format|
format.js format.js
end end
end end
@ -434,6 +470,46 @@ class AttachmentsController < ApplicationController
end end
end end
def add_exist_file_to_org_subfield
file = Attachment.find(params[:file_id])
org_subfields = params[:org_subfields][:org_subfield]
@message = ""
org_subfields.each do |org_subfield|
s = OrgSubfield.find(org_subfield)
if s.attachments.include?file
if @message && @message == ""
@message += l(:label_resource_subfield_prompt) + c.name + l(:label_contain_resource) + file.filename + l(:label_quote_resource_failed)
next
else
@message += "<br/>" + l(:label_resource_subfield_prompt) + c.name + l(:label_contain_resource) + file.filename + l(:label_quote_resource_failed)
next
end
end
attach_copied_obj = file.copy
attach_copied_obj.tag_list.add(file.tag_list) # tag关联
attach_copied_obj.container = s
attach_copied_obj.created_on = Time.now
attach_copied_obj.author_id = User.current.id
attach_copied_obj.copy_from = file.copy_from.nil? ? file.id : file.copy_from
if attach_copied_obj.attachtype == nil
attach_copied_obj.attachtype = 4
end
@obj = s
@save_flag = attach_copied_obj.save
@save_message = attach_copied_obj.errors.full_messages
update_quotes attach_copied_obj
end
respond_to do |format|
format.js
end
rescue NoMethodError
@save_flag = false
@save_message = [] << l(:label_resource_subfield_empty_select)
respond_to do |format|
format.js
end
end
def update_quotes attachment def update_quotes attachment
if attachment.copy_from if attachment.copy_from
attachments = Attachment.find_by_sql("select * from attachments where copy_from = #{attachment.copy_from} or id = #{attachment.copy_from}") attachments = Attachment.find_by_sql("select * from attachments where copy_from = #{attachment.copy_from} or id = #{attachment.copy_from}")
@ -448,6 +524,15 @@ class AttachmentsController < ApplicationController
end end
end end
#找到文件的所有的历史版本
def attachment_versions
@attachment = Attachment.find(params[:id])
@attachment_histories = @attachment.attachment_histories
respond_to do |format|
format.js
end
end
private private
def find_project def find_project
@attachment = Attachment.find(params[:id]) @attachment = Attachment.find(params[:id])
@ -515,7 +600,7 @@ private
def has_login def has_login
unless @attachment && @attachment.container_type == "PhoneAppVersion" unless @attachment && @attachment.container_type == "PhoneAppVersion"
render_403 unless User.current.logged? render_403 if !User.current.logged? && !(@attachment.container_type == 'OrgSubfield' && @attachment.container.organization.allow_guest_download) && !(@attachment.container_type == 'OrgDocumentComment' && @attachment.container.organization.allow_guest_download)
end end
end end
end end

@ -10,7 +10,7 @@ class AvatarController < ApplicationController
unless request.content_type == 'application/octet-stream' unless request.content_type == 'application/octet-stream'
@source_type = params[:source_type] @source_type = params[:source_type]
@source_id = params[:source_id] @source_id = params[:source_id]
@temp_file = params[:avatar][:image] @temp_file = params[:avatar][:image]
@image_file = @temp_file.original_filename @image_file = @temp_file.original_filename
else else
unless request.raw_post.nil? unless request.raw_post.nil?
@ -23,7 +23,7 @@ class AvatarController < ApplicationController
#image_file.force_encoding("UTF-8") if filename.respond_to?(:force_encoding) #image_file.force_encoding("UTF-8") if filename.respond_to?(:force_encoding)
else else
@image_file=params[:filename] @image_file=params[:filename]
end end
@temp_file = StringIO.new(@temp_file) @temp_file = StringIO.new(@temp_file)
end end
end end

@ -0,0 +1,160 @@
class BlogCommentsController < ApplicationController
include ApplicationHelper
before_filter :find_user
def index
end
def create
if User.current.logged?
@article = BlogComment.new
@article.author = User.current
@article.blog_id = params[:blog_id]
@article.safe_attributes = params[:blog_comment]
if request.post?
@article.save_attachments(params[:attachments])
if @article.save
# 更新kindeditor上传的图片资源所有者
# if params[:asset_id]
# ids = params[:asset_id].split(',')
# update_kindeditor_assets_owner ids,@article.id,OwnerTypeHelper::BLOGCOMMENT
# end
render_attachment_warning_if_needed(@article)
else
end
redirect_to user_blogs_path(:user_id=>params[:user_id])
else
respond_to do |format|
format.html {
render :layout => 'new_base_user'
}
end
end
else
redirect_to signin_path
end
end
def new
respond_to do |format|
format.html {render :layout=>'new_base_user'}
end
end
def show
@article = BlogComment.find(params[:id])
respond_to do |format|
format.html {render :layout=>'new_base_user'}
end
end
def update
@article = BlogComment.find(params[:id])
@article.safe_attributes = params[:blog_comment]
@article.save_attachments(params[:attachments])
if @article.save
render_attachment_warning_if_needed(@article)
else
end
if params[:in_act]
redirect_to user_path(params[:user_id])
else
if @article.id.eql?(User.find(params[:user_id]).blog.homepage_id)
redirect_to user_path(params[:user_id])
else
redirect_to user_blog_blog_comment_path(:user_id=>params[:user_id],:blog_id=>params[:blog_id],:id=>params[:id])
end
end
end
def destroy
@article = BlogComment.find(params[:id])
if @article.parent_id.nil? #如果是文章被删那么跳转到用户博客界面如果带了course_id过来那么就要跳转到课程首页
if params[:course_id] #如果带了课程id过来说明这是课程大纲不要删除只需取消课程大纲就ok了
@course = Course.find(params[:course_id])
@course.outline = 0
@course.save
redirect_to course_path(:id=>params[:course_id])
else
@article.children.delete
@article.delete
redirect_to user_blogs_path(:user_id=>User.current)
end
else#如果是回复被删,
if params[:course_id] #如果带了course_id过来了那么这是要跳到课程大纲去的
@article.delete
redirect_to syllabus_course_path(:id=>params[:course_id])
else
root = @article.root
@article.delete
redirect_to user_blog_blog_comment_path(:user_id=>root.author_id,:blog_id=>root.blog_id,:id=>root.id)
end
end
end
def edit
@article = BlogComment.find(params[:id])
respond_to do |format|
format.html {render :layout=>'new_base_user'}
end
end
def quote
@blogComment = BlogComment.find(params[:id])
@subject = @blogComment.title
@subject = "RE: #{@subject}" unless @subject.starts_with?('RE:')
@content = "> #{ll(Setting.default_language, :text_user_wrote, @blogComment.author.realname)}\n> "
@temp = BlogComment.new
@course_id = params[:course_id]
@temp.content = "<blockquote>#{ll(Setting.default_language, :text_user_wrote, @blogComment.author.realname)} <br/>#{@blogComment.content.html_safe}</blockquote>".html_safe
respond_to do | format|
format.js
end
end
#回复
def reply
if params[:in_user_center]
@in_user_center = true
end
@article = BlogComment.find(params[:id]).root
@quote = params[:quote][:quote]
@blogComment = BlogComment.new
@blogComment.author = User.current
@blogComment.blog = Blog.find(params[:blog_id])
params[:blog_comment][:sticky] = params[:blog_comment][:sticky] || 0
params[:blog_comment][:locked] = params[:blog_comment][:locked] || 0
@blogComment.safe_attributes = params[:blog_comment]
@blogComment.content = @quote + @blogComment.content
@blogComment.title = "RE: #{@article.title}" unless params[:blog_comment][:title]
@article.children << @blogComment
@article.save
# @article.update_attribute(:updated_on, @blogComment.updated_on)
@user_activity_id = params[:user_activity_id]
user_activity = UserActivity.where("act_type='BlogComment' and act_id =#{@article.id}").first
if user_activity
user_activity.updated_at = Time.now
user_activity.save
end
attachments = Attachment.attach_files(@blogComment, params[:attachments])
render_attachment_warning_if_needed(@blogComment)
#@article.save
# redirect_to user_blogs_path(:user_id=>params[:user_id])
respond_to do |format|
format.html {
if params[:course_id] #如果呆了course_id过来了那么这是要跳到课程大纲去的
redirect_to syllabus_course_path(:id=>params[:course_id])
else
redirect_to user_blog_blog_comment_path(:user_id=>@article.author_id,:blog_id=>@article.blog_id,:id=>@article)
end
}
format.js
end
rescue Exception => e #如果上面的代码执行发生异常就捕获
flash[:notice] = e.message
end
private
def find_user
@user = User.find(params[:user_id])
end
end

@ -0,0 +1,58 @@
class BlogsController < ApplicationController
before_filter :find_blog,:except => [:index,:create,:new,:set_homepage, :cancel_homepage]
before_filter :find_user
def index
@article = BlogComment.new
respond_to do |format|
format.html {render :layout=>'new_base_user'}
end
end
def create
end
def new
end
def show
end
def update
end
def destory
end
def edit
end
def set_homepage
@blog = Blog.find(params[:id])
@blog.update_attribute(:homepage_id, params[:article_id])
redirect_to user_blogs_path(params[:user_id])
end
def cancel_homepage
@blog = Blog.find(params[:id])
@blog.update_attribute(:homepage_id, nil)
redirect_to user_blogs_path(params[:user_id])
end
private
def find_blog
if params[:blog_id]
@blog = Blog.find(params[:blog_id])
else
render_404
end
if @blog.nil?
#如果某个user的blog不存在那么就创建一条
@blog = Blog.create(:name=>User.find(params[:id]).realname ,
:description=>'',
:author_id=>params[:id])
end
end
def find_user
@user = User.find(params[:user_id])
end
end

@ -18,8 +18,8 @@
class BoardsController < ApplicationController class BoardsController < ApplicationController
layout 'base_projects'#by young layout 'base_projects'#by young
default_search_scope :messages default_search_scope :messages
before_filter :find_project_by_project_id, :find_board_if_available before_filter :find_project_by_project_id, :find_board_if_available, :except => [:join_to_org_subfields]
before_filter :authorize, :except => [:new, :show, :create, :index] before_filter :authorize, :except => [:new, :show, :create, :index, :join_to_org_subfields]
accept_rss_auth :index, :show accept_rss_auth :index, :show
@ -67,65 +67,73 @@ class BoardsController < ApplicationController
end end
def show def show
respond_to do |format| # 讨论区消息状态更新(已读和未读)
format.js if @project
format.html { query_forge_messages = @board.messages
sort_init 'updated_on', 'desc' query_forge_messages.each do |query_forge_message|
sort_update 'created_on' => "#{Message.table_name}.created_on", query = query_forge_message.forge_messages
'replies' => "#{Message.table_name}.replies_count", query.each do |forge_message|
'updated_on' => "COALESCE(last_replies_messages.created_on, #{Message.table_name}.created_on)" if User.current.id == forge_message.user_id
forge_message.update_attributes(:viewed => true)
@topic_count = @board ? @board.topics.count : 0 end
if @project end
@topic_pages = Paginator.new @topic_count, per_page_option, params['page'] end
@topics = @board.topics. # 更新@消息为已读
reorder("#{Message.table_name}.sticky DESC, #{Message.table_name}.created_on desc"). @project.boards.each do |board|
includes(:last_reply). board.messages.each do |m|
limit(@topic_pages.per_page). User.current.at_messages.unviewed('Message', m.id).each {|x| x.viewed!}
offset(@topic_pages.offset). end
end
preload(:author, {:last_reply => :author}). elsif @course
all query_course_messages = @board.messages
elsif @course query_course_messages.each do |query_course_message|
# query = query_course_message.course_messages
# board_topics = @board ? @board.topics.reorder("#{Message.table_name}.sticky DESC, #{Message.table_name}.created_on desc"). query.each do |course_message|
# includes(:last_reply). if User.current.id == course_message.user_id
# # limit(@topic_pages.per_page). course_message.update_attributes(:viewed => true)
# # offset(@topic_pages.offset).
#
# preload(:author, {:last_reply => :author}).
# all : []
# @topics = paginateHelper board_topics,10
if( @board )
limit = 10;
pageno = params[:page];
if(pageno == nil || pageno=='')
dw_topic = nil;
if( params[:parent_id]!=nil && params[:parent_id]!='' )
dw_topic = @board.topics.where(id:params[:parent_id]).first();
end
if( dw_topic != nil )
dw_count = @board.topics.where('(sticky>?) or (sticky=? and created_on>?)',dw_topic.sticky,dw_topic.sticky,dw_topic.created_on).count();
dw_count = dw_count+1;
pageno = dw_count%10==0 ? (dw_count/limit) : (dw_count/limit+1)
end
end
if(pageno == nil || pageno=='')
pageno=1;
end
@topic_count = @board.topics.count();
@topic_pages = Paginator.new @topic_count, limit, pageno
@topics = @board.topics.reorder("#{Message.table_name}.sticky DESC, #{Message.table_name}.created_on desc").
limit(limit).offset(@topic_pages.offset).includes(:last_reply).
preload(:author, {:last_reply => :author}).all();
else
@topics = [];
end end
end end
end
end
sort_init 'updated_on', 'desc'
sort_update 'created_on' => "#{Message.table_name}.created_on",
'replies' => "#{Message.table_name}.replies_count",
'updated_on' => "COALESCE(last_replies_messages.created_on, #{Message.table_name}.created_on)"
@message = Message.new(:board => @board) @is_new = params[:is_new]
#modify by nwb @topic_count = @board ? @board.topics.count : 0
if @project
if @board
limit = 10;
@topic_count = @board.topics.count();
@topic_pages = (params[:page] ? params[:page].to_i + 1 : 0) *10
@topics = @board.topics.reorder("#{Message.table_name}.sticky DESC, COALESCE(last_replies_messages.created_on, #{Message.table_name}.created_on) desc").
limit(limit).offset(@topic_pages).includes(:last_reply).
preload(:author, {:last_reply => :author}).all();
else
@topics = [];
end
elsif @course
if (@board)
limit = 10;
@topic_count = @board.topics.count();
@topic_pages = (params[:page] ? params[:page].to_i + 1 : 0) *10
@topics = @board.topics.reorder("#{Message.table_name}.sticky DESC, COALESCE(last_replies_messages.created_on, #{Message.table_name}.created_on) desc").
limit(limit).offset(@topic_pages).includes(:last_reply).
preload(:author, {:last_reply => :author}).all();
else
@topics = [];
end
end
@page = params[:page] ? params[:page].to_i + 1 : 0
@message = Message.new(:board => @board)
#modify by nwb
respond_to do |format|
format.js
format.html {
if @project if @project
render :action => 'show', :layout => 'base_projects' render :action => 'show', :layout => 'base_projects'
elsif @course elsif @course
@ -135,10 +143,10 @@ class BoardsController < ApplicationController
} }
format.atom { format.atom {
@messages = @board.messages. @messages = @board.messages.
reorder('created_on DESC'). reorder('created_on DESC').
includes(:author, :board). includes(:author, :board).
limit(Setting.feeds_limit.to_i). limit(Setting.feeds_limit.to_i).
all all
if @project if @project
render_feed(@messages, :title => "#{@project}: #{@board}") render_feed(@messages, :title => "#{@project}: #{@board}")
elsif @course elsif @course
@ -192,6 +200,16 @@ class BoardsController < ApplicationController
redirect_to_settings_in_projects redirect_to_settings_in_projects
end end
def join_to_org_subfields
if params[:id]
@board = Board.find(params[:id])
@org_subfield_ids = params[:org_subfield_ids]
@org_subfield_ids.each do |id|
OrgSubfieldBoard.create(:org_subfield_id => id.to_i, :board_id => params[:id].to_i)
end
end
end
private private
def redirect_to_settings_in_projects def redirect_to_settings_in_projects
redirect_to settings_project_url(@project, :tab => 'boards') redirect_to settings_project_url(@project, :tab => 'boards')

@ -19,39 +19,56 @@ class CommentsController < ApplicationController
default_search_scope :news default_search_scope :news
include ApplicationHelper include ApplicationHelper
model_object News model_object News
before_filter :find_model_object before_filter :find_model_object
before_filter :find_project_from_association before_filter :find_project_from_association
before_filter :authorize before_filter :authorize
def create def create
raise Unauthorized unless @news.commentable? raise Unauthorized unless @news.commentable?
if !@news.org_subfield_id.nil?
@org_subfield = OrgSubfield.find(@news.org_subfield_id)
end
@comment = Comment.new @comment = Comment.new
@project ? @comment.comments = params[:comment][:comments] : @comment.comments = params[:comment] #@project ? @comment.comments = params[:comment][:comments] : @comment.comments = params[:comment]
if params[:user_activity_id]
@comment.comments = params[:comment]
else
@comment.comments = params[:comment][:comments]
end
@comment.author = User.current @comment.author = User.current
if @news.comments << @comment if @news.comments << @comment
if params[:asset_id] if params[:asset_id]
ids = params[:asset_id].split(',') ids = params[:asset_id].split(',')
update_kindeditor_assets_owner ids,@comment.id,OwnerTypeHelper::COMMENT update_kindeditor_assets_owner ids,@comment.id,OwnerTypeHelper::COMMENT
end end
# 与我相关动态的记录add start # # <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ض<EFBFBD>̬<EFBFBD>ļ<EFBFBD>¼add start
if( @comment.id && @news.course ) # if( @comment.id && @news.course )
if(@news.author_id != User.current.id) # if(@news.author_id != User.current.id)
notify = ActivityNotify.new() # notify = ActivityNotify.new()
notify.activity_container_id = @news.course.id # notify.activity_container_id = @news.course.id
notify.activity_container_type = 'Course' # notify.activity_container_type = 'Course'
notify.activity_id = @comment.id # notify.activity_id = @comment.id
notify.activity_type = 'Comment' # notify.activity_type = 'Comment'
notify.notify_to = @news.author_id # notify.notify_to = @news.author_id
notify.is_read = 0 # notify.is_read = 0
notify.save() # notify.save()
end # end
end # end
# 与我相关动态的记录add end # # <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ض<EFBFBD>̬<EFBFBD>ļ<EFBFBD>¼add end
flash[:notice] = l(:label_comment_added) #flash[:notice] = l(:label_comment_added)
update_course_activity(@news.class,@news.id)
update_user_activity(@news.class,@news.id)
update_org_activity(@news.class,@news.id)
end end
redirect_to news_url(@news) if params[:user_activity_id]
@user_activity_id = params[:user_activity_id]
respond_to do |format|
format.js
end
else
redirect_to news_url(@news)
end
end end
def destroy def destroy
@ -69,6 +86,6 @@ class CommentsController < ApplicationController
@comment = nil @comment = nil
@news @news
end end
end end

@ -1,3 +1,4 @@
#encoding: utf-8
class CoursesController < ApplicationController class CoursesController < ApplicationController
# layout 'base_courses' # layout 'base_courses'
include CoursesHelper include CoursesHelper
@ -8,7 +9,7 @@ class CoursesController < ApplicationController
helper :attachments helper :attachments
helper :activity_notifys helper :activity_notifys
before_filter :auth_login1, :only => [:show, :feedback] before_filter :auth_login1, :only => [:show, :course_activity, :feedback]
menu_item :overview menu_item :overview
menu_item :feedback, :only => :feedback menu_item :feedback, :only => :feedback
menu_item :homework, :only => :homework menu_item :homework, :only => :homework
@ -25,33 +26,58 @@ class CoursesController < ApplicationController
before_filter :authorize_course, :only => [:show, :settings, :update, :course] before_filter :authorize_course, :only => [:show, :settings, :update, :course]
before_filter :authorize_course_global, :only => [:new,:create] before_filter :authorize_course_global, :only => [:new,:create]
before_filter :toggleCourse, :only => [:finishcourse, :restartcourse] before_filter :toggleCourse, :only => [:finishcourse, :restartcourse]
before_filter :is_deleted, :only => [:show, :settings]
before_filter :require_login, :only => [:join, :unjoin] before_filter :require_login, :only => [:join, :unjoin]
#before_filter :allow_join, :only => [:join] #before_filter :allow_join, :only => [:join]
#查找组织
def search_public_orgs_not_in_course
condition = '%%'
if !params[:name].nil?
condition = "%#{params[:name].strip}%".gsub(" ","")
end
limit = 15
course_org_ids = OrgCourse.find_by_sql("select distinct organization_id from org_courses where course_id = #{params[:id]}").map(&:organization_id)
#@orgs_not_in_course = User.current.organizations.where("organizations.id not in (#{course_org_ids.join(',')}) and organizations.name like ?", condition).page(params[:page].to_i || 1).per(limit)
#@org_count = User.current.organizations.where("organizations.id not in (#{course_org_ids.join(',')}) and organizations.name like ?", condition).count
if course_org_ids.empty?
@orgs_not_in_course = User.current.organizations.where("name like ?",condition).page((params[:page].to_i || 1)).per(limit)
@org_count = @orgs_not_in_course.count
else
course_org_ids = "(" + course_org_ids.join(',') + ")"
@orgs_not_in_course = User.current.organizations.where("organizations.id not in #{course_org_ids} and organizations.name like ?", condition).page((params[:page].to_i || 1)).per(limit)
@org_count = @orgs_not_in_course.empty? ? 0 : @orgs_not_in_course.count
end
@course_count = Project.course_entities.visible.like(params[:name]).page(params[:page]).count
@orgs_page = Paginator.new @org_count, limit,params[:page]
@hint_flag = params[:hint_flag]
#render :json => {:orgs => @orgs_not_in_course, :count => @org_count}.to_json
respond_to do |format|
format.js
end
end
def join def join
if User.current.logged? if User.current.logged?
cs = CoursesService.new cs = CoursesService.new
user = User.current @user = User.current
join = cs.join_course params,user join = cs.join_course params,@user
@state = join[:state] @state = join[:state]
course = join[:course] @course = join[:course]
# else
# @course = Course.find_by_id params[:object_id]
# CourseMessage.create(:user_id => @course.tea_id, :course_id => @course.id, :viewed => false,:content=> params[:role],:course_message_id=>User.current.id,:course_message_type=>'JoinCourseRequest')
# @state = 6
# end
else else
@state = 5 #未登录 @state = 5 #未登录
end end
# if @state == 1 || @state == 3 @object_id = params[:object_id]
# respond_to course_path(course.id)
# else
respond_to do |format|
format.js { render :partial => 'set_join', :locals => {:user => user, :course => course, :object_id => params[:object_id]} }
end
#end
rescue Exception => e
@state = 4 #已经加入了课程
respond_to do |format| respond_to do |format|
format.js { render :partial => 'set_join', :locals => {:user => User.current, :course => nil, :object_id => nil} } format.js #{ render :partial => 'set_join', :locals => {:user => @user, :course => @course, :object_id => params[:object_id]} }
end end
end end
def unjoin def unjoin
@ -64,7 +90,7 @@ class CoursesController < ApplicationController
end end
end end
def join_private_courses def join_private_courses
respond_to do |format| respond_to do |format|
format.js format.js
@ -77,14 +103,14 @@ class CoursesController < ApplicationController
c = cs.edit_course params,@course,User.current c = cs.edit_course params,@course,User.current
@course = c[:course] @course = c[:course]
if @course.errors.full_messages.count <= 0 if @course.errors.full_messages.count <= 0
respond_to do |format| respond_to do |format|
format.html { format.html {
# render :layout => 'base_courses' # render :layout => 'base_courses'
flash[:notice] = l(:notice_successful_update) flash[:notice] = l(:notice_successful_update)
redirect_to settings_course_url(@course) redirect_to settings_course_url(@course)
} }
format.api { render_api_ok } format.api { render_api_ok }
end end
else else
respond_to do |format| respond_to do |format|
format.html { format.html {
@ -106,74 +132,18 @@ class CoursesController < ApplicationController
# 课程搜索 # 课程搜索
# add by nwb # add by nwb
def search def search
courses_all = Course.all_course if params[:name].empty?
name = params[:name] courses = Course.visible
if name.blank? @courses = paginateHelper courses,10
@courses = []
@courses_all = []
@course_count = 0
@course_pages = Paginator.new @course_count, per_page_option, params['page']
else else
@courses = courses_all.visible courses = Course.visible.where("LOWER(name) like '%#{params[:name].to_s.downcase}%'").order("time desc, created_at desc")
if params[:name].present? @courses = paginateHelper courses,10
@courses_all = @courses.like(params[:name])
else
@courses_all = @courses;
end
@course_count = @courses_all.count
@course_pages = Paginator.new @course_count, per_page_option, params['page']
# 课程的动态数
@course_activity_count=Hash.new
@courses_all.each do |course|
@course_activity_count[course.id]=0
end
case params[:course_sort_type]
when '0'
@courses = @courses_all.order("created_at desc")
@s_type = 0
@courses = @courses.offset(@course_pages.offset).limit(@course_pages.per_page)
@course_activity_count=get_course_activity @courses,@course_activity_count
when '1'
@courses = @courses_all.order("course_ac_para desc")
@s_type = 1
@courses = @courses.offset(@course_pages.offset).limit(@course_pages.per_page)
@course_activity_count=get_course_activity @courses,@course_activity_count
when '2'
@courses = @courses_all.order("watchers_count desc")
@s_type = 2
@courses = @courses.offset(@course_pages.offset).limit(@course_pages.per_page)
@course_activity_count=get_course_activity @courses,@course_activity_count
when '3'
@course_activity_count=get_course_activity @courses_all,@course_activity_count_array
@courses=handle_course @courses_all,@course_activity_count
@s_type = 3
@courses = @courses[@course_pages.offset, @course_pages.per_page]
else
@s_type = 0
@courses = @courses_all.order("created_at desc")
@courses = @courses.offset(@course_pages.offset).limit(@course_pages.per_page)
@course_activity_count=get_course_activity @courses,@course_activity_count
end
end end
@name = params[:name]
@type = 'courses'
respond_to do |format| respond_to do |format|
format.html { format.html {
render :layout => 'course_base' render :layout => 'course_base'
scope = Course
unless params[:closed]
scope = scope.active
end
} }
format.atom { format.atom {
courses = Course.visible.order('created_on DESC').limit(Setting.feeds_limit.to_i).all courses = Course.visible.order('created_on DESC').limit(Setting.feeds_limit.to_i).all
@ -312,7 +282,7 @@ class CoursesController < ApplicationController
def member def member
## 有角色参数的才是课程,没有的就是项目 ## 有角色参数的才是课程,没有的就是项目
if (User.current.admin? || @course.is_public == 1 || (@course.is_public == 0 && User.current.member_of_course?(@course))) if (User.current.admin? || @course.is_public == 1 || (@course.is_public == 0 && User.current.member_of_course?(@course)))
@render_file = 'new_member_list' @render_file = 'new_member_list'
@score_sort_by = "desc" @score_sort_by = "desc"
@canShowCode = User.current.allowed_to?(:as_teacher,@course) && params[:role] != '1' @canShowCode = User.current.allowed_to?(:as_teacher,@course) && params[:role] != '1'
@ -326,10 +296,15 @@ class CoursesController < ApplicationController
@all_members = searchTeacherAndAssistant(@course) @all_members = searchTeacherAndAssistant(@course)
@members = @all_members @members = @all_members
when '2' when '2'
@subPage_title = l :label_student_list if @course.open_student == 1 || User.current.member_of_course?(@course)
page = params[:page].nil? ? 0 : (params['page'].to_i - 1) @subPage_title = l :label_student_list
@all_members = student_homework_score(0,page, 10,"desc") page = params[:page].nil? ? 0 : (params['page'].to_i - 1)
@members = @all_members @all_members = student_homework_score(0,page, 10,"desc")
@members = @all_members
else
render_403
return
end
end end
respond_to do |format| respond_to do |format|
if params[:page] if params[:page]
@ -346,15 +321,13 @@ class CoursesController < ApplicationController
def export_course_member_excel def export_course_member_excel
@all_members = student_homework_score(0,0,0,"desc") @all_members = student_homework_score(0,0,0,"desc")
@homeworks = @course.homework_commons.order("created_at desc")
filename="#{@course.teacher.lastname.to_s + @course.teacher.firstname.to_s }_#{@course.name}_#{@course.time.to_s + @course.term}#{l(:excel_member_list)}"; filename="#{@course.teacher.lastname.to_s + @course.teacher.firstname.to_s }_#{@course.name}_#{@course.time.to_s + @course.term}#{l(:excel_member_list)}";
# 如果是ie 需要转码
if(/trident/.match(request.env["HTTP_USER_AGENT"]) != nil)
filename= URI::encode(filename)
end
respond_to do |format| respond_to do |format|
format.xls { format.xls {
send_data(member_to_xls(@all_members,@course.course_groups), :type => "text/excel;charset=utf-8; header=present", send_data(member_to_xls(@homeworks,@course,@all_members,@course.course_groups), :type => "text/excel;charset=utf-8; header=present",
:filename => "#{filename}.xls") :filename => filename_for_content_disposition("#{filename}.xls"))
} }
end end
end end
@ -412,6 +385,7 @@ class CoursesController < ApplicationController
def settings def settings
if User.current.allowed_to?(:as_teacher,@course) if User.current.allowed_to?(:as_teacher,@course)
@select_tab = params[:tab]
@issue_custom_fields = IssueCustomField.sorted.all @issue_custom_fields = IssueCustomField.sorted.all
@issue_category ||= IssueCategory.new @issue_category ||= IssueCategory.new
@member ||= @course.members.new @member ||= @course.members.new
@ -429,6 +403,25 @@ class CoursesController < ApplicationController
end end
def private_or_public
if @course.is_public == 0
@course.update_attributes(:is_public => 1)
else
@course.update_attributes(:is_public => 0)
end
if @course.is_public == 0
course_status = CourseStatus.find_by_course_id(@course.id)
course_status.destroy if course_status
elsif @course.is_public == 1
course_status = CourseStatus.find_by_course_id(@course.id)
course_status.destroy if course_status
course_status = CourseStatus.create(:course_id => @course.id, :grade => 0)
end
respond_to do |format|
format.js
end
end
def search_member def search_member
if User.current.allowed_to?(:as_teacher,@course) || User.current.admin if User.current.allowed_to?(:as_teacher,@course) || User.current.admin
q = "#{params[:name].strip}" q = "#{params[:name].strip}"
@ -447,10 +440,84 @@ class CoursesController < ApplicationController
def create def create
cs = CoursesService.new cs = CoursesService.new
@course = cs.create_course(params,User.current)[:course] @course = cs.create_course(params,User.current)[:course]
if params[:copy_course]
copy_course = Course.find params[:copy_course].to_i
@course.is_copy = params[:copy_course].to_i
@course.open_student = copy_course.open_student
@course.publish_resource = copy_course.publish_resource
@course.save
#copy avatar
copy_avatar(@course, copy_course)
if params[:checkAll]
attachments = copy_course.attachments
attachments.each do |attachment|
attach_copied_obj = attachment.copy
attach_copied_obj.tag_list.add(attachment.tag_list) # tag关联
attach_copied_obj.container = @course
attach_copied_obj.created_on = Time.now
attach_copied_obj.author_id = User.current.id
attach_copied_obj.copy_from = attachment.copy_from.nil? ? attachment.id : attachment.copy_from
if attach_copied_obj.attachtype == nil
attach_copied_obj.attachtype = 4
end
attach_copied_obj.save
update_quotes attach_copied_obj
end
elsif params[:course_attachment_type]
copy_attachments = []
params[:course_attachment_type].each do |type|
case type
when "1"
tag_name = l(:label_courseware)
when "2"
tag_name = l(:label_software)
when "3"
tag_name = l(:label_media)
when "4"
tag_name = l(:label_code)
when "6"
tag_name = "论文"
else
tag_name = ""
end
if tag_name == ""
tag_attachments = copy_course.attachments.select{|attachment|
!attachment.tag_list.include?('课件') &&
!attachment.tag_list.include?('软件') &&
!attachment.tag_list.include?('媒体') &&
!attachment.tag_list.include?('代码') &&
!attachment.tag_list.include?('论文') }
else
tag_attachments = copy_course.attachments.select{|attachment| attachment.tag_list.include?(tag_name)}
end
tag_attachments.each do |attach|
next if copy_attachments.include?(attach)
copy_attachments << attach
end
end
unless copy_attachments.blank?
copy_attachments.each do |c_attach|
attach_copied_obj = c_attach.copy
attach_copied_obj.tag_list.add(c_attach.tag_list) # tag关联
attach_copied_obj.container = @course
attach_copied_obj.created_on = Time.now
attach_copied_obj.author_id = User.current.id
attach_copied_obj.copy_from = c_attach.copy_from.nil? ? c_attach.id : c_attach.copy_from
if attach_copied_obj.attachtype == nil
attach_copied_obj.attachtype = 4
end
attach_copied_obj.save
update_quotes attach_copied_obj
end
end
end
end
if @course if @course
respond_to do |format| respond_to do |format|
flash[:notice] = l(:notice_successful_create) flash[:notice] = l(:notice_successful_create)
format.html {redirect_to settings_course_url(@course, :course_type => 1)} format.html {redirect_to course_url(@course)}
format.api { render :action => 'show', :status => :created, :location => url_for(:controller => 'courses', :action => 'show', :id => @course.id) } format.api { render :action => 'show', :status => :created, :location => url_for(:controller => 'courses', :action => 'show', :id => @course.id) }
end end
else else
@ -464,7 +531,7 @@ class CoursesController < ApplicationController
end end
def course def course
@school_id = params[:school_id] @school_id = params[:school_id]
per_page_option = 10 per_page_option = 10
if @school_id == "0" or @school_id.nil? if @school_id == "0" or @school_id.nil?
@courses_all = Course.active.visible. @courses_all = Course.active.visible.
@ -524,13 +591,17 @@ class CoursesController < ApplicationController
end end
def new def new
@course_type = params[:course_type] ||= params[:course] if User.current.login?
@issue_custom_fields = IssueCustomField.sorted.all @course_type = params[:course_type] ||= params[:course]
@trackers = Tracker.sorted.all @issue_custom_fields = IssueCustomField.sorted.all
@course = Course.new @trackers = Tracker.sorted.all
@course.safe_attributes = params[:course] @course = Course.new
# month = Time.now.month @course.safe_attributes = params[:course]
render :layout => 'new_base' # month = Time.now.month
render :layout => 'new_base'
else
redirect_to signin_url
end
end end
def desc_sort_course_by_avtivity(activity_count, courses) def desc_sort_course_by_avtivity(activity_count, courses)
@ -548,8 +619,8 @@ class CoursesController < ApplicationController
def index def index
if !User.current.admin? if !User.current.admin?
render_404 render_404
return return
end end
@course_type = params[:course_type] @course_type = params[:course_type]
@school_id = params[:school_id] @school_id = params[:school_id]
@ -598,7 +669,7 @@ class CoursesController < ApplicationController
respond_to do |format| respond_to do |format|
format.html { format.html {
render :layout => 'base' render :layout => 'base'
} }
format.atom { format.atom {
courses = Course.visible.order('created_on DESC').limit(Setting.feeds_limit.to_i).all courses = Course.visible.order('created_on DESC').limit(Setting.feeds_limit.to_i).all
@ -614,6 +685,13 @@ class CoursesController < ApplicationController
end end
end end
def is_deleted
if @course.is_delete == 1 and !User.current.admin?
render_404
return
end
end
def get_courses def get_courses
@user = User.current @user = User.current
membership = @user.coursememberships.all membership = @user.coursememberships.all
@ -662,11 +740,50 @@ class CoursesController < ApplicationController
end end
end end
def course_activity
redirect_to course_url(@course, type: params[:type], page: params[:page])
end
def show def show
course_activities = @course.course_activities.order("created_at desc") # 被删除的课程只有超级管理员才能看到is_delete为1的时候标记课程被删除
# if @course.is_delete == 1 && !User.current.admin?
# render_403
# return
# end
#更新创建课程消息状态
create_course_messages = @course.course_messages.where("user_id =? and course_message_type =? and course_id =? and viewed =?", User.current.id, 'Course', @course.id, 0)
create_course_messages.update_all(:viewed => true)
#更新申请结果反馈消息的状态
course_request_messages = CourseMessage.where("user_id =? and course_id =? and course_message_type =? and viewed =?", User.current.id, @course.id, 'CourseRequestDealResult', false)
course_request_messages.update_all(:viewed => true)
course_activities = @course.course_activities
@canShowRealName = User.current.member_of_course? @course @canShowRealName = User.current.member_of_course? @course
@course_activities = paginateHelper course_activities,10 @page = params[:page] ? params[:page].to_i + 1 : 0
if params[:type].present?
case params[:type]
when "homework"
@course_activities = course_activities.where("course_act_type = 'HomeworkCommon'").order('updated_at desc').limit(10).offset(@page * 10)
when "news"
@course_activities = course_activities.where("course_act_type = 'News'").order('updated_at desc').limit(10).offset(@page * 10)
when "message"
@course_activities = course_activities.where("course_act_type = 'Message'").order('updated_at desc').limit(10).offset(@page * 10)
when "poll"
@course_activities = course_activities.where("course_act_type = 'Poll'").order('updated_at desc').limit(10).offset(@page * 10)
when "attachment"
@course_activities = course_activities.where("course_act_type = 'Attachment'").order('updated_at desc').limit(10).offset(@page * 10)
when "journalsForMessage"
@course_activities = course_activities.where("course_act_type = 'JournalsForMessage'").order('updated_at desc').limit(10).offset(@page * 10)
else
@course_activities = course_activities.order('updated_at desc').limit(10).offset(@page * 10)
end
else
@course_activities = course_activities.order('updated_at desc').limit(10).offset(@page * 10)
end
@type = params[:type]
respond_to do |format| respond_to do |format|
format.js
format.html{render :layout => 'base_courses'} format.html{render :layout => 'base_courses'}
format.api format.api
end end
@ -683,6 +800,11 @@ class CoursesController < ApplicationController
end end
def feedback def feedback
@course.journals_for_messages.each do |messages|
query = messages.course_messages.where("user_id = ?", User.current.id)
query.update_all(:viewed => true);
end
if (User.current.admin? || @course.is_public == 1 || (@course.is_public == 0 && User.current.member_of_course?(@course))) if (User.current.admin? || @course.is_public == 1 || (@course.is_public == 0 && User.current.member_of_course?(@course)))
page = params[:page] page = params[:page]
# Find the page of the requested reply # Find the page of the requested reply
@ -707,6 +829,11 @@ class CoursesController < ApplicationController
#param id:已有课程ID #param id:已有课程ID
def copy_course def copy_course
if @course if @course
@new_course = Course.new
respond_to do |format|
format.js
end
=begin
@new_course = Course.new @course.attributes @new_course = Course.new @course.attributes
@new_course.tea_id = User.current.id @new_course.tea_id = User.current.id
@new_course.created_at = DateTime.now @new_course.created_at = DateTime.now
@ -725,18 +852,105 @@ class CoursesController < ApplicationController
@new_course.course_infos << course @new_course.course_infos << course
redirect_to settings_course_url @new_course redirect_to settings_course_url @new_course
end end
=end
else else
render_404 render_404
end end
end end
#从课程创建的老师那里选择课程大纲
def course_outline
@teacher = User.find(@course.tea_id)
@blog_articles = @teacher.blog.articles
@is_in_show_outline_page = params[:is_in_show_outline_page]
respond_to do |format|
format.js
end
end
#根据关键字搜索,查找方法一样的,但返回内容不一样
def search_course_outline
@article_title = params[:title]
@teacher = User.find(@course.tea_id)
@blog_articles = @teacher.blog.articles.like(@article_title)
render :json=>@blog_articles.to_json
end
#设置或者更改课程的大纲
def set_course_outline
@course.outline = params[:outline_id]
@course.save
@is_in_show_outline_page = params[:is_in_show_outline_page]
respond_to do |format|
format.js
end
end
#显示课程大纲
def syllabus
@article = BlogComment.find(@course.outline)
respond_to do |format|
format.html {render :layout => 'base_courses'}
end
end
#删除课程 #删除课程
#删除课程只是将课程的is_delete状态改为falseis_delete为false状态的课程只有管理员可以看到 #删除课程只是将课程的is_deleted状态改为falseis_deleted为false状态的课程只有管理员可以看到
def destroy def destroy
@course.update_attributes(:is_delete => true)
@course = nil
redirect_to user_url(User.current)
end
# 恢复已删除的课程
def renew
if User.current.admin?
@course.update_attributes(:is_delete => false)
redirect_to course_path(@course)
else
return 404
end
end
#搜索作业
def homework_search
@search = "%#{params[:search].strip.downcase}%"
@is_teacher = User.current.logged? && (User.current.admin? || User.current.allowed_to?(:as_teacher,@course))
@page = params[:page] ? params[:page].to_i + 1 : 0
if @is_teacher
@homeworks = @course.homework_commons.where("name like '%#{@search}%'").order("created_at desc").limit(10).offset(@page * 10)
else
@homeworks = @course.homework_commons.where("name like '%#{@search}%' and publish_time <= '#{Date.today}'").order("created_at desc").limit(10).offset(@page * 10)
end
end end
private private
def update_quotes attachment
if attachment.copy_from
attachments = Attachment.find_by_sql("select * from attachments where copy_from = #{attachment.copy_from} or id = #{attachment.copy_from}")
else
attachments = Attachment.find_by_sql("select * from attachments where copy_from = #{attachment.id} or id = #{attachment.copy_from}")
end
attachment.quotes = get_qute_number attachment
attachment.save
attachments.each do |att|
att.quotes = attachment.quotes
att.save
end
end
def get_qute_number attachment
if attachment.copy_from
result = Attachment.find_by_sql("select count(*) as number from attachments where copy_from = #{attachment.copy_from}")
else
result = Attachment.find_by_sql("select count(*) as number from attachments where copy_from = #{attachment.id}")
end
if result.nil? || result.count <= 0
return 0
else
return result[0].number
end
end
def allow_join course def allow_join course
if course_endTime_timeout? course if course_endTime_timeout? course
respond_to do |format| respond_to do |format|
@ -756,7 +970,7 @@ class CoursesController < ApplicationController
def can_show_course def can_show_course
@first_page = FirstPage.find_by_page_type('project') @first_page = FirstPage.find_by_page_type('project')
if @first_page.try(:show_course) == 2 if @first_page.try(:show_course) == 2
render_404 render_404
end end
end end
@ -765,7 +979,7 @@ class CoursesController < ApplicationController
sql_select = "" sql_select = ""
if groupid == 0 if groupid == 0
sql_select = "SELECT members.*,( sql_select = "SELECT members.*,(
SELECT SUM(student_works.final_score) SELECT SUM(IF(student_works.final_score is null,null,student_works.final_score - student_works.absence_penalty - student_works.late_penalty))
FROM student_works,homework_commons FROM student_works,homework_commons
WHERE student_works.homework_common_id = homework_commons.id WHERE student_works.homework_common_id = homework_commons.id
AND homework_commons.course_id = #{@course.id} AND homework_commons.course_id = #{@course.id}
@ -777,7 +991,7 @@ class CoursesController < ApplicationController
WHERE members.course_id = #{@course.id} ORDER BY score #{score_sort_by}" WHERE members.course_id = #{@course.id} ORDER BY score #{score_sort_by}"
else else
sql_select = "SELECT members.*,( sql_select = "SELECT members.*,(
SELECT SUM(student_works.final_score) SELECT SUM(IF(student_works.final_score is null,null,student_works.final_score - student_works.absence_penalty - student_works.late_penalty))
FROM student_works,homework_commons FROM student_works,homework_commons
WHERE student_works.homework_common_id = homework_commons.id WHERE student_works.homework_common_id = homework_commons.id
AND homework_commons.course_id = #{@course.id} AND homework_commons.course_id = #{@course.id}
@ -811,16 +1025,54 @@ class CoursesController < ApplicationController
end end
def member_to_xls members,groups def member_to_xls homeworks, course, members,groups
xls_report = StringIO.new xls_report = StringIO.new
book = Spreadsheet::Workbook.new book = Spreadsheet::Workbook.new
sheet1 = book.create_worksheet :name => "student" sheet1 = book.create_worksheet :name => "student"
blue = Spreadsheet::Format.new :color => :blue, :weight => :bold, :size => 10 blue = Spreadsheet::Format.new :color => :blue, :weight => :bold, :size => 10
sheet1.row(0).default_format = blue #sheet1.row(0).default_format = blue
#sheet1.row(0).concat([l(:excel_user_id),l(:excel_user_name),l(:excel_nickname),l(:excel_student_id),l(:excel_mail),l(:excel_class),l(:excel_f_score),l(:excel_commit_time)])
sheet1[0,0] = "课程编号"
sheet1[0,1] = course.id
sheet1[1,0] = "课程学期"
sheet1[1,1] = course.time.to_s+""+course.term
sheet1[2,0] = "课程名称"
sheet1[2,1] = course.name
sheet1[3,0] = "教师团队"
sheet1[3,1] = (searchTeacherAndAssistant course).map{|member| member.user.show_name}.join('、')
sheet1[4,0] = "主讲教师"
sheet1[4,1] = course.teacher.show_name
sheet1[5,0] = "排名"
sheet1[5,1] = "学生姓名"
sheet1[5,2] = "昵称"
sheet1[5,3] = "学号"
for i in 0 ... homeworks.count
sheet1[5,i+4] = ""+(i+1).to_s+""
end
sheet1[5,homeworks.count+4] = "总成绩"
sheet1[5,0] = "排名"
sheet1[5,0] = "排名"
count_row = 6
members.each_with_index do |member, i|
sheet1[count_row,0]= i+1
sheet1[count_row,1] = member.user.lastname.to_s + member.user.firstname.to_s
sheet1[count_row,2] = member.user.login
sheet1[count_row,3] = member.user.user_extensions.student_id
homeworks.each_with_index do |homework, j|
student_works = homework.student_works.where("user_id = #{member.user.id}")
if student_works.empty?
sheet1[count_row,j+4] = format("%0.2f",0)
else
final_score = student_works.first.final_score.nil? ? 0 : student_works.first.final_score
score = final_score - student_works.first.absence_penalty - student_works.first.late_penalty
sheet1[count_row,j+4] = format("%0.2f",score <0 ? 0:score)
end
end
sheet1[count_row,homeworks.count+4] = format("%0.2f",member.score.nil? ? 0:member.score.to_s)
count_row += 1
end
sheet1.row(0).concat([l(:excel_user_id),l(:excel_user_name),l(:excel_nickname),l(:excel_student_id),l(:excel_mail),l(:excel_homework_score)]) =begin
count_row = 1
group0 = CourseGroup.new(); group0 = CourseGroup.new();
group0.id = 0; group0.id = 0;
group0.name = l(:excel_member_with_out_class) group0.name = l(:excel_member_with_out_class)
@ -842,6 +1094,7 @@ class CoursesController < ApplicationController
end end
end end
end end
=end
book.write xls_report book.write xls_report
xls_report.string xls_report.string
end end

@ -0,0 +1,709 @@
class ExerciseController < ApplicationController
layout "base_courses"
before_filter :find_exercise_and_course, :only => [:create_exercise_question, :edit, :update, :show, :destroy,
:commit_exercise, :commit_answer,:publish_exercise,:republish_exercise,
:show_student_result,:student_exercise_list]
before_filter :find_course, :only => [:index,:new,:create]
include ExerciseHelper
def index
publish_exercises = Exercise.where("publish_time is not null and exercise_status = 1 and publish_time <=?",Time.now)
publish_exercises.each do |exercise|
exercise.update_column('exercise_status', 2)
course = exercise.course
course.members.each do |m|
exercise.course_messages << CourseMessage.new(:user_id => m.user_id, :course_id => course.id, :viewed => false, :status => 2)
end
end
if @course.is_public == 0 && !(User.current.member_of_course?(@course)||User.current.admin?)
render_403
return
end
remove_invalid_exercise(@course)
@is_teacher = User.current.allowed_to?(:as_teacher,@course)
if @is_teacher || User.current.admin?
exercises = @course.exercises.order("created_at asc")
else
exercises = @course.exercises.where("exercise_status <> 1").order("created_at asc")
end
@exercises = paginateHelper exercises,20 #分页
respond_to do |format|
format.html
end
end
def show
publish_exercises = Exercise.where("publish_time is not null and exercise_status = 1 and publish_time <=?",Time.now)
publish_exercises.each do |exercise|
exercise.update_column('exercise_status', 2)
course = exercise.course
course.members.each do |m|
exercise.course_messages << CourseMessage.new(:user_id => m.user_id, :course_id => course.id, :viewed => false, :status => 2)
end
end
unless User.current.member_of_course?(@course) || User.current.admin?
render_403
return
end
@exercise = Exercise.find params[:id]
@is_teacher = User.current.allowed_to?(:as_teacher,@course) || User.current.admin?
exercise_end = @exercise.end_time > Time.now
if @exercise.time == -1
@can_edit_excercise = exercise_end
else
@can_edit_excercise = !has_commit_exercise?(@exercise.id,User.current.id)&& exercise_end
end
unless @is_teacher
@exercise_user = ExerciseUser.where("user_id=? and exercise_id=?", User.current.id, @exercise.id).first
if @exercise_user.nil?
eu = ExerciseUser.create(:user_id => User.current.id, :exercise_id => @exercise.id, :start_at => Time.now, :status => false)
@exercise_user = ExerciseUser.where("user_id=? and exercise_id=?", User.current.id, @exercise.id).first
end
score = calculate_student_score(@exercise, User.current)
@exercise_user.update_attributes(:score => score)
end
# @percent = get_percent(@exercise,User.current)
@exercise_questions = @exercise.exercise_questions
respond_to do |format|
format.html {render :layout => 'base_courses'}
end
#end
end
def new
option = {
:exercise_name => "",
:course_id => @course.id,
:exercise_status => 1,
:user_id => User.current.id,
:time => "",
:end_time => "",
:publish_time => "",
:exercise_description => "",
:show_result => 1
}
@exercise = Exercise.create option
if @exercise
redirect_to edit_exercise_url @exercise.id
end
end
def create
if params[:exercise]
exercise = Exercise.find(params[:exercise_id]) if params[:exercise_id]
exercise ||= Exercise.new
exercise.exercise_name = params[:exercise][:exercise_name]
exercise.exercise_description = params[:exercise][:exercise_description]
exercise.end_time = Time.at(params[:exercise][:end_time].to_time.to_i + 16*60*60 -1)
exercise.publish_time = params[:exercise][:publish_time]
exercise.user_id = User.current.id
exercise.time = params[:exercise][:time]
exercise.course_id = params[:course_id]
exercise.exercise_status = 1
if exercise.save
@exercise = exercise
respond_to do |format|
format.js
end
end
end
end
def edit
respond_to do |format|
format.html{render :layout => 'base_courses'}
end
end
def update
@exercise.exercise_name = params[:exercise][:exercise_name]
@exercise.exercise_description = params[:exercise][:exercise_description]
@exercise.time = params[:exercise][:time].blank? ? -1 : params[:exercise][:time]
@exercise.end_time = Time.at(params[:exercise][:end_time].to_time.to_i + 16*60*60 -1)
@exercise.publish_time = params[:exercise][:publish_time]
@exercise.show_result = params[:exercise][:show_result].blank? ? 1 : params[:exercise][:show_result]
if @exercise.save
respond_to do |format|
format.js
end
else
render_404
end
end
def destroy
@is_teacher = User.current.allowed_to?(:as_teacher,@course) || User.current.admin?
if @exercise && @exercise.destroy
if @is_teacher
exercises = Exercise.where("course_id =?", @course.id)
else
exercises = Exercise.where("course_id =? and exercise_status =?", @course.id, 2)
end
@exercises = paginateHelper exercises,20 #分页
respond_to do |format|
format.js
end
end
end
# 统计结果
def statistics_result
@exercise = Exercise.find(params[:id])
exercise_questions = @exercise.exercise_questions
@exercise_questions = paginateHelper exercise_questions, 5
respond_to do |format|
format.html{render :layout => 'base_courses'}
end
end
# 添加题目
# question_type 1单选 2多选 3填空题
def create_exercise_question
question_title = params[:question_title].nil? || params[:question_title].empty? ? l(:label_enter_single_title) : params[:question_title]
option = {
:question_title => question_title,
:question_type => params[:question_type] || 1,
:question_number => params[:question_type] == "1"? @exercise.exercise_questions.where("question_type = 1").count + 1 :
(params[:question_type] == "2" ? (@exercise.exercise_questions.where("question_type = 2").count + 1) :
@exercise.exercise_questions.where("question_type = 3").count + 1),
:question_score => params[:question_score]
}
@exercise_questions = @exercise.exercise_questions.new option
# params[:question_answer] 题目选项
if params[:question_answer]
for i in 1..params[:question_answer].count
answer = (params[:question_answer].values[i-1].nil? || params[:question_answer].values[i-1].empty?) ? l(:label_new_answer) : params[:question_answer].values[i-1]
question_option = {
:choice_position => i,
:choice_text => answer
}
@exercise_questions.exercise_choices.new question_option
end
end
# 如果是插入的话那么从插入的这个id以后的question_num都将要+1
if params[:quest_id]
@is_insert = true
if @exercise_questions.question_type == 1
ExerciseQuestion.where("question_number>? and question_type=?",params[:quest_num].to_i, 1).update_all(" question_number = question_number + 1")
#@exercise.exercise_questions.where("question_number > #{params[:quest_num].to_i} and question_type == 1").update_all(" question_number = question_number + 1")
elsif @exercise_questions.question_type == 2
ExerciseQuestion.where("question_number>? and question_type=?",params[:quest_num].to_i, 2).update_all(" question_number = question_number + 1")
else
ExerciseQuestion.where("question_number>? and question_type=?",params[:quest_num].to_i, 3).update_all(" question_number = question_number + 1")
end
# @exercise_question_num = params[:quest_num].to_i
@exercise_questions.question_number = params[:quest_num].to_i + 1
end
if @exercise_questions.save
# params[:exercise_choice] 标准答案参数
# 问答题标准答案有三个,单独处理
if @exercise_questions.question_type == 3
for i in 1..params[:exercise_choice].count
standart_answer = ExerciseStandardAnswer.new
standart_answer.exercise_question_id = @exercise_questions.id
standart_answer.answer_text = params[:exercise_choice].values[i-1]
standart_answer.save
end
else
standart_answer = ExerciseStandardAnswer.new
standart_answer.exercise_question_id = @exercise_questions.id
if @exercise_questions.question_type == 1
standart_answer.exercise_choice_id = sigle_selection_standard_answer(params[:exercise_choice])
else
standart_answer.exercise_choice_id = multiselect_standard_answer(params[:exercise_choice])
end
standart_answer.save
end
respond_to do |format|
format.js
end
end
end
# 修改题目
# params[:exercise_question] The id of exercise_question
# params[:question_answer] eg:A、B、C选项
def update_exercise_question
@exercise_question = ExerciseQuestion.find params[:exercise_question]
@exercise_question.question_title = params[:question_title].nil? || params[:question_title].empty? ? l(:label_enter_single_title) : params[:question_title]
@exercise_question.question_score = params[:question_score]
# 处理选项:如果选了某个选项,那么则要删除之前的选项
if params[:question_answer]
@exercise_question.exercise_choices.each do |answer|
answer.destroy unless params[:question_answer].keys.include? answer.id.to_s
end
for i in 1..params[:question_answer].count
question = @exercise_question.exercise_choices.find_by_id params[:question_answer].keys[i-1]
answer = (params[:question_answer].values[i-1].nil? || params[:question_answer].values[i-1].empty?) ? l(:label_new_answer) : params[:question_answer].values[i-1]
if question
question.choice_position = i
question.choice_text = answer
question.save
else
question_option = {
:choice_position => i,
:choice_text => answer
}
@exercise_question.exercise_choices.new question_option
end
end
end
# 更新标准答案
if params[:exercise_choice]
if @exercise_question.question_type == 3
# 删除不合理的选项
@exercise_question.exercise_standard_answers.each do |answer|
answer.destroy unless params[:exercise_choice].keys.include? answer.id.to_s
end
for i in 1..params[:exercise_choice].count
# 找到对应的标准答案
question_standart = @exercise_question.exercise_standard_answers.find_by_id params[:exercise_choice].keys[i-1]
# 标准答案值
answer_standart = (params[:exercise_choice].values[i-1].nil? || params[:exercise_choice].values[i-1].empty?) ? l(:label_new_answer) : params[:exercise_choice].values[i-1]
if question_standart
question_standart.answer_text = answer_standart
question_standart.save
else
standart_answer_option = {
:answer_text => answer_standart
}
@exercise_question.exercise_standard_answers.new standart_answer_option
end
end
else
answer_standart = @exercise_question.exercise_standard_answers.first
answer_standart.exercise_choice_id = @exercise_question.question_type == 1 ? sigle_selection_standard_answer(params[:exercise_choice]) : multiselect_standard_answer(params[:exercise_choice])
answer_standart.save
end
@exercise_question.save
respond_to do |format|
format.js
end
end
end
# 删除题目
def delete_exercise_question
@exercise_question = ExerciseQuestion.find params[:exercise_question]
@exercise = @exercise_question.exercise
if @exercise_question.question_type == 1
ExerciseQuestion.where("question_number>? and question_type=?",params[:quest_num].to_i, 1).update_all(" question_number = question_number - 1")
#@exercise.exercise_questions.where("question_number > #{params[:quest_num].to_i} and question_type == 1").update_all(" question_number = question_number + 1")
elsif @exercise_question.question_type == 2
ExerciseQuestion.where("question_number>? and question_type=?",params[:quest_num].to_i, 2).update_all(" question_number = question_number - 1")
else
ExerciseQuestion.where("question_number>? and question_type=?",params[:quest_num].to_i, 3).update_all(" question_number = question_number - 1")
end
# @exercise_question_num = params[:quest_num].to_i
# @exercise_questions.question_number = params[:quest_num].to_i - 1
#
# exercise_questions = @exercise.exercise_questions.where("question_number > #{@exercise_question.question_number}")
# exercise_questions.each do |question|
# question.question_number -= 1
# question.save
# end
if @exercise_question && @exercise_question.destroy
respond_to do |format|
format.js
end
end
end
# 发布试卷
def publish_exercise
@is_teacher = User.current.allowed_to?(:as_teacher,@course)
@index = params[:index]
@exercise.exercise_status = 2
@exercise.publish_time = Time.now
if @exercise.save
@exercise.course.members.each do |m|
@exercise.course_messages << CourseMessage.create(:user_id =>m.user_id, :course_id => @exercise.course.id, :viewed => false,:status=>2)
end
#redirect_to exercise_index_url(:course_id=> @course.id)
respond_to do |format|
format.js
end
end
end
# 重新发布试卷
# 重新发布的时候会删除所有的答题
def republish_exercise
@is_teacher = User.current.allowed_to?(:as_teacher,@course)
@index = params[:index]
@exercise.exercise_questions.each do |exercise_question|
exercise_question.exercise_answers.destroy_all
end
@exercise.course_messages.destroy_all
@exercise.exercise_users.destroy_all
@exercise.exercise_status = 1
@exercise.publish_time = nil
@exercise.save
respond_to do |format|
format.js
end
end
def student_exercise_list
=begin
if @exercise.end_time <= Time.now
@course.student.each do |student|
if ExerciseUser.where("user_id = ? && exercise_id = ?",student.student_id,@exercise.id).empty?
ExerciseUser.create(:user_id => student.student_id, :exercise_id => @exercise.id, :start_at => @exercise.end_time, :status => true,:score=>0)
end
s_score = calculate_student_score(@exercise, student.student)
exercise_user = ExerciseUser.where("user_id =? and exercise_id=?", student.student_id, @exercise.id).first
exercise_user.update_attributes(:score => s_score)
end
end
=end
@is_teacher = User.current.allowed_to?(:as_teacher,@course) || User.current.admin?
@all_exercises = @course.exercises.where("exercise_status > 1").order("created_at desc")
@exercise_count = @exercise.exercise_users.where('score is not NULL').count
if @is_teacher || (!@exercise.exercise_users.where(:user_id => User.current.id).empty? && @exercise.end_time <= Time.now)
@exercise_users_list = @exercise.exercise_users.where('score is not NULL')
@show_all = true;
elsif !@exercise.exercise_users.where(:user_id => User.current.id).empty? && @exercise.end_time > Time.now
@exercise_users_list = @exercise.exercise_users.where("user_id = ? and score is not NULL",User.current.id)
else
@exercise_users_list = []
end
respond_to do |format|
format.html
format.xls {
filename = "#{@course.teacher.lastname.to_s + @course.teacher.firstname}_#{@course.name}_#{@course.time.to_s + @course.term}_#{@exercise.exercise_name}#{l(:excel_exercise_list)}.xls"
send_data(exercise_to_xls(@exercise_users_list), :type => "text/excel;charset=utf-8; header=present",
:filename => filename_for_content_disposition(filename))
}
end
end
# 学生提交答卷,选中答案的过程中提交
def commit_answer
eq = ExerciseQuestion.find(params[:exercise_question_id])
# 已提交过的且是限时的则不允许答题
if (has_commit_exercise?(@exercise.id,User.current.id) && (!User.current.admin?) && @exercise.time != -1) || @exercise.end_time < Time.now
render :json => {:text => "failure"}
return
end
if eq.question_type == 1
# 单选题
ea = ExerciseAnswer.find_by_exercise_question_id_and_user_id(params[:exercise_question_id],User.current.id)
if ea.nil?
# 尚未答该题,添加答案
ea = ExerciseAnswer.new
ea.user_id = User.current.id
ea.exercise_question_id = params[:exercise_question_id]
end
#修改该题对应答案
ea.exercise_choice_id = params[:exercise_choice_id]
if ea.save
# 保存成功返回成功信息及当前以答题百分比
uncomplete_question = get_uncomplete_question(@exercise, User.current)
if uncomplete_question.count < 1
complete = 1;
else
complete = 0;
end
@percent = get_percent(@exercise,User.current)
render :json => {:text => "ok" ,:complete => complete,:percent => format("%.2f" ,@percent)}
else
#返回失败信息
render :json => {:text => "failure"}
end
elsif eq.question_type == 2
#多选题
ea = ExerciseAnswer.find_by_exercise_choice_id_and_user_id(params[:exercise_choice_id],User.current.id)
if ea.nil?
#尚未答该题,添加答案
ea = ExerciseAnswer.new
ea.user_id = User.current.id
ea.exercise_question_id = params[:exercise_question_id]
ea.exercise_choice_id = params[:exercise_choice_id]
if ea.save
uncomplete_question = get_uncomplete_question(@exercise, User.current)
if uncomplete_question.count < 1
complete = 1;
else
complete = 0;
end
@percent = get_percent(@exercise,User.current)
render :json => {:text => "ok",:complete => complete,:percent => format("%.2f" ,@percent)}
else
render :json => {:text => "failure"}
end
else
#pv不为空则当前选项之前已被选择再次点击则是不再选择该项故删除该答案
if ea.delete
@percent = get_percent(@exercise, User.current)
render :json => {:text => "false" ,:percent => format("%.2f" , @percent)}
else
render :json => {:text => "failure"}
end
end
elsif eq.question_type == 3
#单行文本,多行文本题
ea = ExerciseAnswer.find_by_exercise_question_id_and_user_id(params[:exercise_question_id], User.current.id)
if ea.nil?
# ea为空之前尚未答题添加答案
if params[:answer_text].nil? || params[:answer_text].blank?
#用户提交空答案,视作不作答
@percent = get_percent(@exercise,User.current)
render :json => {:text => "",:percent => format("%.2f", @percent)}
else
#添加答案
ea = ExerciseAnswer.new
ea.user_id = User.current.id
ea.exercise_question_id = params[:exercise_question_id]
ea.answer_text = params[:answer_text]
if ea.save
uncomplete_question = get_uncomplete_question(@exercise, User.current)
if uncomplete_question.count < 1
complete = 1;
else
complete = 0;
end
@percent = get_percent(@exercise,User.current)
render :json => {:text => ea.answer_text,:complete => complete,:percent => format("%.2f",@percent)}
else
render :json => {:text => "failure"}
end
end
else
# ea不为空说明用户之前已作答
if params[:answer_text].nil? || params[:answer_text].blank?
# 用户提交空答案,视为删除答案
if ea.delete
@percent = get_percent(@exercise,User.current)
render :json => {:text => "",:percent => format("%.2f", @percent)}
else
render :json => {:text => "failure"}
end
else
#用户修改答案
ea.answer_text = params[:answer_text]
if ea.save
@percent = get_percent(@exercise,User.current)
render :json => {:text => ea.answer_text,:percent => format("%.2f", @percent)}
else
render :json => {:text => "failure"}
end
end
end
else
render :json => {:text => "failure"}
end
end
# 提交问卷
def commit_exercise
# 老师不需要提交
if User.current.allowed_to?(:as_teacher,@course)
if @exercise.publish_time.nil?
@exercise.update_attributes(:show_result => params[:show_result])
@exercise.update_attributes(:exercise_status => 2)
@exercise.update_attributes(:publish_time => Time.now)
course = @exercise.course
course.members.each do |m|
@exercise.course_messages << CourseMessage.new(:user_id => m.user_id, :course_id => course.id, :viewed => false, :status => 2)
end
redirect_to exercise_url(@exercise)
return
elsif @exercise.publish_time > Time.now
@exercise.update_attributes(:show_result => params[:show_result])
redirect_to exercise_url(@exercise)
return
end
@exercise.update_attributes(:show_result => params[:show_result])
redirect_to exercise_url(@exercise)
# REDO: 提示提交成功
else
# 更新提交状态
cur_exercise_user = ExerciseUser.where("user_id =? and exercise_id=?", User.current, @exercise.id).first
cur_exercise_user.update_attributes(:status => 1)
# 答题过程中需要统计完成量
@uncomplete_question = get_uncomplete_question(@exercise, User.current)
# 获取改学生的考试得分
@score = calculate_student_score(@exercise, User.current)
# @score = 100
if @uncomplete_question.count < 1
# 查看是否有已提交记录
cur_exercise_user.score = @score
if cur_exercise_user.save
#redirect_to poll_index_path(:polls_group_id => @course.id,:polls_type => 'Course')
@status = 0 #提交成功
else
@status = 2 #未知错误
end
else
@status = 1 #有未做得必答题
end
@save = params[:save].to_i if params[:save]
respond_to do |format|
format.js
end
end
end
#查看学生的答卷情况
def show_student_result
@user = User.find params[:user_id]
@can_edit_excercise = false
@exercise_questions = @exercise.exercise_questions
score = calculate_student_score(@exercise, @user)
eu = get_exercise_user(@exercise.id, @user.id)
eu.update_attributes(:score => score)
@exercise_user = ExerciseUser.where("user_id =? and exercise_id=?", @user.id, @exercise.id).first
respond_to do |format|
format.html {render :layout => 'base_courses'}
end
end
# 计算学生得分
def calculate_student_score(exercise, user)
score = 0
score1 = 0
score2 = 0
score3 = 0
exercise_qustions = exercise.exercise_questions
exercise_qustions.each do |question|
answer = get_user_answer(question, user)
standard_answer = get_user_standard_answer(question, user)
unless answer.empty?
# 问答题有多个答案
if question.question_type == 3 && !standard_answer.empty?
if standard_answer.include?(answer.first.answer_text)
score1 = score1+ question.question_score unless question.question_score.nil?
end
elsif question.question_type == 1 && !standard_answer.nil?
if answer.first.exercise_choice.choice_position == standard_answer.exercise_choice_id
score2 = score2 + question.question_score unless question.question_score.nil?
end
elsif question.question_type == 2 && !standard_answer.nil?
arr = get_mulscore(question, user)
if arr.to_i == standard_answer.exercise_choice_id
score3 = score3 + question.question_score unless question.question_score.nil?
end
# ecs = ExerciseAnswer.where("user_id =? and exercise_question_id =?", user.id, question.id)
# arr = []
# ecs.each do |ec|
# arr << ec.exercise_choice.choice_position
# end
# arr.sort
# arr = arr.join("")
# if arr.to_i == standard_answer.exercise_choice_id
# score3 = score + question.question_score unless question.question_score.nil?
# end
end
end
end
score = score1 + score2 + score3
end
private
#测验列表转换为excel
def exercise_to_xls items
xls_report = StringIO.new
book = Spreadsheet::Workbook.new
sheet1 = book.create_worksheet :name => "exercise"
blue = Spreadsheet::Format.new :color => :blue, :weight => :bold, :size => 10
sheet1.row(0).default_format = blue
sheet1.row(0).concat([l(:excel_user_id),l(:excel_user_name),l(:excel_nickname),l(:excel_student_id),l(:excel_mail),l(:excel_class),l(:excel_f_score),l(:excel_commit_time)])
count_row = 1
items.each do |exercise|
sheet1[count_row,0]=exercise.user.id
sheet1[count_row,1] = exercise.user.lastname.to_s + exercise.user.firstname.to_s
sheet1[count_row,2] = exercise.user.login
sheet1[count_row,3] = exercise.user.user_extensions.student_id
sheet1[count_row,4] = exercise.user.mail
sheet1[count_row,5] = ""
sheet1[count_row,6] = exercise.score
sheet1[count_row,7] = format_time(exercise.created_at)
count_row += 1
end
book.write xls_report
xls_report.string
end
# ExerciseUser记录用户是否已提交问卷有对应的记录则已提交没有则新建一个
def get_exercise_user exercise_id,user_id
eu = ExerciseUser.find_by_exercise_id_and_user_id(exercise_id,user_id)
if eu.nil?
eu = ExerciseUser.new
end
eu
end
# 获取当前学生回答问题的答案
def get_user_answer(question,user)
# user_answer = ExerciseAnswer.where("user_id=? and exercise_question_id=?", user.id, question.id).first
user_answer = question.exercise_answers.where("#{ExerciseAnswer.table_name}.user_id = #{user.id}")
user_answer
end
# 获取问题的标准答案
def get_user_standard_answer(question,user)
if question.question_type == 3
standard_answer =[]
question.exercise_standard_answers.each do |answer|
standard_answer << answer.answer_text
end
else
standard_answer = question.exercise_standard_answers.first
end
standard_answer
end
# 是否完成了答题
def get_complete_question(exercise,user)
questions = exercise.exercise_questions
complete_question = []
questions.each do |question|
answers = get_user_answer(question,user)
if !(answers.nil? || answers.count < 1)
complete_question << question
end
end
complete_question
end
# 获取答题百分比
def get_percent exercise,user
complete_count = get_complete_question(exercise,user).count
if exercise.exercise_questions.count == 0
return 0
else
return (complete_count.to_f / exercise.exercise_questions.count.to_f)*100
end
end
def remove_invalid_exercise(course)
exercises = course.exercises.where("exercise_name=?","")
unless exercises.empty?
exercises.each do |exercise|
if exercise.exercise_questions.empty?
exercise.destroy
end
end
end
end
def find_exercise_and_course
@exercise = Exercise.find params[:id]
@course = Course.find @exercise.course_id
rescue Exception => e
render_404
end
def find_course
@course = Course.find params[:course_id]
rescue Exception => e
render_404
end
end

@ -1,3 +1,4 @@
#encoding: utf-8
# Redmine - project management software # Redmine - project management software
# Copyright (C) 2006-2013 Jean-Philippe Lang # Copyright (C) 2006-2013 Jean-Philippe Lang
# #
@ -16,14 +17,16 @@
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
class FilesController < ApplicationController class FilesController < ApplicationController
layout 'base_projects' #by young
layout 'base_projects' #by young
menu_item :files menu_item :files
before_filter :auth_login1, :only => [:index] before_filter :auth_login1, :only => [:index]
before_filter :logged_user_by_apptoken,:only => [:index] before_filter :logged_user_by_apptoken,:only => [:index]
before_filter :find_project_by_project_id#, :except => [:getattachtype] before_filter :find_project_by_project_id#, :except => [:getattachtype]
before_filter :authorize, :except => [:getattachtype,:quote_resource_show,:search,:searchone4reload,:search_project,:quote_resource_show_project,:search_tag_attachment] before_filter :authorize, :except => [:create,:getattachtype,:quote_resource_show,:search,:searchone4reload,:search_project,:quote_resource_show_project,
:search_tag_attachment,:subfield_upload_file,:search_org_subfield_tag_attachment,
:search_tag_attachment,:quote_resource_show_org_subfield,:find_org_subfield_attache,
:search_files_in_subfield,:upload_files_menu]
helper :sort helper :sort
include SortHelper include SortHelper
@ -98,6 +101,7 @@ class FilesController < ApplicationController
@sort = "" @sort = ""
@order = "" @order = ""
@is_remote = true @is_remote = true
@q = params[:name].strip
if params[:sort] if params[:sort]
order_by = params[:sort].split(":") order_by = params[:sort].split(":")
@sort = order_by[0] @sort = order_by[0]
@ -106,60 +110,105 @@ class FilesController < ApplicationController
end end
sort = "#{@sort} #{@order}" sort = "#{@sort} #{@order}"
end end
# show_attachments [@course]
begin begin
q = "%#{params[:name].strip}%" q = "%#{params[:name].strip}%"
#(redirect_to stores_url, :notice => l(:label_sumbit_empty);return) if params[:name].blank? #(redirect_to stores_url, :notice => l(:label_sumbit_empty);return) if params[:name].blank?
if params[:insite] if params[:insite]
if q == "%%" if q == "%%"
@result = [] @project_attachment_result = []
@searched_attach = paginateHelper @result,10 @searched_attach = paginateHelper @project_attachment_result, 10
else else
@result = find_public_attache q,sort @project_attachment_result = find_public_attache q,sort
@result = visable_attachemnts_insite @result,@project @project_attachment_result = visable_attachemnts_insite @project_attachment_result, @project
@searched_attach = paginateHelper @result,10 @searched_attach = paginateHelper @project_attachment_result, 10
end end
else else
@result = find_project_attache q,@project,sort @project_attachment_result = find_project_attache q, @project,sort
@result = visable_attachemnts @result @project_attachment_result = visable_attachemnts @project_attachment_result
@searched_attach = paginateHelper @result,10 @searched_attach = paginateHelper @project_attachment_result,10
@tag_list = get_project_tag_list @project
end end
#rescue Exception => e #rescue Exception => e
# #render 'stores' # #render 'stores'
# redirect_to search_course_files_url # redirect_to search_course_files_url
end end
end end
def search_files_in_subfield
sort = ""
@sort = ""
@order = ""
@is_remote = true
@q = params[:name].strip
if params[:sort]
order_by = params[:sort].split(":")
@sort = order_by[0]
if order_by.count > 1
@order = order_by[1]
end
sort = "#{@sort} #{@order}"
end
# show_attachments [@course]
begin
q = "%#{params[:name].strip}%"
#(redirect_to stores_url, :notice => l(:label_sumbit_empty);return) if params[:name].blank?
if params[:insite]
if q == "%%"
@result = []
@searched_attach = paginateHelper @result,10
else
@result = find_public_attache q,sort
@result = visable_attachemnts_insite @result,@org_subfield
@searched_attach = paginateHelper @result,10
end
else
@result = find_org_subfield_attache q,@org_subfield,sort
@result = visable_attachemnts @result
@searched_attach = paginateHelper @result,10
@tag_list = attachment_tag_list @result
end
#rescue Exception => e
# #render 'stores'
# redirect_to search_course_files_url
end
@page = params[:page] || 1
end
def find_course_attache keywords,course,sort = "" def find_course_attache keywords,course,sort = ""
if sort == "" if sort == ""
sort = "created_on DESC" sort = "created_on DESC"
end end
if keywords != "%%"
resultSet = Attachment.where("attachments.container_type = 'Course' And attachments.container_id = '#{course.id}' AND filename LIKE :like ", like: "%#{keywords}%"). resultSet = Attachment.where("attachments.container_type = 'Course' And attachments.container_id = '#{course.id}' AND filename LIKE :like ", like: "%#{keywords}%").
reorder(sort) reorder(sort)
else
resultSet = Attachment.where("attachments.container_type = 'Course' And attachments.container_id = '#{course.id}' "). reorder(sort)
end
#resultSet = Attachment.find_by_sql("SELECT `attachments`.* FROM `attachments` LEFT OUTER JOIN `homework_attaches` ON `attachments`.container_type = 'HomeworkAttach' AND `attachments`.container_id = `homework_attaches`.id LEFT OUTER JOIN `homework_for_courses` ON `homework_attaches`.bid_id = `homework_for_courses`.bid_id LEFT OUTER JOIN `homework_for_courses` AS H_C ON `attachments`.container_type = 'Bid' AND `attachments`.container_id = H_C.bid_id WHERE (`homework_for_courses`.course_id = 117 OR H_C.course_id = 117 OR (`attachments`.container_type = 'Course' AND `attachments`.container_id = 117)) AND `attachments`.filename LIKE '%#{keywords}%'").reorder("created_on DESC") #resultSet = Attachment.find_by_sql("SELECT `attachments`.* FROM `attachments` LEFT OUTER JOIN `homework_attaches` ON `attachments`.container_type = 'HomeworkAttach' AND `attachments`.container_id = `homework_attaches`.id LEFT OUTER JOIN `homework_for_courses` ON `homework_attaches`.bid_id = `homework_for_courses`.bid_id LEFT OUTER JOIN `homework_for_courses` AS H_C ON `attachments`.container_type = 'Bid' AND `attachments`.container_id = H_C.bid_id WHERE (`homework_for_courses`.course_id = 117 OR H_C.course_id = 117 OR (`attachments`.container_type = 'Course' AND `attachments`.container_id = 117)) AND `attachments`.filename LIKE '%#{keywords}%'").reorder("created_on DESC")
end end
def find_project_attache keywords,project,sort = "" def find_org_subfield_attache keywords,org_subfield,sort = ""
if sort == "" if sort == ""
sort = "created_on DESC" sort = "created_on DESC"
end end
ids = "" if keywords != "%%"
len = 0 resultSet = Attachment.where("attachments.container_type = 'OrgSubfield' And attachments.container_id = '#{org_subfield.id}' AND filename LIKE :like ", like: "%#{keywords}%").
count = project.versions.count reorder(sort)
project.versions.each do |version| else
len = len + 1 resultSet = Attachment.where("attachments.container_type = 'OrgSubfield' And attachments.container_id = '#{org_subfield.id}' "). reorder(sort)
if len != count end
ids += version.id.to_s + ',' #resultSet = Attachment.find_by_sql("SELECT `attachments`.* FROM `attachments` LEFT OUTER JOIN `homework_attaches` ON `attachments`.container_type = 'HomeworkAttach' AND `attachments`.container_id = `homework_attaches`.id LEFT OUTER JOIN `homework_for_courses` ON `homework_attaches`.bid_id = `homework_for_courses`.bid_id LEFT OUTER JOIN `homework_for_courses` AS H_C ON `attachments`.container_type = 'Bid' AND `attachments`.container_id = H_C.bid_id WHERE (`homework_for_courses`.course_id = 117 OR H_C.course_id = 117 OR (`attachments`.container_type = 'Course' AND `attachments`.container_id = 117)) AND `attachments`.filename LIKE '%#{keywords}%'").reorder("created_on DESC")
else end
ids += version.id.to_s
end def find_project_attache keywords,project,sort = ""
if sort == ""
sort = "created_on DESC"
end end
if ids.blank? if keywords != "%%"
resultSet = Attachment.where("attachments.container_type = 'Project' And attachments.container_id = '#{project.id}' AND filename LIKE :like ", like: "%#{keywords}%"). resultSet = Attachment.where("attachments.container_type = 'Project' And attachments.container_id = '#{project.id}' AND filename LIKE :like ", like: "%#{keywords}%").reorder(sort)
reorder(sort)
else else
resultSet = Attachment.where("((attachments.container_type = 'Project' And attachments.container_id = '#{project.id}') OR (container_type = 'Version' AND container_id IN (#{ids}))) AND filename LIKE :like ", like: "%#{keywords}%"). resultSet = Attachment.where("attachments.container_type = 'Project' And attachments.container_id = '#{project.id}' "). reorder(sort)
reorder(sort)
end end
end end
@ -176,23 +225,16 @@ class FilesController < ApplicationController
def index def index
@flag = params[:flag] || false @flag = params[:flag] || false
#sort_init 'filename', 'asc'
# sort_init 'created_on', 'desc'
# sort_update 'created_on' => "#{Attachment.table_name}.created_on",
# 'filename' => "#{Attachment.table_name}.filename",
# 'size' => "#{Attachment.table_name}.filesize",
# 'downloads' => "#{Attachment.table_name}.downloads"
sort = "" sort = ""
@sort = "" @sort = ""
@order = "" @order = ""
@is_remote = false @is_remote = false
if params[:project_id] if params[:project_id]
@isproject = true @page = params[:page] ? params[:page].to_i + 1 : 2
@container_type = 0
if params[:sort] if params[:sort]
params[:sort].split(",").each do |sort_type| params[:sort].split(",").each do |sort_type|
order_by = sort_type.split(":") order_by = sort_type.split(":")
case order_by[0] case order_by[0]
when "filename" when "filename"
attribute = "filename" attribute = "filename"
@ -230,25 +272,19 @@ class FilesController < ApplicationController
else else
sort = "#{Attachment.table_name}.created_on desc" sort = "#{Attachment.table_name}.created_on desc"
end end
# @containers = [ Project.includes(:attachments).find(@project.id)]
# @containers += @project.versions.includes(:attachments).all
@containers = [ Project.includes(:attachments).find(@project.id)] @containers = [ Project.includes(:attachments).reorder(sort).find(@project.id)]
@containers += @project.versions.includes(:attachments).all
ids = []
@containers.each do |c|
ids += c.attachments.pluck(:id)
end
@containers = [Struct.new(:attachments).new(Attachment.where('id in (?)',ids).reorder(sort))]
show_attachments @containers show_attachments @containers
respond_to do |format| @tag_list = attachment_tag_list @all_attachments
format.html
format.js
end
elsif params[:course_id]
@isproject = false
render :layout => 'base_projects'
elsif params[:course_id]
@container_type = 1
@page = params[:page] ? params[:page].to_i + 1 : 2
if params[:sort] if params[:sort]
params[:sort].split(",").each do |sort_type| params[:sort].split(",").each do |sort_type|
order_by = sort_type.split(":") order_by = sort_type.split(":")
@ -298,6 +334,56 @@ class FilesController < ApplicationController
@tag_list = attachment_tag_list @all_attachments @tag_list = attachment_tag_list @all_attachments
render :layout => 'base_courses' render :layout => 'base_courses'
elsif params[:org_subfield_id]
if params[:sort]
params[:sort].split(",").each do |sort_type|
order_by = sort_type.split(":")
case order_by[0]
when "filename"
attribute = "filename"
when "size"
attribute = "filesize"
when "attach_type"
attribute = "attachtype"
when "content_type"
attribute = "created_on"
when "field_file_dense"
attribute = "is_public"
when "downloads"
attribute = "downloads"
when "created_on"
attribute = "created_on"
when "quotes"
attribute = "quotes"
else
attribute = "created_on"
end
@sort = order_by[0]
@order = order_by[1]
if order_by.count == 1 && attribute
sort += "#{Attachment.table_name}.#{attribute} asc "
if sort_type != params[:sort].split(",").last
sort += ","
end
elsif order_by.count == 2 && order_by[1]
sort += "#{Attachment.table_name}.#{attribute} #{order_by[1]} "
if sort_type != params[:sort].split(",").last
sort += ","
end
end
end
else
sort = "#{Attachment.table_name}.created_on desc"
end
@container_type = 2
@containers = [ OrgSubfield.includes(:attachments).reorder(sort).find(@org_subfield.id)]
@organization = Organization.find(@containers.first.organization_id)
show_attachments @containers
@tag_list = attachment_tag_list @all_attachments
@page = params[:page] || 1
render :layout => 'base_org'
# @subfield = params[:org_subfield_id]
end end
end end
@ -312,6 +398,12 @@ class FilesController < ApplicationController
@can_quote = attachment_candown @file @can_quote = attachment_candown @file
end end
def quote_resource_show_org_subfield
@file = Attachment.find(params[:id])
@org_subfield = OrgSubfield.find(params[:org_subfield_id])
@can_quote = attachment_candown @file
end
def new def new
@versions = @project.versions.sort @versions = @project.versions.sort
@course_tag = @project.project_type @course_tag = @project.project_type
@ -333,14 +425,41 @@ class FilesController < ApplicationController
#modify by nwb #modify by nwb
if @project if @project
@addTag=false @addTag=false
container = (params[:version_id].blank? ? @project : @project.versions.find_by_id(params[:version_id])) if params[:in_project_toolbar]
attachments = Attachment.attach_filesex(container, params[:attachments], params[:attachment_type]) @in_project_toolbar = params[:in_project_toolbar]
render_attachment_warning_if_needed(container) end
# 发送邮件
attachments = Attachment.attach_filesex(@project, params[:attachments], params[:attachment_type])
if !attachments.empty? && !attachments[:files].blank? && Setting.notified_events.include?('file_added') if !attachments.empty? && !attachments[:files].blank? && Setting.notified_events.include?('file_added')
Mailer.run.attachments_added(attachments[:files]) Mailer.run.attachments_added(attachments[:files])
end end
# end
if params[:project_attachment_type] && params[:project_attachment_type].is_a?(Array)
params[:project_attachment_type].each do |type|
tag_name = get_project_tag_name_by_type_nmuber type
if !attachments.empty? && attachments[:files] && tag_name != ""
attachments[:files].each do |attachment|
attachment.tag_list.add(tag_name)
attachment.save
end
end
end
else
if params[:project_attachment_type] && params[:project_attachment_type] != "6"
tag_name = get_project_tag_name_by_type_nmuber params[:project_attachment_type]
if !attachments.empty? && attachments[:files] && tag_name != ""
attachments[:files].each do |attachment|
attachment.tag_list.add(tag_name)
attachment.save
end
end
end
end
# 更新资源总数, 根据上传的附件数累加
unless @project.project_score.nil?
@project.project_score.update_attribute(:attach_num, @project.project_score.attach_num + attachments[:files].count)
end
# end
# TODO: 临时用 nyan # TODO: 临时用 nyan
sort_init 'created_on', 'desc' sort_init 'created_on', 'desc'
sort_update 'created_on' => "#{Attachment.table_name}.created_on", sort_update 'created_on' => "#{Attachment.table_name}.created_on",
@ -348,14 +467,11 @@ class FilesController < ApplicationController
'size' => "#{Attachment.table_name}.filesize", 'size' => "#{Attachment.table_name}.filesize",
'downloads' => "#{Attachment.table_name}.downloads" 'downloads' => "#{Attachment.table_name}.downloads"
@containers = [Project.includes(:attachments).reorder("#{Attachment.table_name}.created_on DESC").find(@project.id)] #modify by Long Jun @containers = [Project.includes(:attachments).reorder("#{Attachment.table_name}.created_on DESC").find(@project.id)]
@containers += @project.versions.includes(:attachments).reorder("#{Attachment.table_name}.created_on DESC").all.sort
show_attachments @containers show_attachments @containers
@tag_list = attachment_tag_list @all_attachments
@attachtype = 0 @attachtype = 0
@contenttype = 0 @contenttype = 0
respond_to do |format| respond_to do |format|
format.js format.js
format.html { format.html {
@ -364,33 +480,38 @@ class FilesController < ApplicationController
end end
elsif @course elsif @course
@addTag=false @addTag=false
if params[:in_course_toolbar]
@in_course_toolbar = params[:in_course_toolbar]
end
attachments = Attachment.attach_filesex(@course, params[:attachments], params[:attachment_type]) attachments = Attachment.attach_filesex(@course, params[:attachments], params[:attachment_type])
if !attachments.empty? && !attachments[:files].blank? && Setting.notified_events.include?('file_added') if !attachments.empty? && !attachments[:files].blank? && Setting.notified_events.include?('file_added')
Mailer.run.attachments_added(attachments[:files]) Mailer.run.attachments_added(attachments[:files])
end end
if params[:course_attachment_type] && params[:course_attachment_type].is_a?(Array)
if params[:course_attachment_type] && params[:course_attachment_type] != "5" params[:course_attachment_type].each do |type|
case params[:course_attachment_type] tag_name = get_tag_name_by_type_number type
when "1" if !attachments.empty? && attachments[:files] && tag_name != ""
tag_name = l(:label_courseware) attachments[:files].each do |attachment|
when "2" attachment.tag_list.add(tag_name)
tag_name = l(:label_software) attachment.save
when "3" end
tag_name = l(:label_media) end
when "4"
tag_name = l(:label_code)
else
tag_name = ""
end end
if !attachments.empty? && attachments[:files] && tag_name != "" else
attachments[:files].each do |attachment| if params[:course_attachment_type] && params[:course_attachment_type] != "5"
attachment.tag_list.add(tag_name) tag_name = get_tag_name_by_type_number params[:course_attachment_type]
attachment.save if !attachments.empty? && attachments[:files] && tag_name != ""
attachments[:files].each do |attachment|
attachment.tag_list.add(tag_name)
attachment.save
end
end end
end end
end end
# 更新课程英雄榜得分
update_contributor_score(@course, attachments[:files].first)
# end
# TODO: 临时用 nyan # TODO: 临时用 nyan
sort_init 'created_on', 'desc' sort_init 'created_on', 'desc'
sort_update 'created_on' => "#{Attachment.table_name}.created_on", sort_update 'created_on' => "#{Attachment.table_name}.created_on",
@ -412,11 +533,106 @@ class FilesController < ApplicationController
redirect_to course_files_url(@course) redirect_to course_files_url(@course)
} }
end end
end elsif @org_subfield
@addTag=false
attachments = Attachment.attach_filesex(@org_subfield, params[:attachments], params[:org_subfield_attachment_type])
if params[:org_subfield_attachment_type] && params[:org_subfield_attachment_type].is_a?(Array)
params[:org_subfield_attachment_type].each do |type|
tag_name = get_tag_name_by_type_number type
if !attachments.empty? && attachments[:files] && tag_name != ""
attachments[:files].each do |attachment|
attachment.tag_list.add(tag_name)
attachment.save
end
end
end
else
if params[:org_subfield_attachment_type] && params[:org_subfield_attachment_type] != "5"
tag_name = get_tag_name_by_type_number params[:org_subfield_attachment_type]
if !attachments.empty? && attachments[:files] && tag_name != ""
attachments[:files].each do |attachment|
attachment.tag_list.add(tag_name)
attachment.save
end
end
end
end
# TODO: 临时用 nyan
sort_init 'created_on', 'desc'
sort_update 'created_on' => "#{Attachment.table_name}.created_on",
'filename' => "#{Attachment.table_name}.filename",
'size' => "#{Attachment.table_name}.filesize",
'downloads' => "#{Attachment.table_name}.downloads"
@containers = [OrgSubfield.includes(:attachments).reorder("#{Attachment.table_name}.created_on DESC").find(@org_subfield.id)]
show_attachments @containers
@tag_list = attachment_tag_list @all_attachments
@attachtype = 0
@contenttype = 0
respond_to do |format|
format.js
# format.html {
# redirect_to org_subfield_files_url(@org_subfield)
# }
end
end
end end
end end
def update_contributor_score(course, file )
unless file.author.allowed_to?(:as_teacher, course)
course_contributor_score = CourseContributorScore.where("course_id =? and user_id =?", course.id, file.author.id).first
if course_contributor_score.nil?
CourseContributorScore.create(:course_id => course.id, :user_id => file.author.id, :message_num => 0, :message_reply_num => 0,
:news_reply_num => 0, :resource_num => 5, :journal_num => 0, :journal_reply_num => 0, :total_score => 5)
else
score = course_contributor_score.resource_num + 5
total_score = course_contributor_score.total_score + 5
course_contributor_score.update_attributes(:resource_num => score, :total_score => total_score)
end
end
end
def get_project_tag_name_by_type_nmuber type
case type
when "1"
tag_name = "软件版本"
when "2"
tag_name = "文档"
when "3"
tag_name = "代码"
when "4"
tag_name = "媒体"
when "5"
tag_name = "论文"
when "6"
tag_name = "其它"
else
tag_name = ""
end
end
def get_tag_name_by_type_number type
case type
when "1"
tag_name = l(:label_courseware)
when "2"
tag_name = l(:label_software)
when "3"
tag_name = l(:label_media)
when "4"
tag_name = l(:label_code)
when "6"
tag_name = "论文"
else
tag_name = ""
end
end
def tag_saveEx def tag_saveEx
@tags = params[:tag_name][:name] @tags = params[:tag_name][:name]
@obj_id = params[:object_id] @obj_id = params[:object_id]
@ -551,15 +767,70 @@ class FilesController < ApplicationController
end end
q = "%#{@q.strip}%" q = "%#{@q.strip}%"
@result = find_course_attache q,@course,sort if @project
@result = find_project_attache q, @project,sort
else
@result = find_course_attache q,@course,sort
end
@result = visable_attachemnts @result @result = visable_attachemnts @result
@result = @result.select{|attachment| attachment.tag_list.include?(@tag_name)} if params[:other]
if @project
@result = @result.select{|attachment| !attachment.tag_list.include?('软件版本') && !attachment.tag_list.include?('文档') && !attachment.tag_list.include?('代码') && !attachment.tag_list.include?('媒体') && !attachment.tag_list.include?('论文') }
else
@result = @result.select{|attachment|
!attachment.tag_list.include?('课件') &&
!attachment.tag_list.include?('软件') &&
!attachment.tag_list.include?('媒体') &&
!attachment.tag_list.include?('代码') &&
!attachment.tag_list.include?('论文') }
end
else
@result = @result.select{|attachment| attachment.tag_list.include?(@tag_name)} unless @tag_name.blank?
end
@searched_attach = paginateHelper @result,10 @searched_attach = paginateHelper @result,10
@tag_list = get_course_tag_list @course if @project
@tag_list = get_project_tag_list @project
@result_search_project = @result
else
@tag_list = get_course_tag_list @course
end
respond_to do |format|
format.js
# format.html
end
end
#搜索资源栏目的指定TAG的资源列表
def search_org_subfield_tag_attachment
@q,@tag_name,@order = params[:q],params[:tag_name]
@is_remote = true
if params[:sort]
order_by = params[:sort].split(":")
@sort = order_by[0]
if order_by.count > 1
@order = order_by[1]
end
sort = "#{@sort} #{@order}"
end
q = "%#{@q.strip}%"
@result = find_org_subfield_attache q,@org_subfield,sort
@result = visable_attachemnts @result
@result = @result.select{|attachment| attachment.tag_list.include?(@tag_name)} unless @tag_name.blank?
@searched_attach = paginateHelper @result,10
@tag_list = get_org_subfield_tag_list @org_subfield
respond_to do |format| respond_to do |format|
format.js format.js
# format.html # format.html
end end
end end
def subfield_upload_file
@org_subfield = OrgSubfield.find(params[:org_subfield_id])
end
def upload_files_menu
end
end end

@ -7,7 +7,7 @@ class ForumsController < ApplicationController
before_filter :find_forum_if_available before_filter :find_forum_if_available
before_filter :authenticate_user_edit, :only => [:edit, :update] before_filter :authenticate_user_edit, :only => [:edit, :update]
before_filter :authenticate_user_destroy, :only => [:destroy] before_filter :authenticate_user_destroy, :only => [:destroy]
before_filter :require_login, :only => [:new, :create] before_filter :require_login, :only => [:new, :create,:destroy,:update,:edit]
helper :sort helper :sort
include SortHelper include SortHelper
@ -97,7 +97,24 @@ class ForumsController < ApplicationController
def index def index
@offset, @limit = api_offset_and_limit({:limit => 10}) @offset, @limit = api_offset_and_limit({:limit => 10})
@forums_all = Forum.reorder("sticky DESC") if(params[:reorder_complex])
@type="reorder_complex"
@str=params[:reorder_complex]
@forums_all = Forum.reorder("topic_count #{params[:reorder_complex]},updated_at #{params[:reorder_complex]}")
elsif(params[:reorder_popu])
@type="reorder_popu"
@str=params[:reorder_popu]
@forums_all = Forum.reorder("topic_count #{params[:reorder_popu]}")
elsif(params[:reorder_time])
@type="reorder_time"
@str=params[:reorder_time]
@forums_all = Forum.reorder("updated_at #{params[:reorder_time]}")
else
params[:reorder_complex] = "desc"
@type="reorder_complex"
@str=params[:reorder_complex]
@forums_all = Forum.reorder("topic_count desc,updated_at desc")
end
@forums_count = @forums_all.count @forums_count = @forums_all.count
@forums_pages = Paginator.new @forums_count, @limit, params['page'] @forums_pages = Paginator.new @forums_count, @limit, params['page']
@ -106,6 +123,7 @@ class ForumsController < ApplicationController
#@forums = Forum.all #@forums = Forum.all
respond_to do |format| respond_to do |format|
format.html # index.html.erb format.html # index.html.erb
format.js
format.json { render json: @forums } format.json { render json: @forums }
end end
end end
@ -113,11 +131,25 @@ class ForumsController < ApplicationController
# GET /forums/1 # GET /forums/1
# GET /forums/1.json # GET /forums/1.json
def show def show
sort_init 'updated_at', 'desc' # sort_init 'updated_at', 'desc'
sort_update 'created_at' => "#{Memo.table_name}.created_at", # sort_update 'created_at' => "#{Memo.table_name}.created_at",
'replies' => "#{Memo.table_name}.replies_count", # 'replies' => "#{Memo.table_name}.replies_count",
'updated_at' => "COALESCE (last_replies_memos.created_at, #{Memo.table_name}.created_at)" # 'updated_at' => "COALESCE (last_replies_memos.created_at, #{Memo.table_name}.created_at)"
order = ""
@order_str = ""
if(params[:reorder_complex])
order = " last_replies_memos.created_at #{params[:reorder_complex]}, #{Memo.table_name}.created_at #{params[:reorder_complex]}"
@order_str = "reorder_complex="+params[:reorder_complex]
elsif(params[:reorder_popu])
order = "replies_count #{params[:reorder_popu]}"
@order_str = "reorder_popu="+params[:reorder_popu]
elsif(params[:reorder_time])
order = "#{Memo.table_name}.updated_at #{params[:reorder_time]}"
@order_str = "reorder_time="+params[:reorder_time]
else
order = "#{Memo.table_name}.updated_at desc"
@order_str = "reorder_time=desc"
end
@memo = Memo.new(:forum => @forum) @memo = Memo.new(:forum => @forum)
@topic_count = @forum.topics.count @topic_count = @forum.topics.count
@topic_pages = Paginator.new @topic_count, per_page_option, params['page'] @topic_pages = Paginator.new @topic_count, per_page_option, params['page']
@ -126,19 +158,15 @@ class ForumsController < ApplicationController
includes(:last_reply). includes(:last_reply).
limit(@topic_pages.per_page). limit(@topic_pages.per_page).
offset(@topic_pages.offset). offset(@topic_pages.offset).
order(sort_clause). reorder(order).
preload(:author, {:last_reply => :author}). preload(:author, {:last_reply => :author}).
all all
@memos @memos
# @offset, @limit = api_offset_and_limit({:limit => 10}) @my_topic_count = Memo.where("forum_id = #{@forum.id} and author_id = #{User.current.id} and parent_id is null").count
# @forum = Forum.find(params[:id]) @my_replies_count = Memo.where("forum_id = #{@forum.id} and author_id = #{User.current.id} and parent_id is not null").count
# @memos_all = @forum.topics @errors = params[:errors]
# @topic_count = @memos_all.count
# @topic_pages = Paginator.new @topic_count, @limit, params['page']
# @offset ||= @topic_pages.offset
# @memos = @memos_all.offset(@offset).limit(@limit).all
respond_to do |format| respond_to do |format|
format.js
format.html { format.html {
render :layout => 'base_forums' render :layout => 'base_forums'
}# show.html.erb }# show.html.erb
@ -172,20 +200,23 @@ class ForumsController < ApplicationController
# Author lizanle # Author lizanle
# Description after save后需要进行资源记录的更新 # Description after save后需要进行资源记录的更新
# owner_type = 2 对应的是 forum # owner_type = 2 对应的是 forum
@save_flag=true
if params[:asset_id] if params[:asset_id]
ids = params[:asset_id].split(',') ids = params[:asset_id].split(',')
update_kindeditor_assets_owner ids ,@forum.id,OwnerTypeHelper::FORUM update_kindeditor_assets_owner ids ,@forum.id,OwnerTypeHelper::FORUM
end end
#end #end
respond_to do |format| respond_to do |format|
format.js
format.html { redirect_to @forum, notice: l(:label_forum_create_succ) } format.html { redirect_to @forum, notice: l(:label_forum_create_succ) }
format.json { render json: @forum, status: :created, location: @forum } format.json { render json: @forum, status: :created, location: @forum }
end end
else else
@save_flag=false
respond_to do |format| respond_to do |format|
flash.now[:error] = "#{l :label_forum_create_fail}: #{@forum.errors.full_messages[0]}" flash.now[:error] = "#{l :label_forum_create_fail}: #{@forum.errors.full_messages[0]}"
format.js
format.html { render action: "new" } format.html { render action: "new" }
format.json { render json: @forum.errors, status: :unprocessable_entity } format.json { render json: @forum.errors, status: :unprocessable_entity }
end end
@ -199,10 +230,12 @@ class ForumsController < ApplicationController
respond_to do |format| respond_to do |format|
if @forum.update_attributes(params[:forum]) if @forum.update_attributes(params[:forum])
format.js {render :text=> true}
format.html { redirect_to @forum, notice: l(:label_forum_update_succ) } format.html { redirect_to @forum, notice: l(:label_forum_update_succ) }
format.json { head :no_content } format.json { head :no_content }
else else
flash.now[:error] = "#{l :label_forum_update_fail}: #{@forum.errors.full_messages[0]}" flash.now[:error] = "#{l :label_forum_update_fail}: #{@forum.errors.full_messages[0]}"
format.js { render :text=> false}
format.html { render action: "edit" } format.html { render action: "edit" }
format.json { render json: @forum.errors, status: :unprocessable_entity } format.json { render json: @forum.errors, status: :unprocessable_entity }
end end
@ -261,6 +294,52 @@ class ForumsController < ApplicationController
end end
end end
#检查forum的名字
def check_forum_name
forum_name_exist = true
if params[:forum_id]
forum_name_exist = Forum.where("name = '#{params[:forum_name]}' and id != #{params[:forum_id]}").count >= 1 ? true : false
else
forum_name_exist = Forum.where("name = '#{params[:forum_name]}' ").count >= 1 ? true : false
end
render :text => forum_name_exist
end
#添加论坛tag
def add_forum_tag
@forum = Forum.find(params[:id])
unless @forum.nil?
@forum.tag_list.add(params[:tag_str].split(','))
@forum.save
end
respond_to do |format|
format.js {render :delete_forum_tag}
end
end
#删除forum的tag
def delete_forum_tag
@tag_id = (ActsAsTaggableOn::Tag.find_by_name(params[:tag_name])).id
#forum的taggable_type = 5
@taggings = ActsAsTaggableOn::Tagging.find_by_tag_id_and_taggable_id_and_taggable_type(@tag_id,params[:id],'Forum')
unless @taggings.nil?
@taggings.delete
end
# 是否还有其他记录 引用了 tag_id
@tagging = ActsAsTaggableOn::Tagging.find_by_tag_id(@tag_id)
# 如果taggings表中记录已经不存在 那么检查tags表 作删除动作
if @tagging.nil?
@tag = ActsAsTaggableOn::Tag.find_by_id(@tag_id)
@tag.delete unless @tag.nil?
end
@forum = Forum.find(params[:id])
respond_to do |format|
format.js
end
end
private private
def find_forum_if_available def find_forum_if_available

@ -42,8 +42,8 @@ class GanttsController < ApplicationController
respond_to do |format| respond_to do |format|
format.html { render :action => "show", :layout => 'base_projects' }#by young format.html { render :action => "show", :layout => 'base_projects' }#by young
format.png { send_data(@gantt.to_image, :disposition => 'inline', :type => 'image/png', :filename => "#{basename}.png") } if @gantt.respond_to?('to_image') format.png { send_data(@gantt.to_image, :disposition => 'inline', :type => 'image/png', :filename => filename_for_content_disposition("#{basename}.png")) } if @gantt.respond_to?('to_image')
format.pdf { send_data(@gantt.to_pdf, :type => 'application/pdf', :filename => "#{basename}.pdf") } format.pdf { send_data(@gantt.to_pdf, :type => 'application/pdf', :filename => filename_for_content_disposition("#{basename}.pdf") ) }
end end
end end
end end

@ -1,12 +0,0 @@
#added by baiyu
class GitUsageController < ApplicationController
layout "new_base"
def ch_usage
end
def en_usage
end
end
#end

@ -33,7 +33,7 @@ class HomeworkAttachController < ApplicationController
format.js format.js
format.xls { format.xls {
send_data(homework_to_xls(@all_homework_list), :type => "text/excel;charset=utf-8; header=present", send_data(homework_to_xls(@all_homework_list), :type => "text/excel;charset=utf-8; header=present",
:filename => "#{@course.teacher.lastname.to_s + @course.teacher.firstname}_#{@course.name}_#{@course.time.to_s + @course.term}_#{@bid.name}#{l(:excel_homework_list)}(#{l(:excel_not_rated)}).xls") :filename => filename_for_content_disposition("#{@course.teacher.lastname.to_s + @course.teacher.firstname}_#{@course.name}_#{@course.time.to_s + @course.term}_#{@bid.name}#{l(:excel_homework_list)}(#{l(:excel_not_rated)}).xls") )
} }
end end
end end
@ -66,7 +66,7 @@ class HomeworkAttachController < ApplicationController
format.js format.js
format.xls { format.xls {
send_data(homework_to_xls(all_homework_list), :type => "text/excel;charset=utf-8; header=present", send_data(homework_to_xls(all_homework_list), :type => "text/excel;charset=utf-8; header=present",
:filename => "#{@course.teacher.lastname.to_s + @course.teacher.firstname}_#{@course.name}_#{@course.time.to_s + @course.term}_#{@bid.name}#{l(:excel_homework_list)}(#{l(:excel_been_rated)}).xls") :filename => filename_for_content_disposition("#{@course.teacher.lastname.to_s + @course.teacher.firstname}_#{@course.name}_#{@course.time.to_s + @course.term}_#{@bid.name}#{l(:excel_homework_list)}(#{l(:excel_been_rated)}).xls") )
} }
end end
end end
@ -101,7 +101,7 @@ class HomeworkAttachController < ApplicationController
format.js format.js
format.xls { format.xls {
send_data(homework_to_xls(all_homework_list), :type => "text/excel;charset=utf-8; header=present", send_data(homework_to_xls(all_homework_list), :type => "text/excel;charset=utf-8; header=present",
:filename => "#{@course.teacher.lastname.to_s + @course.teacher.firstname}_#{@course.name}_#{@course.time.to_s + @course.term}_#{@bid.name}#{l(:excel_homework_list)}.xls") :filename => filename_for_content_disposition("#{@course.teacher.lastname.to_s + @course.teacher.firstname}_#{@course.name}_#{@course.time.to_s + @course.term}_#{@bid.name}#{l(:excel_homework_list)}.xls") )
} }
end end
end end

@ -3,287 +3,123 @@ class HomeworkCommonController < ApplicationController
require 'json' require 'json'
require "base64" require "base64"
layout "base_courses" layout "base_courses"
before_filter :find_course, :only => [:index,:new,:create,:next_step]
before_filter :find_homework, :only => [:edit,:update,:alert_anonymous_comment,:start_anonymous_comment,:stop_anonymous_comment,:destroy] include StudentWorkHelper
before_filter :teacher_of_course, :only => [:new, :create, :edit, :update, :destroy, :start_anonymous_comment, :stop_anonymous_comment, :alert_anonymous_comment] before_filter :find_course, :only => [:index,:new,:create]
before_filter :find_homework, :only => [:edit,:update,:alert_anonymous_comment,:start_anonymous_comment,:stop_anonymous_comment,:destroy,:start_evaluation_set,:set_evaluation_attr,:score_rule_set,:alert_forbidden_anonymous_comment]
before_filter :teacher_of_course, :only => [:new, :create, :edit, :update, :destroy, :start_anonymous_comment, :stop_anonymous_comment, :alert_anonymous_comment,:start_evaluation_set,:set_evaluation_attr,:score_rule_set,:alert_forbidden_anonymous_comment]
before_filter :member_of_course, :only => [:index] before_filter :member_of_course, :only => [:index]
def index def index
homeworks = @course.homework_commons.order("created_at desc") @new_homework = HomeworkCommon.new
@new_homework.homework_detail_manual = HomeworkDetailManual.new
@new_homework.course = @course
@page = params[:page] ? params[:page].to_i + 1 : 0
@is_teacher = User.current.logged? && (User.current.admin? || User.current.allowed_to?(:as_teacher,@course)) @is_teacher = User.current.logged? && (User.current.admin? || User.current.allowed_to?(:as_teacher,@course))
if @is_teacher
@homeworks = @course.homework_commons.order("created_at desc").limit(10).offset(@page * 10)
else
@homeworks = @course.homework_commons.where("publish_time <= '#{Date.today}'").order("created_at desc").limit(10).offset(@page * 10)
end
@is_student = User.current.logged? && (User.current.admin? || (User.current.member_of_course?(@course) && !@is_teacher)) @is_student = User.current.logged? && (User.current.admin? || (User.current.member_of_course?(@course) && !@is_teacher))
@homeworks = paginateHelper homeworks,20 @is_new = params[:is_new]
respond_to do |format|
format.html #设置at已读
@homeworks.each do |homework|
homework.journals_for_messages.each do |j|
User.current.at_messages.unviewed('JournalsForMessage', j.id).each {|x| x.viewed!}
end
end end
end
def new
# @homework_type = "1"
#
# @homework = HomeworkCommon.new
# @homework.safe_attributes = params[:homework_common]
# @homework.late_penalty = 2
# @homework.end_time = (Time.now + 3600 * 24).strftime('%Y-%m-%d')
# @homework.publish_time = Time.now.strftime('%Y-%m-%d')
#
# if @homework_type == "1"
# #匿评作业相关属性
# @homework_detail_manual = HomeworkDetailManual.new
# @homework_detail_manual.ta_proportion = 0.6
# @homework_detail_manual.absence_penalty = 2
# @homework_detail_manual.evaluation_num = 3
# @homework_detail_manual.evaluation_start = Time.now.strftime('%Y-%m-%d')
# @homework_detail_manual.evaluation_end = (Time.now + 3600 * 24).strftime('%Y-%m-%d')
# @homework.homework_detail_manual = @homework_detail_manual
# elsif @homework_type == "2"
# #编程作业相关属性
# @homework_detail_programing = HomeworkDetailPrograming.new
# @homework.homework_detail_programing = @homework_detail_programing
# end
respond_to do |format| respond_to do |format|
format.js
format.html format.html
end end
end end
#新建作业下一步 #新建作业,在个人作业列表创建作业
def next_step def new
@homework_type = params[:homework_common_type] render_404
@homework = HomeworkCommon.new
@homework.safe_attributes = params[:homework_common]
@homework.late_penalty = 2
@homework.end_time = (Time.now + 3600 * 24).strftime('%Y-%m-%d')
@homework.publish_time = Time.now.strftime('%Y-%m-%d')
if @homework_type == "1"
#匿评作业相关属性
@homework_detail_manual = HomeworkDetailManual.new
@homework_detail_manual.ta_proportion = 0.6
@homework_detail_manual.absence_penalty = 2
@homework_detail_manual.evaluation_num = 3
@homework_detail_manual.evaluation_start = Time.now.strftime('%Y-%m-%d')
@homework_detail_manual.evaluation_end = (Time.now + 3600 * 24).strftime('%Y-%m-%d')
@homework.homework_detail_manual = @homework_detail_manual
elsif @homework_type == "2"
#编程作业相关属性
@homework_detail_programing = HomeworkDetailPrograming.new
@homework.homework_detail_programing = @homework_detail_programing
end
respond_to do |format|
format.html
end
end end
#新建作业,在个人作业列表创建作业
def create def create
if params[:homework_common] redirect_to user_homeworks_user_path(User.current.id)
homework = HomeworkCommon.new
homework.name = params[:homework_common][:name]
homework.description = params[:homework_common][:description]
homework.end_time = params[:homework_common][:end_time]
homework.publish_time = params[:homework_common][:publish_time]
homework.homework_type = params[:homework_common][:homework_type]
homework.late_penalty = params[:late_penalty]
homework.user_id = User.current.id
homework.course_id = @course.id
homework.save_attachments(params[:attachments])
render_attachment_warning_if_needed(homework)
if homework.homework_type == 2
homework_detail_programing = HomeworkDetailPrograming.new
homework_detail_programing.language = params[:language]
homework_detail_programing.standard_code = params[:standard_code]
homework_detail_programing.ta_proportion = params[:ta_proportion] || 0.6
question = {title:homework.name,content:homework.description}
question[:input] = []
question[:output] = []
if params[:input] && params[:output] && params[:result]
params[:input].each do |k,v|
if params[:output].include? k
homework_test = HomeworkTest.new
homework_test.input = v
homework_test.output = params[:output][k]
homework_test.result = params[:result][k]
homework_test.error_msg = params[:error_msg]
homework.homework_tests << homework_test
question[:input] << homework_test.input
question[:output] << homework_test.output
end
end
end
# uri = URI('http://test.gitlab.trustie.net/api/questions.json')
# req = Net::HTTP::Post.new(uri, initheader = {'Content-Type' =>'application/json'})
# req.body = question.to_json
# res = Net::HTTP.start(uri.hostname, uri.port) do |http|
# http.request(req)
# end
uri = URI('http://192.168.80.21:8080/api/questions.json')
body = question.to_json
res = Net::HTTP.new(uri.host, uri.port).start do |client|
request = Net::HTTP::Post.new(uri.path)
request.body = body
request["Content-Type"] = "application/json"
client.request(request)
end
result = JSON.parse(res.body)
homework_detail_programing.question_id = result["id"] if result["status"] && result["status"] == 0
homework.homework_detail_programing = homework_detail_programing
else
#匿评作业相关属性
homework_detail_manual = HomeworkDetailManual.new
homework_detail_manual.ta_proportion = params[:ta_proportion] || 0.6
homework_detail_manual.comment_status = 1
homework_detail_manual.evaluation_start = params[:evaluation_start]
homework_detail_manual.evaluation_end = params[:evaluation_end]
homework_detail_manual.evaluation_num = params[:evaluation_num]
homework_detail_manual.absence_penalty = params[:absence_penalty]
homework.homework_detail_manual = homework_detail_manual
end
if homework.save
homework_detail_programing.save if homework_detail_programing
homework_detail_manual.save if homework_detail_manual
respond_to do |format|
format.html {
flash[:notice] = l(:notice_successful_create)
redirect_to homework_common_index_path(:course => @course.id)
}
end
return
end
end
respond_to do |format|
format.html {
flash[:notice] = l(:notice_failed_create)
redirect_to new_homework_common_path(:course => @course.id)
}
end
end end
def edit def edit
@user = User.current
@is_in_course = params[:is_in_course].to_i
@course_activity = params[:course_activity].to_i
respond_to do |format| respond_to do |format|
format.html format.html{render :layout => 'new_base_user'}
end end
end end
def update def update
@homework.name = params[:homework_common][:name] if params[:homework_common]
@homework.description = params[:homework_common][:description] @homework.name = params[:homework_common][:name]
@homework.end_time = params[:homework_common][:end_time] @homework.description = params[:homework_common][:description]
@homework.publish_time = params[:homework_common][:publish_time] if params[:homework_common][:publish_time] == ""
@homework.homework_type = params[:homework_common][:homework_type] if params[:homework_common][:homework_type] @homework.publish_time = Date.today
unless @homework.late_penalty == params[:late_penalty] else
@homework.student_works.where("created_at > '#{@homework.end_time} 23:59:59'").each do |student_work| @homework.publish_time = params[:homework_common][:publish_time]
student_work.late_penalty = params[:late_penalty]
student_work.save
end end
@homework.late_penalty = params[:late_penalty] @homework.end_time = params[:homework_common][:end_time] || Time.now
end @homework.course_id = params[:course_id]
# @homework.course_id = @course.id @homework.anonymous_comment = params[:homework_common][:anonymous_comment] ? params[:homework_common][:anonymous_comment] : 0
#匿评作业相关属性 homework_detail_manual = @homework.homework_detail_manual || HomeworkDetailManual.new
if @homework.homework_type == 1 && @homework_detail_manual if @homework.publish_time <= Date.today && homework_detail_manual.comment_status == 0
@homework_detail_manual.ta_proportion = params[:ta_proportion] || 0.6 homework_detail_manual.comment_status = 1
@homework_detail_manual.evaluation_start = params[:evaluation_start]
@homework_detail_manual.evaluation_end = params[:evaluation_end]
@homework_detail_manual.evaluation_num = params[:evaluation_num]
unless @homework_detail_manual.absence_penalty == params[:absence_penalty]
if @homework_detail_manual.comment_status == 3 #当前作业处于匿评结束状态,修改缺评扣分才会修改每个作品应扣分的值
work_ids = "(" + @homework.student_works.map(&:id).join(",") + ")"
@homework.student_works.each do |student_work|
absence_penalty_count = student_work.user.student_works_evaluation_distributions.where("student_work_id IN #{work_ids}").count - student_work.user.student_works_scores.where("student_work_id IN #{work_ids}").count
student_work.absence_penalty = absence_penalty_count > 0 ? absence_penalty_count * @homework_detail_manual.absence_penalty : 0
student_work.save
end
end
@homework_detail_manual.absence_penalty = params[:absence_penalty]
end
elsif @homework.homework_type == 0 #普通作业缺评扣分为0分每个作品的缺评扣分改为0分防止某些作业在结束匿评之后改为普通作业
@homework.student_works.where("absence_penalty != 0").each do |student_work|
student_work.late_penalty = 0
student_work.save
end end
@homework_detail_manual.absence_penalty = 0 if @homework_detail_manual homework_detail_manual.evaluation_start = params[:evaluation_start].blank? ? @homework.end_time + 7 : params[:evaluation_start]
end homework_detail_manual.evaluation_end = params[:evaluation_end].blank? ? homework_detail_manual.evaluation_start + 7 : params[:evaluation_end]
if @homework.homework_type == 2 && @homework_detail_programing #编程作业 @homework.save_attachments(params[:attachments])
@homework_detail_programing.language = params[:language] render_attachment_warning_if_needed(@homework)
@homework_detail_programing.standard_code = params[:standard_code]
@homework_detail_programing.ta_proportion = params[:ta_proportion] || 0.6 #编程作业相关属性
homework_tests = @homework.homework_tests if @homework.homework_type == 2
#需要删除的测试 @homework.homework_detail_programing ||= HomeworkDetailPrograming.new
ids = homework_tests.map(&:id) - params[:input].keys.map(&:to_i) @homework_detail_programing = @homework.homework_detail_programing
ids.each do |id| @homework_detail_programing.language = params[:language_type].to_i
homework_test = HomeworkTest.find id
homework_test.destroy if homework_test @homework.homework_tests.delete_all
end inputs = params[:program][:input]
if params[:input] && params[:output] && params[:result] if Array === inputs
params[:input].each do |k,v| inputs.each_with_index do |val, i|
if params[:output].include? k @homework.homework_tests << HomeworkTest.new(
homework_test = HomeworkTest.find_by_id k input: val,
if homework_test #已存在的测试,修改 output: params[:program][:output][i]
homework_test.input = v )
homework_test.output = params[:output][k]
homework_test.result = params[:result][k]
homework_test.error_msg = params[:error_msg]
else #不存在的测试,增加
homework_test = HomeworkTest.new
homework_test.input = v
homework_test.output = params[:output][k]
homework_test.result = params[:result][k]
homework_test.error_msg = params[:error_msg]
homework_test.homework_common = @homework
end end
homework_test.save
end end
end
end end
#发送修改作业的请求 #分组作业
question = {title:@homework.name,content:@homework.description} if @homework.homework_type == 3
question[:input] = [] @homework.homework_detail_group ||= HomeworkDetailGroup.new
question[:output] = [] @homework_detail_group = @homework.homework_detail_group
@homework.homework_tests.each do |test| @homework_detail_group.min_num = params[:min_num].to_i
question[:input] << test.input @homework_detail_group.max_num = params[:max_num].to_i
question[:output] << test.output @homework_detail_group.base_on_project = params[:base_on_project].to_i
end end
uri = URI("http://192.168.80.21:8080/api/questions/#{@homework_detail_programing.question_id}.json")
body = question.to_json
res = Net::HTTP.new(uri.host, uri.port).start do |client|
request = Net::HTTP::Put.new(uri.path)
request.body = body
request["Content-Type"] = "application/json"
client.request(request)
end
result = JSON.parse(res.body)
end
@homework.save_attachments(params[:attachments]) if @homework.save
render_attachment_warning_if_needed(@homework) @homework_detail_manual.save if @homework_detail_manual
@homework_detail_programing.save if @homework_detail_programing
@homework_detail_group.save if @homework_detail_group
if @homework.save if params[:is_in_course] == "1"
@homework_detail_manual.save if @homework_detail_manual
@homework_detail_programing.save if @homework_detail_programing
respond_to do |format|
format.html {
flash[:notice] = l(:notice_successful_edit)
redirect_to homework_common_index_path(:course => @course.id) redirect_to homework_common_index_path(:course => @course.id)
} elsif params[:is_in_course] == "0"
end redirect_to user_homeworks_user_path(User.current.id)
return elsif params[:is_in_course] == "-1" && params[:course_activity] == "0"
else redirect_to user_path(User.current.id)
respond_to do |format| elsif params[:is_in_course] == "-1" && params[:course_activity] == "1"
format.html { redirect_to course_path(@course.id)
flash[:notice] = l(:notice_failed_edit) end
redirect_to edit_homework_common_path(@homework)
}
end end
end end
end end
@ -291,7 +127,17 @@ class HomeworkCommonController < ApplicationController
def destroy def destroy
if @homework.destroy if @homework.destroy
respond_to do |format| respond_to do |format|
format.html {redirect_to homework_common_index_path(:course => @course.id)} format.html {
if params[:is_in_course] == "1"
redirect_to homework_common_index_path(:course => @course.id)
elsif params[:is_in_course] == "0"
redirect_to user_homeworks_user_path(User.current.id)
elsif params[:is_in_course] == "-1" && params[:course_activity] == "0"
redirect_to user_path(User.current.id)
elsif params[:is_in_course] == "-1" && params[:course_activity] == "1"
redirect_to course_path(@course.id)
end
}
end end
end end
end end
@ -299,47 +145,88 @@ class HomeworkCommonController < ApplicationController
#开启匿评 #开启匿评
#statue 1:启动成功2启动失败作业总数大于等于2份时才能启动匿评3:已开启匿评,请务重复开启,4:没有开启匿评的权限 #statue 1:启动成功2启动失败作业总数大于等于2份时才能启动匿评3:已开启匿评,请务重复开启,4:没有开启匿评的权限
def start_anonymous_comment def start_anonymous_comment
@statue =4 and return unless User.current.admin? || User.current.allowed_to?(:as_teacher,@course) @statue = 4 and return unless User.current.admin? || User.current.allowed_to?(:as_teacher,@course)
@statue = 5 and return if Time.parse(@homework.end_time.to_s).strftime("%Y-%m-%d") >= Time.now.strftime("%Y-%m-%d") @statue = 5 and return if Time.parse(@homework.end_time.to_s).strftime("%Y-%m-%d") >= Time.now.strftime("%Y-%m-%d")
if @homework_detail_manual.comment_status == 1 if @homework_detail_manual.comment_status == 1
student_works = @homework.student_works student_works = @homework.student_works
if student_works && student_works.size >=2 if student_works && student_works.size >= 2
student_works.each_with_index do |work, index| if @homework.homework_type == 3
user = work.user student_work_projects = @homework.student_work_projects.where("student_work_id is not null")
n = @homework_detail_manual.evaluation_num student_work_projects.each_with_index do |pro_work, pro_index|
n = n < student_works.size ? n : student_works.size - 1 n = @homework_detail_manual.evaluation_num
assigned_homeworks = get_assigned_homeworks(student_works, n, index) n = n < student_works.size ? n : student_works.size - 1
assigned_homeworks.each do |h| work_index = -1
student_works_evaluation_distributions = StudentWorksEvaluationDistribution.new(user_id: user.id, student_work_id: h.id) student_works.each_with_index do |stu_work, stu_index|
student_works_evaluation_distributions.save if stu_work.id.to_i == pro_work.student_work_id.to_i
work_index = stu_index
end
end
assigned_homeworks = get_assigned_homeworks(student_works, n, work_index)
assigned_homeworks.each do |h|
student_works_evaluation_distributions = StudentWorksEvaluationDistribution.new(user_id: pro_work.user_id, student_work_id: h.id)
student_works_evaluation_distributions.save
end
end
else
student_works.each_with_index do |work, index|
user = work.user
n = @homework_detail_manual.evaluation_num
n = n < student_works.size ? n : student_works.size - 1
assigned_homeworks = get_assigned_homeworks(student_works, n, index)
assigned_homeworks.each do |h|
student_works_evaluation_distributions = StudentWorksEvaluationDistribution.new(user_id: user.id, student_work_id: h.id)
student_works_evaluation_distributions.save
end
end end
end end
@homework_detail_manual.update_column('comment_status', 2) @homework_detail_manual.update_column('comment_status', 2)
@homework_detail_manual.update_column('evaluation_start', Date.today)
@statue = 1 @statue = 1
# 匿评开启消息邮件通知
send_message_anonymous_comment(@homework, m_status = 2)
Mailer.send_mail_anonymous_comment_open(@homework).deliver
else else
@statue = 2 @statue = 2
end
end
else else
@statue = 3 @statue = 3
end end
@user_activity_id = params[:user_activity_id].to_i
@is_in_course = params[:is_in_course].to_i
@course_activity = params[:course_activity].to_i
end end
#关闭匿评 #关闭匿评
def stop_anonymous_comment def stop_anonymous_comment
@homework_detail_manual.update_column('comment_status', 3) @homework_detail_manual.update_column('comment_status', 3)
@homework_detail_manual.update_column('evaluation_end', Date.today)
#计算缺评扣分
work_ids = "(" + @homework.student_works.map(&:id).join(",") + ")" work_ids = "(" + @homework.student_works.map(&:id).join(",") + ")"
@homework.student_works.each do |student_work| @homework.student_works.each do |student_work|
absence_penalty_count = student_work.user.student_works_evaluation_distributions.where("student_work_id IN #{work_ids}").count - student_work.user.student_works_scores.where("student_work_id IN #{work_ids}").count absence_penalty_count = student_work.user.student_works_evaluation_distributions.where("student_work_id IN #{work_ids}").count - student_work.user.student_works_scores.where("student_work_id IN #{work_ids}").count
student_work.absence_penalty = absence_penalty_count > 0 ? absence_penalty_count * @homework_detail_manual.absence_penalty : 0 student_work.absence_penalty = absence_penalty_count > 0 ? absence_penalty_count * @homework_detail_manual.absence_penalty : 0
student_work.save student_work.save
end end
# 匿评关闭消息邮件通知
send_message_anonymous_comment(@homework, m_status = 3)
Mailer.send_mail_anonymous_comment_close(@homework).deliver
@user_activity_id = params[:user_activity_id].to_i
@is_in_course = params[:is_in_course].to_i
@course_activity = params[:course_activity].to_i
respond_to do |format| respond_to do |format|
format.js format.js
end end
end end
# 开启/关闭匿评消息通知
def send_message_anonymous_comment(homework, m_status )
# status 标记匿评状态 1为关闭 0为开启
course = homework.course
course.members.each do |m|
@homework.course_messages << CourseMessage.new(:user_id => m.user_id, :course_id => course.id, :viewed => false, :status => m_status)
end
end
#提示 #提示
def alert_anonymous_comment def alert_anonymous_comment
@cur_size = 0 @cur_size = 0
@ -353,6 +240,22 @@ class HomeworkCommonController < ApplicationController
@homework.student_works.map { |work| @cur_size += work.student_works_scores.where(:reviewer_role => 3).count} @homework.student_works.map { |work| @cur_size += work.student_works_scores.where(:reviewer_role => 3).count}
end end
@percent = format("%.2f",(@cur_size.to_f / ( @totle_size == 0 ? 1 : @totle_size)) * 100) @percent = format("%.2f",(@cur_size.to_f / ( @totle_size == 0 ? 1 : @totle_size)) * 100)
@user_activity_id = params[:user_activity_id].to_i
@is_in_course = params[:is_in_course].to_i
@course_activity = params[:course_activity].to_i
respond_to do |format|
format.js
end
end
def alert_forbidden_anonymous_comment
if params[:user_activity_id]
@user_activity_id = params[:user_activity_id]
else
@user_activity_id = -1
end
@is_in_course = params[:is_in_course] if params[:is_in_course]
@course_activity = params[:course_activity] if params[:course_Activity]
respond_to do |format| respond_to do |format|
format.js format.js
end end
@ -376,6 +279,47 @@ class HomeworkCommonController < ApplicationController
end end
end end
#启动匿评参数设置
def start_evaluation_set
if params[:user_activity_id]
@user_activity_id = params[:user_activity_id]
else
@user_activity_id = -1
end
@is_in_course = params[:is_in_course]
@course_activity = params[:course_activity].to_i
end
#设置匿评参数
def set_evaluation_attr
if @homework_detail_manual
unless params[:evaluation_start].to_s == @homework_detail_manual.evaluation_start.to_s
@homework_detail_manual.evaluation_start = params[:evaluation_start]
end
unless @homework_detail_manual.evaluation_end.to_s == params[:evaluation_end].to_s
@homework_detail_manual.evaluation_end = params[:evaluation_end]
end
@homework_detail_manual.evaluation_num = params[:evaluation_num]
@homework_detail_manual.save
@user_activity_id = params[:user_activity_id].to_i
@is_in_course = params[:is_in_course].to_i
@course_activity = params[:course_activity].to_i
end
end
#评分设置
def score_rule_set
if params[:user_activity_id]
@user_activity_id = params[:user_activity_id]
else
@user_activity_id = -1
end
@is_in_course = params[:is_in_course]
@course_activity = params[:course_activity].to_i
end
private private
#获取课程 #获取课程
def find_course def find_course
@ -388,6 +332,7 @@ class HomeworkCommonController < ApplicationController
@homework = HomeworkCommon.find params[:id] @homework = HomeworkCommon.find params[:id]
@homework_detail_manual = @homework.homework_detail_manual @homework_detail_manual = @homework.homework_detail_manual
@homework_detail_programing = @homework.homework_detail_programing @homework_detail_programing = @homework.homework_detail_programing
@homework_detail_group = @homework.homework_detail_group
@course = @homework.course @course = @homework.course
rescue rescue
render_404 render_404
@ -399,11 +344,11 @@ class HomeworkCommonController < ApplicationController
#当前用户是不是课程的成员 #当前用户是不是课程的成员
def member_of_course def member_of_course
render_403 unless @course.is_public || User.current.member_of_course?(@course) || User.current.admin? render_403 unless @course.is_public==1 || User.current.member_of_course?(@course) || User.current.admin?
end end
def get_assigned_homeworks(student_works, n, index) def get_assigned_homeworks(student_works, n, index)
student_works += student_works student_works += student_works
student_works[index + 1 .. index + n] student_works[index + 1 .. index + n]
end end
end end

@ -20,11 +20,11 @@ class IssuesController < ApplicationController
default_search_scope :issues default_search_scope :issues
before_filter :authorize1, :only => [:show] before_filter :authorize1, :only => [:show]
before_filter :find_issue, :only => [:show, :edit, :update] before_filter :find_issue, :only => [:show, :edit, :update,:add_journal, :add_journal_in_org]
before_filter :find_issues, :only => [:bulk_edit, :bulk_update, :destroy] before_filter :find_issues, :only => [:bulk_edit, :bulk_update, :destroy]
before_filter :find_project, :only => [:new, :create, :update_form] before_filter :find_project, :only => [:new, :create, :update_form]
#before_filter :authorize, :except => [:index, :show] #before_filter :authorize, :except => [:index, :show]
before_filter :authorize, :except => [:index] before_filter :authorize, :except => [:index,:add_journal, :add_journal_in_org,:delete_journal,:reply,:add_reply]
before_filter :find_optional_project, :only => [:index] before_filter :find_optional_project, :only => [:index]
before_filter :check_for_default_issue_status, :only => [:new, :create] before_filter :check_for_default_issue_status, :only => [:new, :create]
@ -55,6 +55,7 @@ class IssuesController < ApplicationController
helper :timelog helper :timelog
include Redmine::Export::PDF include Redmine::Export::PDF
helper :project_score helper :project_score
include ApplicationHelper
def index def index
retrieve_query retrieve_query
@ -66,27 +67,32 @@ class IssuesController < ApplicationController
if @query.valid? if @query.valid?
case params[:format] case params[:format]
when 'csv', 'pdf' when 'csv', 'pdf'
@limit = 10#Setting.issues_export_limit.to_i @limit = 10#Setting.issues_export_limit.to_i
when 'atom' when 'atom'
@limit = 10#Setting.feeds_limit.to_i @limit = 10#Setting.feeds_limit.to_i
when 'xml', 'json' when 'xml', 'json'
@offset, @limit = api_offset_and_limit({:limit => 10}) @offset, @limit = api_offset_and_limit({:limit => 10})
else else
@limit = 10#per_page_option @limit = 10#per_page_option
end end
@assign_to_id = params[:assigned_to_id] @assign_to_id = params[:assigned_to_id]
@author_id = params[:author_id] @author_id = params[:author_id]
@priority_id = params[:priority_id] @priority_id = params[:priority_id]
@status_id = params[:status_id] @status_id = params[:status_id]
@subject = params[:subject] @subject = params[:subject]
@done_ratio = params[:done_ratio]
@issue_count = @query.issue_count @issue_count = @query.issue_count
@issue_pages = Paginator.new @issue_count, @limit, params['page'] @issue_pages = Paginator.new @issue_count, @limit, params['page']
params[:page] = (params[:page] || 1).to_i + 1 #页码需要加1
@offset ||= @issue_pages.offset @offset ||= @issue_pages.offset
@issues = @query.issues(:include => [:assigned_to, :tracker, :priority, :category, :fixed_version], @issues = @query.issues(:include => [:assigned_to, :tracker, :priority, :category, :fixed_version],
:order => sort_clause, :order => 'issues.updated_on desc',
:offset => @offset, :offset => @offset,
:limit => @limit) :limit => @limit)
if params[:set_filter]
@set_filter = params[:set_filter]
end
@issue_count_by_group = @query.issue_count_by_group @issue_count_by_group = @query.issue_count_by_group
respond_to do |format| respond_to do |format|
format.js format.js
@ -112,7 +118,28 @@ class IssuesController < ApplicationController
end end
def show def show
# 当前用户查看指派给他的缺陷消息,则设置消息为已读
query = ForgeMessage.where("forge_message_type =? and user_id =? and forge_message_id =?", "Issue", User.current, @issue).first
query.update_attribute(:viewed, true) unless query.nil?
# issue 新建的at消息
User.current.at_messages.unviewed('Issue', @issue.id).each {|x| x.viewed!}
# 回复的at消息
@issue.journals.each do |j|
User.current.at_messages.unviewed('Journal', j.id).each {|x| x.viewed!}
end
# 缺陷状态更新
query_journals = @issue.journals
query_journals.each do |query_journal|
query_journal.forge_messages.each do |f|
if User.current.id == f.user_id
f.update_attributes(:viewed => true)
end
end
end
# end
@jour_reply = Journal.new
@journals = @issue.journals.includes(:user, :details).reorder("#{Journal.table_name}.id ASC").all @journals = @issue.journals.includes(:user, :details).reorder("#{Journal.table_name}.id ASC").all
@journals.each_with_index {|j,i| j.indice = i+1} @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.reject!(&:private_notes?) unless User.current.allowed_to?(:view_private_notes, @issue.project)
@ -129,8 +156,9 @@ class IssuesController < ApplicationController
@project_base_tag = (params[:project_id] || @issue.project) ? 'base_projects':'base'#by young @project_base_tag = (params[:project_id] || @issue.project) ? 'base_projects':'base'#by young
@available_watchers = (@issue.project.users.sort + @issue.watcher_users).uniq @available_watchers = (@issue.project.users.sort + @issue.watcher_users).uniq
@journal = Journal.new(:journalized => @issue)
respond_to do |format|`` respond_to do |format|
format.html { format.html {
retrieve_previous_and_next_issue_ids retrieve_previous_and_next_issue_ids
render :template => 'issues/show', :layout => @project_base_tag#by young render :template => 'issues/show', :layout => @project_base_tag#by young
@ -139,7 +167,7 @@ class IssuesController < ApplicationController
format.atom { render :template => 'journals/index', :layout => false, :content_type => 'application/atom+xml' } format.atom { render :template => 'journals/index', :layout => false, :content_type => 'application/atom+xml' }
format.pdf { format.pdf {
pdf = issue_to_pdf(@issue, :journals => @journals) pdf = issue_to_pdf(@issue, :journals => @journals)
send_data(pdf, :type => 'application/pdf', :filename => "#{@project.identifier}-#{@issue.id}.pdf") send_data(pdf, :type => 'application/pdf', :filename => filename_for_content_disposition("#{@project.identifier}-#{@issue.id}.pdf") )
} }
end end
end end
@ -162,7 +190,7 @@ class IssuesController < ApplicationController
respond_to do |format| respond_to do |format|
format.html { format.html {
render_attachment_warning_if_needed(@issue) render_attachment_warning_if_needed(@issue)
flash[:notice] = l(:label_successful_create) #flash[:notice] = l(:label_successful_create)
#flash[:notice] = l(:notice_issue_successful_create, :id => view_context.link_to("#{@issue.subject}", issue_path(@issue), :title => @issue.subject)) #flash[:notice] = l(:notice_issue_successful_create, :id => view_context.link_to("#{@issue.subject}", issue_path(@issue), :title => @issue.subject))
#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 => view_context.link_to("##{@issue.id}", issue_path(@issue), :title => @issue.subject))
if params[:continue] if params[:continue]
@ -193,21 +221,28 @@ class IssuesController < ApplicationController
end end
def update def update
return unless update_issue_from_params if params[:issue_detail]
@issue.save_attachments(params[:attachments] || (params[:issue] && params[:issue][:uploads])) issue = Issue.find(params[:id])
saved = false issue = update_user_issue_detail(issue, params)
begin @saved = update_user_issue_detail(issue, params)
saved = @issue.save_issue_with_child_records(params, @time_entry) return
rescue ActiveRecord::StaleObjectError else
@conflict = true return unless update_issue_from_params
if params[:last_journal_id] @issue.save_attachments(params[:attachments] || (params[:issue] && params[:issue][:uploads]))
@conflict_journals = @issue.journals_after(params[:last_journal_id]).all saved = false
@conflict_journals.reject!(&:private_notes?) unless User.current.allowed_to?(:view_private_notes, @issue.project) begin
@saved = @issue.save_issue_with_child_records(params, @time_entry)
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)
end
end end
end end
if saved
if @saved
#修改界面增加跟踪者 #修改界面增加跟踪者
watcherlist = @issue.watcher_users watcherlist = @issue.watcher_users
select_users = [] select_users = []
@ -236,21 +271,35 @@ class IssuesController < ApplicationController
if reply_id > 0 if reply_id > 0
JournalReply.add_reply(@issue.current_journal.id, reply_id, User.current.id) JournalReply.add_reply(@issue.current_journal.id, reply_id, User.current.id)
end end
flash[:notice] = l(:notice_successful_update) unless @issue.current_journal.new_record? #flash[:notice] = l(:notice_successful_update) unless @issue.current_journal.new_record? 去掉这个notice因为现在更新都是ajax操作
respond_to do |format| respond_to do |format|
format.js
format.html { redirect_to issue_url(@issue.id) } format.html { redirect_to issue_url(@issue.id) }
format.api { render_api_ok } format.api { render_api_ok }
end end
else else
respond_to do |format| respond_to do |format|
format.js
format.html { render :action => 'edit' } format.html { render :action => 'edit' }
format.api { render_validation_errors(@issue) } format.api { render_validation_errors(@issue) }
end end
end end
end end
def update_user_issue_detail(issue, params)
case params[:type]
when "status"
issue.update_attribute(:status_id, params[:status_id])
when "assigned"
issue.update_attribute(:assigned_to_id, params[:assigned_to_id])
when "ratio"
issue.update_attribute(:done_ratio, params[:done_ratio])
when "prior"
issue.update_attribute(:priority_id, params[:priority_id])
end
end
# Updates the issue form when changing the project, status or tracker # Updates the issue form when changing the project, status or tracker
# on issue creation/update # on issue creation/update
def update_form def update_form
@ -310,8 +359,8 @@ class IssuesController < ApplicationController
issue.reload issue.reload
if @copy if @copy
issue = issue.copy({}, issue = issue.copy({},
:attachments => params[:copy_attachments].present?, :attachments => params[:copy_attachments].present?,
:subtasks => params[:copy_subtasks].present? :subtasks => params[:copy_subtasks].present?
) )
end end
journal = issue.init_journal(User.current, params[:notes]) journal = issue.init_journal(User.current, params[:notes])
@ -341,21 +390,21 @@ class IssuesController < ApplicationController
@hours = TimeEntry.sum(:hours, :conditions => ['issue_id IN (?)', @issues]).to_f @hours = TimeEntry.sum(:hours, :conditions => ['issue_id IN (?)', @issues]).to_f
if @hours > 0 if @hours > 0
case params[:todo] case params[:todo]
when 'destroy' when 'destroy'
# nothing to do # nothing to do
when 'nullify' when 'nullify'
TimeEntry.update_all('issue_id = NULL', ['issue_id IN (?)', @issues]) TimeEntry.update_all('issue_id = NULL', ['issue_id IN (?)', @issues])
when 'reassign' when 'reassign'
reassign_to = @project.issues.find_by_id(params[:reassign_to_id]) reassign_to = @project.issues.find_by_id(params[:reassign_to_id])
if reassign_to.nil? if reassign_to.nil?
flash.now[:error] = l(:error_issue_not_found_in_project) flash.now[:error] = l(:error_issue_not_found_in_project)
return return
else
TimeEntry.update_all("issue_id = #{reassign_to.id}", ['issue_id IN (?)', @issues])
end
else else
TimeEntry.update_all("issue_id = #{reassign_to.id}", ['issue_id IN (?)', @issues]) # display the destroy form if it's a user request
end return unless api_request?
else
# display the destroy form if it's a user request
return unless api_request?
end end
end end
@issues.each do |issue| @issues.each do |issue|
@ -371,6 +420,82 @@ class IssuesController < ApplicationController
end end
end end
def add_journal
if User.current.logged?
jour = Journal.new
jour.user_id = User.current.id
jour.notes = params[:notes]
jour.journalized = @issue
jour.save_attachments(params[:attachments])
jour.save
update_user_activity(@issue.class,@issue.id)
update_forge_activity(@issue.class,@issue.id)
@user_activity_id = params[:user_activity_id]
if params[:issue_id]
@issue_id = params[:issue_id]
end
@priorities = IssuePriority.active
respond_to do |format|
format.js
end
end
end
def add_journal_in_org
if User.current.logged?
jour = Journal.new
jour.user_id = User.current.id
jour.notes = params[:notes]
jour.journalized = @issue
jour.save
org_activity = OrgActivity.where("org_act_type='Issue' and org_act_id =#{@issue.id}").first
org_activity.updated_at = jour.created_on
org_activity.save
@user_activity_id = params[:user_activity_id]
respond_to do |format|
format.js
end
end
end
#对某个journ回复,显示回复框
def reply
@issue = Issue.find(params[:id])
@jour = Journal.find(params[:journal_id])
@tempContent = "<blockquote>#{ll(Setting.default_language, :text_user_wrote, @jour.user.realname.blank? ? @jour.user.login: @jour.user.realname)} <br/>#{@jour.notes.html_safe}</blockquote>".html_safe
respond_to do |format|
format.js
end
end
#给issue添加journ。回复内容包含 对某个被回复的journ的内容
def add_reply
if User.current.logged?
jour = Journal.new
jour.user_id = User.current.id
jour.notes = params[:quote]+params[:notes]
@issue = Issue.find params[:id]
jour.journalized = @issue
jour.save
update_user_activity(@issue.class,@issue.id)
update_forge_activity(@issue.class,@issue.id)
respond_to do |format|
format.js
end
end
end
#
def delete_journal
@issue = Issue.find(params[:id])
Journal.destroy(params[:journal_id])
respond_to do |format|
format.js
end
end
private private
def find_project def find_project
@ -411,14 +536,14 @@ class IssuesController < ApplicationController
issue_attributes = params[:issue] issue_attributes = params[:issue]
if issue_attributes && params[:conflict_resolution] if issue_attributes && params[:conflict_resolution]
case params[:conflict_resolution] case params[:conflict_resolution]
when 'overwrite' when 'overwrite'
issue_attributes = issue_attributes.dup issue_attributes = issue_attributes.dup
issue_attributes.delete(:lock_version) issue_attributes.delete(:lock_version)
when 'add_notes' when 'add_notes'
issue_attributes = issue_attributes.slice(:notes) issue_attributes = issue_attributes.slice(:notes)
when 'cancel' when 'cancel'
redirect_to issue_url(@issue) redirect_to issue_url(@issue)
return false return false
end end
end end
@issue.safe_attributes = issue_attributes @issue.safe_attributes = issue_attributes

@ -36,8 +36,7 @@ class JournalsController < ApplicationController
sort_update(@query.sortable_columns) sort_update(@query.sortable_columns)
if @query.valid? if @query.valid?
@journals = @query.journals(:order => "#{Journal.table_name}.created_on DESC", @journals = @query.journals(:order => "#{Journal.table_name}.created_on DESC", :limit => 25)
:limit => 25)
end end
@title = (@project ? @project.name : Setting.app_title) + ": " + (@query.new_record? ? l(:label_changes_details) : @query.name) @title = (@project ? @project.name : Setting.app_title) + ": " + (@query.new_record? ? l(:label_changes_details) : @query.name)
render :layout => false, :content_type => 'application/atom+xml' render :layout => false, :content_type => 'application/atom+xml'
@ -72,9 +71,9 @@ class JournalsController < ApplicationController
end end
# Replaces pre blocks with [...] # Replaces pre blocks with [...]
text = text.to_s.strip.gsub(%r{<pre>((.|\s)*?)</pre>}m, '[...]') text = text.to_s.strip.gsub(%r{<pre>((.|\s)*?)</pre>}m, '[...]')
@content = "> #{ll(Setting.default_language, :text_user_wrote, user)}\n> " @content = "#{ll(Setting.default_language, :text_user_wrote, user)}\n"
@content << text.gsub(/(\r?\n|\r\n?)/, "\n> ") + "\n\n" @content << text.gsub(/(\r?\n|\r\n?)/, "\n ") + "\n"
# @content = "<blockquote style='word-break: break-all;word-wrap: break-word;'>" << @content @content = "<blockquote style='padding-left:0px;margin-left:0px;'>" << @content << "</blockquote>\n\n<br/>"
@id = user.id @id = user.id
rescue ActiveRecord::RecordNotFound rescue ActiveRecord::RecordNotFound
render_404 render_404

@ -81,8 +81,12 @@ class MembersController < ApplicationController
user_ids.each do |user_id| user_ids.each do |user_id|
members << Member.new(:role_ids => params[:membership][:role_ids], :user_id => user_id) members << Member.new(:role_ids => params[:membership][:role_ids], :user_id => user_id)
user_grades << UserGrade.new(:user_id => user_id, :project_id => @project.id) user_grades << UserGrade.new(:user_id => user_id, :project_id => @project.id)
## added by nie
#给新成员发送加入项目的消息发送者id放在ForgeMessage的forge_message_id字段中
#forge_message_type设置为JoinProject
forge_join = ForgeMessage.new(:user_id =>user_id, :forge_message_id=>User.current.id,:project_id => @project.id,:forge_message_type=>"JoinProject", :viewed => false)
forge_join.save
## added by nie
if (params[:membership][:role_ids]) if (params[:membership][:role_ids])
role = Role.find(params[:membership][:role_ids][0]) role = Role.find(params[:membership][:role_ids][0])
project_info << ProjectInfo.new(:user_id => user_id, :project_id => @project.id) if role.allowed_to?(:is_manager) project_info << ProjectInfo.new(:user_id => user_id, :project_id => @project.id) if role.allowed_to?(:is_manager)
@ -155,6 +159,14 @@ class MembersController < ApplicationController
if role && (role.name == "学生" || role.name == "Student") if role && (role.name == "学生" || role.name == "Student")
StudentsForCourse.create(:student_id => user_id, :course_id =>@course.id) StudentsForCourse.create(:student_id => user_id, :course_id =>@course.id)
end end
#给新成员和老师发送加入课程的消息发送者id放在CourseMessage的course_message_id字段中
#course_message_type设置为JoinCourse
#status = 0 表示给学生发status = 1表示给老师发
course_join = CourseMessage.new(:user_id =>user_id, :course_message_id=>User.current.id,:course_id => @course.id,:course_message_type=>"JoinCourse", :content => role, :viewed => false, :status => 0)
course_join.save
CourseMessage.create(:user_id => User.current.id, :course_message_id => user_id, :course_id => @course.id, :course_message_type => "JoinCourse",:content => role, :viewed => false, :status => 1)
members << member members << member
#user_grades << UserGrade.new(:user_id => user_id, :course_id => @course.id) #user_grades << UserGrade.new(:user_id => user_id, :course_id => @course.id)
if (params[:membership][:role_ids]) if (params[:membership][:role_ids])
@ -301,6 +313,8 @@ class MembersController < ApplicationController
grade.destroy grade.destroy
end end
end end
#移出项目发送消息
ForgeMessage.create(:user_id => @member.user_id, :project_id => @project.id, :forge_message_type => "RemoveFromProject", :viewed => false, :forge_message_id => User.current.id)
end end
respond_to do |format| respond_to do |format|
format.html { redirect_to_settings_in_projects } format.html { redirect_to_settings_in_projects }
@ -328,6 +342,8 @@ class MembersController < ApplicationController
end end
@roles = Role.givable.all[3..5] @roles = Role.givable.all[3..5]
@members = @course.member_principals.includes(:roles, :principal).all.sort @members = @course.member_principals.includes(:roles, :principal).all.sort
#移出课程发送消息
CourseMessage.create(:user_id => @member.user_id, :course_id => @course.id, :course_message_type => "RemoveFromCourse", :viewed => false, :course_message_id => User.current.id)
end end
respond_to do |format| respond_to do |format|
format.html { redirect_to_settings_in_courses } format.html { redirect_to_settings_in_courses }

@ -11,7 +11,7 @@ class MemosController < ApplicationController
include AttachmentsHelper include AttachmentsHelper
include ApplicationHelper include ApplicationHelper
layout 'base_memos' # layout 'base_memos'
def quote def quote
@subject = @memo.subject @subject = @memo.subject
@ -73,41 +73,15 @@ class MemosController < ApplicationController
end end
end end
#end #end
format.html { redirect_to back_memo_url, notice: "#{l :label_memo_create_succ}" } format.js
format.json { render json: @memo, status: :created, location: @memo } format.html { redirect_to back_memo_url, notice: "#{l :label_memo_create_succ}" }
format.json { render json: @memo, status: :created, location: @memo }
else else
flash.now[:error] = "#{l :label_memo_create_fail}: #{@memo.errors.full_messages[0]}" flash.now[:error] = "#{l :label_memo_create_fail}: #{@memo.errors.full_messages[0]}"
# back_error_page = @memo.parent_id.nil? ? forum_path(@forum) : forum_memo_path(@forum, @memo.parent_id) format.js
pre_count = REPLIES_PER_PAGE format.html { redirect_to( forum_path(Forum.find(params[:forum_id]),:errors=>@memo.errors.full_messages[0])) }
@memo_new = @memo.dup
@memo = @memo.root # 取出楼主防止输入帖子id让回复作为主贴显示
unless @memo.new_record?
@memo.update_column(:viewed_count, (@memo.viewed_count.to_i + 1))
end
page = params[:page]
if params[:r] && page.nil?
offset = @memo.children.where("#{Memo.table_name}.id < ?", params[:r].to_i).count
page = 1 + offset / pre_count
else
end
@reply_count = @memo.children.count
@reply_pages = Paginator.new @reply_count, pre_count, page
@replies = @memo.children.
includes(:author, :attachments).
reorder("#{Memo.table_name}.created_at DESC").
limit(@reply_pages.per_page).
offset(@reply_pages.offset).
all
if @memo.new_record?
format.html { render :new,:layout=>'base'}
else
format.html { render action: :show }
format.json { render json: @memo.errors, status: :unprocessable_entity } format.json { render json: @memo.errors, status: :unprocessable_entity }
end #end
end end
end end
@ -115,8 +89,25 @@ class MemosController < ApplicationController
REPLIES_PER_PAGE = 20 unless const_defined?(:REPLIES_PER_PAGE) REPLIES_PER_PAGE = 20 unless const_defined?(:REPLIES_PER_PAGE)
def show def show
pre_count = REPLIES_PER_PAGE
# 更新贴吧帖子留言对应的memo_messages的viewed字段
unless @memo.children.blank?
@memo.children.each do |child|
child.memo_messages.each do |memo_message|
if User.current.id == memo_message.user_id
memo_message.update_attributes(:viewed => true)
end
end
end
end
query_memo_messages = @memo.memo_messages
query_memo_messages.each do |query_memo_message|
if User.current.id == query_memo_message.user_id
query_memo_message.update_attributes(:viewed => true)
end
end
pre_count = REPLIES_PER_PAGE
@memo = @memo.root # 取出楼主防止输入帖子id让回复作为主贴显示 @memo = @memo.root # 取出楼主防止输入帖子id让回复作为主贴显示
@memo.update_column(:viewed_count, (@memo.viewed_count.to_i + 1)) @memo.update_column(:viewed_count, (@memo.viewed_count.to_i + 1))
@ -138,34 +129,45 @@ class MemosController < ApplicationController
@memo_new = Memo.new @memo_new = Memo.new
@my_topic_count = Memo.where("forum_id = #{@memo.forum_id} and author_id = #{User.current.id} and parent_id is null").count
@my_replies_count = Memo.where("forum_id = #{@memo.forum_id} and author_id = #{User.current.id} and parent_id is not null").count
# @memo = Memo.find_by_id(params[:id]) # @memo = Memo.find_by_id(params[:id])
# @forum = Forum.find(params[:forum_id]) # @forum = Forum.find(params[:forum_id])
# @replies = @memo.replies # @replies = @memo.replies
# @mome_new = Memo.new # @mome_new = Memo.new
respond_to do |format| respond_to do |format|
format.html # show.html.erb format.html {render :layout=> 'base_forums'}#:layout=> 'base_forums',
format.json { render json: @memo } format.json { render json: @memo }
format.xml { render xml: @memo } format.xml { render xml: @memo }
end end
end end
def edit def edit
@my_topic_count = Memo.where("forum_id = #{@memo.forum_id} and author_id = #{User.current.id} and parent_id is null").count
@my_replies_count = Memo.where("forum_id = #{@memo.forum_id} and author_id = #{User.current.id} and parent_id is not null").count
@replying = false @replying = false
respond_to do |format|
format.html {render :layout=>'base_forums'}
end
end end
def update def update
@flag = false
respond_to do |format| respond_to do |format|
if( #@memo.update_column(:subject, params[:memo][:subject]) && if( #@memo.update_column(:subject, params[:memo][:subject]) &&
@memo.update_column(:content, params[:memo][:content]) && @memo.update_column(:content, params[:memo][:content]) &&
@memo.update_column(:sticky, params[:memo][:sticky]) && @memo.update_column(:sticky, params[:memo][:sticky]) &&
@memo.update_column(:lock, params[:memo][:lock])) @memo.update_column(:lock, params[:memo][:lock]) &&
@memo.update_column(:subject,params[:memo][:subject]) &&
@memo.update_column(:updated_at,Time.now))
@memo.save_attachments(params[:attachments] || (params[:memo] && params[:memo][:uploads])) @memo.save_attachments(params[:attachments] || (params[:memo] && params[:memo][:uploads]))
@memo.save @flag = @memo.save
# @memo.root.update_attribute(:updated_at, @memo.updated_at) # @memo.root.update_attribute(:updated_at, @memo.updated_at)
format.js
format.html {redirect_to back_memo_url, notice: "#{l :label_memo_create_succ}"} format.html {redirect_to back_memo_url, notice: "#{l :label_memo_create_succ}"}
else else
format.js
format.html { render action: "edit" } format.html { render action: "edit" }
format.json { render json: @person.errors, status: :unprocessable_entity } format.json { render json: @person.errors, status: :unprocessable_entity }
end end
@ -211,7 +213,7 @@ class MemosController < ApplicationController
end end
def back_memo_url def back_memo_url
forum_memo_path(@forum, (@memo.parent_id.nil? ? @memo : @memo.parent_id)) forum_memo_path(@forum, (@memo.root.nil? ? @memo : @memo.root))
end end
def back_memo_or_forum_url def back_memo_or_forum_url

@ -22,8 +22,8 @@ class MessagesController < ApplicationController
default_search_scope :messages default_search_scope :messages
before_filter :find_board, :only => [:new, :preview,:edit] before_filter :find_board, :only => [:new, :preview,:edit]
before_filter :find_attachments, :only => [:preview] before_filter :find_attachments, :only => [:preview]
before_filter :find_message, :except => [:new, :preview] before_filter :find_message, :except => [:new, :preview, :join_org_subfield, :get_subfield_on_click_org, :join_org_subfields]
before_filter :authorize, :except => [:preview, :edit, :destroy, :new] before_filter :authorize, :except => [:preview, :edit, :destroy, :new,:join_org_subfield, :get_subfield_on_click_org, :join_org_subfields]
helper :boards helper :boards
helper :watchers helper :watchers
@ -37,6 +37,7 @@ class MessagesController < ApplicationController
# Show a topic and its replies # Show a topic and its replies
def show def show
=begin
if @course if @course
topic_id = params[:r]?params[:r]:params[:id] topic_id = params[:r]?params[:r]:params[:id]
parent_id = params[:id] parent_id = params[:id]
@ -44,6 +45,7 @@ class MessagesController < ApplicationController
redirect_to url redirect_to url
return; return;
end end
=end
@isReply = true @isReply = true
page = params[:page] page = params[:page]
@ -73,7 +75,7 @@ class MessagesController < ApplicationController
@replies = paginateHelper messages_replies,10 @replies = paginateHelper messages_replies,10
@reply = Message.new(:subject => "RE: #{@message.subject}") @reply = Message.new(:subject => "RE: #{@message.subject}")
render :action => "show", :layout => "base_courses"#by young render :action => "show", :layout => "base_courses"#by young
else elsif @project
@reply_pages = Paginator.new @reply_count, REPLIES_PER_PAGE, page @reply_pages = Paginator.new @reply_count, REPLIES_PER_PAGE, page
@replies = @topic.children. @replies = @topic.children.
includes(:author, :attachments, {:board => :project}). includes(:author, :attachments, {:board => :project}).
@ -84,77 +86,71 @@ class MessagesController < ApplicationController
@reply = Message.new(:subject => "RE: #{@message.subject}") @reply = Message.new(:subject => "RE: #{@message.subject}")
render :action => "show", :layout => "base_projects"#by young render :action => "show", :layout => "base_projects"#by young
else
@reply_pages = Paginator.new @reply_count, REPLIES_PER_PAGE, page
@replies = @topic.children.
includes(:author, :attachments, {:board => :project}).
reorder("#{Message.table_name}.created_on DESC").
limit(@reply_pages.per_page).
offset(@reply_pages.offset).
all
@reply = Message.new(:subject => "RE: #{@message.subject}")
@organization = @org_subfield.organization
render :action => "show", :layout => "base_org"#by young
end end
end end
# Create a new topic # Create a new topic
def new def new
@message = Message.new if User.current.logged?
@message.author = User.current @message = Message.new
@message.board = @board @message.author = User.current
@message.safe_attributes = params[:message] @message.board = @board
if request.post? @message.safe_attributes = params[:message]
@message.save_attachments(params[:attachments]) if request.post?
if @message.save @message.save_attachments(params[:attachments])
# 更新kindeditor上传的图片资源所有者 if @message.save
if params[:asset_id] # 更新kindeditor上传的图片资源所有者
ids = params[:asset_id].split(',') if params[:asset_id]
update_kindeditor_assets_owner ids,@message.id,OwnerTypeHelper::MESSAGE ids = params[:asset_id].split(',')
end update_kindeditor_assets_owner ids,@message.id,OwnerTypeHelper::MESSAGE
# 与我相关动态的记录add start
if(@board && @board.course) #项目的先不管
teachers = searchTeacherAndAssistant(@board.course)
for teacher in teachers
if(teacher.user_id != User.current.id)
notify = ActivityNotify.new()
if(@board.course)
notify.activity_container_id = @board.course_id
notify.activity_container_type = 'Course'
else
notify.activity_container_id = @board.project_id
notify.activity_container_type = 'Project'
end
notify.activity_id = @message.id
notify.activity_type = 'Message'
notify.notify_to = teacher.user_id
notify.is_read = 0
notify.save()
end
end end
end
# 与我相关动态的记录add end
call_hook(:controller_messages_new_after_save, { :params => params, :message => @message}) call_hook(:controller_messages_new_after_save, { :params => params, :message => @message})
render_attachment_warning_if_needed(@message) render_attachment_warning_if_needed(@message)
if params[:is_board] if params[:is_board]
if @project if @project
redirect_to project_boards_path(@project) redirect_to project_boards_path(@project)
elsif @course elsif @course
redirect_to course_boards_path(@course) redirect_to course_boards_path(@course)
end
else
redirect_to board_message_url(@board, @message)
end end
else else
redirect_to board_message_url(@board, @message) if params[:is_board]
if @project
redirect_to project_boards_path(@project, :flag => true)
elsif @course
redirect_to course_boards_path(@course, :flag => true)
end
else
layout_file = @project ? 'base_projects' : 'base_courses'
render :action => 'new', :layout => layout_file
end
end end
else else
if params[:is_board] respond_to do |format|
if @project format.html {
redirect_to project_boards_path(@project, :flag => true) layout_file = @project ? 'base_projects' : 'base_courses'
elsif @course render :layout => layout_file
redirect_to course_boards_path(@course, :flag => true) }
end
else
layout_file = @project ? 'base_projects' : 'base_courses'
render :action => 'new', :layout => layout_file
end end
end end
else else
respond_to do |format| redirect_to signin_path
format.html {
layout_file = @project ? 'base_projects' : 'base_courses'
render :layout => layout_file
}
end
end end
end end
@ -177,7 +173,14 @@ class MessagesController < ApplicationController
@reply.board = @board @reply.board = @board
@reply.safe_attributes = params[:reply] @reply.safe_attributes = params[:reply]
@reply.content = @quote + @reply.content @reply.content = @quote + @reply.content
@reply.subject = "RE: #{@topic.subject}" unless params[:reply][:subject]
# @reply.reply_id = params[:id]
@topic.children << @reply @topic.children << @reply
update_course_activity(@topic.class,@topic.id)
update_user_activity(@topic.class,@topic.id)
update_forge_activity(@topic.class,@topic.id)
update_org_activity(@topic.class,@topic.id)
#@topic.update_attribute(:updated_on, Time.now) #@topic.update_attribute(:updated_on, Time.now)
if !@reply.new_record? if !@reply.new_record?
if params[:asset_id] if params[:asset_id]
@ -185,41 +188,20 @@ class MessagesController < ApplicationController
update_kindeditor_assets_owner ids,@reply.id,OwnerTypeHelper::MESSAGE update_kindeditor_assets_owner ids,@reply.id,OwnerTypeHelper::MESSAGE
end end
# 与我相关动态的记录add start
if(@board && @board.course) #项目的先不管
notifyto_arr = {}
notifyto_arr[@topic.author_id] = @topic.author_id
if( params[:parent_topic] != nil && params[:parent_topic] != '')
parent_topic = Message.find(params[:parent_topic])
notifyto_arr[parent_topic.author_id] = parent_topic.author_id
end
notifyto_arr.each do |k,user_id|
if(user_id != User.current.id)
notify = ActivityNotify.new()
if(@board.course)
notify.activity_container_id = @board.course_id
notify.activity_container_type = 'Course'
else
notify.activity_container_id = @board.project_id
notify.activity_container_type = 'Project'
end
notify.activity_id = @reply.id
notify.activity_type = 'Message'
notify.notify_to = user_id
notify.is_read = 0
notify.save()
end
end
end
# 与我相关动态的记录add end
call_hook(:controller_messages_reply_after_save, { :params => params, :message => @reply}) call_hook(:controller_messages_reply_after_save, { :params => params, :message => @reply})
attachments = Attachment.attach_files(@reply, params[:attachments]) attachments = Attachment.attach_files(@reply, params[:attachments])
render_attachment_warning_if_needed(@reply) render_attachment_warning_if_needed(@reply)
else else
#render file: 'messages#show', layout: 'base_courses' #render file: 'messages#show', layout: 'base_courses'
end end
if params[:is_board] if params[:user_activity_id]
@user_activity_id = params[:user_activity_id]
@is_course = params[:is_course]
@is_board = params[:is_board]
respond_to do |format|
format.js
end
elsif params[:is_board]
if @project if @project
redirect_to project_boards_path(@project) redirect_to project_boards_path(@project)
elsif @course elsif @course
@ -236,39 +218,52 @@ class MessagesController < ApplicationController
@isReply = false @isReply = false
if @project if @project
(render_403; return false) unless @message.editable_by?(User.current) (render_403; return false) unless @message.editable_by?(User.current)
else elsif @course
(render_403; return false) unless @message.course_editable_by?(User.current) (render_403; return false) unless @message.course_editable_by?(User.current)
else
(render_403; return false) unless @message.org_subfield_editable_by?(User.current)
end end
@message.safe_attributes = params[:message] @message.safe_attributes = params[:message]
if request.post? && @message.save if request.post? && @message.save
attachments = Attachment.attach_files(@message, params[:attachments]) attachments = Attachment.attach_files(@message, params[:attachments])
render_attachment_warning_if_needed(@message) render_attachment_warning_if_needed(@message)
flash[:notice] = l(:notice_successful_update) #flash[:notice] = l(:notice_successful_update)
@message.reload @message.reload
if params[:is_board] if params[:is_course] && params[:is_course].to_i == 0
redirect_to user_activities_path(User.current.id)
elsif params[:is_course] && params[:is_course].to_i == 1 && params[:is_board] && params[:is_board].to_i == 0
if @project if @project
redirect_to project_boards_path(@project) redirect_to project_path(@project)
elsif @course elsif @course
redirect_to course_boards_path(@course) redirect_to course_activity_path(@course)
end end
else elsif params[:is_course] && params[:is_course].to_i == 1 && params[:is_board] && params[:is_board].to_i == 1
redirect_to board_message_url(@message.board, @message.root, :r => (@message.parent_id && @message.id))
end
elsif request.get? || request.post?
if params[:is_board]
if @project if @project
redirect_to project_boards_path(@project) redirect_to project_boards_path(@project)
elsif @course elsif @course
redirect_to course_boards_path(@course) redirect_to course_boards_path(@course)
end end
else else
respond_to do |format| redirect_to board_message_url(@message.board, @message.root, :r => (@message.parent_id && @message.id))
format.html { end
layout_file = @project ? 'base_projects' : 'base_courses' elsif request.get? || request.post?
render :layout => layout_file if params[:is_course] && params[:is_board]
} @is_course = params[:is_course]
end @is_board = params[:is_board]
end
respond_to do |format|
format.html {
if @project
layout_file = 'base_projects'
elsif @course
layout_file = 'base_courses'
elsif @org_subfield
@organization = @org_subfield.organization
layout_file = 'base_org'
end
render :layout => layout_file
}
end end
end end
end end
@ -277,26 +272,46 @@ class MessagesController < ApplicationController
def destroy def destroy
if @project if @project
(render_403; return false) unless @message.destroyable_by?(User.current) (render_403; return false) unless @message.destroyable_by?(User.current)
else elsif @course
(render_403; return false) unless @message.course_destroyable_by?(User.current) (render_403; return false) unless @message.course_destroyable_by?(User.current)
else
(render_403; return false) unless @message.org_subfield_editable_by?(User.current)
end end
r = @message.to_param r = @message.to_param
@message.destroy @message.destroy
# modify by nwb # modify by nwb
if @project if @project
if params[:is_board] if params[:is_course] && params[:is_course].to_i == 0
redirect_to project_boards_url(@project) redirect_to user_activities_path(User.current.id)
elsif params[:is_course] && params[:is_course].to_i == 1 && params[:is_board] && params[:is_board].to_i == 0
redirect_to project_path(@project)
elsif params[:is_course] && params[:is_course].to_i == 1 && params[:is_board] && params[:is_board].to_i == 1
redirect_to project_boards_path(@project)
elsif @message.parent
redirect_to board_message_url(@board, @message.parent, :r => r)
else else
redirect_to board_message_url(@board, @topic, :r => @reply) redirect_to project_board_url(@project, @board)
end end
elsif @course elsif @course
if params[:is_course] && params[:is_course].to_i == 0
redirect_to user_activities_path(User.current.id)
elsif params[:is_course] && params[:is_course].to_i == 1 && params[:is_board] && params[:is_board].to_i == 0
redirect_to course_activity_path(@course)
elsif params[:is_course] && params[:is_course].to_i == 1 && params[:is_board] && params[:is_board].to_i == 1
redirect_to course_boards_path(@course)
elsif @message.parent
redirect_to board_message_url(@board, @message.parent, :r => r)
else
redirect_to course_boards_path(@course)
end
elsif @org_subfield
if params[:is_board] if params[:is_board]
redirect_to course_boards_url(@course) redirect_to organization_path(:id => @org_subfield.organization_id, :org_subfield_id => @org_subfield.id)
else else
if @message.parent if @message.parent
redirect_to board_message_url(@board, @message.parent, :r => r) redirect_to board_message_url(@board, @message.parent, :r => r)
else else
redirect_to course_board_url(@course, @board) redirect_to organization_path(:id => @org_subfield.organization_id, :org_subfield_id => @org_subfield.id)
end end
end end
end end
@ -318,6 +333,41 @@ class MessagesController < ApplicationController
render :partial => 'common/preview' render :partial => 'common/preview'
end end
def join_org_subfield
@message = Message.find(params[:message_id])
@organizations = User.current.organizations
end
def get_subfield_on_click_org
@org = Organization.find(params[:organization_id])
end
def join_org_subfields
org_subfield_ids = params[:org_subfields]
@message = Message.find(params[:id])
# @message.update_attribute(:updated_on, Time.now)
# type = @message.board.course_id.nil? ? "Project":"Course"
org_subfield_ids.each do |field_id|
@message.quotes = @message.quotes.nil? ? 1 : (@message.quotes + 1)
@message.save
board = OrgSubfield.find(field_id).boards.first
mes = Message.create(:board_id => board.id, :subject => @message.subject, :content => @message.content, :author_id => User.current.id,
:created_on => Time.now, :updated_on => Time.now, :locked => @message.locked, :sticky => @message.sticky)
@message.attachments.each do |attach|
mes.attachments << Attachment.new(:filename => attach.filename, :disk_filename => attach.disk_filename, :filesize => attach.filesize, :content_type => attach.content_type, :digest => attach.digest,
:downloads => 0, :author_id => User.current.id, :created_on => Time.now, :description => attach.description, :disk_directory => attach.disk_directory, :attachtype => attach.attachtype,
:is_public => attach.is_public, :quotes => 0)
end
# OrgSubfieldMessage.create(:org_subfield_id => field_id.to_i, :message_id => mes.id, :message_type => type)
# org_acts = OrgActivity.where("container_type='OrgSubfield' and container_id=? and org_act_type='Message' and org_act_id=?", field_id.to_i, @message.id)
# if org_acts.all.size() > 0
# org_acts.first.update_attribute(:updated_at, Time.now)
# else
OrgActivity.create(:container_type => 'OrgSubfield', :container_id => field_id.to_i, :org_act_type=>'Message', :org_act_id => mes.id, :user_id => User.current.id)
# end
end
end
private private
def find_message def find_message
return unless find_board return unless find_board
@ -334,6 +384,9 @@ class MessagesController < ApplicationController
@project = @board.project @project = @board.project
elsif @board.course_id elsif @board.course_id
@course = @board.course @course = @board.course
else
@org_subfield = @board.org_subfield
@organization = @org_subfield
end end
rescue ActiveRecord::RecordNotFound rescue ActiveRecord::RecordNotFound

@ -85,7 +85,7 @@ class MyController < ApplicationController
flash[:notice] = l(:notice_mail_notification_updated) flash[:notice] = l(:notice_mail_notification_updated)
redirect_to my_account_url redirect_to my_account_url
else else
redirect_to signin_url redirect_to signin_url
end end
end end
@ -109,16 +109,27 @@ class MyController < ApplicationController
# Edit user's account # Edit user's account
def account def account
@user = User.current @user = User.current
lg=@user.login lg=@user.login
@pref = @user.pref @pref = @user.pref
diskfile = disk_filename('User', @user.id) diskfile = disk_filename('User', @user.id)
diskfile1 = diskfile + 'temp' diskfile1 = diskfile + 'temp'
begin begin
if request.post? if request.post?
# 修改邮箱的时候同步修改到gitlab
if @user.mail != params[:user][:mail]
g = Gitlab.client
begin
g.edit_user(@user.gid, :email => params[:user][:mail])
rescue
logger.error "sync user's email of gitlab failed!"
end
end
@user.safe_attributes = params[:user] @user.safe_attributes = params[:user]
@user.pref.attributes = params[:pref] @user.pref.attributes = params[:pref]
@user.pref[:no_self_notified] = (params[:no_self_notified] == '1') @user.pref[:no_self_notified] = (params[:no_self_notified] == '1')
@user.login = params[:login] #@user.login = params[:login]
unless @user.user_extensions.nil? unless @user.user_extensions.nil?
if @user.user_extensions.identity == 2 if @user.user_extensions.identity == 2
@user.firstname = params[:enterprise_name] @user.firstname = params[:enterprise_name]
@ -126,18 +137,20 @@ class MyController < ApplicationController
end end
@se = @user.extensions @se = @user.extensions
if params[:occupation].to_i.to_s == params[:occupation] # if params[:occupation].to_i.to_s == params[:occupation]
@se.school_id = params[:occupation] # @se.school_id = params[:occupation]
else # else
@se.occupation = params[:occupation] # @se.occupation = params[:occupation]
end # end
@se.school_id = params[:occupation]
@se.gender = params[:gender] @se.gender = params[:gender]
@se.location = params[:province] if params[:province] @se.location = params[:province] if params[:province]
@se.location_city = params[:city] if params[:city] @se.location_city = params[:city] if params[:city]
@se.identity = params[:identity].to_i if params[:identity] @se.identity = params[:identity].to_i if params[:identity]
@se.technical_title = params[:technical_title] if params[:technical_title] @se.technical_title = params[:technical_title] if params[:technical_title]
@se.student_id = params[:no] if params[:no] @se.student_id = params[:no] if params[:no]
@se.brief_introduction = params[:brief_introduction] # @se.brief_introduction = params[:brief_introduction]
@se.description = params[:description] @se.description = params[:description]
if @user.save && @se.save if @user.save && @se.save
@ -157,7 +170,7 @@ class MyController < ApplicationController
File.delete(diskfile1) if File.exist?(diskfile1) File.delete(diskfile1) if File.exist?(diskfile1)
end end
render :layout=>'base_users_new' render :layout=>'new_base_user'
end end
# Destroys user's account # Destroys user's account
@ -174,7 +187,7 @@ class MyController < ApplicationController
logout_user logout_user
flash.now[:notice] = l(:notice_account_deleted) flash.now[:notice] = l(:notice_account_deleted)
end end
redirect_to home_url redirect_to signin_path
end end
end end
@ -210,7 +223,7 @@ class MyController < ApplicationController
end end
flash.now[:error] = l(:notice_account_old_wrong_password) flash.now[:error] = l(:notice_account_old_wrong_password)
end end
render :template => 'my/account',:layout=>'base_users_new' render :template => 'my/account',:layout=>'new_base_user'
end end
# Create a new feeds key # Create a new feeds key

@ -46,15 +46,16 @@ class NewsController < ApplicationController
@course = Course.find(params[:course_id]) @course = Course.find(params[:course_id])
end end
if @project if @project
@page = params[:page] ? params[:page].to_i + 1 : 0
scope = @project ? @project.news.visible : News.visible scope = @project ? @project.news.visible : News.visible
@news_count = scope.count @news_count = scope.count
@news_pages = Paginator.new @news_count, @limit, params['page'] #@news_pages = Paginator.new @news_count, @limit, params['page']
@offset ||= @news_pages.offset #@offset ||= @news_pages.offset
@newss = scope.all(:include => [:author, :project], @newss = scope.all(:include => [:author, :project],
:order => "#{News.table_name}.created_on DESC", :order => "#{News.table_name}.created_on DESC",
:offset => @offset, :offset => @page * 10,
:limit => @limit) :limit => 10)
respond_to do |format| respond_to do |format|
format.html { format.html {
@ -63,26 +64,32 @@ class NewsController < ApplicationController
render :layout => false if request.xhr? render :layout => false if request.xhr?
} }
format.js
format.api format.api
format.atom { render_feed(@newss, :title => (@project ? @project.name : Setting.app_title) + ": #{l(:label_news_plural)}") } format.atom { render_feed(@newss, :title => (@project ? @project.name : Setting.app_title) + ": #{l(:label_news_plural)}") }
end end
elsif @course elsif @course
if (User.current.admin? || @course.is_public == 1 || (@course.is_public == 0 && User.current.member_of_course?(@course))) if (User.current.admin? || @course.is_public == 1 || (@course.is_public == 0 && User.current.member_of_course?(@course)))
scope = @course ? @course.news.course_visible : News.course_visible scope = @course ? @course.news.course_visible : News.course_visible
news_arr = scope.map{|news| news.id}
@page = params[:page] ? params[:page].to_i + 1 : 0
news_page = @page *10
@news_count = scope.count @news_count = scope.count
@is_new = params[:is_new]
@q = params[:subject] @q = params[:subject]
if params[:subject].nil? || params[:subject].blank? if params[:subject].nil? || params[:subject].blank?
scope_order = scope.all(:include => [:author, :course], scope_order = scope.reorder("#{News.table_name}.sticky DESC, #{News.table_name}.created_on DESC").limit(10).offset(news_page).includes(:author,:course).all()
:order => "#{News.table_name}.created_on DESC") #all(:include => [:author, :course],
#:order => "#{News.table_name}.sticky DESC, #{News.table_name}.created_on DESC").limit(10).offset(news_page)
else else
scope_order = scope.where("#{News.table_name}.title like '#{'%' << params[:subject].to_s << '%'}'").all(:include => [:author, :course], scope_order = scope.where("#{News.table_name}.title like '#{'%' << params[:subject].to_s << '%'}'").reorder("#{News.table_name}.sticky DESC, #{News.table_name}.created_on DESC").limit(10).offset(news_page).includes(:author,:course).all()
:order => "#{News.table_name}.created_on DESC") #.all(:include => [:author, :course],:order => "#{News.table_name}.sticky DESC, #{News.table_name}.created_on DESC")
end end
# :offset => @offset, @newss = scope_order
# :limit => @limit) #@newss = paginateHelper scope_order,10
@newss = paginateHelper scope_order,10
respond_to do |format| respond_to do |format|
format.html { format.html {
@news = News.new @news = News.new
@ -99,10 +106,38 @@ class NewsController < ApplicationController
end end
def show def show
# 更新news对应的forge_messages的消息viewed字段
if @project
query_message_news = @news.forge_messages
else
query_message_news = @news.course_messages
end
query_message_news.each do |query|
if User.current.id == query.user_id
query.update_attributes(:viewed => true)
end
end
# 更新项目新闻的评阅的消息viewed字段
current_message_comments = @news.comments
current_message_comments.each do |current_message_comment|
if @project
query_message_comment = current_message_comment.forge_messages
else
query_message_comment = current_message_comment.course_messages
end
query_message_comment.each do |query|
if User.current.id == query.user_id
query.update_attributes(:viewed => true)
end
end
end
# end
cs = CoursesService.new cs = CoursesService.new
result = cs.show_course_news params,User.current result = cs.show_course_news params,User.current
@news = result[:news] @news = result[:news]
@comments = result[:comments] @comments = result[:comments]
@comment = Comment.new
#@comments = @news.comments #@comments = @news.comments
#@comments.reverse! if User.current.wants_comments_in_reverse_order? #@comments.reverse! if User.current.wants_comments_in_reverse_order?
#modify by nwb #modify by nwb
@ -111,6 +146,10 @@ class NewsController < ApplicationController
if @course if @course
render :layout => 'base_courses' render :layout => 'base_courses'
end end
elsif @news.org_subfield_id
@org_subfield = OrgSubfield.find(@news.org_subfield_id)
@organization = @org_subfield.organization
render :layout => 'base_org'
end end
end end
@ -118,9 +157,39 @@ class NewsController < ApplicationController
#modify by nwb #modify by nwb
if @project if @project
@news = News.new(:project => @project, :author => User.current) @news = News.new(:project => @project, :author => User.current)
@news.safe_attributes = params[:news]
@news.save_attachments(params[:attachments])
if @news.save
if params[:asset_id]
ids = params[:asset_id].split(',')
update_kindeditor_assets_owner ids,@news.id,OwnerTypeHelper::NEWS
end
render_attachment_warning_if_needed(@news)
#flash[:notice] = l(:notice_successful_create)
redirect_to project_news_index_url(@project)
else
redirect_to project_news_index_url(@project)
#layout_file = 'base_courses'
#render :action => 'new', :layout => layout_file
end
elsif @course elsif @course
@news = News.new(:course => @course, :author => User.current) @news = News.new(:course => @course, :author => User.current)
render :layout => 'base_courses' #render :layout => 'base_courses'
@news.safe_attributes = params[:news]
@news.save_attachments(params[:attachments])
if @news.save
if params[:asset_id]
ids = params[:asset_id].split(',')
update_kindeditor_assets_owner ids,@news.id,OwnerTypeHelper::NEWS
end
render_attachment_warning_if_needed(@news)
#flash[:notice] = l(:notice_successful_create)
redirect_to course_news_index_url(@course)
else
redirect_to course_news_index_url(@course)
#layout_file = 'base_courses'
#render :action => 'new', :layout => layout_file
end
end end
end end
@ -148,19 +217,19 @@ class NewsController < ApplicationController
update_kindeditor_assets_owner ids,@news.id,OwnerTypeHelper::NEWS update_kindeditor_assets_owner ids,@news.id,OwnerTypeHelper::NEWS
end end
# <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ض<EFBFBD>̬<EFBFBD>ļ<EFBFBD>¼add start # <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ض<EFBFBD>̬<EFBFBD>ļ<EFBFBD>¼add start
teachers = searchTeacherAndAssistant(@course) # teachers = searchTeacherAndAssistant(@course)
for teacher in teachers # for teacher in teachers
if(teacher.user_id != User.current.id) # if(teacher.user_id != User.current.id)
notify = ActivityNotify.new() # notify = ActivityNotify.new()
notify.activity_container_id = @course.id # notify.activity_container_id = @course.id
notify.activity_container_type = 'Course' # notify.activity_container_type = 'Course'
notify.activity_id = @news.id # notify.activity_id = @news.id
notify.activity_type = 'News' # notify.activity_type = 'News'
notify.notify_to = teacher.user_id # notify.notify_to = teacher.user_id
notify.is_read = 0 # notify.is_read = 0
notify.save() # notify.save()
end # end
end # end
# <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ض<EFBFBD>̬<EFBFBD>ļ<EFBFBD>¼add end # <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ض<EFBFBD>̬<EFBFBD>ļ<EFBFBD>¼add end
render_attachment_warning_if_needed(@news) render_attachment_warning_if_needed(@news)
flash[:notice] = l(:notice_successful_create) flash[:notice] = l(:notice_successful_create)
@ -173,8 +242,14 @@ class NewsController < ApplicationController
end end
def edit def edit
if @news.org_subfield_id
@org_subfield = OrgSubfield.find(@news.org_subfield_id)
@organization = @org_subfield.organization
end
if @course if @course
render :layout => "base_courses" render :layout => "base_courses"
elsif @org_subfield
render :layout => 'base_org'
end end
end end
@ -183,7 +258,7 @@ class NewsController < ApplicationController
@news.save_attachments(params[:attachments]) @news.save_attachments(params[:attachments])
if @news.save if @news.save
render_attachment_warning_if_needed(@news) render_attachment_warning_if_needed(@news)
flash[:notice] = l(:notice_successful_update) #flash[:notice] = l(:notice_successful_update)
redirect_to news_url(@news) redirect_to news_url(@news)
else else
#flash[:error] = l(:notice_successful_update) #flash[:error] = l(:notice_successful_update)
@ -192,12 +267,17 @@ class NewsController < ApplicationController
end end
def destroy def destroy
if @news.org_subfield_id
@org_subfield = OrgSubfield.find(@news.org_subfield_id)
end
@news.destroy @news.destroy
# modify by nwb # modify by nwb
if @project if @project
redirect_to project_news_index_url(@project) redirect_to project_news_index_url(@project)
elsif @course elsif @course
redirect_to course_news_index_url(@course) redirect_to course_news_index_url(@course)
elsif @org_subfield
redirect_to organization_path(@org_subfield.organization, :org_subfield_id => @org_subfield.id)
end end
end end

@ -0,0 +1,20 @@
class OrgCoursesController < ApplicationController
def create
org_ids = params[:orgNames]
@course = Course.find(params[:course_id])
org_ids.each do |org_id|
if OrgCourse.where("organization_id =? and course_id =?", org_id.to_i, params[:course_id].to_i).count == 0
OrgCourse.create(:organization_id => org_id.to_i, :course_id => params[:course_id].to_i, :created_at => Time.now)
end
end
respond_to do |format|
format.js
end
end
def destroy
@course = Course.find(params[:course_id])
@org_course = OrgCourse.find(params[:id])
@org_course.destroy
end
end

@ -0,0 +1,174 @@
class OrgDocumentCommentsController < ApplicationController
before_filter :find_organization, :only => [:new, :create, :show, :index]
helper :attachments
layout 'base_org'
def new
@org_document_comment = OrgDocumentComment.new
end
def create
@org_document_comment = OrgDocumentComment.new(:organization_id => @organization.id, :creator_id => User.current.id)
@org_document_comment.title = params[:org_document_comment][:title]
@org_document_comment.content = params[:org_document_comment][:content]
@org_document_comment.save_attachments(params[:attachments])
if params[:field_id]
@org_document_comment.org_subfield_id = params[:field_id].to_i
end
if @org_document_comment.save
flash.keep[:notice] = l(:notice_successful_create)
EditorOfDocument.create(:editor_id => User.current.id, :org_document_comment_id => @org_document_comment.id, :created_at => @org_document_comment.updated_at)
if params[:field_id]
@org_subfield = OrgSubfield.find(params[:field_id])
if @org_subfield.subfield_subdomain_dir.nil?
redirect_to organization_path(@organization, :org_subfield_id => params[:field_id])
else
redirect_to show_org_subfield_organization_path(:id => @organization.id, :sub_dir_name => @org_subfield.subfield_subdomain_dir.name)
end
else
redirect_to organization_org_document_comments_path(@organization)
end
else
redirect_to new_org_document_comment_path(:organization_id => @organization.id)
end
end
def show
@document = OrgDocumentComment.find(params[:id])
end
def index
if @organization.is_public? || User.current.admin? || User.current.member_of_org?(@organization)
@documents = @organization.org_document_comments.where("parent_id is null").order("created_at desc")
else
render_403
end
end
def update
@org_document = OrgDocumentComment.find(params[:id])
@org_document.update_attributes(:title => params[:org_document_comment][:title], :content => params[:org_document_comment][:content])
Attachment.attach_files(@org_document, params[:attachments])
# @org_document.save_attachments(params[:attachments])
if @org_document.parent.nil?
act = OrgActivity.where("org_act_type='OrgDocumentComment' and org_act_id =?", @org_document.id).first
act.update_attributes(:updated_at => @org_document.updated_at)
EditorOfDocument.create(:editor_id => User.current.id, :org_document_comment_id => @org_document.id, :created_at => Time.now)
end
respond_to do |format|
format.html {
if params[:flag].to_i == 0
redirect_to organization_org_document_comments_path(:organization_id => @org_document.organization.id)
else
if params[:flag].to_i == 1
redirect_to org_document_comment_path(@org_document.root.id, :organization_id => @org_document.organization.id)
else
redirect_to organization_path(@org_document.organization.id, :org_subfield_id => params[:org_subfield_id])
end
end
}
end
end
def edit
@org_document = OrgDocumentComment.find(params[:id])
@flag = params[:flag]
@organization = Organization.find(params[:organization_id])
end
def add_reply
@document = OrgDocumentComment.find(params[:id]).root
@act = OrgActivity.find(params[:id])
@comment = OrgDocumentComment.new(:organization_id => @document.organization_id, :creator_id => User.current.id, :reply_id => params[:id])
@comment.content = params[:org_content]
@document.children << @comment
@document.save
end
def add_reply_in_doc
@document = OrgDocumentComment.find(params[:id]).root
@comment = OrgDocumentComment.new(:organization_id => @document.organization_id, :creator_id => User.current.id, :reply_id => params[:id])
@comment.content = params[:org_comment][:org_content]
@document.children << @comment
@document.save
respond_to do |format|
format.html {redirect_to org_document_comment_path(:id => @document.id, :organization_id => @document.organization_id)}
end
end
def find_organization
@organization = Organization.find(params[:organization_id])
end
def destroy
@org_document_comment = OrgDocumentComment.find(params[:id])
org = @org_document_comment.organization
if @org_document_comment.id == org.home_id
org.update_attributes(:home_id => nil)
end
if @org_document_comment.destroy
end
respond_to do |format|
format.js
end
end
def delete_reply
@org_document_comment = OrgDocumentComment.find(params[:id])
@document = @org_document_comment.root
org = @org_document_comment.organization
@org_document_comment.destroy
respond_to do |format|
format.html {redirect_to org_document_comment_path(:id => @document.id, :organization_id => @document.organization_id)}
end
end
def quote
@org_comment = OrgDocumentComment.find(params[:id])
@subject = @org_comment.content
@subject = "RE: #{@subject}" unless @subject.starts_with?('RE:')
@content = "> #{ll(Setting.default_language, :text_user_wrote, User.find(@org_comment.creator_id).realname)}\n> "
@temp = OrgDocumentComment.new
#@course_id = params[:course_id]
@temp.content = "<blockquote>#{ll(Setting.default_language, :text_user_wrote, User.find(@org_comment.creator_id).realname)} <br/>#{@org_comment.content.html_safe}</blockquote>".html_safe
respond_to do | format|
format.js
end
end
def reply
@document = OrgDocumentComment.find(params[:id]).root
@quote = params[:quote][:quote]
@org_document = OrgDocumentComment.new(:creator_id => User.current.id, :reply_id => params[:id])
# params[:blog_comment][:sticky] = params[:blog_comment][:sticky] || 0
# params[:blog_comment][:locked] = params[:blog_comment][:locked] || 0
@org_document.title = params[:org_document_comment][:title]
@org_document.content = params[:org_document_comment][:content]
@org_document.content = @quote + @org_document.content
#@org_document.title = "RE: #{@article.title}" unless params[:blog_comment][:title]
@document.children << @org_document
# @user_activity_id = params[:user_activity_id]
# user_activity = UserActivity.where("act_type='BlogComment' and act_id =#{@article.id}").first
# if user_activity
# user_activity.updated_at = Time.now
# user_activity.save
# end
# attachments = Attachment.attach_files(@org_document, params[:attachments])
# render_attachment_warning_if_needed(@org_document)
#@article.save
# redirect_to user_blogs_path(:user_id=>params[:user_id])
respond_to do |format|
format.html {
# if params[:course_id] #如果呆了course_id过来了那么这是要跳到课程大纲去的
# redirect_to syllabus_course_path(:id=>params[:course_id])
# else
redirect_to org_document_comment_path(:id => @document.id, :organization_id => @document.organization_id)
# end
}
format.js
end
end
end

@ -0,0 +1,57 @@
class OrgMemberController < ApplicationController
def org_member_autocomplete
@org = Organization.find(params[:org])
@flag = params[:flag] || false
respond_to do |format|
format.js
end
end
def create
@org = Organization.find(params[:org])
if params[:membership].nil?
@fail_hint = l(:label_blank_user_lists_for_org)
else
member_ids = params[:membership][:user_ids]
role_id = params[:orgRole]
member_ids.each do |user_id|
member = OrgMember.create(:user_id=>user_id, :created_at => Time.now)
@org.org_members << member
OrgMemberRole.create(:org_member_id => member.id, :role_id => role_id)
end
end
respond_to do |format|
format.js
end
end
def update
@member = OrgMember.find(params[:id])
#@member.change_role params[:org_member][:role_ids]
@member_role = @member.org_member_roles[0]
@member_role.role_id = params[:org_member][:role_ids][0]
@member_role.save
@org = @member.organization
respond_to do |format|
format.js
end
end
def new
end
def destroy
member = OrgMember.find(params[:id])
@org = member.organization
member.destroy
respond_to do |format|
format.js
end
end
def index
end
end

@ -0,0 +1,19 @@
class OrgProjectsController < ApplicationController
def create
org_ids = params[:orgNames]
@project = Project.find(params[:project_id])
org_ids.each do |org_id|
if OrgProject.where("organization_id =? and project_id =?", org_id.to_i, @project.id).count == 0
OrgProject.create(:organization_id => org_id.to_i, :project_id => params[:project_id].to_i, :created_at => Time.now)
end
end
respond_to do |format|
format.js
end
end
def destroy
@project = Project.find(params[:project_id])
@org_project = OrgProject.find(params[:id])
@org_project.destroy
end
end

@ -0,0 +1,145 @@
class OrgSubfieldsController < ApplicationController
helper :attachments
include FilesHelper
layout 'base_org'
def create
if OrgSubfield.where("organization_id=#{params[:organization_id]} and name=?",params[:name]).count == 0
@res = true
@subfield = OrgSubfield.create(:name => params[:name])
@organization = Organization.find(params[:organization_id])
@organization.org_subfields << @subfield
if !params[:sub_dir].blank?
sql = "select subfield_subdomain_dirs.* from subfield_subdomain_dirs, org_subfields where subfield_subdomain_dirs.org_subfield_id = org_subfields.id "+
"and org_subfields.organization_id=#{@organization.id} and subfield_subdomain_dirs.name='#{params[:sub_dir]}'"
if SubfieldSubdomainDir.find_by_sql(sql).count == 0
SubfieldSubdomainDir.create(:org_subfield_id => @subfield.id, :name => params[:sub_dir])
end
end
@subfield.update_attributes(:priority => @subfield.id, :field_type => params[:field_type])
else
@res = false
end
end
def show
@flag = params[:flag] || false
sort = ""
@sort = ""
@order = ""
@is_remote = false
if params[:id]
@organization = Organization.find(params[:id])
else
@organization = Organization.where("domain=?",request.subdomain).first
end
@org_subfield = OrgSubfield.find_by_sql("select distinct org_subfields.* from org_subfields,"+
"subfield_subdomain_dirs where org_subfields.id = subfield_subdomain_dirs.org_subfield_id and "+
" org_subfields.organization_id=#{@organization.id} and subfield_subdomain_dirs.name='#{params[:sub_dir_name]}'").first
if @org_subfield.field_type == 'Post'
@org_subfield_ids = @org_subfield.org_document_comments.map(&:id) << 0
@org_activities = OrgActivity.where("(org_act_type='OrgDocumentComment'and org_act_id in (#{@org_subfield_ids.join(",")})) || (container_type='OrgSubfield' and container_id=#{@org_subfield.id})").order('updated_at desc').page(params[:page] || 1).per(10)
#redirect_to organization_path(@organization, :org_subfield_id => @org_subfield.id)
else
if params[:sort]
params[:sort].split(",").each do |sort_type|
order_by = sort_type.split(":")
case order_by[0]
when "filename"
attribute = "filename"
when "size"
attribute = "filesize"
when "attach_type"
attribute = "attachtype"
when "content_type"
attribute = "created_on"
when "field_file_dense"
attribute = "is_public"
when "downloads"
attribute = "downloads"
when "created_on"
attribute = "created_on"
when "quotes"
attribute = "quotes"
else
attribute = "created_on"
end
@sort = order_by[0]
@order = order_by[1]
if order_by.count == 1 && attribute
sort += "#{Attachment.table_name}.#{attribute} asc "
if sort_type != params[:sort].split(",").last
sort += ","
end
elsif order_by.count == 2 && order_by[1]
sort += "#{Attachment.table_name}.#{attribute} #{order_by[1]} "
if sort_type != params[:sort].split(",").last
sort += ","
end
end
end
else
sort = "#{Attachment.table_name}.created_on desc"
end
@container_type = 2
@containers = [ OrgSubfield.includes(:attachments).reorder(sort).find(@org_subfield.id)]
@organization = Organization.find(@containers.first.organization_id)
show_attachments @containers
@tag_list = attachment_tag_list @all_attachments
end
@page = params[:page] || 1
#render :layout => 'base_org'
end
def destroy
@subfield = OrgSubfield.find(params[:id])
@organization = Organization.find(@subfield.organization_id)
@subfield.destroy
end
def update
@subfield = OrgSubfield.find(params[:id])
@organization = Organization.find(@subfield.organization_id)
@subfield.update_attributes(:name => params[:name])
end
def update_sub_dir
@org_subfield = OrgSubfield.find(params[:id])
sql = "select subfield_subdomain_dirs.* from subfield_subdomain_dirs, org_subfields where subfield_subdomain_dirs.org_subfield_id = org_subfields.id "+
"and org_subfields.organization_id=#{@org_subfield.organization.id} and subfield_subdomain_dirs.name='#{params[:sub_dir_name]}'"
if SubfieldSubdomainDir.find_by_sql(sql).count == 0
if @org_subfield.subfield_subdomain_dir
@sub_dir = @org_subfield.subfield_subdomain_dir
@sub_dir = SubfieldSubdomainDir.update(@sub_dir.id, :name => params[:sub_dir_name])
#@sub_dir.update_attribute(:name, params[:sub_dir_name])
else
@sub_dir = SubfieldSubdomainDir.create(:org_subfield_id => @org_subfield.id, :name => params[:sub_dir_name])
end
@exist = false
else
@exist = true
end
end
def show_attachments obj
@attachments = []
obj.each do |container|
@attachments += container.attachments
end
@all_attachments = User.current.admin? ? @attachments : visable_attachemnts(@attachments)
@limit = 10
@feedback_count = @all_attachments.count
@feedback_pages = Paginator.new @feedback_count, @limit, params['page']
@offset ||= @feedback_pages.offset
#@curse_attachments_all = @all_attachments[@offset, @limit]
@obj_attachments = paginateHelper @all_attachments,10
end
#获取指定资源列表的TAG的集合以及每个TAG的数量降序排序
def attachment_tag_list attachments
tag_list = Hash.new
attachments.each do |attachment|
attachment.tag_list.map{|tag| tag_list.has_key?(tag) ? tag_list[tag] = tag_list[tag] + 1 : tag_list[tag] = 1}
end
tag_list.sort {|a,b| b[1]<=>a[1]}
end
end

@ -1,55 +0,0 @@
class OrganizationController < ApplicationController
# layout 'base_projects'
before_filter :require_admin, :except => [:index]
def index
#@projects = Project.find_by_sql("SELECT * FROM projects WHERE id IN (select MAX(id) from projects GROUP BY enterprise_name)")
@organizations = Organization.all
respond_to do |format|
format.html
end
end
def new
@organizations = Organization.new
respond_to do |format|
format.html
end
end
def create
@organizations = Organization.new
@organizations.name = params[:organization][:name]
if @organizations.save
redirect_to admin_organization_url
end
end
def edit
@organization = Organization.find params[:id]
respond_to do |format|
format.html
end
rescue Exception => e
render_404
end
def update
@organization = Organization.find params[:id]
@organization.name = params[:organization][:name]
if @organization.save
redirect_to admin_organization_url
end
rescue Exception => e
render_404
end
def destroy
@organization = Organization.find params[:id]
if @organization.destroy
redirect_to admin_organization_url
end
rescue Exception => e
render_404
end
end

@ -0,0 +1,330 @@
# encoding: utf-8
class OrganizationsController < ApplicationController
helper :sort
include SortHelper
helper :custom_fields
include CustomFieldsHelper
include AvatarHelper
include WordsHelper
include GitlabHelper
include UserScoreHelper
include PollHelper
helper :user_score
helper :journals
helper :attachments
# added by liuping 关注
helper :watchers
helper :activities
### added by william
include ActsAsTaggableOn::TagsHelper
# fq
helper :words
helper :project_score
helper :issues
include UsersHelper
before_filter :find_organization, :only => [:show, :members, :apply_subdomain]
layout 'base_org'
def index
end
def new
@organization = Organization.new
render :layout => 'new_base'
end
def edit
@organization = Organization.find(params[:id])
end
def destroy
@organization = Organization.find(params[:id])
@organization.destroy
respond_to do |format|
format.html{ redirect_to admin_organization_path }
end
end
def create
@organization = Organization.new
@organization.name = params[:organization][:name]
@organization.description = params[:organization][:description]
@organization.is_public = params[:organization][:is_public]
@organization.allow_guest_download = params[:organization][:allow_guest_download] == '1' ? 1 : 0
@organization.creator_id = User.current.id
member = OrgMember.new(:user_id => User.current.id)
@organization.org_members << member
if @organization.save
OrgMemberRole.create(:org_member_id => member.id, :role_id => 11)
redirect_to organization_path(@organization)
end
end
def show
if @organization.is_public? || User.current.admin? || User.current.member_of_org?(@organization)
@organization = Organization.find(params[:id])
if params[:org_subfield_id]
@org_subfield = OrgSubfield.find(params[:org_subfield_id])
@org_subfield_ids = @org_subfield.org_document_comments.map(&:id) << 0
@org_activities = OrgActivity.where("(org_act_type='OrgDocumentComment'and org_act_id in (#{@org_subfield_ids.join(",")})) || (container_type='OrgSubfield' and container_id=#{@org_subfield.id})").order('updated_at desc').page(params[:page] || 1).per(10)
else
shield_project_ids = ShieldActivity.where("container_type='Organization' and container_id=#{@organization.id} and shield_type='Project'").map(&:shield_id)
shield_course_ids = ShieldActivity.where("container_type='Organization' and container_id=#{@organization.id} and shield_type='Course'").map(&:shield_id)
project_ids = (@organization.projects.map(&:id)-shield_project_ids) << 0
course_ids = (@organization.courses.map(&:id)-shield_course_ids) << 0
course_types = "('Message','News','HomeworkCommon','Poll','Course')"
case params[:type]
when nil
@org_activities = OrgActivity.where("(container_id =? and container_type =?) " +
"or (container_type ='Project' and org_act_type in ('Issue','Message','ProjectCreateInfo') and container_id in (#{project_ids.join(',')})) "+
"or (container_type ='Course' and org_act_type in #{course_types} and container_id in (#{course_ids.join(',')}))",
@organization.id, 'Organization').order('updated_at desc').page(params[:page] || 1).per(10)
when 'project_issue'
@org_activities = OrgActivity.where("container_type = 'Project' and org_act_type = 'Issue' and container_id in (#{project_ids.join(',')})").order('updated_at desc').page(params[:page] || 1).per(10)
when 'project_message'
@org_activities = OrgActivity.where("container_type = 'Project' and org_act_type = 'Message' and container_id in (#{project_ids.join(',')})").order('updated_at desc').page(params[:page] || 1).per(10)
when 'org'
@org_activities = OrgActivity.where("container_id =? and container_type =?",@organization.id, 'Organization').order('updated_at desc').page(params[:page] || 1).per(10)
when 'course_homework'
@org_activities = OrgActivity.where("container_type = 'Course' and org_act_type = 'HomeworkCommon' and container_id in (#{course_ids.join(',')})").order('updated_at desc').page(params[:page] || 1).per(10)
when 'course_news'
@org_activities = OrgActivity.where("container_type = 'Course' and org_act_type = 'News' and container_id in (#{course_ids.join(',')})").order('updated_at desc').page(params[:page] || 1).per(10)
when 'course_message'
@org_activities = OrgActivity.where("container_type = 'Course' and org_act_type = 'Message' and container_id in (#{course_ids.join(',')})").order('updated_at desc').page(params[:page] || 1).per(10)
when 'course_poll'
@org_activities = OrgActivity.where("container_type = 'Course' and org_act_type = 'Poll' and container_id in (#{course_ids.join(',')})").order('updated_at desc').page(params[:page] || 1).per(10)
end
end
@page = params[:page] ? params[:page].to_i : 1
respond_to do |format|
format.html
format.js
end
else
render_403
end
end
def update
@organization = Organization.find(params[:id])
@organization.name = params[:organization][:name]
@organization.description = params[:organization][:description]
# @organization.domain = params[:organization][:domain]
@organization.is_public = params[:organization][:is_public] == 'on' ? 1 : 0
@organization.allow_guest_download = params[:organization][:allow_guest_download] == 'on' ? 1 : 0
#@organization.name = params[:organization][:name]
@organization.save
respond_to do |format|
format.html { redirect_to setting_organization_path(@organization)}
end
end
def check_uniq
@check = false;
@org_name = params[:org_name].strip
@config_page = params[:config_page]
sameName = @config_page ? Organization.where('name = ? and id != ?',params[:org_name],params[:org_id].to_i).count == 0 : Organization.where('name = ?',params[:org_name]).count == 0
if sameName == true
@check = true
end
respond_to do |format|
format.js
end
end
def check_uniq_domain
@is_exist = (Organization.where("domain=?", params[:org_domain]).count > 0)
end
def find_organization
@organization = Organization.find(params[:id])
end
def setting
@organization = Organization.find(params[:id])
if User.current.admin? || User.current.admin_of_org?(@organization)
else
render_403
end
end
def clear_org_avatar_temp
end
def set_homepage
@org = Organization.find(params[:id])
@org.home_id = params[:home_id]
@org.save
# respond_to do |format|
# format.html {redirect_to organization_path(org)}
# end
end
def cancel_homepage
@org = Organization.find(params[:id])
@org.home_id = nil
@org.save
end
def autocomplete_search
@project = Project.find(params[:project_id])
#@flag = params[:flag] || false
respond_to do |format|
format.js
end
end
def members
if @organization.is_public? || User.current.admin? || User.current.member_of_org?(@organization)
@members = OrgMember.where("organization_id =?", @organization.id)
else
render_403
end
end
def more_org_projects
@organization = Organization.find params[:id]
@page = params[:page]
@org_projects = @organization.projects.reorder('created_at').uniq.page((params[:page].to_i || 1) +1).per(5)
respond_to do |format|
format.js
end
end
def more_org_courses
@organization = Organization.find(params[:id])
@page = params[:page]
@org_courses = @organization.courses.reorder('created_at').uniq.page((params[:page].to_i || 1) + 1 ).per(5)
respond_to do |format|
format.js
end
end
def join_course_menu
@organization = Organization.find(params[:id])
respond_to do |format|
format.js
end
end
def search_courses
@organization = Organization.find(params[:id])
condition = '%%'
if !params[:name].nil?
condition = "%#{params[:name].strip}%".gsub(" ","")
end
sql = "select courses.* from courses inner join members on courses.id = members.course_id where members.user_id = #{User.current.id} and courses.name like '#{condition}'"+
"and courses.id not in (select distinct org_courses.course_id from org_courses where org_courses.organization_id = #{@organization.id})"
#user_courses = Course.find_by_sql(sql)
@courses = Course.find_by_sql(sql)
# @added_course_ids = @organization.courses.map(&:id)
# @courses = []
# user_courses.each do |course|
# if !@added_course_ids.include?(course.id)
# @courses << course
# end
# end
end
def join_courses
@organization = Organization.find(params[:id])
course_ids = params[:courseNames]
course_ids.each do |id|
OrgCourse.create(:organization_id => @organization.id, :course_id => id.to_i, :created_at => Time.now)
end
respond_to do |format|
format.js
end
end
def join_project_menu
@organization = Organization.find(params[:id])
respond_to do |format|
format.js
end
end
def logout
logout_user
respond_to do |format|
format.html {redirect_to organization_path(params[:id])}
end
end
def search_projects
@organization = Organization.find(params[:id])
condition = '%%'
if !params[:name].nil?
condition = "%#{params[:name].strip}%".gsub(" ","")
end
sql = "select projects.* from projects inner join members on projects.id = members.project_id where members.user_id = #{User.current.id} and projects.status != 9 and projects.name like '#{condition}'" +
" and projects.id not in (select org_projects.project_id from org_projects where organization_id = #{@organization.id})"
#user_projects = Course.find_by_sql(sql)
@projects = Course.find_by_sql(sql)
# @added_course_ids = @organization.projects.map(&:id)
# @projects = []
# user_projects.each do |project|
# if !@added_course_ids.include?(project.id)
# @projects << project
# end
# end
end
def join_projects
@organization = Organization.find(params[:id])
project_ids = params[:projectNames]
project_ids.each do |id|
OrgProject.create(:organization_id => @organization.id, :project_id => id.to_i, :created_at => Time.now)
end
respond_to do |format|
format.js
end
end
def hide_org_subfield
@org_subfield = OrgSubfield.find(params[:org_subfield_id])
@org_subfield.update_attribute(:hide, 1)
end
def show_org_subfield
@org_subfield = OrgSubfield.find(params[:org_subfield_id])
@org_subfield.update_attribute(:hide, 0)
end
def org_resources_subfield
@org = Organization.find(params[:id])
if params[:send_type].present? and (params[:send_type] == 'news' or params[:send_type] == 'message')
@subfield = @org.org_subfields.where("field_type = 'Post'")
else
@subfield = @org.org_subfields.where('field_type = "Resource" ')
end
respond_to do | format|
format.js
end
end
def apply_subdomain
@organization = Organization.find(params[:id])
admins = User.where("admin=1")
admins.each do |admin|
OrgMessage.create(:user_id => admin.id, :organization_id => @organization.id, :message_type => 'ApplySubdomain', :message_id => @organization.id, :sender_id => User.current.id, :viewed => 0, :content => params[:domain])
end
end
def agree_apply_subdomain
@organization = Organization.find(params[:organization_id])
OrgMessage.find(params[:act_id]).update_attribute(:viewed, 1)
@organization.update_attribute(:domain, params[:org_domain])
if OrgMessage.where("message_type='AgreeApplySubdomain' and organization_id=#{@organization.id} and content=?",params[:org_domain]).count == 0
OrgMessage.create(:user_id => params[:user_id], :organization_id => @organization.id, :message_type => 'AgreeApplySubdomain', :message_id => @organization.id, :sender_id => User.current.id, :viewed => 0, :content => params[:org_domain])
end
end
end

@ -2,6 +2,7 @@
class PollController < ApplicationController class PollController < ApplicationController
before_filter :find_poll_and_course, :only => [:edit,:update,:destroy,:show,:statistics_result,:create_poll_question,:commit_poll,:commit_answer,:publish_poll,:republish_poll,:poll_result,:close_poll,:export_poll] before_filter :find_poll_and_course, :only => [:edit,:update,:destroy,:show,:statistics_result,:create_poll_question,:commit_poll,:commit_answer,:publish_poll,:republish_poll,:poll_result,:close_poll,:export_poll]
before_filter :find_container, :only => [:new,:create, :index] before_filter :find_container, :only => [:new,:create, :index]
before_filter :is_logged, :only => [:index, :show, :poll_result,:new,:create,:edit,:update,:destroy,:publish_poll,:republish_poll,:close_poll,:export_poll,:commit_answer,:commit_poll,:statistics_result]
before_filter :is_member_of_course, :only => [:index,:show,:poll_result] before_filter :is_member_of_course, :only => [:index,:show,:poll_result]
before_filter :is_course_teacher, :only => [:new,:create,:edit,:update,:destroy,:publish_poll,:republish_poll,:close_poll,:export_poll] before_filter :is_course_teacher, :only => [:new,:create,:edit,:update,:destroy,:publish_poll,:republish_poll,:close_poll,:export_poll]
include PollHelper include PollHelper
@ -28,6 +29,13 @@ class PollController < ApplicationController
render_403 render_403
return return
end end
# 问卷消息状态更新
query_course_poll = @poll.course_messages
query_course_poll.each do |query|
if User.current.id == query.user_id
query.update_attributes(:viewed => true)
end
end
#已提交问卷的用户不能再访问该界面 #已提交问卷的用户不能再访问该界面
if has_commit_poll?(@poll.id,User.current.id) && (!User.current.admin?) if has_commit_poll?(@poll.id,User.current.id) && (!User.current.admin?)
redirect_to poll_index_url(:polls_type => "Course", :polls_group_id => @course.id) redirect_to poll_index_url(:polls_type => "Course", :polls_group_id => @course.id)
@ -406,7 +414,7 @@ class PollController < ApplicationController
respond_to do |format| respond_to do |format|
format.xls { format.xls {
send_data(poll_to_xls(poll_questions), :type => "text/excel;charset=utf-8; header=present", send_data(poll_to_xls(poll_questions), :type => "text/excel;charset=utf-8; header=present",
:filename => "#{@poll.polls_name}.xls") :filename => filename_for_content_disposition("#{@poll.polls_name}.xls") )
} }
end end
end end
@ -496,6 +504,10 @@ class PollController < ApplicationController
end end
end end
def is_logged
redirect_to signin_path unless User.current.logged?
end
def is_member_of_course def is_member_of_course
render_403 unless(@course && (User.current.member_of_course?(@course) || User.current.admin?)) render_403 unless(@course && (User.current.member_of_course?(@course) || User.current.admin?))
end end

@ -5,39 +5,73 @@ class PraiseTreadController < ApplicationController
def praise_plus def praise_plus
@obj = nil @obj = nil
# @is_in_list = nil @activity = false
if request.get? if request.get?
@obj_id = params[:obj_id] @obj_id = params[:obj_id]
@obj_type = params[:obj_type] @obj_type = params[:obj_type]
@horizontal = params[:horizontal].downcase == "false" ? false:true if !params[:user_activity_id].nil? && !params[:type].nil?
@user_activity_id = params[:user_activity_id]
@type = params[:type]
@activity = true
end
# @is_in_list = nil
@obj = find_object_by_type_and_id(@obj_type,@obj_id) @obj = find_object_by_type_and_id(@obj_type,@obj_id)
unless @obj.author_id == User.current.id pts = PraiseTread.where("praise_tread_object_id=? and praise_tread_object_type=? and user_id=?",@obj_id,@obj_type.to_s,User.current.id)
unless pts.empty?
respond_to do |format|
format.js
end
return
end
@horizontal = params[:horizontal].downcase == "false" ? false:true if params[:horizontal]
if @obj.respond_to?("author_id")
author_id = @obj.author_id
elsif @obj.respond_to?("user_id")
author_id = @obj.user_id
end
unless author_id == User.current.id
praise_tread_plus(@obj_type,@obj_id,1) praise_tread_plus(@obj_type,@obj_id,1)
end end
respond_to do |format|
format.js
end
end end
end end
def praise_minus def praise_minus
@obj = nil @obj = nil
@activity = false
if request.get? if request.get?
@obj = params[:obj] # 传的是对象最后变成id了 #@obj = params[:obj] # 传的是对象最后变成id了
#首先更新praise_tread 表 删除关注记录 #首先更新praise_tread 表 删除关注记录
@pt = PraiseTread.find_by_user_id_and_praise_tread_object_id_and_praise_tread_object_type(User.current.id,@obj,"user") #@pt = PraiseTread.find_by_user_id_and_praise_tread_object_id_and_praise_tread_object_type(User.current.id,@obj,"user")
@pt.delete @obj_id = params[:obj_id]
@obj_type = params[:obj_type]
if !params[:user_activity_id].nil? && !params[:type].nil?
@user_activity_id = params[:user_activity_id]
@type = params[:type]
@activity = true
end
@obj = find_object_by_type_and_id(@obj_type,@obj_id)
@pt = PraiseTread.where("praise_tread_object_id=? and praise_tread_object_type=? and user_id=?",@obj_id,@obj_type.to_s,User.current.id).first
if @pt.nil?
respond_to do |format|
format.js
end
return
end
@pt.delete if !@pt.nil?
#再更新praise_tread_cache表 使相应的记录减1 当为0时删除 #再更新praise_tread_cache表 使相应的记录减1 当为0时删除
@ptc = PraiseTreadCache.find_by_object_id(@obj) @ptc = PraiseTreadCache.where("object_id=? and object_type=?",@obj_id,@obj_type.to_s).first
@ptc.minus(1) @ptc.minus(1) if !@ptc.nil?
if @ptc.praise_num == 0 if @ptc.praise_num == 0
@ptc.delete @ptc.delete
end end
end end
@obj = User.find_by_id(@obj) #@obj = User.find_by_id(@obj)
respond_to do |format| respond_to do |format|
format.html
format.js format.js
end end
end end
@ -48,7 +82,7 @@ class PraiseTreadController < ApplicationController
if request.get? if request.get?
@obj_id = params[:obj_id] @obj_id = params[:obj_id]
@obj_type = params[:obj_type] @obj_type = params[:obj_type]
@horizontal = params[:horizontal].downcase == "false" ? false:true #@horizontal = params[:horizontal].downcase == "false" ? false:true
@obj = find_object_by_type_and_id(@obj_type,@obj_id) @obj = find_object_by_type_and_id(@obj_type,@obj_id)
unless @obj.author_id == User.current.id unless @obj.author_id == User.current.id
praise_tread_plus(@obj_type,@obj_id,0) praise_tread_plus(@obj_type,@obj_id,0)
@ -69,20 +103,36 @@ class PraiseTreadController < ApplicationController
def find_object_by_type_and_id(type,id) def find_object_by_type_and_id(type,id)
@obj = nil @obj = nil
case type case type
when 'User' when 'Memo'
@obj = User.find_by_id(id) @obj = Memo.find_by_id(id)
when 'Issue' when 'Message'
@obj = Issue.find_by_id(id) @obj = Message.find_by_id(id)
when 'Project' when 'HomeworkCommon'
@obj = Project.find_by_id(id) @obj = HomeworkCommon.find_by_id(id)
when 'Bid' when 'JournalsForMessage'
@obj = Bid.find_by_id(id) @obj = JournalsForMessage.find_by_id(id)
when 'Contest' when 'News'
@obj = Contest.find_by_id(id) @obj = News.find_by_id(id)
when 'Memo' when 'Comment'
@obj = Memo.find_by_id(id) @obj = Comment.find_by_id(id)
when 'Message' when 'Journal'
@obj = Message.find_by_id(id) @obj = Journal.find_by_id(id)
when 'BlogComment'
@obj = BlogComment.find_by_id(id)
when 'OrgDocumentComment'
@obj = OrgDocumentComment.find_by_id(id)
when 'User'
@obj = User.find_by_id(id)
when 'Issue'
@obj = Issue.find_by_id(id)
when 'Project'
@obj = Project.find_by_id(id)
when 'Bid'
@obj = Bid.find_by_id(id)
when 'Contest'
@obj = Contest.find_by_id(id)
else
@obj = nil
end end
return @obj return @obj
end end
@ -99,17 +149,14 @@ class PraiseTreadController < ApplicationController
# end # end
#再创建或更新praise_tread_cache表 #再创建或更新praise_tread_cache表
@ptc = PraiseTreadCache.find_by_object_id_and_object_type(id,type) #@ptc = PraiseTreadCache.find_by_object_id_and_object_type(id,type)
@ptc = PraiseTreadCache.where("object_id = ? and object_type = ?",id.to_i,type).first
@ptc = @ptc.nil? ? PraiseTreadCache.new : @ptc @ptc = @ptc.nil? ? PraiseTreadCache.new : @ptc
@ptc.object_id = id.to_i @ptc.object_id = id.to_i
@ptc.object_type = type @ptc.object_type = type
@ptc.save @ptc.save
@ptc.plus(flag,1) @ptc.plus(flag,1)
end end
respond_to do |format|
format.html
format.js
end
end end
end end

@ -30,10 +30,10 @@ class ProjectsController < ApplicationController
before_filter :find_project, :except => [ :index, :search,:list, :new, :create, :copy, :statistics, :new_join, :course, :enterprise_course, :course_enterprise,:view_homework_attaches,:join_project] before_filter :find_project, :except => [ :index, :search,:list, :new, :create, :copy, :statistics, :new_join, :course, :enterprise_course, :course_enterprise,:view_homework_attaches,:join_project]
before_filter :authorize, :only => [:show, :settings, :edit, :sort_project_members, :update, :modules, :close, :reopen,:view_homework_attaches,:course] before_filter :authorize, :only => [:show, :settings, :edit, :sort_project_members, :update, :modules, :close, :reopen,:view_homework_attaches,:course]
before_filter :authorize_global, :only => [:new, :create,:view_homework_attaches] before_filter :authorize_global, :only => [:new, :create,:view_homework_attaches]
before_filter :require_admin, :only => [ :copy, :archive, :unarchive, :destroy, :calendar] before_filter :require_admin, :only => [ :copy, :unarchive, :destroy, :calendar]
before_filter :file, :statistics #:watcherlist before_filter :file, :statistics #:watcherlist
# 除非项目内人员,不可查看成员, TODO: 完了写报表里去 # 除非项目内人员,不可查看成员, TODO: 完了写报表里去
before_filter :memberAccess, only: :member # before_filter :memberAccess, only: :member
# accept_rss_auth :index # accept_rss_auth :index
accept_api_auth :index, :show, :create, :update, :destroy accept_api_auth :index, :show, :create, :update, :destroy
@ -69,6 +69,32 @@ class ProjectsController < ApplicationController
### added by william ### added by william
include ActsAsTaggableOn::TagsHelper include ActsAsTaggableOn::TagsHelper
#查找组织
def search_public_orgs_not_in_project
condition = '%%'
if !params[:name].nil?
condition = "%#{params[:name].strip}%".gsub(" ","")
end
limit = 15
project_org_ids = OrgProject.find_by_sql("select distinct organization_id from org_projects where project_id = #{params[:id]}").map(&:organization_id) << 0
@orgs_not_in_project = User.current.organizations.where("organizations.id not in (#{project_org_ids.join(',')}) and organizations.name like ?", condition).page(params[:page].to_i || 1).per(limit)
@org_count = User.current.organizations.where("organizations.id not in (#{project_org_ids.join(',')}) and organizations.name like '#{condition}'").count
# if project_org_ids.empty?
# @orgs_not_in_project = Organization.where("(is_public or creator_id =?) = 1 and name like ?",User.current.id, condition).page((params[:page].to_i || 1)).per(limit)
# @org_count = Organization.where("is_public = 1 or creator_id =?", User.current.id).where("name like ?", condition).count
# else
# project_org_ids = "(" + project_org_ids.join(',') + ")"
# @orgs_not_in_project = Organization.where("id not in #{project_org_ids} and (is_public = 1 or creator_id =?) and name like ?", User.current.id, condition).page((params[:page].to_i || 1)).per(limit)
# @org_count = Organization.where("id not in #{project_org_ids} and (is_public = 1 or creator_id =?)", User.current.id).where("name like ?", condition).count
# end
@orgs_page = Paginator.new @org_count, limit,params[:page]
@no_roll_hint = params[:hint_flag]
#render :json => {:orgs => @orgs_not_in_project, :count => @org_count}.to_json
respond_to do |format|
format.js
end
end
def index def index
render_404 render_404
end end
@ -92,7 +118,8 @@ class ProjectsController < ApplicationController
@project_count = Project.project_entities.visible.like(params[:name]).page(params[:page]).count @project_count = Project.project_entities.visible.like(params[:name]).page(params[:page]).count
@project_pages = Paginator.new @project_count, @limit, params['page'] @project_pages = Paginator.new @project_count, @limit, params['page']
@name = params[:name]
@type = 'projects'
respond_to do |format| respond_to do |format|
format.html { format.html {
render :layout => 'base' render :layout => 'base'
@ -160,7 +187,7 @@ class ProjectsController < ApplicationController
@trackers = Tracker.sorted.all @trackers = Tracker.sorted.all
@project = Project.new @project = Project.new
@project.safe_attributes = params[:project] @project.safe_attributes = params[:project]
render :layout => 'base' render :layout => 'new_base'
else else
redirect_to signin_url redirect_to signin_url
end end
@ -175,6 +202,8 @@ class ProjectsController < ApplicationController
end end
end end
# 注意修改该方法的时候注意同步修改forked方法
# forked方法也会创建项目
def create def create
unless User.current.login? unless User.current.login?
redirect_to signin_url redirect_to signin_url
@ -186,13 +215,19 @@ class ProjectsController < ApplicationController
@project.safe_attributes = params[:project] @project.safe_attributes = params[:project]
@project.organization_id = params[:organization_id] @project.organization_id = params[:organization_id]
@project.user_id = User.current.id @project.user_id = User.current.id
@project.project_new_type = 1 @project.project_new_type = params[:project_new_type]
params[:project][:is_public] ? @project.is_public = 1 : @project.is_public = 0
if validate_parent_id && @project.save if validate_parent_id && @project.save
@project.set_allowed_parent!(params[:project]['parent_id']) if params[:project].has_key?('parent_id') @project.set_allowed_parent!(params[:project]['parent_id']) if params[:project].has_key?('parent_id')
# Add current user as a project member if he is not admin # Add current user as a project member if he is not admin
#unless User.current.admin? #unless User.current.admin?
r = Role.givable.find_by_id(Setting.new_project_user_role_id.to_i) || Role.givable.first r = Role.givable.find_by_id(Setting.new_project_user_role_id.to_i) || Role.givable.first
m = Member.new(:user => User.current, :roles => [r]) m = Member.new(:user => User.current, :roles => [r])
# project's score
if ProjectScore.where("project_id=?", @project.id).first.nil?
ProjectScore.create(:project_id => @project.id, :score => false)
end
# end
project_info = ProjectInfo.new(:user_id => User.current.id, :project_id => @project.id) project_info = ProjectInfo.new(:user_id => User.current.id, :project_id => @project.id)
user_grades = UserGrade.create(:user_id => User.current.id, :project_id => @project.id) user_grades = UserGrade.create(:user_id => User.current.id, :project_id => @project.id)
Rails.logger.debug "UserGrade created: #{user_grades.to_json}" Rails.logger.debug "UserGrade created: #{user_grades.to_json}"
@ -214,10 +249,11 @@ class ProjectsController < ApplicationController
end end
} }
format.api { render :action => 'show', :status => :created, :location => url_for(:controller => 'projects', :action => 'show', :id => @project.id) } format.api { render :action => 'show', :status => :created, :location => url_for(:controller => 'projects', :action => 'show', :id => @project.id) }
format.js
end end
else else
respond_to do |format| respond_to do |format|
format.html { render :action => 'new', :layout => 'base'}#Added by young format.html { render :action => 'new', :layout => 'new_base'}#Added by young
format.api { render_validation_errors(@project) } format.api { render_validation_errors(@project) }
end end
end end
@ -256,7 +292,8 @@ class ProjectsController < ApplicationController
# Author lizanle # Author lizanle
# Description 项目动态展示方法,删除了不必要的代码 # Description 项目动态展示方法,删除了不必要的代码
def show def show
# 更新消息为已读
update_message_status(User.current, @project)
if params[:jump] && redirect_to_project_menu_item(@project, params[:jump]) if params[:jump] && redirect_to_project_menu_item(@project, params[:jump])
return return
end end
@ -291,9 +328,20 @@ class ProjectsController < ApplicationController
@activity.scope_select {|t| !has["show_#{t}"].nil?} @activity.scope_select {|t| !has["show_#{t}"].nil?}
=end =end
@page = params[:page] ? params[:page].to_i + 1 : 0
# 根据私密性,取出符合条件的所有数据 # 根据私密性,取出符合条件的所有数据
if User.current.member_of?(@project) || User.current.admin? if User.current.member_of?(@project) || User.current.admin?
@events_pages = ForgeActivity.where("project_id = ? and forge_act_type != ?",@project, "Document" ).order("created_at desc").page(params['page'|| 1]).per(20); case params[:type]
when nil
@events_pages = ForgeActivity.where("project_id = ? and forge_act_type in ('Issue', 'Message','News', 'ProjectCreateInfo')",@project).order("updated_at desc").limit(10).offset(@page * 10)
when 'issue'
@events_pages = ForgeActivity.where("project_id = ? and forge_act_type = 'Issue'",@project).order("updated_at desc").limit(10).offset(@page * 10)
when 'news'
@events_pages = ForgeActivity.where("project_id = ? and forge_act_type = 'News'",@project).order("updated_at desc").limit(10).offset(@page * 10)
when 'message'
@events_pages = ForgeActivity.where("project_id = ? and forge_act_type = 'Message'",@project).order("updated_at desc").limit(10).offset(@page * 10)
end
#events = @activity.events(@date_from, @date_to) #events = @activity.events(@date_from, @date_to)
else else
@events_pages = ForgeActivity.includes(:project).where("forge_activities.project_id = ? and projects.is_public @events_pages = ForgeActivity.includes(:project).where("forge_activities.project_id = ? and projects.is_public
@ -320,6 +368,12 @@ class ProjectsController < ApplicationController
end end
def settings def settings
# 修改查看消息状态
applied_messages = ForgeMessage.where("user_id =? and project_id =? and forge_message_type =? and viewed =?", User.current.id, @project, "AppliedProject", 0)
applied_messages.each do |applied_message|
applied_message.update_attributes(:viewed => true)
end
# end
@issue_custom_fields = IssueCustomField.sorted.all @issue_custom_fields = IssueCustomField.sorted.all
@issue_category ||= IssueCategory.new @issue_category ||= IssueCategory.new
@member ||= @project.members.new @member ||= @project.members.new
@ -327,6 +381,15 @@ class ProjectsController < ApplicationController
@wiki ||= @project.wiki @wiki ||= @project.wiki
@select_tab = params[:tab] @select_tab = params[:tab]
#找出所有不属于项目的公共组织
project_org_ids = OrgProject.find_by_sql("select distinct organization_id from org_projects where project_id = #{@project.id}")
if project_org_ids.empty?
@orgs_not_in_project = Organization.where("is_public = 1")
else
project_org_ids = "(" + project_org_ids.join(',') + ")"
@orgs_not_in_project = Organization.where("id not in #{project_org_ids} and is_public = 1")
end
# 处理从新建版本库返回来的错误信息 # 处理从新建版本库返回来的错误信息
if !params[:repository_error_message].to_s.blank? if !params[:repository_error_message].to_s.blank?
html = "" html = ""
@ -340,7 +403,7 @@ class ProjectsController < ApplicationController
if params[:repository] == "pswd_is_null" if params[:repository] == "pswd_is_null"
html << l(:label_password_not_null) html << l(:label_password_not_null)
end end
flash[:error] = html if !html.to_s.blank? flash.now[:error] = html if !html.to_s.blank?
end end
scm = params[:repository_scm] || (Redmine::Scm::Base.all & Setting.enabled_scm).first scm = params[:repository_scm] || (Redmine::Scm::Base.all & Setting.enabled_scm).first
@repository = Repository.factory(scm) @repository = Repository.factory(scm)
@ -349,24 +412,60 @@ class ProjectsController < ApplicationController
end end
# 项目邀请用户加入实现过程
# 两种情况1、系统外用户2、系统内用户 (通过邮件判定) # 两种情况1、系统外用户2、系统内用户 (通过邮件判定)
def send_mail_to_member def send_mail_to_member
# 该邮箱未注册过
if !params[:mail].blank? && User.find_by_mail(params[:mail].to_s).nil? if !params[:mail].blank? && User.find_by_mail(params[:mail].to_s).nil?
email = params[:mail] if !User.where("login =?", params[:mail]).first.nil?
Mailer.run.send_invite_in_project(email, @project, User.current) # 用户名唯一,用户修改邮箱,未修改用户名,用户名等同邮箱的情况,默认改用户已经注册
@is_zhuce = false user = User.find_by_login(params[:mail].to_s)
flash[:notice] = l(:notice_email_sent, :value => email) if !user.member_of?(@project)
# 如果已经邀请过该用户,则不重复发送
if InviteList.where("project_id =? and mail =?", @project.id, params[:mail].to_s).first.nil?
email = params[:mail]
Mailer.request_member_to_project(email, @project, User.current).deliver
flash[:notice] = l(:notice_email_sent, :value => email)
else
flash[:error] = l(:notice_email_invited)
end
else
flash[:error] = l(:label_member_of_project, :value => email)
end
else
email = params[:mail]
first_name = params[:first_name]
last_name = params[:last_name]
gender = params[:gender]
Mailer.send_invite_in_project(email, @project, User.current, first_name, last_name, gender).deliver
@is_zhuce = false
flash[:notice] = l(:notice_email_sent, :value => email)
end
# 邮箱地址已被注册
elsif !User.find_by_mail(params[:mail].to_s).nil? elsif !User.find_by_mail(params[:mail].to_s).nil?
user = User.find_by_mail(params[:mail].to_s) user = User.find_by_mail(params[:mail].to_s)
if !user.member_of?(@project) if !user.member_of?(@project)
email = params[:mail] # 如果已经邀请过该用户,则不重复发送
Mailer.run.request_member_to_project(email, @project, User.current) invite_list = InviteList.where("project_id =? and mail =?", @project.id, params[:mail].to_s).first
flash[:notice] = l(:notice_email_sent, :value => email) if invite_list.nil?
email = params[:mail]
Mailer.request_member_to_project(email, @project, User.current).deliver
flash[:notice] = l(:notice_email_sent, :value => email)
else
# 已经发送过了则隔3小时才能再次发送
if Time.now - invite_list.created_at > 10800
email = params[:mail]
Mailer.request_member_to_project(email, @project, User.current).deliver
flash[:notice] = l(:notice_email_sent, :value => email)
else
flash[:error] = l(:notice_email_invited)
end
end
else else
flash[:error] = l(:label_member_of_project, :value => email) flash[:error] = l(:label_member_of_project, :value => email)
end end
else else
flash[:error] = l(:notice_registed_error, :value => email)
@is_zhuce = true @is_zhuce = true
end end
respond_to do |format| respond_to do |format|
@ -374,25 +473,26 @@ class ProjectsController < ApplicationController
end end
end end
#发送邮件邀请新用户 # 发送邮件邀请新用户页面对应方法
def invite_members_by_mail def invite_members_by_mail
if User.current.member_of?(@project) || User.current.admin? if User.current.member_of?(@project) || User.current.admin?
@inviter_lists = InviteList.where(project_id:@project.id).all @inviter_lists = InviteList.where(project_id:@project.id).order("created_at desc")
@inviters = []
@waiters = [] # @inviters = []
unless @inviter_lists.blank? # @waiters = []
@inviter_lists.each do|inviter_list| # unless @inviter_lists.blank?
unless inviter_list.user.nil? # @inviter_lists.each do|inviter_list|
if inviter_list.user.member_of?(@project) # unless inviter_list.user.nil?
@inviters << inviter_list.user # if inviter_list.user.member_of?(@project)
@inviters_count = @inviters.size # @inviters << inviter_list.user
else # @inviters_count = @inviters.size
@waiters << inviter_list.user # else
@waiters_count = @waiters.size # @waiters << inviter_list.user
end # @waiters_count = @waiters.size
end # end
end # end
end # end
# end
@is_zhuce = false @is_zhuce = false
respond_to do |format| respond_to do |format|
format.html format.html
@ -404,23 +504,36 @@ class ProjectsController < ApplicationController
end end
# 邀请Trustie注册用户 # 邀请Trustie注册用户
def invite_members # def invite_members
if User.current.member_of?(@project) || User.current.admin? # if User.current.member_of?(@project) || User.current.admin?
@member ||= @project.members.new # @member ||= @project.members.new
respond_to do |format| # respond_to do |format|
format.html # format.html
end # end
else # else
render_403 # render_403
end # end
end # end
def edit def edit
end end
def set_public_or_private
@project = Project.find(params[:id])
if @project.is_public?
@project.update_attribute(:is_public, 0)
else
@project.update_attribute(:is_public, 1)
end
end
# by young # by young
# include CoursesHelper # include CoursesHelper
def member def member
# 消息"同意加入项目"
if params[:message_id]
message_invite(params[:message_id], params[:key])
end
update_message_status(User.current, @project)
# params[:login]为邮箱邀请用户加入,主要功能: # params[:login]为邮箱邀请用户加入,主要功能:
# 1、自动注册 # 1、自动注册
# 2、加入项目、创建角色 # 2、加入项目、创建角色
@ -442,6 +555,10 @@ class ProjectsController < ApplicationController
flash[:notice] = l(:label_mail_invite_success) flash[:notice] = l(:label_mail_invite_success)
end end
end end
# 私有项目非项目成员无法访问成员列表
unless @project.is_public?
return render_403 unless User.current.member_of?(@project)
end
## 有角色参数的才是课程,没有的就是项目 ## 有角色参数的才是课程,没有的就是项目
@render_file = 'project_member_list' @render_file = 'project_member_list'
# 判断是否课程 # 判断是否课程
@ -472,6 +589,32 @@ class ProjectsController < ApplicationController
@members = paginateHelper @members @members = paginateHelper @members
end end
def update_message_status(user, project)
project_invite_messages = ForgeMessage.where("user_id =? and project_id =? and forge_message_type =?", user, project, "ProjectInvite")
project_invite_messages.each do |project_invite_message|
project_invite_message.update_attribute(:viewed, true)
end
#更新被加入项目消息的viewed字段
join_project_messages = ForgeMessage.where("user_id =? and project_id =? and forge_message_type=?", user, project, "JoinProject")
join_project_messages.each do |join_project|
join_project.update_attribute(:viewed, true)
end
#更新被移出项目消息的viewed字段
remove_project_messages = ForgeMessage.where("user_id =? and project_id =? and forge_message_type=?", user, project, "RemoveFromProject")
remove_project_messages.update_all(:viewed => true)
end
def message_invite(message_id, key)
forge_message = ForgeMessage.find(message_id)
if key == forge_message.secret_key
# 情况:用户收到邀请邮件还没看,但是管理员已经把该用户添加进项目
if Member.where("user_id =? and project_id =?",forge_message.user_id, forge_message.project_id).first.nil?
Member.create(:role_ids => [4], :user_id => forge_message.user_id, :project_id => forge_message.project_id)
UserGrade.create(:user_id => forge_message.user_id, :project_id => forge_message.project_id)
end
end
end
#判断指定用户是否为课程教师 #判断指定用户是否为课程教师
def isCourseTeacher(id) def isCourseTeacher(id)
result = false result = false
@ -524,6 +667,13 @@ class ProjectsController < ApplicationController
@project.organization_id = params[:organization_id] @project.organization_id = params[:organization_id]
params[:project][:is_public] ? @project.is_public = 1 : @project.is_public = 0 params[:project][:is_public] ? @project.is_public = 1 : @project.is_public = 0
params[:project][:hidden_repo] ? @project.hidden_repo = 1 : @project.hidden_repo = 0 params[:project][:hidden_repo] ? @project.hidden_repo = 1 : @project.hidden_repo = 0
# 更新公开私有时同步gitlab公开私有
unless @project.gpid.nil?
g = Gitlab.client
gproject = g.project(@project.gpid)
params[:project][:is_public] ? g.edit_project(gproject.id, 20) : g.edit_project(gproject.id, 0)
end
# end
if validate_parent_id && @project.save if validate_parent_id && @project.save
@project.set_allowed_parent!(params[:project]['parent_id']) if params[:project].has_key?('parent_id') @project.set_allowed_parent!(params[:project]['parent_id']) if params[:project].has_key?('parent_id')
if params[:project][:is_public] == '0' if params[:project][:is_public] == '0'
@ -563,7 +713,11 @@ class ProjectsController < ApplicationController
flash[:error] = l(:error_can_not_archive_project) flash[:error] = l(:error_can_not_archive_project)
end end
end end
redirect_to admin_projects_url(:status => params[:status]) if params[:type] == "project"
redirect_to user_path(User.current)
else
redirect_to admin_projects_url(:status => params[:status])
end
end end
def unarchive def unarchive
@ -584,14 +738,10 @@ class ProjectsController < ApplicationController
# Delete @project # Delete @project
def destroy def destroy
@project_to_destroy = @project @project_to_destroy = @project
if api_request? || params[:confirm] @project_to_destroy.destroy
@project_to_destroy.destroy respond_to do |format|
respond_to do |format| format.html { redirect_to admin_projects_url }
format.html { redirect_to admin_projects_url } format.api { render_api_ok }
format.api { render_api_ok }
end
else
render :layout => "base_projects"
end end
# hide project in layout # hide project in layout
@project = nil @project = nil
@ -747,5 +897,4 @@ class ProjectsController < ApplicationController
end end
#gcmend #gcmend
end end

@ -29,12 +29,12 @@ class RepositoriesController < ApplicationController
menu_item :repository menu_item :repository
menu_item :settings, :only => [:new, :create, :edit, :update, :destroy, :committers] menu_item :settings, :only => [:new, :create, :edit, :update, :destroy, :committers]
default_search_scope :changesets default_search_scope :changesets
before_filter :find_project_by_project_id, :only => [:new, :create, :newrepo] before_filter :find_project_by_project_id, :only => [:new, :create, :newrepo]
before_filter :find_repository, :only => [:edit, :update, :destroy, :committers] before_filter :find_repository, :only => [:edit, :update, :destroy, :committers]
before_filter :find_project_repository, :except => [:new, :create, :newcreate, :edit, :update, :destroy, :committers, :newrepo] before_filter :find_project_repository, :except => [:new, :create, :newcreate, :edit, :update, :destroy, :committers, :newrepo, :to_gitlab, :forked]
before_filter :find_changeset, :only => [:revision, :add_related_issue, :remove_related_issue] before_filter :find_changeset, :only => [:revision, :add_related_issue, :remove_related_issue]
before_filter :authorize , :except => [:newrepo,:newcreate,:fork] before_filter :authorize , :except => [:newrepo,:newcreate,:fork, :to_gitlab, :forked]
accept_rss_auth :revisions accept_rss_auth :revisions
# hidden repositories filter // 隐藏代码过滤器 # hidden repositories filter // 隐藏代码过滤器
before_filter :check_hidden_repo, :only => [:show, :stats, :revisions, :revision, :diff ] before_filter :check_hidden_repo, :only => [:show, :stats, :revisions, :revision, :diff ]
@ -42,23 +42,132 @@ class RepositoriesController < ApplicationController
include RepositoriesHelper include RepositoriesHelper
helper :project_score helper :project_score
#@root_path = RepositoriesHelper::ROOT_PATH #@root_path = RepositoriesHelper::ROOT_PATH
$g=Gitlab.client
rescue_from Redmine::Scm::Adapters::CommandFailed, :with => :show_error_command_failed rescue_from Redmine::Scm::Adapters::CommandFailed, :with => :show_error_command_failed
def new def new
scm = params[:repository_scm] || (Redmine::Scm::Base.all & Setting.enabled_scm).first if @project.repositories.count == 0
@repository = Repository.factory(scm) scm = params[:repository_scm] || (Redmine::Scm::Base.all & Setting.enabled_scm).first
@repository.is_default = @project.repository.nil? @repository = Repository.factory(scm)
@repository.project = @project @repository.is_default = @project.repository.nil?
@course_tag = params[:course] @repository.project = @project
if @course_tag == 1 @course_tag = params[:course]
render :layout => 'base_courses' if @course_tag == 1
render :layout => 'base_courses'
else
render :layout => 'base_projects'
end
else else
render :layout => 'base_projects' render_403
end
end
def forked
@project = Project.find(params[:id])
@repository = Repository.where("project_id =? and type =?", @project.id, "Repository::Gitlab")
# 如果当前用户已经fork过该项目不会新fork项目则跳至已fork的项
unless has_forked?(@project, User.current)
project = project_from_current_project(@project.id, User.current.id)
redirect_to project_path(project)
else
# 自己不能fork自己的项目
if User.current.id == @project.user_id
flash[:notice] = l(:project_gitlab_fork_own)
redirect_to repository_url(@repository)
else
g = Gitlab.client
if User.current.gid.nil?
begin
g.sync_user(User.current)
ensure
logger.error "Synv user failed ==>#{User.current.id}"
end
end
gproject = g.fork(@project.gpid, User.current.gid)
if gproject
copy_project(@project, gproject)
forked_count = @project.forked_count.to_i + 1
@project.update_attributes(:forked_count => forked_count)
end
end
end
end
# 判断用户是否已经fork过该项目
def has_forked?(project, user)
projects = Project.where("user_id =?", user)
projects.map(&:forked_from_project_id).detect{|s| s == @project.id}.nil? ? true : false
end
# 获取当前用户fork过的项目
def project_from_current_project(project, user)
project = Project.where("user_id =? and forked_from_project_id =?",user, project).first
end
# copy a project for fork
def copy_project(tproject, gproject)
project = Project.new
project.name = tproject.name
project.is_public = tproject.is_public
project.status = tproject.status
project.description = tproject.description
project.hidden_repo = tproject.hidden_repo
project.user_id = User.current.id
project.project_type = 0
project.project_new_type = tproject.project_new_type
project.gpid = gproject.id
project.forked_from_project_id = tproject.id
if project.save
r = Role.givable.find_by_id(Setting.new_project_user_role_id.to_i) || Role.givable.first
m = Member.new(:user => User.current, :roles => [r])
if ProjectScore.where("project_id=?", project.id).first.nil?
ProjectScore.create(:project_id => project.id, :score => false)
end
project_info = ProjectInfo.new(:user_id => User.current.id, :project_id => project.id)
user_grades = UserGrade.create(:user_id => User.current.id, :project_id => project.id)
Rails.logger.debug "UserGrade created: #{user_grades.to_json}"
project_status = ProjectStatus.create(:project_id => @project.id, :watchers_count => 0, :changesets_count => 0, :project_type => @project.project_type,:grade => 0)
Rails.logger.debug "ProjectStatus created: #{project_status.to_json}"
project.members << m
project.project_infos << project_info
copy_repository(project, gproject)
respond_to do |format|
format.html {
flash[:notice] = l(:notice_successful_create)
if params[:continue]
attrs = {:parent_id => project.parent_id}.reject {|k,v| v.nil?}
redirect_to new_project_url(attrs, :course => '0')
else
redirect_to settings_project_url(project)
end
}
format.api { render :action => 'show', :status => :created, :location => url_for(:controller => 'projects', :action => 'show', :id => project.id) }
format.js
end
else
respond_to do |format|
format.html { render :action => 'forked', :layout => 'base_projects'}
format.api { render_validation_errors(@project) }
end
end end
end end
def copy_repository(project, gproject)
# 避免
# if is_sigle_identifier?(project.user_id, gproject.name)
repository = Repository.factory('Git')
repository.project_id = project.id
repository.type = 'Repository::Gitlab'
repository.url = gproject.name
repository.identifier = gproject.name
repository = repository.save
# else
# flash[:notice] = l(:project_gitlab_create_double_message)
# end
end
def newrepo def newrepo
scm = params[:repository_scm] || (Redmine::Scm::Base.all & Setting.enabled_scm).first scm = params[:repository_scm] || (Redmine::Scm::Base.all & Setting.enabled_scm).first
@repository = Repository.factory(scm) @repository = Repository.factory(scm)
@ -71,23 +180,23 @@ class RepositoriesController < ApplicationController
render :layout => 'base_projects' render :layout => 'base_projects'
end end
end end
def fork def fork
@repository_url = params[:repository_url] @repository_url = params[:repository_url]
# @repository.url # @repository.url
# system "htpasswd -mb "+@root_path+"user.passwd "+params[:repository][:identifier]+" "+@upasswd # system "htpasswd -mb "+@root_path+"user.passwd "+params[:repository][:identifier]+" "+@upasswd
# system "echo -e '"+params[:project_id]+"-"+params[:repository][:identifier]+"-write:"+ # system "echo -e '"+params[:project_id]+"-"+params[:repository][:identifier]+"-write:"+
# " "+params[:repository][:identifier]+"' >> "+@root_path+"group.passwd" # " "+params[:repository][:identifier]+"' >> "+@root_path+"group.passwd"
system "git clone --bare "+@repository_url system "git clone --bare "+@repository_url
# system "mv "+@project_path+"/hooks/post-update{.sample,}" # system "mv "+@project_path+"/hooks/post-update{.sample,}"
# system "chmod a+x "+@project_path+"/hooks/post-update" # system "chmod a+x "+@project_path+"/hooks/post-update"
# system "."+@project_path+"/hooks/post-update" # system "."+@project_path+"/hooks/post-update"
# system "echo -e 'Allow from all \n Order Deny,Allow \n "+ # system "echo -e 'Allow from all \n Order Deny,Allow \n "+
# "<Limit PUT POST DELETE PROPPATCH MKCOL COPY MOVE LOCK UNLOCK> \n"+ # "<Limit PUT POST DELETE PROPPATCH MKCOL COPY MOVE LOCK UNLOCK> \n"+
# "Require group "+params[:project_id]+"-"+params[:repository][:identifier]+"-write \n "+ # "Require group "+params[:project_id]+"-"+params[:repository][:identifier]+"-write \n "+
# "</Limit> \n ' >>"+ # "</Limit> \n ' >>"+
# @project_path+"/.htaccess" # @project_path+"/.htaccess"
flash[:notice] = l(:label_notice_fork_successed) flash[:notice] = l(:label_notice_fork_successed)
@repositories = @project.repositories @repositories = @project.repositories
render :action => 'show', :layout => 'base_projects' render :action => 'show', :layout => 'base_projects'
@ -110,9 +219,11 @@ update
} }
def create def create
if params[:repository_scm].to_s == 'Gitlab' # 判断版本库创建者是否有同名版本库,避免版本库路径一致问题
# add by nwb unless is_sigle_identifier?(@project.user_id, params[:repository].first[1])
# 增加对gitlab版本库的支持 flash[:notice] = l(:project_gitlab_create_double_message)
redirect_to settings_project_url(@project, :tab => 'repositories')
else
attrs = pickup_extra_info attrs = pickup_extra_info
@repository = Repository.factory('Git') @repository = Repository.factory('Git')
@repository.safe_attributes = params[:repository] @repository.safe_attributes = params[:repository]
@ -120,67 +231,18 @@ update
@repository.merge_extra_info(attrs[:attrs_extra]) @repository.merge_extra_info(attrs[:attrs_extra])
end end
@repository.project = @project @repository.project = @project
@repository.type = 'Repository::Gitlab'
@repository.url = @repository.identifier
if request.post? && @repository.save if request.post? && @repository.save
s = Trustie::Gitlab::Sync.new
s.create_project(@project, @repository)
redirect_to settings_project_url(@project, :tab => 'repositories') redirect_to settings_project_url(@project, :tab => 'repositories')
else else
redirect_to settings_project_url(@project, :tab => 'repositories')
end
else # 原逻辑
##xianbo
@root_path=RepositoriesHelper::ROOT_PATH
@repository_name=User.current.login.to_s+"/"+params[:repository][:identifier]+".git"
@project_path=@root_path+"htdocs/"+@repository_name
@repository_tag=params[:repository][:upassword] || params[:repository][:password]
@repo_name=User.current.login.to_s+"_"+params[:repository][:identifier]
logger.info "htpasswd -mb "+@root_path+"htdocs/user.passwd "+@repo_name+": "+@repository_tag
logger.info "the value of create repository"+@root_path+": "+@repository_name+": "+@project_path+": "+@repo_name
attrs = pickup_extra_info
if((@repository_tag!="")&&params[:repository_scm]=="Git")
params[:repository][:url]=@project_path
end
###xianbo
@repository = Repository.factory(params[:repository_scm])
@repository.safe_attributes = params[:repository]
if attrs[:attrs_extra].keys.any?
@repository.merge_extra_info(attrs[:attrs_extra])
end
@repository.project = @project
if request.post? && @repository.save
if(params[:repository_scm]=="Git")
system "htpasswd -mb "+@root_path+"htdocs/user.passwd "+@repo_name+" "+@repository_tag
system "echo -e '"+@repo_name+"-write:"+
" "+@repo_name+"' >> "+@root_path+"htdocs/group.passwd"
system "mkdir "+@root_path+"htdocs/"+User.current.login.to_s
system "git init --bare "+@project_path
system "mv "+@project_path+"/hooks/post-update{.sample,}"
system "chmod a+x "+@project_path+"/hooks/post-update"
system "echo -e 'Allow from all \n Order Deny,Allow \n "+
"<Limit PUT POST DELETE PROPPATCH MKCOL COPY MOVE LOCK UNLOCK> \n"+
"Require group "+@repo_name+"-write \n "+
"</Limit> \n ' >> "+
@root_path+"htdocs/"+ @repository_name+"/.htaccess"
system "cd "+@project_path+" ;git update-server-info"
File.open(@project_path+"/hooks/post-update", "w+") do |f|
f.write(HOOK_TEMPLATE)
end
@repository.update_attributes(:login => User.current.login.to_s)
end
redirect_to settings_project_url(@project, :tab => 'repositories',:repository_error_message=>@repository.errors.full_messages) redirect_to settings_project_url(@project, :tab => 'repositories',:repository_error_message=>@repository.errors.full_messages)
else if(@repository_tag.blank?)
#render :action => 'newrepo', :layout =>'base_projects'
redirect_to settings_project_url(@project, :tab => 'repositories',:repository => "pswd_is_null",:repository_error_message=>@repository.errors.full_messages)
else
redirect_to settings_project_url(@project, :tab => 'repositories',:repository => @repository,:repository_error_message=>@repository.errors.full_messages)
end
end end
end end
end end
def edit def edit
end end
@ -223,15 +285,17 @@ update
# Build a hash with repository usernames as keys and corresponding user ids as values # Build a hash with repository usernames as keys and corresponding user ids as values
@repository.committer_ids = params[:committers].values.inject({}) {|h, c| h[c.first] = c.last; h} @repository.committer_ids = params[:committers].values.inject({}) {|h, c| h[c.first] = c.last; h}
flash[:notice] = l(:notice_successful_update) flash[:notice] = l(:notice_successful_update)
redirect_to settings_project_url(@project, :tab => 'repositories') respond_to do |format|
format.html{
render :layout => "base_projects"
}
end
elsif request.get? elsif request.get?
respond_to do |format| respond_to do |format|
format.html{ format.html{
render :layout => "base_projects" render :layout => "base_projects"
} }
end end
end end
end end
@ -242,6 +306,16 @@ update
redirect_to settings_project_url(@project, :tab => 'repositories') redirect_to settings_project_url(@project, :tab => 'repositories')
end end
def to_gitlab
@project = Project.find(params[:project_id])
@repository = Repository.find(params[:id])
s = Trustie::Gitlab::Sync.new
s.sync_project(@project, path: params[:repo_name], import_url: @repository.url)
@repository.type = 'Repository::Gitlab'
@repository.save
redirect_to :controller => 'repositories', :action => 'show', :id => @project.id, to: 'gitlab'
end
def show def show
## TODO: the below will move to filter, done. ## TODO: the below will move to filter, done.
if !User.current.member_of?(@project) if !User.current.member_of?(@project)
@ -251,19 +325,19 @@ update
end end
end end
if params[:to] == 'gitlab' # unless @repository.gitlab?
g = Gitlab.client # # redirect_to to_gitlab_project_repository_path(@project, @repository)
g.post('/session', body: {email: User.current.mail, password: User.current.hashed_password}) # render :to_gitlab
redirect_to "http://192.168.41.130:3000/gitlab-org/gitlab-shell/tree/master" # return
return # end
end
#if( !User.current.member_of?(@project) || @project.hidden_repo) #if( !User.current.member_of?(@project) || @project.hidden_repo)
@repository.fetch_changesets if Setting.autofetch_changesets? && @path.empty? @repository.fetch_changesets if Setting.autofetch_changesets? && @path.empty?
# :name, :path, :kind, :size, :lastrev, :changeset
@entries = @repository.entries(@path, @rev) @entries = @repository.entries(@path, @rev)
# @trees = g.trees(project, @path)
@changeset = @repository.find_changeset_by_name(@rev) @changeset = @repository.find_changeset_by_name(@rev)
#@project_path_cut = RepositoriesHelper::PROJECT_PATH_CUT #@project_path_cut = RepositoriesHelper::PROJECT_PATH_CUT
#@ip = RepositoriesHelper::REPO_IP_ADDRESS #@ip = RepositoriesHelper::REPO_IP_ADDRESS
@ -271,15 +345,35 @@ update
@entries ? render(:partial => 'dir_list_content') : render(:nothing => true) @entries ? render(:partial => 'dir_list_content') : render(:nothing => true)
else else
#Modified by young #Modified by young
# (show_error_not_found; return) unless @entries # (show_error_not_found; return) unless @entries
@changesets = @repository.latest_changesets(@path, @rev) g = Gitlab.client
@changesets = g.commits(@project.gpid, :ref_name => @rev)
# @changesets = @repository.latest_changesets(@path, @rev)
# @changesets_count = @repository.latest_changesets(@path, @rev).count
@changesets_all_count = @project.gpid.nil? ? 0 : g.project(@project.gpid).commit_count
# 访问该页面的是会后则刷新
if @project.project_score.nil?
ProjectScore.create(:project_id => @project.id, :score => false)
end
if @changesets_all_count != @project.project_score.changeset_num && @changesets_all_count != 0
update_commits_count(@project, @changesets_all_count)
end
# end
@changesets_latest_coimmit = @changesets[0]
unless @changesets[0].blank?
update_commits_date(@project, @changesets_latest_coimmit)
end
@properties = @repository.properties(@path, @rev) @properties = @repository.properties(@path, @rev)
@repositories = @project.repositories @repositories = @project.repositories
@course_tag = params[:course] @course_tag = params[:course]
project_path_cut = RepositoriesHelper::PROJECT_PATH_CUT project_path_cut = RepositoriesHelper::PROJECT_PATH_CUT
ip = RepositoriesHelper::REPO_IP_ADDRESS ip = RepositoriesHelper::REPO_IP_ADDRESS
@repos_url = "http://"+@repository.login.to_s+"_"+@repository.identifier.to_s+"@"+ip.to_s+ gitlab_address = Redmine::Configuration['gitlab_address']
@repository.url.slice(project_path_cut, @repository.url.length).to_s if @repository.type.to_s == "Repository::Gitlab"
@repos_url = gitlab_address.to_s+"/"+@project.owner.to_s+"/"+@repository.identifier+"."+"git"
else
@repos_url = "http://"+@repository.login.to_s+"_"+@repository.identifier.to_s+"@"+ip.to_s + @repository.url.slice(project_path_cut, @repository.url.length).to_s
end
if @course_tag == 1 if @course_tag == 1
render :action => 'show', :layout => 'base_courses' render :action => 'show', :layout => 'base_courses'
else else
@ -293,22 +387,37 @@ update
def changes def changes
@entry = @repository.entry(@path, @rev) @entry = @repository.entry(@path, @rev)
(show_error_not_found; return) unless @entry (show_error_not_found; return) unless @entry
@changesets = @repository.latest_changesets(@path, @rev, Setting.repository_log_display_limit.to_i) g = Gitlab.client
limit = 20
#每次页面的换回值从1开始,但是gitlab的页面查询是从0开始,所以先改变page的类型减一在改回来
@commits = g.commits(@project.gpid, page:(params[:page].to_i - 1).to_s)
#add by hx
#rep_count = commit_count(@project)
#页面传递必须要str类型,但是Paginator的初始化必须要num类型,需要类型转化
@commits_count = params[:commit_count].to_i
@commits_pages = Redmine::Pagination::Paginator.new @commits_count,limit,params[:page]
@commit = g.commit(@project.gpid,@rev)
# @changesets = g.get ("/projects/#{@project.gpid}/repository/commits?#{@rev}")
#@changesets = @repository.latest_changesets(@path, @rev, Setting.repository_log_display_limit.to_i)
@properties = @repository.properties(@path, @rev) @properties = @repository.properties(@path, @rev)
@changeset = @repository.find_changeset_by_name(@rev) @changeset = @repository.find_changeset_by_name(@rev)
render :layout => 'base_projects' render :layout => 'base_projects'
end end
def revisions def revisions
@changeset_count = @repository.changesets.count @changeset_count = @repository.changesets.count
@changeset_pages = Paginator.new @changeset_count, @changeset_pages = Paginator.new @changeset_count,
per_page_option, per_page_option,
params['page'] params['page']
@changesets = @repository.changesets. @changesets = @repository.changesets.
limit(@changeset_pages.per_page). limit(@changeset_pages.per_page).
offset(@changeset_pages.offset). offset(@changeset_pages.offset).
includes(:user, :repository, :parents). includes(:user, :repository, :parents).
all all
respond_to do |format| respond_to do |format|
format.html { render :layout => 'base_projects' } format.html { render :layout => 'base_projects' }
@ -322,6 +431,7 @@ update
def entry def entry
entry_and_raw(false) entry_and_raw(false)
render :layout => 'base_projects'
end end
def entry_and_raw(is_raw) def entry_and_raw(is_raw)
@ -334,8 +444,8 @@ update
@content = @repository.cat(@path, @rev) @content = @repository.cat(@path, @rev)
(show_error_not_found; return) unless @content (show_error_not_found; return) unless @content
if is_raw || if is_raw ||
(@content.size && @content.size > Setting.file_max_size_displayed.to_i.kilobyte) || (@content.size && @content.size > Setting.file_max_size_displayed.to_i.kilobyte) ||
! is_entry_text_data?(@content, @path) ! is_entry_text_data?(@content, @path)
# Force the download # Force the download
send_opt = { :filename => filename_for_content_disposition(@path.split('/').last) } send_opt = { :filename => filename_for_content_disposition(@path.split('/').last) }
send_type = Redmine::MimeType.of(@path) send_type = Redmine::MimeType.of(@path)
@ -418,8 +528,8 @@ update
filename = "changeset_r#{@rev}" filename = "changeset_r#{@rev}"
filename << "_r#{@rev_to}" if @rev_to filename << "_r#{@rev_to}" if @rev_to
send_data @diff.join, :filename => "#{filename}.diff", send_data @diff.join, :filename => "#{filename}.diff",
:type => 'text/x-patch', :type => 'text/x-patch',
:disposition => 'attachment' :disposition => 'attachment'
else else
@diff_type = params[:type] || User.current.pref[:diff_type] || 'inline' @diff_type = params[:type] || User.current.pref[:diff_type] || 'inline'
@diff_type = 'inline' unless %w(inline sbs).include?(@diff_type) @diff_type = 'inline' unless %w(inline sbs).include?(@diff_type)
@ -430,7 +540,7 @@ update
User.current.preference.save User.current.preference.save
end end
@cache_key = "repositories/diff/#{@repository.id}/" + @cache_key = "repositories/diff/#{@repository.id}/" +
Digest::MD5.hexdigest("#{@path}-#{@rev}-#{@rev_to}-#{@diff_type}-#{current_language}") Digest::MD5.hexdigest("#{@path}-#{@rev}-#{@rev_to}-#{@diff_type}-#{current_language}")
unless read_fragment(@cache_key) unless read_fragment(@cache_key)
@diff = @repository.diff(@path, @rev, @rev_to) @diff = @repository.diff(@path, @rev, @rev_to)
unless @diff unless @diff
@ -457,16 +567,16 @@ update
def graph def graph
data = nil data = nil
case params[:graph] case params[:graph]
when "commits_per_month" when "commits_per_month"
data = graph_commits_per_month(@repository) data = graph_commits_per_month(@repository)
when "commits_per_author" when "commits_per_author"
data = graph_commits_per_author(@repository) data = graph_commits_per_author(@repository)
when "author_commits_per_month" when "author_commits_per_month"
data = graph_author_commits_per_month(@repository) data = graph_author_commits_per_month(@repository)
when "author_commits_six_month" when "author_commits_six_month"
data = author_commits_six_month(@repository) data = author_commits_six_month(@repository)
when "author_code_six_months" when "author_code_six_months"
data = author_code_six_month(@repository) data = author_code_six_month(@repository)
end end
if data if data
headers["Content-Type"] = "image/svg+xml" headers["Content-Type"] = "image/svg+xml"
@ -477,12 +587,21 @@ update
end end
private private
# 更新项目统计数
def update_commits_count project, count
project.project_score.update_attribute(:changeset_num, count)
end
# 更新项目提交次数时间
def update_commits_date project, date
project.project_score.update_attribute(:commit_time, date.created_at)
end
def find_repository def find_repository
@repository = Repository.find(params[:id]) @repository = Repository.find(params[:id])
@project = @repository.project @project = @repository.project
rescue ActiveRecord::RecordNotFound rescue ActiveRecord::RecordNotFound
render_404 render_404
end end
REV_PARAM_RE = %r{\A[a-f0-9]*\Z}i REV_PARAM_RE = %r{\A[a-f0-9]*\Z}i
@ -546,14 +665,14 @@ update
@date_from = @date_to << 11 @date_from = @date_to << 11
@date_from = Date.civil(@date_from.year, @date_from.month, 1) @date_from = Date.civil(@date_from.year, @date_from.month, 1)
commits_by_day = Changeset.count( commits_by_day = Changeset.count(
:all, :group => :commit_date, :all, :group => :commit_date,
:conditions => ["repository_id = ? AND commit_date BETWEEN ? AND ?", repository.id, @date_from, @date_to]) :conditions => ["repository_id = ? AND commit_date BETWEEN ? AND ?", repository.id, @date_from, @date_to])
commits_by_month = [0] * 12 commits_by_month = [0] * 12
commits_by_day.each {|c| commits_by_month[(@date_to.month - c.first.to_date.month) % 12] += c.last } commits_by_day.each {|c| commits_by_month[(@date_to.month - c.first.to_date.month) % 12] += c.last }
changes_by_day = Change.count( changes_by_day = Change.count(
:all, :group => :commit_date, :include => :changeset, :all, :group => :commit_date, :include => :changeset,
:conditions => ["#{Changeset.table_name}.repository_id = ? AND #{Changeset.table_name}.commit_date BETWEEN ? AND ?", repository.id, @date_from, @date_to]) :conditions => ["#{Changeset.table_name}.repository_id = ? AND #{Changeset.table_name}.commit_date BETWEEN ? AND ?", repository.id, @date_from, @date_to])
changes_by_month = [0] * 12 changes_by_month = [0] * 12
changes_by_day.each {|c| changes_by_month[(@date_to.month - c.first.to_date.month) % 12] += c.last } changes_by_day.each {|c| changes_by_month[(@date_to.month - c.first.to_date.month) % 12] += c.last }
@ -561,26 +680,26 @@ update
12.times {|m| fields << month_name(((Date.today.month - 1 - m) % 12) + 1)} 12.times {|m| fields << month_name(((Date.today.month - 1 - m) % 12) + 1)}
graph = SVG::Graph::Bar.new( graph = SVG::Graph::Bar.new(
:height => 300, :height => 300,
:width => 600, :width => 600,
:fields => fields.reverse, :fields => fields.reverse,
:stack => :side, :stack => :side,
:scale_integers => true, :scale_integers => true,
:step_x_labels => 2, :step_x_labels => 2,
:show_data_values => true, :show_data_values => true,
:graph_title => l(:label_commits_per_month), :graph_title => l(:label_commits_per_month),
:show_graph_title => true :show_graph_title => true
) )
# 具状图 # 具状图
graph.add_data( graph.add_data(
:data => commits_by_month[0..11].reverse, :data => commits_by_month[0..11].reverse,
:title => l(:label_revision_plural) :title => l(:label_revision_plural)
) )
graph.add_data( graph.add_data(
:data => changes_by_month[0..11].reverse, :data => changes_by_month[0..11].reverse,
:title => l(:label_change_plural) :title => l(:label_change_plural)
) )
graph.burn graph.burn
@ -605,23 +724,23 @@ update
fields = fields.collect {|c| c.gsub(%r{<.+@.+>}, '') } fields = fields.collect {|c| c.gsub(%r{<.+@.+>}, '') }
graph = SVG::Graph::BarHorizontal.new( graph = SVG::Graph::BarHorizontal.new(
:height => 400, :height => 400,
:width => 600, :width => 600,
:fields => fields, :fields => fields,
:stack => :side, :stack => :side,
:scale_integers => true, :scale_integers => true,
:show_data_values => true, :show_data_values => true,
:rotate_y_labels => false, :rotate_y_labels => false,
:graph_title => l(:label_commits_per_author), :graph_title => l(:label_commits_per_author),
:show_graph_title => true :show_graph_title => true
) )
graph.add_data( graph.add_data(
:data => commits_data, :data => commits_data,
:title => l(:label_revision_plural) :title => l(:label_revision_plural)
) )
graph.add_data( graph.add_data(
:data => changes_data, :data => changes_data,
:title => l(:label_change_plural) :title => l(:label_change_plural)
) )
graph.burn graph.burn
end end
@ -632,7 +751,7 @@ update
@date_from = @date_to << 12 @date_from = @date_to << 12
@date_from = Date.civil(@date_from.year, @date_from.month, @date_from.day) @date_from = Date.civil(@date_from.year, @date_from.month, @date_from.day)
commits_by_author = Changeset.count(:all, :group => :committer, commits_by_author = Changeset.count(:all, :group => :committer,
:conditions => ["#{Changeset.table_name}.repository_id = ? AND #{Changeset.table_name}.commit_date BETWEEN ? AND ?", repository.id, @date_from, @date_to]) :conditions => ["#{Changeset.table_name}.repository_id = ? AND #{Changeset.table_name}.commit_date BETWEEN ? AND ?", repository.id, @date_from, @date_to])
commits_by_author = commits_by_author.to_a.sort! {|x, y| x.last <=> y.last}.last(25) commits_by_author = commits_by_author.to_a.sort! {|x, y| x.last <=> y.last}.last(25)
fields = commits_by_author.collect {|r| r.first} fields = commits_by_author.collect {|r| r.first}

@ -5,14 +5,18 @@ class SchoolController < ApplicationController
def upload def upload
uploaded_io = params[:logo] uploaded_io = params[:logo]
school_id ||= params[:id] school_id ||= params[:id]
s1 = School.find(school_id)
unless uploaded_io.nil? unless uploaded_io.nil?
File.open(Rails.root.join('public', 'images', 'school', school_id.to_s+'.png'), 'wb') do |file| File.open(Rails.root.join('public', 'images', 'school', school_id.to_s+'.png'), 'wb') do |file|
file.write(uploaded_io.read) file.write(uploaded_io.read)
end end
s1 = School.find(school_id)
s1.logo_link = '/images/school/'+school_id.to_s+'.png' s1.logo_link = '/images/school/'+school_id.to_s+'.png'
s1.save
end end
s1.name = params[:name] unless params[:name].blank?
s1.province = params[:province] unless params[:province].blank?
s1.save
redirect_to admin_schools_url(:school_name => params[:school_name]) redirect_to admin_schools_url(:school_name => params[:school_name])
end end
@ -105,4 +109,45 @@ class SchoolController < ApplicationController
render :text => options render :text => options
end end
#根据学校名字或者拼音来查询
def on_search
condition = "#{params[:name].strip}".gsub(" ","")
#将条件截断为汉字和拼音(全汉字 或者 全拼音 或者 汉字和拼音),
#获取拼音的第一次出现的位置
chinese = []
pinyin = []
condition.scan(/./).each_with_index do |char,index|
if char =~ /[a-zA-Z0-9]/
pinyin << char
elsif char =~ /\'/
else
chinese << char
end
end
if(condition == '')
@school = School.reorder('pinyin').page((params[:page].to_i || 1) - 1).per(100)
@school_count = School.count
else
@school = School.where("name like '%#{chinese.join("")}%' and pinyin like '%#{pinyin.join("")}%'").reorder('pinyin').page((params[:page].to_i || 1) - 1).per(100)
@school_count = School.where("name like '%#{chinese.join("")}%' and pinyin like '%#{pinyin.join("")}%'").count
end
result = []
# @school.each do |sc|
# result << {:value=>sc.name,:data=>sc.id}
# end
render :json =>{ :schools => @school,:count=>@school_count}.to_json
end
#添加学校
def add_school
@school = School.new
@school.name = params[:name].strip
@school.pinyin = Pinyin.t(params[:name].strip, splitter: '')
@school.save
respond_to do |format|
format.js
end
end
end end

@ -0,0 +1,43 @@
class ShieldActivitiesController < ApplicationController
def create
if params[:org_id]
if params[:project_id]
ShieldActivity.create(:container_type => 'Organization', :container_id => params[:org_id].to_i, :shield_type => 'Project', :shield_id => params[:project_id].to_i)
elsif params[:course_id]
ShieldActivity.create(:container_type => 'Organization', :container_id => params[:org_id].to_i, :shield_type => 'Course', :shield_id => params[:course_id].to_i)
end
elsif params[:user_id]
if params[:project_id]
ShieldActivity.create(:container_type => 'User', :container_id => params[:user_id].to_i, :shield_type => 'Project', :shield_id => params[:project_id].to_i)
elsif params[:course_id]
ShieldActivity.create(:container_type => 'User', :container_id => params[:user_id].to_i, :shield_type => 'Course', :shield_id => params[:course_id].to_i)
end
end
end
def show_acts
if params[:org_id]
if params[:project_id]
ShieldActivity.where("container_type='Organization' and container_id=#{params[:org_id].to_i} and shield_type='Project' and shield_id=#{params[:project_id]}").each do |act|
act.destroy
end
# ShieldActivity.create(:container_type => 'Organization', :container_id => params[:org_id].to_i, :shield_type => 'Project', :shield_id => params[:project_id].to_i)
elsif params[:course_id]
ShieldActivity.where("container_type='Organization' and container_id=#{params[:org_id].to_i} and shield_type='Course' and shield_id=#{params[:course_id]}").each do |act|
act.destroy
end
end
elsif params[:user_id]
if params[:project_id]
ShieldActivity.where("container_type='User' and container_id=#{params[:user_id].to_i} and shield_type='Project' and shield_id=#{params[:project_id]}").each do |act|
act.destroy
end
# ShieldActivity.create(:container_type => 'Organization', :container_id => params[:org_id].to_i, :shield_type => 'Project', :shield_id => params[:project_id].to_i)
elsif params[:course_id]
ShieldActivity.where("container_type='User' and container_id=#{params[:user_id].to_i} and shield_type='Course' and shield_id=#{params[:course_id]}").each do |act|
act.destroy
end
end
end
end
end

@ -207,7 +207,7 @@ class SoftapplicationsController < ApplicationController
@softapplication.destroy @softapplication.destroy
respond_to do |format| respond_to do |format|
format.html { redirect_to home_url } format.html { redirect_to signin_path }
format.json { head :no_content } format.json { head :no_content }
end end
end end

@ -84,7 +84,7 @@ class StoresController < ApplicationController
respond_to do |format| respond_to do |format|
format.xls { format.xls {
send_data(homework_to_xls(attachments), :type => "text/excel;charset=utf-8; header=present", send_data(homework_to_xls(attachments), :type => "text/excel;charset=utf-8; header=present",
:filename => "#{l(:label_file_lost_list)}.xls") :filename => filename_for_content_disposition("#{l(:label_file_lost_list)}.xls") )
} }
end end
end end

File diff suppressed because it is too large Load Diff

@ -0,0 +1,10 @@
class SubfieldSubdomainDirsController < ApplicationController
def update
@org_subfield = OrgSubfield.find(params[:org_subfield_id])
if @org_subfield.subfield_subdomain_dir
@org_subfield.subfield_subdomain_dir.update_attribute(:name, :params[:sub_dir_name])
else
SubfieldSubdomainDir.create(:org_subfield_id => @org_subfield.id, :name => params[:sub_dir_name])
end
end
end

@ -0,0 +1,97 @@
class SystemMessagesController < ApplicationController
# before_filter :message_author, :only => [:show]
#
# def message_author
# if(!User.current.logged? && !token.nil?)
#
# User.current =try_to_autologin1
# end
# if @system_messages
# render_403 :message => :notice_not_authorized_message
# else
# deny_access
# end
# end
def index
@system_messages = SystemMessage.all
end
# def show
# @system_messages = SystemMessage.find(params[:id])
# end
# GET /products/new
# def new
# @product = Product.new
# end
# GET /products/1/edit
# def edit
# end
# POST /products
# POST /products.json
def create
unless User.current.admin?
render_403
return
end
@system_messages = SystemMessage.new
@system_messages.description = params[:system_message][:description]
@system_messages.subject = params[:system_message][:subject]
@system_messages.user_id = User.current.id
# @system_messages.save_attachments(params[:attachments])
respond_to do |format|
if @system_messages.save
format.html {redirect_to user_system_messages_path(User.current)}
flash[:notice] = l(:notice_successful_message)
else
if params[:system_messages][:description].empty?
flash[:error] = l(:label_content_blank_fail)
else
flash[:error] = l(:label_admin_message_fail)
end
format.html {redirect_to admin_messages_path}
end
end
end
# PATCH/PUT /products/1
# PATCH/PUT /products/1.json
# def update
# respond_to do |format|
# if @product.update(product_params)
# format.html { redirect_to @product, notice: 'Product was successfully updated.' }
# format.json { render :show, status: :ok, location: @product }
# else
# format.html { render :edit }
# format.json { render json: @product.errors, status: :unprocessable_entity }
# end
# end
# end
# DELETE /products/1
# DELETE /products/1.json
# def destroy
# @system_messages.destroy
# respond_to do |format|
# format.html { redirect_to products_url, notice: 'Product was successfully destroyed.' }
# format.json { head :no_content }
# end
# end
# private
# # Use callbacks to share common setup or constraints between actions.
# def set_product
# @product = Product.find(params[:id])
# end
#
# # Never trust parameters from the scary internet, only allow the white list through.
# def message_params
# params.require(:admin_system_messages).permit(:content)
# end
end

@ -15,6 +15,7 @@ class TagsController < ApplicationController
include ContestsHelper include ContestsHelper
include ActsAsTaggableOn::TagsHelper include ActsAsTaggableOn::TagsHelper
include TagsHelper include TagsHelper
include FilesHelper
helper :projects helper :projects
helper :courses helper :courses
helper :tags helper :tags
@ -226,10 +227,281 @@ class TagsController < ApplicationController
@tag_list = get_course_tag_list @course @tag_list = get_course_tag_list @course
@select_tag_name = params[:select_tag_name] @select_tag_name = params[:select_tag_name]
end end
if @obj && @object_flag == '6' && @obj.container.kind_of?(Project)
@project = @obj.container
@tag_list = get_course_tag_list @project
@select_tag_name = params[:select_tag_name]
end
if @obj && @object_flag == '6' && @obj.container.kind_of?(OrgSubfield)
@org_subfield = @obj.container
@tag_list = get_org_subfield_tag_list @org_subfield
@select_tag_name = params[:select_tag_name]
end
# end # end
end end
end end
#更新某个tag名称
def update_tag_name
@tag_name = params[:tagName]
@rename_tag_name = params[:renameName]
@taggable_id = params[:taggableId]
@taggable_type = numbers_to_object_type(params[:taggableType])
@course_id = params[:courseId]
@rename_tag = (ActsAsTaggableOn::Tag.find_by_name(@rename_tag_name)) #查找重命名后的tag
@tag_id = (ActsAsTaggableOn::Tag.find_by_name(@tag_name)).id #重命名前的tag_id
@taggings = ActsAsTaggableOn::Tagging.find_by_tag_id_and_taggable_id_and_taggable_type(@tag_id,@taggable_id,@taggable_type) unless @taggable_id.blank?
@obj = get_object(@taggable_id,params[:taggableType]) unless @taggable_id.blank?
if @taggable_id.blank? #如果没有传tag_id那么直接更新tag_name就好了。但是要防止 重命名后的tag存在。
if @course_id
course = Course.find @course_id
if course
course.attachments.each do |attachment|
taggings = ActsAsTaggableOn::Tagging.find_by_tag_id_and_taggable_id_and_taggable_type(@tag_id,attachment.id,attachment.class)
if taggings
taggings.delete
attachment.tag_list.add(@rename_tag_name.split(","))
attachment.save
end
end
end
end
else
if(@rename_tag.nil?) #这次命名的是新的tag
# 是否还有其他记录 引用了 tag_id
@tagging = ActsAsTaggableOn::Tagging.where("tag_id = #{@tag_id}")
# 如果taggings表中记录为 1 ,那么改变@tag_id对应的tag的名字
if @tagging.count == 1
@tag = ActsAsTaggableOn::Tag.find_by_id(@tag_id)
@tag.update_attributes({:name=>@rename_tag_name})
else #如果tagging表中的记录大于1那么就要新增tag记录
unless @obj.nil?
@obj.tag_list.add(@rename_tag_name.split(","))
@obj.save
end
#删除原来的对应的taggings的记录
unless @taggings.nil?
@taggings.delete
end
end
else #这是已有的tag
# 更改taggings记录里的tag_id
unless @taggings.nil?
@taggings.update_attributes({:tag_id=>@rename_tag.id})
end
end
end
@obj_flag = params[:taggableType]
if @obj && @obj_flag == '6' && @obj.container.kind_of?(Course)
@course = @obj.container
@tag_list = @tag_list = get_course_tag_list @course
elsif @course_id
@course = Course.find(@course_id)
@tag_list = get_course_tag_list @course
#这里要引用FilesController里的逻辑了。将资源库当前的文件列表刷新一遍。
@flag = params[:flag] || false
sort = ""
@sort = ""
@order = ""
@is_remote = false
@isproject = false
sort = "#{Attachment.table_name}.created_on desc"
@containers = [ Course.includes(:attachments).reorder(sort).find(@course.id)]
show_attachments @containers
elsif @obj && @obj_flag == '5'
@forum = @obj
end
respond_to do |format|
format.js
end
end
def update_project_tag_name
@tag_name = params[:tagName]
@rename_tag_name = params[:renameName]
@taggable_id = params[:taggableId]
@taggable_type = numbers_to_object_type(params[:taggableType])
@project_id = params[:projectId]
@rename_tag = (ActsAsTaggableOn::Tag.find_by_name(@rename_tag_name)) #查找重命名后的tag
@tag_id = (ActsAsTaggableOn::Tag.find_by_name(@tag_name)).id #重命名前的tag_id
@taggings = ActsAsTaggableOn::Tagging.find_by_tag_id_and_taggable_id_and_taggable_type(@tag_id,@taggable_id,@taggable_type) unless @taggable_id.blank?
@obj = get_object(@taggable_id,params[:taggableType]) unless @taggable_id.blank?
if @taggable_id.blank? #如果没有传tag_id那么直接更新tag_name就好了。但是要防止 重命名后的tag存在。
if @project_id
project = Project.find @project_id
if project
project.attachments.each do |attachment|
taggings = ActsAsTaggableOn::Tagging.find_by_tag_id_and_taggable_id_and_taggable_type(@tag_id,attachment.id,attachment.class)
if taggings
taggings.delete
attachment.tag_list.add(@rename_tag_name.split(","))
attachment.save
end
end
end
end
else
if(@rename_tag.nil?) #这次命名的是新的tag
# 是否还有其他记录 引用了 tag_id
@tagging = ActsAsTaggableOn::Tagging.where("tag_id = #{@tag_id}")
# 如果taggings表中记录为 1 ,那么改变@tag_id对应的tag的名字
if @tagging.count == 1
@tag = ActsAsTaggableOn::Tag.find_by_id(@tag_id)
@tag.update_attributes({:name=>@rename_tag_name})
else #如果tagging表中的记录大于1那么就要新增tag记录
unless @obj.nil?
@obj.tag_list.add(@rename_tag_name.split(","))
@obj.save
end
#删除原来的对应的taggings的记录
unless @taggings.nil?
@taggings.delete
end
end
else #这是已有的tag
# 更改taggings记录里的tag_id
unless @taggings.nil?
@taggings.update_attributes({:tag_id=>@rename_tag.id})
end
end
end
@obj_flag = params[:taggableType]
if @obj && @obj_flag == '6' && @obj.container.kind_of?(Project)
@project = @obj.container
@tag_list = @tag_list = get_course_tag_list @project
elsif @project_id
@project = Project.find(@project_id)
@tag_list = get_project_tag_list @project
#这里要引用FilesController里的逻辑了。将资源库当前的文件列表刷新一遍。
@flag = params[:flag] || false
sort = ""
@sort = ""
@order = ""
@is_remote = false
@isproject = false
sort = "#{Attachment.table_name}.created_on desc"
@containers = [ Project.includes(:attachments).reorder(sort).find(@project.id)]
show_attachments @containers
elsif @obj && @obj_flag == '5'
@forum = @obj
end
respond_to do |format|
format.js
end
end
def update_org_subfield_tag_name
@tag_name = params[:tagName]
@rename_tag_name = params[:renameName]
@taggable_id = params[:taggableId]
@taggable_type = numbers_to_object_type(params[:taggableType])
@rename_tag = (ActsAsTaggableOn::Tag.find_by_name(@rename_tag_name)) #查找重命名后的tag
@tag_id = (ActsAsTaggableOn::Tag.find_by_name(@tag_name)).id #重命名前的tag_id
@taggings = ActsAsTaggableOn::Tagging.find_by_tag_id_and_taggable_id_and_taggable_type(@tag_id,@taggable_id,@taggable_type) unless @taggable_id.blank?
@obj = get_object(@taggable_id,params[:taggableType]) unless @taggable_id.blank?
if @taggable_id.blank? #如果没有传tag_id那么直接更新tag_name就好了。但是要防止 重命名后的tag存在。
if params[:org_subfield_id]
org_subfield = OrgSubfield.find params[:org_subfield_id]
if org_subfield
org_subfield.attachments.each do |attachment|
taggings = ActsAsTaggableOn::Tagging.find_by_tag_id_and_taggable_id_and_taggable_type(@tag_id,attachment.id,attachment.class)
if taggings
taggings.delete
attachment.tag_list.add(@rename_tag_name.split(","))
attachment.save
end
end
end
end
else
if(@rename_tag.nil?) #这次命名的是新的tag
# 是否还有其他记录 引用了 tag_id
@tagging = ActsAsTaggableOn::Tagging.where("tag_id = #{@tag_id}")
# 如果taggings表中记录为 1 ,那么改变@tag_id对应的tag的名字
if @tagging.count == 1
@tag = ActsAsTaggableOn::Tag.find_by_id(@tag_id)
@tag.update_attributes({:name=>@rename_tag_name})
else #如果tagging表中的记录大于1那么就要新增tag记录
unless @obj.nil?
@obj.tag_list.add(@rename_tag_name.split(","))
@obj.save
end
#删除原来的对应的taggings的记录
unless @taggings.nil?
@taggings.delete
end
end
else #这是已有的tag
# 更改taggings记录里的tag_id
unless @taggings.nil?
@taggings.update_attributes({:tag_id=>@rename_tag.id})
end
end
end
@obj_flag = params[:taggableType]
if @obj && @obj_flag == '6' && @obj.container.kind_of?(OrgSubfield)
@org_subfield = @obj.container
@tag_list = @tag_list = get_org_subfield_tag_list @org_subfield
elsif params[:org_subfield_id]
@org_subfield = OrgSubfield.find(params[:org_subfield_id])
@tag_list = get_org_subfield_tag_list @org_subfield
#这里要引用FilesController里的逻辑了。将资源库当前的文件列表刷新一遍。
@flag = params[:flag] || false
sort = ""
@sort = ""
@order = ""
@is_remote = false
@isproject = false
sort = "#{Attachment.table_name}.created_on desc"
@containers = [ OrgSubfield.includes(:attachments).reorder(sort).find(@org_subfield.id)]
show_attachments @containers
elsif @obj && @obj_flag == '5'
@forum = @obj
end
respond_to do |format|
format.js
end
end
def show_attachments obj
@attachments = []
obj.each do |container|
@attachments += container.attachments
end
@all_attachments = User.current.admin? ? @attachments : visable_attachemnts(@attachments)
@limit = 10
@feedback_count = @all_attachments.count
@feedback_pages = Paginator.new @feedback_count, @limit, params['page']
@offset ||= @feedback_pages.offset
#@curse_attachments_all = @all_attachments[@offset, @limit]
@obj_attachments = paginateHelper @all_attachments,10
end
def tag_save def tag_save
@select_tag_name = params[:tag_for_save][:tag_name] @select_tag_name = params[:tag_for_save][:tag_name]
@tags = params[:tag_for_save][:name] @tags = params[:tag_for_save][:name]
@ -274,6 +546,14 @@ class TagsController < ApplicationController
@course = @obj.container @course = @obj.container
@tag_list = @tag_list = get_course_tag_list @course @tag_list = @tag_list = get_course_tag_list @course
end end
if @obj && @obj_flag == '6' && @obj.container.kind_of?(Project)
@project = @obj.container
@tag_list = @tag_list = get_project_tag_list @project
end
if @obj && @obj_flag == '6' && @obj.container.kind_of?(OrgSubfield)
@org_subfield = @obj.container
@tag_list = @tag_list = get_org_subfield_tag_list @org_subfield
end
respond_to do |format| respond_to do |format|
format.js format.js
format.html format.html

File diff suppressed because it is too large Load Diff

@ -22,9 +22,26 @@ class WatchersController < ApplicationController
def watch def watch
s = WatchesService.new s = WatchesService.new
watchables = s.watch params.merge(:current_user_id => User.current.id) watchables = s.watch params.merge(:current_user_id => User.current.id)
if params[:action_name] == 'watch'
limit = 10;
query = User.watched_by(params[:target_id]);
@obj_count = query.count();
@obj_pages = Paginator.new @obj_count,limit,params['page']
@list = query.order("#{Watcher.table_name}.id desc").limit(limit).offset(@obj_pages.offset).all();
@action = 'watch'
elsif params[:action_name] == 'fans'
limit = 10;
query = User.find(params[:target_id]).watcher_users;
@obj_count = query.count();
@obj_pages = Paginator.new @obj_count,limit,params['page']
@list = query.order("#{Watcher.table_name}.id desc").limit(limit).offset(@obj_pages.offset).all();
@action = 'fans'
else
end
respond_to do |format| respond_to do |format|
format.html { redirect_to_referer_or {render :text => (true ? 'Watcher added.' : 'Watcher removed.'), :layout => true}} format.html { redirect_to_referer_or {render :text => (true ? 'Watcher added.' : 'Watcher removed.'), :layout => true}}
format.js { render :partial => 'set_watcher', :locals => {:user => User.current, :watched => watchables,:params=>params,:opt=>'add'} } format.js { render :partial => 'set_watcher', :locals => {:user => User.current, :watched => watchables,:params=>params,:opt=>'add',:list => @list,:action_name=>params[:action_name],:page=>params[:page],:count=>@obj_count} }
end end
rescue Exception => e rescue Exception => e
if e.message == "404" if e.message == "404"
@ -38,9 +55,25 @@ class WatchersController < ApplicationController
def unwatch def unwatch
s = WatchesService.new s = WatchesService.new
watchables = s.unwatch params.merge(:current_user_id => User.current.id) watchables = s.unwatch params.merge(:current_user_id => User.current.id)
if params[:action_name] == 'watch'
limit = 10;
query = User.watched_by(params[:target_id]);
@obj_count = query.count();
@obj_pages = Paginator.new @obj_count,limit,params['page']
@list = query.order("#{Watcher.table_name}.id desc").limit(limit).offset(@obj_pages.offset).all();
@action = 'watch'
elsif params[:action_name] == 'fans'
limit = 10;
query = User.find(params[:target_id]).watcher_users;
@obj_count = query.count();
@obj_pages = Paginator.new @obj_count,limit,params['page']
@list = query.order("#{Watcher.table_name}.id desc").limit(limit).offset(@obj_pages.offset).all();
@action = 'fans'
else
end
respond_to do |format| respond_to do |format|
format.html { redirect_to_referer_or {render :text => (false ? 'Watcher added.' : 'Watcher removed.'), :layout => true}} format.html { redirect_to_referer_or {render :text => (false ? 'Watcher added.' : 'Watcher removed.'), :layout => true}}
format.js { render :partial => 'set_watcher', :locals => {:user => User.current, :watched => watchables,:params=>params,:opt=>'delete'} } format.js { render :partial => 'set_watcher', :locals => {:user => User.current, :watched => watchables,:params=>params,:opt=>'delete',:list=>@list,:action_name=>params[:action_name],:page=>params[:page],:count=>@obj_count} }
end end
rescue Exception => e rescue Exception => e
if e.message == "404" if e.message == "404"

@ -27,7 +27,8 @@ class WelcomeController < ApplicationController
def index def index
# 企业版定制: params[:project]为传过来的参数 # 企业版定制: params[:project]为传过来的参数
redirect_to signin_path
return
unless params[:organization].nil? unless params[:organization].nil?
@organization = Organization.find params[:organization] @organization = Organization.find params[:organization]
# @organization_projects = Project.joins(:project_status).joins("LEFT JOIN project_scores ON projects.id = project_scores.project_id").where("projects.organization_id = ?", @organization.id).order("score DESC").limit(10).all # @organization_projects = Project.joins(:project_status).joins("LEFT JOIN project_scores ON projects.id = project_scores.project_id").where("projects.organization_id = ?", @organization.id).order("score DESC").limit(10).all
@ -95,11 +96,14 @@ class WelcomeController < ApplicationController
@projects = Project.all_public.active @projects = Project.all_public.active
render :layout => false, :content_type => 'text/plain' render :layout => false, :content_type => 'text/plain'
end end
def course def course
@course_page = FirstPage.find_by_page_type('course') redirect_to signin_path
@school_id = params[:school_id] || User.current.user_extensions.school.try(:id) || 117 return
@logoLink ||= logolink() #
# @course_page = FirstPage.find_by_page_type('course')
# @school_id = params[:school_id] || User.current.user_extensions.school.try(:id) || 117
# @logoLink ||= logolink()
end end
def logolink() def logolink()
@ -139,69 +143,149 @@ class WelcomeController < ApplicationController
def contest def contest
@contest_page = FirstPage.find_by_page_type('contest') redirect_to signin_path
@contest_notifications = Contestnotification.order("created_at desc").limit(5) return
# @contest_page = FirstPage.find_by_page_type('contest')
# @contest_notifications = Contestnotification.order("created_at desc").limit(5)
end end
def search def search
search_condition = params[:q] @name = params[:q]
search_type = params[:search_type].to_sym unless search_condition.blank? @search_type = params[:search_type]
search_by = params[:search_by] case params[:search_type]
when 'all'
@alls = Elasticsearch::Model.search({
query: {
multi_match: {
query: @name,
type:"most_fields",
operator: "or",
fields: ['login', 'firstname','lastname','name','description^0.5','filename','subject','content^0.5']
}
},
highlight: {
pre_tags: ['<span class="c_red">'],
post_tags: ['</span>'],
fields: {
login: {},
firstname: {},
lastname: {},
name:{},
description:{},
filename:{},
subject:{},
content:{}
}
}
},[User,Course,Attachment,Project,Memo] ).page(params[:page] || 1).per(20).results
when 'user'
@users = User.search(@name).page(params[:page] || 1).per(20)
when 'project'
@projects = Project.search(@name).page(params[:page] || 1).per(20).results
when 'course'
@courses = Course.search(@name).page(params[:page] || 1).per(20).results
when 'attachment'
@attachments = Attachment.search(@name).page(params[:page] || 1).per(20).results
when 'memo'
@memos = Memo.search(@name).page(params[:page] || 1).per(20).results
else
@alls = Elasticsearch::Model.search({
query: {
multi_match: {
query: @name,
type:"most_fields",
operator: "or",
fields: ['login', 'firstname','lastname','name','description^0.5','filename','subject','content^0.5']
}
},
highlight: {
pre_tags: ['<span class="c_red">'],
post_tags: ['</span>'],
fields: {
login: {},
firstname: {},
lastname: {},
name:{},
description:{},
filename:{},
subject:{},
content:{}
}
}
},[User,Course,Attachment,Project,Memo] ).page(params[:page] || 1).per(20).results
if search_type.nil? && params[:contests_search] && params[:name] != ""
search_type = :contests
search_condition = params[:name]
end end
@users_count = User.search(@name).results.total
@course_count = Course.search(@name).results.total
@attach_count = Attachment.search(@name).results.total
@project_count = Project.search(@name).results.total
@memo_count = Memo.search(@name).results.total
@total_count = Elasticsearch::Model.search({
query: {
multi_match: {
query: @name,
type:"most_fields",
operator: "or",
fields: ['login', 'firstname','lastname','name','description^0.5','filename','subject','content^0.5']
}
},
highlight: {
pre_tags: ['<span class="c_red">'],
post_tags: ['</span>'],
fields: {
login: {},
firstname: {},
lastname: {},
name:{},
description:{},
filename:{},
subject:{},
content:{}
}
}
},[User,Course,Attachment,Project,Memo] ).results.total
# search_type = params[:search_type].to_sym unless search_condition.blank?
# search_by = params[:search_by]
#
# if search_type.nil? && params[:contests_search] && params[:name] != ""
# search_type = :contests
# search_condition = params[:name]
# end
respond_to do |format| respond_to do |format|
format.html{ format.js
case search_type format.html{ render :layout=>'users_base'}
when :projects
redirect_to projects_search_url(:name => search_condition,
:project_type => Project::ProjectType_project)
when :courses
redirect_to courses_search_url(:name => search_condition)
when :contests
redirect_to contests_url(:name => search_condition)
when :users
redirect_to users_search_url(:name => search_condition,:search_by => search_by)
when :users_teacher
redirect_to users_search_url(:name => search_condition, :search_by => search_by, :role => :teacher)
when :users_student
redirect_to users_search_url(:name => search_condition, :search_by => search_by, :role => :student)
else
#redirect_to home_path, :alert => l(:label_sumbit_empty)
(redirect_to home_url, :notice => l(:label_sumbit_empty);return) #if params[:name].blank?
end
}
end end
end end
private private
# 判断网站的入口,是课程 course 则跳过index去渲染 course 方法 # 判断网站的入口,是课程 course 则跳过index去渲染 course 方法
def entry_select def entry_select
url = request.original_url.gsub('/','') # url = request.original_url.gsub('/','')
if url.include?(Setting.url_course.gsub('/','')) # if url.include?(Setting.url_course.gsub('/',''))
if @first_page.show_course == 1 # if @first_page.show_course == 1
course # course
render :course # render :course
else # else
render_404 # render_404
end # end
#
return 0 # return 0
elsif url.include?(Setting.url_contest.gsub('/','')) # elsif url.include?(Setting.url_contest.gsub('/',''))
if @first_page.show_contest == 1 # if @first_page.show_contest == 1
contest # contest
render :contest # render :contest
else # else
render_404 # render_404
end # end
#
return 0 # return 0
elsif url.include?(Setting.url_user.gsub('/','')) # elsif url.include?(Setting.url_user.gsub('/',''))
#redirect_to(:controller => "users", :action => "index") # #redirect_to(:controller => "users", :action => "index")
end # end
end end

@ -82,14 +82,14 @@ class WikiController < ApplicationController
@content = @page.content_for_version(params[:version]) @content = @page.content_for_version(params[:version])
if User.current.allowed_to?(:export_wiki_pages, @project) if User.current.allowed_to?(:export_wiki_pages, @project)
if params[:format] == 'pdf' if params[:format] == 'pdf'
send_data(wiki_page_to_pdf(@page, @project), :type => 'application/pdf', :filename => "#{@page.title}.pdf") send_data(wiki_page_to_pdf(@page, @project), :type => 'application/pdf', :filename => filename_for_content_disposition("#{@page.title}.pdf") )
return return
elsif params[:format] == 'html' elsif params[:format] == 'html'
export = render_to_string :action => 'export', :layout => false export = render_to_string :action => 'export', :layout => false
send_data(export, :type => 'text/html', :filename => "#{@page.title}.html") send_data(export, :type => 'text/html', :filename => filename_for_content_disposition("#{@page.title}.html"))
return return
elsif params[:format] == 'txt' elsif params[:format] == 'txt'
send_data(@content.text, :type => 'text/plain', :filename => "#{@page.title}.txt") send_data(@content.text, :type => 'text/plain', :filename => filename_for_content_disposition("#{@page.title}.txt") )
return return
end end
end end
@ -264,7 +264,7 @@ class WikiController < ApplicationController
end end
@page.destroy @page.destroy
respond_to do |format| respond_to do |format|
format.html { redirect_to project_wiki_index_url(@project) } format.html {redirect_to edit_project_wiki_page_url @project, @page.title}
format.api { render_api_ok } format.api { render_api_ok }
end end
end end
@ -286,7 +286,7 @@ class WikiController < ApplicationController
send_data(export, :type => 'text/html', :filename => "wiki.html") send_data(export, :type => 'text/html', :filename => "wiki.html")
} }
format.pdf { format.pdf {
send_data(wiki_pages_to_pdf(@pages, @project), :type => 'application/pdf', :filename => "#{@project.identifier}.pdf") send_data(wiki_pages_to_pdf(@pages, @project), :type => 'application/pdf', :filename => filename_for_content_disposition("#{@project.identifier}.pdf") )
} }
end end
end end

@ -3,6 +3,8 @@
class WordsController < ApplicationController class WordsController < ApplicationController
include ApplicationHelper include ApplicationHelper
before_filter :find_user, :only => [:new, :create, :destroy, :more, :back] before_filter :find_user, :only => [:new, :create, :destroy, :more, :back]
before_filter :require_login, :only => [:create_reply]
def create def create
if params[:new_form][:user_message].size>0 && User.current.logged? if params[:new_form][:user_message].size>0 && User.current.logged?
unless params[:user_id].nil? unless params[:user_id].nil?
@ -53,7 +55,15 @@ class WordsController < ApplicationController
:notes => content, :notes => content,
:is_readed => false} :is_readed => false}
@jfm = add_reply_adapter options @jfm = add_reply_adapter options
@save_succ = true if @jfm.errors.empty?
if @save_succ
update_course_activity('JournalsForMessage',parent_id)
update_user_activity('JournalsForMessage',parent_id)
update_forge_activity('JournalsForMessage',parent_id)
update_org_activity('JournalsForMessage',parent_id)
update_principal_activity('JournalsForMessage',parent_id)
(JournalsForMessage.find parent_id).update_attribute(:updated_on,Time.now)
end
respond_to do |format| respond_to do |format|
# format.html { # format.html {
# if @jfm.errors.empty? # if @jfm.errors.empty?
@ -63,27 +73,44 @@ class WordsController < ApplicationController
# end # end
# render 'test/index' # render 'test/index'
# } # }
format.js{ format.js {
@save_succ = true if @jfm.errors.empty? @user_activity_id = params[:user_activity_id]
@activity = JournalsForMessage.find(parent_id)
@is_activity = params[:is_activity]
} }
end end
end end
def destroy def destroy
@journal_destroyed = JournalsForMessage.delete_message(params[:object_id]) @journal_destroyed = JournalsForMessage.find params[:object_id]
if @journal_destroyed.jour_type == "Bid" if @journal_destroyed.destroy
@bid = Bid.find(@journal_destroyed.jour_id) if @journal_destroyed.jour_type == "Bid"
@jours_count = @bid.journals_for_messages.where('m_parent_id IS NULL').count @bid = Bid.find(@journal_destroyed.jour_id)
elsif @journal_destroyed.jour_type == "Course" @jours_count = @bid.journals_for_messages.where('m_parent_id IS NULL').count
@course = Course.find @journal_destroyed.jour_id elsif @journal_destroyed.jour_type == "Course"
@jours_count = @course.journals_for_messages.where('m_parent_id IS NULL').count @course = Course.find @journal_destroyed.jour_id
elsif @journal_destroyed.jour_type == "Principal" @jours_count = @course.journals_for_messages.where('m_parent_id IS NULL').count
@user = User.find(@journal_destroyed.jour_id) elsif @journal_destroyed.jour_type == "Principal"
@jours_count = @user.journals_for_messages.where('m_parent_id IS NULL').count @user = User.find(@journal_destroyed.jour_id)
@is_user = true @jours_count = @user.journals_for_messages.where('m_parent_id IS NULL').count
end @is_user = true
respond_to do |format| @user_activity_id = params[:user_activity_id] if params[:user_activity_id]
format.js @is_activity = params[:is_activity].to_i if params[:is_activity]
@activity = @journal_destroyed.parent if @journal_destroyed.parent
elsif @journal_destroyed.jour_type == 'HomeworkCommon'
@homework = HomeworkCommon.find @journal_destroyed.jour_id
if params[:user_activity_id]
@user_activity_id = params[:user_activity_id]
else
@user_activity_id = -1
end
@is_in_course = params[:is_in_course].to_i
@course_activity = params[:course_activity].to_i
end
respond_to do |format|
format.js
end
end end
end end
@ -200,11 +227,19 @@ class WordsController < ApplicationController
#给用户留言 #给用户留言
def leave_user_message def leave_user_message
@user = User.find(params[:id]) if User.current.logged?
if params[:new_form][:user_message].size>0 && User.current.logged? && @user @user = User.find(params[:id])
@user.add_jour(User.current, params[:new_form][:user_message]) if params[:new_form][:content].size>0 && User.current.logged? && @user
if params[:private] && params[:private] == '1'
@user.journals_for_messages << JournalsForMessage.new(:user_id => User.current.id, :notes => params[:new_form][:content], :reply_id => 0, :status => true, :is_readed => false, :private => 1)
else
@user.add_jour(User.current, params[:new_form][:content])
end
end
redirect_to feedback_path(@user)
else
render_403
end end
redirect_to feedback_path(@user)
end end
# add by nwb # add by nwb
@ -222,7 +257,39 @@ class WordsController < ApplicationController
flash[:error] = feedback.errors.full_messages[0] flash[:error] = feedback.errors.full_messages[0]
redirect_to course_feedback_url(params[:id]) redirect_to course_feedback_url(params[:id])
end end
end
#作业的回复
def leave_homework_message
if User.current.logged?
@user = User.current
@homework_common = HomeworkCommon.find(params[:id]);
if params[:homework_message].size>0 && User.current.logged? && @user
feedback = HomeworkCommon.add_homework_jour(@user, params[:homework_message], params[:id])
if (feedback.errors.empty?)
if params[:asset_id]
ids = params[:asset_id].split(',')
update_kindeditor_assets_owner ids,feedback[:id],OwnerTypeHelper::JOURNALSFORMESSAGE
end
update_course_activity(@homework_common.class,@homework_common.id)
update_user_activity(@homework_common.class,@homework_common.id)
update_org_activity(@homework_common.class,@homework_common.id)
respond_to do |format|
format.js{
@user_activity_id = params[:user_activity_id]
@is_in_course = params[:is_in_course]
@course_activity = params[:course_activity]
@homework_common_id = params[:homework_common_id]
}
end
else
flash[:error] = feedback.errors.full_messages[0]
end
end
else
render_403
end
end end
def add_brief_introdution def add_brief_introdution

@ -1,4 +1,8 @@
#coding=utf-8
require "base64"
require 'zip' require 'zip'
class ZipdownController < ApplicationController class ZipdownController < ApplicationController
#查找项目(课程) #查找项目(课程)
before_filter :find_project_by_bid_id, :only => [:assort] before_filter :find_project_by_bid_id, :only => [:assort]
@ -7,11 +11,17 @@ class ZipdownController < ApplicationController
SAVE_FOLDER = "#{Rails.root}/files" SAVE_FOLDER = "#{Rails.root}/files"
OUTPUT_FOLDER = "#{Rails.root}/files/archiveZip" OUTPUT_FOLDER = "#{Rails.root}/files/archiveZip"
#统一下载功能 #统一下载功能
def download def download
if User.current.logged? if User.current.logged?
begin begin
send_file "#{OUTPUT_FOLDER}/#{params[:file]}", :filename => filename_for_content_disposition(params[:filename]), :type => detect_content_type(params[:file]) if params[:base64file]
file = Base64.decode64(params[:base64file])
file = file.sub('*', '+')
send_file "#{OUTPUT_FOLDER}/#{file}", :filename => filename_for_content_disposition(file), :type => detect_content_type(file)
else
send_file "#{OUTPUT_FOLDER}/#{params[:file]}", :filename => filename_for_content_disposition(params[:filename]), :type => detect_content_type(params[:file])
end
rescue => e rescue => e
render file: 'public/no_file_found.html' render file: 'public/no_file_found.html'
end end
@ -107,11 +117,17 @@ class ZipdownController < ApplicationController
bid_homework_path, OUTPUT_FOLDER) bid_homework_path, OUTPUT_FOLDER)
} }
[{files:[out_file.file_path], count: 1, index: 1, [{files:[out_file.file_path], count: 1, index: 1,
real_file: out_file.file_path, file: File.basename(out_file.file_path), real_file: out_file.file_path,
file: File.basename(out_file.file_path),
base64file: encode64(File.basename(out_file.file_path)),
size:(out_file.pack_size / 1024.0 / 1024.0).round(2) size:(out_file.pack_size / 1024.0 / 1024.0).round(2)
}] }]
end end
def encode64(str)
Base64.encode64(str).sub('+', '*')
end
def zip_homework_common homework_common def zip_homework_common homework_common
bid_homework_path = [] bid_homework_path = []
digests = [] digests = []
@ -129,7 +145,9 @@ class ZipdownController < ApplicationController
bid_homework_path, OUTPUT_FOLDER) bid_homework_path, OUTPUT_FOLDER)
} }
[{files:[out_file.file_path], count: 1, index: 1, [{files:[out_file.file_path], count: 1, index: 1,
real_file: out_file.file_path, file: File.basename(out_file.file_path), real_file: out_file.file_path,
file: File.basename(out_file.file_path),
base64file: encode64(File.basename(out_file.file_path)),
size:(out_file.pack_size / 1024.0 / 1024.0).round(2) size:(out_file.pack_size / 1024.0 / 1024.0).round(2)
}] }]
end end

@ -75,7 +75,7 @@ module ApiHelper
# 学生获取课程作业的状态 # 学生获取课程作业的状态
def get_homework_status homework def get_homework_status homework
homework_status = "" homework_status = ""
if !homework.nil? if homework
if homework.homework_type == 1 && homework.homework_detail_manual if homework.homework_type == 1 && homework.homework_detail_manual
case homework.homework_detail_manual.comment_status case homework.homework_detail_manual.comment_status
when 1 when 1
@ -180,7 +180,7 @@ module ApiHelper
if timePassed < 0 if timePassed < 0
updateAtValue = "时间有问题" updateAtValue = "时间有问题"
elsif timePassed < ONE_MINUTE elsif timePassed < ONE_MINUTE
updateAtValue = "分钟前" updateAtValue = "1分钟前"
elsif timePassed < ONE_HOUR elsif timePassed < ONE_HOUR
timeIntoFormat = timePassed / ONE_MINUTE timeIntoFormat = timePassed / ONE_MINUTE
updateAtValue = timeIntoFormat.to_s + "分钟前" updateAtValue = timeIntoFormat.to_s + "分钟前"

@ -49,6 +49,50 @@ module ApplicationHelper
end end
end end
def link_to_user_version(version, options = {})
return '' unless version && version.is_a?(Version)
link_to_if version.visible?, format_version_name(version), { :controller => 'versions', :action => 'show', :id => version }, :class => "linkBlue"
end
# 判断课程是否为精品课程
def is_excellent_course course
(course.is_excellent? or course.excellent_option?) ? true : false
end
# 判断课程对成员是否可见
def visible_course?(course)
(course.is_delete? or (!course.is_public? && !User.current.member_of_course?(course))) ? false : true
end
# 获取项目/课程总分
# 发布缺陷 4分 回复缺陷 1分 提交一次 4分 讨论帖子 2分 回复帖子 1分 发布新闻 1分
def static_project_score obj
score = obj.issue_num * 4 + obj.issue_journal_num + (obj.changeset_num||0) * 4 + obj.board_num * 2 + obj.board_message_num + obj.news_num + obj.attach_num * 5
end
# 获取组织成员中文名字
def get_org_member_role_name member
case member.roles[0].name
when 'orgManager'
'管理人员'
when 'orgMember'
'组织成员'
end
end
# 判断组织左侧展开或者隐藏
def is_hide_org_left obj
if obj.nil?
return true
else
if obj.hide == 0
return true
else
return false
end
end
end
# Time 2015-03-24 16:38:05 # Time 2015-03-24 16:38:05
# Author lizanle # Author lizanle
# Description after save后需要进行资源记录的更新 # Description after save后需要进行资源记录的更新
@ -66,6 +110,50 @@ module ApplicationHelper
end end
end end
# 更新课程英雄榜得分
# user传过来必须是学生
def course_member_score(course_id,user_id,type)
course_contributor_score = CourseContributorScore.where("course_id =? and user_id =?", course_id, user_id).first
case type
when "JournalForMessage"
if course_contributor_score.nil?
CourseContributorScore.create(:course_id => course_id, :user_id => user_id, :message_num => 0, :message_reply_num => 0,
:news_reply_num => 0, :resource_num => 0, :journal_num => 1, :journal_reply_num => 0, :total_score => 1)
else
score = course_contributor_score.journal_num + 1
total_score = course_contributor_score.total_score + 1
course_contributor_score.update_attributes(:journal_num => score, :total_score => total_score)
end
when "Message"
if course_contributor_score.nil?
CourseContributorScore.create(:course_id => course_id, :user_id => user_id, :message_num => 2, :message_reply_num => 0,
:news_reply_num => 0, :resource_num => 0, :journal_num => 0, :journal_reply_num => 0, :total_score => 2)
else
score = course_contributor_score.message_num + 2
total_score = course_contributor_score.total_score + 2
course_contributor_score.update_attributes(:message_num => score, :total_score => total_score)
end
when "MessageReply"
if course_contributor_score.nil?
CourseContributorScore.create(:course_id => course_id, :user_id => user_id, :message_num => 0, :message_reply_num => 1,
:news_reply_num => 0, :resource_num => 0, :journal_num => 0, :journal_reply_num => 0, :total_score => 1)
else
score = course_contributor_score.message_reply_num + 1
total_score = course_contributor_score.total_score + 1
course_contributor_score.update_attributes(:message_reply_num => score, :total_score => total_score)
end
when "NewReply"
if course_contributor_score.nil?
CourseContributorScore.create(:course_id => course_id, :user_id => user_id, :message_num => 0, :message_reply_num => 0,
:news_reply_num => 1, :resource_num => 0, :journal_num => 0, :journal_reply_num => 0, :total_score => 1)
else
score = course_contributor_score.news_reply_num + 1
total_score = course_contributor_score.total_score + 1
course_contributor_score.update_attributes(:news_reply_num => score, :total_score => total_score)
end
end
end
# Added by young # Added by young
# Define the course menu's link class # Define the course menu's link class
# 不是数组的转化成数组然后判断当前menu_item是否在给定的列表 # 不是数组的转化成数组然后判断当前menu_item是否在给定的列表
@ -200,8 +288,10 @@ module ApplicationHelper
subject = truncate(subject, :length => 60) subject = truncate(subject, :length => 60)
end end
end end
if issue.status_id == 5 if issue.status_id == 3
s = link_to text, issue_path(issue), :class => "text_line_s", :title => title s = link_to text, issue_path(issue), :class => "text_line_s", :title => title
elsif issue.status_id == 5
s = link_to text, issue_path(issue), :class => "text_line_s del_line", :title => title
else else
s = link_to text, issue_path(issue), :class => "c_blue", :title => title s = link_to text, issue_path(issue), :class => "c_blue", :title => title
end end
@ -609,6 +699,53 @@ module ApplicationHelper
return @result return @result
end end
# 判断版本库是否初始为gitlab
def rep_is_gitlab?(project)
rep = Repository.where("project_id =? and type =?", project, "Repository::Gitlab")
return rep.blank? ? true :false
end
# 获取Gitlab版本库提交总数
def commit_count(project)
g = Gitlab.client
#add by hx
if g.commits(project.gpid , :page=>200).count > 0
count = 4020
elsif g.commits(project.gpid , :page=>25).count==0
count = count_commits(project.gpid , 0 , 25)
elsif g.commits(project.gpid , :page=>50).count ==0
count = count_commits(project.gpid , 25 , 50)+ 25 * 20
elsif g.commits(project.gpid , :page=>75).count ==0
count = count_commits(project.gpid , 50 , 75)+ 50 * 20
elsif g.commits(project.gpid , :page=>100).count== 0
count = count_commits(project.gpid , 75 , 100) + 75 * 20
elsif g.commits(project.gpid , :page=>125).count==0
count = count_commits(project.gpid , 100 , 125) + 100 * 20
elsif g.commits(project.gpid , :page=>150).count==0
count = count_commits(project.gpid , 125 , 150) + 125 * 20
else
count = count_commits(project.gpid , 150 ,200) + 150 * 20
end
end
#add by hx
def count_commits(project_id , left , right)
count = 0
(left..right).each do |page|
if $g.commits(project_id,:page => page).count == 0
break
else
count = count + $g.commits(project_id,:page => page).count
end
end
return count
end
# 获取单一gitlab项目
def gitlab_repository(project)
rep = Repository.where("project_id =? and type =?", project.id,"Repository::Gitlab" ).first
end
# 判断当前用户是否为项目管理员 # 判断当前用户是否为项目管理员
def is_project_manager?(user_id, project_id) def is_project_manager?(user_id, project_id)
@result = false @result = false
@ -760,7 +897,8 @@ module ApplicationHelper
options = args.extract_options! options = args.extract_options!
text = distance_of_time_in_words(Time.now, time) text = distance_of_time_in_words(Time.now, time)
if @project if @project
link_to(text, {:controller => 'activities', :action => 'index', :id => @project, :from => User.current.time_to_date(time)},options.reverse_merge(:title => format_time(time))) content_tag('acronym', text, options.reverse_merge(:title => format_time(time)))
# link_to(text, {:controller => 'activities', :action => 'index', :id => @project, :from => User.current.time_to_date(time)},options.reverse_merge(:title => format_time(time)))
else else
content_tag('acronym', text, options.reverse_merge(:title => format_time(time))) content_tag('acronym', text, options.reverse_merge(:title => format_time(time)))
end end
@ -836,7 +974,17 @@ module ApplicationHelper
first_page = FirstPage.find_by_page_type('project') first_page = FirstPage.find_by_page_type('project')
if args.empty? if args.empty?
title = @html_title || [] title = @html_title || []
title << @project.name if @project if @project
title << @project.name
elsif @course
title << @course.name
elsif @organization
title << @organization.name
elsif @user
title << @user.login
else
title << User.current.login
end
if first_page.nil? || first_page.web_title.nil? if first_page.nil? || first_page.web_title.nil?
title << Setting.app_title unless Setting.app_title == title.last title << Setting.app_title unless Setting.app_title == title.last
else else
@ -1651,6 +1799,13 @@ module ApplicationHelper
# #
def javascript_include_tag(*sources) def javascript_include_tag(*sources)
options = sources.last.is_a?(Hash) ? sources.pop : {} options = sources.last.is_a?(Hash) ? sources.pop : {}
@sources ||= []
sources = sources.delete_if do|source|
@sources.include?(source)
end
@sources += sources
if plugin = options.delete(:plugin) if plugin = options.delete(:plugin)
sources = sources.map do |source| sources = sources.map do |source|
if plugin if plugin
@ -1660,7 +1815,12 @@ module ApplicationHelper
end end
end end
end end
super sources, options
if sources && !sources.empty?
super(sources, options)
else
''
end
end end
def content_for(name, content = nil, &block) def content_for(name, content = nil, &block)
@ -1804,6 +1964,23 @@ module ApplicationHelper
s s
end end
def get_user_identity identity
s = ""
case identity
when 0
s = '教师'
when 1
s = '学生'
when 2
s = '组织'
when 3
s= '开发者'
else
s = '学生'
end
s
end
def get_memo def get_memo
@new_memo = Memo.new @new_memo = Memo.new
@public_forum = Forum.find(1) rescue ActiveRecord::RecordNotFound @public_forum = Forum.find(1) rescue ActiveRecord::RecordNotFound
@ -1812,7 +1989,7 @@ module ApplicationHelper
#获取用户未过期的课程 #获取用户未过期的课程
def get_user_course user def get_user_course user
courses_doing = [] courses_doing = []
user.courses.each do |course| user.courses.select("courses.*,(SELECT MAX(created_at) FROM `course_activities` WHERE course_activities.course_id = courses.id) AS a").order("a desc").each do |course|
if !course_endTime_timeout?(course) if !course_endTime_timeout?(course)
courses_doing.push course courses_doing.push course
end end
@ -1842,6 +2019,10 @@ module ApplicationHelper
elsif attachment.container.is_a?(Course) elsif attachment.container.is_a?(Course)
course = attachment.container course = attachment.container
candown= User.current.member_of_course?(course) || (course.is_public==1 && attachment.is_public == 1) candown= User.current.member_of_course?(course) || (course.is_public==1 && attachment.is_public == 1)
elsif attachment.container.is_a?(OrgSubfield)
candown = true
elsif attachment.container.is_a?(OrgDocumentComment)
candown = true
elsif (attachment.container.has_attribute?(:board) || attachment.container.has_attribute?(:board_id)) && attachment.container.board && elsif (attachment.container.has_attribute?(:board) || attachment.container.has_attribute?(:board_id)) && attachment.container.board &&
attachment.container.board.course attachment.container.board.course
course = attachment.container.board.course course = attachment.container.board.course
@ -1852,7 +2033,12 @@ module ApplicationHelper
candown = true candown = true
elsif attachment.container.class.to_s=="StudentWork" elsif attachment.container.class.to_s=="StudentWork"
candown = true candown = true
elsif attachment.container.class.to_s=="BlogComment" #博客资源允许下载
candown = true
elsif attachment.container.class.to_s=="Memo" #论坛资源允许下载
candown = true
elsif attachment.container.class.to_s == "User"
candown = (attachment.is_public == 1 || attachment.is_public == true || attachment.author_id == User.current.id)
elsif attachment.container_type == "Bid" && attachment.container && attachment.container.courses elsif attachment.container_type == "Bid" && attachment.container && attachment.container.courses
course = attachment.container.courses.first course = attachment.container.courses.first
candown = User.current.member_of_course?(attachment.container.courses.first) || (course.is_public == 1 && attachment.is_public == 1) candown = User.current.member_of_course?(attachment.container.courses.first) || (course.is_public == 1 && attachment.is_public == 1)
@ -2253,6 +2439,21 @@ module ApplicationHelper
technical_title technical_title
end end
def get_user_roll user
technical_title = ""
case user.user_extensions.identity.to_s
when "0"
technical_title = get_technical_title user
when "1"
technical_title = l(:label_account_identity_student)
when "2"
technical_title = l(:label_account_identity_enterprise)
when "3"
technical_title = l(:label_account_identity_developer)
end
technical_title
end
def ie8? def ie8?
request.env["HTTP_USER_AGENT"] =~ /MSIE 8.0/ request.env["HTTP_USER_AGENT"] =~ /MSIE 8.0/
@ -2278,27 +2479,40 @@ module ApplicationHelper
tag_list tag_list
end end
# 获取项目资源的Tag云
def get_project_tag_list project
all_attachments = project.attachments.select{|attachment| attachment.is_public? ||
(attachment.container_type == "Project" && User.current.member_of?(project))||
attachment.author_id == User.current.id
}
tag_list = attachment_tag_list all_attachments
tag_list
end
def get_org_subfield_tag_list org_subfield
all_attachments = org_subfield.attachments.select{|attachment| attachment.is_public? ||
(attachment.container_type == "OrgSubfield" && User.current.member_of_org?(org_subfield.organization))||
attachment.author_id == User.current.id
}
tag_list = attachment_tag_list all_attachments
tag_list
end
#获取匿评相关连接代码 #获取匿评相关连接代码
def homework_anonymous_comment homework def homework_anonymous_comment (homework, is_in_course, user_activity_id = -1, course_activity = -1)
if homework.homework_type == 1 && homework.homework_detail_manual #匿评作业 if Time.parse(homework.end_time.to_s).strftime("%Y-%m-%d") >= Time.now.strftime("%Y-%m-%d")
if Time.parse(homework.end_time.to_s).strftime("%Y-%m-%d") >= Time.now.strftime("%Y-%m-%d") link = link_to "启动匿评","javascript:void(0)", :class => "postOptionLink", :title => "作业截止日期之前不可以启动匿评"
link = "<span class='fr mr10 pr_join_span ' title='作业截止日期之前不可以启动匿评'>启动匿评</span>".html_safe elsif homework.student_works.count >= 2 && homework.homework_detail_manual#作业份数大于2
elsif homework.student_works.count >= 2 #作业份数大于2 case homework.homework_detail_manual.comment_status
case homework.homework_detail_manual.comment_status when 1
when 1 link = link_to '启动匿评', alert_anonymous_comment_homework_common_path(homework,:is_in_course=>is_in_course,:user_activity_id=>user_activity_id,:course_activity=>course_activity), id: "#{homework.id}_start_anonymous_comment", remote: true, disable_with: '加载中...',:class => 'postOptionLink'
link = link_to '启动匿评', alert_anonymous_comment_homework_common_path(homework), id: "#{homework.id}_start_anonymous_comment", remote: true, disable_with: '加载中...',:class => 'fr mr10 work_edit' when 2
when 2 link = link_to '关闭匿评', alert_anonymous_comment_homework_common_path(homework,:is_in_course=>is_in_course,:user_activity_id=>user_activity_id,:course_activity=>course_activity), id: "#{homework.id}_stop_anonymous_comment", remote: true,:class => 'postOptionLink'
link = link_to '关闭匿评', alert_anonymous_comment_homework_common_path(homework), id: "#{homework.id}_stop_anonymous_comment", remote: true,:class => 'fr mr10 work_edit' when 3
when 3 # link = link_to "匿评结束","javascript:void(0)", :class => "postOptionLink", :title => "匿评结束"
link = "<span class='fr pr_join_span mr10' title='匿评结束'>匿评结束</span>".html_safe
end
else
link = "<span class='fr mr10 pr_join_span ' title='学生提交作业数大于2时才可以启动匿评'>启动匿评</span>".html_safe
end end
elsif homework.homework_type == 2 && homework.homework_detail_programing #编程作业作业
link = "<span class='fr mr10 pr_join_span ' title='编程作业'>编程作业</span>".html_safe
else else
link = "<span class='fr mr10 pr_join_span ' title='未开启匿评作业不可以启动匿评'>启动匿评</span>".html_safe link = link_to "启动匿评","javascript:void(0)", :class => "postOptionLink", :title => "学生提交作业数大于等于2时才可以启动匿评"
end end
link link
end end
@ -2306,20 +2520,96 @@ module ApplicationHelper
def student_new_homework homework def student_new_homework homework
work = cur_user_works_for_homework homework work = cur_user_works_for_homework homework
if work.nil? if work.nil?
link_to l(:label_commit_homework), new_student_work_path(:homework => homework.id),:class => 'fr mr10 work_edit' link_to "提交作品", new_student_work_path(:homework => homework.id),:class => 'fr mr10 work_edit'
else else
if homework.homework_type == 1 && homework.homework_detail_manual && homework.homework_detail_manual.comment_status != 1 #匿评作业,且作业状态不是在开启匿评之前 if homework.homework_type == 1 && homework.homework_detail_manual && homework.homework_detail_manual.comment_status != 1 #匿评作业,且作业状态不是在开启匿评之前
"<span class='fr mr10 pr_join_span '>#{l(:label_edit_homework)}</span>".html_safe link_to "作品已交", "javascript:void(0);", :class => 'fr mr10 pr_join_span c_white', :title => "开启匿评后不可修改作品"
elsif homework.homework_type == 2 #编程作业不能修改作品 elsif homework.homework_type == 2 #编程作业修改作品
"<span class='fr mr10 pr_join_span ' title='编程作业不可修改作品'>作品已交</span>".html_safe if homework.homework_detail_manual && homework.homework_detail_manual.comment_status != 1
link_to "作品已交", "javascript:void(0);", :class => 'fr mr10 pr_join_span c_white', :title => "开启匿评后不可修改作品"
else
link_to "修改作品", new_student_work_path(:homework => homework.id),:class => 'fr mr10 work_edit'
end
else else
link_to l(:label_edit_homework), edit_student_work_path(work.id),:class => 'fr mr10 work_edit' link_to "修改作品", edit_student_work_path(work.id),:class => 'fr mr10 work_edit'
end
end
end
#动态列表中,确定学生是该提交还是进列表
def student_work_activity_submit_status(opt={})
default_opt = {class: 'c_blue'}.merge(opt)
is_teacher = User.current.user_extensions && User.current.user_extensions.identity == 0 && User.current.allowed_to?(:add_course, nil, :global => true)
homework = default_opt[:homework]
work = cur_user_works_for_homework homework
if work.nil? && !is_teacher
link_to "提交("+homework.student_works.count.to_s+")", new_student_work_path(:homework => homework.id,:host=> Setting.host_course), :class=> default_opt[:class]
else
link_to "提交("+homework.student_works.count.to_s+")", student_work_index_path(:homework => homework.id,:host=> Setting.host_course), :class=> default_opt[:class]
end
end
#根据传入作业确定显示为编辑作品还是新建作品,或者显示作品数量
def user_for_homework_common homework,is_teacher
if User.current.member_of_course?(homework.course)
if is_teacher #老师显示作品数量
link_to "作品(#{homework.student_works.count})",student_work_index_path(:homework => homework.id),:class => "c_blue"
else #学生显示提交作品、修改作品等按钮
work = cur_user_works_for_homework homework
project = cur_user_projects_for_homework homework
if work.nil? && Time.parse(homework.end_time.to_s).strftime("%Y-%m-%d") >= Time.now.strftime("%Y-%m-%d")
if homework.homework_type ==3 && project.nil? && homework.homework_detail_group.base_on_project == 1
link_to "提交作品(#{homework.student_works.count})","javascript:void(0)", :class => 'c_grey',:style=>"cursor:not-allowed",:title => '请先关联项目再提交作品'
else
link_to "提交作品(#{homework.student_works.count})", new_student_work_path(:homework => homework.id),:class => 'c_blue'
end
elsif work.nil? && Time.parse(homework.end_time.to_s).strftime("%Y-%m-%d") < Time.now.strftime("%Y-%m-%d")
if homework.homework_type ==3 && project.nil? && homework.homework_detail_group.base_on_project == 1
link_to "补交作品(#{homework.student_works.count})","javascript:void(0)", :class => 'c_grey',:style=>"cursor:not-allowed",:title => '请先关联项目再补交作品'
else
link_to "补交作品(#{homework.student_works.count})", new_student_work_path(:homework => homework.id),:class => 'c_red'
end
else
if homework.homework_detail_manual && homework.homework_detail_manual.comment_status == 2 #匿评作业,且作业状态不是在开启匿评之前
link_to "作品匿评", student_work_index_path(:homework => homework.id), :class => 'c_blue', :title => "开启匿评后不可修改作品"
elsif homework.homework_detail_manual && homework.homework_detail_manual.comment_status == 3
link_to "查看作品(#{homework.student_works.count})", student_work_index_path(:homework => homework.id), :class => 'c_blue', :title => "匿评已结束"
elsif homework.homework_type == 2 && Time.parse(homework.end_time.to_s).strftime("%Y-%m-%d") >= Time.now.strftime("%Y-%m-%d")#编程作业不能修改作品
link_to "修改作品(#{homework.student_works.count})", new_student_work_path(:homework => homework.id),:class => 'c_blue'
elsif Time.parse(homework.end_time.to_s).strftime("%Y-%m-%d") >= Time.now.strftime("%Y-%m-%d") && work.user_id == User.current.id
link_to "修改作品(#{homework.student_works.count})", edit_student_work_path(work.id),:class => 'c_blue'
else
link_to "查看作品(#{homework.student_works.count})", student_work_index_path(:homework => homework.id), :class => 'c_blue', :title => "作业截止后不可修改作品"
end
end
end
else
link_to "作品(#{homework.student_works.count})",student_work_index_path(:homework => homework.id),:class => "c_blue"
end
end
def relate_project homework,is_teacher,is_in_course,user_activity_id,course_activity
if User.current.member_of_course?(homework.course)
if is_teacher
#link_to "已关联(#{homework.student_work_projects.count})",student_work_index_path(:homework => homework.id),:class => "c_blue"
else
projects = cur_user_projects_for_homework homework
works = cur_user_works_for_homework homework
if works.nil? && projects.nil?
link_to "关联项目",new_student_work_project_student_work_index_path(:homework => homework.id,:is_in_course=>is_in_course,:user_activity_id=>user_activity_id,:course_activity=>course_activity),remote: true,:class=> 'c_blue', :title=> '请选择分组作业关联的项目'
elsif works.nil?
link_to "取消关联",cancel_relate_project_student_work_index_path(:homework => homework.id,:is_in_course=>is_in_course,:user_activity_id=>user_activity_id,:course_activity=>course_activity), :confirm => "您确定要取消关联吗?", remote: true,:class => "c_blue", :title=> '取消关联项目'
else
#link_to "已关联(#{homework.student_work_projects.count})",student_work_index_path(:homework => homework.id),:class => "c_blue"
end
end end
end end
end end
def student_anonymous_comment homework def student_anonymous_comment homework
if homework.homework_type == 1 && homework.homework_detail_manual if homework.homework_detail_manual
case homework.homework_detail_manual.comment_status case homework.homework_detail_manual.comment_status
when 1 when 1
"<span class='fr mr10 pr_join_span '>未开启匿评</span>".html_safe "<span class='fr mr10 pr_join_span '>未开启匿评</span>".html_safe
@ -2328,16 +2618,25 @@ module ApplicationHelper
when 3 when 3
"<span class='fr mr10 pr_join_span '>匿评已结束</span>".html_safe "<span class='fr mr10 pr_join_span '>匿评已结束</span>".html_safe
end end
elsif homework.homework_type == 0
"<span class='fr mr10 pr_join_span '>未启用匿评</span>".html_safe
elsif homework.homework_type == 2
"<span class='fr mr10 pr_join_span '>&nbsp;编程作业&nbsp;&nbsp;</span>".html_safe
end end
end end
#获取当前用户在指定作业下提交的作业的集合 #获取当前用户在指定作业下提交的作业的集合
def cur_user_works_for_homework homework def cur_user_works_for_homework homework
homework.student_works.where("user_id = ?",User.current).first work = homework.student_works.where("user_id = ?",User.current).first
if homework.homework_type == 3
pro = homework.student_work_projects.where("user_id = #{User.current.id}").first
if pro.nil? || pro.student_work_id == "" || pro.student_work_id.nil?
work = nil
else
work = StudentWork.find pro.student_work_id
end
end
work
end
#获取当前用户在指定作业下关联的项目的集合
def cur_user_projects_for_homework homework
homework.student_work_projects.where("user_id = ?",User.current).first
end end
def file_preview_tag(file, html_options={}) def file_preview_tag(file, html_options={})
@ -2346,6 +2645,12 @@ module ApplicationHelper
end end
end end
def file_preview_eye(file, html_options={})
if %w(pdf pptx doc docx xls xlsx).any?{|x| file.filename.downcase.end_with?(x)}
link_to '', download_named_attachment_path(file.id, file.filename, preview: true),html_options
end
end
#将文本内的/n转换为<br> #将文本内的/n转换为<br>
def text_format text def text_format text
text.gsub("&","&amp;").gsub("<","&lt;").gsub(">","&gt;").gsub("\n","<br/>").html_safe text.gsub("&","&amp;").gsub("<","&lt;").gsub(">","&gt;").gsub("\n","<br/>").html_safe
@ -2472,4 +2777,90 @@ int main(int argc, char** argv){
return 0; return 0;
}".html_safe }".html_safe
end end
#判断用户是否已经提交了问卷
def has_commit_poll?(poll_id,user_id)
pu = PollUser.find_by_poll_id_and_user_id(poll_id,user_id)
if pu.nil?
false
else
true
end
end
def import_ke(default_opt={})
opt = {enable_at: false, prettify: false, init_activity: false}.merge default_opt
ss = ''
unless Setting.at_enabled?
opt[:enable_at] = false
end
ss += javascript_include_tag("/assets/kindeditor/kindeditor",'/assets/kindeditor/pasteimg')
if opt[:enable_at]
ss += javascript_include_tag('/assets/kindeditor/at/jquery.caret.min.js', '/assets/kindeditor/at/jquery.atwho.js', '/assets/kindeditor/at/config.js')
ss += stylesheet_link_tag("/assets/kindeditor/at/jquery.atwho.css")
end
if opt[:prettify]
ss += javascript_include_tag 'prettify'
ss += stylesheet_link_tag 'prettify'
end
if opt[:init_activity]
ss += javascript_include_tag "create_kindeditor"
end
ss.html_safe
end
#课程动态的更新
def update_course_activity type, id
course_activity = CourseActivity.where("course_act_type=? and course_act_id =?", type.to_s, id).first
if course_activity
course_activity.updated_at = Time.now
course_activity.save
end
end
#首页动态更新
def update_user_activity type, id
user_activity = UserActivity.where("act_type=? and act_id =?", type.to_s, id).first
if user_activity
user_activity.updated_at = Time.now
user_activity.save
end
end
#项目动态更新
def update_forge_activity type, id
forge_activity = ForgeActivity.where("forge_act_type=? and forge_act_id=?", type.to_s, id).first
if forge_activity
forge_activity.updated_at = Time.now
forge_activity.save
end
end
#组织动态更新
def update_org_activity type , id
org_activity = OrgActivity.where("org_act_type=? and org_act_id =?", type.to_s, id).first
if org_activity
org_activity.updated_at = Time.now
org_activity.save
end
end
#个人动态更新
def update_principal_activity type, id
principal_activity = PrincipalActivity.where("principal_act_type=? and principal_act_id =?", type.to_s, id).first
if principal_activity
principal_activity.updated_at = Time.now
principal_activity.save
end
end
#项目按更新时间排序
def project_sort_update projects
unless projects.empty?
project_ids = '('+projects.map{|pro|pro.project_id}.join(',')+')'
sort_projects = ForgeActivity.find_by_sql("SELECT MAX(updated_at) AS updated_at,user_id, project_id FROM forge_activities WHERE project_id IN #{project_ids} GROUP BY project_id ORDER BY MAX(updated_at) DESC")
return sort_projects
end
end
end end

@ -96,6 +96,7 @@ module AttachmentsHelper
end end
false false
end end
#判断项目project中是否包含课件attachmentproject中引用了attachment也算作包含 #判断项目project中是否包含课件attachmentproject中引用了attachment也算作包含
def project_contains_attachment? project,attachment def project_contains_attachment? project,attachment
project.attachments.each do |att| project.attachments.each do |att|

@ -1,9 +1,24 @@
module AvatarHelper module AvatarHelper
AVATAR_SIZE="50x50" AVATAR_SIZE="50x50"
def copy_avatar(des, src)
src_file = disk_filename(src.class,src.id)
des_file = disk_filename(des.class,des.id)
FileUtils.cp(src_file, des_file) if File.exist?(src_file)
end
def avatar_image(source) def avatar_image(source, copyed=false)
File.join(relative_path, avatar_directory(source.class), source.id.to_s) source_type = source.class
source_id = source.id
course = Course.find(source_id) rescue nil
if course && copyed
source_id = course.is_copy
end
File.join(relative_path, avatar_directory(source_type), source_id.to_s)
end end
def relative_path def relative_path
@ -23,7 +38,18 @@ module AvatarHelper
end end
def disk_filename(source_type,source_id,image_file=nil) def disk_filename(source_type,source_id,image_file=nil)
File.join(storage_path,avatar_directory(source_type),avatar_filename(source_id,image_file)) File.join(storage_path,avatar_directory(source_type),avatar_filename(source_id,image_file))
end
def copy_course?(source_type, source_id)
file= disk_filename(source_type, source_id)
if source_type == Course && !File.exist?(file)
course = Course.find(source_id) rescue nil
if course && course.is_copy>0
return true
end
end
false
end end
def file_extension(filename=nil) def file_extension(filename=nil)
@ -35,7 +61,9 @@ module AvatarHelper
return File.join(relative_path,'AnonymousUser','0') return File.join(relative_path,'AnonymousUser','0')
end end
if source.class && source.id && File.exist?(disk_filename(source.class,source.id)) if source.class && source.id && File.exist?(disk_filename(source.class,source.id))
avatar_image(source) avatar_image(source, false)
elsif copy_course?(source.class, source.id)
avatar_image(source, true)
else else
File.join(relative_path,avatar_directory(source.class),'0') File.join(relative_path,avatar_directory(source.class),'0')
end end

@ -0,0 +1,2 @@
module BlogCommentsHelper
end

@ -0,0 +1,2 @@
module BlogsHelper
end

@ -11,6 +11,59 @@ module CoursesHelper
#StudentRoles = [5, 10] #StudentRoles = [5, 10]
#AllPeople = StudentRoles+TeacherRoles #AllPeople = StudentRoles+TeacherRoles
## return people count ## return people count
# 推荐的精品课程
def excellent_course_recommend new_course
q = "%#{new_course.name.strip}%"
result = find_excelletn_course(q, new_course)
end
# 查询符合条件的精品课程
# 用新课程名去匹配精品课程中按课程名和Tag名
def find_excelletn_course keywords, current_course
# 获取tag匹配结果ID
a_tags = []
# kc = keywords.to_a
Course.visible.where("is_excellent =?", 1).each do |ec|
if ec.tags.any?{|value| current_course.name.include?(value.to_s)}
a_tags << ec.id
end
end
# sql = "SELECT distinct c.* FROM `courses` c, tags t, taggings ts where t.id = ts.tag_id and ts.taggable_id = c.id and c.is_excellent = 1 and is_delete = 0 and
# ts.taggable_type = 'Course' and t.name like '%#{keywords}%'"
# a_tags = Course.find_by_sql(sql).select{|course| course.is_public ==1 unless User.current.member_of_course?(course)}
# 通过elastic结果获取精品课程
a_courses = []
#courses = Course.search(keywords)
#courses.each do |c|
# a_courses << c.id
#end
a_courses << a_tags unless a_tags.length == 0
# 课程本身不能搜索显示自己
excellent_ids = a_courses.flatten.uniq.delete_if{|i| i == current_course.id}
limit = 5 - excellent_ids.length.to_i
sql = "SELECT distinct c.id FROM course_activities cs, courses c where cs.course_id = c.id
and c.is_excellent =1 and c.id != #{current_course.id} order by cs.updated_at desc;"
default_ecourse_ids = Course.find_by_sql(sql).flatten
# REDO:时间紧,待优化
default_ids =[]
default_ecourse_ids.each do |de|
default_ids << de.id
end
default_ids = default_ids - excellent_ids
#default_ecourse = Course.where("id is not in (?)", ids).find_by_sql(sql).flatten.delete_if{|i| i == current_course.id}.flatten
arr_result = excellent_ids << default_ids
arr_result = arr_result.flatten.first(5)
return arr_result
# 过滤条件:精品课程、本身不在搜索范围
#e_courses = Course.where("is_excellent =? and id in (?)",1, arr_result).where("id !=?", current_course.id)
end
# 判断精品课程是否可见,非课程成员无法查看私有课程
def visible_excellent_course obj
# if course.is_pu
end
# 返回x项目成员数量即roles表中定义的所有成员 # 返回x项目成员数量即roles表中定义的所有成员
def projectCount project def projectCount project
@ -25,6 +78,10 @@ module CoursesHelper
# searchTeacherAndAssistant(project).count # searchTeacherAndAssistant(project).count
end end
def show_nav?(count)
count == 0 ? true : false
end
#课程模块需要展示的模块 #课程模块需要展示的模块
def course_model def course_model
@nav_dispaly_course_all_label = 1 @nav_dispaly_course_all_label = 1
@ -36,7 +93,7 @@ module CoursesHelper
#生成课程老师成员链接 #生成课程老师成员链接
def course_teacher_link teacher_num def course_teacher_link teacher_num
if User.current.member_of_course?(@course) || User.current.admin? if User.current.member_of_course?(@course) || User.current.admin?
link_to "#{teacher_num}", course_member_path(@course, :role => 1), :class => 'info_foot_num c_blue' link_to "#{teacher_num}", course_member_path(@course, :role => 1), :class => 'info_foot_num c_blue', :id => 'teacher_number'
else else
content_tag 'span',teacher_num, :class => 'info_foot_num c_blue' content_tag 'span',teacher_num, :class => 'info_foot_num c_blue'
end end
@ -45,7 +102,7 @@ module CoursesHelper
#生成课程学生列表连接 #生成课程学生列表连接
def course_student_link student_num def course_student_link student_num
if (User.current.logged? && @course.open_student == 1) || (User.current.member_of_course?(@course)) || User.current.admin? if (User.current.logged? && @course.open_student == 1) || (User.current.member_of_course?(@course)) || User.current.admin?
link_to "#{student_num}", course_member_path(@course, :role => 2), :class => 'info_foot_num c_blue' link_to "#{student_num}", course_member_path(@course, :role => 2), :class => 'info_foot_num c_blue', :id => "student_number"
else else
content_tag 'span',student_num, :class => 'info_foot_num c_blue' content_tag 'span',student_num, :class => 'info_foot_num c_blue'
end end
@ -503,8 +560,10 @@ module CoursesHelper
#课程实践年份下拉框 #课程实践年份下拉框
def course_time_option year def course_time_option year
type = [] type = []
month = Time.now.month
now_year = year.nil? ? Time.now.year : (Time.now.year <= year ? Time.now.year : year) now_year = year.nil? ? Time.now.year : (Time.now.year <= year ? Time.now.year : year)
for i in (now_year..now_year + 10) year = month < 3 && now_year >=Time.now.year ? now_year - 1 : now_year
for i in (year..year + 10)
option = [] option = []
option << i option << i
option << i option << i
@ -628,27 +687,26 @@ module CoursesHelper
#重启、关闭课程按钮 #重启、关闭课程按钮
def set_course_time course def set_course_time course
id = "finish_course_#{course.id}" # id = "finish_course_#{course.id}"
linkPath = course_endTime_timeout?(course) ? restartcourse_course_path(course) : finishcourse_course_path(course, format: :js) # linkPath = course_endTime_timeout?(course) ? restartcourse_course_path(course) : finishcourse_course_path(course, format: :js)
desc = course_endTime_timeout?(course) ? l(:label_course_reload) : l(:label_course_closed) # desc = course_endTime_timeout?(course) ? l(:label_course_reload) : l(:label_course_closed)
link_to "<span class='pr_close'></span>#{desc}".html_safe, linkPath, :remote => true, :method => :post, :id => id, :confirm => l(:label_course_closed_tips, :desc => desc), :class => "pr_join_a" # link_to "<span class='pr_close'></span>#{desc}".html_safe, linkPath, :remote => true, :method => :post, :id => id, :confirm => l(:label_course_closed_tips, :desc => desc), :class => "pr_join_a"
end end
#加入课程、退出课程按钮 #加入课程、退出课程按钮
def join_in_course_header(course, user, options=[]) def join_in_course_header(course, user, options=[])
if user.logged? if user.logged?
joined = course.members.map{|member| member.user_id}.include? user.id joined = course.members.map{|member| member.user_id}.include? user.id
text = joined ? ("<em class='pr_arrow'></em>".html_safe + l(:label_course_exit_student)) : ("<em class='pr_add'></em>".html_safe + l(:label_course_join_student)) text = joined ? l(:label_course_exit_student) : l(:label_course_join_student)
url = joined ? join_path(:object_id => course.id) : try_join_path(:object_id => course.id) url = joined ? join_path(:object_id => course.id) : try_join_path(:object_id => course.id)
method = joined ? 'delete' : 'post' method = joined ? 'delete' : 'post'
if joined if joined
link = "<span class='pr_join_span mr5' ><em class='pr_add'></em>#{l(:label_course_join_student)}</span>" + link_to(text, url, :remote => true, :method => method, :class => "pr_join_a", :id => "#{course.id}", :confirm => l(:text_are_you_sure_out)) link = link_to(text, url, :remote => true, :method => method, :class => "pr_join_a", :id => "#{course.id}", :confirm => l(:text_are_you_sure_out))
else else
link = link_to(text, url, :remote => true, :method => method, :id => "#{course.id}", :class => "pr_join_a") + "<span class='pr_join_span mr5' ><em class='pr_arrow'></em>#{l(:label_course_exit_student)}</span>".html_safe link = link_to(text, url, :remote => true, :method => method, :id => "#{course.id}", :class => "pr_join_a")
end end
else else
link = "<span class='pr_join_span mr5' ><em class='pr_add'></em>#{l(:label_course_join_student)}</span>" + link = "<span class='pr_join_span mr5' >#{l(:label_course_join_student)}</span>"
"<span class='pr_join_span mr5' ><em class='pr_arrow'></em>#{l(:label_course_exit_student)}</span>"
end end
link.html_safe link.html_safe
end end
@ -682,28 +740,30 @@ module CoursesHelper
# activity = CourseActivity.first # activity = CourseActivity.first
title = "" title = ""
url = "" url = ""
case activity.course_act_type if activity.course_act
when "Course" case activity.course_act_type
title = activity.course_act.name when "Course"
url = course_path activity.course title = activity.course_act.name
when "HomeworkCommon" url = course_path activity.course
title = "作业&nbsp;" + activity.course_act.name when "HomeworkCommon"
url = student_work_index_path(:homework => activity.course_act.id) title = "作业&nbsp;" + activity.course_act.name
when "News" url = student_work_index_path(:homework => activity.course_act.id)
title = "通知公告&nbsp;" + activity.course_act.title when "News"
url = course_news_index_path(activity.course) title = "通知公告&nbsp;" + activity.course_act.title
when "Attachment" url = course_news_index_path(activity.course)
title = "课件&nbsp;" + activity.course_act.filename when "Attachment"
url = course_files_path(activity.course) title = "课件&nbsp;" + activity.course_act.filename
when "Message" url = course_files_path(activity.course)
title = "课程讨论区&nbsp;" + activity.course_act.subject when "Message"
url = course_boards_path(activity.course,:parent_id => activity.course_act.parent_id ? activity.course_act.parent_id : activity.course_act.id, :topic_id => activity.course_act.id) title = "课程讨论区&nbsp;" + activity.course_act.subject
when "JournalsForMessage" url = course_boards_path(activity.course,:parent_id => activity.course_act.parent_id ? activity.course_act.parent_id : activity.course_act.id, :topic_id => activity.course_act.id)
title = "留言&nbsp;" + activity.course_act.notes when "JournalsForMessage"
url = course_feedback_path(activity.course) title = "留言&nbsp;" + activity.course_act.notes
when "Poll" url = course_feedback_path(activity.course)
title = "问卷&nbsp;" + activity.course_act.polls_name when "Poll"
url = poll_index_path(:polls_type => "Course", :polls_group_id => activity.course_id) title = "问卷&nbsp;" + activity.course_act.polls_name
url = poll_path(activity.course_act_id)
end
end end
link_to title.gsub(/<(?!img)[^>]*>/,'').html_safe, url, :class => "problem_tit c_dblue fl fb" link_to title.gsub(/<(?!img)[^>]*>/,'').html_safe, url, :class => "problem_tit c_dblue fl fb"
end end
@ -711,22 +771,46 @@ module CoursesHelper
#课程动态的描述 #课程动态的描述
def course_activity_desc activity def course_activity_desc activity
desc = "" desc = ""
case activity.course_act_type if activity.course_act
when "Course" case activity.course_act_type
desc = "" when "Course"
when "HomeworkCommon" desc = ""
desc = activity.course_act.description when "HomeworkCommon"
when "News" desc = activity.course_act.description
desc = activity.course_act.description when "News"
when "Attachment" desc = activity.course_act.description
desc = "" when "Attachment"
when "Message" desc = ""
desc = activity.course_act.content when "Message"
when "JournalsForMessage" desc = activity.course_act.content
desc = "" when "JournalsForMessage"
when "Poll" desc = ""
desc = activity.course_act.polls_description when "Poll"
desc = activity.course_act.polls_description
end
end end
desc.html_safe desc.html_safe
end end
# 学生按作业总分排序取前8个
def hero_homework_score(course, score_sort_by)
sql_select = "SELECT members.*,(
SELECT SUM(IF(student_works.final_score is null,null,student_works.final_score - student_works.absence_penalty - student_works.late_penalty))
FROM student_works,homework_commons
WHERE student_works.homework_common_id = homework_commons.id
AND homework_commons.course_id = #{course.id}
AND student_works.user_id = members.user_id
) AS score
FROM members
JOIN students_for_courses
ON students_for_courses.student_id = members.user_id AND students_for_courses.course_id = members.course_id
WHERE members.course_id = #{course.id} ORDER BY score #{score_sort_by} limit 9"
homework_scores = Member.find_by_sql(sql_select)
end
def contributor_course_scor(course_id)
ccs = CourseContributorScore.where("course_id =?", course_id).order("total_score desc") .limit(9)
end
end end

@ -0,0 +1,153 @@
# encoding: utf-8
module ExerciseHelper
# 单选
def sigle_selection_standard_answer(params)
size = params.ord - 96
if size > 0 # 小写字母答案
answer = params.ord - 96
else
answer = params.ord - 64
end
end
# 多选
def multiselect_standard_answer(params)
size = params.ord - 96
answer = []
if size > 0 # 小写字母答案
for i in 0..(params.length-1)
answer << (params[i].ord - 96).to_s
end
else
for i in 0..(params.length-1)
answer << (params[i].ord - 64)
end
end
answer = answer.sort
answer.join("")
end
#
def fill_standart_answer(params, standart_answer)
params.each do |param|
standart_answer.answer_text = param.value
standart_answer.save
end
end
# 获取多选的得分
def get_mulscore(question, user)
ecs = ExerciseAnswer.where("user_id =? and exercise_question_id =?", user.id, question.id)
arr = []
ecs.each do |ec|
arr << ec.exercise_choice.choice_position
end
#arr = arr.sort
str = arr.sort.join("")
return str
end
# 判断用户是否已经提交了问卷
# status 为0的时候是用户点击试卷。为1表示用户已经提交
def has_commit_exercise?(exercise_id, user_id)
pu = ExerciseUser.where("exercise_id=? and user_id=? and status=?",exercise_id, user_id, true)
if pu.empty?
false
else
true
end
end
# 判断学生是否点击过问卷点击则为他保存一个记录记录start_at
def has_click_exercise?(exercise_id, user_id)
pu = ExerciseUser.where("exercise_id=? and user_id=? and status=?",exercise_id, user_id, false)
if pu.empty?
false
else
true
end
end
def convert_to_char(str)
result = ""
length = str.length
unless str.nil?
if length === 1
result += (str.to_i + 64).chr
return result
elsif length > 1
for i in 0...length
result += (str[i].to_i + 64).chr
end
return result
end
end
return result
end
def get_current_score exercise
score = 0
unless exercise.nil?
exercise.exercise_questions.each do |exercise_question|
unless exercise_question.question_score.nil?
score += exercise_question.question_score
end
end
return score
end
return score
end
def answer_be_selected?(answer,user)
pv = answer.exercise_answers.where("#{ExerciseAnswer.table_name}.user_id = #{user.id} ")
if !pv.nil? && pv.count > 0
true
else
false
end
end
#获取未完成的题目
def get_uncomplete_question exercise,user
all_questions = exercise.exercise_questions
uncomplete_question = []
all_questions.each do |question|
answers = get_user_answer(question, user)
if answers.empty?
uncomplete_question << question
end
end
uncomplete_question
end
#获取文本题答案
def get_anwser_vote_text(question_id,user_id)
pv = ExerciseAnswer.find_by_exercise_question_id_and_user_id(question_id,user_id)
if pv.nil?
''
else
pv.answer_text
end
end
# 获取当前学生回答问题的答案
def get_user_answer(question,user)
user_answer = question.exercise_answers.where("#{ExerciseAnswer.table_name}.user_id = #{user.id}")
user_answer
end
# 获取问题的标准答案
def get_user_standard_answer(question,user)
if question.question_type == 3
standard_answer =[]
question.exercise_standard_answers.each do |answer|
standard_answer << answer.answer_text
end
else
standard_answer = question.exercise_standard_answers
end
standard_answer
end
end

@ -67,6 +67,17 @@ module FilesHelper
s.html_safe s.html_safe
end end
#带勾选框的组织资源栏目列表
def org_subfields_check_box_tags(name,org_subfields,attachment)
s = ''
org_subfields.each do |org_subfield|
if !org_subfield.attachments.include?attachment
s << "<label>#{ check_box_tag name, org_subfield.id, false, :id => nil } #{h org_subfield.name}</label><br/>"
end
end
s.html_safe
end
#判断用户是否拥有不包含当前资源的课程,需用户在该课程中角色为教师且该课程属于当前学期或下一学期 #判断用户是否拥有不包含当前资源的课程,需用户在该课程中角色为教师且该课程属于当前学期或下一学期
def has_course? user,file def has_course? user,file
result = false result = false
@ -113,7 +124,8 @@ module FilesHelper
if attachment.is_public? || if attachment.is_public? ||
(attachment.container_type == "Project" && User.current.member_of?(attachment.project)) || (attachment.container_type == "Project" && User.current.member_of?(attachment.project)) ||
(attachment.container_type == "Course" && User.current.member_of_course?(Course.find(attachment.container_id)))|| (attachment.container_type == "Course" && User.current.member_of_course?(Course.find(attachment.container_id)))||
attachment.author_id == User.current.id attachment.author_id == User.current.id ||
attachment.container_type == "OrgSubfield"
result << attachment result << attachment
end end
end end
@ -140,6 +152,12 @@ module FilesHelper
result << attachment result << attachment
end end
end end
elsif obj.is_a?(OrgSubfield)
attachments.each do |attachment|
if attachment.is_public? || (attachment.container_type == "OrgSubfield" && attachment.container_id == obj.id )|| attachment.author_id == User.current.id
result << attachment
end
end
end end
end end
result result

@ -1,4 +1,5 @@
# encoding: utf-8 # encoding: utf-8
include UsersHelper
module HomeworkCommonHelper module HomeworkCommonHelper
#迟交扣分下拉框 #迟交扣分下拉框
def late_penalty_option def late_penalty_option
@ -56,12 +57,12 @@ module HomeworkCommonHelper
end end
#根据传入作业确定跳转到开启匿评还是关闭匿评功能 #根据传入作业确定跳转到开启匿评还是关闭匿评功能
def alert_anonyoms_path homework,homework_detail_manual def alert_anonyoms_path homework,homework_detail_manual,user_activity_id,is_in_course,course_activity
link = "" link = ""
if homework_detail_manual.comment_status == 1 if homework_detail_manual.comment_status == 1
link = start_anonymous_comment_homework_common_url homework.id link = start_anonymous_comment_homework_common_url homework.id,:user_activity_id=>user_activity_id,:is_in_course=>is_in_course,:course_activity=>course_activity
elsif homework_detail_manual.comment_status == 2 elsif homework_detail_manual.comment_status == 2
link = stop_anonymous_comment_homework_common_url homework.id link = stop_anonymous_comment_homework_common_url homework.id,:user_activity_id=>user_activity_id,:is_in_course=>is_in_course,:course_activity=>course_activity
end end
link link
end end

@ -380,6 +380,22 @@ module IssuesHelper
value = content_tag("i", h(value)) if value value = content_tag("i", h(value)) if value
end end
end end
# 缺陷更新结果在消息中显示样式
if no_html == "message"
label = content_tag(:span, label, :class => "issue_update_message")
old_value = content_tag("span", h(old_value)) if detail.old_value
old_value = content_tag("del", 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
if options[:token].nil?
value = atta.filename
else
value = atta.filename
end
else
value = content_tag(:span, h(value), :class => "issue_update_message_value") if value
end
end
if detail.property == 'attr' && detail.prop_key == 'description' if detail.property == 'attr' && detail.prop_key == 'description'
s = l(:text_journal_changed_no_detail, :label => label) s = l(:text_journal_changed_no_detail, :label => label)

@ -116,10 +116,10 @@ module JournalsHelper
end end
end end
#content << content_tag('div', links.join(' ').html_safe, :class => 'contextual', :style => 'margin-top:-25px;') unless links.empty? #content << content_tag('div', links.join(' ').html_safe, :class => 'contextual', :style => 'margin-top:-25px;') unless links.empty?
content << textilizable(journal, :notes) content << textAreailizable(journal, :notes)
css_classes = "wiki" css_classes = "wiki"
css_classes << " editable" if editable css_classes << " editable" if editable
content_tag('div', content.html_safe, :id => "journal-#{journal.id}-notes", :class => css_classes ,:style => "width:510px") content_tag('div', content.html_safe, :id => "journal-#{journal.id}-notes", :class => css_classes)
end end
def link_to_in_place_notes_editor(text, field_id, url, options={}) def link_to_in_place_notes_editor(text, field_id, url, options={})

@ -0,0 +1,2 @@
module OrgCoursesHelper
end

@ -0,0 +1,2 @@
module OrgDocumentCommentHelper
end

@ -0,0 +1,16 @@
module OrgMemberHelper
include ApplicationHelper
def find_user_not_in_current_org_by_name org
if params[:q] && params[:q].lstrip.rstrip != ""
scope = Principal.active.sorted.not_member_of_org(org).like(params[:q])
else
scope = []
end
principals = paginateHelper scope,10
s = content_tag('ul', project_member_check_box_tags_ex('membership[user_ids][]', principals), :class => 'mb5', :id => 'principals')
links = pagination_links_full(@obj_pages, @obj_count, :per_page_links => false, :remote => false, :flag => true){|text, parameters, options|
link_to text, org_member_autocomplete_org_member_index_path(parameters.merge(:q => params[:q],:flag => true,:org=> org, :format => 'js')), :remote => true
}
s + content_tag('ul', links,:class => 'wlist',:style=>'float:left !important', :id => "org_member_pagination_links" )
end
end

@ -0,0 +1,2 @@
module OrgProjectsHelper
end

@ -0,0 +1,3 @@
module OrgSubfieldsHelper
include OrganizationsHelper
end

@ -1,2 +1,31 @@
module EnterprisesHelper # encoding: utf-8
module OrganizationsHelper
include ApplicationHelper
def find_user_not_in_current_org_by_name org
if params[:q] && params[:q].lstrip.rstrip != ""
scope = Principal.active.sorted.not_member_of_org(org).like(params[:q])
else
scope = []
end
principals = paginateHelper scope,10
s = content_tag('ul', project_member_check_box_tags_ex('membership[user_ids][]', principals), :class => 'mb5', :id => 'principals')
links = pagination_links_full(@obj_pages, @obj_count, :per_page_links => false, :remote => false, :flag => true){|text, parameters, options|
link_to text, org_member_autocomplete_org_member_index_path( parameters.merge(:q => params[:q],:flag => true,:org=>org, :format => 'js')), :remote => true
}
s + content_tag('ul', links,:class => 'wlist',:style=>'float:left !important', :id => "org_member_pagination_links" )
end
def get_default_name field
case field.name
when 'activity' then
return '动态'
when 'course' then
return '课程'
when 'project' then
return '项目'
end
end
end end

@ -7,4 +7,5 @@ module OwnerTypeHelper
BID = 6 BID = 6
JOURNALSFORMESSAGE = 7 JOURNALSFORMESSAGE = 7
HOMEWORKCOMMON = 8 HOMEWORKCOMMON = 8
BLOGCOMMENT=9
end end

@ -47,7 +47,7 @@ module PollHelper
true true
end end
end end
#统计答题百分比,统计结果保留两位小数 #统计答题百分比,统计结果保留两位小数
def statistics_result_percentage(e, t) def statistics_result_percentage(e, t)
e = e.to_f e = e.to_f

@ -20,11 +20,6 @@ module ProjectScoreHelper
project.documents.count project.documents.count
end end
#代码提交数量
def changesets_num project
project.changesets.count
end
#讨论区帖子数量 #讨论区帖子数量
def board_message_num project def board_message_num project
board_message_count = 0 board_message_count = 0

@ -18,6 +18,8 @@
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
include AvatarHelper include AvatarHelper
include StudentWorkHelper
include ApiHelper
module ProjectsHelper module ProjectsHelper
def link_to_version(version, options = {}) def link_to_version(version, options = {})
return '' unless version && version.is_a?(Version) return '' unless version && version.is_a?(Version)
@ -75,6 +77,63 @@ module ProjectsHelper
return result return result
end end
# 项目类型
def project_type_select
type = []
option1 = []
option1 << l(:label_development_team)
option1 << l(:label_development_team)
option2 = []
option2 << l(:label_research_group)
option2 << l(:label_research_group)
option3 = []
option3 << l(:label_friend_organization)
option3 << l(:label_friend_organization)
type << option1
type << option2
type << option3
type
end
# 项目类型描述
def project_newtype_descrption
case params
when 1
value = l(:label_type_des_development)
when 2
value = l(:label_type_des_research)
when 3
value = l(:label_type_des_friend)
end
end
# 被邀请成员的状态
def status_for_ivitied(ivite_list, project)
if ivite_list.user.member_of?(project)
value = "已经加入了项目!"
elsif ivite_list.user.active?
value = "邀请已发送,等待用户加入!"
else
value = "邀请已发送,等待用户激活账号!"
end
end
# 获取新增gitlab版本库
def rep_gitlab(project)
rep = Repository.where("project_id =? and type =?", project, "Repository::Gitlab")
end
# 获取新项目的版本库地址
def rep_gitlab_url(project)
gitlab_address = Redmine::Configuration['gitlab_address']
url = gitlab_address.to_s+"/"+project.owner.to_s+"/"+ rep_gitlab(project).first.identifier+"."+"git"
end
# # 获取Forge历史版本库
def rep_forge(project)
rep = Repository.where("project_id =? and type =?", project, "Repository::Git")
end
# Added by young # Added by young
def course_settings_tabs def course_settings_tabs
tabs = [{:name => 'info', :action => :edit_project, :partial => 'projects/edit', :label => :label_information_plural, :course=>'1'}, tabs = [{:name => 'info', :action => :edit_project, :partial => 'projects/edit', :label => :label_information_plural, :course=>'1'},

@ -19,12 +19,27 @@
module RepositoriesHelper module RepositoriesHelper
if Rails.env.development? if Rails.env.development?
ROOT_PATH="/tmp/" if Rails.env.development? ROOT_PATH="/private/tmp/"
else else
ROOT_PATH="/home/pdl/redmine-2.3.2-0/apache2/" ROOT_PATH="/home/pdl/redmine-2.3.2-0/apache2/"
end end
PROJECT_PATH_CUT = 40 PROJECT_PATH_CUT = 40
REPO_IP_ADDRESS = Setting.host_repository REPO_IP_ADDRESS = Setting.host_repository
REPO_GITLAB_ADDRESS = "git.trustie.net"
# 某个成员不能拥有同名版本库,不同的成员可以创建同名版本库
def is_sigle_identifier?(user_id, iden)
projects = Project.where("user_id =?",user_id)
identifiers = []
projects.each do |project|
# 只针对gitlab类型的git类型的后期清掉
repository = Repository.where("project_id =? and type =?", project.id, "Repository::Gitlab").first
if repository
identifiers << repository.identifier
end
end
identifiers.include?(iden) ? false :true
end
def format_revision(revision) def format_revision(revision)
if revision.respond_to? :format_identifier if revision.respond_to? :format_identifier
@ -34,12 +49,21 @@ module RepositoriesHelper
end end
end end
def repository_creater rep
repository_creater = User.find_by_login(rep.login) unless rep.login.nil?
end
def truncate_at_line_break(text, length = 255) def truncate_at_line_break(text, length = 255)
if text if text
text.gsub(%r{^(.{#{length}}[^\n]*)\n.+$}m, '\\1...') text.gsub(%r{^(.{#{length}}[^\n]*)\n.+$}m, '\\1...')
end end
end end
def user_commit_rep(mail)
user = User.find_by_mail(mail)
#user.nil? ? User.find(2) : User.find_by_mail(mail)
end
def render_properties(properties) def render_properties(properties)
unless properties.nil? || properties.empty? unless properties.nil? || properties.empty?
content = '' content = ''

@ -0,0 +1,2 @@
module ShieldActivitiesHelper
end

@ -1,16 +1,17 @@
# encoding: utf-8 # encoding: utf-8
include UserScoreHelper
module StudentWorkHelper module StudentWorkHelper
#获取当前用户的项目列表
def user_projects_option def user_projects_option
cond = Project.visible_condition(User.current) + " AND projects.project_type <> 1" projects = User.current.projects.visible
memberships = User.current.memberships.all(:conditions => cond)
projects = memberships.map(&:project)
not_have_project = [] not_have_project = []
not_have_project << Setting.please_chose not_have_project << "请选择关联项目"
not_have_project << 0 not_have_project << 0
type = [] type = []
type << not_have_project type << not_have_project
projects.each do |project| projects.each do |project|
if project != nil if project
option = [] option = []
option << project.name option << project.name
option << project.id option << project.id
@ -98,4 +99,42 @@ module StudentWorkHelper
end end
result result
end end
#教辅评分比例下拉框
def ta_proportion_option
type = []
i = 0
while i <= 100
option = []
option << i.to_s + "%"
option << i.to_f / 100
type << option
i += 10
end
type
end
def ta_proportion_option_to num
type = []
i = 0
while i <= num
option = []
option << i.to_s + "%"
option << i.to_f / 100
type << option
i += 10
end
type
end
def revise_attachment_status homework, attach
date = Time.parse(format_time(attach.created_on.to_s)).strftime("%Y-%m-%d")
status = ""
if homework.homework_detail_manual && ((homework.anonymous_comment == 0 &&homework.homework_detail_manual.evaluation_start.to_s <= date) || (homework.anonymous_comment == 1 && homework.end_time < date))
status = "此时其他同学作品已公开"
else
status = "此时其他同学作品尚未公开"
end
return status
end
end end

@ -0,0 +1,2 @@
module SubfieldSubdomainDirsHelper
end

@ -0,0 +1,2 @@
module SystemMessagesHelper
end

@ -1,5 +1,6 @@
module TagsHelper module TagsHelper
include StoresHelper include StoresHelper
include CoursesHelper
# 通过 id和type获取对象 # 通过 id和type获取对象
def get_object(obj_id,obj_type) def get_object(obj_id,obj_type)
@obj = nil @obj = nil
@ -62,6 +63,37 @@ module TagsHelper
end end
#判断课程course中是否包含课件attachmentcourse中引用了attachment也算作包含
def course_contains_attachment? course,attachment
course.attachments.each do |att|
if att.id == attachment.id || (!att.copy_from.nil? && !attachment.copy_from.nil? && att.copy_from == attachment.copy_from) || att.copy_from == attachment.id || att.id == attachment.copy_from
return true
end
end
false
end
#判断项目project中是否包含课件attachmentproject中引用了attachment也算作包含
def project_contains_attachment? project,attachment
project.attachments.each do |att|
if att.id == attachment.id || (!att.copy_from.nil? && !attachment.copy_from.nil? && att.copy_from == attachment.copy_from) || att.copy_from == attachment.id || att.id == attachment.copy_from
return true
end
end
false
end
#判断用户是否拥有不包含当前资源的课程,需用户在该课程中角色为教师且该课程属于当前学期或下一学期
def has_course? user,file
result = false
user.courses.each do |course|
if !course_contains_attachment?(course,file) && is_course_teacher(User.current,course) && course_in_current_or_next_term(course)
return true
end
end
result
end
# 判断用户是否是贴吧的管理员 # 判断用户是否是贴吧的管理员
# add by chenmin # add by chenmin
def is_forum_manager?(user_id,forum_id) def is_forum_manager?(user_id,forum_id)

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

Loading…
Cancel
Save