Merge branch 'develop'

This commit is contained in:
huang 2017-10-14 16:18:56 +08:00
commit 1f3417a974
2059 changed files with 202969 additions and 32567 deletions

39
.gitignore vendored Normal file
View File

@ -0,0 +1,39 @@
*.swp
/.project
/.idea/*
/.bundle
*.swp
/config/database.yml
/config/configuration.yml
/config/additional_environment.rb
/config/oneapm.yml
/config/environments/production.rb
/files/*
/log/*
/public/tmp/*
/tmp/*
/public/cache/*
/config/newrelic.yml
/public/images/avatars/*
/db/schema.rb
/Gemfile.lock
/lib/plugins/acts_as_versioned/test/debug.log
.rbenv-gemsets
.DS_Store
public/api_doc/
/.metadata
vendor/cache
/files
/public/images/avatars
/public/files
/tags
/config/initializers/gitlab_config.rb
1234567
public/javascripts/wechat/node_modules/
.ruby-version
.access_token
tmux*.log
config/wechat.yml
config/oneapm.yml

288
.idea/bigdate.iml Normal file
View File

@ -0,0 +1,288 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="RUBY_MODULE" version="4">
<component name="CompassSettings">
<option name="compassSupportEnabled" value="true" />
</component>
<component name="FacetManager">
<facet type="RailsFacetType" name="Ruby on Rails">
<configuration>
<RAILS_FACET_CONFIG_ID NAME="RAILS_FACET_SUPPORT_REMOVED" VALUE="false" />
<RAILS_FACET_CONFIG_ID NAME="RAILS_TESTS_SOURCES_PATCHED" VALUE="true" />
<RAILS_FACET_CONFIG_ID NAME="RAILS_FACET_APPLICATION_ROOT" VALUE="$MODULE_DIR$" />
</configuration>
</facet>
</component>
<component name="ModuleRunConfigurationManager">
<configuration default="false" name="test: bigdate" type="RakeRunConfigurationType" factoryName="Rake">
<module name="bigdate" />
<RAKE_RUN_CONFIG_SETTINGS_ID NAME="RUBY_ARGS" VALUE="-e $stdout.sync=true;$stderr.sync=true;load($0=ARGV.shift)" />
<RAKE_RUN_CONFIG_SETTINGS_ID NAME="WORK DIR" VALUE="$MODULE_DIR$" />
<RAKE_RUN_CONFIG_SETTINGS_ID NAME="SHOULD_USE_SDK" VALUE="false" />
<RAKE_RUN_CONFIG_SETTINGS_ID NAME="ALTERN_SDK_NAME" VALUE="" />
<RAKE_RUN_CONFIG_SETTINGS_ID NAME="myPassParentEnvs" VALUE="true" />
<envs>
<env name="RAILS_ENV" value="test" />
</envs>
<EXTENSION ID="BundlerRunConfigurationExtension" bundleExecEnabled="false" />
<EXTENSION ID="JRubyRunConfigurationExtension" NailgunExecEnabled="false" />
<EXTENSION ID="RubyCoverageRunConfigurationExtension" enabled="false" sample_coverage="true" track_test_folders="true" runner="rcov" />
<EXTENSION ID="org.jetbrains.plugins.ruby.motion.run.MotionSimulatorRunExtension" />
<RAKE_RUN_CONFIG_SETTINGS_ID NAME="RAKE_TASK_NAME" VALUE="test" />
<RAKE_RUN_CONFIG_SETTINGS_ID NAME="RAKE_TASK_ARGS" VALUE="" />
<RAKE_RUN_CONFIG_SETTINGS_ID NAME="RAKE_TASK_ATTACHED_TEST_FRAMEWORKS" VALUE=":test_unit " />
<RAKE_RUN_CONFIG_SETTINGS_ID NAME="RAKE_TASK_OPTION_TRACE" VALUE="false" />
<RAKE_RUN_CONFIG_SETTINGS_ID NAME="RAKE_TASK_OPTION_DRYRUN" VALUE="false" />
<RAKE_RUN_CONFIG_SETTINGS_ID NAME="RAKE_TASK_OPTION_PREREQS" VALUE="false" />
<RunnerSettings RunnerId="RubyDebugRunner" />
<ConfigurationWrapper RunnerId="RubyDebugRunner" />
<method />
</configuration>
<configuration default="false" name="spec: bigdate" type="RakeRunConfigurationType" factoryName="Rake">
<module name="bigdate" />
<RAKE_RUN_CONFIG_SETTINGS_ID NAME="RUBY_ARGS" VALUE="-e $stdout.sync=true;$stderr.sync=true;load($0=ARGV.shift)" />
<RAKE_RUN_CONFIG_SETTINGS_ID NAME="WORK DIR" VALUE="$MODULE_DIR$" />
<RAKE_RUN_CONFIG_SETTINGS_ID NAME="SHOULD_USE_SDK" VALUE="false" />
<RAKE_RUN_CONFIG_SETTINGS_ID NAME="ALTERN_SDK_NAME" VALUE="" />
<RAKE_RUN_CONFIG_SETTINGS_ID NAME="myPassParentEnvs" VALUE="true" />
<envs />
<EXTENSION ID="BundlerRunConfigurationExtension" bundleExecEnabled="false" />
<EXTENSION ID="JRubyRunConfigurationExtension" NailgunExecEnabled="false" />
<EXTENSION ID="RubyCoverageRunConfigurationExtension" enabled="false" sample_coverage="true" track_test_folders="true" runner="rcov" />
<EXTENSION ID="org.jetbrains.plugins.ruby.motion.run.MotionSimulatorRunExtension" />
<RAKE_RUN_CONFIG_SETTINGS_ID NAME="RAKE_TASK_NAME" VALUE="spec" />
<RAKE_RUN_CONFIG_SETTINGS_ID NAME="RAKE_TASK_ARGS" VALUE="" />
<RAKE_RUN_CONFIG_SETTINGS_ID NAME="RAKE_TASK_ATTACHED_TEST_FRAMEWORKS" VALUE=":rspec " />
<RAKE_RUN_CONFIG_SETTINGS_ID NAME="RAKE_TASK_OPTION_TRACE" VALUE="false" />
<RAKE_RUN_CONFIG_SETTINGS_ID NAME="RAKE_TASK_OPTION_DRYRUN" VALUE="false" />
<RAKE_RUN_CONFIG_SETTINGS_ID NAME="RAKE_TASK_OPTION_PREREQS" VALUE="false" />
<method />
</configuration>
<configuration default="false" name="Production: bigdate" type="RailsRunConfigurationType" factoryName="Rails">
<predefined_log_file id="RUBY_RAILS_SERVER" enabled="true" />
<module name="bigdate" />
<RAILS_SERVER_CONFIG_SETTINGS_ID NAME="RUBY_ARGS" VALUE="-e $stdout.sync=true;$stderr.sync=true;load($0=ARGV.shift)" />
<RAILS_SERVER_CONFIG_SETTINGS_ID NAME="WORK DIR" VALUE="$MODULE_DIR$" />
<RAILS_SERVER_CONFIG_SETTINGS_ID NAME="SHOULD_USE_SDK" VALUE="false" />
<RAILS_SERVER_CONFIG_SETTINGS_ID NAME="ALTERN_SDK_NAME" VALUE="" />
<RAILS_SERVER_CONFIG_SETTINGS_ID NAME="myPassParentEnvs" VALUE="true" />
<envs />
<EXTENSION ID="BundlerRunConfigurationExtension" bundleExecEnabled="false" />
<EXTENSION ID="JRubyRunConfigurationExtension" NailgunExecEnabled="false" />
<EXTENSION ID="RubyCoverageRunConfigurationExtension" enabled="false" sample_coverage="true" track_test_folders="true" runner="rcov" />
<EXTENSION ID="org.jetbrains.plugins.ruby.motion.run.MotionSimulatorRunExtension" />
<RAILS_SERVER_CONFIG_SETTINGS_ID NAME="SCRIPT_ARGS" VALUE="" />
<RAILS_SERVER_CONFIG_SETTINGS_ID NAME="PORT" VALUE="3000" />
<RAILS_SERVER_CONFIG_SETTINGS_ID NAME="IP" VALUE="127.0.0.1" />
<RAILS_SERVER_CONFIG_SETTINGS_ID NAME="DUMMY_APP" VALUE="test/dummy" />
<RAILS_SERVER_CONFIG_SETTINGS_ID NAME="RAILS_SERVER_TYPE" VALUE="Default" />
<RAILS_SERVER_CONFIG_SETTINGS_ID NAME="ENVIRONMENT_TYPE" VALUE="production" />
<RAILS_SERVER_CONFIG_SETTINGS_ID NAME="LAUNCH_JS" VALUE="false" />
<RunnerSettings RunnerId="RubyDebugRunner" />
<ConfigurationWrapper RunnerId="RubyDebugRunner" />
<method />
</configuration>
<configuration default="false" name="Development: bigdate" type="RailsRunConfigurationType" factoryName="Rails">
<predefined_log_file id="RUBY_RAILS_SERVER" enabled="true" />
<module name="bigdate" />
<RAILS_SERVER_CONFIG_SETTINGS_ID NAME="RUBY_ARGS" VALUE="-e $stdout.sync=true;$stderr.sync=true;load($0=ARGV.shift)" />
<RAILS_SERVER_CONFIG_SETTINGS_ID NAME="WORK DIR" VALUE="$MODULE_DIR$" />
<RAILS_SERVER_CONFIG_SETTINGS_ID NAME="SHOULD_USE_SDK" VALUE="false" />
<RAILS_SERVER_CONFIG_SETTINGS_ID NAME="ALTERN_SDK_NAME" VALUE="" />
<RAILS_SERVER_CONFIG_SETTINGS_ID NAME="myPassParentEnvs" VALUE="true" />
<envs />
<EXTENSION ID="BundlerRunConfigurationExtension" bundleExecEnabled="false" />
<EXTENSION ID="JRubyRunConfigurationExtension" NailgunExecEnabled="false" />
<EXTENSION ID="RubyCoverageRunConfigurationExtension" enabled="false" sample_coverage="true" track_test_folders="true" runner="rcov" />
<EXTENSION ID="org.jetbrains.plugins.ruby.motion.run.MotionSimulatorRunExtension" />
<RAILS_SERVER_CONFIG_SETTINGS_ID NAME="SCRIPT_ARGS" VALUE="" />
<RAILS_SERVER_CONFIG_SETTINGS_ID NAME="PORT" VALUE="3000" />
<RAILS_SERVER_CONFIG_SETTINGS_ID NAME="IP" VALUE="127.0.0.1" />
<RAILS_SERVER_CONFIG_SETTINGS_ID NAME="DUMMY_APP" VALUE="test/dummy" />
<RAILS_SERVER_CONFIG_SETTINGS_ID NAME="RAILS_SERVER_TYPE" VALUE="Default" />
<RAILS_SERVER_CONFIG_SETTINGS_ID NAME="ENVIRONMENT_TYPE" VALUE="development" />
<RAILS_SERVER_CONFIG_SETTINGS_ID NAME="LAUNCH_JS" VALUE="false" />
<RunnerSettings RunnerId="RubyDebugRunner" />
<RunnerSettings RunnerId="RubyRunner" />
<ConfigurationWrapper RunnerId="RubyDebugRunner" />
<ConfigurationWrapper RunnerId="RubyRunner" />
<method />
</configuration>
</component>
<component name="NewModuleRootManager">
<content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$/test" isTestSource="true" />
<sourceFolder url="file://$MODULE_DIR$/spec" isTestSource="true" />
<excludeFolder url="file://$MODULE_DIR$/tmp" />
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
<orderEntry type="module-library">
<library name="gitlab (v3.2.0, E:/bigData/bigdate/lib/gitlab-cli) [path][gem]">
<CLASSES>
<root url="file://$MODULE_DIR$/lib/gitlab-cli/bin" />
<root url="file://$MODULE_DIR$/lib/gitlab-cli/lib" />
</CLASSES>
<SOURCES>
<root url="file://$MODULE_DIR$/lib/gitlab-cli/bin" />
<root url="file://$MODULE_DIR$/lib/gitlab-cli/lib" />
</SOURCES>
</library>
</orderEntry>
<orderEntry type="module-library">
<library name="grack (v2.0.2, E:/bigData/bigdate/lib/grack) [path][gem]">
<CLASSES>
<root url="file://$MODULE_DIR$/lib/grack/bin" />
<root url="file://$MODULE_DIR$/lib/grack/lib" />
<root url="file://$MODULE_DIR$/lib/grack/tests" />
</CLASSES>
<SOURCES>
<root url="file://$MODULE_DIR$/lib/grack/bin" />
<root url="file://$MODULE_DIR$/lib/grack/lib" />
<root url="file://$MODULE_DIR$/lib/grack/tests" />
</SOURCES>
</library>
</orderEntry>
<orderEntry type="module-library">
<library name="rails_kindeditor (v0.4.5, E:/bigData/bigdate/lib/rails_kindeditor) [path][gem]">
<CLASSES>
<root url="file://$MODULE_DIR$/lib/rails_kindeditor/app" />
<root url="file://$MODULE_DIR$/lib/rails_kindeditor/lib" />
<root url="file://$MODULE_DIR$/lib/rails_kindeditor/config" />
<root url="file://$MODULE_DIR$/lib/rails_kindeditor/vendor" />
<root url="file://$MODULE_DIR$/lib/rails_kindeditor/screenshots" />
</CLASSES>
<SOURCES>
<root url="file://$MODULE_DIR$/lib/rails_kindeditor/app" />
<root url="file://$MODULE_DIR$/lib/rails_kindeditor/lib" />
<root url="file://$MODULE_DIR$/lib/rails_kindeditor/config" />
<root url="file://$MODULE_DIR$/lib/rails_kindeditor/vendor" />
<root url="file://$MODULE_DIR$/lib/rails_kindeditor/screenshots" />
</SOURCES>
</library>
</orderEntry>
<orderEntry type="module-library">
<library name="wechat (v[path], E:/bigData/bigdate/lib/wechat) [path][gem]">
<CLASSES>
<root url="file://$MODULE_DIR$/lib/wechat/bin" />
<root url="file://$MODULE_DIR$/lib/wechat/lib" />
</CLASSES>
<SOURCES>
<root url="file://$MODULE_DIR$/lib/wechat/bin" />
<root url="file://$MODULE_DIR$/lib/wechat/lib" />
</SOURCES>
</library>
</orderEntry>
<orderEntry type="library" scope="PROVIDED" name="actionmailer (v3.2.16, ruby-1.9.3-p484) [gem]" level="application" />
<orderEntry type="library" scope="PROVIDED" name="actionpack (v3.2.16, ruby-1.9.3-p484) [gem]" level="application" />
<orderEntry type="library" scope="PROVIDED" name="activemodel (v3.2.16, ruby-1.9.3-p484) [gem]" level="application" />
<orderEntry type="library" scope="PROVIDED" name="activerecord (v3.2.16, ruby-1.9.3-p484) [gem]" level="application" />
<orderEntry type="library" scope="PROVIDED" name="activeresource (v3.2.16, ruby-1.9.3-p484) [gem]" level="application" />
<orderEntry type="library" scope="PROVIDED" name="activesupport (v3.2.16, ruby-1.9.3-p484) [gem]" level="application" />
<orderEntry type="library" scope="PROVIDED" name="acts-as-taggable-on (v2.4.1, ruby-1.9.3-p484) [gem]" level="application" />
<orderEntry type="library" scope="PROVIDED" name="ansi (v1.5.0, ruby-1.9.3-p484) [gem]" level="application" />
<orderEntry type="library" scope="PROVIDED" name="arel (v3.0.3, ruby-1.9.3-p484) [gem]" level="application" />
<orderEntry type="library" scope="PROVIDED" name="axiom-types (v0.1.1, ruby-1.9.3-p484) [gem]" level="application" />
<orderEntry type="library" scope="PROVIDED" name="better_errors (v1.1.0, ruby-1.9.3-p484) [gem]" level="application" />
<orderEntry type="library" scope="PROVIDED" name="binding_of_caller (v0.7.2, ruby-1.9.3-p484) [gem]" level="application" />
<orderEntry type="library" scope="PROVIDED" name="builder (v3.0.0, ruby-1.9.3-p484) [gem]" level="application" />
<orderEntry type="library" scope="PROVIDED" name="bundler (v1.3.5, ruby-1.9.3-p484) [gem]" level="application" />
<orderEntry type="library" scope="PROVIDED" name="carrierwave (v0.10.0, ruby-1.9.3-p484) [gem]" level="application" />
<orderEntry type="library" scope="PROVIDED" name="chinese_pinyin (v1.0.0, ruby-1.9.3-p484) [gem]" level="application" />
<orderEntry type="library" scope="PROVIDED" name="climate_control (v0.0.3, ruby-1.9.3-p484) [gem]" level="application" />
<orderEntry type="library" scope="PROVIDED" name="cocaine (v0.5.7, ruby-1.9.3-p484) [gem]" level="application" />
<orderEntry type="library" scope="PROVIDED" name="coderay (v1.1.0, ruby-1.9.3-p484) [gem]" level="application" />
<orderEntry type="library" scope="PROVIDED" name="coercible (v1.0.0, ruby-1.9.3-p484) [gem]" level="application" />
<orderEntry type="library" scope="PROVIDED" name="coffee-rails (v3.2.2, ruby-1.9.3-p484) [gem]" level="application" />
<orderEntry type="library" scope="PROVIDED" name="coffee-script (v2.4.1, ruby-1.9.3-p484) [gem]" level="application" />
<orderEntry type="library" scope="PROVIDED" name="coffee-script-source (v1.9.1.1, ruby-1.9.3-p484) [gem]" level="application" />
<orderEntry type="library" scope="PROVIDED" name="daemons (v1.2.2, ruby-1.9.3-p484) [gem]" level="application" />
<orderEntry type="library" scope="PROVIDED" name="debug_inspector (v0.0.2, ruby-1.9.3-p484) [gem]" level="application" />
<orderEntry type="library" scope="PROVIDED" name="delayed_job (v4.0.6, ruby-1.9.3-p484) [gem]" level="application" />
<orderEntry type="library" scope="PROVIDED" name="delayed_job_active_record (v4.0.3, ruby-1.9.3-p484) [gem]" level="application" />
<orderEntry type="library" scope="PROVIDED" name="descendants_tracker (v0.0.4, ruby-1.9.3-p484) [gem]" level="application" />
<orderEntry type="library" scope="PROVIDED" name="domain_name (v0.5.24, ruby-1.9.3-p484) [gem]" level="application" />
<orderEntry type="library" scope="PROVIDED" name="elasticsearch (v1.0.14, ruby-1.9.3-p484) [gem]" level="application" />
<orderEntry type="library" scope="PROVIDED" name="elasticsearch-api (v1.0.14, ruby-1.9.3-p484) [gem]" level="application" />
<orderEntry type="library" scope="PROVIDED" name="elasticsearch-model (v0.1.8, ruby-1.9.3-p484) [gem]" level="application" />
<orderEntry type="library" scope="PROVIDED" name="elasticsearch-rails (v0.1.8, ruby-1.9.3-p484) [gem]" level="application" />
<orderEntry type="library" scope="PROVIDED" name="elasticsearch-transport (v1.0.14, ruby-1.9.3-p484) [gem]" level="application" />
<orderEntry type="library" scope="PROVIDED" name="equalizer (v0.0.11, ruby-1.9.3-p484) [gem]" level="application" />
<orderEntry type="library" scope="PROVIDED" name="erubis (v2.7.0, ruby-1.9.3-p484) [gem]" level="application" />
<orderEntry type="library" scope="PROVIDED" name="execjs (v2.5.2, ruby-1.9.3-p484) [gem]" level="application" />
<orderEntry type="library" scope="PROVIDED" name="factory_girl (v4.5.0, ruby-1.9.3-p484) [gem]" level="application" />
<orderEntry type="library" scope="PROVIDED" name="factory_girl_rails (v4.5.0, ruby-1.9.3-p484) [gem]" level="application" />
<orderEntry type="library" scope="PROVIDED" name="faraday (v0.9.0, ruby-1.9.3-p484) [gem]" level="application" />
<orderEntry type="library" scope="PROVIDED" name="fastercsv (v1.5.0, ruby-1.9.3-p484) [gem]" level="application" />
<orderEntry type="library" scope="PROVIDED" name="ffi (v1.9.8, ruby-1.9.3-p484) [gem]" level="application" />
<orderEntry type="library" scope="PROVIDED" name="grape (v0.9.0, ruby-1.9.3-p484) [gem]" level="application" />
<orderEntry type="library" scope="PROVIDED" name="grape-entity (v0.4.5, ruby-1.9.3-p484) [gem]" level="application" />
<orderEntry type="library" scope="PROVIDED" name="grape-swagger (v0.10.1, ruby-1.9.3-p484) [gem]" level="application" />
<orderEntry type="library" scope="PROVIDED" name="hashie (v3.4.1, ruby-1.9.3-p484) [gem]" level="application" />
<orderEntry type="library" scope="PROVIDED" name="hike (v1.2.3, ruby-1.9.3-p484) [gem]" level="application" />
<orderEntry type="library" scope="PROVIDED" name="htmlentities (v4.3.3, ruby-1.9.3-p484) [gem]" level="application" />
<orderEntry type="library" scope="PROVIDED" name="http-cookie (v1.0.2, ruby-1.9.3-p484) [gem]" level="application" />
<orderEntry type="library" scope="PROVIDED" name="httparty (v0.13.5, ruby-1.9.3-p484) [gem]" level="application" />
<orderEntry type="library" scope="PROVIDED" name="i18n (v0.6.11, ruby-1.9.3-p484) [gem]" level="application" />
<orderEntry type="library" scope="PROVIDED" name="ice_nine (v0.11.1, ruby-1.9.3-p484) [gem]" level="application" />
<orderEntry type="library" scope="PROVIDED" name="journey (v1.0.4, ruby-1.9.3-p484) [gem]" level="application" />
<orderEntry type="library" scope="PROVIDED" name="jquery-rails (v2.0.3, ruby-1.9.3-p484) [gem]" level="application" />
<orderEntry type="library" scope="PROVIDED" name="json (v1.8.3, ruby-1.9.3-p484) [gem]" level="application" />
<orderEntry type="library" scope="PROVIDED" name="kaminari (v0.16.3, ruby-1.9.3-p484) [gem]" level="application" />
<orderEntry type="library" scope="PROVIDED" name="mail (v2.5.4, ruby-1.9.3-p484) [gem]" level="application" />
<orderEntry type="library" scope="PROVIDED" name="mime-types (v1.25.1, ruby-1.9.3-p484) [gem]" level="application" />
<orderEntry type="library" scope="PROVIDED" name="mini_magick (v4.2.4, ruby-1.9.3-p484) [gem]" level="application" />
<orderEntry type="library" scope="PROVIDED" name="multi_json (v1.11.0, ruby-1.9.3-p484) [gem]" level="application" />
<orderEntry type="library" scope="PROVIDED" name="multi_xml (v0.5.5, ruby-1.9.3-p484) [gem]" level="application" />
<orderEntry type="library" scope="PROVIDED" name="multipart-post (v2.0.0, ruby-1.9.3-p484) [gem]" level="application" />
<orderEntry type="library" scope="PROVIDED" name="mysql2 (v0.3.18, ruby-1.9.3-p484) [gem]" level="application" />
<orderEntry type="library" scope="PROVIDED" name="net-ldap (v0.3.1, ruby-1.9.3-p484) [gem]" level="application" />
<orderEntry type="library" scope="PROVIDED" name="netrc (v0.10.3, ruby-1.9.3-p484) [gem]" level="application" />
<orderEntry type="library" scope="PROVIDED" name="paperclip (v3.5.4, ruby-1.9.3-p484) [gem]" level="application" />
<orderEntry type="library" scope="PROVIDED" name="polyglot (v0.3.5, ruby-1.9.3-p484) [gem]" level="application" />
<orderEntry type="library" scope="PROVIDED" name="rack (v1.4.5, ruby-1.9.3-p484) [gem]" level="application" />
<orderEntry type="library" scope="PROVIDED" name="rack-accept (v0.4.5, ruby-1.9.3-p484) [gem]" level="application" />
<orderEntry type="library" scope="PROVIDED" name="rack-cache (v1.2, ruby-1.9.3-p484) [gem]" level="application" />
<orderEntry type="library" scope="PROVIDED" name="rack-mini-profiler (v0.9.3, ruby-1.9.3-p484) [gem]" level="application" />
<orderEntry type="library" scope="PROVIDED" name="rack-mount (v0.8.3, ruby-1.9.3-p484) [gem]" level="application" />
<orderEntry type="library" scope="PROVIDED" name="rack-openid (v1.4.2, ruby-1.9.3-p484) [gem]" level="application" />
<orderEntry type="library" scope="PROVIDED" name="rack-raw-upload (v1.1.1, ruby-1.9.3-p484) [gem]" level="application" />
<orderEntry type="library" scope="PROVIDED" name="rack-ssl (v1.3.4, ruby-1.9.3-p484) [gem]" level="application" />
<orderEntry type="library" scope="PROVIDED" name="rack-test (v0.6.3, ruby-1.9.3-p484) [gem]" level="application" />
<orderEntry type="library" scope="PROVIDED" name="rails (v3.2.16, ruby-1.9.3-p484) [gem]" level="application" />
<orderEntry type="library" scope="PROVIDED" name="railties (v3.2.16, ruby-1.9.3-p484) [gem]" level="application" />
<orderEntry type="library" scope="PROVIDED" name="rake (v11.2.2, ruby-1.9.3-p484) [gem]" level="application" />
<orderEntry type="library" scope="PROVIDED" name="rdoc (v3.12.2, ruby-1.9.3-p484) [gem]" level="application" />
<orderEntry type="library" scope="PROVIDED" name="redis (v3.2.1, ruby-1.9.3-p484) [gem]" level="application" />
<orderEntry type="library" scope="PROVIDED" name="redis-actionpack (v3.2.4, ruby-1.9.3-p484) [gem]" level="application" />
<orderEntry type="library" scope="PROVIDED" name="redis-activesupport (v3.2.5, ruby-1.9.3-p484) [gem]" level="application" />
<orderEntry type="library" scope="PROVIDED" name="redis-rack (v1.4.4, ruby-1.9.3-p484) [gem]" level="application" />
<orderEntry type="library" scope="PROVIDED" name="redis-rails (v3.2.4, ruby-1.9.3-p484) [gem]" level="application" />
<orderEntry type="library" scope="PROVIDED" name="redis-store (v1.1.4, ruby-1.9.3-p484) [gem]" level="application" />
<orderEntry type="library" scope="PROVIDED" name="rest-client (v1.8.0, ruby-1.9.3-p484) [gem]" level="application" />
<orderEntry type="library" scope="PROVIDED" name="rich (v1.4.6, ruby-1.9.3-p484) [gem]" level="application" />
<orderEntry type="library" scope="PROVIDED" name="ruby-ole (v1.2.11.8, ruby-1.9.3-p484) [gem]" level="application" />
<orderEntry type="library" scope="PROVIDED" name="ruby-openid (v2.1.8, ruby-1.9.3-p484) [gem]" level="application" />
<orderEntry type="library" scope="PROVIDED" name="rubyzip (v1.1.7, ruby-1.9.3-p484) [gem]" level="application" />
<orderEntry type="library" scope="PROVIDED" name="sass (v3.4.13, ruby-1.9.3-p484) [gem]" level="application" />
<orderEntry type="library" scope="PROVIDED" name="sass-rails (v3.2.6, ruby-1.9.3-p484) [gem]" level="application" />
<orderEntry type="library" scope="PROVIDED" name="seems_rateable (v1.0.13, ruby-1.9.3-p484) [gem]" level="application" />
<orderEntry type="library" scope="PROVIDED" name="spreadsheet (v1.0.3, ruby-1.9.3-p484) [gem]" level="application" />
<orderEntry type="library" scope="PROVIDED" name="sprockets (v2.2.3, ruby-1.9.3-p484) [gem]" level="application" />
<orderEntry type="library" scope="PROVIDED" name="terminal-table (v1.5.2, ruby-1.9.3-p484) [gem]" level="application" />
<orderEntry type="library" scope="PROVIDED" name="thor (v0.19.1, ruby-1.9.3-p484) [gem]" level="application" />
<orderEntry type="library" scope="PROVIDED" name="thread_safe (v0.3.5, ruby-1.9.3-p484) [gem]" level="application" />
<orderEntry type="library" scope="PROVIDED" name="tilt (v1.4.1, ruby-1.9.3-p484) [gem]" level="application" />
<orderEntry type="library" scope="PROVIDED" name="treetop (v1.4.15, ruby-1.9.3-p484) [gem]" level="application" />
<orderEntry type="library" scope="PROVIDED" name="tzinfo (v0.3.44, ruby-1.9.3-p484) [gem]" level="application" />
<orderEntry type="library" scope="PROVIDED" name="uglifier (v2.7.1, ruby-1.9.3-p484) [gem]" level="application" />
<orderEntry type="library" scope="PROVIDED" name="unf (v0.1.4, ruby-1.9.3-p484) [gem]" level="application" />
<orderEntry type="library" scope="PROVIDED" name="unf_ext (v0.0.7.1, ruby-1.9.3-p484) [gem]" level="application" />
<orderEntry type="library" scope="PROVIDED" name="virtus (v1.0.5, ruby-1.9.3-p484) [gem]" level="application" />
<orderEntry type="library" scope="PROVIDED" name="win32console (v1.3.2, ruby-1.9.3-p484) [gem]" level="application" />
</component>
<component name="RModuleSettingsStorage">
<LOAD_PATH number="0" />
<I18N_FOLDERS number="1" string0="$MODULE_DIR$/config/locales" />
</component>
</module>

View File

@ -6,6 +6,7 @@ unless RUBY_PLATFORM =~ /w32/
if RUBY_PLATFORM =~ /darwin/
gem "rmagick", "= 2.15.4" ## osx must be this version
elsif RUBY_PLATFORM =~ /linux/
gem 'simple_xlsx_reader'
gem "rmagick", "~> 2.13.1" ## centos yum install ImageMagick-devel
end
gem 'certified'
@ -14,6 +15,7 @@ unless RUBY_PLATFORM =~ /w32/
gem 'nokogiri'
end
#gem 'simple_xlsx_reader'
gem 'wechat',path: 'lib/wechat'
gem 'grack', path:'lib/grack'
gem 'gitlab', path: 'lib/gitlab-cli'
@ -75,7 +77,7 @@ group :development, :test do
gem 'pry-byebug'
gem "test-unit", "~>3.0"
end
gem 'rspec-rails', '~> 3.0'
# gem 'rspec-rails', '~> 3.0'
gem 'factory_girl_rails'
end

View File

@ -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/

View File

@ -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/

View File

@ -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/

View File

@ -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/

View File

@ -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/

View File

@ -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/

View File

@ -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/

View File

@ -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/

View File

@ -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/

View File

@ -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/

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -22,7 +22,13 @@ class AccountController < ApplicationController
# 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_authentication, :only => [:login, :logout, :user_join, :avatar, :authentication, :professional_certification, :security_settings, :change_psd]
before_filter :auth_login1, :only => [:avatar, :authentication, :professional_certification, :security_settings, :change_psd]
skip_before_filter :verify_authenticity_token, :only =>[:codepedia_login]
before_filter :require_login, only: [:avatar, :authentication, :professional_certification, :security_settings, :change_psd, :user_auth, :apply_auth, :apply_pro_certification, :check_student_id]
include ApplicationHelper
# Login request and validation
def login
if params[:type] == "activated"
@message = l(:notice_account_activated)
@ -43,13 +49,25 @@ class AccountController < ApplicationController
redirect_to user_path(User.current)
end
else
render :layout => 'login_bigdata'
render :layout => 'login_bigdata'
end
else
authenticate_user
end
end
def codepedia_login
logger.info("codepedia_login#########################################")
logger.info("#{params}")
user, last_login_on = User.try_to_login(params[:username], params[:password])
logger.info(user)
if user.blank?
render :json => { status: 0 }
else
render :json => { status: 1, user: user}
end
end
def user_join
if params[:type] == "activated"
@message = l(:notice_account_activated)
@ -79,7 +97,7 @@ class AccountController < ApplicationController
# 服务协议
def agreement
render :layout => 'static_base'
render :layout => 'base_edu'
end
def about_us
@ -90,8 +108,10 @@ class AccountController < ApplicationController
def logout
if User.current.anonymous?
redirect_to signin_path
elsif request.post?
else
UserActions.create(:action_id => User.current.id, :action_type => "Logout", :user_id => User.current.id)
logout_user
# 记录用户登出行为
redirect_to signin_path
end
# display the logout form
@ -169,7 +189,7 @@ class AccountController < ApplicationController
session[:auth_source_registration] = nil
self.logged_user = @user
flash[:notice] = l(:notice_account_activated)
redirect_to my_account_path(:tip=>1)
redirect_to my_account_path(:tip => 1)
end
else
us = UsersService.new
@ -202,6 +222,11 @@ class AccountController < ApplicationController
account_pending
end
end
if params[:user][:mail].nil?
reward_grade(@user, @user.id, 'Phone', 500)
else
reward_grade(@user, @user.id, 'Mail', 500)
end
end
end
end
@ -317,24 +342,25 @@ class AccountController < ApplicationController
req = Hash.new(false)
req[:valid] = false
type = params[:type].to_i
if type == 1 || type == 2 || params[:phone] =~ /^1\d{10}$/
code = VerificationCode.where(:phone => params[:phone], :code => params[:code], :code_type => (params[:type].to_i != 1 && params[:type].to_i != 2) ? 2 : params[:type].to_i ).last
if type == 1 || type == 2 || type == 4 || params[:phone] =~ /^1\d{10}$/
code = VerificationCode.where(:phone => params[:phone], :code => params[:code], :code_type => (params[:type].to_i != 1 && params[:type].to_i != 2 && params[:type].to_i != 4) ? 2 : params[:type].to_i ).last
else
code = VerificationCode.where(:email => params[:phone], :code => params[:code], :code_type => 3).last
code = VerificationCode.where(:email => params[:phone], :code => params[:code], :code_type => params[:type].to_i).last
end
req[:valid] = !code.nil? && (Time.now.to_i - code.created_at.to_i) <= 10*60
render :json => req
end
# 发送验证码type 1注册手机验证码 2找回密码手机验证码 3找回密码邮箱验证码
# 发送验证码type 1注册手机验证码 2找回密码手机验证码 3找回密码邮箱验证码 4绑定手机 5绑定邮箱
def get_verification_code
code = %W(0 1 2 3 4 5 6 7 8 9)
type = params[:type].to_i
req = Hash.new(false)
req[:status] = 0
req[:msg] = ''
if type == 1
if User.where(:phone => params[:value]).count > 0
req[:status] = 2
req[:status] = 2 #已注册
else
begin
verification_code = code.sample(6).join
@ -347,10 +373,10 @@ class AccountController < ApplicationController
end
req[:status] = 1
end
else
elsif type == 2 || type == 3
if params[:value] =~ /^[a-zA-Z0-9]+([._\\]*[a-z0-9])*@([a-z0-9]+[-a-z0-9]*[a-z0-9]+.){1,63}[a-z0-9]+$/
if User.where(:mail => params[:value]).count == 0
req[:status] = 2
req[:status] = 2 #未注册
else
begin
verification_code = code.sample(6).join
@ -384,11 +410,283 @@ class AccountController < ApplicationController
else
req[:status] = 2
end
else
if params[:value] =~ /^[a-zA-Z0-9]+([._\\]*[a-z0-9])*@([a-z0-9]+[-a-z0-9]*[a-z0-9]+.){1,63}[a-z0-9]+$/
if User.where(:mail => params[:value]).count > 0
req[:status] = 2 #已绑定
req[:msg] = '该邮箱已被绑定'
else
begin
verification_code = code.sample(6).join
user = User.current
token = Token.new(:user => user, :action => "bind")
if token.save
Mailer.run.bind_email(token, verification_code, params[:value])
VerificationCode.create(:email => params[:value], :status => 1, :code_type => 5, :code => verification_code)
end
rescue => e
Rails.logger.error "发送验证码出错: #{e}"
end
req[:status] = 3
req[:link] = params[:value].split("@")[1]
end
elsif params[:value] =~ /^1\d{10}$/
if User.where(:phone => params[:value]).count > 0
req[:status] = 2
req[:msg] = '该手机号已被绑定'
else
begin
verification_code = code.sample(6).join
status = Trustie::Sms.send(mobile: params[:value], code: verification_code)
if status
VerificationCode.create(:phone => params[:value], :status => 1, :code_type => 4, :code => verification_code)
end
rescue => e
Rails.logger.error "发送验证码出错: #{e}"
end
req[:status] = 1
end
else
req[:status] = 2
end
end
render :json => req
end
def avatar
@user = params[:user_id].nil? ? User.current : User.find(params[:user_id])
@setting_type = 2
render :layout => 'base_edu_account'
end
# 实名认证
def authentication
@user = User.current
@apply_user_auth = ApplyUserAuthentication.where(:user_id => @user.id, :auth_type => 1, :status => [0, 2]).order("created_at asc").last
@setting_type = 3
render :layout => 'base_edu_account'
end
# 职业认证
def professional_certification
@user = User.current
@apply_user_auth = ApplyUserAuthentication.where(:user_id => @user.id, :auth_type => 2, :status => [0, 2]).order("created_at asc").last
@setting_type = 4
render :layout => 'base_edu_account'
end
def apply_auth
@user = User.current
@user.lastname = params[:lastname]
@user.firstname = ""
@user.ID_number = params[:ID_number]
@se = @user.extensions
@se.gender = params[:sex]
if @user.save && @se.save
@user.update_attributes(:authentication => 0)
diskfile1 = disk_auth_filename('UserAuthentication', @user.id, 'ID')
diskfileID = diskfile1 + 'temp'
begin
FileUtils.mv diskfileID, diskfile1, force: true if File.exist? diskfileID
ensure
File.delete(diskfileID) if File.exist?(diskfileID)
end
if File.exist?(diskfile1)
ApplyUserAuthentication.create(:user_id => @user.id, :status => 0, :auth_type => 1)
end
end
redirect_to authentication_account_path
end
def apply_pro_certification
@user = User.current
@se = @user.extensions
@se.school_id = params[:occupation]
@se.department_id = params[:department_id]
@se.identity = params[:identity].to_i if params[:identity]
if @se.identity == 0
@se.technical_title = params[:te_technical_title] if params[:te_technical_title]
@se.student_id = nil
elsif @se.identity == 1
@se.student_id = params[:no] if params[:no]
@se.technical_title = nil
elsif @se.identity == 2
@se.technical_title = params[:pro_technical_title] if params[:pro_technical_title]
@se.student_id = nil
end
if @user.save && @se.save
@user.update_attributes(:professional_certification => 0)
if @se.identity == 1
ApplyUserAuthentication.create(:user_id => @user.id, :status => 0, :auth_type => 2)
else
diskfile2 = disk_auth_filename('UserAuthentication', @user.id, 'PRO')
diskfilePRO = diskfile2 + 'temp'
begin
FileUtils.mv diskfilePRO, diskfile2, force: true if File.exist? diskfilePRO
ensure
File.delete(diskfilePRO) if File.exist?(diskfilePRO)
end
if File.exist?(diskfile2)
ApplyUserAuthentication.create(:user_id => @user.id, :status => 0, :auth_type => 2)
end
end
end
redirect_to professional_certification_account_path
end
# 修改资料时判断学号是否已使用
def check_user_student_id
data = {result:0, account:""}
if params[:student_id] && params[:school_id]
if UserExtensions.where("student_id = '#{params[:student_id]}' and school_id = #{params[:school_id]} and user_id != #{User.current.id}").count > 0
user = User.where(:id => UserExtensions.where("student_id = '#{params[:student_id]}' and school_id = #{params[:school_id]} and user_id != #{User.current.id}").map(&:user_id)).first
data[:account] = user.mail.blank? ? user.user_phone : user.user_mail
else
data[:result] = 1
end
end
render :json => data
end
# 实名认证时判断学号是否已使用
def check_student_id
data = {result:0, account:""}
if params[:student_id] && params[:school_id]
auth_count = User.where(:id => UserExtensions.where(:student_id => params[:student_id], :school_id => params[:school_id]).map(&:user_id), :professional_certification => 1).count
apply_count = ApplyUserAuthentication.where(:status => 0, :user_id => User.where(:id => UserExtensions.where(:student_id => params[:student_id], :school_id => params[:school_id]).map(&:user_id), :professional_certification => 0).map(&:id)).count
if auth_count == 0 && apply_count == 0
data[:result] = 1
else
user = auth_count != 0 ? User.where(:id => UserExtensions.where(:student_id => params[:student_id], :school_id => params[:school_id]).map(&:user_id)).first : ApplyUserAuthentication.where(:status => 0, :user_id => User.where(:id => UserExtensions.where(:student_id => params[:student_id], :school_id => params[:school_id]).map(&:user_id), :professional_certification => 0).map(&:id)).first.user
if user != User.current
data[:account] = user.mail.blank? ? user.user_phone : user.user_mail
else
data[:result] = 1
end
end
end
render :json => data
end
# 实名认证时判断证件号码是否已使用
def check_id_number
data = {result:0, account:""}
if params[:id_number]
auth_count = User.where(:ID_number => params[:id_number], :authentication => 1).count
apply_count = ApplyUserAuthentication.where(:status => 0, :user_id => User.where(:ID_number => params[:id_number], :authentication => 0).map(&:id)).count
if auth_count == 0 && apply_count == 0
data[:result] = 1
else
user = auth_count != 0 ? User.where(:ID_number => params[:id_number], :authentication => 1).first : ApplyUserAuthentication.where(:status => 0, :user_id => User.where(:ID_number => params[:id_number], :authentication => 0).map(&:id)).first.user
if user != User.current
data[:account] = user.mail.blank? ? user.user_phone : user.user_mail
else
data[:result] = 1
end
end
end
render :json => data
end
def cancel_pro_apply
@apply_user_auth = ApplyUserAuthentication.where(:user_id => User.current.id, :auth_type => params[:auth_type], :status => 0).update_all(:status => 3)
if params[:auth_type] == "1"
redirect_to authentication_account_path
else
redirect_to professional_certification_account_path
end
end
def apply_trail
apply_action = ApplyAction.where(:user_id => User.current.id, :container_type => "TrialAuthorization", :status => 0).first
school_ids = School.where(:auto_users_trial => 1).map(&:id)
if User.current.user_extensions.identity == 1 && !User.current.user_extensions.student_id.nil? && User.current.user_extensions.student_id != "" && !User.current.user_extensions.school.nil? && school_ids.include?(User.current.user_extensions.school_id)
User.current.update_attributes(:certification => 1)
@tip = "申请成功,我们将在一分钟内完成审核"
if apply_action.blank?
ApplyAction.create(:user_id => User.current.id, :status => 1, :container_type => "TrialAuthorization", :apply_reason => params[:apply_reason])
else
apply_action.update_attributes(:status => 1)
end
else
@tip = "申请成功,我们将在一个工作日内完成审核"
ApplyAction.create(:user_id => User.current.id, :status => 0, :container_type => "TrialAuthorization", :apply_reason => params[:apply_reason])
end
respond_to do |format|
format.js
end
end
def user_auth
@user = User.current
diskfile1 = disk_auth_filename('UserAuthentication', @user.id, 'ID')
diskfile2 = disk_auth_filename('UserAuthentication', @user.id, 'PRO')
diskfileID = diskfile1 + 'temp'
diskfilePRO = diskfile2 + 'temp'
begin
FileUtils.mv diskfileID, diskfile1, force: true if File.exist? diskfileID
FileUtils.mv diskfilePRO, diskfile2, force: true if File.exist? diskfilePRO
ensure
File.delete(diskfileID) if File.exist?(diskfileID)
File.delete(diskfilePRO) if File.exist?(diskfilePRO)
end
if File.exist?(diskfile1) && File.exist?(diskfile2)
ApplyUserAuthentication.create(:user_id => @user.id, :status => 0)
end
redirect_to authentication_account_path
end
def security_settings
@user = User.current
@setting_type = 5
render :layout => 'base_edu_account'
end
def change_psd
@user = User.current
@setting_type = 6
render :layout => 'base_edu_account'
end
# 修改密码时判断密码是否输入正确
def valid_psd
@user = User.current
req = Hash.new(false)
req[:valid] = false
req[:valid] = @user.check_password?(params[:value])
render :json => req
end
def change_or_bind
@user = User.current
@type = params[:type]
@setting_type = 5
render :layout => 'base_edu_account'
end
def bind_email_or_phone
@user = User.current
begin
ActiveRecord::Base.transaction do
if params[:type] == "phone"
@user.update_attributes!(:phone => params[:value])
reward_grade(@user, @user.id, 'Phone', 500)
else
@user.update_attributes!(:mail => params[:value])
reward_grade(@user, @user.id, 'Mail', 500)
end
end
rescue
raise ActiveRecord::Rollback
end
redirect_to security_settings_path
end
def wechat_bind
respond_to do |format|
format.html { render :layout => "login_bigdata"}
@ -547,6 +845,8 @@ class AccountController < ApplicationController
call_hook(:controller_account_success_authentication_after, {:user => user })
code = /\d*/
# 记录用户登录行为
UserActions.create(:action_id => User.current.id, :action_type => "Login", :user_id => User.current.id)
#根据home_url生产正则表达式
eval("code = " + "/^" + home_url.gsub(/\//,"\\\/") + "\\\/*(welcome)?\\\/*(\\\/index\\\/*.*)?\$/")
if (code=~params[:back_url] || params[:back_url].to_s.include?('lost_password')) && last_login_on != ''

File diff suppressed because it is too large Load Diff

View File

@ -60,6 +60,20 @@ class ApplicationController < ActionController::Base
logger.info "HTTP_USER_AGENT #{request.env["HTTP_USER_AGENT"]}"
end
# 判断用户是否认证
# def check_authentication
# # return true
# if params[:action] == "on_search" || params[:action] == "apply_trail" # 之所以这样处理是为了避开account页面ajax加载
# return true
# end
# authentication = ApplyAction.where(:user_id => User.current.id, :status => 1).first
# user_identity = User.current.try(:user_extensions).try(:identity)
# if user_identity.blank? || authentication.blank?
# redirect_to my_account_path
# return
# end
# end
def session_expiration
if session[:user_id]
if session_expired? && !try_to_autologin
@ -106,6 +120,7 @@ class ApplicationController < ActionController::Base
def current_user
find_current_user
end
def find_current_user
user = nil
unless api_request?
@ -205,6 +220,7 @@ class ApplicationController < ActionController::Base
def logout_user
if User.current.logged?
if Redmine::Configuration['cookie_domain'].present?
logger.info("##########################{Redmine::Configuration['cookie_domain']}")
cookies.delete(autologin_cookie_name, domain: Redmine::Configuration['cookie_domain'])
else
cookies.delete autologin_cookie_name
@ -433,7 +449,7 @@ class ApplicationController < ActionController::Base
if params[:project_id]
@project = Project.find(params[:project_id])
elsif params[:shixun_id]
@shixun = Shixun.find(params[:shixun_id])
@shixun = Shixun.find_by_identifier(params[:shixun_id])
elsif params[:course_id]
@course = Course.find(params[:course_id])
elsif params[:org_subfield_id]
@ -624,6 +640,10 @@ class ApplicationController < ActionController::Base
end
def render_403(options={})
if User.current.id == 2
redirect_to signin_url
return
end
@project = nil
render_error({:message => :notice_not_authorized, :status => 403}.merge(options),'common/403')
#render :template => 'common/403'
@ -631,6 +651,10 @@ class ApplicationController < ActionController::Base
end
def render_404(options={})
if User.current.id == 2
redirect_to signin_url
return
end
render_error({:message => :notice_file_not_found, :status => 404}.merge(options),'common/404')
#render :template => 'common/404'
return false
@ -948,6 +972,20 @@ class ApplicationController < ActionController::Base
end
end
# gitlab分页定制
def paginateHelperForGitlab obj, pre_size=15
@obj_count = obj.count
@obj_pages = Paginator.new @obj_count, pre_size, params['page']
if obj.kind_of? ActiveRecord::Base or obj.kind_of? ActiveRecord::Relation
obj.limit(@obj_pages.per_page).offset(@obj_pages.offset)
elsif obj.kind_of? Array
obj[0, @obj_pages.per_page]
else
logger.error "[ApplicationController] Error : application_controller#paginateHelper ===> unknow category: #{obj.class}"
raise RuntimeError, 'unknow type, Please input you type into this helper.'
end
end
#查找首页相关信息
def find_first_page
@first_page = FirstPage.find_by_page_type('project')

View File

@ -79,6 +79,51 @@ class AttachmentsController < ApplicationController
:disposition => 'attachment' #inline can open in browser
end
def direct_download_resource
@resource = ResourceBank.find(params[:id])
storage_path = Redmine::Configuration['attachments_storage_path'] || File.join(Rails.root, "files")
file = File.join(storage_path, @resource.disk_directory.to_s, @resource.disk_filename.to_s)
send_file file, :filename => filename_for_content_disposition(@resource.filename),
:type => detect_content_type(@resource),
:disposition => 'attachment' #inline can open in browser
@resource.increment!(:downloads)
end
def download_resource
@resource = ResourceBank.find(params[:id])
candown = resource_bank_candown @resource, params[:type]
if candown
if stale?(:etag => @resource.digest)
if params[:preview] == 'true'
storage_path = Redmine::Configuration['attachments_storage_path'] || File.join(Rails.root, "files")
convered_file = File.join(storage_path, @resource.disk_directory.to_s, @resource.disk_filename.to_s)
#如果本身不是pdf文件则先寻找是不是已转换化如果没有则转化
unless pdf?(convered_file)
convered_file = File.join(Rails.root, "files", "convered_office", @attachment.disk_filename + ".pdf")
unless File.exist?(convered_file)
office = Trustie::Utils::Office.new(File.join(storage_path, @resource.disk_directory.to_s, @resource.disk_filename.to_s))
office.conver(convered_file)
end
end
if File.exist?(convered_file) && pdf?(convered_file)
send_file convered_file, :type => 'application/pdf; charset=utf-8', :disposition => 'inline'
else
direct_download_resource
end
else
# 记录用户行为
record_user_actions(params[:id])
# 直接下载历史版本
direct_download_resource
end
end
else
render_403 :message => :notice_not_authorized
end
rescue => e
redirect_to "http://" + (Setting.host_name.to_s) +"/file_not_found.html"
end
def direct_download_history
@attachment_history = AttachmentHistory.find(params[:id])
@attachment_history.increment_download
@ -126,6 +171,8 @@ class AttachmentsController < ApplicationController
UserActions.create(:action_id => id, :action_type => "AttachmentHistory", :user_id => User.current.id) unless id.nil?
elsif params[:action] == "download"
UserActions.create(:action_id => id, :action_type => "Attachment", :user_id => User.current.id) unless id.nil?
elsif params[:action] == "download_resource"
UserActions.create(:action_id => id, :action_type => "ResourceBank", :user_id => User.current.id) unless id.nil?
end
end
@ -268,6 +315,8 @@ class AttachmentsController < ApplicationController
def upload
# Make sure that API users get used to set this content type
# as it won't trigger Rails' automatic parsing of the request body for parameters
unless request.content_type == 'application/octet-stream'
@ -295,6 +344,25 @@ class AttachmentsController < ApplicationController
end
end
def upload_with_markdown
logger.debug "upload_with_markdown"
@attachment = Attachment.new(:file => params["editormd-image-file"])
@attachment.author = User.current
# 如果其它类型的条用md必须传类型elsif判断
if params[:container_type] == 'Shixun'
@attachment.container_type = 'Shixun'
@attachment.container_id = params[:container_id]
end
@attachment.filename = params[:filename].presence || Redmine::Utils.random_hex(16)
saved = @attachment.save
saved
render json: {
success: saved ? 1 : 0, # | 1, // 0 表示上传失败1 表示上传成功
message: "上传失败:#{ @attachment.errors.full_messages.join(',') }",
url: download_attachment_path(@attachment.id) # 上传成功时才返回
}
end
def upload_attachment_version
@flag = false
Attachment.transaction do
@ -303,7 +371,7 @@ class AttachmentsController < ApplicationController
@attachment = Attachment.find(params[:attachments ].first[1][:attachment_id])
#将需要修改的记录保存到历史记录
@history = AttachmentHistory.new
@history.attributes = @old_attachment.attributes.dup.except("id")
@history.attributes = @old_attachment.attributes.dup.except("id", "resource_bank_id")
@history.attachment_id = params[:old_attachment_id]
#需要更新版本号,需要拿到原来该文件最大的历史版本号
@old_history = @old_attachment.attachment_histories.reorder('version desc').first
@ -706,6 +774,8 @@ class AttachmentsController < ApplicationController
elsif !@attachment.container.nil? && ((@attachment.container.has_attribute?(:board) || @attachment.container.has_attribute?(:board_id)) && @attachment.container.board &&
@attachment.container.board.contest)
@contest = @attachment.container.board.contest
elsif @attachment.container_type == 'Shixun'
@shixun
else
unless @attachment.container_type == 'Syllabus' || @attachment.container_type == 'Bid' || @attachment.container_type == 'Organization' || @attachment.container_type == 'HomeworkAttach' || @attachment.container_type == 'Memo' || @attachment.container_type == 'Softapplication' || @attachment.container_type == 'PhoneAppVersion' || @attachment.container_type == 'StudentWorksScore'|| @attachment.container_type == 'StudentWork' || @attachment.container_type == 'Work'|| @attachment.container_type == 'ContestantWork'|| @attachment.container_type == 'Contest' || @attachment.container_type == 'HomeworkBank'
@project = @attachment.project

View File

@ -1,3 +1,4 @@
#encoding: utf-8
class AvatarController < ApplicationController
include ActionView::Helpers::NumberHelper
@ -10,15 +11,32 @@ class AvatarController < ApplicationController
unless request.content_type == 'application/octet-stream'
@source_type = params[:source_type]
@source_id = params[:source_id]
@temp_file = params[:avatar][:image]
@image_file = @temp_file.original_filename
@temp_file = params[:img] || params[:avatar][:image]
if @temp_file.respond_to?(:original_filename)
@image_file = @temp_file.original_filename
#image_file.force_encoding("UTF-8") if filename.respond_to?(:force_encoding)
else
@image_file=params[:filename]
end
@is_direct = params[:is_direct]
@auth_type = params[:auth_type]
#base64转换
img_base64_head = 'data:image/jpeg;base64,'
if @temp_file && @temp_file.start_with?(img_base64_head)
@temp_file = StringIO.new(Base64.decode64(@temp_file[img_base64_head.size,@temp_file.size-img_base64_head.size]))
end
else
unless request.raw_post.nil?
@source_type = params[:source_type]
@source_id = params[:source_id]
@temp_file = request.raw_post
@is_direct = params[:is_direct]
@auth_type = params[:auth_type]
if @temp_file.size > 0
if @temp_file.respond_to?(:original_filename)
@image_file = @temp_file.original_filename
@ -31,17 +49,26 @@ class AvatarController < ApplicationController
end
end
size = @temp_file.size
if @temp_file && (@temp_file.size > 0)
if @temp_file && (@temp_file.size > 0)
if @temp_file.size > Setting.upload_avatar_max_size.to_i
@status = 1
@msg = l(:error_upload_avatar_to_large, :max_size => number_to_human_size(Setting.upload_avatar_max_size.to_i))
elsif Trustie::Utils::Image.new(@temp_file).image?
diskfile=disk_filename(@source_type,@source_id)
@urlfile='/' << File.join("images","avatars",avatar_directory(@source_type),avatar_filename(@source_id,@image_file))
if @source_type == 'UserAuthentication'
diskfile = disk_auth_filename('UserAuthentication', @source_id, @auth_type)
diskfile1 = diskfile + 'temp'
File.delete(diskfile1) if File.exist?(diskfile1)
@urlfile='/' << File.join("images","avatars",avatar_directory(@source_type),auth_filename(@source_id,@auth_type))
else
@urlfile='/' << File.join("images","avatars",avatar_directory(@source_type),avatar_filename(@source_id,@image_file))
end
# 用户头像上传时进行特别处理
if @is_direct == '1' && (@source_type == 'User' || @source_type == 'Course' || @source_type == 'Project' || @source_type == 'Organization'|| @source_type == 'Contest')
if @is_direct == '1' && (@source_type == 'User' || @source_type == 'Course' || @source_type == 'Project' || @source_type == 'Organization'|| @source_type == 'Contest' || @source_type == 'UserAuthentication')
diskfile += "temp"
@urlfile += "temp"
end
@ -66,7 +93,9 @@ class AvatarController < ApplicationController
end
end
if @source_type == 'Contest'
if @source_type == 'UserAuthentication'
elsif @source_type == 'Contest'
Trustie::Utils::Image.new(diskfile,true).compress(900)
else
Trustie::Utils::Image.new(diskfile,true).compress(300)
@ -76,19 +105,11 @@ class AvatarController < ApplicationController
else
@status = 2
@msg = l(:not_valid_image_file)
logger.error "上传失败: "+@msg
end
end
@temp_file = nil
sleep(3)
unless File.size(diskfile) < size
logger.info("###############################################################sleep")
sleep(0.5)
end
#@src_file = diskfile
respond_to do |format|
format.json{
render :inline => {status: @status, message:@msg, url:"#{@urlfile.to_s}?#{Time.now.to_i}"}.to_json,:content_type => 'text/html'

View File

@ -43,6 +43,7 @@ class BlogCommentsController < ApplicationController
update_messsages_to_viewed("BlogMessage", params[:blog_id])
@article = BlogComment.find(params[:id])
update_visiti_count @article
@replies = BlogComment.where("root_id = #{@article.id}").reorder("created_on desc")
@reply_count = @replies.count
@replies = get_no_children_comments_all @replies

View File

@ -19,9 +19,9 @@ class BoardsController < ApplicationController
layout 'base_projects'#by young
default_search_scope :messages
before_filter :find_project_by_project_id, :find_board_if_available, :except => [:join_to_org_subfields]
before_filter :authorize, :except => [:new, :show, :create, :index, :join_to_org_subfields, :update_position, :update_name]
before_filter :authorize, :except => [:new, :show, :create, :index, :join_to_org_subfields, :update_position, :update_name, :update_boards_position, :update_boards_name]
accept_rss_auth :index, :show
helper :sort
include SortHelper
@ -49,7 +49,7 @@ class BoardsController < ApplicationController
@boards = @course.boards.includes(:last_message => :author).all
if @course.boards.empty?
@board = @course.boards.build
@board.name = " #{l(:label_borad_course) }"
@board.name = "#{l(:label_borad_course)}"
@board.description = @course.name.to_s
@board.project_id = -1
if @board.save
@ -107,6 +107,8 @@ class BoardsController < ApplicationController
end
sort_name = "updated_on"
sort_type = @b_sort == 1 ? "asc" : "desc"
@q = params[:name]
q = "%#{@q}%"
# 讨论区消息状态更新(已读和未读)
if @project
@ -122,7 +124,7 @@ class BoardsController < ApplicationController
# 'replies' => "#{Message.table_name}.replies_count",
# 'updated_on' => "COALESCE(last_replies_messages.created_on, #{Message.table_name}.created_on)"
@is_new = params[:is_new]
# @is_new = params[:is_new]
@topic_count = @board ? @board.topics.count : 0
if @project
if @board
@ -138,7 +140,7 @@ class BoardsController < ApplicationController
if (@board)
@topic_count = @board.topics.count();
@topic_pages = 0 #(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) #{sort_type}").offset(@topic_pages).includes(:last_reply).preload(:author, {:last_reply => :author}).all();
@topics = @board.topics.where("#{Message.table_name}.subject like '#{q}'").reorder("#{Message.table_name}.sticky DESC, COALESCE(last_replies_messages.created_on, #{Message.table_name}.created_on) #{sort_type}").offset(@topic_pages).includes(:last_reply).preload(:author, {:last_reply => :author}).all();
else
@topics = [];
end
@ -146,7 +148,7 @@ class BoardsController < ApplicationController
if (@board)
@topic_count = @board.topics.count();
@topic_pages = 0 #(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) #{sort_type}").offset(@topic_pages).includes(:last_reply).preload(:author, {:last_reply => :author}).all();
@topics = @board.topics.reorder("#{Message.table_name}.sticky DESC, COALESCE(last_replies_messages.created_on, #{Message.table_name}.updated_on) #{sort_type}").offset(@topic_pages).includes(:last_reply).preload(:author, {:last_reply => :author}).all();
else
@board = @contest.boards.build
@board.name = " #{l(:label_board_contest) }"#self.name
@ -156,7 +158,7 @@ class BoardsController < ApplicationController
if @board.save
@topic_count = @board.topics.count();
@topic_pages = 0 #(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) #{sort_type}").offset(@topic_pages).includes(:last_reply).preload(:author, {:last_reply => :author}).all();
@topics = @board.topics.reorder("#{Message.table_name}.sticky DESC, COALESCE(last_replies_messages.created_on, #{Message.table_name}.updated_on) #{sort_type}").offset(@topic_pages).includes(:last_reply).preload(:author, {:last_reply => :author}).all();
else
@topics = []
end
@ -182,6 +184,7 @@ class BoardsController < ApplicationController
@type = 1
end
@all_count = @topics.count
#分页
@limit = 15
@is_remote = true
@ -260,6 +263,10 @@ class BoardsController < ApplicationController
board.project_id = -1
board.position = parent.children.count + 1
parent.children << board
@course_board = @course.boards.where("parent_id is NULL").first
@board = @course_board.children.order("position asc")
@board_count = @board.count
respond_to do |format|
format.js
end
@ -298,6 +305,11 @@ class BoardsController < ApplicationController
after_boards = @board.parent.children.where("position > #{@board.position}")
after_boards.update_all("position = position - 1")
@board.destroy
@course_board = @course.boards.where("parent_id is NULL").first
@board = @course_board.children.order("position asc")
@board_count = @board.count
if @course || @contest
respond_to do |format|
format.js
@ -327,6 +339,29 @@ class BoardsController < ApplicationController
end
end
def update_boards_position
boards = @board.parent.children
if params[:opr] == 'up' && @board.position > 1
before_board = boards.where("position = #{@board.position - 1}").first
if before_board && @board.update_attribute('position', @board.position - 1)
before_board.update_attribute('position', before_board.position + 1)
end
elsif params[:opr] == 'down' && @board.position < boards.count
after_board = boards.where("position = #{@board.position + 1}").first
if after_board && @board.update_attribute('position', @board.position + 1)
after_board.update_attribute('position', after_board.position - 1)
end
end
@course_board = @course.boards.where("parent_id is NULL").first
@board = @course_board.children.order("position asc")
@board_count = @board.count
respond_to do |format|
format.js
end
end
def update_name
if @course || @contest
@board.update_attribute("name", params[:name])
@ -337,6 +372,19 @@ class BoardsController < ApplicationController
end
end
def update_boards_name
@board.update_attribute("name", params[:name])
@board.update_attribute("description", params[:name])
@course_board = @course.boards.where("parent_id is NULL").first
@board = @course_board.children.order("position asc")
@board_count = @board.count
respond_to do |format|
format.js
end
end
def join_to_org_subfields
if params[:id]
@board = Board.find(params[:id])
@ -347,7 +395,7 @@ class BoardsController < ApplicationController
end
end
private
private
def redirect_to_settings_in_projects
redirect_to settings_project_url(@project, :tab => 'boards')
end

View File

@ -1,17 +1,23 @@
# encoding: utf-8
class ChallengesController < ApplicationController
layout "base_shixun"
before_filter :find_shixun, :only => [:index, :new, :create, :destroy, :challenge_build]
before_filter :find_challenge, :only => [:show, :edit, :update, :challenge_build, :index_up, :index_down, :destroy]
before_filter :check_authentication
before_filter :find_shixun, :only => [:index, :new, :create, :destroy, :challenge_build, :update_evaluation, :add_choose_question, :new_choose_question, :choose_type_show, :edit_choose_question, :update_choose_question, :destroy_challenge_choose]
before_filter :find_challenge, :only => [:show, :edit, :update, :challenge_build, :index_up, :index_down, :destroy, :update_evaluation, :add_choose_question, :new_choose_question, :choose_type_show, :edit_choose_question, :update_choose_question, :destroy_challenge_choose]
before_filter :build_challege_from_params, :only => [:new, :create]
before_filter :tpi_manager_allowed, :only => [:challenge_build, :destroy, :show, :edit, :new, :create]
before_filter :query_challeges, :only => [:show, :edit, :update]
before_filter :tpi_manager_allowed, :only => [:challenge_build, :destroy, :edit, :new, :create]
before_filter :allowed_view, :only => [:show]
before_filter :query_challeges, :only => [:show, :edit, :update, :update_evaluation]
before_filter :find_shixun_language, :only => [:show, :new, :edit]
#before_filter :default_format_js, only: :new_or_edit_choose_question
#skip_before_filter :verify_authenticity_token, :only => [:new_or_edit_choose_question]
include ApplicationHelper
def new
# 顶部导航
@st = params[:st].to_i
@project_menu_type = 11
respond_to do |format|
format.html { render :action => 'new', :layout => 'base_shixun' }
@ -19,43 +25,50 @@ class ChallengesController < ApplicationController
end
def create
challenge_count = @shixun.challenges.count
@challenge = Challenge.new(params[:challenge])
@challenge.position = challenge_count + 1
@challenge.shixun = @shixun
@challenge.user = User.current
if @challenge.save
if params[:sample][:input].length > 0
params[:sample][:input].each_with_index do |value, index|
unless (value == params[:sample][:output][index] && value.blank?)
ChallengeSample.create(:challenge_id => @challenge.id, :input => value, :output => params[:sample][:output][index])
ActiveRecord::Base.transaction do
begin
challenge_count = @shixun.challenges.count
@challenge = Challenge.new(params[:challenge])
@challenge.position = challenge_count + 1
@challenge.shixun = @shixun
@challenge.user = User.current
@challenge.st = params[:st].to_i
@challenge.save!
=begin
if @challenge.save!
if params[:st].to_i != 0
#创建选项
params[:question][:cnt].each_with_index do |test, index|
answer = params[:choice][:answer][index] == "0" ? false : true
ChallengeQuestion.create(:option_name => test, :challenge_id => @challenge.id, :position => index, :right_key => answer)
end
end
end
end
if params[:program][:output].length > 0
params[:program][:output].each do |output|
TestSet.create(:challenge_id => @challenge.id, :input => nil, :output => output)
=end
# 实训是否需要重启
# 非实践任务创建第一个阶段时调用 publishGame, 避免不包含实践任务的实训进行模拟实战时报错
if @challenge.position == 1 && params[:st].to_i != 0
add_shixun_modify_status @shixun, 1
else
shixun_modify_status_without_publish(@shixun, 1)
end
end
unless params[:knowledge].blank?
params[:knowledge][:input].each do |input|
ChallengeTag.create(:name => input, :challenge_id => @challenge.id)
end
end
respond_to do |format|
format.html {redirect_to shixun_challenge_path(@challenge, :shixun_id => @shixun), notice: '创建成功!'}
end
else
respond_to do |format|
format.html { render :action => 'new' }
redirect_to edit_shixun_challenge_path(@challenge, :shixun_id => @shixun)
rescue Exception => e
flash[:error] = "#{e.message}"
redirect_to new_shixun_challenge_path(:shixun_id => @shixun, :st => params[:st].to_i)
raise ActiveRecord::Rollback
end
end
end
# 处理新建challenge返回的pipeline片段
def fragment_from_jenkins
end
def index
# 顶部导航
@challenges = @shixun.challenges.order("position desc")
@challenges = @shixun.challenges.order("position asc")
respond_to do |format|
format.js
format.html
@ -65,6 +78,12 @@ class ChallengesController < ApplicationController
end
def show
challenge_num = Challenge.where(:shixun_id => @shixun).count
challenge_pos = @challenge.position
if challenge_pos < challenge_num
@next_challenge = Challenge.where(:shixun_id => @shixun, :position => challenge_pos + 1).first
end
@prev_challenge = Challenge.where(:shixun_id => @shixun, :position => challenge_pos - 1).first if challenge_pos - 1 > 0
respond_to do |format|
format.html
format.js
@ -72,56 +91,205 @@ class ChallengesController < ApplicationController
end
def edit
end
def destroy
@challenge.destroy
@st = @challenge.st
challenge_num = Challenge.where(:shixun_id => @shixun).count
challenge_pos = @challenge.position
if challenge_pos < challenge_num
@next_challenge = Challenge.where(:shixun_id => @shixun, :position => challenge_pos+1).first
end
@prev_challenge = Challenge.where(:shixun_id => @shixun, :position => challenge_pos - 1).first if (challenge_pos - 1) > 0
@tab = params[:tab].blank? ? 1 : params[:tab].to_i
@editor = params[:editor] # 编辑模式
respond_to do |format|
format.html{redirect_to shixun_challenges_path(@shixun)}
format.html
format.js
end
end
def update
def new_choose_question
ActiveRecord::Base.transaction do
begin
@challenge_choose = ChallengeChoose.new
@challenge_choose.challenge_id = @challenge.id
@challenge_choose.subject = params[:choose][:subject]
@challenge_choose.answer = params[:choose][:answer]
@challenge_choose.standard_answer = params[:standard_answer]
@challenge_choose.score = params[:challenge][:score].to_i
@challenge_choose.difficult = params[:challenge][:difficulty].to_i
@challenge_choose.position = params[:position].to_i
@challenge_choose.category = params[:category].to_i
if @challenge_choose.save!
# 创建选项
params[:question][:cnt].each_with_index do |test, index|
answer = params[:choice][:answer][index] == "0" ? false : true
ChallengeQuestion.create(:option_name => test, :challenge_choose_id => @challenge_choose.id, :position => index, :right_key => answer)
end
# 创建单选多选的技能标签
unless params[:knowledge].blank?
params[:knowledge][:input].each do |input|
ChallengeTag.create(:name => input, :challenge_choose_id => @challenge_choose.id, :challenge_id => @challenge.id)
end
end
end
@index = params[:position].to_i - 1
# 发起重置请求
shixun_modify_status_without_publish(@shixun, 1)
respond_to do |format|
format.js
end
rescue Exception => e
flash[:error] = "#{e.message}"
redirect_to edit_shixun_challenge_path(@challenge, :shixun_id => @shixun)
raise ActiveRecord::Rollback
end
end
end
def update_choose_question
@challenge_choose = ChallengeChoose.where(:id => params[:choose_id]).first
ActiveRecord::Base.transaction do
@challenge_choose.update_attributes(:subject => params[:choose][:subject],
:answer => params[:choose][:answer],
:standard_answer => params[:standard_answer],
:score => params[:challenge][:score].to_i,
:difficult => params[:challenge][:difficulty].to_i)
begin
@challenge_choose.challenge_questions.delete_all
params[:question][:cnt].each_with_index do |test, index|
answer = params[:choice][:answer][index] == "0" ? false : true
ChallengeQuestion.create(:option_name => test, :challenge_choose_id => @challenge_choose.id, :position => index, :right_key => answer)
end
# 发起重置请求
shixun_modify_status_without_publish(@shixun, 1)
@challenge_choose.challenge_tags.delete_all unless @challenge_choose.challenge_tags.blank?
unless params[:knowledge].blank?
params[:knowledge][:input].each do |input|
ChallengeTag.create(:name => input, :challenge_choose_id => @challenge_choose.id, :challenge_id => @challenge.id)
end
end
@challenge_choose = ChallengeChoose.where(:id => params[:choose_id]).first
@index = params[:index].to_i
respond_to do |format|
format.js
end
rescue Exception => e
flash[:error] = "#{e.message}"
format.html{redirect_to edit_shixun_challenge_path(@challenge, :shixun_id => @shixun)}
raise ActiveRecord::Rollback
end
end
end
def edit_choose_question
@challenge_choose = ChallengeChoose.where(:id => params[:choose_id]).first
@category = @challenge_choose.category
@position = @challenge_choose.position.to_i
@index = params[:index].to_i
respond_to do |format|
if @challenge.update_attributes(params[:challenge])
ActiveRecord::Base.transaction do
@challenge_samples.delete_all unless @challenge_samples.blank?
format.js
end
end
def choose_type_show
@challenge_choose = ChallengeChoose.where(:id => params[:choose_id]).first
@index = params[:index].to_i
respond_to do |format|
format.js
end
end
def destroy_challenge_choose
@challenge_choose = ChallengeChoose.where(:id => params[:choose_id]).first
@challenge_choose.destroy
# 发起重置请求
shixun_modify_status_without_publish(@shixun, 1)
redirect_to edit_shixun_challenge_path(@challenge, :shixun_id => @shixun)
end
def add_choose_question
@category = params[:category].to_i
@position = params[:position].to_i
#@challenge_choose = @challenge.challenge_chooses
respond_to do |format|
format.js
end
end
def destroy
next_challenges = @shixun.challenges.where("position > #{@challenge.position}")
next_challenges.update_all("position = position - 1")
@challenges = @shixun.challenges
add_shixun_modify_status(@shixun, 1)
@challenge.destroy
end
def update
ActiveRecord::Base.transaction do
@challenge.update_attributes(params[:challenge])
#if (params[:tab] == "1" || params[:tab].nil?) && @challenge.st != 0
# begin
# @challenge.challenge_questions.delete_all
# params[:question][:cnt].each_with_index do |test, index|
# answer = params[:choice][:answer][index] == "0" ? false : true
# ChallengeQuestion.create(:option_name => test, :challenge_id => @challenge.id, :position => index, :right_key => answer)
# end
# redirect_to edit_shixun_challenge_path(@challenge, :shixun_id => @shixun, :tab => params[:tab])
# rescue Exception => e
# flash[:error] = "#{e.message}"
# format.html{redirect_to edit_shixun_challenge_path(@challenge, :shixun_id => @shixun)}
# raise ActiveRecord::Rollback
# end
#else
redirect_to edit_shixun_challenge_path(@challenge, :shixun_id => @shixun, :tab => params[:tab])
#end
end
end
def update_evaluation
ActiveRecord::Base.transaction do
@challenge.update_attributes(params[:challenge])
begin
if params[:tab].to_i == 2
@test_sets.delete_all unless @test_sets.blank?
@challenge_tags.delete_all unless @challenge_tags.blank?
if params[:sample][:input].length > 0
params[:sample][:input].each_with_index do |value, index|
unless (value == params[:sample][:output][index] && value.blank?)
ChallengeSample.create(:challenge_id => @challenge.id, :input => value, :output => params[:sample][:output][index])
if params[:test_set][:hidden].length > 0
params[:test_set][:input].each_with_index do |input, index|
unless (input[index] == params[:test_set][:output][index] && input[index].nil?)
params[:test_set][:hidden][index].to_i == 0 ? open = 1 : open = 0
TestSet.create(:challenge_id => @challenge.id, :input => input, :output => params[:test_set][:output][index], :is_public => open, :position => (index + 1))
end
end
end
if params[:program][:output].length > 0
params[:program][:output].each do |output|
TestSet.create(:challenge_id => @challenge.id, :input => nil, :output => output)
end
end
# 向jenkins端发送请求构建公共测试用例
shixun_modify_status_publish(@shixun, 1)
elsif params[:tab].to_i == 5
@challenge_tags.delete_all unless @challenge_tags.blank?
unless params[:knowledge].blank?
params[:knowledge][:input].each do |input|
ChallengeTag.create(:name => input, :challenge_id => @challenge.id)
end
end
end
format.html {redirect_to shixun_challenge_path(@challenge, :shixun_id => @shixun), notice: '更新成功!'}
format.json { head :no_content }
else
format.html { render action: "edit" }
format.json { render json: @challenge.errors }
if params[:tab].to_i == 5
redirect_to edit_shixun_challenge_path(@challenge, :shixun_id => @shixun, :tab => params[:tab]), notice: 'Succeed'
else
redirect_to edit_shixun_challenge_path(@challenge, :shixun_id => @shixun, :tab => params[:tab])
end
rescue Exception => e
flash[:error] = "#{e.message}"
redirect_to edit_shixun_challenge_path(@challenge, :shixun_id => @shixun, :tab => params[:tab])
raise ActiveRecord::Rollback
end
end
end
def index_down
next_challenge = @challenge.next_challenge
position = @challenge.position
@challenge.update_attribute(:position, (position + 1))
next_challenge.update_attribute(:position, next_challenge.position - 1)
@challenges = @shixun.challenges
# 向jenkins端发送请求构建公共测试用例
add_shixun_modify_status(@shixun, 1)
end
def index_up
@ -130,12 +298,14 @@ class ChallengesController < ApplicationController
@challenge.update_attribute(:position, (position - 1))
last_challenge.update_attribute(:position, last_challenge.position + 1)
@challenges = @shixun.challenges
# 向jenkins端发送请求构建公共测试用例
add_shixun_modify_status(@shixun, 1)
end
# build job 只负责发送请求
def challenge_build
gitUrl = git_repository_url(@shixun, "Shixun")
gitUrl = Base64.encode64(gitUrl)
gitUrl = Base64.urlsafe_encode64(gitUrl)
taskId = params[:id]
jobName = @shixun.forked_form
step = @challenge.position
@ -168,6 +338,12 @@ class ChallengesController < ApplicationController
end
end
def allowed_view
unless (allow_to_view_challenge(@challenge, @shixun) || User.current.manager_of_shixun?(@shixun))
render_403
end
end
def build_challege_from_params
if params[:id].blank?
@challenge = Challenge.new
@ -181,7 +357,6 @@ class ChallengesController < ApplicationController
end
def query_challeges
@challenge_samples = @challenge.challenge_samples
@test_sets = @challenge.test_sets
@challenge_tags = @challenge.challenge_tags
end
@ -196,7 +371,16 @@ class ChallengesController < ApplicationController
# Find project of id params[:id]
def find_shixun
shixun_id = params[:shixun_id] || (params[:challenge] && params[:challenge][:shixun_id])
@shixun = Shixun.find(shixun_id)
@shixun = Shixun.find_by_identifier(shixun_id)
if @shixun.nil?
render_404
return
else
if (@shixun.status == 0 && !(User.current.manager_of_shixun?(@shixun) || User.current.admin?))
render_403
return
end
end
rescue ActiveRecord::RecordNotFound
render_404
end
@ -206,4 +390,8 @@ class ChallengesController < ApplicationController
@language = language_switch language
end
def default_format_js
response.headers['content--type'] = 'text/javascript'
request.format = 'js'
end
end

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,2 @@
class DebatesController < ApplicationController
end

View File

@ -0,0 +1,120 @@
class DepartmentController < ApplicationController
before_filter :find_department, :only => [:destroy]
#根据部门名字或者拼音来查询
def on_search
school = School.find params[:school_id]
if school
condition = "#{params[:name].strip}".gsub(" ","")
#获取拼音的第一次出现的位置
if(condition == '')
@departments = school.departments.order("CONVERT(name USING gbk) COLLATE gbk_chinese_ci asc").page((params[:page].to_i || 1) - 1).per(100)
@department_count = school.departments.count
else
@departments = school.departments.where("name like '%#{condition}%'").order("CONVERT(name USING gbk) COLLATE gbk_chinese_ci asc").page((params[:page].to_i || 1) - 1).per(100)
@department_count = school.departments.where("name like '%#{condition}%'").count
end
render :json =>{ :departments => @departments,:count=>@department_count}.to_json
end
end
#申请学院或部门(单位) name:名称 remarks:备注
def apply_add_department
school = School.find params[:school_id]
data = {result:0,name:params[:name],department_id:0}
#0 成功 1参数错误 2名称已存在 3.失败
data[:result] = 0
if school
#检验参数
if params[:name] == ""
data[:result] = 1
else
department = Department.where(:school_id => school.id, :name => params[:name]).first
if department
data[:result] = 2
else
department = Department.new
department.name = params[:name].strip
department.school = school
#status 0未处理 1通过 2拒绝
apply_department = ApplyAddDepartment.new
#用belongs_to 可以一起存数据库
apply_department.department = department
apply_department.school = department.school
apply_department.name = department.name
apply_department.status = 0
apply_department.remarks = params[:remarks]
apply_department.user_id = User.current.id
if apply_department.save
data[:department_id] = department.id
unless User.current.professional_certification
user_extention = User.current.extensions
user_extention.department_id = department.id
user_extention.save!
end
# 向管理员发送信息
users = User.where(:admin => 1)
users.each do |user|
AppliedMessage.create(:user_id => user.id, :status => 0, :applied_user_id => User.current.id, :viewed => 0, :applied_id => apply_department.id, :applied_type => "ApplyAddDepartment", :name => department.name )
end
else
data[:result] = 3
end
end
end
else
data[:result] = 4
end
render :json =>data
end
def search_repeat_departmentname
status = 0 #没有重复的
name = params[:name]
school = School.where(:id => params[:school_id].to_i).first
if school
if name
department = school.departments.where(:name => name).first
if department
status = 1 #有重复的
else
status = 2 #无重复的
end
end
else
status = 0
end
render :json =>status
end
def destroy
if @department
# if UserExtensions.where(:department_id => @department.id).count == 0
ApplyAddDepartment.where(:department_id=>@department.id).update_all(:status => 2)
@apply_dep = ApplyAddDepartment.where(:department_id=>@department.id).first
@department.destroy
# end
respond_to do |format|
format.js
end
end
end
private
def find_department
@department = Department.find params[:id]
rescue ActiveRecord::RecordNotFound
render_404
end
end

View File

@ -0,0 +1,80 @@
# encoding: utf-8
class DiscussesController < ApplicationController
include ApplicationHelper
before_filter :find_dis_object, :except => [:destroy]
before_filter :find_discuss, :only => [:destroy]
def create
if @model
if params[:reply_id].blank?
notes = User.current.show_name.to_s + " 评论了你发布的实训:<a href='#{shixun_discuss_shixun_path(@model)}'>#{params[:content]}</a>"
@model.discusses << Discuss.new(:content => params[:content], :user_id => User.current.id, :praise_count => 0, :challenge_id => params[:challenge_id])
JournalsForMessage.create(
:jour_id => @model.user_id,
:jour_type => "Principal",
:user_id => User.current.id,
:reply_id => 0,
:is_readed => 0,
:private => 1,
:notes => notes
)
else
notes = User.current.show_name.to_s + " 评论了你的回复:<a href='#{shixun_discuss_shixun_path(@model)}'>#{params[:content]}</a>"
user_id = Discuss.find(params[:reply_id]).try(:user_id)
@model.discusses << Discuss.new(
:content => params[:content],
:user_id => User.current.id,
:parent_id => params[:reply_id],
:root_id => params[:reply_id],
:praise_count => 0,
:challenge_id => params[:challenge_id]
)
JournalsForMessage.create(
:jour_id => user_id,
:jour_type => "Principal",
:user_id => User.current.id,
:reply_id => 0,
:is_readed => 0,
:private => 1,
:notes => notes
)
end
if params[:dis_type] == "Shixun"
redirect_to shixun_discuss_shixun_path(@model, :challenge_id => params[:challenge_id])
end
end
end
def destroy
if @discuss
if @discuss.dis_type == "Shixun"
@shixun = @discuss.dis
end
@discuss.destroy
@game_challenge = Challenge.find(params[:challenge_id])
end
end
private
def find_discuss
@discuss = Discuss.find params[:id]
rescue ActiveRecord::RecordNotFound
render_404
end
def find_dis_object
unless params[:dis_id] && params[:dis_type]
render_404
else
case params[:dis_type]
when 'Shixun'
@model = Shixun.find params[:dis_id]
end
end
rescue ActiveRecord::RecordNotFound
render_404
end
end

View File

@ -1,115 +1,109 @@
#encoding: utf-8
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, :update_question_num,
:send_to_course, :get_student_uncomplete_question, :edit_question_score]
:send_to_course, :get_student_uncomplete_question, :edit_question_score, :setting, :set_public,
:ex_setting]
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")
#remove_invalid_exercise(@course)
@is_teacher = User.current.allowed_to?(:as_teacher,@course) || User.current.admin?
if @is_teacher
exercises = @course.exercises.order("created_at desc")
else
exercises = @course.exercises.where("exercise_status <> 1").order("created_at asc")
exercises = @course.exercises.where("exercise_status <> 1").order("created_at desc")
end
@exercises = paginateHelper exercises,20 #分页
@left_nav_type = 8
if params[:type]
@type = params[:type]
exercises = exercises.where(:exercise_status => params[:type])
end
@search = params[:search] ? params[:search].to_s.strip : ""
if params[:search]
exercises = exercises.where("exercise_name like '%#{@search}%'")
end
@exercises = paginateHelper exercises,15 #分页
@left_nav_type = 4
respond_to do |format|
format.js
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]
@exercise.course_messages.each do |message|
if User.current.id == message.user_id && message.viewed == 0
message.update_attributes(:viewed => true) if message.viewed == 0
end
end
@is_teacher = User.current.allowed_to?(:as_teacher,@course) || User.current.admin?
exercise_end = @exercise.end_time.nil? ? false : @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
elsif @exercise_user.start_at.nil?
@exercise_user.update_attributes(:start_at => Time.now)
end
exercise_end = @exercise.end_time.nil? ? false : @exercise.end_time > Time.now
if @exercise.time == -1
@can_edit_excercise = exercise_end && @exercise_user.commit_status == 0
else
@can_edit_excercise = !has_commit_exercise?(@exercise.id,User.current.id) && exercise_end
end
#score = calculate_student_score(@exercise, User.current)
#@exercise_user.update_attributes(:objective_score => score, :score => (score + (@exercise_user.subjective_score > 0 ? @exercise_user.subjective_score : 0)))
else
@can_edit_excercise = false
end
# @percent = get_percent(@exercise,User.current)
@exercise_questions = @exercise.exercise_questions
@left_nav_type = 8
#@exercise_questions = @exercise.exercise_questions
respond_to do |format|
format.html {render :layout => 'base_courses'}
format.html {render :layout => 'base_edu'}
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
# 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.new
respond_to do |format|
format.html{render :layout => 'base_edu'}
end
end
def create
if params[:exercise]
exercise = Exercise.find(params[:exercise_id]) if params[:exercise_id]
exercise ||= Exercise.new
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.time = -1
exercise.exercise_status = 1
if exercise.save
@exercise = exercise
@ -121,21 +115,15 @@ class ExerciseController < ApplicationController
end
def edit
@left_nav_type = 8
respond_to do |format|
format.html{render :layout => 'base_courses'}
end
format.html{render :layout => 'base_edu'}
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[:show_result] ? 1 : 0
@exercise.question_random = params[:question_random] ? 0 : 1
@exercise.choice_random = params[:choice_random] ? 0 : 1
if @exercise.save
respond_to do |format|
format.js
@ -148,15 +136,34 @@ class ExerciseController < ApplicationController
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
redirect_to exercise_index_path(:course_id => @course.id)
end
end
def setting
@is_teacher = User.current.allowed_to?(:as_teacher,@course) || User.current.admin?
@is_new = params[:is_new] ? true : false
respond_to do |format|
format.html{render :layout => 'base_edu'}
end
end
def ex_setting
@exercise.publish_time = params[:exercise_publish_time] if params[:exercise_publish_time]
@exercise.end_time = params[:exercise_end_time] if params[:exercise_end_time]
@exercise.time = -1
@exercise.question_random = params[:question_random] ? 1 : 0
@exercise.choice_random = params[:choice_random] ? 1 : 0
@exercise.score_open = params[:score_open] ? 1 : 0
@exercise.answer_open = params[:answer_open] ? 1 : 0
if @exercise.save
redirect_to student_exercise_list_exercise_path(@exercise)
end
end
def set_public
if User.current.admin? || User.current.allowed_to?(:as_teacher, @course)
@exercise.update_attributes(:is_public => true)
end
end
@ -165,7 +172,7 @@ class ExerciseController < ApplicationController
@exercise = Exercise.find(params[:id])
exercise_questions = @exercise.exercise_questions
@exercise_questions = paginateHelper exercise_questions, 5
@left_nav_type = 8
@left_nav_type = 4
respond_to do |format|
format.html{render :layout => 'base_courses'}
end
@ -178,10 +185,7 @@ class ExerciseController < ApplicationController
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) :
(params[:question_type] == "3" ? (@exercise.exercise_questions.where("question_type = 3").count + 1) :
@exercise.exercise_questions.where("question_type = 4").count + 1)),
:question_number => @exercise.exercise_questions.count + 1,
:question_score => params[:question_score]
}
@exercise_questions = @exercise.exercise_questions.new option
@ -197,20 +201,23 @@ class ExerciseController < ApplicationController
end
end
# 如果是插入的话那么从插入的这个id以后的question_num都将要+1
if params[:quest_id]
if params[:quest_id] != "0"
@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")
elsif @exercise_questions.question_type == 3
ExerciseQuestion.where("question_number>? and question_type=?",params[:quest_num].to_i, 3).update_all(" question_number = question_number + 1")
else
ExerciseQuestion.where("question_number>? and question_type=?",params[:quest_num].to_i, 4).update_all(" question_number = question_number + 1")
insert_que = ExerciseQuestion.find params[:quest_id]
if insert_que
@exercise.exercise_questions.where("question_number>?",insert_que.question_number).update_all("question_number = question_number + 1")
# if @exercise_questions.question_type == 1
# ExerciseQuestion.where("question_number>?",params[:quest_num].to_i).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")
# elsif @exercise_questions.question_type == 3
# ExerciseQuestion.where("question_number>? and question_type=?",params[:quest_num].to_i, 3).update_all(" question_number = question_number + 1")
# else
# ExerciseQuestion.where("question_number>? and question_type=?",params[:quest_num].to_i, 4).update_all(" question_number = question_number + 1")
# end
# @exercise_question_num = params[:quest_num].to_i
@exercise_questions.question_number = insert_que.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] 标准答案参数
@ -327,16 +334,17 @@ class ExerciseController < ApplicationController
@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")
elsif @exercise_question.question_type == 3
ExerciseQuestion.where("question_number>? and question_type=?",params[:quest_num].to_i, 3).update_all(" question_number = question_number - 1")
else
ExerciseQuestion.where("question_number>? and question_type=?",params[:quest_num].to_i, 4).update_all(" question_number = question_number - 1")
end
ExerciseQuestion.where("question_number>?",params[:quest_num].to_i).update_all("question_number = question_number - 1")
# 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")
# elsif @exercise_question.question_type == 3
# ExerciseQuestion.where("question_number>? and question_type=?",params[:quest_num].to_i, 3).update_all(" question_number = question_number - 1")
# else
# ExerciseQuestion.where("question_number>? and question_type=?",params[:quest_num].to_i, 4).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
#
@ -358,12 +366,12 @@ class ExerciseController < ApplicationController
exercise_questions = @exercise.exercise_questions
if @exercise_question
if params[:opr] == 'up' && @exercise_question.question_number > 1
@before_que = exercise_questions.where("question_type = #{@exercise_question.question_type} and question_number = #{@exercise_question.question_number - 1}").first
@before_que = exercise_questions.where("question_number = #{@exercise_question.question_number - 1}").first
if @before_que && @exercise_question.update_attribute('question_number', @exercise_question.question_number - 1)
@before_que.update_attribute('question_number', @before_que.question_number + 1)
end
elsif params[:opr] == 'down' && @exercise_question.question_number < exercise_questions.count
@after_que = exercise_questions.where("question_type = #{@exercise_question.question_type} and question_number = #{@exercise_question.question_number + 1}").first
@after_que = exercise_questions.where("question_number = #{@exercise_question.question_number + 1}").first
if @after_que && @exercise_question.update_attribute('question_number', @exercise_question.question_number + 1)
@after_que.update_attribute('question_number', @after_que.question_number - 1)
end
@ -470,77 +478,69 @@ class ExerciseController < ApplicationController
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
@name,@select_group = params[:name].to_s.strip || "",params[:group]
@order,@b_sort,@name,@group,@comment,@status = params[:order] || "end_at",params[:sort] || "desc",params[:name].to_s.strip || "",params[:ex_group], params[:ex_comment], params[:ex_status]
@is_teacher = User.current.allowed_to?(:as_teacher,@course) || User.current.admin?
if @is_teacher
@all_exercises = @course.exercises.order("created_at desc")
else
@all_exercises = @course.exercises.where("exercise_status > 1").order("created_at desc")
end
student_id = @course.student.blank? ? "(-1)" : "(" + @course.student.map{|student| student.student_id}.join(",") + ")"
if @select_group
if @select_group == "0"
none_group_students = @course.members.select{ |member| member.course_group_id == 0 }
if none_group_students.empty?
student_in_group = '(0)'
else
student_in_group = '(' + none_group_students.map{ |member| member.user_id }.join(',') + ')'
end
elsif @select_group == "-1"
all_group_students = @course.members.select{ |member| member.course_group_id }
if all_group_students.empty?
student_in_group = '(0)'
else
student_in_group = '(' + all_group_students.map{ |member| member.user_id }.join(',') + ')'
end
if @group
group_students = @course.members.where(:course_group_id => @group).joins("join users on members.user_id = users.id").select{|m| m.roles.to_s.include?("Student")}
if group_students.empty?
student_in_group = '(-1)'
else
course_group = CourseGroup.find_by_id(@select_group)
group_students = course_group.users
if group_students.empty?
student_in_group = '(0)'
else
student_in_group = '(' + group_students.map{ |user| user.id }.join(',') + ')'
end
student_in_group = '(' + group_students.map{ |member| member.user_id }.join(',') + ')'
end
if @is_teacher || (!@exercise.exercise_users.where("user_id = #{User.current.id}").empty? && @exercise.end_time <= Time.now)
@exercise_users_list = search_exercise_member @exercise.exercise_users.where("user_id in #{student_id} and user_id in #{student_in_group}"), @name
if @is_teacher || (!@exercise.exercise_users.where(:user_id => User.current.id, :commit_status => 1).empty? && @exercise.score_open && @exercise.end_time <= Time.now)
@exercise_users_list = @exercise.exercise_users.where("user_id in #{student_in_group}").order("#{@order} #{@b_sort}")
@show_all = true;
elsif !@exercise.exercise_users.where("user_id = #{User.current.id}").empty? && @exercise.end_time > Time.now
@exercise_users_list = search_exercise_member @exercise.exercise_users.where("user_id = ? and user_id in #{student_id} and user_id in #{student_in_group}",User.current.id), @name
elsif !@exercise.exercise_users.where(:user_id => User.current.id, :commit_status => 1).empty?
@exercise_users_list = @exercise.exercise_users.where("user_id = ? and user_id in #{student_in_group}",User.current.id)
else
@exercise_users_list = []
end
else
if @is_teacher || (!@exercise.exercise_users.where("user_id = #{User.current.id}").empty? && @exercise.end_time <= Time.now)
@exercise_users_list = search_exercise_member @exercise.exercise_users.where("user_id in #{student_id}"), @name
if @is_teacher || (!@exercise.exercise_users.where(:user_id => User.current.id, :commit_status => 1).empty? && @exercise.score_open && @exercise.end_time <= Time.now)
@exercise_users_list = @exercise.exercise_users.where("user_id in #{student_id}").order("#{@order} #{@b_sort}")
@show_all = true;
elsif !@exercise.exercise_users.where("user_id = #{User.current.id}").empty? && @exercise.end_time > Time.now
@exercise_users_list = search_exercise_member @exercise.exercise_users.where("user_id = ? and user_id in #{student_id}",User.current.id), @name
elsif User.current.member_of_course?(@course)
@exercise_users_list = @exercise.exercise_users.where("user_id = ? and user_id in #{student_id}",User.current.id)
else
@exercise_users_list = []
end
end
@exercise_count = @exercise.exercise_users.where("commit_status = 1 and user_id in #{student_id}").count
@left_nav_type = 8
unless @comment.blank?
if @comment.include?('0')
@exercise_users_list = @exercise_users_list.where(:subjective_score => -1)
else
@exercise_users_list = @exercise_users_list.where("subjective_score != -1")
end
end
unless @status.blank?
@exercise_users_list = @exercise_users_list.where(:commit_status => @status)
end
@exercise_users_list = search_exercise_member @exercise_users_list, @name
@tab = params[:tab].nil? ? 1 : params[:tab].to_i
@score = @b_sort == "desc" ? "asc" : "desc"
@exercise_count = @exercise_users_list.count
@has_commit_count = @exercise.exercise_users.where(:commit_status => 1).count
@no_group_count = @course.members.where(:course_group_id => 0).select{|m| m.roles.to_s.include?("Student")}.count
@limit = 50
@is_remote = true
@page = (params['page'] || 1).to_i
@exercise_pages = Paginator.new @exercise_count, @limit, @page
@offset ||= @exercise_pages.offset
@exercise_users_list = paginateHelper @exercise_users_list, @limit
respond_to do |format|
format.js
format.html
format.html{render :layout => 'base_edu'}
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"
filename = "#{@course.teacher.lastname.to_s + @course.teacher.firstname}_#{@course.name}_#{@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))
}
@ -690,11 +690,11 @@ class ExerciseController < ApplicationController
else
# 更新提交状态
cur_exercise_user = ExerciseUser.where("user_id =? and exercise_id=?", User.current, @exercise.id).first
cur_exercise_user.update_attributes(:status => 1, :commit_status => 1)
if @exercise.time && @exercise.time != -1
cur_exercise_user.update_attributes(:status => 1, :commit_status => 1, :end_at => Time.now)
#if @exercise.time && @exercise.time != -1
score = calculate_student_score(@exercise, User.current)
cur_exercise_user.update_attributes(:score => score)
end
cur_exercise_user.update_attributes(:objective_score => score, :score => score + (cur_exercise_user.subjective_score > 0 ? cur_exercise_user.subjective_score : 0))
#end
# 答题过程中需要统计完成量
#@uncomplete_question = get_uncomplete_question(@exercise, User.current)
# 获取改学生的考试得分
@ -748,16 +748,20 @@ class ExerciseController < ApplicationController
#查看学生的答卷情况
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
@left_nav_type = 8
respond_to do |format|
format.html {render :layout => 'base_courses'}
@is_teacher = User.current.allowed_to?(:as_teacher,@course) || User.current.admin?
if @is_teacher || (User.current.member_of_course?(@exercise.course) && @exercise.exercise_status > 2)
@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_edu'}
end
else
render_403
end
end
@ -820,11 +824,13 @@ class ExerciseController < ApplicationController
# 查作者是我,或者作者是当前课程的老师,且不在当前课程内的试卷 进行导入
@order,@b_sort = params[:order] || "created_at",params[:sort] || "desc"
@r_sort = @b_sort == "desc" ? "asc" : "desc"
courses = User.current.courses.not_deleted.select { |course| User.current.allowed_to?(:as_teacher,course)}
course_ids = courses.empty? ? "(-1)" : "(" + courses.map { |course| course.id}.join(',') + ")"
@search = params[:search] ? params[:search].to_s.strip.downcase : ""
#courses = User.current.courses.not_deleted.select { |course| User.current.allowed_to?(:as_teacher,course)}
#course_ids = courses.empty? ? "(-1)" : "(" + courses.map { |course| course.id}.join(',') + ")"
#none_courses = User.current.courses.where("is_delete = 1 or #{Course.table_name}.id = #{params[:course_id].to_i}")
#none_course_ids = none_courses.empty? ? "(-1)" : "(" + none_courses.map { |course| course.id}.join(',') + ")"
@exercises = Exercise.where("(user_id = #{User.current.id} or course_id in #{course_ids}) and course_id != #{params[:course_id].to_i}").order("#{@order} #{@b_sort}")
#@exercises = Exercise.where("(user_id = #{User.current.id} or course_id in #{course_ids}) and course_id != #{params[:course_id].to_i} and exercise_name like '%#{@search}%'").order("#{@order} #{@b_sort}")
@exercises = Exercise.where("user_id = #{User.current.id} and exercise_name like '%#{@search}%'").order("#{@order} #{@b_sort}")
@course_id = params[:course_id]
@is_remote = true
@ex_count = @exercises.count
@ -859,15 +865,15 @@ class ExerciseController < ApplicationController
def import_other_exercise
course_id = params[:course_id]
@course = Course.find(course_id)
params[:exercise_id].each_with_index do |ex,i|
exercise = Exercise.find(ex)
if params[:exercise_id]
exercise = Exercise.find(params[:exercise_id])
option = {
:exercise_name => exercise.exercise_name,
:exercise_status => 1,
:user_id => User.current.id,
:show_result => 1,
:course_id => @course.id,
:time => exercise.time,
:time => -1,
:exercise_description => exercise.exercise_description
}
@exercise = Exercise.create option
@ -899,9 +905,6 @@ class ExerciseController < ApplicationController
end
@exercise.save
end
respond_to do |format|
format.js
end
end
private
@ -937,7 +940,7 @@ class ExerciseController < ApplicationController
else
name = name.downcase
select_exercises = exercises.select{ |exercise|
exercise.user[:login].to_s.downcase.include?(name) || exercise.user.user_extensions[:student_id].to_s.downcase.include?(name) || (exercise.user[:lastname].to_s.downcase + exercise.user[:firstname].to_s.downcase).include?(name)
exercise.user.user_extensions[:student_id].to_s.downcase.include?(name) || (exercise.user[:lastname].to_s.downcase + exercise.user[:firstname].to_s.downcase).include?(name)
}
end
select_exercises

View File

@ -74,21 +74,21 @@ class FilesController < ApplicationController
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,@course
# @searched_attach = paginateHelper @result,10
end
else
# if params[:insite]
# if q == "%%"
# @result = []
# # @searched_attach = paginateHelper @result,10
# else
# @result = find_public_attache q,sort
# @result = visable_attachemnts_insite @result,@course
# # @searched_attach = paginateHelper @result,10
# end
# else
@result = find_course_attache q,@course,sort
@result = visable_attachemnts @result
# @searched_attach = paginateHelper @result,10
@tag_list = get_course_tag_list @course
end
#@tag_list = get_course_tag_list @course
#end
@all_attachments = @result
get_attachment_for_tip(@all_attachments)
@limit = 10
@ -124,6 +124,9 @@ class FilesController < ApplicationController
else
@file.is_publish = 1
end
if @file.is_public == 0 && params[:is_public]
@file.is_public = 1
end
@file.save
respond_to do |format|
format.js
@ -223,9 +226,9 @@ class FilesController < ApplicationController
sort = "created_on DESC"
end
if keywords != "%%"
resultSet = Attachment.where("attachments.container_type = 'Course' And attachments.container_id = '#{course.id}' AND filename LIKE :like ", like: "%#{keywords}%").reorder(sort)
resultSet = Attachment.where("attachments.container_type = 'Course' And attachments.container_id = '#{course.id}' AND (filename LIKE '#{keywords}' or description LIKE '#{keywords}')").reorder(sort)
else
resultSet = Attachment.where("attachments.container_type = 'Course' And attachments.container_id = '#{course.id}' "). reorder(sort)
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")
end
@ -377,6 +380,8 @@ class FilesController < ApplicationController
end
end
else
@sort = "created_on"
@order = "desc"
sort = "#{Attachment.table_name}.created_on desc"
end
@ -385,7 +390,7 @@ class FilesController < ApplicationController
show_attachments @containers
get_attachment_for_tip(@all_attachments)
@tag_list = attachment_tag_list @all_attachments
#@tag_list = attachment_tag_list @all_attachments
@left_nav_type = 5
render :layout => 'base_courses'
@ -597,7 +602,12 @@ class FilesController < ApplicationController
attachment.publish_time = Time.now
end
attachment.description = params[:description]
attachment.is_public = params[:is_public] ? 1 : 0
attachment.save
resource_bank = ResourceBank.create(:course_id => @course.id, :attachment_id => attachment.id, :filename => attachment.filename, :disk_filename => attachment.disk_filename, :filesize => attachment.filesize, :digest => attachment.digest, :downloads => 0,
:user_id => attachment.author_id, :description => attachment.description, :disk_directory => attachment.disk_directory, :is_public => attachment.is_public, :copy_from => attachment.copy_from,
:quotes => 1, :applicable_syllabus => @course.course_list_name, :content_type => attachment.content_type)
attachment.update_column('resource_bank_id', resource_bank.id)
end
end
if params[:course_attachment_type] && params[:course_attachment_type].is_a?(Array)
@ -935,7 +945,7 @@ class FilesController < ApplicationController
@tag_list = get_project_tag_list @project
@result_search_project = @result
else
@tag_list = get_course_tag_list @course
#@tag_list = get_course_tag_list @course
end
respond_to do |format|
format.js

View File

@ -8,6 +8,7 @@ class ForumsController < ApplicationController
before_filter :authenticate_user_edit, :only => [:edit, :update]
before_filter :authenticate_user_destroy, :only => [:destroy]
before_filter :require_login, :only => [:new, :create,:destroy,:update,:edit]
before_filter :check_authentication
helper :sort
include SortHelper
@ -118,8 +119,10 @@ class ForumsController < ApplicationController
end
def index
order = ""
order = "sticky desc, created_at desc"
@order_str = ""
@user = User.current
=begin
if(params[:reorder_complex])
order = "replies_count #{params[:reorder_complex]}, #{Memo.table_name}.created_at #{params[:reorder_complex]}"
@order_str = "reorder_complex="+params[:reorder_complex]
@ -133,6 +136,7 @@ class ForumsController < ApplicationController
order = "#{Memo.table_name}.updated_at desc"
@order_str = "reorder_time=desc"
end
=end
@memo = Memo.new(:forum => @forum)
@memos = Memo.where("parent_id is null")
@topic_count = @memos.count
@ -143,14 +147,18 @@ class ForumsController < ApplicationController
reorder(order).
preload(:author, {:last_reply => :author}).
all
@forums = Forum.find_by_sql("SELECT *,topic_count + memo_count tm FROM `forums` order by tm desc;")
#@forums = Forum.find_by_sql("SELECT *,topic_count + memo_count tm FROM `forums` order by tm desc;")
@my_forums_count = Memo.where("author_id =? and parent_id is null", User.current.id).count
@my_memos_count = Memo.where("author_id =? and parent_id is not null", User.current.id).count
@errors = params[:errors]
memos_id = Memo.where("author_id =?", User.current.id).map(&:id)
@memos_praise_count = PraiseTread.where(:praise_tread_object_id => memos_id, :praise_tread_object_type => "Memo").count
respond_to do |format|
format.js
format.html {
render :layout => 'base_new_forum'
render :layout => 'base_edu'
}# show.html.erb
format.json { render json: @forum }
end
@ -180,13 +188,10 @@ class ForumsController < ApplicationController
end
@memo = Memo.new(:forum => @forum)
@topic_count = @forum.topics.count
@topic_pages = Paginator.new @topic_count, per_page_option, params['page']
@memos = @forum.topics.includes(:last_reply).
limit(@topic_pages.per_page).
offset(@topic_pages.offset).
reorder(order).
preload(:author, {:last_reply => :author}).
all
@limit = 20
@is_remote = true
@topic_pages = Paginator.new @topic_count, @limit, params['page'] || 1
@memos = paginateHelper @forum.topics.includes(:last_reply).reorder(order).preload(:author, {:last_reply => :author}), @limit
@my_topic_count = Memo.where("forum_id = #{@memo.forum_id} and parent_id is null").count
@my_replies_count = Memo.where("forum_id = #{@memo.forum_id} and parent_id is not null").count
@errors = params[:errors]

View File

@ -3,13 +3,77 @@ class GamesController < ApplicationController
layout "base_myshixun"
skip_before_filter :verify_authenticity_token, :only => [:file_update]
before_filter :find_myshixun, :only => [:index]
before_filter :find_game, :only => [:show, :game_build, :entry,:next_step, :outputs_show, :file_edit, :file_update, :game_status, :change_status]
before_filter :find_repository, :only => [:show, :entry, :file_edit, :file_update]
before_filter :find_game, :only => [:show, :game_build, :entry,:next_step, :prev_step,:outputs_show, :file_edit, :file_update, :get_waiting_time, :web_display,
:game_status, :change_status, :answer, :minus_score, :refresh_game_list, :reset_original_code, :reset_new_code, :evaluating_choice, :sync_codes]
before_filter :find_repository, :only => [:show, :entry, :file_edit, :file_update, :reset_original_code, :reset_new_code, :html_show]
before_filter :allowd_manager
before_filter :allowd_view, :only => [:show]
before_filter :find__shixun_language, :only => [:show, :entry]
include ApplicationHelper
require 'open3'
# 同步更新最新代码
# 同步完成后需要更新myshixun的commit_id为实训的commit最新值
# --------------------------
# 新思路有冲突则则重置没有冲突直接pull
# --------------------------
def sync_codes
g = Gitlab.client
myshixun_user_login = User.where(:id => @myshixun.user_id).first.try(:login)
myshixun_rep_identifier = Repository.where(:myshixun_id => @myshixun.id, :type => "Repository::Gitlab").first.try(:identifier)
gitlab_address = Redmine::Configuration['gitlab_address']
myshixun_domain = Redmine::Configuration['myshixun_domain']
gitlab_myshixun_url = git_myshixun_url(@myshixun, @myshixun.try(:user_id))
shixun = @myshixun.shixun
gitlab_shixun_url = git_shixun_url(shixun, (shixun.try(:fork_from).blank? ? "educoder" : "eduforge"))
if RUBY_PLATFORM =~ /w32/
path = "c:/test/"
else
path = "/home/pdl/myshixun_shell"
end
script = "cd #{path}
git clone #{gitlab_address.to_s+'/'+myshixun_user_login+'/'+ myshixun_rep_identifier}.git
cd #{myshixun_rep_identifier}/
git remote set-url origin https://#{shixun.fork_from.blank? ? "educoder" : "eduforge"}:xinhu1ji2qu3@#{myshixun_domain}/#{myshixun_user_login}/#{myshixun_rep_identifier}.git
git remote add remote_origin #{gitlab_shixun_url}
#git pull
git pull remote_origin master
if [ $? -eq 0 ];then
echo -e 'git pull succssed'
else
git reset --hard #{@myshixun.commit_id}
git pull remote_origin master
if [ $? -eq 0 ];then
echo -e 'git reset and pull succssed'
else
echo -e 'git reset and pull failed'
fi
fi
git push -f origin master
if [ $? -eq 0 ];then
echo -e 'git push succssed'
else
echo -e 'git push failed'
fi
cd ../
rm -rf #{myshixun_rep_identifier}/"
aFile =File.new(File.join("#{path}","#{@myshixun.identifier}.sh"), "w+")
if aFile
aFile.syswrite(script)
else
logger.error "Unable to open file!"
end
system("sh #{path}/#{@myshixun.identifier}.sh")
# stdin, stdout, stderr = Open3.popen3("sh #{path}/#{@myshixun.identifier}.sh")
shixun_new_commit = g.commits(@myshixun.shixun.try(:gpid)).first.try(:id)
@myshixun.update_column(:commit_id, shixun_new_commit)
sleep(2) # g
respond_to do |format|
format.js{ redirect_to myshixun_game_path( @game, :myshixun_id => @myshixun)}
end
# render :json => {:status => 200}
end
def index
@games = @myshixun.games.includes(:challenge)
@games_count = @games.count
@ -22,55 +86,117 @@ class GamesController < ApplicationController
# mushixun的版本库必须创建时就创建
# 首次进入版本库自动打开文件
# path"" && path: @game.path
# @praise 判断是否点赞
# @tread 判断是否踩
# git_repository_url @myshixun, "Myshixun"
# @st 0 实践任务 1 选择题任务
def show
# g = Gitlab.client
# g_name = g.project(@myshixun.gpid).try(:name)
# g_rep = @myshixun.repository
# g_identifier = g_rep.try(:identifier)
# if g_name.include?("-") || g_identifier.include?("-")
# g_user_id = @myshixun.owner.try(:gid)
# g_name = g_name.split("-")
# g_project_name = g_name[0]
# num = g_name[1]
# g_id = g.current_user_project(g_user_id, g_project_name).first.try(:id)
# sql = "update `repositories` set identifier='#{g_project_name}' where id=#{g_rep.id}"
# ActiveRecord::Base.connection.execute(sql)
# @myshixun.update_attribute(:gpid, g_id)
# end
# 展示全部实训
# git_myshixun_url_ip @myshixun, user_id
@is_subject = params[:is_subject]
if @game.status == 1
# 放置页面ajax数据还没获取就关闭
@game.update_attribute(:status, 0)
end
# logger.info("#################%%%%%%#{@game.outputs.first.out_put}")
# @games = @myshixun.games.includes(:challenge)
@game_challenge = @game.challenge
logger.info("test ................#{@game_challenge.id}")
game_path = (@game_challenge.path.blank? ? @path : @game_challenge.path.strip)
logger.info("test game_path ................#{game_path}")
@challenges = Challenge.where(:shixun_id => @myshixun.shixun_id)
@shixun = @myshixun.shixun
# 判断tpm是否修改了
@tpm_modified = tpm_is_modified(@myshixun, @shixun.try(:gpid))
# end
@praise_count = PraiseTread.where(:praise_tread_object_id => @game_challenge.id, :praise_tread_object_type => "Challenge").count
@tread_count = PraiseTread.where(:praise_tread_object_id => @game_challenge.id, :praise_tread_object_type => "ChallengeTread").count
# @games_count = @games.count
@st = @game_challenge.st
@had_done = @game.had_done
@praise = PraiseTread.where("praise_tread_object_id=? and praise_tread_object_type=? and user_id=?", @game_challenge.id, @game_challenge.class.to_s, User.current.id).first
@tread = PraiseTread.where("praise_tread_object_id=? and praise_tread_object_type=? and user_id=?", @game_challenge.id, "ChallengeTread", User.current.id).first
@rev = @rev.nil? ? "master" : @rev
@git_url = git_repository_url(@myshixun, "Myshixun")
@type = params[:type]
logger.info("##########************languae is #{@language}")
logger.info("out is666************#{@path} ")
challenge_path = @game_challenge.path
@discusses_count = @shixun.discusses.where(:parent_id => nil).count
# 用户选项
#@user_answer = @game.outputs.first.actual_output.split("") unless @st == 0 || @game.outputs.blank?
# 默认打开文件
if @path == "" && !game_path.nil? && !@repository.cat(game_path, @rev).blank? && @type != "root"
@path = game_path
@file_open = true
logger.info("666666666666************languae ")
logger.info("path is666************#{@path} ")
@content = @repository.cat(@path, @rev)
logger.info("666666666666************languae is #{@content}")
else
logger.info("77777************languae ")
logger.info("repository id is #{@repository.try(:id)}, repository's shixun_id =#{@repository.try(:myshixun_id)} shixun_id =#{@repository.try(:shixun_id)}, project_id => #{@repository.try(:project_id)}")
# 验证challenge文件名的合法性
if @path.blank? && !challenge_path.blank? && challenge_path.include?(".") && @type != "root"
@path = challenge_path.strip
file_content = @g.files(@myshixun.gpid, @path, @rev).content
if file_content.blank?
# gitlab缺陷forked完成短暂时间内取不了内容的所以做一个小轮询间隔0.1秒
# 超过2秒则失败需通过页面刷新
for i in 0..20 do
sleep(0.1)
file_content = @g.files(@myshixun.gpid, @path, @rev).content
unless file_content.blank?
logger.info("start: file_content is####{file_content.first(6)}")
break
end
end
end
@content = tran_base64_decode64(file_content)
end
if @content.nil?
@entries = @repository.entries(@path, @rev)
logger.info("7777************#{@entries} ")
end
logger.info("88888************#{@entries} ")
@latest_output = @game.latest_output.try(:out_put).to_s
outputs = @game.outputs
(@myshixun.games.count == @game_challenge.position && @game.status ==2) ? @had_done = 1 : @had_done = 0
if outputs.count == 0
@results = []
else
@results = outputs.map{|result| [result.code, result.id]}
# 页面前后端分离数据转换
test_sets = @game_challenge.test_sets
unless test_sets.blank?
@test_sets = test_set_static_data(test_sets)
end
logger.info("##################languae is #{@language}")
logger.info("##################latest_output is #{@latest_output}")
logger.info("##################had_done is #{@had_done}")
logger.info("##################status is #{@game.status}")
logger.info("##################result is #{@results}")
logger.info("#################################{@public_test_sets}")
@test_sets_count = test_sets.count
@test_sets_hidden_count = test_sets.blank? ? 0 :test_sets.select{|test_set| test_set.is_public == false}.count
@test_sets_public_count = @test_sets_count - @test_sets_hidden_count
had_test = Output.where(:game_id => @game.id, :query_index => (@game.query_index - 1))
@had_test_count = had_test.count
@had_passed_testsests_error_count = had_test.blank? ? 0 : had_test.select{|had_test| had_test.result == false}.count
@had_passed_testsests_error_count = @had_test_count - @had_passed_testsests_error_count
@had_passed_testsests_hidden_count = had_test.blank? ? 0 : had_test.select{|had_test| had_test.result == true && had_test.is_public == false}.count
@had_passed_testsests_public_count = had_test.blank? ? 0 : had_test.select{|had_test| had_test.result == true && had_test.is_public == true}.count
@final_score = ((@game.answer_open? || @shixun.status <= 1) ? 0 : @game.final_score.to_i)
@gold = @myshixun.shixun.status <= 1 ? 0 : (@game.answer_open? ? -@game_challenge.score.to_i : @game.final_score.to_i)
@had_done = @game.had_done
@language = @game_challenge.shixun.language
error_position = had_test.blank? ? nil : had_test.select{|had_test| had_test.result == false}.last
logger.info("latest output id is #{error_position.id unless error_position.blank?}")
@latest_output = error_position.try(:out_put).gsub(/\n/, '<br/>').gsub(/\t/, '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;').to_json unless error_position.try(:out_put).blank?
logger.info(@latest_output)
respond_to do |format|
format.html
format.js
end
rescue Exception => e
logger.error("game error##############{e.message}")
flash[:error] = e.message
end
# 代码预览
def entry
entry_and_raw(false)
@content = @repository.cat(@path, @rev)
# entry_and_raw(false)
file_content = @g.files(@myshixun.gpid, @path, @rev).content
@content =tran_base64_decode64(file_content)
# @content = @repository.cat(@path, @rev)
end
def file_edit
@ -83,13 +209,19 @@ class GamesController < ApplicationController
def file_update
@g = Gitlab.client
content = params[:content].strip
@g.edit_file(@myshixun.gpid, :content => params[:content], :file_path => @path, :branch_name => @rev, :commit_message => "shixun exec")
content = params[:content].try(:strip)
code_file = @g.edit_file(@myshixun.gpid, :content => params[:content], :file_path => @path, :branch_name => @rev, :commit_message => "shixun exec")
unless code_file.blank?
render :json => {:success => "success"}
end
=begin
respond_to do |format|
format.js{redirect_to entry_myshixun_game_path(@game, :myshixun_id => @myshixun, :path => @path)}
format.js
end
rescue Exception => e
puts e.message
=end
end
# json调用显示左边的隐藏具体详情@game 字段 msg
@ -101,57 +233,200 @@ class GamesController < ApplicationController
end
end
# 获取评测的等待的时间
# res['waitNum'] 评测等待人数
# res['waitingTime'] 评测等待时间
# res['onRun'] 0 表示在等待中 1 表示可执行
def get_waiting_time
shixun_tomcat = Redmine::Configuration['shixun_tomcat']
uri = "#{shixun_tomcat}/bridge/game/getWaitingTime"
params = {:tpiID => "#{@myshixun.id}"}
resubmit = @_params['resubmit']
res = uri_exec uri, params
if (res && res['code'] != 0)
@message = "实训云平台繁忙繁忙等级94"
raise("实训云平台繁忙繁忙等级94")
end
render :json => {:result => "success", :onRun => res['onRun'], :waitNum => res['waitNum'], :waitingTime => res['waitingTime'], :resubmit => resubmit }
#render :json => {:result => "success", :onRun => 0, :waitNum => 12, :waitingTime => 1234 }
rescue Exception => e
render :json => {:result => "failed"}
end
# status 0: 未提交测评或者提交测评失败后报错1中间状态还没返回值2返回值并成功
# resubmit 唯一随机码,为了区分每一次重新评测结果
CODES = %W(1 2 3 4 5 6 7 8 9 A B C D E F G H J K L N M O P Q R S T U V W X Y Z)
def game_build
game_challenge = @game.challenge
gitUrl = git_repository_url(@myshixun, "Myshixun")
gitUrl = Base64.encode64(gitUrl)
taskId = params[:id]
jobName = "myshixun_#{@myshixun.id}"
ActiveRecord::Base.transaction do
@game.update_attributes!(:status => 1)
testCode = {}
test_sets = game_challenge.test_sets
unless test_sets.blank?
test_sets.each_with_index do |test_set, index|
testCode.store("testCode_#{index}",test_set.try(:output))
shixun = @myshixun.shixun
gitUrl = git_myshixun_url_ip(@myshixun, @myshixun.try(:user_id))
gitUrl = Base64.urlsafe_encode64(gitUrl)
taskId = @game.id
code = CODES.sample(8).join
# status为2说明是重新评测
if @game.status == 2
resubmit = "#{code}_#{@myshixun.id}"
else
# 重新评测不影响已通关的实训状态
@game.update_attributes!(:status => 1) if resubmit.nil?
end
gameInfo = shixun.gameInfo
shixun_tomcat = Redmine::Configuration['shixun_tomcat']
step = game_challenge.try(:position)
# 注意:这个地方的参数写的时候不能换行
params = {:tpiID => "#{@myshixun.id}", :buildID => "#{taskId}", :instanceGitURL => "#{gitUrl}", :instanceChallenge => "#{step}", :resubmit => resubmit, :operationEnvironment => "#{shixun.try(:language)}"}
# uri = URI("#{shixun_tomcat}/bridge/game/gameEvaluate")
uri = "#{shixun_tomcat}/bridge/game/gameEvaluate"
res = uri_exec uri, params
logger.info("#####################buildJobForInstance result is #{res}")
logger.info("#####################buildJobForInstance params is #{params}")
if (res && res['code'] != 0)
@message = "实训云平台繁忙繁忙等级86"
raise("实训云平台繁忙繁忙等级86")
end
render :json => {:result => "success", :resubmit => resubmit}
rescue Exception => e
if resubmit.nil?
@game.update_attributes!(:status => 0)
end
logger.error("###################" + e.message)
#REDO Jenkins服务异常弹框抛出
render :json => {:result => "failed"}
end
# @myshixun -status 1:完成实训
# 全部通关奖励1000分
# retry_status 评测的唯一标识,重新评测对以前已产生的结果不造成影响
# params[:resubmit] 不为空表示已通过该关后重新评测, 重新评测必须是通过该关后才能执行
# @had_done 1 通关所有关
def game_status
game_challenge = @game.challenge
had_done = @game.had_done
resubmit_identifier = @game.resubmit_identifier
shixun = @myshixun.shixun
score = 0
tag_count = 0
logger.info("##### resubmit_identifier is #{resubmit_identifier}")
if params[:resubmit].blank? # 非重新评测
if had_done == 1 # 通过最后一关,即所有关卡
@myshixun.update_attribute(:status, 1)
end
# 通过当前一关
if @game.status == 2
@game.update_attribute(:end_time, Time.now)
game_passed_code(@game.id, game_challenge.try(:path), @myshixun.try(:gpid), 1)
if !@game.answer_open && shixun.status > 1
reward_grade(@game.user, @game.id, 'Game', game_challenge.score)
reward_experience(@game.user, @game.id, 'Game', game_challenge.score)
score = game_challenge.score
tag_count = game_challenge.challenge_tags.count
elsif shixun.status > 1 && @game.answer_open
score = -game_challenge.score.to_i
tag_count = 0
else
score = "+0"
tag_count = 0
end
end
testCode = testCode.to_json
jenkins_shixuns = Redmine::Configuration['jenkins_shixuns']
step = game_challenge.try(:position)
params = {:jobName => "#{jobName}", :taskId => "#{taskId}", :step => "#{step}", :gitUrl => "#{gitUrl}", :testCode => "#{testCode}"}
uri = URI("#{jenkins_shixuns}/jenkins-exec/api/buildJob")
res = uri_exec uri, params
if (res && res['code'] != 0)
raise("Build job failed")
game_status = @game.status
else # 重新评测
if params[:resubmit] == resubmit_identifier # 本次重新评测结果已经返回并存入数据库
game_status = (@game.retry_status == 2 ? 2 : 0) # retry_status 2成功 1 失败
if game_status == 2 && had_done == 1 # 重新评测如果评测成功
had_done =1
game_passed_code(@game.id, game_challenge.try(:path), @myshixun.try(:gpid), 1)
else
had_done = 0
end
else
# game_status 在前端有行为判断2表示通关0表示失败1表示评测中的中间状态
game_status = 1
had_done = 0
end
render :json => {data:"success"}
end
rescue
raise ActiveRecord::Rollback
redirect_to myshixun_game_path(@game, :myshixun_id => @myshixun)
test_sets = game_challenge.test_sets
unless test_sets.blank?
total_test_sets = test_set_static_data(test_sets)
end
logger.info("#################################{@public_test_sets}")
@test_sets_count = test_sets.count
@test_sets_hidden_count = test_sets.blank? ? 0 :test_sets.select{|test_set| test_set.is_public == false}.count
@test_sets_public_count = @test_sets_count - @test_sets_hidden_count
had_test = Output.where(:game_id => @game.id, :query_index => (@game.query_index - 1))
@had_test_count = had_test.count
@had_passed_testsests_error_count = had_test.blank? ? 0 : had_test.select{|had_test| had_test.result == false}.count
@had_passed_testsests_error_count = @had_test_count - @had_passed_testsests_error_count
@had_passed_testsests_hidden_count = had_test.blank? ? 0 : had_test.select{|had_test| had_test.result == true && had_test.is_public == false}.count
@had_passed_testsests_public_count = had_test.blank? ? 0 : had_test.select{|had_test| had_test.result == true && had_test.is_public == true}.count
@final_score = ((@game.answer_open? || shixun.status <= 1) ? 0 : @game.final_score.to_i)
@gold = @myshixun.shixun.status <= 1 ? 0 : (@game.answer_open? ? -game_challenge.score.to_i : @game.final_score.to_i)
error_position = had_test.blank? ? nil : had_test.select{|had_test| had_test.result == false}.last
@latest_output = error_position.try(:out_put).gsub(/\n/, '<br/>').gsub(/\t/, '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;') unless error_position.try(:out_put).blank?
logger.info("@compile_success###################{@compile_success}")
@language = game_challenge.shixun.language
render :json => {test_sets: total_test_sets,
test_sets_count: @test_sets_count,
test_sets_hidden_count: @test_sets_hidden_count,
test_sets_public_count: @test_sets_public_count,
had_test_count: @had_test_count,
had_passed_testsests_error_count: @had_passed_testsests_error_count,
had_passed_testsests_hidden_count: @had_passed_testsests_hidden_count,
had_passed_testsests_public_count: @had_passed_testsests_public_count,
final_score: @final_score,
gold: @gold,
latest_output: @latest_output,
status: game_status,
had_done: had_done,
language: @language,
score: score,
tag_count: tag_count,
position: game_challenge.position
}
end
def game_status
outputs = @game.outputs
game_challenge = @game.challenge
if outputs.count == 0
outputs = ""
else
outputs = outputs.map{|result| [result.code, result.id]}
# 选择题评测(选择题不需要重新评测)
# score 获得金币数 tag_count 技能数 right用户是否全对 answer_right全部选择题的正确性
def evaluating_choice
@game_challenge = @game.challenge
@challenges = Challenge.where(:shixun_id => @myshixun.shixun_id)
@shixun = @myshixun.shixun
score = 0
tag_count = 0
@right = true
answer_right = []
@game_challenge.challenge_chooses.each_with_index do |choose, index|
correct = (params[:answer][index] == choose.standard_answer) ? true : false
#choose.current_choose_outputs.delete if choose.current_choose_outputs.present?
#ChooseOutputs.create(:challenge_choose_id => choose.id, :user_id => User.current.id, :answer => params[:answer][index], :correct => correct)
Output.create(:game_id => @game.id, :test_set_position => choose.position, :actual_output => params[:answer][index], :result => correct, :query_index => @game.query_index)
if @shixun.status > 1 && !@game.answer_open
if correct
score += choose.score
tag_count += choose.challenge_tags.count
end
elsif @shixun.status > 1 && @game.answer_open
score -= choose.score
end
unless correct
@right = false
end
answer_right << correct
end
(@myshixun.games.count == game_challenge.position && @game.status ==2) ? had_done = 1 : had_done = 0
# 下一关自动开启
if had_done != 1 && @game.status == 2
@game.next_game.update_attribute(:status, 0)
@had_done = @game.had_done
if @right
@game.update_attributes(:status => 2, :end_time => Time.now)
reward_grade(@game.user, @game.id, 'Game', score)
reward_experience(@game.user, @game.id, 'Game', score)
@game.update_attribute(:final_score, score)
end
respond_to do |format|
format.js{redirect_to myshixun_game_path(@game, :myshixun_id => @myshixun, :choose => @right)}
end
latest_output = @game.latest_output.try(:out_put)
render :json => {status: @game.status, output: latest_output, results: outputs, had_done: had_done}
end
def change_status
@game.update_attribute(:status, 0)
outputs = @game.outputs
@ -163,18 +438,203 @@ class GamesController < ApplicationController
render :json => {status: @game.status, output: "服务器网络异常", results: outputs, had_done: 0}
end
# 获取等待的任务数
# 如果没有等待任务页面上将不显示
# msg -1 不存在等待的任务
# 如果该方法异常则直接返回0跳过等待
def waiting_info
begin
shixun_tomcat = Redmine::Configuration['shixun_tomcat']
params = {:buildID => "#{@game.id}"}
uri = URI("#{shixun_tomcat}/jenkins-exec/api/getWaitingTime")
res = uri_exec uri, params
if (res && res['code'] != 0)
raise("获取等待任务数异常")
end
task_count = res['msg'].to_i
task_count > 0 ? task_count : 0
render :json => {task_count: task_count}
rescue
render :json => {task_count: 0}
end
end
# 自动推送下一个任务
def next_step
render_403 if @game.status != 2
unless show_next_stage?(@game, @myshixun.shixun.try(:status))
render_403
end
next_game = @game.next_game
next_game.update_attribute(:status, 0) if next_game.status == 3
next_game.update_attributes(:status => 0, :open_time => Time.now) if next_game.status == 3
respond_to do |format|
format.js{ redirect_to myshixun_game_path(next_game, :myshixun_id => @myshixun)}
end
end
def prev_step
prev_game = @game.prev_game
respond_to do |format|
format.js{ redirect_to myshixun_game_path(prev_game, :myshixun_id => @myshixun)}
end
end
# 获取答案,第一次查看需扣掉该关卡的积分
# 如果已看过,下次可以免费查看
# viewed 1: 直接查看 2弹框提示将要扣除积分确定后显示内容 3弹框提示分数不够
def answer
challenge = @game.challenge
@challenge_score = challenge.score.to_i
@answer = ""
# 已经开启过
@score = User.current.grade.to_i - @challenge_score
if(params[:choose] == "true")
challenge.challenge_chooses.each_with_index do |choose, index|
@answer += ""+ ((index + 1).to_s) +"题:<br />"
@answer += (choose.answer.blank? ? choose.standard_answer : choose.answer)
@answer += "<br /><br /><br />"
end
else
@answer = challenge.answer
end
if challenge.shixun.status < 2 || @game.answer_open || (challenge.st != 0 && @game.status == 2)
@viewed = 1
else
if @score >= 0
@viewed = 2
else
@viewed = 3
end
end
respond_to do |format|
format.js
format.html
end
end
# web渲染
def web_display
path = @game.challenge.path.strip
port = (50000 + @game.myshixun_id).to_s
# 测试
#path = "src/step1/Helloworld.php"
#port = (50000+4116).to_s
@url = "http://106.75.96.108:" + port + '/' + path
respond_to do |format|
format.js{redirect_to myshixun_game_path(next_game, :myshixun_id => @myshixun.id)}
format.html{render :layout => false}
end
end
def minus_score
@game_challenge = @game.challenge
user = User.current
challenge_score = @game_challenge.score.to_i
reward_grade(user, @game.id, 'Answer', -challenge_score)
@answer = ""
if @game.challenge.st == 0
@answer = @game_challenge.answer
else
@game_challenge.challenge_chooses.each_with_index do |choose, index|
@answer += ""+ ((index + 1).to_s) +"题:<br />"
@answer += (choose.answer.blank? ? choose.standard_answer : choose.answer)
@answer += "<br /><br /><br />"
end
end
@game.update_column(:answer_open, true)
end
def refresh_game_list
myshixun_id = params[:myshixun_id]
@myshixun = Myshixun.find_by_identifier(myshixun_id)
@challenges = Challenge.where(:shixun_id => @myshixun.shixun_id)
respond_to do |format|
format.js
end
end
def reset_original_code
begin
@shixun = @myshixun.shixun
@g = Gitlab.client
game_code = GameCode.where(:game_id => @game.id).first
content = game_code.try(:original_code)
if content.nil?
raise("初始代码为空,代码重置失败")
end
@path = params[:path]
@rev = @rev.nil? ? "master" : @rev
message = "file reset"
update_gitlab_file(content, @path, @rev, message)
file_content = @g.files(@myshixun.gpid, @path, @rev).content
@content = tran_base64_decode64(file_content)
if @content.nil?
raise("初始代码为空,代码重置失败")
# @entries = @repository.entries(@path, @rev)
end
respond_to do |format|
format.js
end
rescue Exception => e
@error_messages = e.message
end
end
def reset_new_code
begin
@shixun = @myshixun.shixun
@g = Gitlab.client
game_code = GameCode.where(:game_id => @game.id).first
content = game_code.try(:new_code)
if content.nil?
raise("示例代码为空,代码重置失败")
end
@path = params[:path]
@rev = @rev.nil? ? "master" : @rev
message = "file reset"
update_gitlab_file(content, @path, @rev, message)
file_content = @g.files(@myshixun.gpid, @path, @rev).content
@content = tran_base64_decode64(file_content)
if @content.nil?
raise("示例代码为空,代码重置失败")
# @entries = @repository.entries(@path, @rev)
end
respond_to do |format|
format.js
end
rescue Exception => e
@error_messages = e.message
end
end
private
def update_gitlab_file content, path, rev, message
code_file = @g.edit_file(@myshixun.gpid, :content => content, :file_path => path, :branch_name => rev, :commit_message => "#{message}")
if code_file.nil?
raise("网络异常,文件更新失败")
end
end
def test_set_static_data test_sets
test_result = []
unless test_sets.blank?
test_sets.each do |test_set|
output = Output.where(:game_id => @game.id, :test_set_position => test_set.position).first
actual_output = output.try(:actual_output)
result = output.try(:result)
compile_success = (actual_output.blank? || !actual_output.downcase.match(/error/).blank?) ? 0 : 1
public_result = {:is_public => (test_set.is_public ? 1 : 0), :result => result, :input => test_set.input,
:actual_output => actual_output, :output => test_set.output, :compile_success => compile_success}
logger.info("1111#################################{public_result.to_json}")
test_result << public_result.to_json
end
end
test_result = test_result.blank? ? test_result : test_result.join(",")
logger.info("222#################################{test_result}")
return test_result
end
def entry_and_raw(is_raw)
@entry = @repository.entry(@path, @rev)
(show_error_not_found; return) unless @entry
@ -230,7 +690,10 @@ class GamesController < ApplicationController
# 判断成员是否允许查看
def allowd_view
render_403 if @game.status == 3
if @myshixun.shixun.try(:status) == 2 && @game.status == 3 && User.current.id != @myshixun.shixun.try(:user_id)
render_403
end
# render_403 if (@game.status == 3 && User.current.id != @myshixun.shixun.try(:user_id))
end
def find__shixun_language
@ -241,13 +704,22 @@ class GamesController < ApplicationController
# Find myshixun of id params[:id]
def find_myshixun
myshixun_id = params[:myshixun_id] || (params[:game] && params[:game][:myshixun_id])
@myshixun = Myshixun.find(myshixun_id)
@myshixun = Myshixun.find_by_identifier(myshixun_id)
if @myshixun.nil?
render_404
return
end
rescue ActiveRecord::RecordNotFound
render_404
end
def find_game
@game = Game.find(params[:id])
# myshixun_id = params[:myshixun_id]
@game = Game.find_by_identifier(params[:id])
if @game.nil?
render_404
return
end
@myshixun = @game.myshixun
rescue ActiveRecord::RecordNotFound
render_404

View File

@ -0,0 +1,254 @@
class HomeworkBankController < ApplicationController
before_filter :require_login, :only => [:index, :show, :new, :create, :edit, :update, :destroy, :destroy_all, :choose_user_course, :send_h_bank_to_course]
before_filter :find_homework_bank, :only => [:show, :edit, :update, :destroy, :set_public]
def index
@order,@b_sort = params[:order] || "updated_at",params[:sort] || "desc"
@user = User.current
@r_sort = @b_sort == "desc" ? "asc" : "desc"
@search = params[:search]
if(params[:type].blank? || params[:type] == "1") #我的题库
@homeworks = @user.homework_banks.where("homework_type in (1, 4) and name like ?", "%#{@search}%")
elsif params[:type] == "2" #公共题库
@homeworks = HomeworkBank.where(:is_public => true).where("homework_type in (1, 4) and name like ?", "%#{@search}%")
end
if params[:property]
@property = params[:property].to_i
@homeworks = @homeworks.where(:homework_type => params[:property].to_i)
end
@homeworks = @homeworks.reorder("#{@order} #{@b_sort}")
@type = params[:type] ? params[:type] : '1'
@limit = 15
@is_remote = true
@hw_count = @homeworks.count
@hw_pages = Paginator.new @hw_count, @limit, params['page'] || 1
@offset ||= @hw_pages.offset
@homeworks = paginateHelper @homeworks,15
respond_to do |format|
format.js
format.html {render :layout => 'base_edu'}
end
end
def show
@is_admin = User.current == @homework.user || User.current.admin?
respond_to do |format|
format.html {render :layout => 'base_edu'}
end
end
def new
@homework_type = params[:homework_type].to_i
@homework = HomeworkBank.new
respond_to do |format|
format.html{render :layout => 'base_edu'}
end
end
# 新建实训作业
def shixuns
search = params[:search]
@homework = HomeworkBank.new
@shixuns = Shixun.where(:status => 2).where("name like ?", "%#{search}%")
@shixuns_count = @shixuns.count
@limit = 10
@is_remote = true
@shixun_pages = Paginator.new @shixuns_count, @limit, params['page'] || 1
@offset ||= @shixun_pages.offset
@shixuns = paginateHelper @shixuns, @limit
respond_to do |format|
format.js
end
end
def create
if params[:homework_bank] || params[:shixun_homework]
homework = HomeworkBank.new
if params[:shixun_homework]
shixun = Shixun.find(params[:shixun_homework])
homework.name = shixun.name
homework.description = shixun.description
else
homework.name = params[:homework_bank][:name]
homework.description = params[:homework_bank][:description]
homework.reference_answer = params[:homework_bank][:reference_answer]
homework.save_attachments(params[:attachments])
render_attachment_warning_if_needed(homework)
end
homework.is_public = 0
homework.quotes = 0
homework.homework_type = params[:shixun_homework] ? 4 : (params[:homework_type].to_i || 1)
homework.user_id = User.current.id
unless params[:course_list].blank?
if CourseList.where(:name => params[:course_list].strip).count > 0
homework.course_list_id = CourseList.where(:name => params[:course_list].strip).first.id
else
course_list = CourseList.create(:name => params[:course_list].strip, :user_id => User.current.id, :is_admin => 0)
homework.course_list_id = course_list.id
end
end
#homework.syllabus_id = params[:syllabus_id] if params[:syllabus_id] && params[:syllabus_id] != '0'
#编程作业相关属性
if homework.homework_type == 2
homework.language = params[:language_type].to_i
sample_inputs = params[:sample][:input]
if Array === sample_inputs
sample_inputs.each_with_index do |val, i|
homework.homework_bank_samples << HomeworkBankSample.new(
input: val,
output: params[:sample][:output][i]
)
end
end
inputs = params[:program][:input]
if Array === inputs
inputs.each_with_index do |val, i|
homework.homework_bank_tests << HomeworkBankTest.new(
input: val,
output: params[:program][:output][i]
)
end
end
end
#分组作业
if homework.homework_type == 3
homework.min_num = params[:min_num].to_i
homework.max_num = params[:max_num].to_i
end
if homework.save
if homework.homework_type == 4
HomeworkBankShixun.create(:homework_bank_id => homework.id, :shixun_id => shixun.id)
end
redirect_to homework_bank_path(homework)
end
end
end
def edit
@homework_type = @homework.homework_type
respond_to do |format|
format.html{render :layout => 'base_edu'}
end
end
def update
if params[:homework_bank]
@homework.name = params[:homework_bank][:name]
@homework.description = params[:homework_bank][:description]
@homework.reference_answer = params[:homework_bank][:reference_answer]
if params[:course_list].blank?
@homework.course_list_id = nil
else
if CourseList.where(:name => params[:course_list].strip).count > 0
@homework.course_list_id = CourseList.where(:name => params[:course_list].strip).first.id
else
course_list = CourseList.create(:name => params[:course_list].strip, :user_id => User.current.id, :is_admin => 0)
@homework.course_list_id = course_list.id
end
end
#@homework.syllabus_id = params[:syllabus_id] ? (params[:syllabus_id] == '0' ? nil : params[:syllabus_id].to_i) : nil
@homework.save_attachments(params[:attachments])
render_attachment_warning_if_needed(@homework)
#编程作业相关属性
if @homework.homework_type == 2
@homework.language = params[:language_type].to_i if params[:language_type]
@homework.homework_bank_samples.delete_all if params[:sample]
sample_inputs = params[:sample][:input] if params[:sample]
if Array === sample_inputs
sample_inputs.each_with_index do |val, i|
@homework.homework_bank_samples << HomeworkBankSample.new(
input: val,
output: params[:sample][:output][i]
)
end
end
@homework.homework_bank_tests.delete_all if params[:program]
inputs = params[:program][:input] if params[:program]
if Array === inputs
inputs.each_with_index do |val, i|
@homework.homework_bank_tests << HomeworkBankTest.new(
input: val,
output: params[:program][:output][i]
)
end
end
end
#分组作业
if @homework.homework_type == 3
@homework.min_num = params[:min_num].to_i if params[:min_num]
@homework.max_num = params[:max_num].to_i if params[:max_num]
end
if @homework.save
redirect_to homework_bank_path(@homework)
end
end
end
def destroy
@homework.homework_commons.update_all(:homework_bank_id => nil)
@homework.destroy
redirect_to homework_bank_index_path()
end
def destroy_all
if params[:check_homework_bank] && !params[:check_homework_bank].blank?
params[:check_homework_bank].each do |hb_id|
homework = HomeworkBank.find hb_id
if homework && homework.user == User.current
HomeworkCommon.where(:homework_bank_id => homework.id).update_all(:homework_bank_id => nil)
homework.destroy
end
end
end
redirect_to homework_bank_index_path
end
def choose_user_course
if !params[:search].nil?
search = "%#{params[:search].to_s.strip.downcase}%"
@courses = User.current.courses.where("is_delete = 0 and is_end = 0 and (#{Course.table_name}.id = #{params[:search].to_i } or #{Course.table_name}.name like :p)",:p=>search).select{ |course| User.current.has_teacher_role(course)}
else
@courses = User.current.courses.where("is_delete = 0 and is_end = 0").select{ |course| User.current.has_teacher_role(course)}
end
@homework_ids = params[:check_homework_bank] if params[:check_homework_bank]
@search = params[:search]
respond_to do |format|
format.js
end
end
def send_h_bank_to_course
course = Course.find params[:course_id]
if course
params[:homework_id].each do |homework_id|
homework = HomeworkBank.find homework_id
quote_homework_bank homework, course
end
end
end
def set_public
@homework.update_attributes(:is_public => true)
respond_to do |format|
format.html{ redirect_to homework_bank_path(@homework) }
format.js
end
end
private
def find_homework_bank
@homework = HomeworkBank.find params[:id]
rescue ActiveRecord::RecordNotFound
render_404
end
end

View File

@ -5,37 +5,54 @@ class HomeworkCommonController < ApplicationController
layout "base_courses"
include StudentWorkHelper
include ApplicationHelper
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,:alert_open_student_works,:open_student_works,
:set_score_open,:alert_score_open_modal,:add_to_homework_bank,:publish_homework]
:set_score_open,:alert_score_open_modal,:add_to_homework_bank,:publish_homework,:setting,:set_public,:homework_setting,:update_explanation]
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,:alert_open_student_works,
:open_student_works,:add_to_homework_bank,:publish_homework]
before_filter :member_of_course, :only => [:index]
:open_student_works,:add_to_homework_bank,:publish_homework,:update_explanation]
before_filter :member_of_course, :only => [:index,:setting]
def index
#unless params[:page]
# update_homework_time(@course.homework_commons)
#end
search = "%#{params[:search].to_s.strip.downcase}%"
@new_homework = HomeworkCommon.new
@new_homework.homework_detail_manual = HomeworkDetailManual.new
@new_homework.course = @course
@search = "#{params[:search].to_s.strip.downcase}" if params[:search]
@order = params[:order]
@page = params[:page] ? params[:page].to_i + 1 : 0
@homework_type = params[:homework_type].to_i
@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)
@homework_commons = @course.homework_commons.where("name like '%#{search}%'").order("created_at desc")
if @search
@homework_commons = @course.homework_commons.where(:homework_type => @homework_type).where("name like '%#{@search}%'")
else
#@homeworks = @course.homework_commons.where("publish_time <= '#{Date.today}'").order("created_at desc").limit(10).offset(@page * 10)
@homework_commons = @course.homework_commons.where("name like '%#{search}%' and publish_time <= '#{Time.now}'").order("created_at desc")
@homework_commons = @course.homework_commons.where(:homework_type => @homework_type)
end
if @order.blank?
if @is_teacher
@homework_commons = @homework_commons.order("publish_time desc")
else
@homework_commons = @homework_commons.where("publish_time <= '#{Time.now}'").order("publish_time desc")
end
else
case @order
when '1'
@homework_commons = @homework_commons.includes(:homework_detail_manual).where("homework_detail_manuals.comment_status = #{@order} and end_time > '#{Time.now}'").order("homework_commons.publish_time desc")
when '3'
@homework_commons = @homework_commons.includes(:homework_detail_manual).where("homework_detail_manuals.comment_status = #{@order} and homework_detail_manuals.evaluation_end > '#{Time.now}'").order("homework_commons.publish_time desc")
when '4'
@homework_commons = @homework_commons.includes(:homework_detail_manual).where("(homework_detail_manuals.comment_status = #{@order} and homework_detail_manuals.appeal_time > '#{Time.now}')").order("homework_commons.publish_time desc")
when '5'
@homework_commons = @homework_commons.includes(:homework_detail_manual).where("(homework_detail_manuals.comment_status = #{@order} and archive_time > '#{Time.now}')").order("homework_commons.publish_time desc")
else
@homework_commons = @homework_commons.includes(:homework_detail_manual).where("homework_detail_manuals.comment_status = #{@order}").order("homework_commons.publish_time desc")
end
end
#update_homework_time @homework_commons
@is_student = User.current.logged? && (User.current.admin? || (User.current.member_of_course?(@course) && !@is_teacher))
@is_new = params[:is_new]
@homeworks = paginateHelper @homework_commons,10
@homeworks = paginateHelper @homework_commons,15
#设置at已读
ids = @homeworks.inject([]) do |ids, homework|
jids = homework.journals_for_messages.map(&:id)
@ -58,33 +75,294 @@ class HomeworkCommonController < ApplicationController
#新建作业,在个人作业列表创建作业
def new
render_404
@homework_type = params[:homework_type].to_i
@homework = HomeworkCommon.new
@ref_answer = HomeworkReferenceAnswer.new
respond_to do |format|
format.html{render :layout => 'base_edu'}
end
end
# 新建实训作业
def shixuns
search = params[:search]
@course = Course.find(params[:course])
@homework = HomeworkCommon.new
@shixuns = Shixun.where(:status => 2).where("name like ?", "%#{search}%")
@shixuns_count = @shixuns.count
@limit = 8
@is_remote = true
@shixun_pages = Paginator.new @shixuns_count, @limit, params['page'] || 1
@offset ||= @shixun_pages.offset
@shixuns = paginateHelper @shixuns, @limit
respond_to do |format|
format.js
end
end
#新建作业,在个人作业列表创建作业
def create
redirect_to user_homeworks_user_path(User.current.id)
if params[:homework_common] || params[:shixun_homework]
homework = HomeworkCommon.new
if params[:shixun_homework]
shixun = Shixun.find(params[:shixun_homework])
homework.name = shixun.name
homework.description = shixun.description
else
homework.name = params[:homework_common][:name]
homework.description = params[:homework_common][:description]
homework.reference_answer = params[:homework_common][:reference_answer]
homework.save_attachments(params[:attachments])
render_attachment_warning_if_needed(homework)
end
homework.anonymous_comment = 1
homework.homework_type = params[:shixun_homework] ? 4 : (params[:homework_type].to_i || 1)
homework.late_penalty = 0
homework.teacher_priority = 1
homework.user_id = User.current.id
homework.course_id = params[:course]
homework_detail_manual = HomeworkDetailManual.new
homework_detail_manual.te_proportion = 1.0
homework_detail_manual.ta_proportion = 0
homework_detail_manual.comment_status = 0
homework_detail_manual.evaluation_num = 0
homework_detail_manual.absence_penalty = 0
homework.homework_detail_manual = homework_detail_manual
#编程作业相关属性
if homework.homework_type == 2
homework_detail_programing = HomeworkDetailPrograming.new
homework.homework_detail_programing = homework_detail_programing
homework_detail_programing.ta_proportion = 0
homework_detail_programing.language = params[:language_type].to_i
sample_inputs = params[:sample][:input]
if Array === sample_inputs
sample_inputs.each_with_index do |val, i|
homework.homework_samples << HomeworkSample.new(
input: val,
output: params[:sample][:output][i]
)
end
end
inputs = params[:program][:input]
if Array === inputs
inputs.each_with_index do |val, i|
homework.homework_tests << HomeworkTest.new(
input: val,
output: params[:program][:output][i]
)
end
end
end
#分组作业
if homework.homework_type == 3
homework_detail_group = HomeworkDetailGroup.new
homework.homework_detail_group = homework_detail_group
homework_detail_group.min_num = params[:min_num].to_i
homework_detail_group.max_num = params[:max_num].to_i
homework_detail_group.base_on_project = 0
end
if homework.save
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.homework_type != 4 && homework_detail_manual.comment_status == 1
create_works_list homework
elsif homework.homework_type == 4
HomeworkCommonsShixuns.create(:homework_common_id => homework.id, :shixun_id => shixun.id)
end
if params[:quotes] && !params[:quotes].blank?
quotes_homework = HomeworkBank.find params[:quotes].to_i
quotes_homework.update_column(:quotes, quotes_homework.quotes+1)
homework.update_attributes(:homework_bank_id => quotes_homework.id)
end
# if params[:add_to_bank]
# homework_bank = add_to_homework_bank_f homework
# homework_bank.save
# homework.update_attributes(:homework_bank_id => homework_bank.id)
# end
redirect_to student_work_index_path(:homework => homework.id, :is_new => 1, :tab => 4)
end
end
end
def setting
@is_new = params[:is_new].to_i if params[:is_new]
@is_empty = @homework.publish_time.nil?
@is_teacher = User.current.logged? && (User.current.admin? || User.current.allowed_to?(:as_teacher,@course))
respond_to do |format|
format.html{render :layout => 'base_edu'}
end
end
def homework_setting
@homework.publish_time = params[:homework_publish_time] if params[:homework_publish_time]
@homework.end_time = params[:homework_end_time] if params[:homework_end_time]
@homework.archive_time = params[:homework_archive_time] if params[:homework_archive_time]
if @homework.archive_time < Time.now && @homework_detail_manual.comment_status < 6
@homework_detail_manual.comment_status = 6
elsif @homework.archive_time > Time.now && @homework_detail_manual.comment_status == 6
@homework_detail_manual.comment_status = 5
end
if params[:homework_allow_late] == '1'
@homework.allow_late = true
@homework.late_penalty = params[:homework_late_penalty].to_i
else
@homework.allow_late = false
@homework.late_penalty = 0
end
anonymous_comment = @homework.anonymous_comment
absence_penalty = @homework_detail_manual.absence_penalty
appeal_penalty = @homework_detail_manual.appeal_penalty
if @homework_detail_manual.comment_status < 3
if params[:homework_anonymous_comment]
@homework.anonymous_comment = 0
@homework_detail_manual.evaluation_start = params[:homework_evaluation_start] if params[:homework_evaluation_start]
@homework_detail_manual.evaluation_end = params[:homework_evaluation_end] if params[:homework_evaluation_end]
@homework_detail_manual.evaluation_num = params[:homework_evaluation_num] if params[:homework_evaluation_num]
@homework_detail_manual.absence_penalty = params[:homework_absence_penalty] if params[:homework_absence_penalty]
else
@homework.anonymous_comment = 1
@homework_detail_manual.evaluation_start = nil
@homework_detail_manual.evaluation_end = nil
@homework_detail_manual.evaluation_num = 0
@homework_detail_manual.absence_penalty = 0
end
else
@homework_detail_manual.evaluation_end = params[:homework_evaluation_end] if params[:homework_evaluation_end]
@homework_detail_manual.evaluation_num = params[:homework_evaluation_num] if params[:homework_evaluation_num]
@homework_detail_manual.absence_penalty = params[:homework_absence_penalty] if params[:homework_absence_penalty]
end
if anonymous_comment != @homework.anonymous_comment
@homework_detail_manual.te_proportion = 1
@homework_detail_manual.ta_proportion = 0
@homework_detail_programing.ta_proportion = 0 if @homework_detail_programing
end
if @homework_detail_manual.comment_status < 4
if @homework.anonymous_comment == 0 && params[:homework_anonymous_appeal]
@homework.anonymous_appeal = 1
@homework_detail_manual.appeal_time = params[:homework_appeal_time] if params[:homework_appeal_time]
@homework_detail_manual.appeal_penalty = params[:homework_appeal_penalty] if params[:homework_appeal_penalty]
else
@homework.anonymous_appeal = 0
@homework_detail_manual.appeal_time = nil
@homework_detail_manual.appeal_penalty = 0
end
else
@homework_detail_manual.appeal_time = params[:homework_appeal_time] if params[:homework_appeal_time]
@homework_detail_manual.appeal_penalty = params[:homework_appeal_penalty] if params[:homework_appeal_penalty]
end
if absence_penalty != @homework_detail_manual.absence_penalty && @homework_detail_manual.comment_status >= 4
all_dis_eva = StudentWorksEvaluationDistribution.where(:student_work_id => @homework.student_works.map(&:id))
has_sw_count = all_dis_eva.select("distinct user_id").count
anon_count = all_dis_eva.count / has_sw_count
@homework.student_works.where("work_status != 0").each do |student_work|
absence_penalty_count = student_work.user.student_works_evaluation_distributions.where(:student_work_id => @homework.student_works.map(&:id)).count - student_work.user.student_works_scores.where(:student_work_id => @homework.student_works.map(&:id), :reviewer_role => 3).count
student_work.absence_penalty = absence_penalty_count > 0 ? absence_penalty_count * @homework_detail_manual.absence_penalty : 0
student_work.save
end
end
if appeal_penalty != @homework_detail_manual.appeal_penalty && @homework_detail_manual.comment_status >= 4
@homework.student_works.each do |student_work|
appeal_penalty_count = student_work.user.student_works_scores.where(:student_work_id => @homework.student_works.map(&:id), :appeal_status => 3).count
student_work.appeal_penalty = appeal_penalty_count > 0 ? appeal_penalty_count * @homework_detail_manual.absence_penalty : 0
student_work.save
end
end
if params[:homework_ta_mode] && @homework_detail_manual.ta_mode.to_i != params[:homework_ta_mode].to_i
@homework_detail_manual.ta_mode = params[:ta_mode].to_i
@homework_detail_manual.save
if @homework_detail_manual.ta_mode == 1
@homework.student_works.where("work_status != 0").each do |student_work|
ts_score = StudentWorksScore.find_by_sql("SELECT AVG(score) AS score FROM (SELECT * FROM (SELECT * FROM student_works_scores WHERE student_work_id = #{student_work.id} AND reviewer_role = 2 AND score IS NOT NULL ORDER BY created_at DESC) AS t GROUP BY user_id) AS a")
student_work.teaching_asistant_score = ts_score.first.score.nil? ? nil : ts_score.first.score.try(:round, 2).to_f
student_work.save
end
else
@homework.student_works.where("work_status != 0").each do |student_work|
ts_score = StudentWorksScore.where("student_work_id = #{student_work.id} AND reviewer_role = 2 AND score IS NOT NULL").order("created_at DESC")
student_work.teaching_asistant_score = ts_score.first.nil? ? nil : ts_score.first.score
student_work.save
end
end
end
if params[:homework_final_mode] && params[:homework_final_mode].to_i != @homework_detail_manual.final_mode
@homework_detail_manual.final_mode = params[:homework_final_mode].to_i
if params[:homework_final_mode].to_i == 0
@homework_detail_manual.te_proportion = params[:te_proportion]
@homework_detail_manual.ta_proportion = params[:ta_proportion]
@homework_detail_programing.ta_proportion = params[:sy_proportion] if @homework_detail_programing
@homework_detail_programing.save if @homework_detail_programing
end
@homework_detail_manual.save if @homework_detail_manual
@homework.save
@homework = HomeworkCommon.find @homework.id
@homework.student_works.each do |student_work|
set_final_score @homework,student_work
student_work.save
end
elsif params[:homework_final_mode] && @homework_detail_manual.final_mode == 0
if (params[:te_proportion] && params[:te_proportion].to_s != @homework_detail_manual.te_proportion.to_s) || (params[:ta_proportion] && params[:ta_proportion].to_s != @homework_detail_manual.ta_proportion.to_s) || (@homework_detail_programing && @homework_detail_programing.ta_proportion.to_s != params[:sy_proportion].to_s)
@homework_detail_manual.te_proportion = params[:te_proportion]
@homework_detail_manual.ta_proportion = params[:ta_proportion]
@homework_detail_programing.ta_proportion = params[:sy_proportion] if @homework_detail_programing
@homework_detail_manual.save if @homework_detail_manual
@homework_detail_programing.save if @homework_detail_programing
@homework.save
@homework = HomeworkCommon.find @homework.id
@homework.student_works.each do |student_work|
set_final_score @homework,student_work
student_work.save
end
end
end
if @homework.homework_type == 4
if @homework_detail_manual.answer_open_evaluation != params[:answer_open_evaluation].to_i
@homework_detail_manual.answer_open_evaluation = params[:answer_open_evaluation].to_i
if @homework.end_time < Time.now
@homework.student_works.each do |student_work|
set_shixun_final_score @homework, student_work, @homework_detail_manual.answer_open_evaluation
end
end
end
@homework.score_open = params[:homework_score_open] ? 1 : 0
else
@homework.work_public = params[:homework_work_public] ? 1 : 0
@homework.score_open = params[:homework_score_open] ? 1 : 0
@homework.answer_public = params[:homework_answer_public] ? 1 : 0
end
@homework.save
@homework_detail_manual.save
redirect_to student_work_index_path(:homework => @homework.id)
end
def edit
@user = User.current
@hw_status = params[:hw_status].to_i
@is_manage = params[:is_manage]
if @hw_status != 1
@left_nav_type = 3
respond_to do |format|
format.html{render :layout => 'base_courses'}
end
else
respond_to do |format|
format.html{render :layout => 'base_course_community'}
end
@homework_type = @homework.homework_type
respond_to do |format|
format.html{render :layout => 'base_edu'}
end
end
def update
if params[:homework_common]
is_update = @homework.name != params[:homework_common][:name] || @homework.description != params[:homework_common][:description] || params[:homework_type].to_i != @homework.homework_type
is_update = @homework.name != params[:homework_common][:name] || @homework.description != params[:homework_common][:description] || @homework.reference_answer != params[:homework_common][:reference_answer]
if params[:homework_type].to_i == 2
is_update = is_update || params[:language_type] != @homework.homework_detail_programing.language
if !is_update && params[:sample] && params[:program]
@ -98,92 +376,8 @@ class HomeworkCommonController < ApplicationController
@homework.name = params[:homework_common][:name]
@homework.description = params[:homework_common][:description]
homework_detail_manual = @homework.homework_detail_manual || HomeworkDetailManual.new
if params[:homework_common][:end_time] != ""
if params[:homework_common][:publish_time] == ""
@homework.publish_time = Time.now
else
@homework.publish_time = params[:homework_common][:publish_time]
end
param_end_time = Time.parse(params[:homework_common][:end_time]).to_s
homework_end_time = @homework.end_time ? @homework.end_time.to_s : ''
if homework_end_time != param_end_time
if homework_end_time > param_end_time
@homework.student_works.where("work_status = 1").each do |st|
if param_end_time < st.commit_time
st.late_penalty = @homework.late_penalty
st.work_status = 2
st.save
#更新CourseHomeworkStatistics中学生的迟交作品数
course_statistics = CourseHomeworkStatistics.find_by_course_id_and_user_id(@homework.course_id, st.user_id)
course_statistics.update_attribute('late_commit_work_num', course_statistics.late_commit_work_num + 1) if course_statistics
end
end
else
@homework.student_works.where("work_status = 2").each do |st|
if param_end_time >= Time.parse(st.commit_time.to_s).strftime("%Y-%m-%d")
st.late_penalty = 0
st.work_status = 1
st.save
#更新CourseHomeworkStatistics中学生的迟交作品数
course_statistics = CourseHomeworkStatistics.find_by_course_id_and_user_id(@homework.course_id, st.user_id)
course_statistics.update_attribute('late_commit_work_num', (course_statistics.late_commit_work_num - 1) < 0 ? 0 : (course_statistics.late_commit_work_num - 1)) if course_statistics
end
end
end
end
@homework.end_time = params[:homework_common][:end_time] || Time.now
status = false
if @homework.publish_time > Time.now && homework_detail_manual.comment_status == 1
homework_detail_manual.comment_status = 0
@homework.student_works.destroy_all
#更新CourseHomeworkStatistics中每个学生的未交作品数
@homework.course.student.each do |student|
course_statistics = CourseHomeworkStatistics.find_by_course_id_and_user_id(@homework.course_id, student.student_id)
course_statistics.update_attribute('un_commit_work_num', (course_statistics.un_commit_work_num - 1) < 0 ? 0 : (course_statistics.un_commit_work_num - 1)) if course_statistics
end
elsif @homework.publish_time <= Time.now && homework_detail_manual.comment_status == 0
homework_detail_manual.comment_status = 1
create_works_list @homework if params[:homework_type].to_i != 3
status = true
#更新CourseHomeworkStatistics中每个学生的未交作品数
@homework.course.student.each do |student|
course_statistics = CourseHomeworkStatistics.find_by_course_id_and_user_id(@homework.course_id, student.student_id)
course_statistics.update_attribute('un_commit_work_num', course_statistics.un_commit_work_num + 1) if course_statistics
end
end
eval_start = homework_detail_manual.evaluation_start
if eval_start.nil? || (Time.parse(eval_start.to_s) <= @homework.end_time && homework_detail_manual.comment_status <= 1)
homework_detail_manual.evaluation_start = (@homework.end_time + 7*24*60*60).strftime("%Y-%m-%d")
homework_detail_manual.evaluation_end = homework_detail_manual.evaluation_start + 7
end
end
if params[:homework_type] && params[:homework_type].to_i != @homework.homework_type
if @homework.homework_type == 2
@homework.homework_detail_programing.destroy if @homework.homework_detail_programing
@homework.homework_tests.destroy_all
elsif @homework.homework_type == 3
@homework.homework_detail_group.destroy if @homework.homework_detail_group
create_works_list @homework if homework_detail_manual.comment_status > 0 && @homework.student_works.empty?
end
if params[:homework_type].to_i == 3
@homework.student_works.destroy_all
end
@homework.homework_type = params[:homework_type].to_i
end
anonymous = params[:homework_common][:anonymous_comment] ? params[:homework_common][:anonymous_comment].to_i : 1
if anonymous != @homework.anonymous_comment
if anonymous == 1
homework_detail_manual.ta_proportion = @homework.homework_type == 2 ? 0.4 : 1.0
else
homework_detail_manual.ta_proportion = @homework.homework_type == 2 ? 0.3 : 0.6
end
end
@homework.save_attachments(params[:attachments])
@homework.reference_answer = params[:homework_common][:reference_answer]
render_attachment_warning_if_needed(@homework)
#编程作业相关属性
@ -191,13 +385,6 @@ class HomeworkCommonController < ApplicationController
@homework.homework_detail_programing ||= HomeworkDetailPrograming.new
@homework_detail_programing = @homework.homework_detail_programing
@homework_detail_programing.language = params[:language_type].to_i if params[:language_type]
if anonymous != @homework.anonymous_comment
if anonymous == 1
@homework_detail_programing.ta_proportion = 0.6
else
@homework_detail_programing.ta_proportion = 0.5
end
end
@homework.homework_samples.delete_all if params[:sample]
sample_inputs = params[:sample][:input] if params[:sample]
@ -231,15 +418,7 @@ class HomeworkCommonController < ApplicationController
@homework_detail_group.base_on_project = params[:base_on_project] ? 1 : 0
end
if anonymous != @homework.anonymous_comment
@homework.student_works.where("work_status != 0").each do |student_work|
student_work.save
end
end
@homework.anonymous_comment = params[:homework_common][:anonymous_comment] ? params[:homework_common][:anonymous_comment].to_i : 1
if @homework.save
homework_detail_manual.save if homework_detail_manual
@homework_detail_programing.save if @homework_detail_programing
@homework_detail_group.save if @homework_detail_group
@ -247,20 +426,7 @@ class HomeworkCommonController < ApplicationController
# create_works_list @homework
# end
@hw_status = params[:hw_status].to_i
if params[:is_manage] == "1"
redirect_to user_manage_homeworks_user_path(User.current.id)
elsif params[:is_manage] == "2"
redirect_to user_receive_homeworks_user_path(User.current.id)
elsif @hw_status == 1
redirect_to user_course_community_path(User.current.id)
elsif @hw_status == 2
redirect_to course_path(@course.id)
elsif @hw_status == 5
redirect_to student_work_index_url(:homework => @homework.id)
else
redirect_to homework_common_index_path(:course => @course.id)
end
redirect_to student_work_index_url(:homework => @homework.id)
end
end
end
@ -275,43 +441,43 @@ class HomeworkCommonController < ApplicationController
is_eva_student_works = StudentWork.where(:homework_common_id => is_eva_homeworks.map{|hw| hw.id})
has_eva_homeworks = @course.homework_commons.includes(:homework_detail_manual).where("homework_commons.anonymous_comment = 0 and homework_detail_manuals.comment_status = 3")
has_eva_student_works = StudentWork.where(:homework_common_id => has_eva_homeworks.map{|hw| hw.id})
@course.student.each do |student|
user = student.student
course_statistics = CourseHomeworkStatistics.find_by_course_id_and_user_id(@homework.course_id, student.student_id)
if user && course_statistics
committed_work_num = user.student_works.where("homework_common_id in #{homework_ids} and work_status != 0").count
un_commit_work_num = (hw_count - committed_work_num) < 0 ? 0 : (hw_count - committed_work_num)
late_commit_work_num = user.student_works.where("homework_common_id in #{homework_ids} and work_status = 2").count
absence_evaluation_work_num = user.student_works_evaluation_distributions.where(:student_work_id => has_eva_student_works.map(&:id)).count -
user.student_works_scores.where(:reviewer_role => 3, :student_work_id => has_eva_student_works.map(&:id)).group_by(&:student_work_id).count
absence_evaluation_work_num = absence_evaluation_work_num < 0 ? 0 : absence_evaluation_work_num
un_evaluation_work_num = user.student_works_evaluation_distributions.where(:student_work_id => is_eva_student_works.map(&:id)).count -
user.student_works_scores.where(:reviewer_role => 3, :student_work_id => is_eva_student_works.map(&:id)).group_by(&:student_work_id).count
un_evaluation_work_num = un_evaluation_work_num < 0 ? 0 : un_evaluation_work_num
appeal_num = user.student_works_scores.where(:student_work_id => student_works.map(&:id), :appeal_status => 3).count
average_score = user.student_works.where(:id => student_works.map(&:id)).select("AVG(student_works.work_score) as score").first ? user.student_works.where(:id => student_works.map(&:id)).select("AVG(student_works.work_score) as score").first.score : 0
total_score = user.student_works.where(:id => student_works.map(&:id)).select("SUM(student_works.work_score) as score").first ? user.student_works.where(:id => student_works.map(&:id)).select("SUM(student_works.work_score) as score").first.score : 0
course_statistics.update_attributes(:committed_work_num => committed_work_num, :un_commit_work_num => un_commit_work_num,
:late_commit_work_num => late_commit_work_num, :absence_evaluation_work_num => absence_evaluation_work_num, :un_evaluation_work_num => un_evaluation_work_num,
:appeal_num => appeal_num, :average_score => average_score, :total_score => total_score)
end
end
# @course.student.each do |student|
# user = student.student
# course_statistics = CourseHomeworkStatistics.find_by_course_id_and_user_id(@homework.course_id, student.student_id)
# if user && course_statistics
# committed_work_num = user.student_works.where("homework_common_id in #{homework_ids} and work_status != 0").count
# un_commit_work_num = (hw_count - committed_work_num) < 0 ? 0 : (hw_count - committed_work_num)
# late_commit_work_num = user.student_works.where("homework_common_id in #{homework_ids} and work_status = 2").count
# absence_evaluation_work_num = user.student_works_evaluation_distributions.where(:student_work_id => has_eva_student_works.map(&:id)).count -
# user.student_works_scores.where(:reviewer_role => 3, :student_work_id => has_eva_student_works.map(&:id)).group_by(&:student_work_id).count
# absence_evaluation_work_num = absence_evaluation_work_num < 0 ? 0 : absence_evaluation_work_num
# un_evaluation_work_num = user.student_works_evaluation_distributions.where(:student_work_id => is_eva_student_works.map(&:id)).count -
# user.student_works_scores.where(:reviewer_role => 3, :student_work_id => is_eva_student_works.map(&:id)).group_by(&:student_work_id).count
# un_evaluation_work_num = un_evaluation_work_num < 0 ? 0 : un_evaluation_work_num
# appeal_num = user.student_works_scores.where(:student_work_id => student_works.map(&:id), :appeal_status => 3).count
# average_score = user.student_works.where(:id => student_works.map(&:id)).select("AVG(student_works.work_score) as score").first ? user.student_works.where(:id => student_works.map(&:id)).select("AVG(student_works.work_score) as score").first.score : 0
# total_score = user.student_works.where(:id => student_works.map(&:id)).select("SUM(student_works.work_score) as score").first ? user.student_works.where(:id => student_works.map(&:id)).select("SUM(student_works.work_score) as score").first.score : 0
# course_statistics.update_attributes(:committed_work_num => committed_work_num, :un_commit_work_num => un_commit_work_num,
# :late_commit_work_num => late_commit_work_num, :absence_evaluation_work_num => absence_evaluation_work_num, :un_evaluation_work_num => un_evaluation_work_num,
# :appeal_num => appeal_num, :average_score => average_score, :total_score => total_score)
# end
# end
respond_to do |format|
format.html {
@hw_status = params[:hw_status].to_i
if @hw_status == 1
redirect_to user_path(User.current.id)
elsif @hw_status == 2
redirect_to course_path(@course.id)
else
redirect_to homework_common_index_path(:course => @course.id)
end
redirect_to homework_common_index_path(:course => @course.id, :homework_type => @homework.homework_type)
}
end
end
end
#更新作业说明
def update_explanation
@is_teacher = User.current.admin? || User.current.allowed_to?(:as_teacher, @course)
@homework.update_attribute('explanation', params[:homework_common][:explanation])
redirect_to student_work_index_path(:homework => @homework.id, :tab => 2)
end
#加入到题库
def add_to_homework_bank
if params[:type] && (params[:type].to_i == 1 || params[:type].to_i == 3)
@ -325,24 +491,25 @@ class HomeworkCommonController < ApplicationController
end
homework_bank = add_to_homework_bank_f @homework
homework_bank.save
if @homework.homework_type == 4
HomeworkBankShixun.create(:homework_bank_id => homework_bank.id, :shixun_id => @homework.homework_commons_shixuns.shixun_id)
end
@homework.update_attributes(:homework_bank_id => homework_bank.id)
elsif params[:type].to_i == 2
homework_bank = HomeworkBank.where(:id => @homework.homework_bank_id).first
if homework_bank
homework_bank.update_attributes(:name => @homework.name, :description => @homework.description, :homework_type => @homework.homework_type)
homework_bank.update_attributes(:name => @homework.name, :description => @homework.description, :homework_type => @homework.homework_type, :reference_answer => @homework.reference_answer)
if @homework.homework_type == 2 && @homework.homework_detail_programing
homework_bank.update_attributes(:language => @homework.homework_detail_programing.language)
homework_bank.homework_bank_tests.destroy_all
@homework.homework_tests.each_with_index do |homework_test|
homework_bank.homework_bank_tests << HomeworkBankTest.new(
test_type: 1,
input: homework_test.input,
output: homework_test.output
)
end
@homework.homework_samples.each_with_index do |homework_test|
homework_bank.homework_bank_tests << HomeworkBankTest.new(
test_type: 0,
homework_bank.homework_bank_samples << HomeworkBankSample.new(
input: homework_test.input,
output: homework_test.output
)
@ -355,9 +522,14 @@ class HomeworkCommonController < ApplicationController
if @homework.is_update
@homework.update_attributes(:is_update => 0)
end
@user_activity_id = params[:user_activity_id].to_i
@hw_status = params[:hw_status].to_i
@is_teacher = User.current.admin? || User.current.allowed_to?(:as_teacher, @course)
end
def set_public
@homework.update_attributes(:is_public => true)
respond_to do |format|
format.html{ redirect_to student_work_index_path(:homework => @homework.id) }
format.js
end
end
def publish_homework
@ -374,10 +546,10 @@ class HomeworkCommonController < ApplicationController
create_works_list @homework
end
#更新CourseHomeworkStatistics中每个学生的未交作品数
@course.student.each do |student|
course_statistics = CourseHomeworkStatistics.find_by_course_id_and_user_id(@homework.course_id, student.student_id)
course_statistics.update_attribute('un_commit_work_num', course_statistics.un_commit_work_num + 1) if course_statistics
end
# @course.student.each do |student|
# course_statistics = CourseHomeworkStatistics.find_by_course_id_and_user_id(@homework.course_id, student.student_id)
# course_statistics.update_attribute('un_commit_work_num', course_statistics.un_commit_work_num + 1) if course_statistics
# end
@course.members.each do |m|
@homework.course_messages << CourseMessage.new(:user_id => m.user_id, :course_id => @course.id, :viewed => false, :status => nil)
@ -434,8 +606,8 @@ class HomeworkCommonController < ApplicationController
end
#更新CourseHomeworkStatistics中该学生的待匿评数
course_statistics = CourseHomeworkStatistics.find_by_course_id_and_user_id(@homework.course_id, pro_work.user_id)
course_statistics.update_attribute('un_evaluation_work_num', course_statistics.un_evaluation_work_num + n) if course_statistics
# course_statistics = CourseHomeworkStatistics.find_by_course_id_and_user_id(@homework.course_id, pro_work.user_id)
# course_statistics.update_attribute('un_evaluation_work_num', course_statistics.un_evaluation_work_num + n) if course_statistics
end
else
student_works.each_with_index do |work, index|
@ -449,8 +621,8 @@ class HomeworkCommonController < ApplicationController
end
#更新CourseHomeworkStatistics中该学生的待匿评数
course_statistics = CourseHomeworkStatistics.find_by_course_id_and_user_id(@homework.course_id, user.id)
course_statistics.update_attribute('un_evaluation_work_num', course_statistics.un_evaluation_work_num + n) if course_statistics
# course_statistics = CourseHomeworkStatistics.find_by_course_id_and_user_id(@homework.course_id, user.id)
# course_statistics.update_attribute('un_evaluation_work_num', course_statistics.un_evaluation_work_num + n) if course_statistics
end
end
@homework_detail_manual.update_column('comment_status', 2)
@ -485,9 +657,9 @@ class HomeworkCommonController < ApplicationController
student_work.save
#更新CourseHomeworkStatistics中该学生的待匿评数和缺评数
course_statistics = CourseHomeworkStatistics.find_by_course_id_and_user_id(@homework.course_id, student_work.user_id)
course_statistics.update_attribute('un_evaluation_work_num', (course_statistics.un_evaluation_work_num - absence_penalty_count) < 0 ? 0 : (course_statistics.un_evaluation_work_num - absence_penalty_count)) if course_statistics
course_statistics.update_attribute('absence_evaluation_work_num', course_statistics.absence_evaluation_work_num + absence_penalty_count) if course_statistics
# course_statistics = CourseHomeworkStatistics.find_by_course_id_and_user_id(@homework.course_id, student_work.user_id)
# course_statistics.update_attribute('un_evaluation_work_num', (course_statistics.un_evaluation_work_num - absence_penalty_count) < 0 ? 0 : (course_statistics.un_evaluation_work_num - absence_penalty_count)) if course_statistics
# course_statistics.update_attribute('absence_evaluation_work_num', course_statistics.absence_evaluation_work_num + absence_penalty_count) if course_statistics
end
# 未参与匿评的缺评计算

View File

@ -0,0 +1,17 @@
class IframesController < ApplicationController
layout false
skip_before_filter :verify_authenticity_token, :only => [:html_content]
def show
render :layout => false
end
# 渲染实训代码
def html_content
@contents = params[:contents] || ""
respond_to do |format|
format.js
format.html
end
end
end

View File

@ -0,0 +1,72 @@
class KuberneteController < ApplicationController
require 'open3'
layout "base_edu"
RC_PATH = "files/k8s/webssh/controller.yaml"
SVC_PATH = "files/k8s/webssh/service.yaml"
SERVER_URL = "https://106.75.96.108:6443"
TOKEN = "c7dd73a7c86992fb"
# YAML.load(File.open(rc_PATH))
# REDO:销毁的时候文件一并要销毁
def exec_pod
# 生成ymal文件
nod_name = params[:name]
path_type = params[:type]
rc = YAML.load(File.open(RC_PATH))
svc = YAML.load(File.open(SVC_PATH))
File.new(File.join("files/k8s/#{path_type}", "controller-#{nod_name}.yaml"),"w+")
File.new(File.join("files/k8s/#{path_type}", "service-#{nod_name}.yaml"),"w+")
rc = change_yaml_info(rc, nod_name, "rc")
svc = change_yaml_info(svc, nod_name, "svc")
current_rc_path = "files/k8s/#{path_type}/controller-#{nod_name}.yaml"
current_svc_path = "files/k8s/#{path_type}/service-#{nod_name}.yaml"
open(current_rc_path, 'w') { |f| YAML.dump(rc, f) }
open(current_svc_path, 'w') { |f| YAML.dump(svc, f) }
# 启动容器
# 删除容器命令
# 如果连接到其它服务器可以使用ssh -t
kubenete_rc = "kubectl --server='" + SERVER_URL + "' --token='" + TOKEN + "' --insecure-skip-tls-verify=true " + "create -f " + current_rc_path
kubenete_svc = "kubectl --server='" + SERVER_URL + "' --token='" + TOKEN + "' --insecure-skip-tls-verify=true " + "create -f " + current_svc_path
logger.info("webss kubenete_rc is" + kubenete_rc)
logger.info("webss kubenete_svc is" + kubenete_svc)
# stdin, stdout, stderr, wait_thr = Open3.popen3([env,] cmd... [, opts])
# 可以多少秒以后执行
stdin, stdout, stderr = Open3.popen3(kubenete_rc)
logger.info("Open3 result is ###"+ stdout.gets)
stdin2, stdout2, stderr2 = Open3.popen3(kubenete_svc)
logger.info("Open3 result is ###"+ stdout2.gets)
render :json => {:status => "good"}
end
def exec_container
pod_name = "webssh-master#{parmas[:myshixun_id]}"
git_url =
# kubectl exec webssh-master1-gn1ww -c webssh python -v
# webssh 容器中执行命令,克隆代码,注意代码存放位置
git_clone = "kubectl --server='#{SERVER_URL}' --token='#{TOKEN}' --insecure-skip-tls-verify=true exec webssh-master1-gn1ww -c webssh clone #{git_url}"
stdin, stdout, stderr = Open3.popen3(git_clone)
format.js
end
def new
end
def create
end
private
# yaml数据处理
# 处理数据类型如下
def change_yaml_info rc, nod_name, type
rc['metadata']['name'] = rc['metadata']['name'] + nod_name
rc['metadata']['labels']['name'] = rc['metadata']['labels']['name'] + nod_name
rc['spec']['selector']['name'] = rc['spec']['selector']['name'] + nod_name
if type == "rc"
rc['spec']['template']['metadata']['labels']['name'] = rc['spec']['template']['metadata']['labels']['name'] + nod_name
elsif type == "svc"
rc['spec']['ports'][0]['nodePort'] = rc['spec']['ports'][0]['nodePort'].to_i + nod_name.to_i
end
return rc
end
end

File diff suppressed because it is too large Load Diff

View File

@ -19,6 +19,7 @@
class MembersController < ApplicationController
helper :users
model_object Member
include CoursesHelper
before_filter :find_model_object, :except => [:index, :create, :autocomplete, :allow_to_join_project, :refused_allow_to_join_project]
#before_filter :find_model_object_contest, :except => [:index, :create, :autocomplete]
before_filter :find_project_from_association, :except => [:index, :create, :autocomplete, :allow_to_join_project, :refused_allow_to_join_project]
@ -240,18 +241,27 @@ class MembersController < ApplicationController
@create_member_error_messages = "角色不能留空" unless params[:membership][:role_ids]
@create_member_error_messages = "用户不能留空" unless params[:membership][:user_ids]
if params[:membership][:user_ids]
#if params[:membership][:user_ids]
if params[:choose_student_ids] && params[:membership]
attrs = params[:membership].dup
user_ids = attrs.delete(:user_ids)
user_ids = params[:choose_student_ids].split(",")
user_ids.each do |user_id|
member = Member.new(:role_ids => params[:membership][:role_ids], :user_id => user_id)
if @course.members.where(:user_id => user_id).empty?
member = Member.new(:role_ids => params[:membership][:role_ids], :user_id => user_id)
else
member = @course.members.where(:user_id => user_id).first
member_role = MemberRole.new(:role_id => params[:membership][:role_ids][0], :is_current => 0)
member.member_roles << member_role
end
role_ids = params[:membership][:role_ids]
#role = Role.find(params[:membership][:role_ids])
# 这里的判断只能通过角色名,可以弄成常量
if role_ids && role_ids.include?("10")
StudentsForCourse.create(:student_id => user_id, :course_id =>@course.id)
end
if params[:course_group_id] && params[:course_group_id] != '0'
member.course_group_id = params[:course_group_id].to_i
end
#给新成员和老师发送加入课程的消息发送者id放在CourseMessage的course_message_id字段中
#course_message_type设置为JoinCourse
@ -276,9 +286,11 @@ class MembersController < ApplicationController
end
@course.members << members
@course.course_infos << course_info
@roles = Role.givable.all[3..5]
members = @course.member_principals.includes(:roles, :principal).all.sort
#@teacher_count = searchTeacherAndAssistant(@course).count
#@student_count = @course.student.count
#@no_group_count = @course.members.where("course_group_id = 0").select{|m| m.roles.to_s.include?("Student")}.count
#@roles = Role.givable.all[3..5]
#members = @course.member_principals.includes(:roles, :principal).all.sort
else
@create_member_error_messages = l(:label_user_role_null)
end
@ -441,24 +453,42 @@ class MembersController < ApplicationController
end
elsif @course
if request.delete? && @member.deletable?
@member.destroy
user_admin = CourseInfos.where("user_id = ? and course_id = ?", @member.user_id, @course.id)
if user_admin.size > 0
user_admin.each do |user|
user.destroy
if @member.member_roles.count == 1
joined = StudentsForCourse.where('student_id = ? and course_id = ?', @member.user_id,@course.id).destroy_all
@member.destroy
else
if params[:type] == '1'
@member.member_roles.where("role_id = 7 or role_id = 9").destroy_all
@member.member_roles.where("role_id = 10").first.update_attributes(:is_current => 1)
else
@member.member_roles.where("role_id = 10").destroy_all
joined = StudentsForCourse.where('student_id = ? and course_id = ?', @member.user_id,@course.id).destroy_all
@member.update_attributes(:course_group_id => 0)
if params[:group_id] == '0'
@members = @course.members.select{|m| m.roles.to_s.include?("Student")}
else
@members = @course.members.where("course_group_id = 0").select{|m| m.roles.to_s.include?("Student")}
end
@member.member_roles.where("role_id = 7 or role_id = 9").first.update_attributes(:is_current => 1)
end
end
joined = StudentsForCourse.where('student_id = ? and course_id = ?', @member.user_id,@course.id)
joined.each do |join|
join.destroy
end
@teacher_count = searchTeacherAndAssistant(@course).count
@student_count = @course.student.count
@no_group_count = @course.members.where("course_group_id = 0").select{|m| m.roles.to_s.include?("Student")}.count
# user_admin = CourseInfos.where("user_id = ? and course_id = ?", @member.user_id, @course.id)
# if user_admin.size > 0
# user_admin.each do |user|
# user.destroy
# end
# end
@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
respond_to do |format|
format.html { redirect_to_settings_in_courses }
format.html { redirect_to members_course_path(@course) }
format.js
format.api {
if @member.destroyed?

View File

@ -1,6 +1,6 @@
class MemosController < ApplicationController
default_search_scope :memos
before_filter :find_forum, :only => [:new, :create, :preview, :update]
before_filter :find_forum, :only => [:new, :create, :preview, :update, :reply]
before_filter :find_attachments, :only => [:preview]
before_filter :find_memo, :except => [:new, :create, :preview]
before_filter :authenticate_user_edit, :only => [:edit, :update]
@ -29,13 +29,14 @@ class MemosController < ApplicationController
def new
# 如何是问吧主页来的,导航不显示具体贴吧名
@user = User.current
@memo = Memo.new
@my_forums_count = Memo.where("author_id =? and parent_id is null", User.current.id).count
@my_memos_count = Memo.where("author_id =? and parent_id is not null", User.current.id).count
@my_forums_count = Memo.where("author_id =? and parent_id is null",@user.id).count
@my_memos_count = Memo.where("author_id =? and parent_id is not null", @user.id).count
@forums = Forum.reorder("topic_count desc,updated_at desc")
respond_to do |format|
format.js
format.html {render layout: 'base_new_forum'}
format.html {render layout: 'base_edu'}
format.json { render json: @memo }
end
end
@ -88,6 +89,7 @@ class MemosController < ApplicationController
REPLIES_PER_PAGE = 20 unless const_defined?(:REPLIES_PER_PAGE)
def show
@user = User.current
# 更新贴吧帖子留言对应的memo_messages的viewed字段
unless @memo.children.blank?
@memo.children.each do |child|
@ -99,12 +101,13 @@ class MemosController < ApplicationController
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)
unless query_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
end
pre_count = REPLIES_PER_PAGE
@memo = @memo.root # 取出楼主防止输入帖子id让回复作为主贴显示
@memo.update_column(:viewed_count, (@memo.viewed_count.to_i + 1))
@ -140,19 +143,20 @@ class MemosController < ApplicationController
respond_to do |format|
format.js
format.html {render :layout => 'base_new_forum'}
format.html {render :layout => 'base_edu'}
format.json { render json: @memo }
format.xml { render xml: @memo }
end
end
def edit
@my_topic_count = 0
@my_replies_count = Memo.where(:parent_id => @memo.id).count
@forums = Forum.reorder("topic_count desc,updated_at desc")
@replying = false
#@my_topic_count = 0
#@my_replies_count = Memo.where(:parent_id => @memo.id).count
#@forums = Forum.reorder("topic_count desc,updated_at desc")
#@replying = false
@user = User.current
respond_to do |format|
format.html {render :layout => 'base_new_forum'}
format.html {render :layout => 'base_edu'}
end
end
@ -161,10 +165,9 @@ class MemosController < ApplicationController
@flag = false
respond_to do |format|
if( #@memo.update_column(:subject, params[:memo][:subject]) &&
@memo.update_column(:content, params[:memo][:content]) &&
@memo.update_column(:sticky, params[:memo][:sticky]) &&
@memo.update_column(:lock, params[:memo][:lock]) &&
if( @memo.update_column(:content, params[:memo][:content]) &&
@memo.update_column(:sticky, params[:memo][:sticky].to_i) &&
@memo.update_column(:lock, params[:memo][:lock].to_i) &&
@memo.update_column(:subject,params[:memo][:subject]) &&
@memo.update_column(:updated_at,Time.now))
@memo.save_attachments(params[:attachments] || (params[:memo] && params[:memo][:uploads]))
@ -172,7 +175,7 @@ class MemosController < ApplicationController
@flag = @memo.save
# @memo.root.update_attribute(:updated_at, @memo.updated_at)
format.js
format.html {redirect_to back_memo_url, notice: "#{l :label_memo_update_succ}"}
format.html {redirect_to back_memo_url}
else
format.js
format.html { render action: "edit" }
@ -181,12 +184,64 @@ class MemosController < ApplicationController
end
end
def reply
if params[:memo].present? && params[:memo][:parent_id].present?
parent = Memo.find params[:memo][:parent_id]
@memo = params[:activity_id].blank? ? parent : Memo.find(params[:activity_id].to_i)
@reply = Memo.new
@reply.author = User.current
@reply.forum_id = parent.forum_id
@reply.content = params[:content]
@reply.subject = "RE: #{@memo.subject}"
#@reply.reply_id = params[:id]
@reply.root_id = parent.root_id.nil? ? parent.id : parent.root_id
# @reply.reply_id = params[:id]
parent.children << @reply
else
@reply = Memo.new()
@reply.content = params[:content]
@reply.subject = @memo.subject
@reply.author = User.current
@reply.forum_id = @forum.id
#@reply.content = @quote + @reply.content
#@reply.subject = "RE: #{@topic.subject}" unless params[:reply][:subject]
@reply.root_id = @memo.id
@reply.safe_attributes = params[:reply]
@memo.children << @reply
# @reply.reply_id = params[:id]
end
redirect_to message_replies_forum_memo_path(@memo.forum, @memo, :user_activity_id => params[:user_activity_id])
end
def message_replies
@replies = Memo.where(:root_id => @memo.id).order("created_at desc")
@reply_count = @replies.count
@replies = get_no_children_comments_all @replies
#@limit_count = @replies.count
#@page = params[:page] ? params[:page].to_i + 1 : 0
#@limit = 10
#@replies = @replies[@page * @limit..@page * @limit + 9]
@reply = Message.new()
@user_activity_id = params[:user_activity_id].blank? ? @memo.id : params[:user_activity_id].to_i
respond_to do |format|
format.js
end
end
def destroy
@memo.destroy
respond_to do |format|
# format.html { redirect_to @back_url }
format.html { redirect_to back_memo_or_forum_url }
#format.html { redirect_to @back_url }
format.html { redirect_to forums_path }
format.js{
@memo = Memo.find(params[:user_activity_id].to_i)
@replies = Memo.where(:root_id => @memo.id).order("created_at desc")
@reply_count = @replies.count
@replies = get_no_children_comments_all @replies
#redirect_to message_replies_forum_memo_path(@memo.forum, @memo, :user_activity_id => params[:user_activity_id])
}
format.json { head :no_content }
end
end
@ -195,7 +250,13 @@ class MemosController < ApplicationController
def change_sticky
@memo.sticky ? @memo.update_attribute(:sticky, false) : @memo.update_attribute(:sticky, true)
respond_to do |format|
format.html { redirect_to forum_memo_path(@memo.forum, @memo) }
format.html {
if params[:index]
redirect_to forums_path
else
redirect_to forum_memo_path(@memo.forum, @memo)
end
}
end
end

View File

@ -20,10 +20,10 @@ class MessagesController < ApplicationController
before_filter :authorize1, :only => [:show]
menu_item :boards
default_search_scope :messages
before_filter :find_board, :only => [:new, :preview,:edit]
before_filter :find_board, :only => [:new, :create, :preview, :edit, :update, :sticky_topic]
before_filter :find_attachments, :only => [: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,:join_org_subfield, :get_subfield_on_click_org, :join_org_subfields]
before_filter :find_message, :except => [:new, :create, :preview, :join_org_subfield, :get_subfield_on_click_org, :join_org_subfields]
before_filter :authorize, :except => [:preview, :edit, :update, :destroy, :message_replies, :new, :create, :join_org_subfield, :get_subfield_on_click_org, :join_org_subfields, :sticky_topic]
helper :boards
helper :watchers
@ -39,7 +39,7 @@ class MessagesController < ApplicationController
def show
# 顶部导航
@project_menu_type = 3
@topic.update_column('visits', @topic.visits + 1)
@isReply = true
# page = params[:page]
# # Find the page of the requested reply
@ -51,31 +51,32 @@ class MessagesController < ApplicationController
@replies = Message.where("root_id = #{@topic.id}").reorder("created_on desc")
@reply_count = @replies.count
@replies = get_no_children_comments_all @replies
@limit_count = @replies.count
@page = params[:page] ? params[:page].to_i + 1 : 0
@limit = 10
@replies = @replies[@page * @limit..@page * @limit + 9]
@reply = Message.new(:subject => "RE: #{@message.subject}")
#@limit_count = @replies.count
#@page = params[:page] ? params[:page].to_i + 1 : 0
#@limit = 10
#@replies = @replies[@page * @limit..@page * @limit + 9]
@reply = Message.new
if @course
#帖子消息状态更新
course_messages = CourseMessage.where("user_id =? and course_message_type =? and course_message_id =? and course_id =? and viewed =?", User.current.id, 'Message', @topic.id, @course.id, 0)
course_messages.update_all(:viewed => true)
#@replies = @topic.children.
#includes(:author, :attachments, :praise_tread_cache, {:board => :project}).
#reorder("#{Message.table_name}.created_on DESC").
#limit(@reply_pages.per_page).
#offset(@reply_pages.offset).
#all
#includes(:author, :attachments, :praise_tread_cache, {:board => :project}).
#reorder("#{Message.table_name}.created_on DESC").
#limit(@reply_pages.per_page).
#offset(@reply_pages.offset).
#all
#@replies = paginateHelper messages_replies,10
# 班级帖子回复消息设为已读
@replies.each do |comment|
course_message = CourseMessage.where(:course_message_type => 'Message', :course_message_id => comment.id, :user_id => User.current.id, :viewed => 0)
course_message.update_all(:viewed => 1)
course_message = CourseMessage.where(:course_message_type => 'Message', :course_message_id => comment.id, :user_id => User.current.id, :viewed => 0)
course_message.update_all(:viewed => 1)
end
@left_nav_type = 2
respond_to do |format|
format.js
format.html {render :layout => 'base_courses'}
format.html {render :layout => 'base_edu'}
end
#render :action => "show", :layout => "base_courses"#by young
elsif @project
@ -133,11 +134,19 @@ class MessagesController < ApplicationController
# Create a new topic
def new
@message = Message.new
respond_to do |format|
format.html { render :layout => 'base_edu' }
end
end
def create
if User.current.logged?
@message = Message.new
@message.author = User.current
@message.board = @board
@message.safe_attributes = params[:message]
@message.sticky = params[:message][:sticky] ? 1 : 0
if request.post?
if @project
is_public = @project.is_public
@ -157,16 +166,18 @@ class MessagesController < ApplicationController
call_hook(:controller_messages_new_after_save, { :params => params, :message => @message})
render_attachment_warning_if_needed(@message)
if params[:is_board]
if @project
redirect_to project_boards_path(@project)
elsif @course
redirect_to course_boards_path(@course, :board_id => @board.id)
elsif @contest
redirect_to contest_boards_path(@contest, :board_id => @board.id)
end
else
if @course
redirect_to board_message_url(@board, @message)
else
if params[:is_board]
if @project
redirect_to project_boards_path(@project)
elsif @contest
redirect_to contest_boards_path(@contest, :board_id => @board.id)
end
else
redirect_to board_message_url(@board, @message)
end
end
else
if params[:is_board]
@ -178,7 +189,7 @@ class MessagesController < ApplicationController
redirect_to contest_boards_path(@contest, :board_id => @board.id, :flag => true)
end
else
layout_file = @project ? 'base_projects' : (@course ? 'base_courses' : 'base_contests')
layout_file = @project ? 'base_projects' : (@course ? 'base_edu' : 'base_contests')
render :action => 'new', :layout => layout_file
end
@ -187,7 +198,7 @@ class MessagesController < ApplicationController
@left_nav_type = 2
respond_to do |format|
format.html {
layout_file = @project ? 'base_projects' : (@course ? 'base_courses' : 'base_contests')
layout_file = @project ? 'base_projects' : (@course ? 'base_edu' : 'base_contests')
render :layout => layout_file
}
end
@ -201,7 +212,7 @@ class MessagesController < ApplicationController
def reply
if params[:parent_id]
parent = Message.find params[:parent_id]
@topic = params[:activity_id].nil? ? parent : Message.find(params[:activity_id].to_i)
@topic = params[:activity_id].blank? ? parent : Message.find(params[:activity_id].to_i)
@reply = Message.new
@reply.author = User.current
@reply.board = parent.board
@ -232,37 +243,56 @@ class MessagesController < ApplicationController
update_forge_activity(@topic.class,@topic.id)
update_org_activity(@topic.class,@topic.id)
redirect_to message_replies_board_message_path(@topic, :board_id => @board.id, :user_activity_id => params[:user_activity_id])
#@topic.update_attribute(:updated_on, Time.now)
if !@reply.new_record?
if params[:asset_id]
ids = params[:asset_id].split(',')
update_kindeditor_assets_owner ids,@reply.id,OwnerTypeHelper::MESSAGE
end
# if !@reply.new_record?
# if params[:asset_id]
# ids = params[:asset_id].split(',')
# update_kindeditor_assets_owner ids,@reply.id,OwnerTypeHelper::MESSAGE
# end
#
# call_hook(:controller_messages_reply_after_save, { :params => params, :message => @reply})
# attachments = Attachment.attach_files(@reply, params[:attachments])
# render_attachment_warning_if_needed(@reply)
# else
# #render file: 'messages#show', layout: 'base_courses'
# end
call_hook(:controller_messages_reply_after_save, { :params => params, :message => @reply})
attachments = Attachment.attach_files(@reply, params[:attachments])
render_attachment_warning_if_needed(@reply)
else
#render file: 'messages#show', layout: 'base_courses'
end
if params[:user_activity_id]
@user_activity_id = params[:user_activity_id]
@is_course = params[:is_course] if params[:is_course]
@is_board = params[:is_board] if params[:is_board]
respond_to do |format|
format.js
end
return
else
redirect_to board_message_url(@board, @topic)
return
end
# if params[:user_activity_id]
# @user_activity_id = params[:user_activity_id]
# @is_course = params[:is_course] if params[:is_course]
# @is_board = params[:is_board] if params[:is_board]
# respond_to do |format|
# format.js
# end
# return
# else
# redirect_to board_message_url(@board, @topic)
# return
# end
end
def message_replies
@replies = Message.where("root_id = #{@topic.id}").reorder("created_on desc")
@reply_count = @replies.count
@replies = get_no_children_comments_all @replies
#@limit_count = @replies.count
#@page = params[:page] ? params[:page].to_i + 1 : 0
#@limit = 10
#@replies = @replies[@page * @limit..@page * @limit + 9]
@reply = Message.new()
@user_activity_id = params[:user_activity_id].blank? ? @topic.id : params[:user_activity_id].to_i
if !params[:user_activity_id].blank? && params[:user_activity_id].to_i != @topic.id
@topic.update_attributes(:visits => @topic.visits + 1)
end
respond_to do |format|
format.js
end
end
# Edit a message
def edit
@isReply = false
if @project
(render_403; return false) unless @message.editable_by?(User.current)
elsif @course
@ -273,55 +303,34 @@ class MessagesController < ApplicationController
(render_403; return false) unless @message.org_subfield_editable_by?(User.current)
end
respond_to do |format|
format.html {
if @project
layout_file = 'base_projects'
elsif @course
@left_nav_type = 2
layout_file = 'base_edu'
elsif @contest
@left_nav_type = 4
layout_file = 'base_contests'
elsif @org_subfield
@organization = @org_subfield.organization
layout_file = 'base_org'
end
render :layout => layout_file
}
end
end
def update
@message.safe_attributes = params[:message]
if request.post? && @message.save
@message.sticky = params[:message][:sticky] ? 1 : 0
if @message.save
attachments = Attachment.attach_files(@message, params[:attachments])
render_attachment_warning_if_needed(@message)
#flash[:notice] = l(:notice_successful_update)
@message.reload
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
redirect_to project_path(@project)
elsif @course
redirect_to course_activity_path(@course)
elsif @contest
redirect_to contest_path(@contest)
end
elsif params[:is_course] && params[:is_course].to_i == 1 && params[:is_board] && params[:is_board].to_i == 1
if @project
redirect_to project_boards_path(@project)
elsif @course
redirect_to course_boards_path(@course)
elsif @contest
redirect_to contest_boards_path(@contest)
end
else
redirect_to board_message_url(@message.board, @message.root, :r => (@message.parent_id && @message.id))
end
elsif request.get? || request.post?
if params[:is_course] && params[:is_board]
@is_course = params[:is_course]
@is_board = params[:is_board]
end
respond_to do |format|
format.html {
if @project
layout_file = 'base_projects'
elsif @course
@left_nav_type = 2
layout_file = 'base_courses'
elsif @contest
@left_nav_type = 4
layout_file = 'base_contests'
elsif @org_subfield
@organization = @org_subfield.organization
layout_file = 'base_org'
end
render :layout => layout_file
}
end
redirect_to board_message_url(@message.board, @message.root, :r => (@message.parent_id && @message.id))
end
end
@ -333,9 +342,7 @@ class MessagesController < ApplicationController
@user_activity_id = params[:user_activity_id]
@is_course = params[:is_course] if params[:is_course]
@is_board = params[:is_board] if params[:is_board]
respond_to do |format|
format.js
end
redirect_to message_replies_board_message_path(@topic, :board_id => @board.id, :user_activity_id => params[:user_activity_id])
return
end
if @project
@ -366,7 +373,7 @@ class MessagesController < ApplicationController
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)
redirect_to course_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
@ -399,6 +406,21 @@ class MessagesController < ApplicationController
end
end
def sticky_topic
(render_403; return false) unless (User.current.admin? || User.current.allowed_to?(:as_teacher, @course))
@topic.update_attributes(:sticky => @topic.sticky == 1 ? 0 : 1)
respond_to do |format|
format.js
format.html{
if params[:is_board]
redirect_to course_boards_path(@course)
else
redirect_to board_message_path(@topic.board_id, @topic)
end
}
end
end
def quote
# @subject = @message.subject
# @subject = "RE: #{@subject}" unless @subject.starts_with?('RE:')
@ -437,8 +459,8 @@ class MessagesController < ApplicationController
: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)
: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)

View File

@ -16,10 +16,10 @@
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
class MyController < ApplicationController
include ApplicationHelper
layout "users_base"
# edit
skip_before_filter :check_authentication, :only => [:account]
before_filter :auth_login1, :only => [:account]
#
before_filter :require_login, except: [:change_mail_notification]
helper :issues
@ -145,14 +145,43 @@ class MyController < ApplicationController
applied_message = AppliedMessage.where(:id => params[:applied_message_id]).first
applied_message.update_attribute(:viewed, true)
end
# 基本资料不完善 @force为false 完善 @force为true
@force = false
if params[:tip]
@force = true
@user = params[:user_id].nil? ? User.current : User.find(params[:user_id])
# @user = User.current
# 认证
ue = @user.user_extensions
@trail_authentication = ApplyAction.where(:user_id => User.current.id, :container_type => "TrialAuthorization").order("created_at desc").first
@authentication = @user.authentication
if @user.nickname.nil? || @user.lastname.nil? || ue.try(:identity).nil? || ue.try(:location).nil? || ue.try(:location).nil?
@require_auth = true
else
if User.current.certification != 1 && (@trail_authentication.blank? || (@trail_authentication.status == 2 && (@trail_authentication.updated_at.to_i + 5*60) < Time.now.to_i))
@require_trail_auth = true
end
end
# @require_auth = true
#
# # 基本资料不完善 @force为false 完善 @force为true
# @force = false
# # @authentication = @user.authentication
# @trail_authentication = AuthenticationsUsers.where(:user_id => User.current.id).first
# if params[:tip]
# @force = true
# else
# user = UserExtensions.where(:user_id => User.current.id).first
# if user.identity.nil? || user.school_id.nil? || User.current.lastname.nil?
# @force = false
# else
# @force = @trail_authentication.blank? ? false : true
# end
# end
# # 用户认证
# @auth = @user.authentication ? false : true
@user = User.current
@s_message = AppliedMessage.where(:status => 3, :user_id => User.current.id, :viewed => 0, :applied_type => 'ApplyAddSchools').first
@d_message = AppliedMessage.where(:status => 3, :user_id => User.current.id, :viewed => 0, :applied_type => 'ApplyAddDepartment').first
AppliedMessage.where(:status => 3, :user_id => User.current.id, :viewed => 0, :applied_type => 'ApplyAddSchools').update_all(:viewed => true)
AppliedMessage.where(:status => 3, :user_id => User.current.id, :viewed => 0, :applied_type => 'ApplyAddDepartment').update_all(:viewed => true)
lg = @user.login
@pref = @user.pref
@ -160,21 +189,23 @@ class MyController < ApplicationController
diskfile1 = diskfile + 'temp'
begin
if request.post?
changed_login = (@user.login != params[:login])
changed_mail = (@user.mail != params[:user][:mail])
@user.safe_attributes = params[:user]
#changed_login = (@user.login != params[:login])
#changed_mail = (@user.mail != params[:user][:mail])
#@user.safe_attributes = params[:user]
@user.nickname = params[:nickname]
@user.lastname = params[:lastname]
@user.firstname = ""
@user.show_realname = params[:show_realname] ? 0 : 1
@user.pref.attributes = params[:pref]
@user.pref[:no_self_notified] = (params[:no_self_notified] == '1')
@user.login = params[:login].strip
unless @user.user_extensions.nil?
# 如果用户是从业者将单位名称保存至学校id字段
if @user.user_extensions.identity == 3
# @user.firstname = params[:enterprise_name]
@user.user_extensions.school_id = params[:occupation]
end
end
#@user.login = params[:login].strip
# unless @user.user_extensions.nil?
# # 如果用户是从业者将单位名称保存至学校id字段
# if @user.user_extensions.identity == 3
# # @user.firstname = params[:enterprise_name]
# @user.user_extensions.school_id = params[:occupation]
# end
# end
@se = @user.extensions
# if params[:occupation].to_i.to_s == params[:occupation]
@ -183,30 +214,53 @@ class MyController < ApplicationController
# @se.occupation = params[:occupation]
# end
@se.school_id = params[:occupation]
@se.department_id = params[:department_id]
@se.gender = params[:sex]
@se.location = params[:province] if params[:province]
@se.location_city = params[:city] if params[:city]
@se.identity = params[:identity].to_i if params[:identity]
@se.technical_title = params[:technical_title] if params[:technical_title]
@se.student_id = params[:no] if params[:no]
if @se.identity == 0
@se.technical_title = params[:te_technical_title] if params[:te_technical_title]
@se.student_id = nil
elsif @se.identity == 1
@se.student_id = params[:no] if params[:no]
@se.technical_title = nil
elsif @se.identity == 2
@se.technical_title = params[:pro_technical_title] if params[:pro_technical_title]
@se.student_id = nil
end
# @se.brief_introduction = params[:brief_introduction]
@se.description = params[:description]
@se.brief_introduction = params[:brief_introduction]
if @user.save && @se.save
# 修改邮箱的时候同步修改到gitlab
if changed_mail || changed_login
g = Gitlab.client
s = Trustie::Gitlab::Sync.new
begin
gid = @user.gid
if gid.nil?
gid = s.sync_user(@user).id
reward_grade(@user, @user.id, 'Account', 500)
if @se.identity == 1
school_ids = School.where(:auto_users_trial => 1).map(&:id)
if !@se.student_id.nil? && @se.student_id != "" && !@se.school.nil? && school_ids.include?(@se.school_id)
apply_action = ApplyAction.where(:user_id => @user.id, :container_type => "TrialAuthorization", :status => 0).first
unless apply_action.blank?
@user.update_attributes(:certification => 1)
apply_action.update_attributes(:status => 1)
end
g.edit_user(gid, :email => params[:user][:mail], :username => @user.login)
rescue Exception => e
puts e
end
end
# 修改邮箱的时候同步修改到gitlab
# if changed_mail || changed_login
# g = Gitlab.client
# s = Trustie::Gitlab::Sync.new
# begin
# gid = @user.gid
# if gid.nil?
# gid = s.sync_user(@user).id
# end
# g.edit_user(gid, :email => params[:user][:mail], :username => @user.login)
# rescue Exception => e
# puts e
# end
# end
# 头像保存
FileUtils.mv diskfile1, diskfile, force: true if File.exist? diskfile1
@ -214,7 +268,7 @@ class MyController < ApplicationController
@user.notified_project_ids = (@user.mail_notification == 'selected' ? params[:notified_project_ids] : [])
set_language_if_valid @user.language
flash[:notice] = l(:notice_account_updated)
redirect_to user_url(@user)
redirect_to my_account_url()
return
else
@user.login = lg
@ -225,7 +279,8 @@ class MyController < ApplicationController
File.delete(diskfile1) if File.exist?(diskfile1)
end
render :layout => 'new_base_user'
@setting_type = 1
render :layout => 'base_edu_account'
end
# Destroys user's account
@ -250,6 +305,7 @@ class MyController < ApplicationController
def password
begin
@act='password'
# @user = params[:user_id].nil? ? User.current : User.find(params[:user_id])
@user = User.current
unless @user.change_password_allowed?
flash.now[:error] = l(:notice_can_t_change_password)
@ -278,7 +334,8 @@ class MyController < ApplicationController
end
flash.now[:error] = l(:notice_account_old_wrong_password)
end
render :template => 'my/account',:layout=>'new_base_user'
@setting_type = 5
render :template => 'account/change_psd',:layout=>'base_edu_account'
end
# Create a new feeds key
@ -367,7 +424,7 @@ class MyController < ApplicationController
}
layout[group] = group_items
@user.pref[:my_page_layout] = layout
@user.pref.save
@user.pref.saveaccount
end
end
render :nothing => true

View File

@ -1,33 +1,167 @@
# encoding: utf-8
class MyshixunsController < ApplicationController
layout 'base_myshixun'
skip_before_filter :verify_authenticity_token, :only => [:training_task_status]
before_filter :require_login, :except => [:training_task_status]
before_filter :find_myshixun, :only => [:show]
skip_before_filter :verify_authenticity_token, :only => [:training_task_status, :close_webssh]
before_filter :require_login, :except => [:training_task_status, :close_webssh]
before_filter :check_authentication, :except => [:training_task_status, :close_webssh]
before_filter :find_myshixun, :only => [:show, :myshixun_reset, :open_webssh]
include ApplicationHelper
# 将代码重置到开启状态
# 方法使用文件更新非Git重置
def code_reset
end
def code_reset_success
end
# 连接webssh
def open_webssh
username = Redmine::Configuration['webssh_username']
password = Redmine::Configuration['webssh_password']
begin
shixun_tomcat = Redmine::Configuration['shixun_tomcat']
uri = "#{shixun_tomcat}/bridge/webssh/getConnectInfo"
user_id = User.current.id
params = {tpiID:@myshixun.id, operationEnvironment:@myshixun.shixun.try(:language)}
res = uri_exec uri, params
if res && res['code'].to_i != 0
raise("实训云平台繁忙繁忙等级92")
end
render :json => {:host => res['address'], :port => res['port'], :username => username, :password => password, :game_id => @myshixun.id}
rescue Exception => e
logger.error(e)
render :json => {:error => e.try(:message)}
# @message = e.try(:message)
end
end
# 断开webssh连接
def close_webssh
username = Redmine::Configuration['webssh_username']
password = Redmine::Configuration['webssh_password']
begin
shixun_tomcat = Redmine::Configuration['shixun_tomcat']
uri = "#{shixun_tomcat}/bridge/webssh/deleteSSH"
user_id = User.current.id
logger.info("#############################")
logger.info("game_id:" + @_params[:id])
params = {tpiID:@_params[:id]} # @_params[:id] 是webssh传过来的gameId
res = uri_exec uri, params
if res && res['code'].to_i != 0
raise("实训云平台繁忙繁忙等级93")
end
render :jsonp => {:host => res['address'], :port => res['port'], :username => username, :password => password}
rescue Exception => e
logger.error(e)
@message = e.try(:message)
end
end
# 实训重置只更新脚本
def myshixun_reset
ActiveRecord::Base.transaction do
begin
g = Gitlab.client
shixun_tomcat = Redmine::Configuration['shixun_tomcat']
shixun = @myshixun.shixun
@challenges = shixun.challenges
# 删除选择题用户记录
unless @challenges.blank?
@challenges.each do |challenge|
if challenge.st != 0
challenge.challenge_chooses.each do |choose|
user_output = choose.choose_outputs
unless user_output.blank?
user_output.delete
end
end
end
end
end
#end
myshixun_job = Base64.urlsafe_encode64("myshixun_#{@myshixun.id}")
StudentWork.where(:myshixun_id => @myshixun.id).update_all(:myshixun_id => nil, :work_status => 0)
@myshixun.destroy
myshixun_member = @myshixun
repository = @myshixun.repository
repository.destroy
g_project = g.project(@myshixun.gpid)
unless g_project.id.nil?
git_rep = g.delete_project(@myshixun.gpid)
logger.info("### delete repository result is #{git_rep}")
if git_rep != true
raise("实训云平台繁忙繁忙等级87")
end
end
redirect_to shixun_exec_shixun_path(shixun, :type => 1, :is_subject => params[:is_subject])
rescue Exception => e
flash[:error] = "实训云平台繁忙繁忙等级89"
g.delete_project(@myshixun.gpid) if !g_project.try(:id).nil?
redirect_to myshixun_path(@myshixun)
logger.error("myshixun reset failed #{e}")
raise ActiveRecord::Rollback
end
end
end
# taskId 即返回的game id
# params [:stauts] 0 表示成功,其它则失败
# 返回结果:params [:stauts] 0 表示成功,其它则失败
# msg 错误信息
# output 为测试用户编译输出结果
# myshixun:status 1为完成实训
# @jenkins: caseId对应test_set的positionpassed: 1表示成功0表示失败
# resubmit 1表示已通关后重新评测0表示非重新评测
# retry_status 0初始值1重新评测失败2重新评测成功
def training_task_status
status = params[:status].to_i
task_id = params[:taskId]
outPut = Base64.decode64(params[:outPut]) unless params[:outPut].blank?
message = Base64.decode64(params[:msg]) unless params[:msg].blank?
game = Game.find(task_id)
#params[:jsonTestDetails] = '{"buildID":"1","compileSuccess":"1","msg":[{"caseId":"1","expectedOutput":"56ysMOS9jeWQjOWtpueahOaAu+WIhuS4ujoyNDcK56ysMeS9jeWQjOWtpueahOaAu+WIhuS4ujoz MjIK","input":"Mg0KMjMsNTYsNzgsOTANCjIxLDU2LDc4LDc2LDkx","output":"56ysMOS9jeWQjOWtpueahOaAu+WIhuS4ujoyNDcK56ysMeS9jeWQjOWtpueahOaAu+WIhuS4ujoz MjIK","passed":"1"},{"caseId":"2","expectedOutput":"56ysMOS9jeWQjOWtpueahOaAu+WIhuS4ujoyMjgK56ysMeS9jeWQjOWtpueahOaAu+WIhuS4ujoy MzUK56ysMuS9jeWQjOWtpueahOaAu+WIhuS4ujoyMDYK","input":"Mw0KOTgsNzYsNTQNCjkwLDU0LDg3LDQNCjc4LDI2LDEyLDkw","output":"56ysMOS9jeWQjOWtpueahOaAu+WIhuS4ujoyMjgK56ysMeS9jeWQjOWtpueahOaAu+WIhuS4ujoy MzUK56ysMuS9jeWQjOWtpueahOaAu+WIhuS4ujoyMDYK","passed":"1"}],"outPut":"Y29tcGlsZSBzdWNjZXNzZnVsbHk","resubmit":"57D9COBR_5806","status":"0"}'
jsonTestDetails = JSON.parse(params[:jsonTestDetails])
status = jsonTestDetails['status']
game_id = jsonTestDetails['buildID']
resubmit = jsonTestDetails['resubmit']
outPut = tran_base64_decode64(jsonTestDetails['outPut'])
jenkins_testsets = jsonTestDetails['msg']
compile_success = jsonTestDetails['compileSuccess']
# message = Base64.decode64(params[:msg]) unless params[:msg].blank?
logger.info(outPut)
game = Game.find(game_id)
challenge = game.challenge
if status == 0
myshixun = game.myshixun
games_count = myshixun.games.count
if challenge.position == games_count
myshixun.update_attribute(:status, 1)
unless jenkins_testsets.blank?
jenkins_testsets.each do |j_test_set|
logger.info("j_test_set: ############## #{j_test_set['output']}")
actual_output = tran_base64_decode64(j_test_set['output'])
logger.info "actual_output:################################################# #{actual_output}"
game_outputs = Output.create(:code => status, :game_id => game_id, :out_put => outPut, :test_set_position => j_test_set['caseId'],
:actual_output => actual_output, :result => j_test_set['passed'].to_i, :query_index => game.query_index, :compile_success => compile_success.to_i)
# output = Output.where(:game_id => game.id, :test_set_position => j_test_set['caseId'].to_i).first
# logger.info("#############{outPut}")
# if output.nil?
# game_outputs = Output.create(:code => status, :game_id => game_id, :out_put => outPut, :test_set_position => j_test_set['caseId'],
# :actual_output => actual_output, :result => j_test_set['passed'].to_i)
# else
# output.update_attributes(:code => status, :out_put => outPut, :actual_output => actual_output, :result => j_test_set['passed'].to_i)
# end
end
end
if status == "0"
if !resubmit.blank?
game.update_attributes(:retry_status => 2, :resubmit_identifier => resubmit)
else
game.update_attributes(:status => 2, :end_time => Time.now)
unless game.answer_open? # 如果没有查看答案,则获得该关卡得分
game.update_attribute(:final_score, challenge.score)
end
end
else # status == "-1" 表示返回结果错误
if !resubmit.blank?
game.update_attributes(:retry_status => 1, :resubmit_identifier => resubmit)
else
game.update_attribute(:status, 0)
end
game_outputs = Output.create(:code => status, :msg => message, :game_id => task_id, :out_put => outPut)
game.update_attribute(:status, 2)
game.update_attribute(:final_score, challenge.score)
else
game_outputs = Output.create(:code => status, :msg => message, :game_id => task_id, :out_put => outPut)
game.update_attribute(:status, 0)
end
render :json => {:data => "success"}
end
@ -41,7 +175,7 @@ class MyshixunsController < ApplicationController
private
# Find myshixun of id params[:id]
def find_myshixun
@myshixun = Myshixun.find(params[:id])
@myshixun = Myshixun.find_by_identifier(params[:id])
rescue ActiveRecord::RecordNotFound
render_404
end

View File

@ -17,13 +17,24 @@ class PraiseTreadController < ApplicationController
end
# @is_in_list = nil
@obj = find_object_by_type_and_id(@obj_type,@obj_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?
pts = PraiseTread.where("praise_tread_object_id=? and praise_tread_object_type=? and user_id=?", @obj_id, @obj_type.to_s, User.current.id).first
unless pts.blank?
if(params[:game_praise] == "true")
pts.delete
if params[:obj_type] == "Challenge"
praise_tread_count = PraiseTread.where(:praise_tread_object_id => @obj_id, :praise_tread_object_type => "Challenge").count
else
praise_tread_count = PraiseTread.where(:praise_tread_object_id =>@obj_id, :praise_tread_object_type => "ChallengeTread").count
end
render :json => {praise: false, praise_tread_count: praise_tread_count}
return
end
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
@ -33,6 +44,15 @@ class PraiseTreadController < ApplicationController
# unless author_id == User.current.id
praise_tread_plus(@obj_type,@obj_id,1)
# end
if params[:game_praise] == "true"
if params[:obj_type] == "Challenge"
praise_tread_count = PraiseTread.where(:praise_tread_object_id => @obj_id, :praise_tread_object_type => "Challenge").count
else
praise_tread_count = PraiseTread.where(:praise_tread_object_id => @obj_id, :praise_tread_object_type => "ChallengeTread").count
end
render :json => {praise: true, praise_tread_count: praise_tread_count}
return
end
respond_to do |format|
format.js
end
@ -137,6 +157,10 @@ class PraiseTreadController < ApplicationController
@obj = Syllabus.find_by_id(id)
when 'Work'
@obj = Work.find_by_id(id)
when 'Challenge' || 'ChallengeTread'
@obj = Challenge.find_by_id(id)
when 'Discuss'
@obj = Discuss.find_by_id(id)
else
@obj = nil
end

View File

@ -929,10 +929,10 @@ class ProjectsController < ApplicationController
end
end
def uri_exec uri, params
res = Net::HTTP.post_form(uri, params).body
res = JSON.parse(res)
end
# def uri_exec uri, params
# # res = Net::HTTP.post_form(uri, params).body
# # res = JSON.parse(res)
# end
# 开启实训项目,学生会fork一个项目并自动发送任务
def training_project_extend

View File

@ -36,17 +36,17 @@ class RepositoriesController < ApplicationController
before_filter :find_repository, :only => [:edit, :update, :destroy, :committers]
before_filter :find_project_repository, :except => [:commits, :shixun_show, :new, :create, :newcreate, :edit, :update, :destroy, :committers,
:newrepo, :to_gitlab, :forked, :export_rep_static, :training_project_extend, :shixun_entry]
:newrepo, :to_gitlab, :forked, :export_rep_static, :training_project_extend, :shixun_entry, :shixun_commit_diff]
# 实训项目新增
before_filter :find_project_and_repository, :only => [:commits, :shixun_show, :shixun_entry]
before_filter :find_project_and_repository, :only => [:commits, :shixun_show, :shixun_entry, :shixun_commit_diff]
# 连接gitlab
# before_filter :connect_gitlab, :only => [:quality_analysis, :commit_diff]
before_filter :find_changeset, :only => [:revision, :add_related_issue, :remove_related_issue]
# before_filter :authorize , :except => [:newrepo,:newcreate,:fork, :to_gitlab, :forked, :project_archive, :quality_analysis, :commit_diff]
before_filter :authorize_visible , :except => [:shixun_show, :newrepo,:newcreate,:fork, :to_gitlab, :forked, :project_archive, :quality_analysis, :commit_diff]
before_filter :authorize_visible , :except => [:shixun_show, :newrepo,:newcreate,:fork, :to_gitlab, :forked, :project_archive, :quality_analysis, :commit_diff, :shixun_commit_diff]
# 版本库新增权限
# before_filter :show_rep, :only => [:show, :stats, :revisions, :revision, :diff, :commit_diff ]
accept_rss_auth :revisions
@ -524,14 +524,14 @@ update
def shixun_show
# 顶部导航
@project_menu_type = 5
@entries = @repository.entries(@path, @rev)
@entries = @repository.entries(@path, @rev) # Repository::Gitlab
if request.xhr?
@entries ? render(:partial => 'dir_list_content') : render(:nothing => true)
else
@changesets_latest_coimmit = @g.rep_last_changes(@shixun.gpid, :rev => @rev, :path => @path)
# @g.rep_last_changes(@project.gpid, :rev => @rev, :path => @path)
# 总的提交数
@changesets_all_count = @g.user_static(@shixun.gpid, :rev => @rev).count
@changesets_all_count = @g.user_static(@shixun.gpid, :rev => @rev).count.to_i
# 获取默认分支
@g_default_branch = @g_project.default_branch.nil? ? "master" : @g_project.default_branch
@ -543,10 +543,14 @@ update
# token值解密
# gitlab_token = aes_dicrypt("priEn3UwXfJs3Pmy", token)
@zip_path = Gitlab.endpoint.to_s + "/projects/" + @shixun.gpid.to_s + "/repository/archive?&private_token=" + token
@creator = @shixun.owner.to_s
if @shixun.fork_from.present?
login = User.find_by_mail("eduforge@163.com").try(:login)
else
login = User.find_by_mail("educoder@163.com").try(:login)
end
gitlab_address = Redmine::Configuration['gitlab_address']
@repos_url = gitlab_address.to_s+"/" + @creator + "/" + @repository.identifier+"."+"git"
@repos_url = git_shixun_url(@shixun, login)
# @repos_url = gitlab_address.to_s+"/" + @creator + "/" + @repository.identifier+"."+"git"
# 提交总数同步更新
@shixun.update_attribute(:changeset_num, @changesets_all_count)
@ -619,11 +623,15 @@ update
@project_menu_type = 5
@entry = @repository.entry(@path, @rev)
(show_error_not_found; return) unless @entry
limit = 10
limit = 15
# 每次页面的换回值从1开始,但是gitlab的页面查询是从0开始,所以先改变page的类型减一在改回来
@commits = @g.commits(@shixun.gpid, page:(params[:page].to_i - 1).to_s, ref_name:@rev)
@commits_count = params[:commit_count].nil? ? @g.user_static(@shixun.gpid, :rev => @rev).count : params[:commit_count].to_i
@commits_pages = Paginator.new @commits_count, limit, params[:page]
# @commits_pages = Paginator.new @commits_count, limit, params[:page]
@commits_pages = Paginator.new @commits_count, limit, params['page'] || 1
@offset ||= @commits_pages.offset
@commits = paginateHelperForGitlab @commits, limit
render :layout => 'base_shixun'
end
@ -687,7 +695,7 @@ update
# 顶部导航
@project_menu_type = 5
entry_and_raw(false)
# entry_and_raw(false)
@content = @repository.cat(@path, @rev)
# @changesets_latest_coimmit = @g.commit(@project.gpid, @entry.try(:lastrev))
@changesets_latest_coimmit = @g.rep_last_changes(@shixun.gpid, :rev => @rev, :path => @path)
@ -797,6 +805,17 @@ update
render :layout => 'base_projects'
end
def shixun_commit_diff
@commit_diff = @g.commit_diff(@shixun.gpid, params[:changeset_id])
diff = ActiveSupport::JSON.decode(@commit_diff.to_json).first
diff = OpenStruct.new(diff)
@diff_file = Trustie::Gitlab::Diff::File.new(diff)
# @commit_details = @g.commit(@project.gpid, params[:changeset])
render :layout => 'base_shixun'
end
# 实训项目
# 每次提交对应的文件差异
def commit
@ -900,7 +919,7 @@ update
end
def find_project_and_repository
@shixun = Shixun.find(params[:id])
@shixun = Shixun.find_by_identifier(params[:id])
@repository = @shixun.repository
render_404 if @shixun.gpid.nil?
@path = params[:path].is_a?(Array) ? params[:path].join('/') : params[:path].to_s
@ -918,6 +937,7 @@ update
end
rescue ActiveRecord::RecordNotFound
render_404
return
rescue InvalidRevisionParam
show_error_not_found
end

View File

@ -1,285 +1,317 @@
class SchoolController < ApplicationController
layout 'course_base'
before_filter :require_admin, :only => :upload_logo
def upload
uploaded_io = params[:logo]
school_id ||= params[:id]
s1 = School.find(school_id)
unless uploaded_io.nil?
File.open(Rails.root.join('public', 'images', 'school', school_id.to_s+'.png'), 'wb') do |file|
file.write(uploaded_io.read)
end
s1.logo_link = '/images/school/'+school_id.to_s+'.png'
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])
end
def upload_logo
@school = School.find params[:id]
@school_name = params[:school_name]
end
#获取制定学校开设的课程数
def course_count school_id
School.find(school_id).courses.count
end
def index
end
def get_province
@provinces = School.find_by_sql("select distinct province from schools")
options = ""
@provinces.each do |p|
options << "<option value = '#{p.province}' >#{p.province}</option>"
end
# 取id取学校名
# 连接子表: 查询已添加用户的学校
school = School.select("id, name").
joins("RIGHT JOIN (
SELECT DISTINCT school_id
FROM #{UserExtensions.table_name}
WHERE school_id IS NOT NULL) AS sids ON schools.id = sids.school_id").
where("#{School.table_name}.id IS NOT NULL")
options_s = ""
school.each do |s|
options_s << "<li style = 'width: 33%; float: left'><a style='cursor: pointer;' id=#{s.id} onclick='test(this.id, this.text)'>#{s.name}</a></li>"
end
res = Hash.new
res[:text] = options
res[:text_s] = options_s
render :json => res
end
def get_options
@school = School.where("province = ?", params[:province])
p = params[:province]
##@school = School.all
options = ""
@school.each do |s|
#options << "<option value=#{s.id}>#{s.name}</option>"
options << "<li style = 'width: 33%; float: left'><a style='cursor: pointer;' id=#{s.id} onclick='test(this.id, this.text)'>#{s.name}</a></li>"
end
render :text => options
end
def get_schoollist
@school = School.where("province = ?", params[:province])
options = ""
@school.each do |s|
options << "<li style = 'width: 33%; float: left'><a style='cursor: pointer;' id=#{s.id} onclick='test(this.id)'>#{s.name}</a></li>"
end
render :text => options
end
def search_school
q = "%#{params[:key_word].strip}%"
@school = School.where("name LIKE ?", q)
@school = @school.where("province = ?", params[:province]) if (params[:province] != '0' )
options = ""
@school.each do |s|
options << "<li style = 'width: 33%; float: left'> <a style='cursor: pointer;' id=#{s.id} onclick='test(this.id)'>#{s.name}</a></li>"
end
options = "<div class='flash error' id='flash_error'>#{l(:label_school_not_fount)}</div>" if options.blank?
render :text => options
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
#申请高校(单位) name:名称 province:省 city:市 address:地址 remarks:备注
def apply_add_school
data = {result:0,name:params[:name],school_id:0}
#0 成功 1参数错误 2名称已存在 3.失败
data[:result] = 0
#检验参数
if params[:name] == "" || params[:province] == "" || params[:city] == "" || params[:address] == ""
data[:result] = 1
else
school = School.where("name = '#{params[:name]}'").first
if school
data[:result] = 2
else
school = School.new
school.name = params[:name].strip
school.pinyin = Pinyin.t(params[:name].strip, splitter: '')
school.province = params[:province]
#status 0未处理 1通过 2拒绝
applyschool = ApplyAddSchools.new
#用belongs_to 可以一起存数据库
applyschool.school = school
applyschool.name = school.name
applyschool.province = params[:province]
applyschool.city = params[:city]
applyschool.address = params[:address]
applyschool.remarks = params[:remarks]
applyschool.user_id = User.current.id
if applyschool.save
data[:school_id] = school.id
user_extention= User.current.extensions
user_extention.school_id = school.id
user_extention.save!
# 向管理员发送信息
users = User.where(:admin => 1)
users.each do |user|
AppliedMessage.create(:user_id => user.id, :status => 0, :applied_user_id => User.current.id, :viewed => 0, :applied_id => school.id, :applied_type => "ApplyAddSchools", :name => school.name )
end
else
data[:result] = 3
end
end
end
render :json =>data
end
def search_repeat_schoolname
status = 0 #没有重复的
name = params[:name]
if name
school = School.where("name = '#{name}'").first
if school
status = 1 #有重复的
end
end
render :json =>status
end
def edit_apply_name
name = params[:name] || ""
status = -1
if name != ""
applyschool = ApplyAddSchools.where("id=?",params[:id]).first
applyschool.name = name.strip
if applyschool.school
applyschool.school.name = name
applyschool.school.pinyin = Pinyin.t(name.strip, splitter: '')
applyschool.school.save!
end
applyschool.save!
status = 0
end
render :json=>{:status=>status,:id=>params[:id],:name=>name}
end
def edit_apply_address
address = params[:address] || ""
status = -1
if address != ""
applyschool = ApplyAddSchools.where("id=?",params[:id]).first
applyschool.address = address
applyschool.save!
status = 0
end
render :json=>{:status=>status,:id=>params[:id],:address=>address}
end
def edit_apply_province
province = params[:province] || ""
city = params[:city] || ""
status = -1
if(province != "") &&(city != "")
applyschool = ApplyAddSchools.where("id=?",params[:id]).first
applyschool.province = province
applyschool.city = city
if applyschool.school
applyschool.school.province = province
applyschool.school.save!
end
applyschool.save!
if applyschool.user_id && applyschool.user_id != 0
user = User.find(applyschool.user_id)
user_extention= user.extensions
user_extention.location = province
user_extention.location_city = city
user_extention.save!
end
status = 0
end
render :json=>{:status=>status,:id=>params[:id],:province=>province,:city=>city}
end
end
class SchoolController < ApplicationController
layout 'course_base'
before_filter :require_admin, :only => :upload_logo
before_filter :find_school, :only => [:destroy]
def upload
uploaded_io = params[:logo]
school_id ||= params[:id]
s1 = School.find(school_id)
unless uploaded_io.nil?
File.open(Rails.root.join('public', 'images', 'school', school_id.to_s+'.png'), 'wb') do |file|
file.write(uploaded_io.read)
end
s1.logo_link = '/images/school/'+school_id.to_s+'.png'
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])
end
def upload_logo
@school = School.find params[:id]
@school_name = params[:school_name]
render :layout => "base_management"
end
#获取制定学校开设的课程数
def course_count school_id
School.find(school_id).courses.count
end
def index
render :layout => "base_management"
end
def get_province
@provinces = School.find_by_sql("select distinct province from schools")
options = ""
@provinces.each do |p|
options << "<option value = '#{p.province}' >#{p.province}</option>"
end
# 取id取学校名
# 连接子表: 查询已添加用户的学校
school = School.select("id, name").
joins("RIGHT JOIN (
SELECT DISTINCT school_id
FROM #{UserExtensions.table_name}
WHERE school_id IS NOT NULL) AS sids ON schools.id = sids.school_id").
where("#{School.table_name}.id IS NOT NULL")
options_s = ""
school.each do |s|
options_s << "<li style = 'width: 33%; float: left'><a style='cursor: pointer;' id=#{s.id} onclick='test(this.id, this.text)'>#{s.name}</a></li>"
end
res = Hash.new
res[:text] = options
res[:text_s] = options_s
render :json => res
end
def get_options
@school = School.where("province = ?", params[:province])
p = params[:province]
##@school = School.all
options = ""
@school.each do |s|
#options << "<option value=#{s.id}>#{s.name}</option>"
options << "<li style = 'width: 33%; float: left'><a style='cursor: pointer;' id=#{s.id} onclick='test(this.id, this.text)'>#{s.name}</a></li>"
end
render :text => options
end
def get_schoollist
@school = School.where("province = ?", params[:province])
options = ""
@school.each do |s|
options << "<li style = 'width: 33%; float: left'><a style='cursor: pointer;' id=#{s.id} onclick='test(this.id)'>#{s.name}</a></li>"
end
render :text => options
end
def search_school
q = "%#{params[:key_word].strip}%"
@school = School.where("name LIKE ?", q)
@school = @school.where("province = ?", params[:province]) if (params[:province] != '0' )
options = ""
@school.each do |s|
options << "<li style = 'width: 33%; float: left'> <a style='cursor: pointer;' id=#{s.id} onclick='test(this.id)'>#{s.name}</a></li>"
end
options = "<div class='flash error' id='flash_error'>#{l(:label_school_not_fount)}</div>" if options.blank?
render :text => options
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 params[:no_school_ids]
if(condition == '')
@school = School.where("id not in #{params[:no_school_ids]}").reorder('pinyin').page((params[:page].to_i || 1) - 1).per(100)
@school_count = School.count
else
@school = School.where("id not in #{params[:no_school_ids]} and name like '%#{chinese.join("")}%' and pinyin like '%#{pinyin.join("")}%'").reorder('pinyin').page((params[:page].to_i || 1) - 1).per(100)
@school_count = School.where("id not in #{params[:no_school_ids]} and name like '%#{chinese.join("")}%' and pinyin like '%#{pinyin.join("")}%'").count
end
else
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
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
#申请高校(单位) name:名称 province:省 city:市 address:地址 remarks:备注
def apply_add_school
data = {result:0,name:params[:name],school_id:0}
#0 成功 1参数错误 2名称已存在 3.失败
data[:result] = 0
#检验参数
if params[:name] == "" || params[:province] == "" || params[:city] == "" || params[:address] == ""
data[:result] = 1
else
school = School.where("name = '#{params[:name]}'").first
if school
data[:result] = 2
else
school = School.new
school.name = params[:name].strip
school.pinyin = Pinyin.t(params[:name].strip, splitter: '')
school.province = params[:province]
school.city = params[:city]
school.address = params[:address]
#status 0未处理 1通过 2拒绝
applyschool = ApplyAddSchools.new
#用belongs_to 可以一起存数据库
applyschool.school = school
applyschool.name = school.name
applyschool.province = params[:province]
applyschool.city = params[:city]
applyschool.address = params[:address]
applyschool.remarks = params[:remarks]
applyschool.user_id = User.current.id
if applyschool.save
data[:school_id] = school.id
user_extention= User.current.extensions
user_extention.school_id = school.id
user_extention.save!
# 向管理员发送信息
users = User.where(:admin => 1)
users.each do |user|
AppliedMessage.create(:user_id => user.id, :status => 0, :applied_user_id => User.current.id, :viewed => 0, :applied_id => school.id, :applied_type => "ApplyAddSchools", :name => school.name )
end
else
data[:result] = 3
end
end
end
render :json =>data
end
def search_repeat_schoolname
status = 0 #没有重复的
name = params[:name]
if name
school = School.where("name = '#{name}'").first
if school
status = 1 #有重复的
end
end
render :json =>status
end
def edit_apply_name
name = params[:name] || ""
status = -1
if name != ""
applyschool = ApplyAddSchools.where("id=?",params[:id]).first
applyschool.name = name.strip
if applyschool.school
applyschool.school.name = name
applyschool.school.pinyin = Pinyin.t(name.strip, splitter: '')
applyschool.school.save!
end
applyschool.save!
status = 0
end
render :json=>{:status=>status,:id=>params[:id],:name=>name}
end
def edit_apply_address
address = params[:address] || ""
status = -1
if address != ""
applyschool = ApplyAddSchools.where("id=?",params[:id]).first
applyschool.address = address
applyschool.save!
status = 0
end
render :json=>{:status=>status,:id=>params[:id],:address=>address}
end
def edit_apply_province
province = params[:province] || ""
city = params[:city] || ""
status = -1
if(province != "") &&(city != "")
applyschool = ApplyAddSchools.where("id=?",params[:id]).first
applyschool.province = province
applyschool.city = city
if applyschool.school
applyschool.school.province = province
applyschool.school.save!
end
applyschool.save!
if applyschool.user_id && applyschool.user_id != 0
user = User.find(applyschool.user_id)
user_extention= user.extensions
user_extention.location = province
user_extention.location_city = city
user_extention.save!
end
status = 0
end
render :json=>{:status=>status,:id=>params[:id],:province=>province,:city=>city}
end
def destroy
if @school
if UserExtensions.where(:school_id => @school.id).count == 0
School.where(:id=>@school.id).destroy_all
@school.destroy
end
respond_to do |format|
format.js
end
end
end
private
def find_school
@school = School.find params[:id]
rescue ActiveRecord::RecordNotFound
render_404
end
end

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,85 @@
class StagesController < ApplicationController
before_filter :check_authentication
before_filter :find_subject, :only => [ :create]
before_filter :find_stage, :only => [:edit, :update, :destroy]
include ApplicationHelper
def create
if params[:stage_name]
stage = Stage.new
stage.name = params[:stage_name]
stage.description = params[:stage_des]
stage.subject_id = @subject.id
stage.user_id = User.current.id
stage.position = @subject.stages.count + 1
ActiveRecord::Base.transaction do
if stage.save && params[:shixun_id]
begin
params[:shixun_id].each do |shixun_id|
shixun = Shixun.find shixun_id
stage.stage_shixuns << StageShixun.new(:subject_id => @subject.id, :shixun_id => shixun_id, :position => stage.stage_shixuns.count + 1) if shixun
end
rescue Exception => e
end
end
end
redirect_to subject_path(@subject)
end
end
def edit
respond_to do |format|
format.js
end
end
def update
if params[:stage_name]
@stage.name = params[:stage_name]
@stage.description = params[:stage_des]
ActiveRecord::Base.transaction do
if @stage.save
begin
@stage.stage_shixuns.destroy_all
params[:shixun_id].each do |shixun_id|
shixun = Shixun.find shixun_id
@stage.stage_shixuns << StageShixun.new(:subject_id => @subject.id, :shixun_id => shixun_id, :position => @stage.stage_shixuns.count + 1) if shixun
end
rescue Exception => e
end
end
end
redirect_to subject_path(@subject)
end
end
def destroy
if User.current.manager_of_subject?(@subject)
@subject.stages.where("position > #{@stage.position}").update_all("position = position - 1")
@stage.destroy
@status = 1
else
@status = 0
end
end
private
def find_subject
@subject = Subject.find_by_id(params[:subject])
if @subject.nil?
render_404
return
end
rescue ActiveRecord::RecordNotFound
render_404
end
def find_stage
@stage = Stage.find(params[:id])
@subject = @stage.subject
rescue ActiveRecord::RecordNotFound
render_404
end
end

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,157 @@
# encoding: utf-8
class SubjectsController < ApplicationController
layout 'base_subject'
before_filter :require_login
before_filter :check_authentication
before_filter :find_subject, :except => [:index, :new, :create, :create_subject, :new_subject, :append_to_stage]
include ApplicationHelper
include SubjectsHelper
def index
@order = params[:order] || "myshixun_count"
bsort = params[:sort] || "desc"
@sort = bsort == "desc" ? "asc" : "desc"
search = params[:search]
#ids = Subject.find_by_sql("select group_concat(id) as allId from subjects where id in (SELECT distinct(subject_id) FROM `stages`)")
if @order == "myshixun_count"
#@shixuns = @shixuns.select("shixuns.*, (select count(myshixuns.id) from myshixuns where myshixuns.shixun_id = shixuns.id group by shixuns.id) AS myshixunCount").reorder("status = 2 desc, myshixunCount desc")
@subjects = Subject.where("hidden = 0").select("subjects.*, (select count(myshixuns.id) from myshixuns, stage_shixuns where myshixuns.shixun_id = stage_shixuns.shixun_id and stage_shixuns.subject_id = subjects.id group by subjects.id) AS myshixunCount").reorder("status = 2 desc, myshixunCount #{bsort}")
else
@subjects = Subject.where("hidden = 0").reorder("#{@order} #{bsort}")
end
@subject_created_count = Subject.where(:user_id => User.current.id).count
@subjects_all_count = @subjects.count
#@subjects = Subject.where("name like ?", "%#{search}%").reorder("#{@order} #{@sort}")
@subjects_count = @subjects.count
@limit = 16
@is_remote = true
@subject_pages = Paginator.new @subjects_count, @limit, params['page'] || 1
@offset ||= @subject_pages.offset
@subjects = paginateHelper @subjects, @limit
render :layout => "base_edu"
end
def show
@stages = @subject.stages
@is_manager = User.current.manager_of_subject?(@subject)
end
def new
@subject = Subject.new
render :layout => "base_edu"
end
def create
if params[:subject]
subject = Subject.create(:name => params[:subject][:name], :learning_notes => params[:subject][:learning_notes], :description => params[:subject][:description], :user_id => User.current.id, :visits => 0, :status => 0)
end
redirect_to subject_path(subject)
end
def edit
render :layout => "base_edu"
end
def update
if params[:subject]
subject = @subject.update_attributes(:name => params[:subject][:name], :learning_notes => params[:subject][:learning_notes], :description => params[:subject][:description])
end
redirect_to subject_path(@subject)
end
def update_attr
if params[:name]
@subject.update_attributes(:name => params[:name])
elsif params[:description]
@subject.update_attributes(:description => params[:description])
end
end
def new_subject
if Course.where(:tea_id => User.current.id).count > 0
@status = 1
@course_lists = CourseList.where(:id => ShixunMajorCourse.where(:shixun_id => Shixun.where(:user_id => User.current.id).map(&:id)).map(&:course_list_id))
else
@status = 0
end
respond_to do |format|
format.js
end
end
def create_subject
if params[:course_list_id]
course = CourseList.find params[:course_list_id]
if course
subject = Subject.create(:name => course.name, :user_id => User.current.id, :visits => 0, :status => 0, :course_list_id => course.id)
end
end
redirect_to subject_path(subject)
end
def choose_subject_shixun
#course_list = @subject.course_list
@shixuns = User.current.shixuns.where(:status => [0, 1, 2]).reorder("created_at desc")
#@shixuns = Shixun.where(:user_id => User.current.id, :status => [0, 1, 2], :id => course_list.shixun_major_courses.map(&:shixun_id))
@shixuns_count = @shixuns.count
@limit = 8
@shixuns_pages = Paginator.new @shixuns_count, @limit, params['page'] || 1
@offset ||= @shixuns_pages.offset
@shixuns = paginateHelper @shixuns, @limit
end
def append_to_stage
@shixuns = Shixun.where(:id => params[:choose_ids].split(",")).reorder("id desc")
end
def publish
apply = ApplyAction.where(:container_type => "ApplySubject", :container_id => @subject.id).order("created_at desc").first
if apply && apply.status == 0
@status = 0
else
#if Shixun.where(:id => @subject.stage_shixuns.map(&:shixun_id), :status => [0, 1]).count > 0
# @status = 2
#else
@subject.update_attributes(:status => 1)
ApplyAction.create(:container_type => "ApplySubject", :container_id => @subject.id, :user_id => User.current.id, :status => 0)
notes = User.current.show_name.to_s + " 申请发布课程实训:<a href='#{subject_path(@subject)}'>#{@subject.name}</a>"
JournalsForMessage.create(:jour_id => 1, :jour_type => 'Principal', :user_id => User.current.id, :notes => notes, :private => 1, :reply_id => 0)
@status = 1
# end
end
end
def cancel_publish
apply = ApplyAction.where(:container_type => "ApplySubject", :container_id => @subject.id).order("created_at desc").first
if apply && apply.status == 0
apply.update_attributes(:status => 3)
end
@subject.update_attributes(:status => 0)
redirect_to subject_path(@subject)
end
def cancel_has_publish
@subject.update_attributes(:status => 0)
redirect_to subject_path(@subject)
end
def destroy
if @subject
ApplyAction.where(:container_type => "ApplySubject", :container_id => @subject.id).destroy_all
@subject.destroy
respond_to do |format|
format.js
end
end
end
private
# Find subject of id params[:id]
def find_subject
@subject = Subject.find_by_id(params[:id])
render_404 if @subject.nil?
rescue ActiveRecord::RecordNotFound
render_404
end
end

View File

@ -1,7 +1,9 @@
class SyllabusMemberController < ApplicationController
before_filter :find_syllabus, :only => [:syl_member_autocomplete, :create, :change_manager, :change_manager_alert]
before_filter :find_syllabus_member, :only => [:destroy, :update_rank]
def syl_member_autocomplete
@syllabus = Syllabus.find(params[:syllabus])
@flag = params[:flag] || false
respond_to do |format|
format.js
@ -9,11 +11,10 @@ class SyllabusMemberController < ApplicationController
end
def create
@syllabus = Syllabus.find(params[:syllabus])
if params[:membership].nil?
if params[:member_id].nil?
@fail_hint = l(:label_blank_user_lists_for_org)
else
member_ids = params[:membership][:user_ids]
member_ids = params[:member_id]
last_rank = @syllabus.syllabus_members.order("rank asc").last.rank
user_ids = @syllabus.syllabus_members.map{|sy| sy.user_id}
member_ids.each_with_index do |user_id, i|
@ -22,37 +23,53 @@ class SyllabusMemberController < ApplicationController
@syllabus.syllabus_members << member
end
end
@members = @syllabus.syllabus_members.order("rank asc")
@members = @syllabus.syllabus_members.includes(:user => {:user_extensions => []}).order("rank asc")
@is_syllabus_member = User.current.admin? || @syllabus.syllabus_members.map{|sm| sm.user_id}.include?(User.current.id)
end
respond_to do |format|
format.js
end
end
def change_manager_alert
@members = @syllabus.syllabus_members.where("id != #{@syllabus.user_id}")
end
def change_manager
if params[:chooseteacher]
man_member = SyllabusMember.where(:syllabus_id => @syllabus.id, :user_id => @syllabus.user_id).first
cha_member = @syllabus.syllabus_members.where(:id => params[:chooseteacher].to_i).first
if man_member && cha_member
man_member.update_attributes(:rank => cha_member.rank)
cha_member.update_attributes(:rank => 1)
@syllabus.update_attributes(:user_id => cha_member.user_id)
end
end
@members = @syllabus.syllabus_members.includes(:user => {:user_extensions => []}).order("rank asc")
@is_syllabus_member = User.current.admin? || @syllabus.syllabus_members.map{|sm| sm.user_id}.include?(User.current.id)
end
def destroy
member = SyllabusMember.find(params[:id])
@syllabus = member.syllabus
after_syl_members = @syllabus.syllabus_members.where("rank > #{member.rank}")
after_syl_members = @syllabus.syllabus_members.where("rank > #{@member.rank}")
after_syl_members.update_all("rank = rank - 1")
member.destroy
@members = @syllabus.syllabus_members.order("rank asc")
@member.destroy
@members = @syllabus.syllabus_members.includes(:user => {:user_extensions => []}).order("rank asc")
@is_syllabus_member = User.current.admin? || @syllabus.syllabus_members.map{|sm| sm.user_id}.include?(User.current.id)
respond_to do |format|
format.js
end
end
def update_rank
member = SyllabusMember.find(params[:id])
@syllabus = member.syllabus
members = @syllabus.syllabus_members
if params[:opr] == 'up' && member.rank > 1
before_mem = members.where("rank = #{member.rank - 1}").first
if before_mem && member.update_attribute('rank', member.rank - 1)
if params[:opr] == 'up' && @member.rank > 1
before_mem = members.where("rank = #{@member.rank - 1}").first
if before_mem && @member.update_attribute('rank', @member.rank - 1)
before_mem.update_attribute('rank', before_mem.rank + 1)
end
elsif params[:opr] == 'down' && member.rank < members.count
after_mem = members.where("rank = #{member.rank + 1}").first
if after_mem && member.update_attribute('rank', member.rank + 1)
elsif params[:opr] == 'down' && @member.rank < members.count
after_mem = members.where("rank = #{@member.rank + 1}").first
if after_mem && @member.update_attribute('rank', @member.rank + 1)
after_mem.update_attribute('rank', after_mem.rank - 1)
end
end
@ -61,4 +78,14 @@ class SyllabusMemberController < ApplicationController
format.js
end
end
private
def find_syllabus
@syllabus = Syllabus.find params[:syllabus]
end
def find_syllabus_member
@member = SyllabusMember.find(params[:id])
@syllabus = @member.syllabus
end
end

View File

@ -1,42 +1,93 @@
# encoding: utf-8
#encoding: utf-8
class SyllabusesController < ApplicationController
include ApplicationHelper
helper :attachments
include AttachmentsHelper
include CoursesHelper
include SyllabusesHelper
include UsersHelper
before_filter :is_logged, :only => [:index, :show, :edit, :new, :update, :destroy, :delete_syllabus, :syllabus_resources, :syllabus_homeworks]
before_filter :check_authentication
before_filter :find_syllabus, :only => [:show, :edit, :update, :destroy, :syllabus_courselist, :edit_syllabus_eng_name, :edit_syllabus_title, :update_base_info, :delete_syllabus,
:delete_des, :members, :update_des, :edit_ref, :update_ref, :add_sy_member_alert, :search_not_sy_member, :syllabus_resources, :syllabus_homeworks,
:send_homeworks_to_course, :choose_user_course, :send_resources_to_course, :send_r_and_h_to_course]
before_filter :is_logged, :only => [:index, :show, :edit, :new, :update, :destroy, :delete_syllabus]
before_filter :find_syllabus, :only => [:show, :edit, :update, :destroy, :syllabus_courselist, :edit_syllabus_eng_name, :edit_syllabus_title, :update_base_info, :delete_syllabus, :delete_des, :members]
def index
@status = params[:type].nil? ? 1 : params[:type].to_i # 1表示正在进行2表示已结束
@tab = params[:tab].nil? ? 1 : params[:tab].to_i
@my_syllabuses = "我的课堂"
user = User.current
@syllabuses = user.syllabuses
if @status == 1
case @tab
when 2
@courses = user.courses.not_deleted_not_end.order("updated_at desc").select{ |course| user.has_teacher_role(course)}
when 3
@courses = user.courses.not_deleted_not_end.order("updated_at desc").select{ |course| !user.has_teacher_role(course)}
when 1
@courses = user.courses.not_deleted_not_end.order("updated_at desc")
end
else
case @tab
when 2
@courses = user.courses.not_deleted_but_is_end.order("updated_at desc").select{ |course| user.has_teacher_role(course)}
when 3
@courses = user.courses.not_deleted_but_is_end.order("updated_at desc").select{ |course| !user.has_teacher_role(course)}
when 1
@courses = user.courses.not_deleted_but_is_end.order("updated_at desc")
end
end
@limit = 15
@is_remote = true
@courses_count = @courses.count
@courses_pages = Paginator.new @courses_count, @limit, params['page'] || 1
@offset ||= @courses_pages.offset
@courses = paginateHelper @courses, @limit
respond_to do |format|
format.html{ render :layout => 'base_edu'}
format.js
end
end
def show
@is_syllabus_teacher = User.current.admin? || @syllabus.syllabus_members.map{|sm| sm.user_id}.include?(User.current.id) || !@syllabus.courses.not_deleted_not_end.select { |course| User.current.has_teacher_role(course)}.blank?
@is_syllabus_member = !@syllabus.courses.not_deleted_not_end.select { |course| User.current.member_of_course?(course)}.blank?
@is_syllabus_admin = User.current.admin? || @syllabus.syllabus_members.map{|sm| sm.user_id}.include?(User.current.id)
@is_authen_teacher = User.current.authentication && User.current.user_extensions.try(:identity) != 1
@reference_materials = @syllabus.reference_materials
@members = @syllabus.syllabus_members.includes(:user => {:user_extensions => []}).order("rank asc")
@courses = @syllabus.courses.where("is_delete = 0 and is_end = 0").select("courses.*,(SELECT MAX(updated_at) FROM `course_activities` WHERE course_activities.course_id = courses.id) AS ca_update").order("ca_update desc")
@end_courses = @syllabus.courses.where("is_delete = 0 and is_end = 1").select("courses.*,(SELECT MAX(updated_at) FROM `course_activities` WHERE course_activities.course_id = courses.id) AS ca_update").order("ca_update desc")
respond_to do |format|
format.js
format.html{render :layout => 'base_syllabus'}
format.html{render :layout => 'base_edu_syllabus'}
format.api
end
end
def new
@syllabus = Syllabus.new
render :layout => 'new_base'
render :layout => 'base_edu'
end
def create
if User.current.user_extensions.identity
@syllabus = Syllabus.new
@syllabus.title = params[:title]
@syllabus.title = params[:title].to_s.strip
@syllabus.eng_name = params[:eng_name]
@syllabus.user_id = User.current.id
@syllabus.major_level = params[:major_level].to_i
@syllabus.discipline_category_id = params[:discipline_category_id].to_i
@syllabus.first_level_discipline_id = params[:first_level_discipline_id].to_i
@syllabus.major_id = params[:major_id].to_i
@syllabus.syllabus_type = params[:syllabus_type].to_i
@syllabus.description = Message.where("id = 19412").first.nil? ? '' : Message.where("id = 19412").first.content
if @syllabus && @syllabus.save
member = SyllabusMember.create(:user_id => @syllabus.user_id, :rank => 1)
@syllabus.syllabus_members << member
respond_to do |format|
flash[:notice] = l(:notice_successful_create)
#flash[:notice] = l(:notice_successful_create)
format.html {redirect_to syllabus_path(@syllabus)}
format.api { render :action => 'show', :status => :created, :location => url_for(:controller => 'syllabuses', :action => 'show', :id => @syllabus.id) }
end
@ -50,9 +101,219 @@ class SyllabusesController < ApplicationController
end
end
def regex_syllabus_name
data = {result:1}
if params[:syllabus_id]
if User.current.syllabuses.where("id != #{params[:syllabus_id]} and title = '#{params[:name]}'").count > 0
data[:result] = 0
end
else
if Syllabus.where(:user_id => User.current.id, :title => params[:name]).count > 0
data[:result] = 0
end
end
render :json => data
end
def edit
respond_to do |format|
format.html{render :layout => 'base_syllabus'}
format.html{render :layout => 'base_edu'}
end
end
def update
title = @syllabus.title
@syllabus.title = params[:title].to_s.strip
@syllabus.eng_name = params[:eng_name]
@syllabus.major_level = params[:major_level].to_i
@syllabus.discipline_category_id = params[:discipline_category_id].to_i
@syllabus.first_level_discipline_id = params[:first_level_discipline_id].to_i
@syllabus.major_id = params[:major_id].to_i
@syllabus.syllabus_type = params[:syllabus_type].to_i
if @syllabus.save
if title != params[:title].to_s.strip
@syllabus.courses.each do |course|
course.name.gsub!(/^#{title}/, params[:title].to_s.strip)
course.save
end
end
end
redirect_to syllabus_path(@syllabus)
end
def edit_ref
@reference_materials = @syllabus.reference_materials
respond_to do |format|
format.js
end
end
def update_ref
@syllabus.reference_materials.destroy_all
refer_inputs = params[:syllabus][:book] if params[:syllabus]
if Array === refer_inputs
refer_inputs.each_with_index do |val, i|
@syllabus.reference_materials << ReferenceMaterial.new(
book: val,
editor: params[:syllabus][:editor][i],
press: params[:syllabus][:press][i]
)
end
end
sy_update_record = SyllabusUpdateRecord.new(:property => 2, :user_id => User.current.id)
@syllabus.syllabus_update_records << sy_update_record
@reference_materials = @syllabus.reference_materials
@is_syllabus_admin = User.current.admin? || @syllabus.syllabus_members.map{|sm| sm.user_id}.include?(User.current.id)
respond_to do |format|
format.js
end
end
def update_des
@syllabus.description = params[:syllabus][:description]
@syllabus.des_status = 1
#@syllabus.save_attachments(params[:attachments])
if @syllabus.save
sy_update_record = SyllabusUpdateRecord.new(:property => 1, :user_id => User.current.id)
@syllabus.syllabus_update_records << sy_update_record
if params[:asset_id]
ids = params[:asset_id].split(',')
update_kindeditor_assets_owner ids,@syllabus.id,OwnerTypeHelper::SYLLABUS
end
end
redirect_to syllabus_path(@syllabus)
end
def add_sy_member_alert
respond_to do |format|
format.js
end
end
def search_not_sy_member
if params[:q] && params[:q].lstrip.rstrip != ""
@users = Principal.active.sorted.not_member_of_syllabus(@syllabus).like(params[:q])
else
@users = []
end
end
def syllabus_resources
@is_syllabus_teacher = User.current.admin? || @syllabus.syllabus_members.map{|sm| sm.user_id}.include?(User.current.id) || !@syllabus.courses.not_deleted_not_end.select { |course| User.current.has_teacher_role(course)}.blank?
@is_syllabus_member = !@syllabus.courses.not_deleted_not_end.select { |course| User.current.member_of_course?(course)}.blank?
@is_syllabus_admin = User.current.admin? || @syllabus.syllabus_members.map{|sm| sm.user_id}.include?(User.current.id)
@is_authen_teacher = User.current.authentication && User.current.user_extensions.try(:identity) != 1
@order, @r_sort = params[:order] || "created_at", params[:sort] || "asc"
@sort = @r_sort == "desc" ? "asc" : "desc"
@resources = sy_resources @syllabus
if @order == "created_at"
@resources = @resources.order("#{@order} #{@sort}")
else
@resources = @resources.select("resource_banks.*, (quotes+downloads) as heat").order("#{@order} #{@sort}, created_at desc")
end
@resource_count = @resources.count
@public_resource_count = @resources.where(:is_public => 1).count
@private_resource_count = @resources.where(:is_public => 0).count
if !(@is_syllabus_admin || @is_syllabus_member)
@resources = @resources.where(:is_public => 1)
end
#分页
@page_resource_count = @resources.count
@limit = 10
@is_remote = true
@resource_pages = Paginator.new @page_resource_count, @limit, params['page'] || 1
@offset ||= @resource_pages.offset
@resources = paginateHelper @resources,@limit
respond_to do |format|
format.js
end
end
def syllabus_homeworks
@is_syllabus_teacher = User.current.admin? || @syllabus.syllabus_members.map{|sm| sm.user_id}.include?(User.current.id) || !@syllabus.courses.not_deleted_not_end.select { |course| User.current.has_teacher_role(course)}.blank?
@is_syllabus_member = !@syllabus.courses.not_deleted_not_end.select { |course| User.current.member_of_course?(course)}.blank?
@is_syllabus_admin = User.current.admin? || @syllabus.syllabus_members.map{|sm| sm.user_id}.include?(User.current.id)
@is_authen_teacher = User.current.authentication && User.current.user_extensions.try(:identity) != 1
@order, @r_sort = params[:order] || "created_at", params[:sort] || "asc"
@sort = @r_sort == "desc" ? "asc" : "desc"
@homeworks = @syllabus.homework_banks.order("#{@order} #{@sort}")
@homework_count = @homeworks.count
@public_homework_count = @homeworks.where(:is_public => 1).count
@private_homework_count = @homeworks.where(:is_public => 0).count
if !(@is_syllabus_admin || @is_syllabus_member)
@homeworks = @homeworks.where(:is_public => 1)
end
@page_homework_count = @homeworks.count
@limit = 10
@is_remote = true
@homework_pages = Paginator.new @page_homework_count, @limit, params['page'] || 1
@offset ||= @homework_pages.offset
@homeworks = paginateHelper @homeworks, @limit
respond_to do |format|
format.js
end
end
def choose_user_course
if !params[:search].nil?
search = "%#{params[:search].to_s.strip.downcase}%"
@courses = User.current.courses.where("is_delete = 0 and is_end = 0 and (#{Course.table_name}.id = #{params[:search].to_i } or #{Course.table_name}.name like :p)",:p=>search).select { |course| User.current.has_teacher_role(course)}
else
@courses = User.current.courses.where("is_delete = 0 and is_end = 0").select { |course| User.current.has_teacher_role(course)}
end
@resource_ids = params[:check_resource] if params[:check_resource]
@homework_ids = params[:check_homework] if params[:check_homework]
@search = params[:search]
#这里仅仅是传递需要发送的资源id
@type = params[:type]
respond_to do |format|
format.js
end
end
def send_resources_to_course
course = Course.find params[:course_id]
if course
params[:resource_id].each do |resource_id|
resource = ResourceBank.find resource_id
quote_resource_bank resource, course
end
end
end
def send_homeworks_to_course
course = Course.find params[:course_id]
if course
params[:homework_id].each do |homework_id|
homework = HomeworkBank.find homework_id
quote_homework_bank homework, course
end
end
end
def send_r_and_h_to_course
course = Course.find params[:course_id]
if course
resources = sy_resources @syllabus
homeworks = @syllabus.homework_banks.order("#{@order} #{@sort}")
ActiveRecord::Base.transaction do
begin
resources.each do |resource|
quote_resource_bank resource, course
end
homeworks.each do |homework|
quote_homework_bank homework, course
end
rescue Exception => e
puts e
end
end
end
end
@ -62,21 +323,6 @@ class SyllabusesController < ApplicationController
end
end
def update
@syllabus.description = params[:syllabus][:description]
@syllabus.des_status = 1
@syllabus.save_attachments(params[:attachments])
if @syllabus.save
if params[:asset_id]
ids = params[:asset_id].split(',')
update_kindeditor_assets_owner ids,@syllabus.id,OwnerTypeHelper::SYLLABUS
end
redirect_to syllabus_path(@syllabus)
else
redirect_to syllabus_path(@syllabus)
end
end
#删除课程大纲的描述
def delete_des
if @syllabus
@ -92,7 +338,7 @@ class SyllabusesController < ApplicationController
def destroy
if @syllabus && @syllabus.courses.not_deleted.empty?
@syllabus.destroy
redirect_to user_courselist_user_path(User.current)
redirect_to syllabuses_path()
end
end
@ -183,6 +429,57 @@ class SyllabusesController < ApplicationController
end
end
def get_discipline_categories
data = {result:0,options:[]}
if params[:major_level]
if DisciplineCategory.where(:major_level => params[:major_level].to_i).count > 0
data[:result] = 1
DisciplineCategory.where(:major_level => params[:major_level].to_i).each do |dis|
option = []
option << dis.name.to_s
option << dis.id
data[:options] << option
end
end
end
render :json =>data
end
def get_first_level_disciplines
data = {result:0,options:[]}
if params[:discipline_category_id]
if FirstLevelDiscipline.where(:discipline_category_id => params[:discipline_category_id].to_i).count > 0
data[:result] = 1
FirstLevelDiscipline.where(:discipline_category_id => params[:discipline_category_id].to_i).each do |dis|
option = []
option << dis.name.to_s
option << dis.id
data[:options] << option
end
end
end
render :json =>data
end
def get_major
data = {result:0,options:[]}
if params[:first_level_discipline_id]
if Major.where(:first_level_discipline_id => params[:first_level_discipline_id].to_i).count > 0
data[:result] = 1
Major.where(:first_level_discipline_id => params[:first_level_discipline_id].to_i).each do |dis|
option = []
option << dis.name.to_s
option << dis.id
data[:options] << option
end
end
end
render :json =>data
end
private
def find_syllabus
@syllabus = Syllabus.find params[:id]

File diff suppressed because it is too large Load Diff

View File

@ -21,36 +21,70 @@ class WatchersController < ApplicationController
def watch
s = WatchesService.new
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();
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();
@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();
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();
@list = query.order("#{Watcher.table_name}.id desc").limit(limit).offset(@obj_pages.offset).all
@action = 'fans'
else
if params[:target_id]
if params[:target_id] && params[:user_watcher].blank?
watchables = s.watch params.merge(:current_user_id => User.current.id)
@user = User.find(params[:target_id])
watch_query = User.watched_by(@user.id)
@user_watchlist_count = watch_query.count
@user_watchlist = watch_query.order("#{Watcher.table_name}.id desc").limit(12)
fan_query = @user.watcher_users
@user_fanlist_count = fan_query.count
@user_fanlist = fan_query.order("#{Watcher.table_name}.id desc").limit(12)
end
end
if params[:object_type] == 'project'
@project = Project.find(params[:object_id])
respond_to do |format|
format.js
end
elsif params[:user_watcher] == "user_fanslist"
@watched = User.find(params[:target_id].to_i)
@user = User.find(params[:object_id].to_i)
@watched.add_watcher(@user)
watch_query = User.watched_by(@user.id)
@user_watchlist_count = watch_query.count
fan_query = @user.watcher_users
@user_fanlist_count = fan_query.count
@user_fanlist = fan_query.order("#{Watcher.table_name}.id desc")
@limit = 20
@is_remote = true
@fans_pages = Paginator.new @user_fanlist_count, @limit, params['page'] || 1
@offset ||= @fans_pages.offset
@user_fanlist = paginateHelper @user_fanlist, @limit
respond_to do |format|
format.js
end
else
respond_to do |format|
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',:list => @list,:action_name=>params[:action_name],:page=>params[:page],:count=>@obj_count} }
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
@ -66,22 +100,28 @@ class WatchersController < ApplicationController
s = WatchesService.new
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();
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();
@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();
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();
@list = query.order("#{Watcher.table_name}.id desc").limit(limit).offset(@obj_pages.offset).all()
@action = 'fans'
else
if params[:target_id]
if params[:target_id] && params[:user_watcher].blank?
@user = User.find(params[:target_id])
watch_query = User.watched_by(@user.id)
@user_watchlist_count = watch_query.count()
@user_watchlist = watch_query.order("#{Watcher.table_name}.id desc").limit(4)
fan_query = @user.watcher_users
@user_fanlist_count = fan_query.count()
@user_fanlist = fan_query.order("#{Watcher.table_name}.id desc").limit(4)
end
end
if params[:object_type] == 'project'
@ -89,6 +129,41 @@ class WatchersController < ApplicationController
respond_to do |format|
format.js
end
elsif params[:user_watcher] == "user_watchlist"
@watched = User.find(params[:target_id].to_i)
@user = User.find(params[:object_id].to_i)
@watched.remove_watcher(@user)
watch_query = User.watched_by(@user.id)
@user_watchlist_count = watch_query.count
@user_watchlist = watch_query.order("#{Watcher.table_name}.id desc")
fan_query = @user.watcher_users
@user_fanlist_count = fan_query.count
@limit = 20
@is_remote = true
@watchlist_pages = Paginator.new @user_watchlist_count, @limit, params['page'] || 1
@offset ||= @watchlist_pages.offset
@user_watchlist = paginateHelper @user_watchlist, @limit
respond_to do |format|
format.js
end
elsif params[:user_watcher] == "user_fanslist"
@watched = User.find(params[:target_id].to_i)
@user = User.find(params[:object_id].to_i)
@watched.remove_watcher(@user)
watch_query = User.watched_by(@user.id)
@user_watchlist_count = watch_query.count
fan_query = @user.watcher_users
@user_fanlist_count = fan_query.count
@user_fanlist = fan_query.order("#{Watcher.table_name}.id desc")
@limit = 20
@is_remote = true
@fans_pages = Paginator.new @user_fanlist_count, @limit, params['page'] || 1
@offset ||= @fans_pages.offset
@user_fanlist = paginateHelper @user_fanlist, @limit
respond_to do |format|
format.js
end
else
respond_to do |format|
format.html { redirect_to_referer_or {render :text => (false ? 'Watcher added.' : 'Watcher removed.'), :layout => true}}
@ -103,7 +178,7 @@ class WatchersController < ApplicationController
end
#set_watcher(@watchables, User.current, false)
end
def join
if User.current.logged?
course = Project.find(params[:object_id])
@ -111,7 +186,7 @@ class WatchersController < ApplicationController
members = []
members << Member.new(:role_ids => [5], :user_id => User.current.id)
course.members << members
StudentsForCourse.create(:student_id => User.current.id, :course_id => params[:object_id])
else
end
@ -121,13 +196,13 @@ class WatchersController < ApplicationController
format.js { render :partial => 'set_join', :locals => {:user => User.current, :course => Project.find(params[:object_id])} }
end
end
def unjoin
if User.current.logged?
@member = Member.where('project_id = ? and user_id = ?', params[:object_id], User.current.id)
@member.first.destroy
joined = StudentsForCourse.where('student_id = ? and course_id = ?', User.current.id, params[:object_id])
joined.each do |join|
join.destroy
@ -169,6 +244,8 @@ class WatchersController < ApplicationController
end
end
# params user_watcher 用户关注列表
# user_fans 用户粉丝列表
def destroy
@watched.set_watcher(User.find(params[:user_id]), false)
respond_to do |format|

View File

@ -1,294 +1,298 @@
# Redmine - project management software
# Copyright (C) 2006-2013 Jean-Philippe Lang
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
class WelcomeController < ApplicationController
# layout "base_welcome"
include ApplicationHelper
include WelcomeHelper
helper :project_score
caches_action :robots, :course, :contest, expires_in: 2.hours, layout: false
#before_filter :find_first_page, :only => [:index]
# before_filter :fake, :only => [:index, :course]
before_filter :entry_select, :only => [:index]
def index
@welcome = true
render :layout => 'login_bigdata'
end
def robots
@projects = Project.all_public.active
render :layout => false, :content_type => 'text/plain'
end
def course
redirect_to signin_path
return
#
# @course_page = FirstPage.find_by_page_type('course')
# @school_id = params[:school_id] || User.current.user_extensions.school.try(:id) || 117
# @logoLink ||= logolink()
end
def logolink()
@course_page = FirstPage.find_by_page_type('course')
logo = get_avatar?(@course_page)
id = params[:school_id]
logo_link = ""
if id.nil? && (User.current.user_extensions.nil? || User.current.user_extensions.school.nil?)
if logo
logo_link = url_to_avatar(@course_page)
else
logo_link = '/images/transparent.png'
end
else
if id == "0"
if logo
logo_link = url_to_avatar(@course_page)
else
logo_link = '/images/transparent.png'
end
else
if id.nil?
if School.find(User.current.user_extensions.school.id).logo_link.nil?
logo_link = '/images/transparent.png'
else
logo_link = School.find(User.current.user_extensions.school.id).logo_link
end
else
logo_link = School.find(id).logo_link
end
end
end
return logo_link
end
def contest
redirect_to signin_path
return
# @contest_page = FirstPage.find_by_page_type('contest')
# @contest_notifications = Contestnotification.order("created_at desc").limit(5)
end
def search
@name = params[:q]
@search_type = params[:search_type]
page = (params[:page] || 1).to_i
@users_count = User.search(@name).results.total
@syllabus_count = Syllabus.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','title','name','description^0.5','filename','subject','content^0.5']
}
},
highlight: {
pre_tags: ['<span class="c_red">'],
post_tags: ['</span>'],
fields: {
login: {},
firstname: {},
lastname: {},
title:{},
name:{},
description:{},
filename:{},
subject:{},
content:{}
}
}
},[User,Syllabus,Course,Attachment,Project,Memo] ).results.total
case params[:search_type]
when 'all'
if (page-1)*20 >= @total_count
page = 1
params[:page] = "1"
end
@alls = Elasticsearch::Model.search({
query: {
multi_match: {
query: @name,
type:"most_fields",
operator: "or",
fields: ['login', 'firstname','lastname','title','name','description^0.5','filename','subject','content^0.5']
}
},
highlight: {
pre_tags: ['<span class="c_red">'],
post_tags: ['</span>'],
fields: {
login: {},
firstname: {},
lastname: {},
title:{},
name:{},
description:{},
filename:{},
subject:{},
content:{}
}
}
},[User,Syllabus,Course,Attachment,Project,Memo] ).page(page).per(20).results
when 'user'
if (page-1)*20 >= @users_count
page = 1
params[:page] = "1"
end
@users = User.search(@name).page(page).per(20)
when 'syllabus'
if (page-1)*20 >= @syllabus_count
page = 1
params[:page] = "1"
end
@syllabuses = Syllabus.search(@name).page(page).per(20).results
when 'project'
if (page-1)*20 >= @project_count
page = 1
end
@projects = Project.search(@name).page(page).per(20).results
when 'course'
if (page-1)*20 >= @course_count
page = 1
params[:page] = "1"
end
@courses = Course.search(@name).page(page).per(20).results
when 'attachment'
if (page-1)*20 >= @attach_count
page = 1
params[:page] = "1"
end
@attachments = Attachment.search(@name).page(page).per(20).results
when 'memo'
if (page-1)*20 >= @memo_count
page = 1
params[:page] = "1"
end
@memos = Memo.search(@name).page(page).per(20).results
else
if (page-1)*20 >= @total_count
page = 1
params[:page] = "1"
end
@alls = Elasticsearch::Model.search({
query: {
multi_match: {
query: @name,
type:"most_fields",
operator: "or",
fields: ['login', 'firstname','lastname','title','name','description^0.5','filename','subject','content^0.5']
}
},
highlight: {
pre_tags: ['<span class="c_red">'],
post_tags: ['</span>'],
fields: {
login: {},
firstname: {},
lastname: {},
title:{},
name:{},
description:{},
filename:{},
subject:{},
content:{}
}
}
},[User,Syllabus,Course,Attachment,Project,Memo] ).page(page).per(20).results
end
# 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|
format.js
format.html{ render :layout=>'users_base'}
end
end
private
# 判断网站的入口,是课程 course 则跳过index去渲染 course 方法
def entry_select
# url = request.original_url.gsub('/','')
# if url.include?(Setting.url_course.gsub('/',''))
# if @first_page.show_course == 1
# course
# render :course
# else
# render_404
# end
#
# return 0
# elsif url.include?(Setting.url_contest.gsub('/',''))
# if @first_page.show_contest == 1
# contest
# render :contest
# else
# render_404
# end
#
# return 0
# elsif url.include?(Setting.url_user.gsub('/',''))
# #redirect_to(:controller => "users", :action => "index")
# end
end
# def render(*args)
# _fake if @fake_filter
# super
# end
# private
# def fake
# @fake_filter = true
# end
# # 骗子方法
# def _fake
# instance_variables.map { |variable|
# if variable.to_s =~ /Count$/
# self.instance_variable_set(variable.to_sym,
# ("1" + (self.instance_variable_get(variable.to_sym).to_s)).to_i)
# end
# }
# end
end
# Redmine - project management software
# Copyright (C) 2006-2013 Jean-Philippe Lang
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
class WelcomeController < ApplicationController
# layout "base_welcome"
include ApplicationHelper
include WelcomeHelper
helper :project_score
caches_action :robots, :course, :contest, expires_in: 2.hours, layout: false
#before_filter :find_first_page, :only => [:index]
# before_filter :fake, :only => [:index, :course]
before_filter :entry_select, :only => [:index]
skip_before_filter :check_authentication, :only => [:index]
def index
# @welcome是因为有的页面不需要导航
@welcome = true
@courses = Course.where(:homepage_show => 1).limit(6)
@shixuns = Shixun.where(:homepage_show => 1).limit(6)
render :layout => 'login_bigdata'
end
def robots
@projects = Project.all_public.active
render :layout => false, :content_type => 'text/plain'
end
def course
redirect_to signin_path
return
#
# @course_page = FirstPage.find_by_page_type('course')
# @school_id = params[:school_id] || User.current.user_extensions.school.try(:id) || 117
# @logoLink ||= logolink()
end
def logolink()
@course_page = FirstPage.find_by_page_type('course')
logo = get_avatar?(@course_page)
id = params[:school_id]
logo_link = ""
if id.nil? && (User.current.user_extensions.nil? || User.current.user_extensions.school.nil?)
if logo
logo_link = url_to_avatar(@course_page)
else
logo_link = '/images/transparent.png'
end
else
if id == "0"
if logo
logo_link = url_to_avatar(@course_page)
else
logo_link = '/images/transparent.png'
end
else
if id.nil?
if School.find(User.current.user_extensions.school.id).logo_link.nil?
logo_link = '/images/transparent.png'
else
logo_link = School.find(User.current.user_extensions.school.id).logo_link
end
else
logo_link = School.find(id).logo_link
end
end
end
return logo_link
end
def contest
redirect_to signin_path
return
# @contest_page = FirstPage.find_by_page_type('contest')
# @contest_notifications = Contestnotification.order("created_at desc").limit(5)
end
def search
@name = params[:q]
@search_type = params[:search_type]
page = (params[:page] || 1).to_i
@users_count = User.search(@name).results.total
@syllabus_count = Syllabus.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','title','name','description^0.5','filename','subject','content^0.5']
}
},
highlight: {
pre_tags: ['<span class="c_red">'],
post_tags: ['</span>'],
fields: {
login: {},
firstname: {},
lastname: {},
title:{},
name:{},
description:{},
filename:{},
subject:{},
content:{}
}
}
},[User,Syllabus,Course,Attachment,Project,Memo] ).results.total
case params[:search_type]
when 'all'
if (page-1)*20 >= @total_count
page = 1
params[:page] = "1"
end
@alls = Elasticsearch::Model.search({
query: {
multi_match: {
query: @name,
type:"most_fields",
operator: "or",
fields: ['login', 'firstname','lastname','title','name','description^0.5','filename','subject','content^0.5']
}
},
highlight: {
pre_tags: ['<span class="c_red">'],
post_tags: ['</span>'],
fields: {
login: {},
firstname: {},
lastname: {},
title:{},
name:{},
description:{},
filename:{},
subject:{},
content:{}
}
}
},[User,Syllabus,Course,Attachment,Project,Memo] ).page(page).per(20).results
when 'user'
if (page-1)*20 >= @users_count
page = 1
params[:page] = "1"
end
@users = User.search(@name).page(page).per(20)
when 'syllabus'
if (page-1)*20 >= @syllabus_count
page = 1
params[:page] = "1"
end
@syllabuses = Syllabus.search(@name).page(page).per(20).results
when 'project'
if (page-1)*20 >= @project_count
page = 1
end
@projects = Project.search(@name).page(page).per(20).results
when 'course'
if (page-1)*20 >= @course_count
page = 1
params[:page] = "1"
end
@courses = Course.search(@name).page(page).per(20).results
when 'attachment'
if (page-1)*20 >= @attach_count
page = 1
params[:page] = "1"
end
@attachments = Attachment.search(@name).page(page).per(20).results
when 'memo'
if (page-1)*20 >= @memo_count
page = 1
params[:page] = "1"
end
@memos = Memo.search(@name).page(page).per(20).results
else
if (page-1)*20 >= @total_count
page = 1
params[:page] = "1"
end
@alls = Elasticsearch::Model.search({
query: {
multi_match: {
query: @name,
type:"most_fields",
operator: "or",
fields: ['login', 'firstname','lastname','title','name','description^0.5','filename','subject','content^0.5']
}
},
highlight: {
pre_tags: ['<span class="c_red">'],
post_tags: ['</span>'],
fields: {
login: {},
firstname: {},
lastname: {},
title:{},
name:{},
description:{},
filename:{},
subject:{},
content:{}
}
}
},[User,Syllabus,Course,Attachment,Project,Memo] ).page(page).per(20).results
end
# 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|
format.js
format.html{ render :layout=>'users_base'}
end
end
private
# 判断网站的入口,是课程 course 则跳过index去渲染 course 方法
def entry_select
# url = request.original_url.gsub('/','')
# if url.include?(Setting.url_course.gsub('/',''))
# if @first_page.show_course == 1
# course
# render :course
# else
# render_404
# end
#
# return 0
# elsif url.include?(Setting.url_contest.gsub('/',''))
# if @first_page.show_contest == 1
# contest
# render :contest
# else
# render_404
# end
#
# return 0
# elsif url.include?(Setting.url_user.gsub('/',''))
# #redirect_to(:controller => "users", :action => "index")
# end
end
# def render(*args)
# _fake if @fake_filter
# super
# end
# private
# def fake
# @fake_filter = true
# end
# # 骗子方法
# def _fake
# instance_variables.map { |variable|
# if variable.to_s =~ /Count$/
# self.instance_variable_set(variable.to_sym,
# ("1" + (self.instance_variable_get(variable.to_sym).to_s)).to_i)
# end
# }
# end
end

View File

@ -342,23 +342,23 @@ class WordsController < ApplicationController
def leave_homework_message
if User.current.logged?
@user = User.current
@homework_common = HomeworkCommon.find(params[:id]);
@homework = 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], @homework_common.id)
feedback = HomeworkCommon.add_homework_jour(@user, params[:homework_message], params[:id], @homework.id)
if (feedback.errors.empty?)
if params[:asset_id]
ids = params[:asset_id].split(',')
update_kindeditor_assets_owner ids,feedback[:id],OwnerTypeHelper::JOURNALSFORMESSAGE
end
@homework_common.update_column('updated_at', Time.now)
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)
@homework.update_column('updated_at', Time.now)
update_course_activity(@homework.class,@homework.id)
update_user_activity(@homework.class,@homework.id)
update_org_activity(@homework.class,@homework.id)
respond_to do |format|
format.js{
@user_activity_id = params[:user_activity_id].to_i
@hw_status = params[:hw_status].to_i if params[:hw_status]
@is_teacher = User.current.allowed_to?(:as_teacher, @homework_common.course) || User.current.admin?
@is_teacher = User.current.allowed_to?(:as_teacher, @homework.course) || User.current.admin?
}
end
else
@ -375,7 +375,7 @@ class WordsController < ApplicationController
if User.current.logged?
@user = User.current
reply = JournalsForMessage.find params[:id].to_i
@homework_common = HomeworkCommon.find reply.jour_id
@homework = HomeworkCommon.find reply.jour_id
if params[:reply_message].size>0 && User.current.logged? && @user
options = {:notes => params[:reply_message], :reply_id => reply.user_id,:user_id => @user.id,:m_parent_id => params[:id].to_i,:m_reply_id => params[:id].to_i, :root_id => reply.root_id}
feedback = HomeworkCommon.add_homework_jour(@user, params[:reply_message], reply.jour_id, reply.root_id, options)
@ -384,15 +384,15 @@ class WordsController < ApplicationController
ids = params[:asset_id].split(',')
update_kindeditor_assets_owner ids,feedback[:id],OwnerTypeHelper::JOURNALSFORMESSAGE
end
@homework_common.update_column('updated_at', Time.now)
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)
@homework.update_column('updated_at', Time.now)
update_course_activity(@homework.class,@homework.id)
update_user_activity(@homework.class,@homework.id)
update_org_activity(@homework.class,@homework.id)
respond_to do |format|
format.js{
@user_activity_id = params[:user_activity_id].to_i
@hw_status = params[:hw_status].to_i if params[:hw_status]
@is_teacher = User.current.allowed_to?(:as_teacher, @homework_common.course) || User.current.admin?
@is_teacher = User.current.allowed_to?(:as_teacher, @homework.course) || User.current.admin?
}
end
else
@ -514,8 +514,19 @@ class WordsController < ApplicationController
if params[:text].size>0 && @user
# @user.add_jour(me, params[:text])
#私信
if params[:shixun_name]
game_id = params[:game_id]
message = params[:text]
admin_id = User.where(:admin => 1).first.try(:id)
user_ids = [admin_id, params[:shixun_author_id].to_i]
user_ids.each do |user_id|
JournalsForMessage.create(:jour_id => game_id, :jour_type => "Game", :user_id => user_id, :notes => message, :reply_id => 0, :status => true, :is_readed => false, :private => 1)
end
else
message = "<span style='color:red;'>【未收到激活邮件的用户反馈,用户邮箱:"+me.mail+"】</span><br>"+params[:text]
@user.journals_for_messages << JournalsForMessage.new(:user_id => me.id, :notes => message, :reply_id => 0, :status => true, :is_readed => false, :private => 1)
end
else
status = 0
end
@ -524,6 +535,7 @@ class WordsController < ApplicationController
render_403
end
end
private

View File

@ -205,6 +205,45 @@ module ApiHelper
end
# 获取当前时间
def time_from_future time
lastUpdateTime = time.to_i*1000
currentTime = Time.now.to_i*1000
timePassed = lastUpdateTime - currentTime;
timeIntoFormat = 0
updateAtValue = ""
if timePassed < 0
updateAtValue = "马上"
elsif timePassed < ONE_MINUTE
updateAtValue = "1分钟"
elsif timePassed < ONE_HOUR
timeIntoFormat = timePassed / ONE_MINUTE
updateAtValue = timeIntoFormat.to_s + "分钟"
elsif (timePassed < ONE_DAY)
timeIntoFormat = timePassed / ONE_HOUR
updateAtValue = timeIntoFormat.to_s + "小时"
elsif (timePassed < ONE_MONTH)
timeIntoFormat = timePassed / ONE_DAY
updateAtValue = timeIntoFormat.to_s + ""
elsif (timePassed < ONE_YEAR)
timeIntoFormat = timePassed / ONE_MONTH
updateAtValue = timeIntoFormat.to_s + "个月"
else
timeIntoFormat = timePassed / ONE_YEAR
updateAtValue = timeIntoFormat.to_s + ""
end
updateAtValue
end
# 计算到结束还有多长时间 **天**小时**分
def how_much_time time
result = ""
result = ((time - Time.now.to_i).to_i / (24*60*60)).to_s + ""
result += (((time - Time.now.to_i).to_i % (24*60*60)) / (60*60)).to_s + " 小时 "
result += ((((time - Time.now.to_i).to_i % (24*60*60)) % (60*60)) / 60).to_s + ""
end
#日期转换为时间
def convert_to_time date, num
if num == 0

File diff suppressed because it is too large Load Diff

View File

@ -39,11 +39,19 @@ module AvatarHelper
def avatar_filename(source_id,image_file)
"#{source_id}" #<< file_extension(image_file)
end
def auth_filename(source_id,type)
"#{source_id}#{type}"
end
def disk_filename(source_type,source_id,image_file=nil)
File.join(storage_path,avatar_directory(source_type),avatar_filename(source_id,image_file))
end
def disk_auth_filename(source_type,source_id,type)
File.join(storage_path,avatar_directory(source_type),auth_filename(source_id,type))
end
def copy_course?(source_type, source_id)
file= disk_filename(source_type, source_id)
if source_type == Course && !File.exist?(file)

View File

@ -1,2 +1,28 @@
# encoding: utf-8
module ChallengesHelper
def difficulty_type difficulty
case difficulty
when 1
"简单"
when 2
"中等"
when 3
"复杂"
end
end
def find_game_status challenge_id
game = Game.where(:challenge_id => challenge_id, :user_id => User.current.id).first
case game.try(:status)
when 0
"待完成&nbsp;&nbsp;<a href='javascript:void(0);'><i data-tip-down='点击开始' class='fa fa-play-circle color-light-green fr font-24 -text-danger w20_center'></i></a>".html_safe
when 1
"<i data-tip-down='评测中' class='fa fa-unlock-alt fr font-20 mt5 -text-danger w20_center'></i></a>".html_safe
when 2
"已完成&nbsp;&nbsp;<a href='javascript:void(0);'><i data-tip-down='已解决' class='fa fa-check-circle fr font-24 color-light-green w20_center' ></i></a>".html_safe
when 3,nil
"未开始&nbsp;&nbsp;<a><i data-tip-down='请先完成前序关卡。无法点击' class='fa fa-play-circle fr font-24 color-grey w20_center' ></i></a>".html_safe
end
end
end

View File

@ -12,6 +12,32 @@ module CoursesHelper
#AllPeople = StudentRoles+TeacherRoles
## return people count
def student_course_homework_score course, user
homework_ids = course.homework_commons.where("homework_type in (1, 4) and publish_time < '#{Time.now}'").map(&:id)
score = 0
user.student_works.where(:homework_common_id => homework_ids).each do |work|
score = score + work.work_score if work.work_score
end
format("%.1f",score)
end
# 学生的发布资源数
def student_course_resource_num course, user
num = course.attachments.where(:author_id => user.id).count
end
# 学生的发布帖子数
def student_course_message_num course, user
num = Message.where(:board_id => course.boards.map(&:id), :author_id => user.id, :parent_id => nil).count
end
# 学生的回复评论数
def student_course_reply_num course, user
boards_id = course.boards.empty? ? "(-1)" : "(" + course.boards.map(&:id).join(",") + ")"
me_num = Message.where("board_id in #{boards_id} and author_id = #{user.id} and parent_id is not null").count
jour_num = JournalsForMessage.where(:jour_type => 'HomeworkCommon', :jour_id => course.homework_commons.map(&:id), :user_id => user.id).count
num = me_num + jour_num
end
# 推荐的精品课程
def excellent_course_recommend new_course
@ -78,19 +104,42 @@ module CoursesHelper
#生成课程老师成员链接
def course_teacher_link teacher_num
if User.current.member_of_course?(@course) || User.current.admin?
link_to "#{teacher_num}", course_member_path(@course, :role => 1), :class => 'sy_cblue', :id => 'teacher_number'
if User.current.allowed_to?(:as_teacher, @course) || User.current.member_of_course?(@course)
link_to teacher_num, members_course_path(@course), :class => 'ml5 edu-cir-grey-q color-orange05', :id => 'teacher_number'
# elsif User.current.member_of_course?(@course)
# link_to teacher_num, course_member_path(@course, :role => 't'), :class => 'ml5 edu-cir-grey-q color-orange05', :id => 'teacher_number'
else
content_tag 'span',teacher_num, :class => 'sy_cblue'
content_tag 'span',teacher_num, :class => 'ml5 edu-cir-grey-q color-orange05'
end
end
#生成课程学生列表连接
def course_student_link student_num
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 => 'sy_cblue', :id => "student_number"
if User.current.allowed_to?(:as_teacher, @course) || User.current.member_of_course?(@course)
link_to "#{student_num}", members_course_path(@course, :role => 'as'), :class => 'ml5 edu-cir-grey-q color-orange05', :id => 'student_number'
# elsif (User.current.logged? && @course.open_student == 1) || (User.current.member_of_course?(@course))
# link_to "#{student_num}", course_member_path(@course, :role => 'as'), :class => 'ml5 edu-cir-grey-q color-orange05', :id => "student_number"
else
content_tag 'span',student_num, :class => 'sy_cblue'
content_tag 'span',student_num, :class => 'ml5 edu-cir-grey-q color-orange05'
end
end
# 生成分班列表连接
def course_group_link group_num
if User.current.allowed_to?(:as_teacher, @course) || User.current.member_of_course?(@course)
link_to "#{group_num}", members_course_path(@course, :role => @course.course_groups.first.id), :class => 'ml5 edu-cir-grey-q color-orange03', :id => 'group_number'
# elsif (User.current.logged? && @course.open_student == 1) || (User.current.member_of_course?(@course))
# link_to "#{group_num}", course_member_path(@course, :role => @course.course_groups.first.id), :class => 'ml5 edu-cir-grey-q color-orange03', :id => "group_number"
else
content_tag 'span',group_num, :class => 'ml5 edu-cir-grey-q color-orange05'
end
end
# 班级结束天数
def course_end_date course
if course.end_date
curr = Time.new
((Date.parse(course.end_date.to_s) - Date.parse(curr.to_s)).to_i)
end
end
@ -306,7 +355,9 @@ module CoursesHelper
members
end
def groupCount course
course.course_groups.count
end
def searchStudent_by_name project, name
#searchPeopleByRoles(project, StudentRoles)
@ -596,8 +647,10 @@ module CoursesHelper
# 获取动态列表名称
def get_acts_list_type type
case type
when "homework"
l(:label_homework_acts)
when "common_homework"
l(:label_common_homework_acts)
when "shixun_homework"
l(:label_shixun_homework_acts)
when "news"
l(:label_news_acts)
when "attachment"
@ -617,7 +670,7 @@ module CoursesHelper
def course_group_option course
type = []
option1 = []
option1 << "暂无"
option1 << "选择分班"
option1 << 0
type << option1
unless course.course_groups.nil?
@ -794,40 +847,20 @@ module CoursesHelper
url = joined ? join_path(:object_id => course.id) : join_private_courses_courses_path()
method = joined ? 'delete' : 'post'
if joined
link = link_to(text, url, :remote => true, :method => method, :class => "sy_btn_grey fl", :id => "#{course.id}", :confirm => l(:text_are_you_sure_out))
link = link_to(text, url, :remote => true, :method => method, :class => "joinclass", :id => "#{course.id}", :confirm => l(:text_are_you_sure_out))
else
link = link_to(text, url, :remote => true, :method => method, :id => "#{course.id}", :class => "sy_btn_grey fl")
link = link_to(text, url, :remote => true, :method => method, :id => "#{course.id}", :class => "joinclass")
end
else
if User.current.logged?
link = "<a href='javascript:void(0)' class='sy_btn_grey fl ml10' >#{l(:label_course_join_student)}</a>"
link = "<a href='javascript:void(0)' class='joinclass'>#{l(:label_course_join_student)}</a>"
else
link = link_to(l(:label_course_join_student), signin_url_without_domain, :class => "sy_btn_grey fl ml10")
link = link_to(l(:label_course_join_student), signin_url_without_domain, :class => "joinclass")
end
end
link.html_safe
end
# 可以查看到资源库的资源
def visable_attachemnts_incourse course
return[] unless course
result = []
course.attachments.each do |attachment|
if attachment.is_public? && attachment.is_publish == 1 || User.current == attachment.author || User.current.allowed_to?(:as_teacher,course) || (User.current.member_of_course?(course) && attachment.is_publish == 1) || User.current.admin?
result << attachment
end
end
result
end
def visable_course_homework course
if User.current.admin? || User.current.allowed_to?(:as_teacher,course)
homework_num = course.homework_commons.count
else
homework_num = course.homework_commons.where("publish_time <= '#{Time.now}'").count
end
homework_num
end
def zh_course_role role
if role == "TeachingAsistant"

View File

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

View File

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

View File

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

View File

@ -1,6 +1,44 @@
# encoding: utf-8
module ExerciseHelper
def un_commit_num exercise
course = exercise.course
exercise.exercise_users.where(:commit_status => 0, :user_id => course.student.map(&:student_id)).count
end
def has_commit_num exercise
course = exercise.course
exercise.exercise_users.where(:commit_status => 1, :user_id => course.student.map(&:student_id)).count
end
def un_comment_num exercise
course = exercise.course
exercise.exercise_users.where(:commit_status => 1, :user_id => course.student.map(&:student_id), :subjective_score => -1).count
end
def has_comment_num exercise
course = exercise.course
exercise.exercise_users.where(:commit_status => 1, :user_id => course.student.map(&:student_id)).count - exercise.exercise_users.where(:commit_status => 1, :user_id => course.student.map(&:student_id), :subjective_score => -1).count
end
def answer_is_correct eq, user
is_correct = false
case eq.question_type
when 1
answer = get_user_answer(eq, user)
standard_answer = get_user_standard_answer(eq, user)
is_correct = !answer.empty? && !standard_answer.empty? && answer.first.exercise_choice.choice_position == standard_answer.first.exercise_choice_id
when 2
standard_answer = get_user_standard_answer(eq, user)
is_correct = !standard_answer.empty? && get_mulscore(eq, user).to_i == standard_answer.first.exercise_choice_id
when 3
answer = get_user_answer(eq, user)
standard_answer = get_user_standard_answer(eq, user)
is_correct = !answer.empty? && !standard_answer.empty? && standard_answer.include?(answer.first.answer_text)
end
is_correct
end
# 单选
def sigle_selection_standard_answer(params)
size = params.ord - 96
@ -160,6 +198,17 @@ module ExerciseHelper
uncomplete_question
end
def question_commit_status question, user
status = ""
case question.question_type
when 3, 4
get_anwser_vote_text(question.id,user.id) == "" ? status = "未答" : status = ""
when 1, 2
get_user_answer(question,user).empty? ? status = "未答" : status = ""
end
status
end
#获取文本题答案
def get_anwser_vote_text(question_id,user_id)
pv = ExerciseAnswer.find_by_exercise_question_id_and_user_id(question_id,user_id)

View File

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

View File

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

View File

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

View File

@ -0,0 +1,5 @@
module ManagementHelper
end

View File

@ -0,0 +1,42 @@
module ManagementsHelper
def trial_authorization_status status
case status
when "0", nil
0
when "1"
1
when "2"
2
else
[1,2]
end
end
def query_user_status_num status
user = (status == 0) ? user = User.all : User.where(:status => status)
return user.count
end
def course_list_major_time id
Major.where(:id => id).first.try(:name)
end
# params[:id]: course_list_id
def get_course_list_major id
Major.where(:id => MajorCourse.where(:course_list_id => id).map(&:major_id))
end
def course_list_count id
Major.where(:id => id).first.try(:name)
end
def delete_mirror_http del_uri
del_uri = URI.parse(URI.encode(del_uri.strip))
del_data = {}
del_http = Net::HTTP.new del_uri.host, del_uri.port
del_req = Net::HTTP::Delete.new(del_uri.request_uri)
del_req.form_data = del_data
del_res = del_http.start { |http| http.request del_req }
end
end

View File

@ -12,4 +12,9 @@ module OwnerTypeHelper
ArticleHomepage = 11
PROJECT = 12
CONTEST = 13
HOMEWORKREFERENCEANSWER = 14
STUDENTWORK = 15
HOMEWORKBANK = 16
SUBJECT = 17
EXERCISEQUESTION = 18
end

View File

@ -1,5 +1,9 @@
module ShixunsHelper
def had_passed_count
end
#显示项目配置菜单
def show_project_memu user
if user.allowed_to?(:edit_project, @shixun)
@ -13,5 +17,9 @@ module ShixunsHelper
end
result
end
def had_passed_challenge challenge
Game.where(:challenge_id => challenge.id, :status => 2).limit(3).reorder("final_score desc")
end
end

View File

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

View File

@ -2,6 +2,18 @@
include UserScoreHelper
module StudentWorkHelper
def update_shixun_work_status homework
homework.student_works.each do |work|
if work.work_status == 0
myshixun = Myshixun.where(:shixun_id => homework.homework_commons_shixuns.shixun_id, :user_id => work.user_id).first
if myshixun
work.update_attributes(:work_status => myshixun.created_at <= homework.end_time ? 1 : 2, :late_penalty => myshixun.created_at <= homework.end_time ? 0 : homework.late_penalty, :commit_time => myshixun.created_at, :myshixun_id => myshixun.id)
end
end
set_shixun_final_score homework, work, homework.homework_detail_manual.answer_open_evaluation
end
end
#获取当前用户的项目列表
def user_projects_option
projects = User.current.projects.visible
@ -73,13 +85,68 @@ module StudentWorkHelper
str
end
#获取学生作品的评分记录:同一个教师或教辅只显示未隐藏的评分
# 作品的助教评分模式
def ta_score_mode homework
mode = homework.homework_detail_manual.ta_mode == 1 ? '平均' : '复审'
mode
end
#根据传入作业确定显示为编辑作品还是新建作品,或者显示作品数量
def user_work_status homework
if User.current.logged?
if User.current.member_of_course?(homework.course)
work = cur_user_works_for_homework homework
project = cur_user_projects_for_homework homework
if work.nil? && homework.end_time >= Time.now
if homework.homework_type == 4
#link_to "关联实战", relate_myshixun_student_work_index_path(:homework => homework.id),:class => 'white-btn orange-btn fr mr10 mt8',:remote => true
else
link_to "提交作品", new_student_work_url_without_domain(homework.id),:class => 'white-btn orange-btn fr mr10 mt8'
end
elsif work.nil? && homework.end_time < Time.now
if homework.allow_late && homework.homework_detail_manual.comment_status < 6
if homework.homework_type == 4
#link_to "关联实战", relate_myshixun_student_work_index_path(:homework => homework.id),:class => 'white-btn orange-btn fr mr10 mt8',:remote => true
else
link_to "补交作品", new_student_work_url_without_domain(homework.id),:class => 'white-btn orange-btn fr mr10 mt8'
end
end
elsif work
if homework.homework_type == 4
myshixun = Myshixun.find work.myshixun_id
is_modify = ShixunModify.where(:myshixun_id => myshixun.try(:id), :shixun_id => myshixun.shixun.try(:id), :status => 1).first
if myshixun && is_modify.blank?
link_to "继续实战", myshixun_game_path(myshixun.current_task, :myshixun_id => myshixun), :class => "white-btn orange-btn fr mr10 mt8", :target => "_blank"
elsif myshixun
link_to "继续实战", 'javascript:void(0);', :onclick => "sure_box_redirect('#{myshixun_reset_myshixun_path(myshixun)}', '实训已经更新啦,系统正在为您重置');", :class => "white-btn orange-btn fr mr10 mt8"
end
else
if homework.end_time >= Time.now && work.user_id == User.current.id
link_to "修改作品", edit_student_work_url_without_domain(work.id),:class => 'white-btn orange-btn fr mr10 mt8'
end
# work_ids = "(" + homework.student_works.has_committed.map(&:id).join(",") + ")"
# if homework.homework_detail_manual && homework.homework_detail_manual.comment_status == 3 && User.current.student_works_evaluation_distributions.where("student_work_id IN #{work_ids}").count > 0 #匿评作业,且作业状态不是在开启匿评之前
# link_to "匿评作品", student_work_index_url_in_org(homework.id, 2), :class => 'white-btn orange-btn fr mr10 mt8', :title => "开启匿评后不可修改作品"
# elsif homework.homework_detail_manual && homework.homework_detail_manual.comment_status > 3
# link_to "查看作品", student_work_path(work), :class => 'white-btn orange-btn fr mr10 mt8', :title => "匿评已结束"
# elsif homework.end_time >= Time.now && work.user_id == User.current.id
# link_to "修改作品", edit_student_work_url_without_domain(work.id),:class => 'white-btn orange-btn fr mr10 mt8'
# else
# link_to "查看作品", student_work_path(work), :class => 'white-btn orange-btn fr mr10 mt8', :title => "作业截止后不可修改作品"
# end
end
end
end
end
end
#获取学生作品的评分记录:同一个教师或教辅只显示未隐藏的评分、匿评多次评分只取最新一条
def student_work_score_record work
# sql = "SELECT MAX(id) id FROM student_works_scores WHERE (reviewer_role = 2 OR reviewer_role = 1) AND score IS NOT NULL AND is_hidden = 0 AND student_work_id = #{work.id} GROUP BY user_id"
# tea_ts_ids = StudentWorksScore.find_by_sql sql
# tea_ts_ids = tea_ts_ids.empty? ? "(-1)" : "(" + tea_ts_ids.map{|tea| tea.id}.join(",") + ")"
# scores = work.student_works_scores.where("score IS NULL or reviewer_role = 3 or id in #{tea_ts_ids}").order("updated_at desc")
scores = work.student_works_scores.where(:is_hidden => false).order("created_at desc")
sql = "SELECT MAX(id) id FROM student_works_scores WHERE reviewer_role = 3 AND score IS NOT NULL AND is_hidden = 0 AND student_work_id = #{work.id} GROUP BY user_id"
st_ts_ids = StudentWorksScore.find_by_sql sql
st_ts_ids = st_ts_ids.empty? ? "(-1)" : "(" + st_ts_ids.map{|tea| tea.id}.join(",") + ")"
scores = work.student_works_scores.where("is_hidden = 0 and(reviewer_role = 1 or reviewer_role = 2 or id in #{st_ts_ids})").order("updated_at desc")
#scores = work.student_works_scores.where(:is_hidden => false).order("created_at desc")
return scores
end
@ -106,9 +173,9 @@ module StudentWorkHelper
#传入分数,获取对应颜色
def score_color score
if score
color = score >= 90 ? "c_red" : "c_green"
color = score >= 90 ? "color-red-light" : "color-light-green"
else
color = "c_grey"
color = "color-grey"
end
color
end
@ -173,15 +240,29 @@ module StudentWorkHelper
return status
end
def group_student_works student_work, homework
pros = student_work.student_work_projects.where("is_leader = 0")
def group_member_work student_work
member_work = nil
if student_work.student_work_projects.count > 0
member_work = student_work
else
student_work_pro = StudentWorkProject.where(:user_id => student_work.user_id, :homework_common_id => student_work.homework_common_id).first
if student_work_pro
member_work = StudentWork.find student_work_pro.student_work_id
end
end
member_work
end
def group_student_works member_work, student_work, homework
pros = member_work.student_work_projects.where("user_id != #{student_work.user_id}")
user_ids = pros.empty? ? "(-1)" : "(" + pros.map{|stu|stu.user_id}.join(",") + ")"
student_works = homework.student_works.where("user_id in #{user_ids}")
return student_works
end
def add_score_to_member student_work, homework, new_score
student_works = group_student_works student_work, homework
member_work = group_member_work student_work
student_works = group_student_works member_work, student_work, homework
student_works.each do |st_work|
st_work.student_works_scores << StudentWorksScore.create(:user_id => new_score.user_id, :score => new_score.score, :reviewer_role => new_score.reviewer_role, :comment => new_score.comment)
if new_score.reviewer_role == 1
@ -190,7 +271,7 @@ module StudentWorkHelper
ts_score = StudentWorksScore.find_by_sql("SELECT AVG(score) AS score FROM (SELECT * FROM (SELECT * FROM student_works_scores WHERE student_work_id = #{st_work.id} AND reviewer_role = 2 AND score IS NOT NULL ORDER BY created_at DESC) AS t GROUP BY user_id) AS a")
st_work.teaching_asistant_score = ts_score.first.score.nil? ? nil : ts_score.first.score.try(:round, 2).to_f
else
st_work.student_score = student_work.student_score
st_work.student_score = member_work.student_score
end
st_work.save
end

View File

@ -0,0 +1,23 @@
module SubjectsHelper
def subject_co_users subject
shixuns = Shixun.where(:id => subject.stage_shixuns.map(&:shixun_id))
co_users = User.where(:id => shixuns.map(&:user_id)).where("id != #{subject.user_id}")
end
def subject_data subject
result = {}
subject_choices = 0
subject_shixuns = 0
subject_score = 0
subject.stage_shixuns.each do |stage_shixun|
shixun = stage_shixun.shixun
subject_choices += shixun.challenges.where(:st => [1, 2]).count
subject_shixuns += shixun.challenges.where(:st => 0).count
subject_score += shixun.shixun_score
end
result[:subject_choices] = subject_choices
result[:subject_shixuns] = subject_shixuns
result[:subject_score] = subject_score
result
end
end

View File

@ -51,36 +51,33 @@ module SyllabusesHelper
count
end
#课程性质下拉框
def syllabus_type
type = []
def syllabus_type_option
content = []
option0 = []
option0 << "请选择课程性质"
option0 << 0
option1 = []
option1 << "专业选修课"
option1 << 3
option2 = []
option2 << "学科必修课"
option2 << 2
option3 = []
option3 << "公共必修课"
option3 << 1
option4 = []
option4 << "实践选修课"
option4 << 5
option5 = []
option6 = []
option1 << "请选择"
option1 << 0
option2 << "公共必修课"
option2 << 1
option3 << "学科必修课"
option3 << 2
option4 << "专业选修课"
option4 << 3
option5 << "实践必修课"
option5 << 4
option6 << "实践选修课"
option6 << 5
type << option1
type << option2
type << option3
type << option4
type << option5
type << option6
type
content << option0
content << option1
content << option2
content << option3
content << option4
content << option5
content
end
end

View File

@ -325,11 +325,11 @@ module UsersHelper
url = {:controller => 'users', :action => 'update', :id => user, :page => params[:page], :status => params[:status], :tab => nil}
if user.locked?
link_to l(:button_unlock), url.merge(:user => {:status => User::STATUS_ACTIVE}), :method => :put, :class => 'icon icon-unlock'
link_to "解锁", url.merge(:user => {:status => User::STATUS_ACTIVE}), :method => :put, :class => 'mr10 link-color-blue'
elsif user.registered?
link_to l(:button_activate), url.merge(:user => {:status => User::STATUS_ACTIVE}), :method => :put, :class => 'icon icon-unlock'
elsif user != User.current
link_to l(:button_lock), url.merge(:user => {:status => User::STATUS_LOCKED}), :method => :put, :class => 'icon icon-lock'
link_to "加锁", url.merge(:user => {:status => User::STATUS_LOCKED}), :method => :put, :class => 'mr10 link-color-blue'
end
end

View File

@ -262,11 +262,25 @@ module WatchersHelper
content.present? ? content_tag('ul', content, :class => 'watchers') : content
end
#用户关注、取消关注
def watcher_link_for_user(target, user)
return '' unless user && user.logged?
watched = target.watched_by?(user)
text = watched ? '已关注' : '添加关注'
url = watch_path(:object_type => 'user',
:object_id => target.id,
:target_id => target.id)
method = watched ? 'delete' : 'post'
id = watched ? 'cancel_watch' : ''
title = watched ? '取消关注' : '已关注'
if target != user
link_to text, url, :remote => true, :method => method, :remote => true,
:class => "fr font-14 user_watch",:id => id, :title => title
else
link_to "关注", "javascript:void(0)", :remote => true, :method => method,
:class => "fr font-14 user_watch", :id => id, :title => title
end
end
# 缺陷跟踪者列表复选框生成
def watchers_checkboxes(object, users, checked=nil)

View File

@ -22,6 +22,23 @@ module WelcomeHelper
include CoursesHelper
include ProjectsHelper
def color_change index
case index
when 0
"edu-index-bg-green"
when 1
"edu-index-bg-blue"
when 2
"edu-index-bg-purple"
when 3
"edu-index-bg-yellow"
when 4
"edu-index-bg-orange"
when 5
"edu-index-bg-green"
end
end
def get_timestamp(obj)
if obj.respond_to? :updated_on
:updated_on

View File

@ -4,6 +4,7 @@ class AppliedMessage < ActiveRecord::Base
attr_accessible :applied_id, :applied_type, :status, :user_id, :viewed, :applied_user_id, :role, :project_id, :name
belongs_to :applied ,:polymorphic => true
belongs_to :apply_add_schools
belongs_to :apply_add_department
belongs_to :user
has_many :message_alls, :class_name => 'MessageAll', :as =>:message, :dependent => :destroy

View File

@ -0,0 +1,6 @@
# status0 审核中 1 同意 2 拒绝 3 撤销
class ApplyAction < ActiveRecord::Base
default_scope :order => 'updated_at desc'
attr_accessible :container_id, :container_type, :dealer_id, :reason, :user_id, :status, :apply_reason
belongs_to :user
end

View File

@ -0,0 +1,8 @@
class ApplyAddDepartment < ActiveRecord::Base
belongs_to :school
belongs_to :user
attr_accessible :name, :remarks, :status, :school_id, :user_id, :department_id
has_many :applied_messages, :class_name =>'AppliedMessage', :as => :applied
belongs_to :department
# status: 0表示未批准 status1表示已批准 status 2表示已更改 status 3表示已拒绝 status: 4表示已更改后废除的部门
end

View File

@ -1,8 +1,8 @@
class ApplyAddSchools < ActiveRecord::Base
# status0 未审批 1 已批阅
attr_accessible :address, :city, :name, :province, :remarks, :school_id, :status
has_many :applied_messages, :class_name =>'AppliedMessage', :as => :applied
belongs_to :school
#after_create :send_massage
end
class ApplyAddSchools < ActiveRecord::Base
# status0 未审批 1 已批阅, :2 已拒绝
attr_accessible :address, :city, :name, :province, :remarks, :school_id, :status
has_many :applied_messages, :class_name =>'AppliedMessage', :as => :applied
belongs_to :school
#after_create :send_massage
end

View File

@ -0,0 +1,6 @@
class ApplyUserAuthentication < ActiveRecord::Base
belongs_to :user
# status0 审核中 1 同意 2 拒绝 3 撤销
# auth_type1 实名认证, 2 职业认证
attr_accessible :auth_type, :dealer, :deal_time, :remarks, :status, :user_id
end

View File

@ -21,6 +21,7 @@ require 'elasticsearch/model'
class Attachment < ActiveRecord::Base
belongs_to :container, :polymorphic => true
belongs_to :project, foreign_key: 'container_id', conditions: "attachments.container_type = 'Project'"
belongs_to :shixun, foreign_key: 'container_id', conditions: "attachments.container_type = 'Shixun'"
belongs_to :course, foreign_key: 'container_id', conditions: "attachments.container_type = 'Course'"
belongs_to :org_subfield, foreign_key: 'container_id', conditions: "attachements.container_type = 'OrgSubfield'"
belongs_to :organization, foreign_key: 'container_id', conditions: "attachements.container_type = 'Organization'"
@ -28,6 +29,7 @@ class Attachment < ActiveRecord::Base
belongs_to :softapplication, foreign_key: 'container_id', conditions: "attachments.container_type = 'Softapplication'"
belongs_to :author, :class_name => "User", :foreign_key => "author_id"
belongs_to :attachmentstype, :foreign_key => "attachtype",:primary_key => "id"
belongs_to :resource_bank
# 被ForgeActivity虚拟关联
has_many :forge_acts, :class_name => 'ForgeActivity',:as =>:forge_act ,:dependent => :destroy
has_many :forwards, :as => :from, :dependent => :destroy

View File

@ -0,0 +1,8 @@
class Authentication < ActiveRecord::Base
attr_accessible :level, :permissions
serialize :permissions, Array
has_and_belongs_to_many :users
# has_many :users_authenticationses
# has_many :users, :through => :users_authenticationses
end

View File

@ -0,0 +1,3 @@
class AuthenticationsUsers < ActiveRecord::Base
attr_accessible :authentication_id, :user_id
end

View File

@ -2,8 +2,8 @@ class Blog < ActiveRecord::Base
# attr_accessible :title, :body
include Redmine::SafeAttributes
belongs_to :user
has_many :articles, :class_name => 'BlogComment', :conditions => "#{BlogComment.table_name}.parent_id IS NULL ", :order => "#{BlogComment.table_name}.created_on DESC"
has_many :blog_comments, :dependent => :destroy, :order => "#{BlogComment.table_name}.created_on DESC"
has_many :articles, :class_name => 'BlogComment', :conditions => "#{BlogComment.table_name}.parent_id IS NULL ", :order => "#{BlogComment.table_name}.created_at DESC"
has_many :blog_comments, :dependent => :destroy, :order => "#{BlogComment.table_name}.created_at DESC"
belongs_to :last_comment, :class_name => 'BlogComment', :foreign_key => :last_comment_id
acts_as_tree :dependent => :nullify
#acts_as_list :scope => '(user_id = #{user_id} AND parent_id #{user_id ? = "#{parent_id}" : "IS NULL"})'

View File

@ -20,7 +20,7 @@ class BlogComment < ActiveRecord::Base
validates_presence_of :title, :content
validates_length_of :title, :maximum => 255
#validate :cannot_reply_to_locked_comment, :on => :create
safe_attributes 'title', 'content',"sticky", "locked", "root_id"
safe_attributes 'title', 'content',"sticky", "locked", "root_id", 'visits'
after_save :add_user_activity
after_update :update_activity

View File

@ -1,3 +1,5 @@
#coding=utf-8
# st 0实践任务1选择题任务
class Challenge < ActiveRecord::Base
default_scope :order => 'position'
belongs_to :shixun,:touch=> true
@ -6,22 +8,85 @@ class Challenge < ActiveRecord::Base
has_many :test_sets, :dependent => :destroy
has_many :challenge_tags, :dependent => :destroy
has_many :games, :dependent => :destroy
has_many :challenge_chooses, :dependent => :destroy
validates_presence_of :subject
validates_presence_of :score
# validates_presence_of :score
validates_presence_of :task_pass
validates_length_of :subject, :maximum => 255
def game_difficulty
str = "简单"
case self.difficulty
when 1
str = "简单"
when 2
str = "中等"
when 3
str = "困难"
end
str
end
def choose_correct_num
num = 0
self.challenge_chooses.each do |choose|
outputs = ChooseOutputs.where(:challenge_choose_id => choose.id, :user_id => User.current.id).first
if outputs.nil?
num = nil
else
num += (outputs.correct ? 1 : 0)
end
end
return num
end
def choose_score
score = 0
self.challenge_chooses.each do |choose|
score += choose.score.to_i
end
return score
end
def choose_tags_num
num = 0
self.challenge_chooses.each do |choose|
num += choose.challenge_tags.count
end
return num
end
def next_challenge
challenge_count = Challenge.where(:shixun_id => self.shixun_id).count
render_404 if self.position ==challenge_count
Challenge.where(:position => (self.position + 1), :shixun_id => self.shixun).first
end
def prev_challenge
render_404 if self.position == 1
Challenge.where(:position => (self.position - 1), :shixun_id => self.shixun).first
end
def last_challenge
render_404 if self.position < 2
position = self.position - 1
Challenge.where(:position => position, :shixun_id => self.shixun).first
end
def current_user_game
myshixun = Myshixun.where(:shixun_id => self.shixun.id, :user_id => User.current.id).first
game = Game.where(:myshixun_id => myshixun, :challenge_id => self.id).first
end
# 正确答案
def right_answers
answer = ""
self.challenge_questions.each do |ans|
if ans.right_key
answer << (ans.position + 65).chr
end
end
return answer
end
end

View File

@ -0,0 +1,19 @@
class ChallengeChoose < ActiveRecord::Base
# attr_accessible :title, :body
# category 1 单选, 2多选
# standard_answer 正确答案 answer 答题的思路
default_scope :order => 'position'
belongs_to :challenge
has_many :challenge_tags, :dependent => :destroy
has_many :challenge_questions, :dependent => :destroy
has_one :choose_outputs, :dependent => :destroy
#has_many :outputs, :dependent => :destroy
validates_presence_of :subject
# 判断当前用户是否答题
def current_choose_outputs
ChooseOutputs.where(:challenge_choose_id => self.id, :user_id => User.current.id).first
end
end

View File

@ -0,0 +1,6 @@
class ChallengeQuestion < ActiveRecord::Base
# 选择题的选项内容
belongs_to :challenge_choose
# right_key 选项是否是答案, position 选项的位置
attr_accessible :challenge_choose_id, :option_name, :position, :right_key
end

View File

@ -1,4 +1,5 @@
class ChallengeTag < ActiveRecord::Base
attr_accessible :challenge_id, :name
attr_accessible :challenge_id, :name, :challenge_choose_id
belongs_to :challenge
belongs_to :challenge_choose
end

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