diff --git a/README.rdoc b/README.rdoc
index b237aa4..eea1a0d 100644
--- a/README.rdoc
+++ b/README.rdoc
@@ -1,3 +1,3 @@
-= Bulletin
+= CurationPost
This project rocks and uses MIT-LICENSE.
\ No newline at end of file
diff --git a/Rakefile b/Rakefile
index ccd84f8..efcca7b 100644
--- a/Rakefile
+++ b/Rakefile
@@ -8,7 +8,7 @@ require 'rdoc/task'
RDoc::Task.new(:rdoc) do |rdoc|
rdoc.rdoc_dir = 'rdoc'
- rdoc.title = 'Announcement'
+ rdoc.title = 'Curation'
rdoc.options << '--line-numbers'
rdoc.rdoc_files.include('README.rdoc')
rdoc.rdoc_files.include('lib/**/*.rb')
diff --git a/announcement.gemspec b/announcement.gemspec
deleted file mode 100644
index fa041d1..0000000
--- a/announcement.gemspec
+++ /dev/null
@@ -1,339 +0,0 @@
-# encoding: UTF-8
-$:.push File.expand_path("../lib", __FILE__)
-# Maintain your gem's version:
-require "announcement/version"
-require 'json'
-require 'yaml'
-require 'fileutils'
-bundle_update_flag = ARGV[0]=='update' || ARGV[0]=='install'
-if bundle_update_flag
- env_pwd = ENV['PWD']
- begin
- require ::File.expand_path('app/helpers/bundler_helper.rb', env_pwd)
- extend BundlerHelper
- rescue LoadError
- def bundler_with_clean_env(&block)
- if block_given?
- if Bundler.respond_to?(:with_unbundled_env)
- Bundler.with_unbundled_env(&block)
- else
- Bundler.with_clean_env(&block)
- end
- end
- end
- end
- if File.exist?("#{env_pwd}/app/models/google.rb")
- FileUtils.rm("#{env_pwd}/app/models/google.rb", :force => true)
- end
- if Dir.exist?("#{env_pwd}/app/models/concern")
- FileUtils.rm_r("#{env_pwd}/app/models/concern", :force => true)
- end
- app_path = File.expand_path(__dir__)
- template_path = env_pwd + '/app/templates'
- all_template = Dir.glob(template_path+'/*/')
- puts 'editing files for sassc'
- use_local_gemfile = File.exist?(env_pwd + '/.use_local_gemfile')
- new_gemfile_text = File.read(app_path+'/temp_file/Gemfile')
- old_gemfile_text = File.read(env_pwd+'/Gemfile')
- check_texts = ['@import "../../bootstrap/variables";',".response-content {\n justify-self: auto;\n}\n"]
- git_url = bundler_with_clean_env{%x[cd '#{env_pwd}' && git config --get remote.origin.url].split("\n")[0]}
- git_remote = bundler_with_clean_env{%x[cd '#{env_pwd}' && git remote].split("\n")[0]}
- if !(git_url.include?('//ruling.digital/git')) && !(File.exist?("#{env_pwd}/custom_git.txt"))
- puts 'changing remote url'
- bundler_with_clean_env{system("cd #{env_pwd} && git remote set-url #{git_remote} https://ruling.digital/git")}
- end
- default_announcement_widget_info = JSON.parse(File.read("#{app_path}/modules/announcement/info.json"))["widgets"].sort_by{|h| h["filename"].to_i} rescue []
- all_template.each do |folder|
- if !folder.include?('mobile')
- begin
- if folder.split('/')[-1] != 'mobile'
- bundler_with_clean_env{%x[cp -rf #{app_path}/temp_file/templates/javascripts/* #{folder}assets/javascripts/plugin/.]}
- unity_text = File.open(folder+'assets/stylesheets/template/base/_unity.scss','r:UTF-8') do |f|
- f.read
- end rescue ''
- if unity_text.split(/\n/).join.strip.empty?
- File.open(folder+'assets/stylesheets/template/base/_unity.scss', 'a') do |file|
- file.puts "@charset \"utf-8\";\n\n@import \"variables\";\n\n// Title\n.unity-title {\n margin: 0.5em 0;\n line-height: 1.5;\n font-family: $main-font;\n font-size: $font-h1;\n\n .layout-footer & {\n margin-bottom: 10px;\n border-bottom: none;\n\n span {\n display: inline;\n margin-bottom: 0;\n border-bottom: none;\n }\n }\n}\n\n.status {\n font-family: $main-font;\n font-size: 0.75rem;\n}\n\n.status-top {\n background-color: $theme-color-second;\n}\n\n.status-hot {\n background-color: $theme-color-third;\n}\n\n.status-source {\n background-color: $theme-color-main;\n\n a {\n color: $theme-white;\n }\n}\n"
- end
- end
- filename = folder+'assets/stylesheets/template/base/_variables.scss'
- texts = File.open(filename,'r:UTF-8') do |f|
- f.read
- end.force_encoding('UTF-8').gsub(/(\r\n){2,}/, "\r\n")
- s1 = texts.scan(/{|}/)
- if s1.count % 2 != 0
- i = texts.rindex(s1[-1])
- texts[i] = ""
- end
- regex_pattern = /((?=^)[ \t\r\n]*)*\.response-content {\n justify-self: auto;\n}[\r\n]*|((?=^)[ \t\r\n]*)*\.response-content {\n position: static;\n}[\r\n]*|((?=^)[ \t\r\n]*)*\.response-content {\n position: relative;\n}[\r\n]*/m #|((?=^)[ \t\r\n]*)*\.response-content[^{]*{[^}]*@media[^{]*{[^{]*}[^{]*@media[^{]*{[^{]*}[^}]*}[^}]*}
- if !texts.include? "$font-h1:"
- texts = "$font-h1: 1.5rem;\n$font-h2: 1.35rem;\n$font-h3: 1.2rem;\n$font-h4: 1.1rem;\n$font-h5: 1rem;\n$font-h6: 0.9rem;\n\n" + texts
- end
- if !texts.include? "$main-font:"
- texts = "$main-font: Arial, \"微軟正黑體\", \"Helvetica Neue\", Helvetica, sans-serif;\n" + texts
- end
- if !texts.include? "$theme-white"
- texts = "$theme-white: #fff;\n" + texts
- end
- File.open(filename,'w') do |f|
- f.write texts
- end
- tp_text = File.read(folder+'assets/stylesheets/template/template.scss').force_encoding('UTF-8') rescue ''
- tp_last_text = tp_text
- tp_text.scan(/@import.*http.*;/).each do |pat|
- if pat.scan(/@import\W+url/).count==0
- pat1 = pat.sub(/@import\W/,"@import url(")
- pat1 = pat1.sub(/;/,");")
- tp_last_text = tp_last_text.sub(pat,pat1)
- end
- end
- if tp_last_text != tp_text
- File.open(folder+'assets/stylesheets/template/template.scss','w') do |f|
- f.write tp_last_text
- end
- end
- texts = texts.gsub(/\n{2,}/,"\n")
- auto_save_array = texts.scan(regex_pattern)
- if auto_save_array.count > 1
- auto_save_text = auto_save_array.join('')
- File.open(folder+'assets/stylesheets/template/base/_autobackup.bak', 'a') do |file|
- file.puts auto_save_text
- end
- texts = texts.gsub(regex_pattern,"")
- File.open(filename, 'w') do |file|
- file.write (texts)
- end
- end
- check_texts.each do |check_text|
- if !texts.include?(check_text)
- puts "editing #{folder}assets/stylesheets/template/base/_variables.scss"
- texts = texts + "\n" + check_text
- File.open(filename, 'w') do |file|
- file.write(texts)
- end
- end
- end
- end
- rescue => e
- puts "not found #{folder}assets/stylesheets/template/base/_variables.scss"
- end
- begin
- puts "updating announcement show page"
- bundler_with_clean_env{%x[cp -f #{app_path}/modules/announcement/show.html.erb #{folder}modules/announcement/show.html.erb]}
- rescue
- puts "There has some error in updating announcement show page"
- end
- info_json_file = "#{folder}modules/announcement/info.json"
- if File.exist?(info_json_file)
- begin
- file_text = File.read(info_json_file) rescue ""
- encode_file_text = file_text.encode("UTF-8", "UTF-8", invalid: :replace, replace: "???")
- next if (encode_file_text.include?("???") rescue true)
- info = JSON.parse(encode_file_text) rescue {}
- flag = (info.count != 0 rescue false)
- if flag
- puts "Checking announcement widgets"
- widget_info = info["widgets"].sort_by{|h| h["filename"].to_i} rescue []
- update_flag = false
- last_index = widget_info.collect{|v| v["filename"].to_s.scan(/\d+/).collect{|v1| v1.to_i}}.flatten.sort[-1] rescue nil
- if !last_index.nil?
- idx_regex = /^(\d+[\. \t]*)|[ \t]+$/
- default_announcement_widget_info.each do |h|
- name_without_index = h["name"]["zh_tw"].gsub(idx_regex,'')
- widget_info_index = (widget_info.index{|hh| hh["name"]["zh_tw"].gsub(idx_regex,'') == name_without_index}||-1 rescue -1)
- if (widget_info_index == -1 || widget_info_index.nil?)
- update_flag = true
- copy_h = h.dup
- h.delete("force_cover")
- last_index = last_index + 1
- copy_h["filename"] = copy_h["filename"].sub(/\d+/){|ff| last_index.to_s}
- copy_h["name"].keys.each do |locale|
- copy_h["name"][locale] = copy_h["name"][locale].sub(/\d+/){|ff| last_index.to_s}
- end
- widget_info << copy_h
- bundler_with_clean_env{%x[cp -f #{app_path}/modules/announcement/_#{h["filename"]}.html.erb #{folder}modules/announcement/_#{copy_h["filename"]}.html.erb]}
- elsif h["force_cover"] == "true"
- bundler_with_clean_env{%x[cp -f #{app_path}/modules/announcement/_#{h["filename"]}.html.erb #{folder}modules/announcement/_#{widget_info[widget_info_index]["filename"]}.html.erb]}
- end
- end
- if update_flag
- info["widgets"] = widget_info
- puts "Writing json #{info["widgets"].count} in #{info_json_file}"
- begin
- info_json = JSON.pretty_generate(info).gsub(":[",":[\n").gsub(":{",":{\n")
- rescue
- info_json = info.to_s.gsub("=>",": \n")
- end
- File.open(info_json_file,"w+"){|f| f.write(info_json)}
- end
- bundler_with_clean_env{%x[cp -rn #{app_path}/modules/announcement/thumbs/* #{folder}modules/announcement/thumbs/.]}
- end
- end
- rescue => e
- puts e
- puts "There has some error when checking announcement widgets"
- end
- end
- end
- end
- if !use_local_gemfile && old_gemfile_text != new_gemfile_text
- unicorn_rails = %x[which unicorn_rails].sub("\n",'')
- puts 'updating gemfile'
- if Dir["#{env_pwd}/config/secrets.yml"].length==0
- r = open("#{env_pwd}/config/environment.rb",'r'){|f| f.read()}
- secret_key = r.scan(/Orbit::Application\.config\.secret_key_base = '(.*)'/).flatten[0] rescue nil
- if !secret_key.nil?
- open("#{env_pwd}/config/secrets.yml",'w+') do |f|
- c = {"production"=> {"secret_key_base"=> secret_key},"development"=> {"secret_key_base"=> secret_key}}
- c = c.to_yaml.sub("---\n",'')
- f.write(c)
- end
- end
- end
- bundler_with_clean_env{%x[cp -f '#{env_pwd}'/Gemfile '#{env_pwd}'/Gemfile.bak123]}
- bundler_with_clean_env{%x[cp -f '#{app_path}'/temp_file/Gemfile '#{env_pwd}'/Gemfile]}
- check_version = %x[cd #{env_pwd} && git rev-list `git rev-parse --abbrev-ref HEAD` | grep 2f23511469505bd114df2c863a477a8730bcdefa]
- if check_version.strip != '' #update mongoid version
- command4 = ""
- puts 'mongoid has been updated!'
- else
- command4 = ";mv #{env_pwd}/app/controllers/sessions_controller.rb #{env_pwd}/tmp/sessions_controller_backup.rb;cp -rf #{app_path}/temp_file/app #{env_pwd};cp -rf #{app_path}/temp_file/config #{env_pwd};rm #{env_pwd}/app/models/google.rb"
- end
- log_development = File.mtime(env_pwd+'/log/development.log').strftime('%Y%m%d%H%M').to_i rescue 0
- log_production = File.mtime(env_pwd+'/log/production.log').strftime('%Y%m%d%H%M').to_i rescue 0
- if log_development > log_production
- mode = 'development'
- else
- mode = 'production'
- end
- files = Dir[env_pwd+'/Gemfile.lock']
- dir_name = env_pwd.split('/')[-1]
- watch_dog = %x[screen -ls auto_reopen_#{dir_name}]
- if watch_dog.scan("auto_reopen_#{dir_name}").count != 0
- bundler_with_clean_env{%x[screen -ls | grep auto_reopen_#{dir_name} | cut -d. -f1 | awk '{print $1}' | xargs kill]}
- end
- if %x[ruby -v].scan(/\d\.\d\.\d/)[0] == '2.1.3'
- install_cmd = 'rvm install 2.1.10 && rvm use default 2.1.10;'
- use_cmd = 'source ~/.rvm/scripts/rvm && rvm use 2.1.10 --default;'
- else
- install_cmd = ''
- use_cmd = ''
- end
- #if files.count ==0
- # command1 = "gem install bundler -v 1.17.3 ; bundle update --all"
- #else
- if RUBY_VERSION.to_f==2.1
- command1 = "gem install bundler -v 1.17.3 ; bundle update --all"
- #else
- #command1 = "gem install bundler -v 2.3.3 ; bundle update --all"
- end
- #end
- filedata = File.read(env_pwd+"/built_in_extensions.rb")
- exist_str = "gem 'patchfile', git: 'http://gitlab.tp.rulingcom.com/chiu/patch_file.git'"
- if filedata.include? exist_str
- puts "patchfile exist"
- else
- file = env_pwd+"/built_in_extensions.rb"
- open(file, 'a') { |f|
- f.puts exist_str
- }
- end
- all_command = "#{install_cmd} #{command1} #{command4} "
- watch_dog_cmd = "watch -n 30 \'unset UNICORN_FD && bundle exec #{unicorn_rails} -c config/unicorn.rb -D -E #{mode}\'"
- #file = File.new(File.join(env_pwd,'bundle_update_background.sh'),"w")
- #file.write(all_command)
- #file.chmod(0755)
- #file.close
- restart_cmd = "UNICORN_PID=\"`fuser tmp/pids/unicorn.sock tmp/sockets/unicorn.sock tmp/unicorn.sock` `cat tmp/pids/unicorn.pid `\" && kill -s TERM $UNICORN_PID ; while (kill -0 $UNICORN_PID > /dev/null 2>&1) ; do printf '.' && sleep 1 ; done ; unset UNICORN_FD; bundle exec unicorn_rails -c config/unicorn.rb -D -E #{mode}"
-
- a = Thread.start do
- bundler_with_clean_env do
- puts env_pwd
- puts mode
- exec("cd #{env_pwd} && env -i HOME=\"$HOME\" bash -l -c \"#{all_command}\" ;screen -d -m -S auto_reopen_#{dir_name} bash -c \"#{use_cmd} #{restart_cmd};#{watch_dog_cmd}\" ")
- end
- end
- now_priority = Thread.current.priority.to_i
- system('sleep 2')
- a.priority = now_priority + 2
- a.run
- #Thread.exit
- else
- dir_name = env_pwd.split('/')[-1]
- watch_dog = %x[screen -ls auto_reopen_#{dir_name}]
- if watch_dog.scan("auto_reopen_#{dir_name}").count != 0
- bundler_with_clean_env{%x[screen -ls | grep auto_reopen_#{dir_name} | cut -d. -f1 | awk '{print $1}' | xargs kill]}
- end
- #system("cp -rf #{app_path}/temp_file/app #{env_pwd}")
- end
- c = open("#{env_pwd}/config/mongoid.yml",'r'){|f| f.read}
- if c.scan(/^[ \t]*sessions\:/).length != 0
- c = c.gsub(/^([ \t]*)sessions\:/,'\1clients:')
- r = YAML.load(c)
- r.each do |mode,v1|
- v1.each do |clients,d|
- d.each do |k,v|
- next if v.class != Hash
- if !v["username"].nil?
- if v["options"].nil?
- v["options"] = {}
- end
- v["options"]["user"] = v["username"]
- v.delete "username"
- end
- if !v["password"].nil?
- if v["options"].nil?
- v["options"] = {}
- end
- v["options"]["password"] = v["password"]
- v.delete "password"
- end
- if !v["options"].nil? && !v["options"]["pool_size"].nil?
- v["options"]["max_pool_size"] = v["options"]["pool_size"]
- v["options"].delete "pool_size"
- end
- if !v["options"].nil? && v["options"]["read"].class == String
- v["options"]["read"] = {"mode"=> v["options"]["read"]}
- end
- end
- end
- end
- c = YAML.dump(r).sub("---\n",'')
- open("#{env_pwd}/config/mongoid.yml",'w+'){|f| f.write(c)}
- end
- if !File.exist?("#{env_pwd}/.carrierwave_upgraded")
- upgrading = File.exist?("#{env_pwd}/.carrierwave_upgrading")
- File.open("#{env_pwd}/.carrierwave_upgrading", "w") {}
- uploaders = Dir.chdir(env_pwd){ Dir.glob("app/uploaders/*") }
- uploaders.each do |uploader|
- if upgrading
- bundler_with_clean_env{%x[cd #{env_pwd} && git checkout -- #{uploader}]}
- end
- uploader_contents = File.read("#{env_pwd}/#{uploader}")
- uploader_contents.gsub!(/^[ \t]*require[ \t]+['"]carrierwave\/processing\/mime_types['"][ \t]*$/, '')
- uploader_contents.gsub!(/^[ \t]*include[ \t]+CarrierWave::MimeTypes[ \t]*$/, '')
- File.open("#{env_pwd}/#{uploader}", "w"){|f| f.write(uploader_contents)}
- end
- File.open("#{env_pwd}/.carrierwave_upgraded", "w") {}
- end
-end
-# Describe your gem and declare its dependencies:
-Gem::Specification.new do |s|
- s.name = "announcement"
- s.version = Announcement::VERSION
- s.authors = ["RulingDigital"]
- s.email = ["orbit@rulingcom.com"]
- s.homepage = "http://www.rulingcom.com"
- s.summary = "Announcements for Orbit"
- s.description = "Announcements for Orbit"
- s.license = "MIT"
- s.metadata = {
- "_require" => "#{File.expand_path("../app/models/announcement_setting", __FILE__)}",
- "global_hash" => "{enable_manually_sort: (AnnouncementSetting.first.enable_manually_sort rescue false),enable_annc_dept: (AnnouncementSetting.first.enable_annc_dept rescue false), annc_depts_translations: (AnnouncementSetting.first.annc_depts_translations rescue {})}"
- }
- s.files = Dir["{app,config,db,lib}/**/*", "MIT-LICENSE", "Rakefile", "README.rdoc"]
- s.test_files = Dir["test/**/*"]
-
- s.add_dependency "rufus-scheduler", "~> 3.6.0"
- s.add_dependency "mimemagic" , "0.3.9"
-end
diff --git a/app/controllers/admin/announcements_controller.rb b/app/controllers/admin/curations_controller.rb
similarity index 52%
rename from app/controllers/admin/announcements_controller.rb
rename to app/controllers/admin/curations_controller.rb
index 316818d..450e4d2 100644
--- a/app/controllers/admin/announcements_controller.rb
+++ b/app/controllers/admin/curations_controller.rb
@@ -1,67 +1,67 @@
# encoding: utf-8
require 'rubyXL'
-class Admin::AnnouncementsController < OrbitAdminController
- include Admin::AnnouncementsHelper
+class Admin::CurationsController < OrbitAdminController
+ include Admin::CurationsHelper
before_action ->(module_app = @app_title) { set_variables module_app }
before_action :set_bulletin, only: [:edit, :destroy, :comment]
before_action :load_access_level, :load_settings
before_action :set_module_pages, only: [:edit,:new]
def set_module_pages
- @module_pages = Page.where(:module => 'announcement').collect{|p| [p.name,p.id] }
+ @module_pages = Page.where(:module => 'curation').collect{|p| [p.name,p.id] }
end
def initialize
super
- @app_title = "announcement"
+ @app_title = "curation"
end
def update_sort
ids = params[:ids]
ids.each_with_index do |id,i|
- Bulletin.where(id: id).update(sort_number: i)
+ CurationPost.where(id: id).update(sort_number: i)
end
- AnnsCache.all.delete
+ CurationCache.all.delete
edit_sort
render 'update_sort',layout: false
-
+
end
def update_sort_setting
setting = @announcement_setting
setting.update_attributes(settings_params)
if defined?(OrbitHelper::SharedHash) && OrbitHelper::SharedHash
- OrbitHelper::SharedHash['announcement'][:enable_manually_sort] = setting.enable_manually_sort
+ OrbitHelper::SharedHash['curation'][:enable_manually_sort] = setting.enable_manually_sort
end
- redirect_to edit_sort_admin_announcement_path
+ redirect_to edit_sort_admin_curation_path
end
-
+
def edit_sort
- @setting = AnnouncementSetting.first
- @announcements = Bulletin.where(is_top: true).order_by({is_top: -1,sort_number: 1,postdate: -1, _id: -1})
- @table_fields = ['announcement.table.sort_number','announcement.table.title','announcement.default_widget.postdate']
+ @setting = CurationSetting.first
+ @announcements = CurationPost.where(is_top: true).order_by({is_top: -1,sort_number: 1,postdate: -1, _id: -1})
+ @table_fields = ['curation.table.sort_number','curation.table.title','curation.default_widget.postdate']
end
def comment_hidden
- b = BulletinComment.find(params[:id]) rescue nil
+ b = CurationPostComment.find(params[:id]) rescue nil
if !b.nil?
b.is_hidden = !b.is_hidden
b.save
- @table_feed_fields = ["announcement.time", "announcement.comment", "announcement.account","ip","is_hidden"]
- @comments = b.bulletin.bulletin_comments.reverse rescue []
+ @table_feed_fields = ["curation.time", "curation.comment", "curation.account","ip","is_hidden"]
+ @comments = b.curation_post.curation_post_comments.reverse rescue []
render partial: 'comment'
end
end
def comment
- @table_feed_fields = ["announcement.time", "announcement.comment", "announcement.account","ip","is_hidden"]
- @comments = @bulletin.bulletin_comments.reverse rescue []
+ @table_feed_fields = ["curation.time", "curation.comment", "curation.account","ip","is_hidden"]
+ @comments = @bulletin.curation_post_comments.reverse rescue []
end
def index
- Bulletin.remove_expired_status
+ CurationPost.remove_expired_status
@tags = @module_app.tags
- @table_fields = [:status, :category, :title, :start_date, :end_date, "announcement.comment", :last_modified]
- setting = AnnouncementSetting.first
+ @table_fields = [:status, :category, :title, :start_date, :end_date, "curation.comment", :last_modified]
+ setting = CurationSetting.first
@annc_depts = []
@enable_annc_dept = false
if (setting.enable_annc_dept rescue false)
- @table_fields.insert(1, "announcement.annc_dept")
+ @table_fields.insert(1, "curation.annc_dept")
@annc_depts = setting.annc_depts
@enable_annc_dept = true
end
@@ -71,55 +71,55 @@ class Admin::AnnouncementsController < OrbitAdminController
if current_user_is_sub_manager
@categories = current_user.approved_categories.select{|c| c.module_app_id == @module_app.id} rescue []
@filter_fields = filter_fields(@categories, @tags)
- @bulletins = Bulletin.where(:create_user_id=>current_user.id,:is_preview.in=>[false,nil])
+ @bulletins = CurationPost.where(:create_user_id=>current_user.id,:is_preview.in=>[false,nil])
.order_by(sort)
.with_categories(filters("category"))
.with_tags(filters("tag"))
.with_status(filters("status"))
else
- @bulletins = Bulletin.where(:uid=>nil)
+ @bulletins = CurationPost.where(:uid=>nil)
@categories = @module_app.categories.enabled
@filter_fields = filter_fields(@categories, @tags)
end
else
@categories = @module_app.categories.enabled
@filter_fields = filter_fields(@categories, @tags)
- @bulletins = Bulletin.where(:is_preview.in=>[false,nil])
+ @bulletins = CurationPost.where(:is_preview.in=>[false,nil])
.order_by(sort)
.with_categories(filters("category"))
.with_tags(filters("tag"))
.with_status(filters("status"))
end
@bulletins = search_data(@bulletins,[:title]).page(params[:page]).per(10)
-
+
if request.xhr?
render :partial => "index"
end
end
def get_all_anncs_without_subannc
- Bulletin.remove_expired_status
+ CurationPost.remove_expired_status
@tags = @module_app.tags
@table_fields = [:category, :title, :start_date]
@current_user = current_user
- if AnnouncementSetting.first.is_display_edit_only && !current_user.is_admin? && !current_user.is_manager?(@module_app)
+ if CurationSetting.first.is_display_edit_only && !current_user.is_admin? && !current_user.is_manager?(@module_app)
current_user_is_sub_manager = !current_user.is_manager?(@module_app) && (current_user.is_sub_manager?(@module_app) || current_user.is_sub_manager_with_role?(@module_app)) rescue false
if current_user_is_sub_manager
@categories = current_user.approved_categories.select{|c| c.module_app_id == @module_app.id} rescue []
@filter_fields = filter_fields(@categories, @tags)
- @bulletins = Bulletin.where(:create_user_id=>current_user.id,:title.ne => "",:is_preview.in=>[false,nil])
+ @bulletins = CurationPost.where(:create_user_id=>current_user.id,:title.ne => "",:is_preview.in=>[false,nil])
.order_by(sort)
.with_categories(filters("category"))
.with_tags(filters("tag"))
.with_status(filters("status"))
else
- @bulletins = Bulletin.where(:uid=>nil)
+ @bulletins = CurationPost.where(:uid=>nil)
@categories = @module_app.categories.enabled
@filter_fields = filter_fields(@categories, @tags)
end
else
@categories = @module_app.categories.enabled
@filter_fields = filter_fields(@categories, @tags)
- @bulletins = Bulletin.where(:title.ne => "",:is_preview.in=>[false,nil])
+ @bulletins = CurationPost.where(:title.ne => "",:is_preview.in=>[false,nil])
.order_by(sort)
.with_categories(filters("category"))
.with_tags(filters("tag"))
@@ -133,17 +133,13 @@ class Admin::AnnouncementsController < OrbitAdminController
render :layout => false
end
end
- def feed
- @table_feed_fields = ["announcement.feed_name",:tags , :category , "announcement.rssfeed", "announcement.jsonfeed"]
- @feeds = BulletinFeed.all.asc(:created_at)
-
- end
+
def generate_iframe_url
iframe_params = params.require(:iframe).permit!
uids = iframe_params['member_ids'].to_a.map{|m_id| MemberProfile.find(m_id).uid rescue nil}.select{|uid| !uid.nil?}
url_params = iframe_params.except(:member_ids)
url_params['uids'] = uids if uids != []
- render :plain => '/xhr/panel/announcement/widget/sync_data?'+url_params.to_param
+ render :plain => '/xhr/panel/curation/widget/sync_data?'+url_params.to_param
end
def settings
@setting = @announcement_setting
@@ -164,16 +160,16 @@ class Admin::AnnouncementsController < OrbitAdminController
def excel_format
respond_to do |format|
format.xlsx {
- response.headers['Content-Disposition'] = 'attachment; filename="announcement_import_format.xlsx"'
+ response.headers['Content-Disposition'] = 'attachment; filename="curation_import_format.xlsx"'
}
end
end
def export_excel
- @thread = Multithread.where(:key=>'export_announcements').first
+ @thread = Multithread.where(:key=>'export_curations').first
update_flag = true
if @thread.nil?
- @thread = Multithread.create(:key=>'export_announcements',:status=>{:status=>'Processing'})
+ @thread = Multithread.create(:key=>'export_curations',:status=>{:status=>'Processing'})
else
update_flag = false if @thread.status[:status] == 'Processing' && @thread.respond_to?(:updated_at) && (@thread.updated_at > DateTime.now - 1.minute rescue false)
if update_flag
@@ -187,11 +183,11 @@ class Admin::AnnouncementsController < OrbitAdminController
end
Thread.new do
begin
- @announcements = Bulletin.where(:is_preview.ne=>true).desc(:id)
- last_updated = [Bulletin.max(:updated_at).to_i, AnnouncementSetting.max(:updated_at).to_i].max
- filename = "public/announcement_export_#{last_updated}.xlsx"
+ @announcements = CurationPost.where(:is_preview.ne=>true).desc(:id)
+ last_updated = [CurationPost.max(:updated_at).to_i, CurationSetting.max(:updated_at).to_i].max
+ filename = "public/curation_export_#{last_updated}.xlsx"
if File.exist?(filename)
- @thread.update(:status=>{:status=>'finish','finish_percent'=>100,'info'=>I18n.t('announcement.read_from_cache')})
+ @thread.update(:status=>{:status=>'finish','finish_percent'=>100,'info'=>I18n.t('curation.read_from_cache')})
else
excel_contents = render_to_string( handlers: [:axlsx], formats: [:xlsx] ,partial: 'export_excel.xlsx' )
File.open(filename, 'w') do |f|
@@ -199,7 +195,7 @@ class Admin::AnnouncementsController < OrbitAdminController
end
end
@thread.status[:file] = filename
- @thread.status[:filename] = "announcement_export_#{DateTime.now.in_time_zone(Time.zone.utc_offset / 3600).strftime('%Y_%m_%d_%H%M')}.xlsx"
+ @thread.status[:filename] = "curation_export_#{DateTime.now.in_time_zone(Time.zone.utc_offset / 3600).strftime('%Y_%m_%d_%H%M')}.xlsx"
@thread.save
rescue => e
@thread.status[:status] = 'error'
@@ -209,7 +205,7 @@ class Admin::AnnouncementsController < OrbitAdminController
end
end
end
- redirect_to admin_announcement_import_path(:thread_id=>@thread.id.to_s)
+ # redirect_to admin_curation_import_path(:thread_id=>@thread.id.to_s)
end
def render_404
render :file => "#{Rails.root}/app/views/errors/404.html", :layout => false, :status => 404, :formats => [:html]
@@ -222,160 +218,42 @@ class Admin::AnnouncementsController < OrbitAdminController
render_404
end
end
- def import_from_xml
- download_tmp_xml params["import_xml"]
- import_from_tmp_xml File.read(File.join(Rails.root, "tmp", "ann_cc_ntu.xml"))
- redirect_to admin_announcements_path
- end
-
- def import_from_wp
- import_from_wordpress params["import_xml"].tempfile
- redirect_to admin_announcements_path
- end
-
- def importanns
- workbook = RubyXL::Parser.parse(params["import_file"].tempfile)
- raw_categories = @module_app.categories.asc(:created_at).to_a.map.with_index{|v, k| [k.to_s,v]}.to_h
- raw_tags = @module_app.tags.asc(:created_at).to_a.map.with_index{|v, k| [k.to_s,v]}.to_h
- categories = raw_categories.clone
- tags = raw_tags.clone
- sheet = workbook[0]
- if sheet.count <= 503
- sheet.each_with_index do |row, i|
- if i == 2
- begin
- cats_text = row.cells[0].value.to_s.sub(/(^|,)\s*Example\s*:.*$/,'')
- cats_keys = cats_text.split('->').map{|s| s.split(',')[-1].strip}[0...-1]
- cats_values = cats_text.split('->')[1..-1].to_a.map{|s| s.strip.sub(/,\s*\d+$/,'')}
- categories_relations = cats_keys.zip(cats_values).to_h
- rescue => e
- categories_relations = {}
- end
- begin
- tags_text = row.cells[1].value.to_s.sub(/(^|,)\s*Example\s*:.*$/,'')
- tags_keys = tags_text.split('->').map{|s| s.split(',')[-1].strip}[0...-1]
- tags_values = tags_text.split('->')[1..-1].to_a.map{|s| s.strip.sub(/,\s*\d+$/,'')}
- tags_relations = tags_keys.zip(tags_values).to_h
- rescue => e
- tags_relations = {}
- end
- if categories_relations.present?
- categories = categories_relations.map do |k, v|
- tmp = raw_categories[k]
- if tmp && tmp.title.strip == v
- [k, tmp]
- else
- tmp = raw_categories.detect{|kk, vv| vv.title.strip == v}
- if tmp.nil?
- tmp = @module_app.categories.create(:title_translations=> localize_data(v))
- end
- [k, tmp]
- end
- end.to_h
- end
- if tags_relations.present?
- tags = tags_relations.map do |k, v|
- tmp = raw_tags[k]
- if tmp && tmp.name.strip == v
- [k, tmp]
- else
- tmp = raw_tags.detect{|kk, vv| vv.name.strip == v}
- if tmp.nil?
- tmp = @module_app.tags.create(:name_translations=> localize_data(v))
- end
- [k, tmp]
- end
- end.to_h
- end
- end
- next if i < 3
- v = row.cells.first.value rescue nil
- next if v.blank?
- import_this_announcement(row, categories, tags)
- end
- redirect_to admin_announcements_path
- else
- redirect_to admin_announcements_path(:error => "1")
- end
- end
def createsettings
- setting = AnnouncementSetting.new(settings_params)
+ setting = CurationSetting.new(settings_params)
setting.save
- redirect_to admin_announcement_settings_path
+ redirect_to admin_curation_settings_path
end
-
+
def updatesettings
setting = @announcement_setting
- ids = params['announcement_setting']['anns_status_settings'].to_a.collect do |i,v|
+ ids = params['curation_setting']['curation_status_settings'].to_a.collect do |i,v|
v['_id']
end.compact
- AnnsStatusSetting.where(:id.nin=>ids).destroy
+ CurationStatusSetting.where(:id.nin=>ids).destroy
setting.update_attributes(settings_params)
setting.save
- redirect_to admin_announcement_settings_path
- end
-
- def feedform
- if params[:type] == "new"
- @announcement_feed = BulletinFeed.new(id: nil)
- render :partial => "feed_form"
- else params[:type] == "edit"
- @announcement_feed = BulletinFeed.find(params[:id])
- render :partial => "edit_feed_form"
- end
- end
-
- def createfeed
- announcement_feed = BulletinFeed.new(feed_params)
- announcement_feed.save
- #BulletinFeed.create_feed_cache(nil,announcement_feed)
- feeds = BulletinFeed.all.asc(:created_at)
- render :partial => "feed", :collection => feeds
- end
-
- def updatefeed
- ann_feed = BulletinFeed.find(params[:id])
- ann_feed.update_attributes(feed_params)
- ann_feed.save
- #BulletinFeed.create_feed_cache(nil,ann_feed)
- feeds = BulletinFeed.all.asc(:created_at)
- render :partial => "feed", :collection => feeds
- end
-
- def deletefeed
- ann_feed = BulletinFeed.find(params[:id])
- ann_feed.destroy
- feeds = BulletinFeed.all.asc(:created_at)
- render :partial => "feed", :collection => feeds
+ redirect_to admin_curation_settings_path
end
def new
@tags = @module_app.tags
@statuses = []
- @bulletin = Bulletin.new
+ @bulletin = CurationPost.new
@bulletin.email_sentdate = Time.now
@reach_limit = @bulletin.check_status_limit(current_user,true)
- if defined? Calendar
- categories = user_authenticated_categories rescue ['all']
- if categories.first == "all"
- @calendar_categories = CalendarType.all
- else
- @calendar_categories = CalendarType.where(:category_id.in => categories) rescue []
- end
- end
end
def create
bps = bulletin_params
- bulletin = Bulletin.new(bps)
- if !bps['bulletin_links_attributes'].nil?
- bps['bulletin_links_attributes'].each do |idx,link|
- bps['bulletin_links_attributes'].delete(idx.to_s) if link['url'].blank?
+ bulletin = CurationPost.new(bps)
+ if !bps['curation_post_links_attributes'].nil?
+ bps['curation_post_links_attributes'].each do |idx,link|
+ bps['curation_post_links_attributes'].delete(idx.to_s) if link['url'].blank?
end
end
- if((!AnnouncementSetting.first.only_manager_can_edit_status) || (AnnouncementSetting.first.only_manager_can_edit_status && (@current_user.is_admin? || @current_user.is_manager?(@module_app))) )
- if bps[:is_top] == "1" && !AnnouncementSetting.check_limit_for_user(bulletin.create_user_id, bulletin.id)
+ if((!CurationSetting.first.only_manager_can_edit_status) || (CurationSetting.first.only_manager_can_edit_status && (@current_user.is_admin? || @current_user.is_manager?(@module_app))) )
+ if bps[:is_top] == "1" && !CurationSetting.check_limit_for_user(bulletin.create_user_id, bulletin.id)
bps[:is_top] = "0"
bps[:top_end_date] = nil
end
@@ -385,12 +263,9 @@ class Admin::AnnouncementsController < OrbitAdminController
bps[:is_hidden] = false
end
- if !defined?(Calendar).nil?
- bps = update_calendar(bps,bulletin)
- end
bulletin.create_user_id = current_user.id
bulletin.update_user_id = current_user.id
- if AnnouncementSetting.is_pro?
+ if CurationSetting.is_pro?
if user_can_approve?
bulletin.approved = true
else
@@ -399,7 +274,7 @@ class Admin::AnnouncementsController < OrbitAdminController
else
bulletin.approved = true
end
-
+
bulletin.save
build_email(bulletin,I18n.locale)
Thread.new do
@@ -411,7 +286,7 @@ class Admin::AnnouncementsController < OrbitAdminController
def approve_bulletin
id = params[:id]
- bulletin = Bulletin.find(id)
+ bulletin = CurationPost.find(id)
if params["approved"] == "true"
bulletin.approved = true
bulletin.rejected = false
@@ -424,7 +299,7 @@ class Admin::AnnouncementsController < OrbitAdminController
end
bulletin.save
#BulletinFeed.create_feed_cache(bulletin)
- redirect_to admin_announcements_path
+ redirect_to admin_curation_path
end
def edit
@@ -432,14 +307,6 @@ class Admin::AnnouncementsController < OrbitAdminController
@reach_limit = @bulletin.check_status_limit(current_user,true)
@tags = @module_app.tags
@categories = @module_app.categories.enabled
- if defined? Calendar
- categories = user_authenticated_categories rescue ['all']
- if categories.first == "all"
- @calendar_categories = CalendarType.all
- else
- @calendar_categories = CalendarType.where(:category_id.in => categories) rescue []
- end
- end
@statuses = []
@bulletin.email_sentdate = Time.now if @bulletin.email_sent == false
else
@@ -449,8 +316,8 @@ class Admin::AnnouncementsController < OrbitAdminController
def update
uid = params[:id].split('-').last
- bulletin = Bulletin.find_by(:uid=>uid)
- Bulletin.where(:copy_id=>bulletin.id.to_s).destroy
+ bulletin = CurationPost.find_by(:uid=>uid)
+ CurationPost.where(:copy_id=>bulletin.id.to_s).destroy
bulletin.is_edit = true
bulletin.save
set_approved = bulletin.is_preview
@@ -460,13 +327,13 @@ class Admin::AnnouncementsController < OrbitAdminController
bps[:tags] = bps[:tags].blank? ? [] : bps[:tags]
bps[:email_member_ids] = bps[:email_member_ids].blank? ? [] : bps[:email_member_ids]
- if !bps['bulletin_links_attributes'].nil?
- bps['bulletin_links_attributes'].each do |idx,link|
- bps['bulletin_links_attributes'].delete(idx.to_s) if link['url'].blank?
+ if !bps['curation_post_links_attributes'].nil?
+ bps['curation_post_links_attributes'].each do |idx,link|
+ bps['curation_post_links_attributes'].delete(idx.to_s) if link['url'].blank?
end
end
- if((!AnnouncementSetting.first.only_manager_can_edit_status) || (AnnouncementSetting.first.only_manager_can_edit_status && (@current_user.is_admin? || @current_user.is_manager?(@module_app))) )
- if bps[:is_top] == "1" && !AnnouncementSetting.check_limit_for_user(bulletin.create_user_id, bulletin.id)
+ if((!CurationSetting.first.only_manager_can_edit_status) || (CurationSetting.first.only_manager_can_edit_status && (@current_user.is_admin? || @current_user.is_manager?(@module_app))) )
+ if bps[:is_top] == "1" && !CurationSetting.check_limit_for_user(bulletin.create_user_id, bulletin.id)
bps[:is_top] = "0"
bps[:top_end_date] = nil
end
@@ -494,38 +361,32 @@ class Admin::AnnouncementsController < OrbitAdminController
bulletin.notify_feed("update")
end
#BulletinFeed.create_feed_cache(bulletin)
- now_bulletin_page = Bulletin.where(:title.ne => "",:is_preview.in=>[false,nil])
+ now_bulletin_page = CurationPost.where(:title.ne => "",:is_preview.in=>[false,nil])
.order_by(sort).map(&:id).map.with_index.select{|v,i| v==bulletin.id}[0][1] rescue nil
now_bulletin_page = now_bulletin_page.nil? ? 0 : ((now_bulletin_page+1).to_f/10).ceil
- redirect_to admin_announcements_path(:page=>now_bulletin_page)
+ redirect_to admin_curations_path(:page=>now_bulletin_page)
end
def destroy
@bulletin.destroy
- Thread.new do
- @bulletin.notify_feed("destroy")
- end
- redirect_to admin_announcements_path
+ redirect_to admin_curations_path
end
def delete
if params[:ids]
- Bulletin.any_in(:uid => params[:ids]).destroy_all
- Thread.new do
- Bulletin.notify_feed_delete(params[:ids])
- end
+ CurationPost.any_in(:uid => params[:ids]).destroy_all
end
if request.xhr?
render :body => nil, :status => 204
else
- redirect_to admin_announcements_path
+ redirect_to admin_curations_path
end
end
def preview
if params['preview_type'].eql?('edit')
bulletin_data = bulletin_params
- org_bulletin = Bulletin.find(params['bulletin_id'])
+ org_bulletin = CurationPost.find(params['bulletin_id'])
bulletin = org_bulletin.clone
bulletin.generate_uid
bulletin.bulletin_files = []
@@ -534,16 +395,16 @@ class Admin::AnnouncementsController < OrbitAdminController
bulletin.image = org_bulletin.image
end
- if !bulletin_data['bulletin_files_attributes'].blank?
- bulletin_data['bulletin_files_attributes'].each do |key, bulletin_file|
+ if !bulletin_data['curation_post_files_attributes'].blank?
+ bulletin_data['curation_post_files_attributes'].each do |key, bulletin_file|
next if !bulletin_file['_destroy'].blank?
file = nil
if bulletin_file['id'].blank?
- file = BulletinFile.new(bulletin_file)
+ file = CurationPostFile.new(bulletin_file)
file.bulletin_id = bulletin.id
file.save
else
- org_file = BulletinFile.find(bulletin_file['id'])
+ org_file = CurationPostFile.find(bulletin_file['id'])
file = org_file.clone
file.bulletin_id = bulletin.id
file.file = org_file.file
@@ -557,15 +418,15 @@ class Admin::AnnouncementsController < OrbitAdminController
end
end
- if !bulletin_data['bulletin_links_attributes'].blank?
- bulletin_data['bulletin_links_attributes'].each do |key, bulletin_link|
+ if !bulletin_data['curation_post_links_attributes'].blank?
+ bulletin_data['curation_post_links_attributes'].each do |key, bulletin_link|
next if !bulletin_link['_destroy'].blank?
if bulletin_link['id'].blank?
- link = BulletinLink.new(bulletin_link)
+ link = CurationPostLink.new(bulletin_link)
link.bulletin_id = bulletin.id
else
- link = BulletinLink.find(bulletin_link['id']).clone
+ link = CurationPostLink.find(bulletin_link['id']).clone
link.bulletin_id = bulletin.id
bulletin_link.delete('id')
bulletin_link.delete('_destroy')
@@ -577,33 +438,33 @@ class Admin::AnnouncementsController < OrbitAdminController
end
end
- bulletin_data.delete('bulletin_files_attributes')
- bulletin_data.delete('bulletin_links_attributes')
+ bulletin_data.delete('curation_post_files_attributes')
+ bulletin_data.delete('curation_post_links_attributes')
bulletin.update_attributes(bulletin_data)
bulletin.copy_id = params['bulletin_id']
else
- bulletin = Bulletin.new(bulletin_params)
+ bulletin = CurationPost.new(bulletin_params)
end
-
+
bulletin.is_preview = true
bulletin.save
#BulletinFeed.create_feed_cache(bulletin)
render :plain=>page_for_bulletin(bulletin) + "?preview=true"
end
def get_preview_action
- bulletin = Bulletin.find_by(:uid=>params['uid'])
+ bulletin = CurationPost.find_by(:uid=>params['uid'])
is_not_edit = (!bulletin.is_edit)
org_bulletin = bulletin.get_org_model
- Bulletin.where(:copy_id=>org_bulletin.id.to_s).destroy
+ CurationPost.where(:copy_id=>org_bulletin.id.to_s).destroy
if is_not_edit
bulletin.destroy
render :json=> {:success=>true,:action=>"close"}
else
- render :json=> {:success=>true,:action=>"redirect",:path=>edit_admin_announcement_path(:id=>org_bulletin.id)}
+ render :json=> {:success=>true,:action=>"redirect",:path=>edit_admin_curation_path(:id=>org_bulletin.id)}
end
end
def destroy_preview
- bulletin = Bulletin.find_by(:uid=>params['uid'])
+ bulletin = CurationPost.find_by(:uid=>params['uid'])
if bulletin.is_preview
bulletin.destroy
end
@@ -624,7 +485,7 @@ class Admin::AnnouncementsController < OrbitAdminController
is_sent = !params[:resend_mail].eql?("true") if !params[:resend_mail].blank?
doc = Nokogiri::HTML(bulletin.title_translations[locale])
title = doc.text.empty? ? 'no content' : doc.text
-
+
bulletin.email.update_attributes(
:create_user=>current_user,
:mail_sentdate=>bulletin.email_sentdate,
@@ -649,59 +510,22 @@ class Admin::AnnouncementsController < OrbitAdminController
private
def load_settings
- @announcement_setting = AnnouncementSetting.first rescue nil
+ @announcement_setting = CurationSetting.first rescue nil
if @announcement_setting.nil?
- @announcement_setting = AnnouncementSetting.create
+ @announcement_setting = CurationSetting.create
end
end
def set_bulletin
- @bulletin = Bulletin.find(params[:id])
+ @bulletin = CurationPost.find(params[:id])
end
def bulletin_params
- params[:bulletin][:email_sent] = params[:bulletin][:email_sent].nil? ? 0 : params[:bulletin][:email_sent]
- params.require(:bulletin).permit!
- end
-
- def feed_params
- feed_params = params.require(:bulletin_feed).permit!
- if feed_params[:tag_ids].nil?
- feed_params[:tag_ids] = []
- end
- if feed_params[:category_ids].nil?
- feed_params[:category_ids] = []
- end
- feed_params
+ params[:curation_post][:email_sent] = params[:curation_post][:email_sent].nil? ? 0 : params[:curation_post][:email_sent]
+ params.require(:curation_post).permit!
end
def settings_params
- params.require(:announcement_setting).permit!
- end
- def update_calendar(bps,bulletin)
- bps = bps.to_h.with_indifferent_access
- if bps[:add_to_calendar] == '0' && !bps[:event_id].blank?
- Event.find(bps[:event_id]).destroy rescue nil
- bps[:event_id] = nil
- elsif bps[:add_to_calendar] == '1'
- event = Event.find(bps[:event_id]) rescue Event.new(create_user_id: current_user.id)
- e_start = bps[:calendar_start_date].blank? ? bps[:postdate] : bps[:calendar_start_date]
- e_start = Time.now.to_datetime if e_start.blank?
- e_end = bps[:calendar_end_date].blank? ? bps[:deadline] : bps[:calendar_end_date]
- #e_end = Time.now.to_datetime + 1.year if e_end.blank?
- event.update_attributes(model_class: 'Bulletin',
- module_key: 'announcement',
- model_cat: bps[:category_id],
- model_tags: bps[:tags],
- model_page_id: bps[:page_id],
- model_id: bulletin.id,start: e_start,
- end: e_end,update_user_id: current_user.id,
- all_day: bps[:calendar_all_day],
- calendar_type_id: bps[:calendar_type_id],
- title_translations: bps[:title_translations],
- note_translations: bps[:subtitle_translations])
- bps[:event_id] = event.id
- end
- bps
+ params.require(:curation_setting).permit!
end
end
diff --git a/app/controllers/announcement_feeds_controller.rb b/app/controllers/announcement_feeds_controller.rb
deleted file mode 100644
index 1b334d5..0000000
--- a/app/controllers/announcement_feeds_controller.rb
+++ /dev/null
@@ -1,96 +0,0 @@
-require "rss"
-class AnnouncementFeedsController < ApplicationController
- include Admin::AnnouncementsHelper
- def feed_add_remote
- if params[:url].present?
- uid = params[:uid].to_s
- bulletin_feed = BulletinFeed.where(uid: uid).first
- if !(bulletin_feed.remote_urls.include?(params[:url]))
- bulletin_feed.remote_urls << params[:url]
- bulletin_feed.save
- end
- end
- render :json => {success: true}
- end
- def feed_remove_remote
- if params[:url].present?
- uid = params[:uid].to_s
- bulletin_feed = BulletinFeed.where(uid: uid).first
- if bulletin_feed.remote_urls.delete(params[:url])
- bulletin_feed.save
- end
- end
- render :json => {success: true}
- end
- def feed
- uid = params[:uid].to_s
- startdt = params[:start].blank? ? nil : params[:start]
- enddt = params[:end].blank? ? nil : params[:end]
- dt = params[:date].blank? ? nil : params[:date]
- feed_cache = BulletinFeedCache.where(uid: uid, start: startdt, end: enddt, date: dt)
- feed_cache_old = feed_cache.all_of([{:invalid_date.ne=>nil},{:invalid_date.lte => Time.now}]).last
- feed_cache.all_of([{:invalid_date.ne=>nil},{:invalid_date.lte => Time.now}]).destroy
- count = feed_cache.count
- if count > 1
- feed_cache.limit(count-1).destroy
- end
- feed_cache = feed_cache.first
- anns = ''
- if feed_cache.nil?
- anns = BulletinFeed.where(uid: uid).first.generate_one_cache_timeout(startdt: startdt,enddt: enddt,dt: dt,base_url: request.base_url,timeout: 20)
- anns = (feed_cache_old.content rescue "") if anns.nil?
- else
- anns = feed_cache.content
- end
- render :json => anns
- end
-
- def rssfeed
- uid = params[:uid].to_s
- @bf = BulletinFeed.find_by(:uid => uid) rescue nil
- if !@bf.nil?
- tags = @bf.tag_ids
- if !tags.empty?
- @announcements = Bulletin.can_display_and_sorted.is_approved.filter_by_tags(tags)
- else
- @announcements = Bulletin.can_display_and_sorted.is_approved
- end
- categories = @bf.category_ids
- if !categories.empty?
- @announcements = @announcements.filter_by_categories(categories)
- end
- end
- respond_to do |format|
- format.html {redirect_to "/xhr/announcements/rssfeed/#{@bf.uid}.rss"}
- format.rss
- end
- end
-
- def feeds
- feeds = []
- BulletinFeed.all.each do |bf|
- feed = {}
- feed["title_translations"] = bf.title_translations
- feed["uid"] = bf.uid
- feed["url"] = "#{request.base_url}/xhr/announcements/feed/#{bf.uid}"
- feed["xml_url"] = "#{request.base_url}/xhr/announcements/rssfeed/#{bf.uid}.rss"
- feed["tags"] = []
- bf.tag_ids.each do |t|
- tag = Tag.find(t)
- d = {}
- d["name_translations"] = tag.name_translations
- feed["tags"] << d
- end
- feeds << feed
- end
- render :json => {"feeds" => feeds}.to_json
- end
-
-
-end
-
-
-
-
-
-
diff --git a/app/controllers/bulletins_controller.rb b/app/controllers/curation_posts_controller.rb
similarity index 98%
rename from app/controllers/bulletins_controller.rb
rename to app/controllers/curation_posts_controller.rb
index c0193ee..c10cef8 100644
--- a/app/controllers/bulletins_controller.rb
+++ b/app/controllers/curation_posts_controller.rb
@@ -1,5 +1,5 @@
# encoding: utf-8
-class BulletinsController < ApplicationController
+class CurationPostsController < ApplicationController
before_filter :set_I18n
def annc_depts_translations
if defined?(OrbitHelper::SharedHash) && OrbitHelper::SharedHash
diff --git a/app/controllers/announcements_controller.rb b/app/controllers/curations_controller.rb
similarity index 98%
rename from app/controllers/announcements_controller.rb
rename to app/controllers/curations_controller.rb
index 76c2abd..fd53a34 100644
--- a/app/controllers/announcements_controller.rb
+++ b/app/controllers/curations_controller.rb
@@ -1,6 +1,6 @@
-class AnnouncementsController < ApplicationController
+class CurationsController < ApplicationController
ViewRootDir = File.expand_path("../../views", __FILE__)
- include AnnouncementsHelper
+ include CurationsHelper
DefaultImgSrc = "/assets/announcement-default.jpg\" onerror=\"this.src="/assets/announcement-default-2.jpg";this.onerror='';"
def initialize
super
@@ -300,7 +300,7 @@ class AnnouncementsController < ApplicationController
end
max_all_count = [OrbitHelper.widget_data_count,anns.count].min
if @tab_option != 0
- OrbitHelper.set_widget_title(OrbitHelper.widget_title +
+ OrbitHelper.set_widget_title(OrbitHelper.widget_title +
"
" +
"
" +
(use_tag ? tags.map.with_index{|tag,i|
@@ -310,7 +310,7 @@ class AnnouncementsController < ApplicationController
if tag != "all"
begin
read_more_text = I18n.t("announcement.more_") + tags_translations[tag]
- rescue
+ rescue
nil
end
end
@@ -322,7 +322,7 @@ class AnnouncementsController < ApplicationController
if cat != "all"
begin
read_more_text = I18n.t("announcement.more_") + cats_translations[cat]
- rescue
+ rescue
nil
end
end
@@ -361,19 +361,19 @@ class AnnouncementsController < ApplicationController
}
}
var wpexLocalize = {
- "lightboxType": "iLightbox",
- "iLightbox": { "auto": false, "skin": "minimal", "path": "horizontal",
+ "lightboxType": "iLightbox",
+ "iLightbox": { "auto": false, "skin": "minimal", "path": "horizontal",
"infinite": false, "maxScale": 1, "minScale": 0, "width": 1400, "height": "",
- "slideshow": { "pauseTime": 3000, "startPaused": true },
- "effects": { "reposition": true, "repositionSpeed": 200, "switchSpeed": 300,
- "loadedFadeSpeed": 50, "fadeSpeed": 500
- },
- "show": { "title": true, "speed": 200 },
- "hide": { "speed": 200 },
+ "slideshow": { "pauseTime": 3000, "startPaused": true },
+ "effects": { "reposition": true, "repositionSpeed": 200, "switchSpeed": 300,
+ "loadedFadeSpeed": 50, "fadeSpeed": 500
+ },
+ "show": { "title": true, "speed": 200 },
+ "hide": { "speed": 200 },
"overlay": { "blur": true, "opacity": "0.9" },
- "slideShow": "Slideshow", "next": "Next", "previous": "Previous" ,
- "thumbnails": { "maxWidth": 120, "maxHeight": 80 }
- }
+ "slideShow": "Slideshow", "next": "Next", "previous": "Previous" ,
+ "thumbnails": { "maxWidth": 120, "maxHeight": 80 }
+ }
};
$(document).ready(function(){
var first_filter_tab = $("[data-subpart-id=\"'+subpart.id.to_s+'\"] .filter_tab").eq(0);
@@ -403,7 +403,7 @@ class AnnouncementsController < ApplicationController
if cats.count == 1 && cats[0] != "all"
begin
read_more_text = I18n.t("announcement.more_") + ((all_tags.count == 1 && all_tags[0] != 'all') ? tags_translations[tags[0]] : cats_translations[cats[0]])
- rescue
+ rescue
nil
end
end
@@ -581,7 +581,7 @@ class AnnouncementsController < ApplicationController
first_deadline = sorted_anns.pluck(:deadline).compact.sort[0]
first_postdate = anns_for_locale.open_in_future.limit(1).pluck(:postdate)[0]
invalid_date = [first_postdate,first_deadline].compact.sort[0]
-
+
if devide_flag
now_anns = sorted_anns.to_a
top_anns = now_anns.select{|v| v.is_top}.map{|v| data_to_human_type(v,set_tags)}
diff --git a/app/helpers/admin/announcements_helper.rb b/app/helpers/admin/curations_helper.rb
similarity index 99%
rename from app/helpers/admin/announcements_helper.rb
rename to app/helpers/admin/curations_helper.rb
index af3f1ca..9dee073 100644
--- a/app/helpers/admin/announcements_helper.rb
+++ b/app/helpers/admin/curations_helper.rb
@@ -2,7 +2,7 @@ require "net/http"
require "uri"
require 'json'
-module Admin::AnnouncementsHelper
+module Admin::CurationsHelper
def page_for_bulletin(bulletin)
if !bulletin.is_external_link || bulletin.external_link.blank?
ann_page = nil
diff --git a/app/helpers/announcements_helper.rb b/app/helpers/curations_helper.rb
similarity index 98%
rename from app/helpers/announcements_helper.rb
rename to app/helpers/curations_helper.rb
index f2bd5fd..2fdbe73 100644
--- a/app/helpers/announcements_helper.rb
+++ b/app/helpers/curations_helper.rb
@@ -1,4 +1,4 @@
-module AnnouncementsHelper
+module CurationsHelper
extend self
def data_to_human_type(a,set_tag_ids=nil,tmp_enable_annc_dept=false,annc_depts=[])
@@ -218,7 +218,7 @@ module AnnouncementsHelper
if wrap_elements.count > 0
htmls = parsing_repeats_again(wrap_elements,d[data_name][i], level + 1)
htmls[0].each_with_index do |html,i|
- element = element.gsub(html,htmls[1][i])
+ element = element.gsub(html,htmls[1][i])
end
end
item.each do |key,value|
@@ -254,11 +254,11 @@ module AnnouncementsHelper
doc = Nokogiri::HTML(file, nil, "UTF-8")
file.close
controller = AnnouncementsController.new
- begin
+ begin
data = @data# rescue nil
- rescue Exception => e
+ rescue Exception => e
write_debug_file(e,'announcements',@target_action) if Site::DEBUG
- end
+ end
if !data.nil?
wrap_elements = doc.css("*[data-list][data-level='0']")
htmls = parsing_repeats_again(wrap_elements,data,1)
@@ -291,11 +291,11 @@ module AnnouncementsHelper
doc = Nokogiri::HTML(file, nil, "UTF-8")
file.close
controller = AnnouncementsController.new
- begin
+ begin
data = @data# rescue nil
- rescue Exception => e
+ rescue Exception => e
write_debug_file(e,'announcements',@target_action) if Site::DEBUG
- end
+ end
if data.nil?
return "
No content to show.
".html_safe
end
@@ -400,8 +400,8 @@ module AnnouncementsHelper
if layout_types.empty?
Dir.glob("#{Rails.root}/app/templates/#{@key}/modules/#{module_app}/*").each do |w|
next if File.ftype(w).eql?("directory")
- w = File.basename(w, ".*")
- w = File.basename(w, ".*")
+ w = File.basename(w, ".*")
+ w = File.basename(w, ".*")
if w[0,1] != "_" && w[0,1] != "s" && w != "info"
layout_types << w
end
@@ -434,7 +434,7 @@ module AnnouncementsHelper
#{e['description']}
- "
+ "
end.join+
"
diff --git a/app/models/bulletin_feed.rb b/app/models/bulletin_feed.rb
deleted file mode 100644
index 0d12b43..0000000
--- a/app/models/bulletin_feed.rb
+++ /dev/null
@@ -1,179 +0,0 @@
-class BulletinFeed
- include Mongoid::Document
- include Mongoid::Timestamps
- include Slug
-
- field :title, as: :slug_title, type: String, localize: true
- field :tag_ids, type: Array, default: []
- field :category_ids, type: Array, default: []
- field :remote_urls, type: Array, default: []
- before_save do
- BulletinFeedCache.where(uid: self.uid).each do |cache|
- cache.regenerate
- end
- end
- def annc_depts_translations
- if defined?(OrbitHelper::SharedHash) && OrbitHelper::SharedHash
- OrbitHelper::SharedHash['announcement'][:annc_depts_translations] rescue AnnouncementSetting.first.annc_depts_translations
- else
- AnnouncementSetting.first.annc_depts_translations rescue {}
- end
- end
- def enable_annc_dept
- if defined?(OrbitHelper::SharedHash) && OrbitHelper::SharedHash
- OrbitHelper::SharedHash['announcement'][:enable_annc_dept] rescue AnnouncementSetting.first.enable_annc_dept
- else
- AnnouncementSetting.first.enable_annc_dept rescue false
- end
- end
- def self.create_feed_cache(bulletin=nil,bulletin_feed=nil)
- Thread.new do
- if !bulletin.nil?
- BulletinFeed.where(:tag_ids.in => Array(bulletin.tag_ids).collect{|v| v.to_s}).each do |bulletin_feed|
- uid = bulletin_feed.uid
- BulletinFeedCache.where(:uid => uid).each do |cache|
- cache.regenerate
- end
- end
- elsif !bulletin_feed.nil?
- uid = bulletin_feed.uid
- BulletinFeedCache.where(:uid => uid).each do |cache|
- cache.regenerate
- end
- end
- end
- end
- def generate_one_cache_timeout(startdt: nil,enddt: nil,dt: nil, base_url: nil, timeout: nil)
- begin
- if timeout.nil?
- feed_cache_content = self.generate_one_cache(startdt: startdt,enddt: enddt,dt: dt,base_url: base_url)
- else
- Timeout::timeout(timeout) do
- feed_cache_content = nil
- thread = Thread.new do
- feed_cache_content = self.generate_one_cache(startdt: startdt,enddt: enddt,dt: dt,base_url: base_url)
- end
- (1..(timeout.to_i+1)).each do
- sleep(1)
- break if !feed_cache_content.nil? && !thread.alive?
- end
- feed_cache_content
- end
- end
- rescue=> e
- puts [e,e.backtrace]
- nil
- end
- end
- def generate_one_cache(startdt: nil,enddt: nil,dt: nil, base_url: nil)
- base_url = Site.first.root_url if base_url.nil?
- uid = self.uid
- bf = self
- annc_depts = []
- tmp_enable_annc_dept = (enable_annc_dept rescue false)
- if tmp_enable_annc_dept
- annc_depts = annc_depts_translations[I18n.default_locale.to_s] rescue []
- end
- tags = bf.tag_ids
- categories = bf.category_ids
- if !(categories.empty? && tags.empty?)
- anns_before_filter = Bulletin.is_approved_and_show
- can_display_and_sorted_flag = false
- if !dt.nil?
- dt = DateTime.parse(dt)
- dtt = dt + 1.day
- anns_before_filter = anns_before_filter.where(:postdate.gt => dt, :postdate.lt => dtt)
- elsif !startdt.blank? && enddt.blank?
- startdt = DateTime.parse(startdt)
- enddt = DateTime.now
- anns_before_filter = anns_before_filter.where(:postdate.gt => startdt, :postdate.lt => enddt)
- elsif !startdt.blank? && !enddt.blank?
- startdt = DateTime.parse(startdt)
- enddt = DateTime.parse(enddt) + 1.day
- anns_before_filter = anns_before_filter.where(:postdate.gt => startdt, :postdate.lt => enddt)
- else
- can_display_and_sorted_flag = true
- end
-
- if !tags.empty?
- anns_before_filter = anns_before_filter.filter_by_tags(tags)
- end
- if !categories.empty?
- anns_before_filter = anns_before_filter.filter_by_categories(categories,paginate=false)
- end
- anns_before_filter.selector = {"$and"=>[anns_before_filter.selector,{"$or"=>(I18n.available_locales.map{|v| {"title.#{v}"=>{"$nin"=>["", nil]}}})}]}
- if can_display_and_sorted_flag
- announcements = anns_before_filter.valid_time_range.to_a
- else
- announcements = anns_before_filter.to_a
- end
- else
- anns_before_filter = Bulletin.can_display_and_sorted
- announcements = anns_before_filter.to_a
- end
- all_anns = []
- tag_ids = []
- category_ids = []
-
- first_postdate = anns_before_filter.open_in_future.limit(1).pluck(:postdate)[0]
- first_deadline = nil
- cat_ids = announcements.collect{|a| a.category_id.blank? ? nil : a.category_id.to_s}.compact.uniq
- tag_ids = announcements.collect{|a| a.tag_ids.collect{|v| v.blank? ? nil : v.to_s}}.flatten.compact.uniq
- tag_names = tag_ids.map{|tag_id| Tag.find(tag_id).name_translations rescue nil}.compact
- category_titles = cat_ids.map{|cat_id| Category.find(cat_id).title_translations rescue nil}.compact
- basic_query = {:module => 'announcement',:enabled_for=>I18n.locale}
- if !cat_ids.blank?
- query = basic_query.merge({:categories.all => cat_ids})
- else
- query = basic_query.clone
- end
- if !tag_ids.blank?
- query = query.merge({:tags.all => tag_ids})
- end
- page = Page.where(query).first || Page.where(basic_query).first
- more_url = page ? page.get_url : nil
-
- announcements.each_with_index do |anns,i|
- deadline = anns.deadline
- if !deadline.blank?
- if first_deadline.nil? || first_deadline>deadline
- first_deadline = deadline
- end
- end
- a = anns.get_data(annc_depts, tmp_enable_annc_dept, more_url, base_url, cat_ids, tag_ids)
- all_anns << a
- end
- invalid_date = [first_postdate,first_deadline].compact.sort[0]
- anns = {
- "announcements" => all_anns,
- "tags" => tag_names,
- "categories" => category_titles
- }.to_json
- BulletinFeedCache.where(uid: uid,start: startdt,end: enddt,date: dt).destroy
- feed_cache = BulletinFeedCache.create(uid: uid,content: anns,start: startdt,end: enddt,date: dt,invalid_date: invalid_date)
- anns
- end
- def self.smart_convertor(text,url)
- doc = Nokogiri.HTML(text)
- doc.search('a[href]').each do |link|
- if link['href'].nil?
- link.delete 'href'
- elsif link['href'].start_with?('/')
- link['href'] = url + link['href']
- elsif link['href'].start_with?('../')
- link['href'] = url + link['href'][3..-1]
- end
- end
- doc.search('img[src]').each do |link|
- if link['src'].nil?
- link.delete 'src'
- elsif link['src'].start_with?('/')
- link['src'] = url + link['src']
- elsif link['src'].start_with?('../')
- link['src'] = url + link['src'][3..-1]
- end
- end
-
- return doc.css('body').inner_html
- end
-end
\ No newline at end of file
diff --git a/app/models/bulletin_feed_cache.rb b/app/models/bulletin_feed_cache.rb
deleted file mode 100644
index 9147370..0000000
--- a/app/models/bulletin_feed_cache.rb
+++ /dev/null
@@ -1,34 +0,0 @@
-class BulletinFeedCache
- include Mongoid::Document
- include Mongoid::Timestamps
-
- field :content, type: String, default: ''
- field :uid
- field :start
- field :end
- field :date
- field :invalid_date, type: DateTime
- def self.regenerate_all
- caches = self.all.to_a
- time_now = Time.now
- caches.each do |cache|
- if cache.invalid_date && cache.invalid_date <= time_now
- cache.destroy
- else
- cache.regenerate
- end
- end
- uids = BulletinFeed.all.pluck(:uid) - caches.collect(&:uid)
- BulletinFeed.where(:uid.in=> uids).each do |feed|
- feed.generate_one_cache()
- end
- end
- def regenerate
- st = self.start
- et = self.end
- dt = self.date
- uid = self.uid
- BulletinFeed.where(uid: uid).each{|v| v.generate_one_cache(startdt: st,enddt: et,dt: dt)} rescue nil
- self.destroy
- end
-end
\ No newline at end of file
diff --git a/app/models/anns_cache.rb b/app/models/curation_cache.rb
similarity index 86%
rename from app/models/anns_cache.rb
rename to app/models/curation_cache.rb
index 346ea23..1a660ff 100644
--- a/app/models/anns_cache.rb
+++ b/app/models/curation_cache.rb
@@ -1,7 +1,7 @@
-class AnnsCache
+class CurationCache
include Mongoid::Document
field :parent_id
field :filter_result
field :locale,type: String,default: 'zh_tw'
field :invalid_date, type: DateTime
-end
\ No newline at end of file
+end
diff --git a/app/models/bulletin.rb b/app/models/curation_post.rb
similarity index 67%
rename from app/models/bulletin.rb
rename to app/models/curation_post.rb
index 92ffd32..d4ea01c 100644
--- a/app/models/bulletin.rb
+++ b/app/models/curation_post.rb
@@ -1,4 +1,4 @@
-class Bulletin
+class CurationPost
include Mongoid::Document
include Mongoid::Timestamps
@@ -8,8 +8,8 @@ class Bulletin
include OrbitTag::Taggable
include OrbitCategory::Categorizable
include Slug
- require 'announcement/cache'
- include Announcement::Cache
+ require 'curation/cache'
+ include Curation::Cache
attr_accessor :org_tag_ids,:org_category_id
def tags=(ids)
self.org_tag_ids = self.tag_ids
@@ -35,13 +35,10 @@ class Bulletin
end
super(index,value)
end
- SubPart.class_eval { include Announcement::Cache }
- Page.class_eval { include Announcement::Cache }
+ SubPart.class_eval { include Curation::Cache }
+ Page.class_eval { include Curation::Cache }
before_destroy do
- if self.event_id.present? && !defined?(Calendar).nil?
- Event.where(:id=>self.event_id).destroy
- end
- AnnsCache.all.destroy
+ CurationCache.all.destroy
end
field :is_edit, type: Boolean, default: false #use to check whether the preview record changed
field :copy_id
@@ -53,7 +50,6 @@ class Bulletin
field :calendar_end_date, :type => DateTime
field :calendar_all_day,type: Boolean,default: false
field :calendar_type_id
- field :event_id
field :page_id
field :title, as: :slug_title, type: String, localize: true
field :title_plain_text, type: String, localize: true
@@ -92,13 +88,13 @@ class Bulletin
field :display_sub_annc_date, :type => Boolean, :default => false
mount_uploader :image, ImageUploader
- has_many :bulletin_links, :autosave => true, :dependent => :destroy
- has_many :bulletin_files, :autosave => true, :dependent => :destroy
- has_many :bulletin_comments, :autosave => true, :dependent => :destroy
- has_many :bulletin_carousel_images, :autosave => true, :dependent => :destroy
- accepts_nested_attributes_for :bulletin_files, :allow_destroy => true
- accepts_nested_attributes_for :bulletin_links, :allow_destroy => true
- accepts_nested_attributes_for :bulletin_carousel_images, :allow_destroy => true
+ has_many :curation_post_links, :autosave => true, :dependent => :destroy
+ has_many :curation_post_files, :autosave => true, :dependent => :destroy
+ has_many :curation_post_comments, :autosave => true, :dependent => :destroy
+ has_many :curation_post_carousel_images, :autosave => true, :dependent => :destroy
+ accepts_nested_attributes_for :curation_post_files, :allow_destroy => true
+ accepts_nested_attributes_for :curation_post_links, :allow_destroy => true
+ accepts_nested_attributes_for :curation_post_carousel_images, :allow_destroy => true
before_destroy :destroy_email
@@ -122,7 +118,7 @@ class Bulletin
index({postdate: 1}, { unique: false, background: true })
index({is_top: -1,postdate: -1, _id: -1}, { unique: false, background: true })
index({approved: -1,is_hidden: 1,is_preview: 1, is_top: -1,postdate: -1,_id: -1,deadline: -1}, { unique: false, background: true })
- if AnnouncementSetting.pluck(:enable_manually_sort).first == true
+ if CurationSetting.pluck(:enable_manually_sort).first == true
index({approved: -1,is_hidden: 1,is_preview: 1, is_top: -1,sort_number: 1,postdate: -1,_id: -1,deadline: -1}, { unique: false, background: true })
end
field :sort_number, type: Integer
@@ -141,23 +137,13 @@ class Bulletin
def to_calendar_param
self.to_param
end
- def calendar_type
- CalendarType.where(:category_id.in => self.calendar_type_id)
- end
- def event
- if !self.event_id.nil?
- Event.where(:id => self.event_id).first
- else
- nil
- end
- end
def check_limit
check_status_limit(update_user).length>0 ? false : true
end
def check_status_limit(user,check_only=false)
role_ids = user.member_profile.roles.map(&:id) rescue []
status_settings = (role_ids.collect do |role_id|
- AnnouncementSetting.first.anns_status_settings.select{|v| v.role_id.to_s == role_id.to_s}
+ CurationtSetting.first.anns_status_settings.select{|v| v.role_id.to_s == role_id.to_s}
end.flatten rescue [])
reach_limit = []
if status_settings.count != 0
@@ -239,7 +225,7 @@ class Bulletin
self.display_img rescue false
end
def comments
- self.bulletin_comments.select{|v| !v.is_hidden}
+ self.curation_post_comments.select{|v| !v.is_hidden}
end
def open_comment_for_user(user)
role_ids = user.member_profile.roles.collect{|v| v.id.to_s} rescue ['visitor']
@@ -267,26 +253,21 @@ class Bulletin
status.html_safe
end
def top_text
- I18n.t("announcement.status.top")
+ I18n.t("curation.status.top")
end
def hot_text
- I18n.t("announcement.status.hot")
+ I18n.t("curation.status.hot")
end
def hidden_text
I18n.t("announcement.status.hidden")
end
def carousel_image_type
- (self.custom_carousel_image_type == 0 ? AnnouncementSetting.last.carousel_image_type : self.custom_carousel_image_type - 1) rescue 0
+ (self.custom_carousel_image_type == 0 ? CurationSetting.last.carousel_image_type : self.custom_carousel_image_type - 1) rescue 0
end
def carousel_image_width
- (self.custom_carousel_image_width.blank? ? AnnouncementSetting.last.carousel_image_width : self.custom_carousel_image_width) rescue "75%"
- end
- def self.agenda_events(agenda_start, agenda_end,read_more_url)
- events = self.monthly_event(agenda_start, agenda_end).convert_front(read_more_url)
- end
- def self.monthly_event(start_date,end_date)
- self.any_of({:postdate.lte => start_date,:deadline.gte => start_date},{:postdate.gte => start_date,:deadline.lte => end_date},{:postdate.lte => end_date,:deadline.gte => end_date}).asc(:postdate)
+ (self.custom_carousel_image_width.blank? ? CurationSetting.last.carousel_image_width : self.custom_carousel_image_width) rescue "75%"
end
+
def self.convert_front(read_more_url)
self.all.collect do |re|
{:id => re.id.to_s,
@@ -301,7 +282,7 @@ class Bulletin
end
def get_sub_annc_title_trans(locale=I18n.locale)
I18n.with_locale(locale) do
- self.custom_sub_annc_title_trans.blank? ? (AnnouncementSetting.first.get_sub_annc_title_trans(locale) rescue I18n.t("announcement.table.title")) : self.custom_sub_annc_title_trans
+ self.custom_sub_annc_title_trans.blank? ? (CurationSetting.first.get_sub_annc_title_trans(locale) rescue I18n.t("curation.table.title")) : self.custom_sub_annc_title_trans
end
end
def get_sub_annc_list
@@ -313,16 +294,16 @@ class Bulletin
end
def enable_annc_dept
if defined?(OrbitHelper::SharedHash) && OrbitHelper::SharedHash
- OrbitHelper::SharedHash['announcement'][:enable_annc_dept] rescue AnnouncementSetting.first.enable_annc_dept
+ OrbitHelper::SharedHash['curation'][:enable_annc_dept] rescue CurationSetting.first.enable_annc_dept
else
- AnnouncementSetting.first.enable_annc_dept rescue false
+ CurationSetting.first.enable_annc_dept rescue false
end
end
def annc_depts_translations
if defined?(OrbitHelper::SharedHash) && OrbitHelper::SharedHash
- OrbitHelper::SharedHash['announcement'][:annc_depts_translations] rescue AnnouncementSetting.first.annc_depts_translations
+ OrbitHelper::SharedHash['curation'][:annc_depts_translations] rescue CurationSetting.first.annc_depts_translations
else
- AnnouncementSetting.first.annc_depts_translations rescue {}
+ CurationSetting.first.annc_depts_translations rescue {}
end
end
def self.smart_convertor(text,url)
@@ -377,7 +358,7 @@ class Bulletin
if tag_ids.nil?
tag_ids = self.tag_ids
end
- basic_query = {:module => 'announcement',:enabled_for=>locale}
+ basic_query = {:module => 'curation',:enabled_for=>locale}
if !cat_ids.blank?
query = basic_query.merge({:categories.all => cat_ids})
else
@@ -423,142 +404,35 @@ class Bulletin
a["author"] = author
a["params"] = self.to_param
a["subtitle_ann"] = self.subtitle if self.display_subtitle?
- a["bulletin_links"] = []
- a["bulletin_files"] = []
- a["bulletin_carousel_images"] = self.bulletin_carousel_images.map{|image| {"src"=>"#{base_url}" + image.file.url,"description"=>image.description.to_s,"description_text"=>image.description_text }}
+ a["curation_post_links"] = []
+ a["curation_post_files"] = []
+ a["curation_post_carousel_images"] = self.curation_post_carousel_images.map{|image| {"src"=>"#{base_url}" + image.file.url,"description"=>image.description.to_s,"description_text"=>image.description_text }}
a["external_link"] = self["is_external_link"] ? self.external_link : nil
self.tags.each do |tag|
a["tags"] << {"name_translations" => tag.name_translations}
end
cat = self.category
a["category"] = {"title_translations" => (cat.title_translations rescue {})}
- self.bulletin_links.each do |bl|
+ self.curation_post_links.each do |bl|
b = {}
b["url"] = bl.url
b["title_translations"] = bl.title_translations
- a["bulletin_links"] << b
+ a["curation_post_links"] << b
end
- self.bulletin_files.each do |bf|
+ self.curation_post_files.each do |bf|
b = {}
b["description_translations"] = bf.description_translations
b["title_translations"] = bf.title_translations
b["url"] = ("#{base_url}" + bf.file.url rescue "")
- a["bulletin_files"] << b
+ a["curation_post_files"] << b
end
return a
end
- def get_related_feeds
- @category_id ||= self.category_id
- @tag_ids ||= self.tag_ids
- related_feeds = BulletinFeed.any_of({:category_ids=>@category_id.to_s}, {:tag_ids.in=>@tag_ids.map(&:to_s)}).to_a
- end
- def notify_feed(type="create")
- if @is_hidden_changed
- if self.is_hidden
- if type == 'create'
- return []
- else
- type = 'destroy'
- end
- else
- type = 'create'
- end
- elsif self.is_hidden
- return []
- end
- related_feeds = self.get_related_feeds.select{|feed| feed.remote_urls.count != 0}
- if related_feeds.count != 0
- bulletin_data = self.get_data
- if type == "destroy"
- tmp_data = {'type'=>'destroy', 'data'=>[self.uid]}
- else
- tmp_data = {'type'=>type, 'data'=>[bulletin_data.to_json]}
- end
- request = Net::HTTP::Post.new('/xhr/feeds/notify_change', 'Content-Type' => 'application/json')
- related_feeds.each do |feed|
- tmp_data['uid'] = feed.uid
- request.body = tmp_data.to_json
- feed.remote_urls.each do |remote_url|
- uri = URI(remote_url)
- http_req = Net::HTTP.new(uri.host, uri.port)
- if remote_url.include?('https')
- http_req.use_ssl = true
- end
- response = self.class.http_request( http_req , request )
- end
- end
- end
- end
def migrate_title_plain_text
self.title_plain_text_translations = OrbitHelper.get_plain_text_translations(self.title_translations)
end
- def self.notify_all_feed(force_update=false)
- related_feeds = BulletinFeed.where(:remote_urls.nin=>[nil, []]).to_a
- related_feeds.each do |feed|
- uid = feed.uid
- startdt = nil
- enddt = nil
- dt = nil
- feed_cache = BulletinFeedCache.where(uid: uid, start: startdt, end: enddt, date: dt)
- if force_update
- feed_cache = nil
- else
- feed_cache_old = feed_cache.all_of([{:invalid_date.ne=>nil},{:invalid_date.lte => Time.now}]).last
- feed_cache.all_of([{:invalid_date.ne=>nil},{:invalid_date.lte => Time.now}]).destroy
- count = feed_cache.count
- if count > 1
- feed_cache.limit(count-1).destroy
- end
- feed_cache = feed_cache.first
- anns = ''
- end
- if feed_cache.nil?
- anns = feed.generate_one_cache_timeout(startdt: startdt,enddt: enddt,dt: dt,timeout: 20)
- anns = (feed_cache_old.content rescue "") if anns.nil?
- else
- anns = feed_cache.content
- end
- request = Net::HTTP::Post.new('/xhr/feeds/notify_change', 'Content-Type' => 'application/json')
- tmp_data = {'type'=>'update_all', 'uid'=> uid, 'data'=>anns}
- request.body = tmp_data.to_json
- feed.remote_urls.each do |remote_url|
- uri = URI(remote_url)
- http_req = Net::HTTP.new(uri.host, uri.port)
- if remote_url.include?('https')
- http_req.use_ssl = true
- end
- response = self.http_request( http_req , request )
- end
- end
- end
- def self.notify_feed_delete(ids)
- all_feeds = BulletinFeed.all.select{|feed| feed.remote_urls.count != 0}
- if all_feeds.count != 0
- tmp_data = {'type'=>'destroy'}
- request = Net::HTTP::Post.new('/xhr/feeds/notify_change', 'Content-Type' => 'application/json')
- all_feeds.each do |feed|
- feed_uid = feed.uid
- feed_cache = BulletinFeedCache.where(:uid=>feed_uid).first
- if feed_cache
- tmp_data['uid'] = feed_uid
- tmp_data['data'] = ids & JSON.parse(feed_cache.content)["announcements"].map{|a| a["id"]}
- request.body = tmp_data.to_json
- if tmp_data['data'].count != 0
- feed.remote_urls.each do |remote_url|
- uri = URI(remote_url)
- http_req = Net::HTTP.new(uri.host, uri.port)
- if remote_url.include?('https')
- http_req.use_ssl = true
- end
- response = self.http_request( http_req , request )
- end
- end
- end
- end
- end
- end
def self.http_request(http, request)
response = http.request(request)
if response.code.to_i == 301 || response.code.to_i == 302
diff --git a/app/models/bulletin_carousel_image.rb b/app/models/curation_post_carousel_image.rb
similarity index 81%
rename from app/models/bulletin_carousel_image.rb
rename to app/models/curation_post_carousel_image.rb
index 47e6c93..42e95f4 100644
--- a/app/models/bulletin_carousel_image.rb
+++ b/app/models/curation_post_carousel_image.rb
@@ -1,5 +1,5 @@
# encoding: utf-8
-class BulletinCarouselImage
+class CurationPostCarouselImage
include Mongoid::Document
include Mongoid::Timestamps
@@ -8,7 +8,7 @@ class BulletinCarouselImage
field :description, localize: true
- belongs_to :bulletin
+ belongs_to :curation_post
def description_text
Nokogiri::HTML(self.description.to_s).css("body").text() rescue ""
end
diff --git a/app/models/bulletin_comment.rb b/app/models/curation_post_comment.rb
similarity index 89%
rename from app/models/bulletin_comment.rb
rename to app/models/curation_post_comment.rb
index 9ca0570..bde1c94 100644
--- a/app/models/bulletin_comment.rb
+++ b/app/models/curation_post_comment.rb
@@ -1,8 +1,8 @@
# encoding: utf-8
-class BulletinComment
+class CurationPostComment
include Mongoid::Document
include Mongoid::Timestamps
-
+
field :ip
field :comment
field :account_id
@@ -17,5 +17,5 @@ class BulletinComment
def roles
MemberProfile.where(:id => self.account_id).collect{|v| v.roles}.flatten
end
- belongs_to :bulletin
-end
\ No newline at end of file
+ belongs_to :curation_post
+end
diff --git a/app/models/bulletin_file.rb b/app/models/curation_post_file.rb
similarity index 85%
rename from app/models/bulletin_file.rb
rename to app/models/curation_post_file.rb
index 01fa4fb..44adb4a 100644
--- a/app/models/bulletin_file.rb
+++ b/app/models/curation_post_file.rb
@@ -1,5 +1,5 @@
# encoding: utf-8
-class BulletinFile
+class CurationPostFile
include Mongoid::Document
include Mongoid::Timestamps
@@ -10,14 +10,14 @@ class BulletinFile
field :title, localize: true
field :choose_lang, :type => Array, :default => ["en","zh_tw"]
field :privacy_type, type: String, default: 'public'
- belongs_to :bulletin
+ belongs_to :curation_post
def self.to_fronted(locale=I18n.locale)
self.all.map{|file| file.to_fronted(locale)}.compact rescue []
end
def to_fronted(locale=I18n.locale)
file = self
- (file.enabled_for?(locale) && !file[:file].blank?) ? { "file_url" => "/xhr/announcements/file/#{file.id}/#{file['file']}" + "\" title=\"#{file.file_title}",
- "file_title" => (file.title.blank? ? URI.unescape(File.basename(file.file.path)) : file.title rescue '')
+ (file.enabled_for?(locale) && !file[:file].blank?) ? { "file_url" => "/xhr/curations/file/#{file.id}/#{file['file']}" + "\" title=\"#{file.file_title}",
+ "file_title" => (file.title.blank? ? URI.unescape(File.basename(file.file.path)) : file.title rescue '')
} : nil rescue nil
end
diff --git a/app/models/bulletin_link.rb b/app/models/curation_post_link.rb
similarity index 90%
rename from app/models/bulletin_link.rb
rename to app/models/curation_post_link.rb
index ccb9b52..751c103 100644
--- a/app/models/bulletin_link.rb
+++ b/app/models/curation_post_link.rb
@@ -1,17 +1,17 @@
# encoding: utf-8
require 'uri'
-class BulletinLink
+class CurationPostLink
include Mongoid::Document
include Mongoid::Timestamps
-
+
field :url
field :title, localize: true
-
- belongs_to :bulletin
+
+ belongs_to :curation_post
before_save :add_http
-
+
#validates :url, :presence => true, :format => /\A(http|https):\/\/(([a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5})|((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?))(:[0-9]{1,5})?(\/.*)?\Z/i
protected
@@ -23,4 +23,4 @@ class BulletinLink
end
end
-end
\ No newline at end of file
+end
diff --git a/app/models/announcement_setting.rb b/app/models/curation_setting.rb
similarity index 74%
rename from app/models/announcement_setting.rb
rename to app/models/curation_setting.rb
index 22cfe92..397fc04 100644
--- a/app/models/announcement_setting.rb
+++ b/app/models/curation_setting.rb
@@ -1,4 +1,4 @@
-class AnnouncementSetting
+class CurationPostSetting
include Mongoid::Document
include Mongoid::Timestamps
field :carousel_image_type, :type => Integer, :default => 0 # 0: carousel, 1: album
@@ -24,7 +24,7 @@ class AnnouncementSetting
def self.check_limit_for_user(user_id, b_id = nil)
limit = self.first.top_limit rescue 0
return true if limit == 0
- count = Bulletin.where(:is_top => true, :create_user_id => user_id, :id.ne => b_id).count
+ count = CurationPost.where(:is_top => true, :create_user_id => user_id, :id.ne => b_id).count
return count < limit
end
@@ -34,18 +34,18 @@ class AnnouncementSetting
def get_sub_annc_title_trans(locale=I18n.locale)
I18n.with_locale(locale) do
- self.sub_annc_title_trans.blank? ? I18n.t("announcement.table.title") : self.sub_annc_title_trans
+ self.sub_annc_title_trans.blank? ? I18n.t("curation.table.title") : self.sub_annc_title_trans
end
end
before_save do
can_update_shared_hash = (defined?(OrbitHelper::SharedHash) && OrbitHelper::SharedHash)
if self.enable_manually_sort_changed? && self.enable_manually_sort
- Bulletin.index({approved: -1,is_hidden: 1,is_preview: 1, is_top: -1,sort_number: 1,postdate: -1,_id: -1,deadline: -1}, { unique: false, background: true })
- Bulletin.create_indexes
+ CurationPost.index({approved: -1,is_hidden: 1,is_preview: 1, is_top: -1,sort_number: 1,postdate: -1,_id: -1,deadline: -1}, { unique: false, background: true })
+ CurationPost.create_indexes
if can_update_shared_hash
OrbitHelper::SharedMutex.synchronize do
- OrbitHelper::SharedHash["announcement"][:enable_manually_sort] = self.enable_manually_sort
+ OrbitHelper::SharedHash["curation"][:enable_manually_sort] = self.enable_manually_sort
end
end
@need_update_bulletin = true
@@ -54,7 +54,7 @@ class AnnouncementSetting
if self.enable_annc_dept_changed?
if can_update_shared_hash
OrbitHelper::SharedMutex.synchronize do
- OrbitHelper::SharedHash["announcement"][:enable_annc_dept] = self.enable_annc_dept
+ OrbitHelper::SharedHash["curation"][:enable_annc_dept] = self.enable_annc_dept
end
end
@need_update_bulletin = true
@@ -62,7 +62,7 @@ class AnnouncementSetting
if self.annc_depts_changed?
if can_update_shared_hash
OrbitHelper::SharedMutex.synchronize do
- OrbitHelper::SharedHash["announcement"][:annc_depts_translations] = self.annc_depts_translations
+ OrbitHelper::SharedHash["curation"][:annc_depts_translations] = self.annc_depts_translations
end
end
@need_update_bulletin = true
@@ -71,9 +71,8 @@ class AnnouncementSetting
after_save do
if @need_update_bulletin
Thread.new do
- AnnsCache.all.delete
- Bulletin.notify_all_feed(true)
+ CurationCache.all.delete
end
end
end
-end
\ No newline at end of file
+end
diff --git a/app/models/anns_status_setting.rb b/app/models/curation_status_setting.rb
similarity index 55%
rename from app/models/anns_status_setting.rb
rename to app/models/curation_status_setting.rb
index 75413a0..7cd6e4d 100644
--- a/app/models/anns_status_setting.rb
+++ b/app/models/curation_status_setting.rb
@@ -1,7 +1,7 @@
-class AnnsStatusSetting
+class CurationStatusSetting
include Mongoid::Document
field :role_id
field :status
field :top_limit
- belongs_to :announcement_setting
-end
\ No newline at end of file
+ belongs_to :curation_setting
+end
diff --git a/config/initializers/scheduler.rb b/config/initializers/scheduler.rb
index 24f6666..b1348c4 100644
--- a/config/initializers/scheduler.rb
+++ b/config/initializers/scheduler.rb
@@ -5,5 +5,5 @@ scheduler = Rufus::Scheduler.new
#return if defined?(Rails::Console) || Rails.env.test? || File.split($0).last == 'rake'
scheduler.cron '43 2 * * *' do
- system('bundle exec rake bulletin:remove_preview_bulletins')
+ system('bundle exec rake curation:remove_preview_curation_posts')
end
diff --git a/config/locales/en.yml b/config/locales/en.yml
index bb04029..8cbdcb5 100644
--- a/config/locales/en.yml
+++ b/config/locales/en.yml
@@ -2,7 +2,7 @@ en:
restful_actions:
feed: Feed
import: Import
- announcement:
+ curation:
read_from_cache: "Read from cache!"
delete_selected: "Delete Selected"
expired: This announcement has been expired.
diff --git a/config/locales/zh_tw.yml b/config/locales/zh_tw.yml
index c4a5274..9c8cdc7 100644
--- a/config/locales/zh_tw.yml
+++ b/config/locales/zh_tw.yml
@@ -3,7 +3,7 @@ zh_tw:
feed: 供給
import: 匯入
get_all_anncs_without_subannc: "選擇相關公告"
- announcement:
+ curation:
read_from_cache: "從暫存中讀取!"
delete_selected: "刪除所選"
expired: 此則公告已過期
diff --git a/curation.gemspec b/curation.gemspec
new file mode 100644
index 0000000..7e79c8c
--- /dev/null
+++ b/curation.gemspec
@@ -0,0 +1,173 @@
+# encoding: UTF-8
+$:.push File.expand_path("../lib", __FILE__)
+
+# Maintain your gem's version:
+require "curation/version"
+require "json"
+bundle_update_flag = ARGV[0]=='update' || ARGV[0]=='install'
+if bundle_update_flag
+ require File.expand_path("../update_curation_post", __FILE__)
+ env_pwd = ENV['PWD']
+ begin
+ require ::File.expand_path('app/helpers/bundler_helper.rb', env_pwd)
+ extend BundlerHelper
+ rescue LoadError
+ def bundler_with_clean_env(&block)
+ if block_given?
+ if Bundler.respond_to?(:with_unbundled_env)
+ Bundler.with_unbundled_env(&block)
+ else
+ Bundler.with_clean_env(&block)
+ end
+ end
+ end
+ end
+ app_path = File.expand_path(__dir__)
+ template_path = env_pwd + '/app/templates'
+ all_template = Dir.glob(template_path+'/*/')
+ default_info_contents = JSON.parse(File.read("#{app_path}/modules/curation/info.json")) rescue {}
+ default_event_news_index_info = default_info_contents["frontend"].sort_by{|h| h["filename"].to_f} rescue []
+ default_event_news_widget_info = default_info_contents["widgets"].sort_by{|h| h["filename"].to_f} rescue []
+ default_event_news_show_info = default_info_contents["show"] rescue nil
+ all_template.each do |folder|
+ if !folder.include?('mobile')
+ if Dir.exist?("#{folder}modules/curation")
+ bundler_with_clean_env{system ("cp -rf #{folder}modules/curation #{folder}modules/curation && rm -rf #{folder}modules/curation")}
+ end
+ if Dir.exist?("#{folder}modules/curation/curation")
+ bundler_with_clean_env{system ("cp -rf #{folder}modules/curation/curation/* #{folder}modules/curation/. && rm -rf #{folder}modules/curation/curation")}
+ end
+ info_json_file = "#{folder}modules/curation/info.json"
+ if File.exist?(info_json_file)
+ bundler_with_clean_env{system ('cp -f '+ app_path + '/modules/curation/show.html.erb ' + "#{folder}modules/curation/.")}
+ update_event_news_template(folder)
+ begin
+ file_text = File.read(info_json_file) rescue ""
+ encode_file_text = file_text.encode("UTF-8", "UTF-8", invalid: :replace, replace: "???")
+ next if (encode_file_text.include?("???") rescue true)
+ info = JSON.parse(encode_file_text) rescue {}
+ flag = (info.count != 0 rescue false)
+ if flag
+ puts "Checking curation index"
+ index_info = info["frontend"].sort_by{|h| h["filename"].to_i} rescue []
+ last_index = index_info.collect{|v| v["filename"].to_s.scan(/\d+/).collect{|v1| v1.to_i}}.flatten.sort[-1] rescue nil
+ update_index_flag = false
+ if !last_index.nil?
+ idx_regex = /^(\d+[\. \t]*)|[ \t]+$/
+ default_event_news_index_info.each do |h|
+ name_without_index = h["name"]["zh_tw"].gsub(idx_regex,'')
+ index_info_index = (index_info.index{|hh| hh["name"]["zh_tw"].gsub(idx_regex,'') == name_without_index}||-1 rescue -1)
+ if index_info_index == -1
+ update_index_flag = true
+ copy_h = h.dup
+ h.delete("force_cover")
+ last_index = last_index + 1
+ copy_h["filename"] = copy_h["filename"].sub(/\d+/){|ff| last_index.to_s}
+ copy_h["name"].keys.each do |locale|
+ copy_h["name"][locale] = copy_h["name"][locale].sub(/\d+/){|ff| last_index.to_s}
+ end
+ index_info << copy_h
+ bundler_with_clean_env{%x[cp -f #{app_path}/modules/curation/#{h["filename"]}.html.erb #{folder}modules/curation/#{copy_h["filename"]}.html.erb]}
+ elsif h["force_cover"] == "true"
+ bundler_with_clean_env{%x[cp -f #{app_path}/modules/curation/#{h["filename"]}.html.erb #{folder}modules/curation/#{index_info[index_info_index]["filename"]}.html.erb]}
+ end
+ end
+ if update_index_flag
+ info["frontend"] = index_info
+ puts "Writing json #{info["frontend"].count} in #{info_json_file}"
+ end
+ end
+ puts "Checking event_news widgets"
+ widget_info = info["widgets"].sort_by{|h| h["filename"].to_i} rescue []
+ last_index = widget_info.collect{|v| v["filename"].to_s.scan(/\d+/).collect{|v1| v1.to_i}}.flatten.sort[-1] rescue nil
+ update_widget_flag = false
+ if !last_index.nil?
+ idx_regex = /^(\d+[\. \t]*)|[ \t]+$/
+ default_event_news_widget_info.each do |h|
+ name_without_index = h["name"]["zh_tw"].gsub(idx_regex,'')
+ widget_info_index = (widget_info.index{|hh| hh["name"]["zh_tw"].gsub(idx_regex,'') == name_without_index}||-1 rescue -1)
+ if widget_info_index == -1
+ update_widget_flag = true
+ copy_h = h.dup
+ h.delete("force_cover")
+ last_index = last_index + 1
+ copy_h["filename"] = copy_h["filename"].sub(/\d+/){|ff| last_index.to_s}
+ copy_h["name"].keys.each do |locale|
+ copy_h["name"][locale] = copy_h["name"][locale].sub(/\d+/){|ff| last_index.to_s}
+ end
+ widget_info << copy_h
+ bundler_with_clean_env{%x[cp -f #{app_path}/modules/curation/_#{h["filename"]}.html.erb #{folder}modules/curation/_#{copy_h["filename"]}.html.erb]}
+ elsif h["force_cover"] == "true"
+ bundler_with_clean_env{%x[cp -f #{app_path}/modules/curation/_#{h["filename"]}.html.erb #{folder}modules/event_news_mod/_#{widget_info[widget_info_index]["filename"]}.html.erb]}
+ end
+ end
+ if update_widget_flag
+ info["widgets"] = widget_info
+ puts "Writing json #{info["widgets"].count} in #{info_json_file}"
+ end
+ end
+
+ update_show_flag = false
+ if !default_event_news_show_info.nil?
+ update_show_flag = info["show"] != default_event_news_show_info
+ info["show"] = default_event_news_show_info
+ default_event_news_show_info.each do |info_detail|
+ filename = info_detail['filename']
+ bundler_with_clean_env{%x[cp -f #{app_path}/modules/curation/#{filename}.html.erb #{folder}modules/curation/#{filename}.html.erb]}
+ end
+ end
+
+ if update_index_flag || update_widget_flag || update_show_flag
+ begin
+ info_json = JSON.pretty_generate(info).gsub(":[",":[\n").gsub(":{",":{\n")
+ rescue
+ info_json = info.to_s.gsub("=>",": \n")
+ end
+ File.open(info_json_file,"w+"){|f| f.write(info_json)}
+ end
+ end
+ rescue => e
+ puts e
+ puts "There has some error when checking event_news widgets"
+ end
+ else
+ if !Dir.exist?(File.dirname(info_json_file)) && Dir.exist?(File.dirname(File.dirname(info_json_file)))
+ bundler_with_clean_env{system ('cp -r '+ app_path + '/modules/ ' + folder)}
+ end
+ end
+ end
+ end
+
+ # all_template.each do |folder|
+ # if !folder.include?('mobile')
+ # moudle_path = "#{folder}modules/universal_table/"
+ # begin
+ # if Dir.exist?(File.dirname(moudle_path))
+ # bundler_with_clean_env{system ('cp -r '+ app_path + '/modules/ ' + folder)}
+ # end
+ # rescue => e
+ # puts "There was some error when updating event_news widget."
+ # end
+ # end
+ # end
+end
+# Describe your gem and declare its dependencies:
+Gem::Specification.new do |s|
+ s.name = "curation"
+ s.version = Curation::VERSION
+ s.authors = ["RulingDigital"]
+ s.email = ["orbit@rulingcom.com"]
+ s.homepage = "http://www.rulingcom.com"
+ s.summary = "Curation for Orbit"
+ s.description = "Curation for Orbit"
+ s.license = "MIT"
+ s.metadata = {
+ "_require" => "#{File.expand_path("../app/models/curation_setting", __FILE__)}",
+ "global_hash" => "{enable_manually_sort: (CurationSetting.first.enable_manually_sort rescue false), is_postdate_sort_first: (CurationSetting.first.is_postdate_sort_first rescue false)}"
+ }
+
+ s.files = Dir["{app,config,db,lib}/**/*", "MIT-LICENSE", "Rakefile", "README.rdoc"]
+ s.test_files = Dir["test/**/*"]
+
+ s.add_dependency "rufus-scheduler", "~> 3.6.0"
+end
diff --git a/lib/announcement.rb b/lib/announcement.rb
deleted file mode 100644
index d706f72..0000000
--- a/lib/announcement.rb
+++ /dev/null
@@ -1,6 +0,0 @@
-require "announcement/engine"
-require "announcement/cache"
-require "announcement/migrate"
-module Announcement
-
-end
diff --git a/lib/announcement/cache.rb b/lib/announcement/cache.rb
deleted file mode 100644
index 202e13f..0000000
--- a/lib/announcement/cache.rb
+++ /dev/null
@@ -1,35 +0,0 @@
-module Announcement
- module Cache
- require 'active_support/concern'
- extend ActiveSupport::Concern
- included do
- after_save :cache_tag_ids, :do_before_save
- after_destroy :do_before_save
- before_destroy :cache_tag_ids
- end
- def cache_tag_ids
- if self.class == ::Bulletin
- @tag_ids = self.tag_ids
- @org_tag_ids = self.org_tag_ids
- @category_id = self.category_id
- @org_category_id = self.org_category_id
- end
- end
- def do_before_save
- if self.class == ::SubPart
- ::AnnsCache.where(parent_id: /^#{self.id}/).delete
- elsif self.class == ::Bulletin || (self.class == ::Page && self.module == "announcement")
- if self.class == ::Bulletin
- tmp_tag_ids = (Array(@tag_ids) + Array(@org_tag_ids)).uniq
- tmp_cat_ids = (Array(@category_id) + Array(@org_category_id)).uniq
- Thread.new do
- ::BulletinFeedCache.where(:uid.in => ::BulletinFeed.any_of([{:tag_ids.in => tmp_tag_ids.collect{|v| v.to_s}},{:category_ids.in => tmp_cat_ids.collect{|v| v.to_s}}]).pluck(:uid)).to_a.each do |cache|
- cache.regenerate
- end
- end
- end
- ::AnnsCache.all.delete
- end
- end
- end
-end
\ No newline at end of file
diff --git a/lib/announcement/migrate.rb b/lib/announcement/migrate.rb
deleted file mode 100644
index f705722..0000000
--- a/lib/announcement/migrate.rb
+++ /dev/null
@@ -1,41 +0,0 @@
-module Announcement
- module Migrate
- def self.call
- puts ['announcement migrate start']
- gem_root = Announcement::Engine.root
- require File.join(gem_root, 'app/models/announcement_setting')
- require File.join(gem_root, 'app/models/bulletin')
- require File.join(gem_root, 'app/models/bulletin_feed')
- require File.join(gem_root, 'app/models/bulletin_feed_cache')
- require File.join(gem_root, 'app/models/anns_cache')
-
- setting = AnnouncementSetting.first || AnnouncementSetting.create
-
- if !setting.migrate_flag.include?("v1")
- Bulletin.all.pluck(:id, :title).each do |id, title_translations|
- if title_translations.nil?
- next
- end
- Bulletin.where(id: id).view.update_many({
- "$set" => {
- title_plain_text: OrbitHelper.get_plain_text_translations(title_translations)
- }
- })
- end
-
- setting.migrate_flag << "v1"
- setting.save
- end
-
- AnnsCache.all.delete
-
- #solve bug for thousands of generated feed cache
- if BulletinFeedCache.count > BulletinFeed.count*5
- BulletinFeedCache.collection.drop
- end
- BulletinFeedCache.regenerate_all
-
- puts ['announcement migrate end']
- end
- end
-end
\ No newline at end of file
diff --git a/lib/curation.rb b/lib/curation.rb
new file mode 100644
index 0000000..1797c22
--- /dev/null
+++ b/lib/curation.rb
@@ -0,0 +1,6 @@
+require "curation/engine"
+require "curation/cache"
+require "curation/migrate"
+module Curation
+
+end
diff --git a/lib/curation/cache.rb b/lib/curation/cache.rb
new file mode 100644
index 0000000..967995f
--- /dev/null
+++ b/lib/curation/cache.rb
@@ -0,0 +1,26 @@
+module Curation
+ module Cache
+ require 'active_support/concern'
+ extend ActiveSupport::Concern
+ included do
+ after_save :cache_tag_ids, :do_before_save
+ after_destroy :do_before_save
+ before_destroy :cache_tag_ids
+ end
+ def cache_tag_ids
+ if self.class == ::CurationPost
+ @tag_ids = self.tag_ids
+ @org_tag_ids = self.org_tag_ids
+ @category_id = self.category_id
+ @org_category_id = self.org_category_id
+ end
+ end
+ def do_before_save
+ if self.class == ::SubPart
+ ::CurationCache.where(parent_id: /^#{self.id}/).delete
+ elsif self.class == ::CurationPost || (self.class == ::Page && self.module == "curation")
+ ::CurationCache.all.delete
+ end
+ end
+ end
+end
diff --git a/lib/announcement/engine.rb b/lib/curation/engine.rb
similarity index 54%
rename from lib/announcement/engine.rb
rename to lib/curation/engine.rb
index a1278dd..5179f6c 100644
--- a/lib/announcement/engine.rb
+++ b/lib/curation/engine.rb
@@ -1,10 +1,10 @@
require "yaml"
-module Announcement
+module Curation
class Engine < ::Rails::Engine
- initializer "announcement" do
+ initializer "curation" do
Rails.application.config.to_prepare do
begin
- translate_data = Dir["#{Announcement::Engine.root}/config/locales/*.yml"] .map{|yaml_file| YAML.load(File.read(yaml_file))}
+ translate_data = Dir["#{Curation::Engine.root}/config/locales/*.yml"] .map{|yaml_file| YAML.load(File.read(yaml_file))}
data = {}
key1 = {}
key2 = {}
@@ -42,29 +42,29 @@ module Announcement
translate_data.each do |t_data|
v = t_data.values
k = t_data.keys[0]
- key1[k] = v[0]['announcement']['picture_showing_size']
- key2[k] = v[0]['announcement']['tabs_options']
- key3[k] = v[0]['announcement']['read_more_position_options']
- key4[k] = v[0]['announcement']['all_tabs_setting']
+ key1[k] = v[0]['curation']['picture_showing_size']
+ key2[k] = v[0]['curation']['tabs_options']
+ key3[k] = v[0]['curation']['read_more_position_options']
+ key4[k] = v[0]['curation']['all_tabs_setting']
key1_options.each_with_index do |kk,i|
- key1_attr[i][k] = v[0]['announcement'][kk]
+ key1_attr[i][k] = v[0]['curation'][kk]
end
key2_options.each_with_index do |kk,i|
- key2_attr[i][k] = v[0]['announcement'][kk]
+ key2_attr[i][k] = v[0]['curation'][kk]
end
key3_options.each_with_index do |kk,i|
- key3_attr[i][k] = v[0]['announcement'][kk]
+ key3_attr[i][k] = v[0]['curation'][kk]
end
key4_options.each_with_index do |kk,i|
- key4_attr[i][k] = v[0]['announcement'][kk]
+ key4_attr[i][k] = v[0]['curation'][kk]
end
- key_item1[k] = v[0]['announcement']['showing_back_and_next']
- key_item2[k] = v[0]['announcement']['enable_search']
- value_item1[k] = v[0]['announcement']['not_show']
- value_item2[k] = v[0]['announcement']['show_bottom']
- value_item3[k] = v[0]['announcement']['show_top']
- value2_item1[k] = v[0]['announcement']['no']
- value2_item2[k] = v[0]['announcement']['yes']
+ key_item1[k] = v[0]['curation']['showing_back_and_next']
+ key_item2[k] = v[0]['curation']['enable_search']
+ value_item1[k] = v[0]['curation']['not_show']
+ value_item2[k] = v[0]['curation']['show_bottom']
+ value_item3[k] = v[0]['curation']['show_top']
+ value2_item1[k] = v[0]['curation']['no']
+ value2_item2[k] = v[0]['curation']['yes']
end
data[key1] = key1_attr
data[key2] = key2_attr
@@ -74,7 +74,7 @@ module Announcement
data_item[key_item2] = [value2_item1,value2_item2]
data_item[key1] = key1_attr
rescue => e
- puts ['error in announcement',e]
+ puts ['error in curation',e]
end
if ENV['worker_num']=='0' && File.basename($0) != 'rake' && !Rails.const_defined?('Console')
@@ -82,21 +82,21 @@ module Announcement
begin
Migrate.call
rescue => e
- puts ['error in announcement', e, e.backtrace]
+ puts ['error in curation', e, e.backtrace]
end
end
end
- OrbitApp.registration "Announcement", :type => "ModuleApp" do
- module_label "announcement.announcement"
+ OrbitApp.registration "Curation", :type => "ModuleApp" do
+ module_label "curation.curation"
base_url File.expand_path File.dirname(__FILE__)
- widget_methods ["widget","random_announcement_widget", "tag_cloud"]
+ widget_methods ["widget","random_curation_widget", "tag_cloud"]
widget_settings [{"data_count"=>30}]
- taggable "Bulletin"
+ taggable "CurationPost"
categorizable
authorizable
frontend_enabled
- feeds_url "/xhr/announcements/feeds"
+ feeds_url "/xhr/curations/feeds"
data_count 1..30
begin
show_options data
@@ -106,61 +106,47 @@ module Announcement
end
if File.basename($0) != 'rake'
gem_root = Announcement::Engine.root
- require File.join(gem_root, 'app/models/bulletin_feed')
- require File.join(gem_root, 'app/models/bulletin_feed_cache')
- require File.join(gem_root, 'app/models/anns_cache')
+ require File.join(gem_root, 'app/models/curation_cache')
begin
avoid_page_cache AnnsCache
- avoid_page_cache BulletinFeedCache
- avoid_page_cache BulletinFeed
rescue => e
puts ["avoid_page_cache", e.to_s]
end
end
side_bar do
- head_label_i18n 'announcement.announcement', icon_class: "icons-megaphone"
+ head_label_i18n 'curation.curation', icon_class: "icons-megaphone"
available_for "users"
- active_for_controllers (['admin/announcements'])
- head_link_path "admin_announcements_path"
+ active_for_controllers (['admin/curations'])
+ head_link_path "admin_curations_path"
- context_link 'announcement.all_articles',
- :link_path=>"admin_announcements_path" ,
+ context_link 'curation.all_articles',
+ :link_path=>"admin_curations_path" ,
:priority=>1,
- :active_for_action=>{'admin/announcements'=>'index'},
+ :active_for_action=>{'admin/curations'=>'index'},
:available_for => 'users'
- context_link 'announcement.manually_sort',
- :link_path=>"edit_sort_admin_announcement_path" ,
+ context_link 'curation.manually_sort',
+ :link_path=>"edit_sort_admin_curation_path" ,
:priority=>2,
- :active_for_action=>{'admin/announcement'=>'edit_sort'},
+ :active_for_action=>{'admin/curation'=>'edit_sort'},
:available_for => 'managers'
- context_link 'new_',
- :link_path=>"new_admin_announcement_path" ,
+ context_link 'new_',
+ :link_path=>"new_admin_curation_path" ,
:priority=>3,
- :active_for_action=>{'admin/announcements'=>'new'},
+ :active_for_action=>{'admin/curations'=>'new'},
:available_for => 'sub_managers'
context_link 'categories',
:link_path=>"admin_module_app_categories_path" ,
- :link_arg=>"{:module_app_id=>ModuleApp.find_by(:key=>'announcement').id}",
+ :link_arg=>"{:module_app_id=>ModuleApp.find_by(:key=>'curation').id}",
:priority=>4,
- :active_for_action=>{'admin/announcements'=>'categories'},
- :active_for_category => 'Announcement',
+ :active_for_action=>{'admin/curations'=>'categories'},
+ :active_for_category => 'Curation',
:available_for => 'managers'
context_link 'tags',
:link_path=>"admin_module_app_tags_path" ,
- :link_arg=>"{:module_app_id=>ModuleApp.find_by(:key=>'announcement').id}",
+ :link_arg=>"{:module_app_id=>ModuleApp.find_by(:key=>'curation').id}",
:priority=>5,
- :active_for_action=>{'admin/announcements'=>'tags'},
- :active_for_tag => 'Announcement',
- :available_for => 'managers'
- context_link 'announcement.feed_list',
- :link_path=>"admin_announcement_feed_path" ,
- :priority=>6,
- :active_for_action=>{'admin/announcements'=>'feed'},
- :available_for => 'managers'
- context_link 'announcement.import',
- :link_path=>"admin_announcement_import_path" ,
- :priority=>7,
- :active_for_action=>{'admin/announcements'=>'import'},
+ :active_for_action=>{'admin/curations'=>'tags'},
+ :active_for_tag => 'Curation',
:available_for => 'managers'
context_link 'announcement.settings',
:link_path=>"admin_announcement_settings_path" ,
@@ -172,9 +158,9 @@ module Announcement
# temp = YAML.load_file(File.join(Rails.root,"config","mongoid.yml"))
# dbsettings = temp["production"]["sessions"]["default"]
# s = Moped::Session.new(dbsettings["hosts"])
- # s.use dbsettings["database"]
+ # s.use dbsettings["database"]
# s[:bulletins].indexes.create({expirable_created_at: 1},{ expireAfterSeconds: 180 })
end
end
end
-end
\ No newline at end of file
+end
diff --git a/lib/curation/migrate.rb b/lib/curation/migrate.rb
new file mode 100644
index 0000000..5d1ce20
--- /dev/null
+++ b/lib/curation/migrate.rb
@@ -0,0 +1,32 @@
+module Curation
+ module Migrate
+ def self.call
+ puts ['curation migrate start']
+ gem_root = Curation::Engine.root
+ require File.join(gem_root, 'app/models/curation_setting')
+ require File.join(gem_root, 'app/models/curation_cache')
+
+ setting = CurationSetting.first || CurationSetting.create
+
+ if !setting.migrate_flag.include?("v1")
+ CurationPost.all.pluck(:id, :title).each do |id, title_translations|
+ if title_translations.nil?
+ next
+ end
+ CurationPost.where(id: id).view.update_many({
+ "$set" => {
+ title_plain_text: OrbitHelper.get_plain_text_translations(title_translations)
+ }
+ })
+ end
+
+ setting.migrate_flag << "v1"
+ setting.save
+ end
+
+ CurationCache.all.delete
+
+ puts ['curation migrate end']
+ end
+ end
+end
diff --git a/lib/announcement/version.rb b/lib/curation/version.rb
similarity index 54%
rename from lib/announcement/version.rb
rename to lib/curation/version.rb
index 1b52275..c895ef6 100644
--- a/lib/announcement/version.rb
+++ b/lib/curation/version.rb
@@ -1,3 +1,3 @@
-module Announcement
+module Curation
VERSION = "0.0.1"
end
diff --git a/lib/tasks/bulletin_tasks.rake b/lib/tasks/bulletin_tasks.rake
deleted file mode 100644
index 434204a..0000000
--- a/lib/tasks/bulletin_tasks.rake
+++ /dev/null
@@ -1,8 +0,0 @@
-desc 'Remove duplicated bulletins (announcements) created by preview'
-
-namespace :bulletin do
- task :remove_preview_bulletins => [:environment] do
- bulletins = Bulletin.where(is_preview: true)
- bulletins.destroy_all
- end
-end
diff --git a/lib/tasks/curation_tasks.rake b/lib/tasks/curation_tasks.rake
new file mode 100644
index 0000000..420aa73
--- /dev/null
+++ b/lib/tasks/curation_tasks.rake
@@ -0,0 +1,8 @@
+desc 'Remove duplicated curation posts created by preview'
+
+namespace :curation do
+ task :remove_preview_curation_posts => [:environment] do
+ posts = CurationPost.where(is_preview: true)
+ posts.destroy_all
+ end
+end
diff --git a/modules/announcement/_annc_widget1.html.erb b/modules/curation/_annc_widget1.html.erb
similarity index 100%
rename from modules/announcement/_annc_widget1.html.erb
rename to modules/curation/_annc_widget1.html.erb
diff --git a/modules/announcement/_annc_widget10.html.erb b/modules/curation/_annc_widget10.html.erb
similarity index 100%
rename from modules/announcement/_annc_widget10.html.erb
rename to modules/curation/_annc_widget10.html.erb
diff --git a/modules/announcement/_annc_widget11.html.erb b/modules/curation/_annc_widget11.html.erb
similarity index 100%
rename from modules/announcement/_annc_widget11.html.erb
rename to modules/curation/_annc_widget11.html.erb
diff --git a/modules/announcement/_annc_widget12.html.erb b/modules/curation/_annc_widget12.html.erb
similarity index 100%
rename from modules/announcement/_annc_widget12.html.erb
rename to modules/curation/_annc_widget12.html.erb
diff --git a/modules/announcement/_annc_widget13.html.erb b/modules/curation/_annc_widget13.html.erb
similarity index 100%
rename from modules/announcement/_annc_widget13.html.erb
rename to modules/curation/_annc_widget13.html.erb
diff --git a/modules/announcement/_annc_widget14.html.erb b/modules/curation/_annc_widget14.html.erb
similarity index 100%
rename from modules/announcement/_annc_widget14.html.erb
rename to modules/curation/_annc_widget14.html.erb
diff --git a/modules/announcement/_annc_widget15.html.erb b/modules/curation/_annc_widget15.html.erb
similarity index 100%
rename from modules/announcement/_annc_widget15.html.erb
rename to modules/curation/_annc_widget15.html.erb
diff --git a/modules/announcement/_annc_widget16.html.erb b/modules/curation/_annc_widget16.html.erb
similarity index 100%
rename from modules/announcement/_annc_widget16.html.erb
rename to modules/curation/_annc_widget16.html.erb
diff --git a/modules/announcement/_annc_widget17.html.erb b/modules/curation/_annc_widget17.html.erb
similarity index 100%
rename from modules/announcement/_annc_widget17.html.erb
rename to modules/curation/_annc_widget17.html.erb
diff --git a/modules/announcement/_annc_widget18.html.erb b/modules/curation/_annc_widget18.html.erb
similarity index 100%
rename from modules/announcement/_annc_widget18.html.erb
rename to modules/curation/_annc_widget18.html.erb
diff --git a/modules/announcement/_annc_widget19.html.erb b/modules/curation/_annc_widget19.html.erb
similarity index 100%
rename from modules/announcement/_annc_widget19.html.erb
rename to modules/curation/_annc_widget19.html.erb
diff --git a/modules/announcement/_annc_widget2.html.erb b/modules/curation/_annc_widget2.html.erb
similarity index 100%
rename from modules/announcement/_annc_widget2.html.erb
rename to modules/curation/_annc_widget2.html.erb
diff --git a/modules/announcement/_annc_widget3.html.erb b/modules/curation/_annc_widget3.html.erb
similarity index 100%
rename from modules/announcement/_annc_widget3.html.erb
rename to modules/curation/_annc_widget3.html.erb
diff --git a/modules/announcement/_annc_widget4.html.erb b/modules/curation/_annc_widget4.html.erb
similarity index 100%
rename from modules/announcement/_annc_widget4.html.erb
rename to modules/curation/_annc_widget4.html.erb
diff --git a/modules/announcement/_annc_widget5.html.erb b/modules/curation/_annc_widget5.html.erb
similarity index 100%
rename from modules/announcement/_annc_widget5.html.erb
rename to modules/curation/_annc_widget5.html.erb
diff --git a/modules/announcement/_annc_widget6.html.erb b/modules/curation/_annc_widget6.html.erb
similarity index 100%
rename from modules/announcement/_annc_widget6.html.erb
rename to modules/curation/_annc_widget6.html.erb
diff --git a/modules/announcement/_annc_widget7.html.erb b/modules/curation/_annc_widget7.html.erb
similarity index 100%
rename from modules/announcement/_annc_widget7.html.erb
rename to modules/curation/_annc_widget7.html.erb
diff --git a/modules/announcement/_annc_widget8.html.erb b/modules/curation/_annc_widget8.html.erb
similarity index 100%
rename from modules/announcement/_annc_widget8.html.erb
rename to modules/curation/_annc_widget8.html.erb
diff --git a/modules/announcement/_annc_widget9.html.erb b/modules/curation/_annc_widget9.html.erb
similarity index 100%
rename from modules/announcement/_annc_widget9.html.erb
rename to modules/curation/_annc_widget9.html.erb
diff --git a/modules/announcement/annc_index1.html.erb b/modules/curation/annc_index1.html.erb
similarity index 100%
rename from modules/announcement/annc_index1.html.erb
rename to modules/curation/annc_index1.html.erb
diff --git a/modules/announcement/annc_index10.html.erb b/modules/curation/annc_index10.html.erb
similarity index 100%
rename from modules/announcement/annc_index10.html.erb
rename to modules/curation/annc_index10.html.erb
diff --git a/modules/announcement/annc_index11.html.erb b/modules/curation/annc_index11.html.erb
similarity index 100%
rename from modules/announcement/annc_index11.html.erb
rename to modules/curation/annc_index11.html.erb
diff --git a/modules/announcement/annc_index12.html.erb b/modules/curation/annc_index12.html.erb
similarity index 100%
rename from modules/announcement/annc_index12.html.erb
rename to modules/curation/annc_index12.html.erb
diff --git a/modules/announcement/annc_index13.html.erb b/modules/curation/annc_index13.html.erb
similarity index 100%
rename from modules/announcement/annc_index13.html.erb
rename to modules/curation/annc_index13.html.erb
diff --git a/modules/announcement/annc_index14.html.erb b/modules/curation/annc_index14.html.erb
similarity index 100%
rename from modules/announcement/annc_index14.html.erb
rename to modules/curation/annc_index14.html.erb
diff --git a/modules/announcement/annc_index15.html.erb b/modules/curation/annc_index15.html.erb
similarity index 100%
rename from modules/announcement/annc_index15.html.erb
rename to modules/curation/annc_index15.html.erb
diff --git a/modules/announcement/annc_index16.html.erb b/modules/curation/annc_index16.html.erb
similarity index 100%
rename from modules/announcement/annc_index16.html.erb
rename to modules/curation/annc_index16.html.erb
diff --git a/modules/announcement/annc_index17.html.erb b/modules/curation/annc_index17.html.erb
similarity index 100%
rename from modules/announcement/annc_index17.html.erb
rename to modules/curation/annc_index17.html.erb
diff --git a/modules/announcement/annc_index18.html.erb b/modules/curation/annc_index18.html.erb
similarity index 100%
rename from modules/announcement/annc_index18.html.erb
rename to modules/curation/annc_index18.html.erb
diff --git a/modules/announcement/annc_index2.html.erb b/modules/curation/annc_index2.html.erb
similarity index 100%
rename from modules/announcement/annc_index2.html.erb
rename to modules/curation/annc_index2.html.erb
diff --git a/modules/announcement/annc_index3.html.erb b/modules/curation/annc_index3.html.erb
similarity index 100%
rename from modules/announcement/annc_index3.html.erb
rename to modules/curation/annc_index3.html.erb
diff --git a/modules/announcement/annc_index4.html.erb b/modules/curation/annc_index4.html.erb
similarity index 100%
rename from modules/announcement/annc_index4.html.erb
rename to modules/curation/annc_index4.html.erb
diff --git a/modules/announcement/annc_index5.html.erb b/modules/curation/annc_index5.html.erb
similarity index 100%
rename from modules/announcement/annc_index5.html.erb
rename to modules/curation/annc_index5.html.erb
diff --git a/modules/announcement/annc_index6.html.erb b/modules/curation/annc_index6.html.erb
similarity index 100%
rename from modules/announcement/annc_index6.html.erb
rename to modules/curation/annc_index6.html.erb
diff --git a/modules/announcement/annc_index7.html.erb b/modules/curation/annc_index7.html.erb
similarity index 100%
rename from modules/announcement/annc_index7.html.erb
rename to modules/curation/annc_index7.html.erb
diff --git a/modules/announcement/annc_index8.html.erb b/modules/curation/annc_index8.html.erb
similarity index 100%
rename from modules/announcement/annc_index8.html.erb
rename to modules/curation/annc_index8.html.erb
diff --git a/modules/announcement/annc_index9.html.erb b/modules/curation/annc_index9.html.erb
similarity index 100%
rename from modules/announcement/annc_index9.html.erb
rename to modules/curation/annc_index9.html.erb
diff --git a/modules/announcement/info.json b/modules/curation/info.json
similarity index 100%
rename from modules/announcement/info.json
rename to modules/curation/info.json
diff --git a/modules/announcement/show.html.erb b/modules/curation/show.html.erb
similarity index 100%
rename from modules/announcement/show.html.erb
rename to modules/curation/show.html.erb
diff --git a/modules/announcement/thumbs/annc_index10_thumbs.png b/modules/curation/thumbs/annc_index10_thumbs.png
similarity index 100%
rename from modules/announcement/thumbs/annc_index10_thumbs.png
rename to modules/curation/thumbs/annc_index10_thumbs.png
diff --git a/modules/announcement/thumbs/annc_index11_thumbs.png b/modules/curation/thumbs/annc_index11_thumbs.png
similarity index 100%
rename from modules/announcement/thumbs/annc_index11_thumbs.png
rename to modules/curation/thumbs/annc_index11_thumbs.png
diff --git a/modules/announcement/thumbs/annc_index12_thumbs.png b/modules/curation/thumbs/annc_index12_thumbs.png
similarity index 100%
rename from modules/announcement/thumbs/annc_index12_thumbs.png
rename to modules/curation/thumbs/annc_index12_thumbs.png
diff --git a/modules/announcement/thumbs/annc_index13_thumbs.png b/modules/curation/thumbs/annc_index13_thumbs.png
similarity index 100%
rename from modules/announcement/thumbs/annc_index13_thumbs.png
rename to modules/curation/thumbs/annc_index13_thumbs.png
diff --git a/modules/announcement/thumbs/annc_index14_thumbs.png b/modules/curation/thumbs/annc_index14_thumbs.png
similarity index 100%
rename from modules/announcement/thumbs/annc_index14_thumbs.png
rename to modules/curation/thumbs/annc_index14_thumbs.png
diff --git a/modules/announcement/thumbs/annc_index15_thumbs.png b/modules/curation/thumbs/annc_index15_thumbs.png
similarity index 100%
rename from modules/announcement/thumbs/annc_index15_thumbs.png
rename to modules/curation/thumbs/annc_index15_thumbs.png
diff --git a/modules/announcement/thumbs/annc_index16_thumbs.png b/modules/curation/thumbs/annc_index16_thumbs.png
similarity index 100%
rename from modules/announcement/thumbs/annc_index16_thumbs.png
rename to modules/curation/thumbs/annc_index16_thumbs.png
diff --git a/modules/announcement/thumbs/annc_index19_thumbs.png b/modules/curation/thumbs/annc_index19_thumbs.png
similarity index 100%
rename from modules/announcement/thumbs/annc_index19_thumbs.png
rename to modules/curation/thumbs/annc_index19_thumbs.png
diff --git a/modules/announcement/thumbs/annc_index1_thumbs.png b/modules/curation/thumbs/annc_index1_thumbs.png
similarity index 100%
rename from modules/announcement/thumbs/annc_index1_thumbs.png
rename to modules/curation/thumbs/annc_index1_thumbs.png
diff --git a/modules/announcement/thumbs/annc_index2_thumbs.png b/modules/curation/thumbs/annc_index2_thumbs.png
similarity index 100%
rename from modules/announcement/thumbs/annc_index2_thumbs.png
rename to modules/curation/thumbs/annc_index2_thumbs.png
diff --git a/modules/announcement/thumbs/annc_index3_thumbs.png b/modules/curation/thumbs/annc_index3_thumbs.png
similarity index 100%
rename from modules/announcement/thumbs/annc_index3_thumbs.png
rename to modules/curation/thumbs/annc_index3_thumbs.png
diff --git a/modules/announcement/thumbs/annc_index4_thumbs.png b/modules/curation/thumbs/annc_index4_thumbs.png
similarity index 100%
rename from modules/announcement/thumbs/annc_index4_thumbs.png
rename to modules/curation/thumbs/annc_index4_thumbs.png
diff --git a/modules/announcement/thumbs/annc_index5_thumbs.png b/modules/curation/thumbs/annc_index5_thumbs.png
similarity index 100%
rename from modules/announcement/thumbs/annc_index5_thumbs.png
rename to modules/curation/thumbs/annc_index5_thumbs.png
diff --git a/modules/announcement/thumbs/annc_index6_thumbs.png b/modules/curation/thumbs/annc_index6_thumbs.png
similarity index 100%
rename from modules/announcement/thumbs/annc_index6_thumbs.png
rename to modules/curation/thumbs/annc_index6_thumbs.png
diff --git a/modules/announcement/thumbs/annc_index7_thumbs.png b/modules/curation/thumbs/annc_index7_thumbs.png
similarity index 100%
rename from modules/announcement/thumbs/annc_index7_thumbs.png
rename to modules/curation/thumbs/annc_index7_thumbs.png
diff --git a/modules/announcement/thumbs/annc_index8_thumbs.png b/modules/curation/thumbs/annc_index8_thumbs.png
similarity index 100%
rename from modules/announcement/thumbs/annc_index8_thumbs.png
rename to modules/curation/thumbs/annc_index8_thumbs.png
diff --git a/modules/announcement/thumbs/annc_index9_thumbs.png b/modules/curation/thumbs/annc_index9_thumbs.png
similarity index 100%
rename from modules/announcement/thumbs/annc_index9_thumbs.png
rename to modules/curation/thumbs/annc_index9_thumbs.png
diff --git a/modules/announcement/thumbs/annc_widget10_thumbs.png b/modules/curation/thumbs/annc_widget10_thumbs.png
similarity index 100%
rename from modules/announcement/thumbs/annc_widget10_thumbs.png
rename to modules/curation/thumbs/annc_widget10_thumbs.png
diff --git a/modules/announcement/thumbs/annc_widget11_thumbs.png b/modules/curation/thumbs/annc_widget11_thumbs.png
similarity index 100%
rename from modules/announcement/thumbs/annc_widget11_thumbs.png
rename to modules/curation/thumbs/annc_widget11_thumbs.png
diff --git a/modules/announcement/thumbs/annc_widget12_thumbs.png b/modules/curation/thumbs/annc_widget12_thumbs.png
similarity index 100%
rename from modules/announcement/thumbs/annc_widget12_thumbs.png
rename to modules/curation/thumbs/annc_widget12_thumbs.png
diff --git a/modules/announcement/thumbs/annc_widget13_thumbs.png b/modules/curation/thumbs/annc_widget13_thumbs.png
similarity index 100%
rename from modules/announcement/thumbs/annc_widget13_thumbs.png
rename to modules/curation/thumbs/annc_widget13_thumbs.png
diff --git a/modules/announcement/thumbs/annc_widget14_thumbs.png b/modules/curation/thumbs/annc_widget14_thumbs.png
similarity index 100%
rename from modules/announcement/thumbs/annc_widget14_thumbs.png
rename to modules/curation/thumbs/annc_widget14_thumbs.png
diff --git a/modules/announcement/thumbs/annc_widget1_thumbs.png b/modules/curation/thumbs/annc_widget1_thumbs.png
similarity index 100%
rename from modules/announcement/thumbs/annc_widget1_thumbs.png
rename to modules/curation/thumbs/annc_widget1_thumbs.png
diff --git a/modules/announcement/thumbs/annc_widget2_thumbs.png b/modules/curation/thumbs/annc_widget2_thumbs.png
similarity index 100%
rename from modules/announcement/thumbs/annc_widget2_thumbs.png
rename to modules/curation/thumbs/annc_widget2_thumbs.png
diff --git a/modules/announcement/thumbs/annc_widget3_thumbs.png b/modules/curation/thumbs/annc_widget3_thumbs.png
similarity index 100%
rename from modules/announcement/thumbs/annc_widget3_thumbs.png
rename to modules/curation/thumbs/annc_widget3_thumbs.png
diff --git a/modules/announcement/thumbs/annc_widget4_thumbs.png b/modules/curation/thumbs/annc_widget4_thumbs.png
similarity index 100%
rename from modules/announcement/thumbs/annc_widget4_thumbs.png
rename to modules/curation/thumbs/annc_widget4_thumbs.png
diff --git a/modules/announcement/thumbs/annc_widget5_thumbs.png b/modules/curation/thumbs/annc_widget5_thumbs.png
similarity index 100%
rename from modules/announcement/thumbs/annc_widget5_thumbs.png
rename to modules/curation/thumbs/annc_widget5_thumbs.png
diff --git a/modules/announcement/thumbs/annc_widget6_thumbs.png b/modules/curation/thumbs/annc_widget6_thumbs.png
similarity index 100%
rename from modules/announcement/thumbs/annc_widget6_thumbs.png
rename to modules/curation/thumbs/annc_widget6_thumbs.png
diff --git a/modules/announcement/thumbs/annc_widget7_thumbs.png b/modules/curation/thumbs/annc_widget7_thumbs.png
similarity index 100%
rename from modules/announcement/thumbs/annc_widget7_thumbs.png
rename to modules/curation/thumbs/annc_widget7_thumbs.png
diff --git a/modules/announcement/thumbs/annc_widget8_thumbs.png b/modules/curation/thumbs/annc_widget8_thumbs.png
similarity index 100%
rename from modules/announcement/thumbs/annc_widget8_thumbs.png
rename to modules/curation/thumbs/annc_widget8_thumbs.png
diff --git a/modules/announcement/thumbs/annc_widget9_thumbs.png b/modules/curation/thumbs/annc_widget9_thumbs.png
similarity index 100%
rename from modules/announcement/thumbs/annc_widget9_thumbs.png
rename to modules/curation/thumbs/annc_widget9_thumbs.png
diff --git a/temp_file/Gemfile b/temp_file/Gemfile
deleted file mode 100644
index 3fd3178..0000000
--- a/temp_file/Gemfile
+++ /dev/null
@@ -1,296 +0,0 @@
-begin
- require ::File.expand_path('../app/helpers/bundler_helper.rb', __FILE__)
- extend BundlerHelper
-rescue LoadError
- def bundler_with_clean_env(&block)
- if block_given?
- if Bundler.respond_to?(:with_unbundled_env)
- Bundler.with_unbundled_env(&block)
- else
- Bundler.with_clean_env(&block)
- end
- end
- end
-end
-source 'https://rubygems.org'
-#update all site!!!!!!!!
-if $0.to_s.scan('bundle').length==0
- self.bundler_with_clean_env{
- # Deprecated: bundle show => bundle list, bundle show gem => bundle info gem --path
- # Tested: bundler >= 1.17 will have bundle info and bundle list
- flag = system("bundle info announcement --path >/dev/null 2>&1 || bundle show announcement >/dev/null 2>&1")
- system("bundle install") if !flag
- }
-end
-gem 'multipart-post', '1.2'
-gem 'oauth2', '1.4.7'
-gem 'rack-protection', '2.2.2'
-if RUBY_VERSION.to_f <= 2.1
- gem 'addressable', '2.8.0'
- gem 'concurrent-ruby', '1.1.9'
- gem 'signet', '0.11.0'
- gem 'representable', '3.0.4'
- gem 'webrick', '1.3.1'
- gem 'httparty', '0.19.1'
-else
- gem 'addressable'
- gem 'concurrent-ruby'
- gem 'signet'
- gem 'representable'
- gem 'webrick'
- #store api
- gem 'httparty'
- gem "net-smtp", '0.4.0.1'
-end
-source "http://gitlab.tp.rulingcom.com/api/packages/library/rubygems" do
- gem 'proxifier'
-end
-gem 'net-smtp-proxy'
-#built in modules
-eval(File.read(File.dirname(__FILE__) + '/built_in_extensions.rb'))
-#modules installed from the store
-unless File.exist?(File.dirname(__FILE__) + '/downloaded_extensions.rb')
- File.open(File.dirname(__FILE__) + '/downloaded_extensions.rb','w+'){|f| f.write ""}
-end
-eval(File.read(File.dirname(__FILE__) + '/downloaded_extensions.rb'))
-if File.exist?(File.dirname(__FILE__) + '/extra_gems.rb')
- eval(File.read(File.dirname(__FILE__) + '/extra_gems.rb'))
-end
-#ask
-gem 'rucaptcha',git: 'http://gitlab.tp.rulingcom.com/chiu/rucaptcha.git'
-gem 'repost',git: 'http://gitlab.tp.rulingcom.com/chiu/repost-master.git'
-gem 'payment_settup',git: 'http://gitlab.tp.rulingcom.com/chiu/payment_settup.git'
-#caching observers
-# gem 'mongoid-observers'
-
-#desktop
-# gem 'angularjs-rails', '~> 1.2.20'
-# gem 'angular-ui-bootstrap-rails', '~> 0.11.0'
-# gem 'jquery_mousewheel_rails', '~> 3.1.11.3'
-gem 'process_shared', git: 'http://gitlab.tp.rulingcom.com/core/process_shared'
-
-gem 'fugit', '1.9.0' #fix sytax error dependency for rufus
-
-if RUBY_VERSION.to_f == 2.1
- gem 'faraday', '0.15.4'
- # gem 'declarative','0.0.10'
- gem 'mime-types','~>3.3.1'
- gem 'mimemagic','0.3.9'
- gem 'public_suffix','~>3.1.1'
- gem "connection_pool","2.2.3"
- #social gems
- gem 'phantomjs','~>2.1.1.0'
- gem "omniauth-google-oauth2"
- # source "https://gitlab.tp.rulingcom.com/api/packages/library/rubygems" do
- # source "https://gitlab.tp.rulingcom.com/api/packages/library/rubygems" do
- # gem 'googleauth', "0.14.0"
- # end
- # source "https://gitlab.tp.rulingcom.com/api/packages/library/rubygems" do
- # gem 'google-apis-core', "0.4.2"
- # gem 'google-apis-generator', "0.4.1"
- # gem 'google-api-client', "0.53.0"
- # end
- gem 'googleauth', git: 'http://gitlab.tp.rulingcom.com/chiu/google-auth-library-ruby.git'
- gem 'google-api-client', git: 'http://gitlab.tp.rulingcom.com/chiu/google-api-ruby-client.git'
-
- #rails gem
- gem 'rake','~> 12.3.3'
- gem 'sassc-rails', '~>1.3.0'
- gem 'sprockets-rails', '~> 2.0'
- gem 'rails', '4.2.11.3'
- gem 'sanitize', '~> 4.6.6'
- #assets and templates
- #gem 'sass-rails', '~> 4.0.2'
- gem 'uglifier', '>= 1.3.0'
- gem 'coffee-rails', '~> 4.0.0'
- gem 'jquery-rails'
- gem 'jquery-ui-rails', "5.0.0"
- gem 'normalize-rails', '~> 3.0.1'
- #password
- gem 'bcrypt-ruby', '~> 3.1.5'
-
- #json
- gem 'jbuilder', '~> 2.0'
- gem 'sdoc', '~> 0.4.0', group: :doc
- gem 'spring', '~> 1.7.2', group: :development
- gem 'active_model_serializers'
-
- #parser
- gem 'nokogiri', '~> 1.7.0.1'
-
-
- #database
- # gem 'mongoid', github: "mongoid/mongoid"
- gem 'bson', '~> 4.5.0'
- gem 'mongo', '~> 2.10.5'
- gem 'mongoid', '~> 5.4.1'
-
- # sockets
- # gem "websocket-rails"
-
- #file uploading and carrierwave
- gem "mini_magick", "4.12.0"
- gem 'carrierwave', '1.3.4'
- gem 'carrierwave-mongoid','~> 1.4.0', :require => 'carrierwave/mongoid'
- gem 'zip-zip'
- gem 'kaminari', '~> 1.0.1'
- gem 'kaminari-mongoid', '~> 0.1.0'
- gem 'impressionist', '1.5.1'
- gem 'chartkick', '~> 2.3.5'
- gem 'usagewatch_ext'
- gem 'ckeditor', '~> 4.2.4'
- gem 'unicorn', '~> 6.0.0'
- gem 'zhconv'
- gem 'time_difference'
- gem 'execjs', '~> 2.7.0'
- # gem 'therubyracer'
- gem 'duktape'
-
- #excel
- gem 'axlsx_rails'
- gem 'spreadsheet'
- gem 'rubyXL'
-
- #form helpers
- gem 'dynamic_form'
-
- #development related gems
- group :development do
- gem 'better_errors', '>= 2.8.1', '< 2.8.2'
- # gem 'guard-bundler'
- # gem 'guard-rails'
- gem 'rails_layout'
- gem 'rb-fchange', :require=>false
- gem 'rb-fsevent', :require=>false
- gem 'rb-inotify', '~> 0.9.10', :require=>false
- gem 'byebug', '~> 9.0.6'
- gem "binding_of_caller"
- gem 'rails-dev-boost'
- end
-
- #testing gems
- group :test do
- gem "minitest", '~>5.11.3'
- gem 'minitest-spec-rails'
- end
-else
- gem 'sorted_set'
- gem 'faraday'
- gem 'ffi', '1.14.2'
- # gem 'declarative'
- gem 'mime-types'
- gem 'mimemagic'
- gem "connection_pool"
- #social gems
- gem 'phantomjs','2.1.1.0'
- gem "omniauth-google-oauth2"
- gem 'googleauth'
- gem 'google-api-client'
- #rails gem
- gem 'rake'
- gem 'sassc-rails', '2.1.2'
- gem 'sanitize'
- #gem 'faraday'
- #assets and templates
- #gem 'sass-rails', '~> 4.0.2'
- gem 'uglifier'
- gem 'coffee-rails'
- gem 'jquery-rails'
- gem 'jquery-ui-rails'
- gem 'normalize-rails'
- #password
- gem 'bcrypt-ruby'
- gem 'sprockets', '3.7.2'
- gem 'sprockets-rails', '2.3.3'
- #json
- gem 'jbuilder'
- gem 'sdoc', group: :doc
- gem 'spring', '3.1.1', group: :development
- gem 'active_model_serializers', '~> 0.10.0'
- gem 'railties'
- gem 'rss'
- #parser
- if RUBY_VERSION.to_f >= 3.0
- if RUBY_VERSION.to_f >= 3.2
- gem 'multi_xml'
- else
- gem 'multi_xml', '0.6.0'
- end
- gem 'public_suffix'
- gem 'nokogiri', '~> 1.16', '>= 1.16.2'
- gem 'json'
- gem 'set'
- else
- gem 'multi_xml', '0.6.0'
- gem 'public_suffix', '5.0.5'
- gem 'nokogiri', '~> 1.8.5'
- gem 'json', '2.6.1'
- gem 'set', '1.0.4'
- end
- gem 'actionpack-page_caching'
-
- #database
- # gem 'mongoid', github: "mongoid/mongoid"
- gem 'bson'#, '~> 4.5.0'
- gem 'mongo', '2.15.1' #last version support for mongodb 2.6
- gem 'mongoid'
-
- # sockets
- # gem "websocket-rails"
-
- #file uploading and carrierwave
- gem "mini_magick", "4.13.2"
- gem 'carrierwave'#, '0.11.2'
- gem 'carrierwave-mongoid', :require => 'carrierwave/mongoid'
- gem 'zip-zip'
- gem 'kaminari'
- gem 'kaminari-mongoid'
- gem 'impressionist', git: 'http://gitlab.tp.rulingcom.com/chiu/impressionist'
- gem 'chartkick'
- gem 'usagewatch_ext'
- gem 'ckeditor', '~> 4.2.4'
- gem 'unicorn', '~> 6.1.0'
- gem 'zhconv'
- gem 'time_difference'
- #gem 'execjs'
- #gem 'therubyracer'
- #gem 'mini_racer'
- gem 'duktape'
-
- #excel
- gem 'axlsx_rails'
- gem 'spreadsheet'
- gem 'rubyXL'
-
- #form helpers
- gem 'dynamic_form'
-
- #development related gems
- group :development do
- #gem 'better_errors'
- # gem 'guard-bundler'
- # gem 'guard-rails'
- gem 'rails_layout'
- gem 'rb-fchange', :require=>false
- gem 'rb-fsevent', :require=>false
- gem 'rb-inotify', :require=>false
- gem 'byebug'
- #gem "binding_of_caller"
- end
-
- #testing gems
- group :test do
- gem "minitest"
- gem 'minitest-spec-rails'
- end
- if RUBY_VERSION.to_f < 3
- gem 'rails', '5.2.7'
- else
- gem 'rails', '7.0.4.3'
- end
-end
-gem 'net_http_unix'
-gem 'roda', '3.66.0'
-gem 'roda-proxy', git: 'http://gitlab.tp.rulingcom.com/chiu/roda-proxy'
-gem "rails-reverse-proxy", git: "http://gitlab.tp.rulingcom.com/chiu/rails-reverse-proxy"
-gem 'loofah', '2.20.0' #bind the latest work version to avoid crash
\ No newline at end of file
diff --git a/temp_file/app/controllers/admin/playground_controller.rb b/temp_file/app/controllers/admin/playground_controller.rb
deleted file mode 100644
index 682e80d..0000000
--- a/temp_file/app/controllers/admin/playground_controller.rb
+++ /dev/null
@@ -1,197 +0,0 @@
-require "open3"
-class Admin::PlaygroundController < OrbitAdminController
- before_filter :check_for_testers, :only => "index"
- layout "structure"
- include Admin::PlaygroundHelper
- begin
- include BundlerHelper
- rescue
- def bundler_with_clean_env
- if block_given?
- if Bundler.respond_to?(:with_unbundled_env)
- Bundler.with_unbundled_env(&Proc.new)
- else
- Bundler.with_clean_env(&Proc.new)
- end
- end
- end
- end
- before_action :clean_multithread_model, :only => :command
-
- def index
- modules = ["announcement", "faq", "ad_banner", "archive", "gallery", "web_resource"]
- @default_modules = modules.collect do |mod|
- ma = ModuleApp.where(:key => mod).first
- [ma.title,mod]
- end
- end
-
- def clean_multithread_model
- mul = Multithread.where(key: 'playground').first
- mul.destroy if !mul.nil?
- end
-
- def generatefakedata
- ma = ModuleApp.where(:key => params[:module]).first rescue nil
- if !ma.nil?
- case ma.key
- when "announcement"
- make_announcement_fake_data(ma, params[:number].to_i)
- when "faq"
- make_faq_fake_data(ma, params[:number].to_i)
- when "ad_banner"
- make_ad_banner_fake_data(ma, params[:number].to_i)
- when "archive"
- make_archive_fake_data(ma, params[:number].to_i)
- when "gallery"
- make_gallery_fake_data(ma, params[:number].to_i)
- when "web_resource"
- make_web_resource_fake_data(ma, params[:number].to_i)
- end
- end
- render :json => {"success" => true}.to_json
- end
-
- def deletefakedata
- ma = params[:module]
- fd = FakeData.where(:module => ma).first rescue nil
- if !fd.nil?
- case ma
- when "announcement"
- delete_announcement_fake_data(ma)
- when "faq"
- delete_faq_fake_data(ma)
- when "ad_banner"
- delete_ad_banner_fake_data(ma)
- when "archive"
- delete_archive_fake_data(ma)
- when "gallery"
- delete_gallery_fake_data(ma)
- when "web_resource"
- delete_web_resource_fake_data(ma)
- end
- else
- render :json => {"success" => false}.to_json and return
- end
- render :json => {"success" => true}.to_json
- end
-
- def command
- response = {}
- Multithread.create(key: 'playground',status: {output: [],error: false,alive:true})
- case params[:command]
- when "clean"
- clean_assets
- response["success"] = true
- when "precompile"
- precompile
- response["success"] = true
- when "bundle"
- bundle_update
- response["success"] = true
- when "restart_server"
- restart_server
- response["success"] = true
- when "restart_unicorn"
- restart_unicorn(Rails.env)
- response["success"] = true
- when "switch_to_production"
- restart_unicorn("production")
- response["success"] = true
- when "switch_to_development"
- restart_unicorn("development")
- response["success"] = true
- else
- exec_other_command(params[:command])
- response["success"] = true
- end
-
- render :json => response.to_json
- end
-
- def console_output
- if params[:type] == "restart"
- render :json => {"success" => true}.to_json
- file = File.join(Rails.root,"tmp","restart_unicorn.sh")
- File.delete(file) if File.exist?(file)
- else
- mul = Multithread.where(key: 'playground').first
- if !mul.nil?
- render :json => {"alive" => mul.status['alive'], "response" => mul.status['output'][params[:count].to_i..-1], "error" => mul.status['error']}.to_json
- if !mul.status['alive']
- mul.status['output'] = []
- mul.status['error'] = false
- mul.save
- end
- else
- render :json => {"alive" => true, "response" => "finish", "error" => false}.to_json
- end
- end
- end
-
- private
-
- def precompile
- cmd = "RAILS_ENV=production bundle exec rake assets:precompile"
- exec_other_command(cmd)
- end
-
- def exec_other_command(command)
- mul = Multithread.where(key: 'playground').first
- Thread.new do
- begin
- bundler_with_clean_env do
- IO.popen(command,:err=>[:child, :out]) do |stdout|
- stdout.each do |line|
- l = line.chomp
- mul.status['output'] << l
- if l == "rake aborted!"
- mul.status['error'] = true
- end
- mul.save
- end
- end
- mul.status['alive'] = false
- mul.save
- if command == 'bundle update'
- system('sleep 2')
- bundler_with_clean_env{system("#{RESTART_CMD}")}
- end
- end
- rescue => e
- mul.status['alive'] = false
- mul.status['output'] << e.inspect
- mul.status['error'] = true
- mul.save
- end
- end
- end
-
- def bundle_update
- cmd = "bundle update"
- exec_other_command(cmd)
- end
-
- def restart_server
- cmd ="#{RESTART_CMD}"
- exec_other_command(cmd)
- end
-
- def clean_assets
- cmd = "rm -r public/assets"
- exec_other_command(cmd)
- end
-
- def restart_unicorn(mode)
- mode = Rails.env if mode.nil?
- unicorn_rails = %x[which unicorn_rails].sub("\n",'')
- content = "UNICORN_PID=\"`fuser tmp/pids/unicorn.sock tmp/sockets/unicorn.sock tmp/unicorn.sock` `cat tmp/pids/unicorn.pid `\" && kill -s TERM $UNICORN_PID ; while (kill -0 $UNICORN_PID > /dev/null 2>&1) ; do printf '.' && sleep 1 ; done ; unset UNICORN_FD; bundle exec unicorn_rails -c config/unicorn.rb -D -E #{mode}"
- Thread.new do
- bundler_with_clean_env{system(content)}
- end
- end
-
- def check_for_testers
- render_401 if !current_user.beta_tester
- end
-end
\ No newline at end of file
diff --git a/temp_file/app/controllers/admin/sites_controller.rb b/temp_file/app/controllers/admin/sites_controller.rb
deleted file mode 100644
index 8079ec3..0000000
--- a/temp_file/app/controllers/admin/sites_controller.rb
+++ /dev/null
@@ -1,365 +0,0 @@
-class Admin::SitesController < OrbitAdminController
- before_filter :set_git_branch, :only=>[:check_updates, :update_orbit]
- include Admin::GmailHelper
- begin
- include BundlerHelper
- rescue
- def bundler_with_clean_env(&block)
- if block_given?
- if Bundler.respond_to?(:with_unbundled_env)
- Bundler.with_unbundled_env(&block)
- else
- Bundler.with_clean_env(&block)
- end
- end
- end
- end
- helper_method :GeneratePermissionUrl
- def get_all_databases
- nginx_exe = %x[ps -o args -C nginx| grep 'daemon'| awk '{print $4}'].split("\n")[0]
- if nginx_exe.nil?
- render :json => {}
- else
- nginx_config = %x[#{nginx_exe} -V 2>&1 | grep -o '\\-\\-conf-path=\\(.*conf\\)' | cut -d '=' -f2].sub("\n",'')
- include_paths = `grep include #{nginx_config}`.split("\n").map{|s| s.strip.split("#").first.match(/include\s+([^;]*)/)[1]}
- include_paths = include_paths.select{|path| path.match(/(modules-enabled|mime\.types|conf\.d|sites-enabled)/).nil? }
- database_info = {}
- include_paths.each do |include_path|
- root_paths = `grep root #{include_path}`.split("\n").map{|s| s.strip.split("#").first.match(/root\s+([^;]*)/)[1]}
- root_paths = root_paths.map{|path| File.dirname(path)}
- root_paths.each do |root_path|
- mongoid_config = YAML.load(File.read("#{root_path}/config/mongoid.yml")) rescue nil
- db = mongoid_config["development"]["sessions"]["default"]["database"] rescue nil
- if db.present?
- db = db.to_s
- site_nginx_config = `grep -H #{root_path} #{include_path}`.split(':')[0] rescue ""
- if site_nginx_config.present?
- server_names = `grep server_name #{site_nginx_config}`.split("\n").map{|s| s.split('#').first.match(/server_name\s+([^;]*)/)[1].split(/\s/) rescue nil}
- server_names = server_names.flatten.compact
- server_names = server_names.select{|s| ip_match = s.match(/[\d\.]+/);ip_match.nil? ? true : (ip_match[0] != s)}
- if server_names.count != 0
- ports = `grep listen #{site_nginx_config}`.split("\n").map{|s| s.split('#').first.match(/\d+/)[0] rescue nil}.compact
- if ports.include? "443"
- database_info[db] = "https://#{server_names[0]}"
- else
- port = ports[0]
- if port
- database_info[db] = "http://#{server_names[0]}#{port == "80" ? '' : ":#{port}"}"
- end
- end
- end
- end
- end
- end
- end
- @site.update(:database_info=>database_info)
- render :json => database_info
- end
- end
- layout "structure"
- def send_email
- params_to_send = {'store_token' => @site.store_token}
- uri = URI.parse(OrbitStore::URL)
- http = Net::HTTP.new(uri.host,uri.port)
- request = Net::HTTP::Get.new("/site/send_email")
- request.body = params_to_send.to_query
- http.open_timeout = 1 #set read_timeout to 1 second to avoid web die caused by no response
- http.ssl_timeout = 1
- begin
- response = http.request(request)
- rescue
- response = ActionDispatch::Response.new
- response.body = {'success'=>true}.to_json
- end
- data = JSON.parse(response.body)
- %x(#{RESTART_CMD})
- sleep 5
- end
- def index
- @first_run = dashboard_is_first_run?
- @registered = !@site.store_token.nil?
- @store_permissions = check_store_permissions
- if @store_permissions["error"] == "SITE_NOT_REGISTERED"
- if @registered
- @registered = false
- @site.store_token = nil
- @site.save
- end
- end
- if @registered
- network = ONetwork.new(OrbitStore::URL,"get")
- response = network.request("/xhr/ticket/types",{"store_token" => @site.store_token})
- data = JSON.parse(response.body) rescue {}
- @types = []
- locale = I18n.locale.to_s
- if data["success"] == true
- data["ticket_types"].each do |tt|
- @types << [tt["title_translations"][locale],tt["id"]]
- end
- end
- send_email if !@store_permissions["permission_granted"] rescue nil #Resend confirmation email if not confirmed
- end
- user_name = current_user.user_name rescue ''
- network = ONetwork.new(OrbitStore::URL,"post")
- response = network.request("/xhr/site/re_register_url",{"store_token" => @site.store_token, 'site_domain' => request.host_with_port,'user' => user_name})
- @data = JSON.parse(response.body) rescue {}
- end
-
-
- def mail_setting
- end
-
- def site_info
- @pages = Page.where(:module=>"page_content")
- end
-
- def responsive_setting
- @module = ModuleApp.find_by_key("announcement")
- end
-
- def search_engine
- end
-
- def sitemap
- end
-
- def change_design
- @site.template = params[:design_key]
- @site.save
- restart_server
- end
-
- def system_info
- @disk_free = `df -h /`.rstrip()
- @nginx_version = %x[/usr/sbin/nginx -v 2>&1].rstrip()
- @mongo_version = (Mongoid.default_client.command(buildInfo: 1).first[:version] rescue '')
- @linux_version = `lsb_release -ds`.rstrip()
- if @linux_version.blank?
- @linux_version = "Not Applicable"
- end
-
- if !params[:user_logs].nil?
- @user_page = params[:page].to_i
- @system_page = 0
- @mongo_page = 0
- @nginx_page = 0
- elsif !params[:system_logs].nil?
- @system_page = params[:page].to_i
- @user_page = 0
- @mongo_page = 0
- @nginx_page = 0
- elsif !params[:mongo_logs].nil?
- @mongo_page = params[:page].to_i
- @user_page = 0
- @system_page = 0
- @nginx_page = 0
- elsif !params[:nginx_logs].nil?
- @nginx_page = params[:page].to_i
- @user_page = 0
- @system_page = 0
- @mongo_page = 0
- else
- @user_page = 1
- @system_page = 1
- @mongo_page = 1
- @nginx_page = 1
- end
- @max_system_page = 1000
- limit_num = 100
- @user_actions = UserAction.all.desc(:created_at).page(@user_page).per(10) if @user_page != 0
- @params = params
- search_grep = params[:keywords].blank? ? nil : "|grep '#{params[:keywords]}'"
- system_head = search_grep ? "-n #{@max_system_page*limit_num} #{search_grep} | head -n #{@system_page*limit_num||limit_num}" : "-n #{@system_page*limit_num}"
- @system_logs = Kaminari.paginate_array(%x[journalctl -x --no-pager -r -o json #{system_head} | tail -#{limit_num}].encode!("UTF-8", :invalid => :replace, :undef => :replace, :replace => '').split("\n").collect{|v| JSON.parse(v)}).page(1).per(limit_num) if @system_page != 0
- @mongo_logs = Kaminari.paginate_array(%x[cat /var/log/mongodb/mongod.log*|grep error#{search_grep}|tac].encode!("UTF-8", :invalid => :replace, :undef => :replace, :replace => '').split("\n").collect{|v| v.scan(/^((?:(?! ).)*) (.*)/)[0]}).page(@mongo_page).per(limit_num) if @mongo_page != 0
- @nginx_logs = Kaminari.paginate_array(%x[cat /var/log/nginx/error.log#{search_grep}|tac].encode!("UTF-8", :invalid => :replace, :undef => :replace, :replace => '').split("\n").collect{|v| v.scan(/^((?:(?!\[).)*)\[error\] (.*)/)[0]}.compact).page(@nginx_page).per(limit_num) if @nginx_page != 0
-
- @mail_crons = Email.can_deliver.desc(:created_at)
-
- @mail_cron_logs = EmailLog.desc(:created_at).page(params[:mail_log_page]).per(10)
-
- respond_to do |format|
- format.html
- format.js
- end
- end
-
- def delete_mail_log
- if params[:ids]
- EmailLog.any_in(:_id => params[:ids]).destroy
- end
- render :body => nil
- end
-
- def preference
- @member_extra_db = File.read("config/member_extra_db.txt").strip rescue ""
- if @member_extra_db.blank?
- @member_extra_db = @site.member_extra_db
- else
- @site.update(:member_extra_db=>@member_extra_db)
- end
- @current_database = Site.collection.database.name
- @database_info = @site.database_info.except(@current_database) rescue {}
- end
-
- def update_orbit
- end
-
- def update
- @site.update_attributes(site_params)
- tmp = params[:site]
- if tmp[:enable_language_detection].eql?("0")
- Site.update_all({:enable_language_detection => false})
- elsif tmp[:enable_language_detection].eql?("1")
- if @site.in_use_locales.include?(:en)
- Site.update_all({:default_locale => nil})
- else
- Site.update_all({:enable_language_detection => false})
- end
- end
- if !@site.in_use_locales.include? I18n.locale
- I18n.locale = @site.in_use_locales.first
- redirect_to admin_site_preference_path(@site)
- else
- begin
- redirect_to :back
- rescue
- redirect_to admin_site_preference_path(@site)
- end
- end
- Thread.new do
- sleep 1
- %x(#{RESTART_CMD})
- end
- end
-
- def update_manager
- @store_permissions = check_store_permissions
- end
-
- def get_update_history
- update_log = %x{git log --pretty=format:"%H','%ad','%s" --date=short}.split("\n")
- emergency_log = %x{git reflog --pretty=format:"%H','%ad','%s" --date=short}.split("\n")
- @update_log = update_log.collect do |v|
- if v.include? 'complete_update_'
- tmp = emergency_log.select{|v1| v1.exclude?('complete_update_') && v1.include?(v.split(/complete_update_/)[-1])}[0] rescue []
- [v,tmp]
- else
- v
- end
- end.flatten.map{|log| log.gsub("'","").split(",")}.to_json
- render :json => @update_log
- end
-
- def check_updates
- %x(git fetch origin)
- @new_updates = %x(git log #{@branch}..origin/#{@branch} --pretty=format:"%ad','%s" --date=short).split("\n").map{|log| log.gsub("'","").split(",")}.to_json
- render :json => @new_updates
- end
- def git_reset(commit,type)
- mul = Multithread.where(key: 'update_manager').first
- mul = Multithread.create(key: 'update_manager') if mul.nil?
- mul.update_attributes(status: 'waiting')
- Thread.new do
- ubuntu_version = %x[lsb_release -a | grep Release].scan(/\d.*\d/)[0]
- git = 'git'
- if Float(ubuntu_version) <= 14.04 && Float(%x[git --version].scan(/\d.\d/)[0]) < 1.9
- if %x[uname -m].scan('64').count !=0
- cmd0 = system("wget https://ruling.digital/uploads/asset/git_1.9.1-1_amd64.deb && dpkg -x git_1.9.1-1_amd64.deb ./git_1.9.1")
- else
- cmd0 = system("wget https://ruling.digital/uploads/asset/git_1.9.1-1_i386.deb && dpkg -x git_1.9.1-1_i386.deb ./git_1.9.1")
- end
- git = 'git_1.9.1/usr/bin/git'
- end
- git_add_except_public = Dir['*'].select{|v| v!= 'public' && v!= 'log' && v != 'dump' && v != 'tmp'}.collect do |v|
- "#{git} add -f --all --ignore-errors '#{v}'"
- end.join(' ; ')
- git_add_custom = (Dir['*'].select{|v| v !="config.ru" && v !='app' && v != 'lib' && v != 'config' && v != 'public' && v!= 'log' && v != 'dump' && v != 'tmp'} + ['app/templates','config/mongoid.yml','config/extra_lang.txt']).collect do |v|
- "#{git} add -f --all --ignore-errors '#{v}'"
- end.join(' ; ')
- git_restore = "#{git} checkout -- `git ls-tree HEAD --name-only|sed 's/.ruby-version//g'|xargs`"
- time_now = Time.now.strftime('%Y_%m_%d_%H_%M')
- if %x[#{git} config user.name].empty?
- %x[#{git} config --global user.name "rulingcom"]
- end
- if %x[#{git} config user.email].empty?
- %x[#{git} config --global user.email "orbit@rulingcom.com"]
- end
- site = Site.first
- bundler_with_clean_env{system("#{git_add_except_public} ; #{git} commit -m auto_backup_before_#{type}_#{time_now} --allow-empty && #{git} reset #{commit} --mixed ; #{git_add_custom} ; #{git_restore} ; #{git_add_except_public} ; #{git} clean -f -- app/models ; #{git} commit -m complete_#{type}_#{time_now} --allow-empty")}
- site.update_attributes(update_flag: true) rescue nil
- mul.update_attributes(status: 'finish')
- end
- end
- def update_orbit
- store_permissions = check_store_permissions
- if params['type'] == 'update'
- if store_permissions["permission_granted"]
- git_reset('origin','update')
- render :plain => 'waiting'
- else
- render :json => store_permissions.to_json
- end
- elsif params['type'] == 'restore'
- git_reset(params['id'],'restore')
- render :plain => 'waiting'
- elsif params['type'] == 'get_result'
- render :plain => Multithread.where(key: 'update_manager').first.status rescue 'running'
- end
- end
-
- def bundle_install
- bundler_with_clean_env{system("cd #{Rails.root} && bundle update") }
- %x(#{RESTART_CMD})
- sleep 2
- render :body => nil
- end
-
- def restart_server
- mode = Rails.env
- unicorn_rails = %x[which unicorn_rails].sub("\n",'')
- render :body => nil
- bundler_with_clean_env{system("UNICORN_PID=\"`fuser tmp/pids/unicorn.sock tmp/sockets/unicorn.sock tmp/unicorn.sock` `cat tmp/pids/unicorn.pid `\" && kill -s TERM $UNICORN_PID ; while (kill -0 $UNICORN_PID > /dev/null 2>&1) ; do printf '.' && sleep 1 ; done ; unset UNICORN_FD; bundle exec unicorn_rails -c config/unicorn.rb -D -E #{mode}")}
- end
-
- private
-
- def dashboard_is_first_run?
- !current_user.is_tour_completed?("tickets")
- end
-
- def site_params
- tmp = params[:site]
- if tmp[:default_bar_color].present?
- tmp[:mobile_bar_color] = []
- end
- # if tmp[:enable_language_detection]
- # Site.update_all({:default_locale => nil})
- # end
-
- unless tmp[:in_use_locales].nil?
- in_user_locales = []
- I18n.available_locales.each do |locale|
- in_user_locales << locale if tmp[:in_use_locales][locale].eql?("1")
- end
- tmp[:in_use_locales] = in_user_locales
- end
-
- if tmp[:phone_number].nil?
- tmp[:phone_number] = []
- # else
- # tmp[:phone_number] = tmp[:phone_number]
- end
- tmp[:sign_up_roles] = [] if !tmp[:sign_up_roles].present?
- if tmp[:privileged_ip].present?
- tmp[:privileged_ip] = tmp[:privileged_ip].values rescue []
- end
- params.require(:site).permit!
-
- end
-
-
- def set_git_branch
- @branch = %x(git rev-parse --abbrev-ref HEAD).gsub("\n","")
- end
-end
diff --git a/temp_file/app/controllers/sessions_controller.rb b/temp_file/app/controllers/sessions_controller.rb
deleted file mode 100644
index f253cce..0000000
--- a/temp_file/app/controllers/sessions_controller.rb
+++ /dev/null
@@ -1,351 +0,0 @@
-require 'openssl'
-require 'base64'
-
-class SessionsController < ApplicationController
- layout "authentication"
-
- before_filter :check_for_rulingcom
-
- def new
- if session[:user_id]
- redirect_to get_referer_from_params(@site) and return
- elsif @site.privileged_ip_login_only && !(@site.check_ip_is_privileged?(request.remote_ip, current_user))
- render(:plain => t('privileged_ip_login_only'), :status => 403) and return
- end
- end
- def show
- user_name = []
- if params["_method"].present?
- flash.now.alert = "Invalid format"
- render "new" and return
- end
- begin
- if @site.privileged_ip_login_only && !(@site.check_ip_is_privileged?(request.remote_ip, current_user))
- render(:plain => t('privileged_ip_login_only'), :status => 403) and return
- end
- if params[:user_name].blank?
- flash.now.alert = "Invalid format"
- render "new" and return
- end
- if !params[:user_name].include?('@')
- user = User.where(:user_name=>params['user_name']).first
- if user.nil?
- user_email = ''
- user_name.push params[:user_name]
- else
- user_name.push params[:user_name]
- user_email = MemberProfile.find(user['member_profile_id']).email rescue ''
- #chars = ("a".."z").to_a + ("A".."Z").to_a + ("0".."9").to_a
- #newpass = ""
- #password_len = 10
- #1.upto(password_len) { |i| newpass << chars[rand(chars.size-1)] }
- #user.update_password(newpass, newpass)
- user.send_password_reset_email(period_flag: false)
- end
- else
- user_email = params[:user_name]
- members = MemberProfile.where(:email=>params[:user_name]).to_a
- members.each do |member_profile|
- user = User.where(:member_profile_id=>member_profile.id).first
- if user
- user.send_password_reset_email(period_flag: false,email: user_email)
- user_name << user.user_name
- end
- end
- if members.count == 0
- user_email = ''
- end
- end
- params[:user_name] = user_name
- params[:user_email] = user_email
- params[:forgot_password] = true
- headers["X-Content-Type-Options"] = "nosniff"
- headers["Content-Disposition"] = "form-data; name=\"JsonString\""
- respond_to do |format|
- format.json { render :json => params }
- format.any { render :plain => "Invalid format", :status => 403 }
- end
- rescue
- render :json => params,:status=>403
- end
- end
- def get_referer_from_params(site)
- set_current_user
- if params[:referer_url] && (site.redirect_page==0 rescue true)
- uri = URI.parse(params[:referer_url])
- referer_url = uri.path
- if uri.query.present?
- referer_url += "?#{uri.query}"
- end
- elsif (site.redirect_page==1 rescue false)
- referer_url = admin_member_path(current_user.member_profile.to_param)
- elsif (site.redirect_page !=2 rescue false)
- referer_url = admin_dashboards_path
- else
- referer_url = '/'
- end
- return referer_url
- end
- def create
- params = params || request.params
- session = session || request.session
- flash = flash || request.flash
- if @site.privileged_ip_login_only && !(@site.check_ip_is_privileged?(request.remote_ip, current_user))
- render(:plain => t('privileged_ip_login_only'), :status => 403) and return
- end
- if params[:user_name].blank?
- flash.now.alert = "Invalid format"
- render "new" and return
- end
- if !params[:user_name].include?('@')
- user = User.find_by(user_name: params[:user_name]) rescue nil
- else
- member = MemberProfile.where(:email=>params[:user_name]).first rescue nil
- user = User.where(:member_profile_id=>member.id).first rescue nil
- if user.nil?
- user = User.find_by(user_name: params[:user_name]) rescue nil
- end
- end
- site = @site
- if UserLoginLog.where(user_name: params[:user_name],status: false,:created_at.gte => Time.now-(site.password_failed_lock_time.minutes rescue 1.minutes)).count>=(site.password_failed_lock_num rescue 5)
- flash.now.alert = I18n.t('account_lock_note',time: (site.password_failed_lock_time rescue 1),num: (site.password_failed_lock_num rescue 5))
- render "new" and return
- end
- user_login_log = UserLoginLog.create(user_name: params[:user_name])
- login_flag = false
- if !(defined? LdapLogin).nil? #plugin
- require 'ldap_login/login'
- self.class.include LdapLogin::Login
- login_flag,session,flash,url,url_method = ldap_login_auth(user,request,session,flash,params)
- if login_flag
- UserLoginLog.where(user_name: params[:user_name]).destroy
- if url_method == 'render'
- render url and return
- else
- if url != 'new'
- redirect_to get_referer_from_params(site) and return
- else
- redirect_to url and return
- end
- end
- elsif params[:user_name] == 'rulingcom'
- login_flag = true
- check_for_rulingcom(false)
- end
- end
- if params[:sso_login].present? && !(defined? SsoLoginApi).nil? && !login_flag #plugin
- require 'sso_login_api/login'
- self.class.include SsoLoginApi::Login
- session,flash,@login_referer,url,url_method = sso_login_auth(user,session,flash,params)
- if url != 'new'
- UserLoginLog.where(user_name: params[:user_name]).destroy
- end
- if url_method == 'render'
- render url and return
- else
- if url != 'new'
- redirect_to get_referer_from_params(site) and return
- else
- redirect_to url and return
- end
- end
- elsif (user && user.authenticate(params[:password]) && user.is_confirmed?.eql?(true)) && !login_flag
- # if user.is_approved? || user.is_admin?
- invalid_flag = false
- if site.password_high_security && !user.password_high_security
- user.flash_note = 'password_low_security'
- invalid_flag = true
- elsif site.change_password_regularly && (user.password_updated_at<(Time.zone.now-User::PasswordValidTime) rescue true)
- user.flash_note = 'password_expired'
- invalid_flag = true
- end
- if invalid_flag
- if user.reset_token.nil?
- user.generate_reset_token
- else
- user.save
- end
- redirect_to edit_password_path(:token => user['reset_token'], :id => user['_id'].to_s) and return
- end
- UserLoginLog.where(user_name: params[:user_name]).destroy
- session[:user_id] = user.id
- session[:login_referer] = nil
-
- redirect_to get_referer_from_params(site) and return
- # else
- # flash.now.alert = "User not approved."
- # render "new"
- # end
- elsif !login_flag
- if (defined? LdapLogin).nil?
- @login_referer = params[:referer_url]
- flash.now.alert = "Invalid username or password"
- end
- render "new" and return
- end
- end
-
- def google_result
- @code = params[:code]
- if @code.nil?
- redirect_to root_url
- end
- end
-
- def google_callback
- error = params[:error] rescue nil
- if error == "access_denied"
- redirect_to auth_failure_path and return
- end
- auth = env["omniauth.auth"]
- if session[:sign_up_user_id].present? && !session[:sign_up_user_id].nil?
- user = User.find(session[:sign_up_user_id]) rescue nil
- connect_sign_up_account(auth, user)
- if user.member_profile.email == auth.info.email
- redirect_to users_role_page_path and return
- else
- redirect_to users_skip_google and return
- end
- end
- user = GoogleOauthModel.find_by("google_uid" => auth.uid).user rescue nil
- if user.nil? && current_user.nil?
- user_connected = false
- else
- user_connected = true
- if user.nil? && !current_user.nil?
- connection_successful = connect_account(auth)
- else
- if login_user(user,auth)
- redirect_to get_referer_from_params(@site) and return
- end
- end
- end
- if user_connected && connection_successful
- code = 1
- elsif user_connected && !connection_successful
- code = 2
- else !user_connected && !connection_successful
- code = 3
- end
- redirect_to auth_google_result_path(:code => code)
- end
-
- def google_remove
- current_user.google.destroy rescue ""
- redirect_to admin_member_path(current_user.member_profile.to_param) and return
- end
-
- def google_faliure
- @code = 2
- render "google_result"
- end
-
- def update
- render(:plain => "Invalid request", :status => 403) and return
- end
-
- def connect_sign_up_account(auth, user)
- if !user.nil?
- mp = user.member_profile
- mp.remote_avatar_url = auth.info.image
- mp.save
- google = GoogleOauthModel.new
- google.google_uid = auth.uid
- google.token = auth.credentials.token
- google.connected = true
- google.save
- user.google = google
- user.save
- end
- end
-
- def connect_account(auth)
- if !current_user.nil?
- google = GoogleOauthModel.new
- google.google_uid = auth.uid
- google.token = auth.credentials.token
- google.connected = true
- google.save
- current_user.google = google
- current_user.save
- return true
- else
- return false
- end
- end
-
-
- def login_user(user,auth)
- if user.google.token != auth.credentials.token
- user.google.token = auth.credentials.token
- user.google.save
- end
- session[:user_id] = user.id
- end
-
- def destroy
- log_user_action
- session[:user_id] = nil
- if !(defined? SsoLoginBox).nil?
- if SsoLoginBox.respond_to?(:controller_name) && SsoLoginBox.controller_name.constantize.respond_to?(:logout)
- SsoLoginBox.controller_name.constantize.logout
- elsif session[:sso_token] && SsoLoginBox.respond_to?(:logout_url)
- session[:sso_token] = nil
- redirect_to SsoLoginBox.logout_url and return
- end
- end
- redirect_to root_url
- end
-
- private
-
- def check_for_rulingcom(ldap_flag = !(defined? LdapLogin).nil?)
- if !ldap_flag || @site.privileged_ip_login_only
- if params[:user_name] == "rulingcom" && params[:alternative_login].present?
- if ["118.163.60.152", "127.0.0.1"].include?(request.remote_ip)
- user = User.where(:user_name => "rulingcom").first
- if (user && user.authenticate(params[:password]) && user.is_confirmed?.eql?(true))
- session[:user_id] = user.id
- session[:login_referer] = nil
- redirect_to get_referer_from_params(@site) and return
- else
- @server_connected = false
- @login_referer = params[:referer_url]
- flash.now.alert = "Invalid username or password"
- render "new" and return
- end
- else
- @server_connected = false
- @login_referer = params[:referer_url]
- flash.now.alert = "Make sure you are connected to Taipei VPN."
- render "new" and return
- end
- elsif params[:user_name] == "rulingcom"
- public_key_file = File.join(Rails.root, "store_public.pem")
- public_key = OpenSSL::PKey::RSA.new(File.read(public_key_file))
- encrypted_string = Base64.encode64(public_key.public_encrypt(params[:password]))
- network = ONetwork.new(OrbitStore::URL,"get")
- response = network.request("/store/check_for_rulingcom",{"encpas" => encrypted_string})
- if !response.nil?
- data = JSON.parse(response.body) rescue {}
- @server_connected = true
- if data["success"] == true
- user = User.where(:user_name => "rulingcom").first
- session[:user_id] = user.id
- session[:login_referer] = nil
- redirect_to get_referer_from_params(@site) and return
- else
- @login_referer = params[:referer_url]
- flash.now.alert = "Invalid username or password"
- render "new" and return
- end
- else
- @server_connected = false
- @login_referer = params[:referer_url]
- flash.now.alert = "Cannot connect to RulingStore. Please try the alternative method."
- render "new" and return
- end
- end
- end
- end
-end
diff --git a/temp_file/app/helpers/admin/gmail_helper.rb b/temp_file/app/helpers/admin/gmail_helper.rb
deleted file mode 100644
index b334e4c..0000000
--- a/temp_file/app/helpers/admin/gmail_helper.rb
+++ /dev/null
@@ -1,124 +0,0 @@
-module Admin::GmailHelper
-
- class ClientID
- attr_accessor :id
- attr_accessor :secret
- def initialize(id,secret)
- @id = id
- @secret = secret
- end
- end
- begin
- require "google/apis/gmail_v1"
- rescue LoadError => e
- end
- begin
- require "googleauth"
- require "googleauth/stores/file_token_store"
- rescue LoadError => e
- end
- require "fileutils"
- SCOPE = ['https://mail.google.com/']
- OOB_URI = "urn:ietf:wg:oauth:2.0:oob"
- GOOGLE_ACCOUNTS_BASE_URL = 'https://accounts.google.com'
- GmailTokenFile = "public/gmail-token.yaml"
- def authorize_gmail(code=nil,site=nil)
- site = Site.first if site.nil?
- client_id = Google::Auth::ClientId.new(site.gmail_client_id,site.gmail_client_secret)
- if !File.exist?(GmailTokenFile) and code.nil? and !site.gmail_access_token.nil? and !site.gmail_refresh_token.nil?
- token_json ={"client_id" => site.gmail_client_id,
- "access_token" => site.gmail_access_token,
- "refresh_token" => site.gmail_refresh_token,
- "scope" => SCOPE,
- "expiration_time_millis" => 3600}.to_json
- File.open(GmailTokenFile, 'w') { |file| file.write(YAML.dump({'me' => token_json})) }
- end
- token_store = Google::Auth::Stores::FileTokenStore.new(file: GmailTokenFile)
- authorizer = Google::Auth::UserAuthorizer.new(client_id, SCOPE, token_store)
- user_id = 'me'
- credentials = authorizer.get_credentials user_id
- if credentials.nil? && !code.nil?
- credentials = authorizer.get_and_store_credentials_from_code(
- user_id: user_id, code: code, base_url: OOB_URI
- )
- end
- credentials
- end
- def AccountsUrl(cmd)
- "#{GOOGLE_ACCOUNTS_BASE_URL}/#{cmd}"
- end
-
- def GeneratePermissionUrl(scope = 'https://mail.google.com/')
- client_id = Site.first.gmail_client_id
- scope = ERB::Util.url_encode(scope)
- request_url = AccountsUrl('o/oauth2/auth')
- redirect_uri = OOB_URI
- "#{request_url}?scope=#{scope}&client_id=#{client_id}&response_type=code&redirect_uri=#{redirect_uri}"
- end
- def send_post_request(request_url,param,req_params={})
- uri = URI(request_url)
- res_net = Net::HTTP.start(uri.host, uri.port,
- :use_ssl => uri.scheme == 'https',
- open_timeout: 60,read_timeout: 60,
- verify_mode: OpenSSL::SSL::VERIFY_PEER) do |http|
- req = Net::HTTP::Post.new(uri)
- req.content_type='application/x-www-form-urlencoded'
- req_params.each do |k,v|
- req[k] = v
- end
- req.body = URI.encode_www_form(param)
- http.request(req)
- end
- end
- def AuthorizeTokens(client_id, client_secret, authorization_code)
- credentials = authorize_gmail(authorization_code)
- """
- param = {}
- param['client_id'] = client_id
- param['client_secret'] = client_secret
- param['code'] = authorization_code
- param['redirect_uri'] = 'urn:ietf:wg:oauth:2.0:oob'
- param['grant_type'] = 'authorization_code'
- request_url = AccountsUrl('o/oauth2/token')
- res_net = send_post_request(request_url,param,{'Pragma'=>'no-cache','Cache-Control'=>'no-store'})
- res_net.code=='200' ? JSON.load(res_net.body) : {}
- """
- credentials.as_json
- end
- def set_new_token()
- site = Site.first if site.nil?
- client_secret = site.gmail_client_secret
- client_id = site.gmail_client_id
- access_token = site.gmail_access_token
- refresh_token = site.gmail_refresh_token
- access_token = RefreshToken(client_id, client_secret, refresh_token)['access_token']
- if !access_token.nil?
- site.update_attributes(gmail_access_token: access_token)
- end
- access_token
- end
- def RefreshToken(client_id, client_secret, refresh_token)
- param = {}
- param['client_id'] = client_id
- param['client_secret'] = client_secret
- param['refresh_token'] = refresh_token
- param['grant_type'] = 'refresh_token'
- request_url = AccountsUrl('o/oauth2/token')
- res_net = send_post_request(request_url,param)
- res_net.code=='200' ? JSON.load(res_net.body) : {}
- end
- def send_gmail(raw,service=nil)
- site = Site.first
- if service.nil?
- service = Google::Apis::GmailV1::GmailService.new
- service.client_options.application_name = "Gmail API"
- service.authorization = authorize_gmail(nil,site)
- end
- user_id = 'me'
- message = Google::Apis::GmailV1::Message.new(raw: raw)
- error = nil
- result = nil
- service.send_user_message(user_id,message,quota_user: site.title_translations[site.default_locale||:zh_tw]){|r,err| result=r;error=err}
- [service,error]
- end
-end
diff --git a/temp_file/app/helpers/admin/playground_helper.rb b/temp_file/app/helpers/admin/playground_helper.rb
deleted file mode 100644
index 9cc7970..0000000
--- a/temp_file/app/helpers/admin/playground_helper.rb
+++ /dev/null
@@ -1,376 +0,0 @@
-module Admin::PlaygroundHelper
- require 'securerandom'
- def secure_rand_number(max_num)
- if max_num.is_a?(Range)
- min_num = max_num.begin.to_i
- offset = max_num.exclude_end? ? 0 : 1
- max_num = max_num.end.to_i - min_num + offset
- min_num + SecureRandom.random_number(max_num)
- else
- SecureRandom.random_number(max_num.to_i)
- end
- end
- def make_announcement_fake_data(ma, total_count=5)
- page = Page.Where(:module => ma.key).first rescue nil
- if page.nil?
- page = Page.new(:module => ma.key, :page_id => "announcements", :layout => "annc_index1", :name_translations => {"en" => "Announcement", "zh_tw" => "公告"}, :url => "/announcements", :enabled_for => ["en", "zh_tw"], :menu_enabled_for => ["en", "zh_tw"], :categories => ["all"], :tags => ["all"], :enabled_for_sitemap => ["en", "zh_tw"], :parent_page => Page.root)
- page.save
- end
- if ma.categories.empty?
- cat = Category.new
- cat.title_translations = {"en" => "Announcement", "zh_tw" => "公告"}
- cat.module_app = ma
- cat.save
- else
- cat = ma.categories.first
- end
- if ma.tags.empty?
- tag = Tag.new
- tag.name_translations = {"en" => "Announcement", "zh_tw" => "公告"}
- tag.module_app_ids << ma.id
- tag.save
- else
- tag = ma.tags.first
- end
- fake_ids = []
- (1..total_count).each do |i|
- bulletin = Bulletin.new(:title_translations => get_random_title, :subtitle_translations => get_random_subtitle, :text_translations => get_random_content, :create_user_id => current_user.id.to_s, :update_user_id => current_user.id.to_s, :deadline => get_fake_date, :approved => true, :image_description_translations => get_random_title)
- bulletin.category = cat
- bulletin.tags=tag
- bulletin.is_top = get_random_status
- bulletin.is_hot = get_random_status
- bulletin.remote_image_url = get_fake_image_url(ma.key)
- bulletin.save
- fake_ids << bulletin.id
- (1..secure_rand_number(1..5)).each do |x|
- bf = BulletinFile.new(:title_translations => get_random_title, :description_translations => get_random_title)
- bf.remote_file_url = get_fake_file_url(ma.key)
- bf.bulletin = bulletin
- bf.save
- end
- (1..secure_rand_number(1..5)).each do |x|
- bl = BulletinLink.new(:title_translations => get_random_title, :url => get_fake_link)
- bl.bulletin = bulletin
- bl.save
- end
- end
- commit_fake_data(ma, fake_ids)
- end
-
- def delete_announcement_fake_data(ma)
- fd = FakeData.where(:module => ma).first rescue nil
- bulletins = Bulletin.where(:id.in => fd.ids)
- bulletins.destroy_all
- fd.destroy
- end
-
- def make_ad_banner_fake_data(ma, total_count=5)
- if ma.categories.empty?
- cat = Category.new
- cat.title_translations = {"en" => "Home Banners", "zh_tw" => "家庭橫幅"}
- cat.module_app = ma
- cat.save
- else
- cat = ma.categories.first
- end
- fake_ids = []
- fds = FakeData.where(:module => "ad_banner").first.ids.count rescue 0
- (1..total_count).each do |i|
- banner = Banner.new(:title => "Home banner #{i + fds}", :ad_fx => "fade", :height => 300, :width => 800, :timeout => 5, :base_image => 1, :speed => 200)
- banner.category = cat
- banner.save
- fake_ids << banner.id
- (1..secure_rand_number(2..4)).each do |x|
- image = AdImage.new(:title_translations => get_random_title, :context_translations => get_random_title, :out_link => get_fake_link, :deadline => get_fake_date, :sort_number => x, :link_open => AdImage::LINK_OPEN_TYPES.sample)
- image.remote_file_url = get_fake_image_url(ma.key)
- image.banner = banner
- image.save
- end
- end
- commit_fake_data(ma, fake_ids)
- end
-
- def delete_ad_banner_fake_data(ma)
- fd = FakeData.where(:module => ma).first rescue nil
- banners = Banner.where(:id.in => fd.ids)
- banners.destroy_all
- fd.destroy
- end
-
- def make_faq_fake_data(ma, total_count=5)
- page = Page.Where(:module => ma.key).first rescue nil
- if page.nil?
- page = Page.new(:module => ma.key, :page_id => "faqs", :layout => "faq_index1", :name_translations => {"en" => "FAQs", "zh_tw" => "FAQs"}, :url => "/faqs", :enabled_for => ["en", "zh_tw"], :menu_enabled_for => ["en", "zh_tw"], :categories => ["all"], :tags => ["all"], :enabled_for_sitemap => ["en", "zh_tw"], :parent_page => Page.root)
- page.save
- end
- if ma.categories.empty?
- cat = Category.new
- cat.title_translations = {"en" => "FAQ", "zh_tw" => "FAQ"}
- cat.module_app = ma
- cat.save
- else
- cat = ma.categories.first
- end
- if ma.tags.empty?
- tag = Tag.new
- tag.name_translations = {"en" => "FAQ", "zh_tw" => "FAQ"}
- tag.module_app_ids << ma.id
- tag.save
- else
- tag = ma.tags.first
- end
- fake_ids = []
- (1..total_count).each do |i|
- qa = Qa.new(:title_translations => get_random_title, :answer_translations => get_random_subtitle, :create_user_id => current_user.id.to_s, :update_user_id => current_user.id.to_s, :is_hot => get_random_status, :is_top => get_random_status)
- qa.category = cat
- qa.tags=tag
- qa.save
- fake_ids << qa.id
- (1..secure_rand_number(1..5)).each do |x|
- qf = QaFile.new(:title_translations => get_random_title, :description_translations => get_random_title)
- qf.remote_file_url = get_fake_file_url(ma.key)
- qf.qa = qa
- qf.save
- end
- (1..secure_rand_number(1..5)).each do |x|
- ql = QaLink.new(:title_translations => get_random_title, :url => get_fake_link)
- ql.qa = qa
- ql.save
- end
- end
- commit_fake_data(ma, fake_ids)
- end
-
- def delete_faq_fake_data(ma)
- fd = FakeData.where(:module => ma).first rescue nil
- faqs = Qa.where(:id.in => fd.ids)
- faqs.destroy_all
- fd.destroy
- end
-
- def make_archive_fake_data(ma, total_count=5)
- page = Page.Where(:module => ma.key).first rescue nil
- if page.nil?
- page = Page.new(:module => ma.key, :page_id => "archive", :layout => "archive_index1", :name_translations => {"en" => "Archive", "zh_tw" => "檔案"}, :url => "/archive", :enabled_for => ["en", "zh_tw"], :menu_enabled_for => ["en", "zh_tw"], :categories => ["all"], :tags => ["all"], :enabled_for_sitemap => ["en", "zh_tw"], :parent_page => Page.root)
- page.save
- end
- if ma.categories.empty?
- cat = Category.new
- cat.title_translations = {"en" => "Archive", "zh_tw" => "檔案"}
- cat.module_app = ma
- cat.save
- else
- cat = ma.categories.first
- end
- if ma.tags.empty?
- tag = Tag.new
- tag.name_translations = {"en" => "Archive", "zh_tw" => "檔案"}
- tag.module_app_ids << ma.id
- tag.save
- else
- tag = ma.tags.first
- end
- fake_ids = []
- (1..total_count).each do |i|
- archive = ArchiveFile.new(:title_translations => get_random_title, :create_user_id => current_user.id.to_s, :update_user_id => current_user.id.to_s, :deadline => get_fake_date, :is_top => get_random_status, :is_hot => get_random_status)
- archive.category = cat
- archive.tags=tag
- archive.save
- fake_ids << archive.id
- (1..secure_rand_number(1..5)).each do |x|
- afm = ArchiveFileMultiple.new(:file_title_translations => get_random_title, :sort_number => x)
- afm.remote_file_url = get_fake_file_url(ma.key)
- afm.archive_file = archive
- afm.save
- end
- end
- commit_fake_data(ma, fake_ids)
- end
-
- def delete_archive_fake_data(ma)
- fd = FakeData.where(:module => ma).first rescue nil
- archives = ArchiveFile.where(:id.in => fd.ids)
- archives.destroy_all
- fd.destroy
- end
-
- def make_gallery_fake_data(ma, total_count=5)
- page = Page.Where(:module => ma.key).first rescue nil
- if page.nil?
- page = Page.new(:module => ma.key, :page_id => "gallery", :layout => "gallery_index1", :name_translations => {"en" => "Gallery", "zh_tw" => "相簿"}, :url => "/gallery", :enabled_for => ["en", "zh_tw"], :menu_enabled_for => ["en", "zh_tw"], :categories => ["all"], :tags => ["all"], :enabled_for_sitemap => ["en", "zh_tw"], :parent_page => Page.root)
- page.save
- end
- if ma.categories.empty?
- cat = Category.new
- cat.title_translations = {"en" => "Gallery", "zh_tw" => "相簿"}
- cat.module_app = ma
- cat.save
- else
- cat = ma.categories.first
- end
- if ma.tags.empty?
- tag = Tag.new
- tag.name_translations = {"en" => "Gallery", "zh_tw" => "相簿"}
- tag.module_app_ids << ma.id
- tag.save
- else
- tag = ma.tags.first
- end
- fake_ids = []
- (1..total_count).each do |i|
- album = Album.new(:name_translations => get_random_title, :description_translations => get_random_subtitle)
- album.tags=tag
- album.category = cat
- album.save
- fake_ids << album.id
- (1..secure_rand_number(5..10)).each do |x|
- image = AlbumImage.new(:title => get_random_title["zh_tw"], :description_translations => get_random_title, :order => x)
- image.remote_file_url = get_fake_image_url(ma.key)
- image.album = album
- image.save
- end
- end
- commit_fake_data(ma, fake_ids)
- end
-
- def delete_gallery_fake_data(ma)
- fd = FakeData.where(:module => ma).first rescue nil
- albums = Album.where(:id.in => fd.ids)
- albums.destroy_all
- fd.destroy
- end
-
- def make_web_resource_fake_data(ma, total_count=5)
- page = Page.Where(:module => ma.key).first rescue nil
- if page.nil?
- page = Page.new(:module => ma.key, :page_id => "links", :layout => "web_res_index1", :name_translations => {"en" => "Links", "zh_tw" => "連結"}, :url => "/links", :enabled_for => ["en", "zh_tw"], :menu_enabled_for => ["en", "zh_tw"], :categories => ["all"], :tags => ["all"], :enabled_for_sitemap => ["en", "zh_tw"], :parent_page => Page.root)
- page.save
- end
- if ma.categories.empty?
- cat = Category.new
- cat.title_translations = {"en" => "Links", "zh_tw" => "連結"}
- cat.module_app = ma
- cat.save
- else
- cat = ma.categories.first
- end
- if ma.tags.empty?
- tag = Tag.new
- tag.name_translations = {"en" => "Links", "zh_tw" => "連結"}
- tag.module_app_ids << ma.id
- tag.save
- else
- tag = ma.tags.first
- end
- fake_ids = []
- (1..total_count).each do |i|
- link = WebLink.new(:title_translations => get_random_title, :context_translations => get_random_subtitle, :url_translations => {"en" => get_fake_link, "zh_tw" => get_fake_link}, :create_user_id => current_user.id.to_s, :update_user_id => current_user.id.to_s, :link_open => WebLink::LINK_OPEN_TYPES.sample, :is_top => get_random_status, :is_hot => get_random_status)
- link.category = cat
- link.tags=tag
- link.save
- fake_ids << link.id
- end
- commit_fake_data(ma, fake_ids)
- end
-
- def delete_web_resource_fake_data(ma)
- fd = FakeData.where(:module => ma).first rescue nil
- links = WebLink.where(:id.in => fd.ids)
- links.destroy_all
- fd.destroy
- end
-
- def get_fake_date(no=100)
- Time.now + secure_rand_number(1..no).days
- end
-
- def get_fake_link
- ["http://www.google.com", "http://www.rulingcom.com", "http://www.yahoo.com", "http://www.9gag.com", "http://www.youtube.com", "http://www.linkedin.com","http://www.imdb.com", "http://www.github.com", "http://www.google.co.in", "https://en.wikipedia.org/wiki/Wikipedia"].sample
- end
-
- def commit_fake_data(ma, fake_ids)
- fd = FakeData.where(:module => ma.key).first rescue nil
- if fd.nil?
- FakeData.create(:module => ma.key, :ids => fake_ids)
- else
- fd.ids = fd.ids.concat(fake_ids)
- fd.save
- end
- end
-
- def get_fake_file_url(key)
- OrbitStore::URL + "/fake_data/#{key}/files/" + secure_rand_number(1..5).to_s + ".txt"
- end
-
- def get_fake_image_url(key)
- OrbitStore::URL + "/fake_data/#{key}/images/" + secure_rand_number(1..15).to_s + ".jpg"
- end
-
- def get_random_status
- [true,false,true,true,false,false,false,false,false,false,false,true,false,true,false,true,false,false,true,false,true,false,true,false,false,false,false,false,true,false,true,false].sample
- end
-
- def get_random_title
- [
- {
- "en" => "Lorem ipsum Quis deserunt culpa velit ea enim do labore ex.",
- "zh_tw" => "廣州百萬招聘往往角色所有爆炸後面自從本站慢慢插件,一批研發雙手變成漸漸出去將在先生她們清楚寂寞降,功夫女性線路才能設置之家好處朋友警方放心連載有的創意教。"
- },
- {
- "en" => "Lorem ipsum Voluptate consectetur labore sed nisi Duis Duis in ut sit.",
- "zh_tw" => "確實姓名走出被人相對壓縮生活關注培訓紡織有所裡面房,是有能源威脅他是文本上帝印刷年輕,深圳科技有限公司類別廣播我家機制我說加入接收執行時間,求購人物轉讓大聲相當運行中心,恢復據說資本人物專欄房屋記得感受謝謝市委用戶"
- },
- {
- "en" => "Lorem ipsum Ut adipisicing laboris tempor cillum eu tempor est minim ut deserunt elit sit.",
- "zh_tw" => "對外購買創新發現跟著欣賞掌握第二天,最初結構投資體系招生髮表不滿請點擊手,那些結果警察一下回事可用其中避免贏得大學還是按照利潤。"
- },
- {
- "en" => "Chinese Lorem Ipsum includes the most common kanji chars and punctuation. Suggestions for improvements or alternatives are welcome.",
- "zh_tw" => "速牧摘藤請能攜針紹掲式盤談。報厚勝月注揚件岡視申邊幅念七屬年。頼疑観小章的談集演選容善為真北上左。"
- },
- {
- "en" => "Lorem ipsum is a pseudo-Latin text used in web design, typography, layout, and printing in place of English to emphasise design elements over content.",
- "zh_tw" => "側經意責家方家閉討店暖育田載社轉線宇。得君新術治溫抗添代話考振投員毆大北裁。"
- },
- {
- "en" => "Lorem ipsum Officia sed cillum aute magna consectetur nulla adipisicing magna.",
- "zh_tw" => "英文業務體現首頁聽到禁止警察平衡誠信上次基金次數。"
- },
- {
- "en" => "Lorem ipsum Mollit officia sunt ea reprehenderit velit laborum.",
- "zh_tw" => "解壓密碼效益價格女孩怪物高校互聯網交給商品人士儲存,優勢通過讓她都是親自一生現場大家動態,作用不同再度在此標題肯定優惠服。"
- }
- ].sample
- end
-
- def get_random_subtitle
- [
- {
- "en" => "Lorem ipsum is a pseudo-Latin text used in web design, typography, layout, and printing in place of English to emphasise design elements over content. It's also called placeholder (or filler) text. It's a convenient tool for mock-ups.",
- "zh_tw" => "財富整無必提引人懸身作渡健朝化紙事。人解食米生利娘法平終票織絶般改。文本行暮際對新左報事迫開件勝初測出人。速摘藤請能攜針紹式盤談。報厚勝月注揚件視申幅念七屬年。頼疑小章的談集演選容為真北左。"
- },
- {
- "en" => "While lorem ipsum's still resembles classical Latin, it actually has no meaning whatsoever. As Cicero's text doesn't contain the letters K, W, or Z, alien to latin, these, and others are often inserted randomly to mimic the typographic appearence of European languages, as are digraphs not to be found in the original.",
- "zh_tw" => "目報貴代向能究介集分頃妻。休表化降最州別文東表住線。呼支保木前果告共芝暴禁玉姫五點稚。第色絡明域市造神草要督運流題。信下臨法職左通出官質給探。沖金普議雪受國女出般馬紙手災半塊。通別暮載典子郎將開展造能一。"
- },
- {
- "en" => "In a professional context it often happens that private or corporate clients corder a publication to be made and presented with the actual content still not being ready. Think of a news blog that's filled with content hourly on the day of going live. However, reviewers tend to be distracted by comprehensible content.",
- "zh_tw" => "轉殺東入館特造賠感購予主市推製理承博。選被桶善外出神際抵法政。品誰非萬女話感合文昭。恐勢供村著雨木助階野食川園公大。連返一暮際平首寫一會未京美刃。珍者見藤石第返前鳥科宅様。直島載死談待思際考以響策依室參將機。演況民王手更愛五督銘索女。"
- }
- ].sample
- end
-
- def get_random_content
- [
- {
- "en" => "Lorem ipsum In magna nisi aliquip enim ex consectetur. Lorem ipsum Id laboris veniam ullamco velit minim sit in aute commodo. Lorem ipsum Eiusmod nisi consectetur eu nostrud nisi et commodo laborum sint commodo. Lorem ipsum Irure aliquip laboris aliquip qui sint incididunt sunt nisi Ut pariatur. Lorem ipsum Sint culpa proident consequat sed eu proident ex ea dolor. Lorem ipsum Aliquip proident adipisicing fugiat fugiat consequat sed ex nulla. Lorem ipsum Labore culpa enim enim voluptate cillum velit labore esse voluptate. Lorem ipsum Aute est quis mollit consectetur reprehenderit. Lorem ipsum Pariatur et in Ut id laboris aute aliqua. Lorem ipsum Ut id non ad cillum non est ad sunt reprehenderit in nulla. Lorem ipsum Ea commodo cillum veniam Ut aute exercitation ullamco dolor aliqua. Lorem ipsum Quis anim ad officia esse ut magna. Lorem ipsum Irure aute reprehenderit officia esse qui ex laborum mollit Duis laboris.",
- "zh_tw" => "對待證券首頁看法我和確認發布你看明顯之類答案透明多麼破,確保風險做法吸收不大,誘惑女子新手不論不可地上採購能力漫畫音樂營養河北笑,蒐集製造英國河南即可決策所說強化註冊還有廣場這麼這樣,好友音樂黃金有一定女,次數黑暗想法告知手續北京註冊。循環策略簡體中文股份塑料,加入時間經過會不會一家特色公告屬性協議多,公告穿著死亡說明角度體制交通路線期間太陽問題桌面依法,影視大學生道德虛擬業主自由不能,進去飛機本周越來越傳奇結構批發新人官員要有下,理念現像對比用戶名中國計算機目的,定位插件晚上加油年輕僅僅監督探索授權方式創業經營放棄。處理實現航空規定明天總,這一電源限制原因意思指數實驗表達互動代理體內較大早就代表,就不參數貢獻服務理論一方面計算進來貫徹規格面議不如監管證據,優秀監管試題回答容量,突破允許障礙考研你能也就是他們的我說空調也,拍攝男女增長其他官方方面發布結束模擬女子出了欄目我的心他,大幅備案無數貿易多種和平招聘,一時商標要在從事毫不手段經典可能會遭,高達旁邊演員代理適用於鑑定堅持管理。許多本次臨時發現小學前往第二章新型鏈接讓她這里聯賽鄭,相關讀者存儲博客零售最近多次付出造成請點擊也在房間帶,出去說是避免騎士還是注重不停網通相冊排行榜到處,尊重思路回到責任編輯每個人鬱,靈魂沒有甚至自己可能會說過出席化學新技術對手責任編輯可惜他說,家庭諾基亞沒事開通個性保密辛苦文檔選擇準備商城基本上他也休閒。"
- },
- {
- "en" => "Lorem ipsum Ad dolor in aliqua labore in dolor qui anim laborum. Lorem ipsum Et sed cillum anim nisi dolore. Lorem ipsum Enim sit dolor incididunt in tempor laborum nulla dolor nulla officia. Lorem ipsum Ut ea incididunt ad in esse eiusmod magna Excepteur sed esse. Lorem ipsum Cupidatat elit in ut dolore in mollit velit. Lorem ipsum Dolor enim aliqua consectetur veniam exercitation anim Duis occaecat aute in ex. Lorem ipsum Voluptate eiusmod sint pariatur quis velit aute enim fugiat. Lorem ipsum Officia dolore exercitation nisi qui minim anim id magna exercitation. Lorem ipsum Non in mollit veniam ut Excepteur officia. Lorem ipsum Ea in aliqua non ut commodo consequat commodo proident in anim. Lorem ipsum Culpa et Excepteur occaecat incididunt laborum pariatur ad ex reprehenderit. Lorem ipsum Cillum sed occaecat elit Excepteur Duis dolor exercitation commodo ut dolore. Lorem ipsum Sunt reprehenderit in dolore voluptate Excepteur ullamco pariatur sed dolore magna nisi. Lorem ipsum Mollit anim Ut elit aliqua labore laborum aliquip commodo nisi sint. Lorem ipsum Esse eu elit in nisi id sint nulla consectetur.",
- "zh_tw" => "加入時間一樣轉讓能量人們導致要有互動初步同學手機是怎麼,無關比例穿著再說上來好像我愛充滿當,新聞支付不足增加發揮神經果然將。招商經濟發展不少最後條款準確不,接受之類觀點身影蘇州總部可見言論空中一會這個問題電子如果您,解放危機顯卡享受足夠味道快速分類回答生成聯。一款帶來監督獎勵也能台北提出開了前面檢查,監管液晶交易建設而言看過放下江湖對了航空,智慧現代化緊緊一邊哥,屏幕長大角色前面精神新華網,刷新物質滿意看看反饋情感放在購買男生簡,默認最重要男孩世界杯還可以獲取全市版主我,位於讓他菜單矛盾塑料讓我畢業生作用人大常委會清楚寂。它們排行榜一張優勢本身接著感情人間有時候排行他就,形式第二天加快查詢尷尬影視大全你有詳細勝利和你演出出,世界杯多多供應改革監督出台作出總結提高最快全體美元文明西,神經那天法院你會靈活備案味道減,總是處理器森林服務器便宜中央不得不福建,回應插件倒是我們告訴你多媒體政府江蘇遺憾開口哥哥,言論你想文學外貿將會母親辛苦部落分析例如高級對,有限責任公司回事核心只要它們以往哪些大幅提交優勢對外否則。全省讓我們享受騎士嘗試男生新華網據說用戶,數碼相機用戶名退出得到見面部門老公小區讓他大賽被人開了,職責溝通字幕普遍介紹運,每年有一些點這裡下載身子竟然篇文章全國新年多個是不是天津您。這段頭銜下降河北獲得防止獨立道理公主策劃部落方案其實,等等等待不錯客服以外提示商家面對新聞,虛擬排行榜可以說恢復此時加大優勢上漲第一。品牌天使本身電子放在勝,又有痛苦尤其是如有商品金額有限公司爭取森林舉報好評期,印刷說到一部分金錢酒店畢業生交友概念治理付出,患者研究真實污染大力外資西安一聲這麼多內置舉報投,進步上次所需治理上傳文件大小否則個人形成有限責任公司成果魔法。提前安排的是考研起來手指小心所以監控一看很難一,媽媽在線有限責任公司適應重視就好會員增加環境試驗青年謝謝四川,贏得客人生意賓館語文。一體情形接下來鈴聲玻璃數碼相機動物英,出了禮物值得書庫看起來開了,治理不喜歡互相妻子偉大頭銜滿意動力花,似乎立刻爭取魔獸作品把你頻道,價值工程種種鐵路模擬慢慢保持爆炸才是迅速同一進,接收相關配套分配案例以後方面,具體室內請大家路線法律責任會員你有多,傳真零售日韓人事避免教育活,協調同步實施身影一大等方面海外本。趕緊安排特色技巧它們如果你非法,位於是由稱為不肯不錯核心你是行情明,股東日期值得國產正文,水晶後面模樣出售好多,說到不足怎麼辦市場名單友情鏈接稿件事,成熟隨著轉移解決不在人類台灣還在,家族慢慢鐵通怎麼電器願意設置內容簡介點這裡自主創,發貼或是男子裝置舉行網通優勢不限交通沒事聯盟最。年齡寶寶你自己曝光儀器體會情況不可一台這次考生農業變化鼠標,情感就在這麼多結婚身上公里給我紡織轉讓,錄入流程形成真實過了預防是有其實科技設計,外資充分森林如有事業,股東欣賞污染開展法院山東還沒有英國英文投票。廣播本地下載均為部分還可以,理解一對平時為何精華並不地址老婆演,一對不能湖北爸爸讓她早就酒店權力歐,同一先進多個協調通過創造關心機構興奮有機會都,笑話文化請求稿件我這現實求助改革,標題令人限制批准是個聯賽理念竟然麻煩目前,導航街道上次最新是他次數需,先進性反而付款認識批准禮物像是郵政。水果合理不肯智能明天世,時間措施鍵盤大部分國家吸引東西藥品不大作為光臨所謂,有時發行將軍女性再說都沒裡面地上實際上股權語文而已運行平台結,郵編但我前面讓我們亞洲拿出必須人口商品全身突破退出作品當中計,具備出發反正您是公斤想要。"
- }
- ].sample
- end
-
-end
\ No newline at end of file
diff --git a/temp_file/app/helpers/orbit_backend_helper.rb b/temp_file/app/helpers/orbit_backend_helper.rb
deleted file mode 100644
index 3110133..0000000
--- a/temp_file/app/helpers/orbit_backend_helper.rb
+++ /dev/null
@@ -1,250 +0,0 @@
-require "uri"
-require "net/http"
-module OrbitBackendHelper
- def self.included(base)
- ActionView::Helpers::FormBuilder.send(:include,OrbitFormHelper)
- end
-
- def group_impression_by_day(field,day_limit,start_day=Time.now,format = 'day')
- key_op = [['year','$year'],['month', '$month'], ['day', '$dayOfMonth']]
- key_op = key_op.take(1 + key_op.find_index { |key, op| format == key })
- project_date_fields = Hash[*key_op.collect { |key, op| [key, {op => "$#{field}"}] }.flatten]
- group_id_fields = Hash[*key_op.collect { |key, op| [key, "$#{key}"] }.flatten]
- pipeline = [
- {"$match"=> {"created_at" => {"$gte" => (start_day.to_date-(day_limit-2).days rescue ''), "$lte" => start_day}}},
- {"$project" => {field => 1}.merge(project_date_fields)},
- {"$group" => {"_id" => group_id_fields,"count" => {"$sum" => 1}}},
- {"$sort" => {"created_at"=>-1}}
- ]
- tmp = Impression.collection.aggregate(pipeline).to_a
- if tmp.count < day_limit
- tmp1 = tmp
- tmp = (0...day_limit).collect do |i|
- d = start_day - i.days
- d_year = d.year
- d_month = d.month
- d_day = d.day
- count = tmp1.select do |v|
- n_date = v['_id']
- n_date['year']==d_year && n_date['month']==d_month && n_date['day']==d_day
- end[0]['count'] rescue 0
- {'_id'=>{'year'=>d_year,'month'=>d_month,'day'=>d_day},'count'=>count}
- end
- end
- tmp
- end
- def thead(field,center=false,enable_sort=true)
- sort = field.to_s.include?('.') ? field.to_s.split('.')[1] : field.to_s
- active = params[:sort].eql? sort
- order = active ? (["asc", "desc"]-[params[:order]]).first : "asc"
- arrow = (order.eql? "desc") ? "" : ""
- klass = field.eql?(:title) ? "span5" : "span2"
-
- th_data = (sort=="preview" || !enable_sort) ? t(field.to_sym) : "#{t(field.to_sym)} #{active ? arrow : ""}"
-
- "
#{th_data}
".html_safe
- end
-
-
- def add_attribute(partial, f, attribute)
- new_object = f.object.send(attribute).build rescue nil
- fields = f.fields_for(attribute, new_object, :child_index => "new_#{attribute}") do |f|
- render :partial => partial, :object => new_object, :locals => {:f => f}
- end
- end
-
- def is_filter_active?(field, value)
- params[:filters][field].include?(value.to_s) ? "active" : "" rescue ""
- end
-
-
- def select_category(f, module_app)
- @user_authorized_categories = module_app.categories.enabled.authorized(current_user) if @user_authorized_categories.nil?
- render :partial => '/admin/categories/select_form', :locals => {:f=> f, :module_app=>module_app, :categories=> @user_authorized_categories }
- end
-
- def copy_to_all_language_button(language_tab, language_area)
- render :partial => '/shared/copy_to_all_language_button', :locals => {:language_area => language_area, :language_tab => language_tab}
- end
-
- def select_tags(f, module_app)
- render :partial => '/admin/tags/tag_form', :locals => {:f=> f, :module_app=>module_app, :tags=>module_app.tags }
- end
-
- def render_filter(fields, search_dom_id=nil, quick_new=false)
- render :partial => "shared/filter", :locals =>{:fields => fields, :search_dom_id=>search_dom_id, :quick_new=>quick_new}
- end
-
- def display_visitors(options={})
- Impression.where(options).count
- end
-
- def display_visitors_today
- if (defined? @result_of_thirty_day).nil?
- display_visitors(created_at: {'$gte' => Time.now.beginning_of_day})
- else
- @result_of_thirty_day[0]['count']
- end
- end
-
- def display_visitors_this_week
- if (defined? @result_of_thirty_day).nil?
- display_visitors(created_at: {'$gte' => Time.now.beginning_of_week})
- else
- @result_of_thirty_day[0..((Time.now-Time.now.beginning_of_week)/86400).floor].map{|v| v['count']}.reduce{|v,x| v+x}
- end
- end
-
- def display_visitors_this_month
- if (defined? @result_of_thirty_day).nil?
- visitors_this_month = Rails.cache.fetch("visitors_this_month", expires_in: 1.day) do
- display_visitors(created_at: {'$gte' => Time.now.beginning_of_month})
- end
- visitors_this_month
- else
- @result_of_thirty_day[0..((Time.now-Time.now.beginning_of_month)/86400).floor].map{|v| v['count']}.reduce{|v,x| v+x}
- end
- end
-
- def display_visitors_this_year
- visitors_this_year = Rails.cache.fetch("visitors_this_year", expires_in: 1.day) do
- display_visitors(created_at: {'$gte' => Time.now.beginning_of_year})
- end
- visitors_this_year
- end
-
- def get_month_traffic
- #site = Site.first
- #if site.month_traffic_cache.blank? or (site.month_traffic_cache['updated_at'] < (Time.now-1.day) rescue true)
- #site.month_traffic_cache = {}
- #site.month_traffic_cache['result'] = []
- @result_of_thirty_day = group_impression_by_day(:created_at,30)
- trafic_result = @result_of_thirty_day.map do |v|
- date = v['_id'].values
- [Date.new(date[0],date[1],date[2]).to_time,v['count']]
- end
- #site.month_traffic_cache['result'] = trafic_result
- #site.month_traffic_cache['updated_at'] = Time.now
- #site.save
- #end
-
- #[:name=> t(:visitors_count),:data=>site.month_traffic_cache['result']]
- [:name=> t(:visitors_count),:data=>trafic_result]
- end
-
- def can_edit_or_delete?(obj)
- create_user = obj.create_user_id.to_s rescue nil
- if @user_authenticated_categories.first == "all"
- return true
- elsif obj.class == Page && current_user.is_manager?(ModuleApp.where(:key=>'page_content').first)
- return true
- elsif @current_user_is_sub_manager && !create_user.nil?
- return ( @user_authenticated_categories.include?(obj.category_id) rescue (create_user == current_user.id.to_s))
- else
- tmp = false
- if @changed_module_app
- if obj.class == Page
- if obj.tmp_root_page_id
- obj = Page.find(obj.tmp_root_page_id)
- end
- if obj.bind_model.present?
- new_obj = obj.bind_model.constantize.where(:uid=>obj.bind_uid).first rescue nil
- obj = new_obj if new_obj
- end
- end
- tmp = @user_authenticated_categories.include?obj.category_id rescue (current_user.is_manager?(@changed_module_app) rescue false)
- else
- tmp = @user_authenticated_categories.include?obj.category_id rescue (current_user.is_manager?(@module_app) rescue false)
- end
- tmp
- end
- end
-
- def user_authenticated_categories
- @user_authenticated_categories
- end
-
- def is_user_sub_manager?
- @current_user_is_sub_manager
- end
-
- def has_access? #@user_has_privileges comes from orbit_member_controller.. used just in members
- @user_has_privileges
- end
-
- def check_store_permissions #checks with the store if it has proper access and rights to access store
- store_permission = {}
- store_token = @site.store_token rescue nil
- if !store_token.nil?
- params_to_send = {'store_token' => @site.store_token}
- uri = URI.parse(OrbitStore::URL)
- http = Net::HTTP.new(uri.host,uri.port)
- http.read_timeout =1 #seconds
- request = Net::HTTP::Get.new("/site/permissions")
- request.body = params_to_send.to_query
- http.open_timeout = 1 #set read_timeout to 1 second to avoid web die caused by no response
- http.ssl_timeout = 1
- begin
- response = http.request(request)
- rescue
- response = ActionDispatch::Response.new
- response.body = {'success'=>true}.to_json
- end
- if response.nil?
- data = {}
- data["message"] = "Could not connect to the store."
- data["error"] = "CONNECTION_REFUSED"
- data["success"] = false
- else
- data = JSON.parse(response.body) rescue nil
- end
- if data.nil?
- data = {}
- data["message"] = "Could not connect to the store."
- data["error"] = "JSON_ERROR"
- data["success"] = false
- end
- if !data["success"]
- case data["error"]
- when "INVALID_SITE_TOKEN"
- @site.store_token = nil
- @site.save
- end
- store_permission["permission_granted"] = false
- store_permission["error"] = data["error"]
- store_permission["message"] = data["message"]
- else
- store_permission["permission_granted"] = true
- end
- else
- store_permission["permission_granted"] = false
- store_permission["error"] = "SITE_NOT_REGISTERED"
- store_permission["message"] = "Site not registered."
- end
- store_permission
- end
-
- def render_401
- render "errors/401"
- end
-
- def render_403
- render "errors/403"
- end
-
- def need_access_right
- render_401 if !has_access?
- end
-
- def get_referer_url
- referer_path = Rails.application.routes.recognize_path(request.referer)
- if referer_path[:controller]!="pages" or (referer_path[:controller]==params[:controller] and referer_path[:action]!="index")
- referer_url = '/'+params[:controller]
- else
- referer_url = request.referer
- end
- referer_url
- end
-
-end
-
diff --git a/temp_file/app/helpers/orbit_form_helper.rb b/temp_file/app/helpers/orbit_form_helper.rb
deleted file mode 100644
index 5dd716e..0000000
--- a/temp_file/app/helpers/orbit_form_helper.rb
+++ /dev/null
@@ -1,162 +0,0 @@
-module OrbitFormHelper
- def self.included(base)
- #ActionView::Helpers::FormBuilder.send(:include, Orbit::FormBuilder)
- ActionView::Helpers::FormBuilder.send(:include,ActionView::Helpers::UrlHelper)
- ActionView::Helpers::FormBuilder.send(:include,ActionView::Helpers::TagHelper)
- ActionView::Helpers::FormBuilder.send(:include,ActionView::Context)
- ActionView::Helpers::FormBuilder.send(:include,ActionView::Helpers::FormTagHelper)
- end
-
- def datetime_picker(object_name, options = {})
- def objectify_options(options)
- @default_options = {} if @default_options.class != Hash
- @default_options.merge(options.merge(object: @object))
- end
- options[:icon_time] ||= 'icons-clock'
- options[:icon_date] ||= 'icons-calendar'
- options[:icon_clear] ||= 'icons-cross-3'
- options[:input_class] ||= 'input-large'
- options[:new_record] = true if options[:new_record].nil?
- options = objectify_options(options)
- options[:value] ||= options[:object].send(object_name) if options[:object] && options[:object][object_name]
- options[:placeholder] ||= (options[:format].to_s.empty? ? nil : options[:format])
- case options[:picker_type]
- when 'date'
- content_tag :div, :id => options[:id], :class => options[:class] do
- date_picker(object_name, options)
- end
- when 'time'
- content_tag :div, :id => options[:id], :class => options[:class] do
- time_picker(object_name, options)
- end
- when 'separated'
- options[:label] ||= I18n.t('datetime_picker.separated.label')
- content_tag :div, :id => options[:id], :class => "separated_picker #{options[:class]}" do
- concat label_tag options[:label] unless options[:no_label]
- concat hidden_field(object_name, :value => options[:value])
- concat separated_picker(object_name, options)
- end
- when 'simple'
- content_tag :div, :id => options[:id], :class => options[:class] do
- simple_picker(object_name, options)
- end
- else
- content_tag :div, :id => options[:id], :class => options[:class] do
- default_picker(object_name, options)
- end
- end
- end
-
- def default_picker(object_name, options)
- custom = {}
- options[:format] = options[:format] || 'yyyy/MM/dd hh:mm'
- options[:value] = format_value(options[:value], options[:format]) if options[:value] && !options[:new_record]
- options[:value] = "" if options[:new_record]
- custom[:picker_class] = 'default_picker'
- custom[:label] = options[:label] || I18n.t('datetime_picker.default.label')
- custom[:placeholder] = options[:placeholder] || I18n.t('datetime_picker.default.placeholder')
- picker(object_name, options.merge(custom))
- end
-
- def picker(object_name, options)
- content_tag :div, :class => "#{options[:picker_class]} input-append" do
- concat label_tag options[:label] unless options[:no_label]
- if object_name.nil?
- if !options['id'].nil?
- concat text_field_tag nil ,options[:value], :placeholder => options[:placeholder], :class => options[:input_class], 'data-format' => options[:format], :data => options[:data], :id => options['id']
- else
- concat text_field_tag nil,options[:value], :placeholder => options[:placeholder], :class => options[:input_class], 'data-format' => options[:format], :data => options[:data]
- end
- else
- if !@object.nil?
- if !options['id'].nil?
- concat text_field object_name , :placeholder => options[:placeholder], :class => options[:input_class], 'data-format' => options[:format], :value => options[:value], :data => options[:data], :id => options['id']
- else
- concat text_field object_name, :placeholder => options[:placeholder], :class => options[:input_class], 'data-format' => options[:format], :value => options[:value], :data => options[:data]
- end
- else
- if !options['id'].nil?
- concat text_field_tag object_name ,options[:value], :placeholder => options[:placeholder], :class => options[:input_class], 'data-format' => options[:format], :value => options[:value], :data => options[:data], :id => options['id']
- else
- concat text_field_tag object_name ,options[:value], :placeholder => options[:placeholder], :class => options[:input_class], 'data-format' => options[:format], :value => options[:value], :data => options[:data]
- end
- end
- end
- concat (content_tag :span, :class => 'add-on clearDate' do
- content_tag :i, nil, :class => options[:icon_clear]
- end)
- concat (content_tag :span, :class => 'add-on iconbtn' do
- content_tag :i, nil, 'data-time-icon' => options[:icon_time], 'data-date-icon' => options[:icon_date]
- end)
- end
- end
-
- def format_value(value, format = 'yyyy-MM-dd hh:mm')
- value.strftime(format.gsub('yyyy', '%Y').gsub('MM', '%m').gsub('dd', '%d').gsub('hh', 'h').gsub('HH','H').gsub('H', '%H').gsub('h', '%H').gsub('mm', '%M')) rescue value.to_s
- end
-
-
- def simple_picker(object_name, options)
- onkeypress_for_input = 'return (event.charCode >= 48 && event.charCode <= 57) || event.keyCode == 8 || event.keyCode == 46 || (event.keyCode >= 37 && event.keyCode <= 40) || event.keyCode == 9'
- onkeyup_for_input = 'this.value=(this.value.length <= 2 ? (parseInt(this.value) > 0 && parseInt(this.value) < 32 ? this.value : this.value.substring(0,this.value.length-1)) : this.value.substring(0,this.value.length-1))'
- onkeyup_for_input2 = 'this.value=(this.value.length == 4 ? (parseInt(this.value) > 1900 && parseInt(this.value) < 3000 ? this.value : this.value.substring(0,this.value.length-1)) : (this.value.length > 4 ? this.value.substring(0,this.value.length-1) : this.value))'
- html = "
-
- "
- html = html + hidden_field(object_name, :value => options[:value] || "1901-01-01")
- html = html + "
"
- html.html_safe
- end
-
- def date_picker(object_name, options)
- custom = {}
- custom[:format] = options[:format] || 'yyyy/MM'
- custom[:value] = format_value(options[:value], custom[:format]) if options[:value]
- custom[:picker_class] = 'date_picker'
- custom[:label] = options[:label] || I18n.t('datetime_picker.date.label')
- options[:placeholder] ||= I18n.t('datetime_picker.date.placeholder')
- picker(object_name, options.merge(custom))
- end
-
- def time_picker(object_name, options)
- custom = {}
- custom[:format] = options[:format] || 'HH:mm'
- custom[:value] = format_value(options[:value], custom[:format]) if options[:value]
- custom[:picker_class] = 'time_picker'
- custom[:label] = options[:label] || I18n.t('datetime_picker.time.label')
- custom[:placeholder] = options[:placeholder] || I18n.t('datetime_picker.time.placeholder')
- picker(object_name, options.merge(custom))
- end
-
- def separated_picker(object_name, options)
- custom = {}
- custom[:no_label] = true
- custom[:separated] = true
- date_picker(nil, options.merge(custom).merge({:format=>'yy/mm/dd','id'=>"_1_#{object_name}"})) + time_picker(nil, options.merge(custom).merge({:format=>'hh:mm','id'=>"_2_#{object_name}"}))
- end
-
-
- def single_picker(object_name, options)
- content_tag :div, :id => options[:id], :class => options[:class] do
- picker(object_name, options)
- end
- end
-
- def double_picker(object_name, options)
-
- end
-
-
-end
-
-module Orbit::FormBuilder
- # ActionPack's metaprogramming would have done this for us, if FormHelper#labeled_input
- # had been defined at load. Instead we define it ourselves here.
- #def datetime_picker(method, options = {})
- # @template.datetime_picker(@object_name, method, objectify_options(options))
- #end
-end
\ No newline at end of file
diff --git a/temp_file/app/helpers/orbit_helper.rb b/temp_file/app/helpers/orbit_helper.rb
deleted file mode 100644
index c7605fc..0000000
--- a/temp_file/app/helpers/orbit_helper.rb
+++ /dev/null
@@ -1,642 +0,0 @@
-module OrbitHelper
- def self.set_params(params,current_user)
- @params = params
- @current_user = current_user
- end
- def self.set_page_controller(c)
- @page_controller = c
- end
-
- def self.get_page_controller
- @page_controller
- end
-
- def self.set_page_categories(categories)
- @categories = categories;
- end
-
- def self.set_page_tags(tags)
- @tags = tags;
- end
-
- def self.create_item_json(root_page=nil)
- locale = I18n.locale
- pipeline = [{"$sort" => {"number" => 1}}]
- if !root_page.nil? #item include root_page
- pipeline << {"$match" => {"$or" => [{"url" => (root_page.url=='/' ? /^\// : /^#{root_page.url}\//)},{"_id" => root_page.id}]}}
- end
- pipeline += [
- {"$project" => {"name" => "$name.#{locale}",
- "url" => {"$cond" => [{"$gt"=>["$external_url.#{locale}", ""]},
- "$external_url.#{locale}",
- {"$concat" =>[{"$literal"=> (@prefix_url ? @prefix_url : "/#{locale.to_s}")},"$url"]},
- ]},
- "parent_page_id" => "$parent_page_id",
- "id" => "$_id",
- "page_id" => "$page_id",
- "module" => "$module",
- "page_type" => {"$cond" => [{"$lte"=>["$page_type", nil]},
- "page",
- "$page_type"
- ]},
- "access_level" => {"$cond" => [{"$lte"=>["$access_level", nil]},
- "none",
- "$access_level"
- ]},
- "enabled_for" => "$enabled_for",
- "menu_enabled_for" => "$menu_enabled_for",
- "is_root" => {"$cond" => [{"$lte"=>["$parent_page_id", nil]},
- true,
- false
- ]}
- }
- },
- {"$project" => {"name" => "$name",
- "url"=>"$url",
- "parent_page_id" => "$parent_page_id",
- "id" => "$_id",
- "page_id" => "$page_id",
- "module" => "$module",
- "page_type" => "$page_type",
- "access_level" => "$access_level",
- "enabled_for" => "$enabled_for",
- "menu_enabled_for" => "$menu_enabled_for",
- "is_root" => "$is_root",
- "target"=>{"$cond" => [{"$eq" => [{"$substr" => ["$url",0,4]}, "http"]},
- {"$literal"=> "_blank"},
- {"$literal"=> "_self"},
- ]}
- }
-
- },
- {"$group" => {"_id"=>"$parent_page_id","children"=>{"$push"=>"$$ROOT"}}}
- ]
- return Page.collection.aggregate(pipeline).inject({}) do |r, s|
- r.merge!({s['_id'] => s['children']})
- end
- end
-
- def self.register_subpart(subpart_id)
- subpart = SubPart.find(subpart_id) rescue nil
- if !subpart.nil?
- self.set_current_widget subpart
- self.set_widget_data_count subpart.data_count
- self.set_widget_categories subpart.categories
- self.set_widget_module_app subpart.module
- self.set_widget_item_url subpart
- self.set_widget_title subpart.title
- self.set_widget_categories subpart.categories || []
- self.set_widget_tags subpart.tags || []
- custom_value = subpart.custom_string_field || subpart.custom_array_field || subpart.custom_data_field rescue nil
- if !custom_value.nil?
- self.set_widget_custom_value custom_value
- else
- self.set_widget_custom_value nil
- end
- end
- end
-
- def self.set_page_role_status(role_status)
- @role_status = role_status;
- end
-
- def self.set_member_sort_position(sort_position)
- @sort_position = sort_position;
- end
-
- def self.set_page_data_count(data_count)
- @data_count = data_count
- end
-
- def self.page_data_count
- @data_count
- end
-
- def self.set_page_number(page)
- @page_number = page
- if @page_number == 0
- @page_number = 1
- end
- end
-
- def self.page_number
- @page_number || 1
- end
-
- def self.page_categories
- @categories
- end
-
- def self.page_tags
- @tags
- end
-
- def self.page_role_status
- @role_status
- end
-
- def self.member_sort_position
- @sort_position
- end
-
- def self.current_user
- @current_user
- end
-
- def self.page_for_tag(tag)
- if @params[:url]
- page_for_tag_url = "/#{@site_locale}#{@params[:url]}"
- else
- page_for_tag = nil
- pages = Page.where(:module => @module_app.key)
- pages.each do |page|
- if page.tags.count ==1
- if page.tags.include?(tag)
- page_for_tag = page
- end
- end
- break if !page_for_tag.nil?
- end
-
- if page_for_tag.nil?
- pages.each do |page|
- if page.tags.include?(tag)
- page_for_tag = page
- end
- break if !page_for_tag.nil?
- end
- end
-
- page_for_tag = pages.first if page_for_tag.nil?
- page_for_tag_url = page_for_tag.url
- end
- '/'+I18n.locale.to_s + page_for_tag_url + '?tags[]='+tag.id.to_s
- end
-
- def self.this_module_app
- @module_app
- end
-
- def self.widget_module_app
- @widget_module_app
- end
-
- def self.set_this_module_app(module_app)
- @module_app = ModuleApp.where(:key=>module_app).first
- end
-
- def self.set_widget_custom_value(value)
- @widget_custom_value = value
- end
-
- def self.widget_custom_value
- @widget_custom_value
- end
-
- def self.set_widget_module_app(module_app)
- @widget_module_app = ModuleApp.where(:key=>module_app).first
- end
-
- def self.set_widget_title(title)
- @widget_title = title
- end
-
- def self.widget_title
- @widget_title
- end
-
- def self.set_widget_tags(tags)
- @widget_tags = tags
- end
-
- def self.widget_tags
- @widget_tags
- end
-
- def self.user_can_edit?(obj)
- return false if @current_user.nil?
- return true if @current_user.is_admin?
- if obj.class == Page
- @site ||= ApplicationHelper::CurrentSite
- if @site.has_sub_home
- if obj.tmp_root_page_id
- new_obj = Page.find(obj.tmp_root_page_id)
- if new_obj.bind_model.present?
- new_obj2 = new_obj.bind_model.constantize.where(:uid=>new_obj.bind_uid).first rescue nil
- obj = new_obj2 if new_obj2
- end
- end
- end
- end
- return @current_user.nil? ? false : self.user_has_cateogry?(obj.category_id)
- end
-
- def self.user_access_level?
- access_level = nil
- if @current_user.nil?
- access_level = "user"
- elsif@current_user.is_admin?
- access_level = "admin"
- elsif @current_user.is_manager?(@module_app)
- access_level = "manager"
- elsif @current_user.is_sub_manager?(@module_app)
- access_level = "sub_manager"
- elsif @current_user.is_manager_with_role?(@module_app)
- access_level = "manager"
- elsif @current_user.is_sub_manager_with_role?(@module_app)
- access_level = "sub_manager"
- end
- access_level
- end
-
- def self.user_has_cateogry?(cat)
- return false if @current_user.nil?
- if @current_user.is_admin? or @current_user.is_manager?(@module_app)
- return true
- else
- category = Category.find(cat) rescue nil
- return false if category.nil?
- return @current_user.approved_categories.include?category rescue false
- end
- end
- def self.page
- @page
- end
- def self.set_page(page)
- @page_show_url = nil
- @plugin_show_url_map = nil
- @page = page
- end
- def self.params
- @params
- end
-
- def self.url_to_show(slug)
- #pages = Page.where(:url=>@params[:url]).to_a
- if self.page.nil?
- "/#{@site_locale}#{@params[:url]}/#{slug}"
- else
- @page_show_url = @page_show_url || self.page.get_url
- "/#{@site_locale}#{@page_show_url}/#{slug}"
- end
- end
-
- def self.url_to_plugin_show(slug,module_app)
- @plugin_show_url_map ||= {}
- if @plugin_show_url_map[module_app].nil?
- @plugin_show_url_map[module_app] = Page.find_by(:module => module_app).get_url rescue ""
- end
- if @plugin_show_url_map[module_app].blank?
- @url_to_plugin_show = "#"
- else
- @url_to_plugin_show = "/#{@site_locale}#{@plugin_show_url_map[module_app]}/#{slug}" rescue "#"
- end
- end
-
-
- def self.override_widget_module_app(module_app)
- self.set_widget_module_app module_app
- widget = self.get_current_widget
- if self.page.nil?
- self.set_page((widget.page_part.page rescue Page.root))
- end
- self.calc_widget_read_more_url(widget)
- end
-
- def self.calc_widget_read_more_page_for_module(widget,locale=I18n.locale) #read_more_page_id.blank? || read_more_page.nil?
- module_app = widget.module
- module_app = self.widget_module_app.key if module_app.nil?
-
- pages = self.page.find_page(:module => module_app,:enabled_for.in=>[@site_locale.to_s])
- current_module_app = (@widget_module_app.key==module_app rescue false) ? @widget_module_app : ModuleApp.where(:key=>module_app).first
- order_method = (current_module_app.nil? || current_module_app.asc) ? :asc : :desc
- finalpage = pages.where(:categories.all=> widget.categories).first
- if finalpage.nil?
- nils_cats, not_nils_cats = Category.where(:id.in => widget.categories,:disable.ne=>true).order_by(sort_number: order_method).partition { |cat| cat[:sort_number].nil? }
- widget_categories = not_nils_cats + nils_cats
- finalpage = widget_categories.first.nil? ? (pages.where(:categories=>['all']).first || pages.first) : (pages.where(:categories.in => [widget_categories.first.id]).first || pages.where(:categories=>['all']).first || pages.first)
- end
- return finalpage
- end
-
- def self.calc_widget_read_more_url(widget,locale=I18n.locale)
- finalpage = widget.read_more_page_id.blank? ? nil : self.page.find_page(:page_id=> widget.read_more_page_id,:enabled_for=>locale).first rescue nil
- if finalpage.nil?
- finalpage = self.calc_widget_read_more_page_for_module(widget,locale)
- end
- if !finalpage.nil?
- @url_widget_for_show = "/#{@site_locale.to_s}#{finalpage.get_url}"
- else
- @url_widget_for_show = "#"
- end
- @url_widget_for_show
- end
-
- def self.set_widget_item_url(widget)
- if self.page.nil?
- puts ['page is nil']
- self.set_page((widget.page_part.page rescue Page.root))
- end
- @url_widget_for_show = widget.get_read_more_page_url
- end
-
- def self.array_include(arr1,arr2)
- final = []
- arr2.each do |el|
- final.push(arr1.include?el)
- end
- !final.include?false
- end
-
- def self.widget_item_url(obj)
- @url_widget_for_show + "/" + obj
- end
-
- def self.widget_more_url
- @url_widget_for_show
- end
-
- def page_url(url)
- "#{request.host_with_port}/#{locale}#{url}"
- end
-
- def self.set_request_object(request)
- @site_request_object = request
- end
-
- def self.request
- @site_request_object
- end
-
- def self.set_site_locale(locale)
- @site_locale = locale
- end
-
- def self.set_widget_data_count(data_count)
- @widget_data_count = data_count
- end
-
- def self.widget_data_count
- @widget_data_count
- end
-
- def self.set_widget_categories(categories)
- @widget_categories = []
- disabled_categories = Category.where(:id.in=>categories,:disable=>true).pluck(:id).map(&:to_s)
- @widget_categories = categories - disabled_categories
- @widget_categories = ["all"] if @widget_categories.blank?
- end
-
- def self.widget_categories
- @widget_categories
- end
-
- def self.get_site_locale
- @site_locale
- end
-
- def self.current_widget_module
- @controller_name
- end
-
- def self.set_current_widget_module(name)
- @controller_name = name
- end
-
- def self.set_current_widget(widget)
- @current_widget = widget
- end
-
- def self.get_current_widget
- @current_widget
- end
-
- def get_item_module_infos(page)
- if page['parent_page_id'].nil?
- ["Home","icons-house"]
- else
- @all_module_app = @all_module_app || ModuleApp.all.group_by(&:key)
- module_app = @all_module_app[page['module']][0] rescue nil
- unless module_app.nil?
- [module_app.title, (module_app.get_registration.icon_class || module_app.get_registration.get_icon_class_no_sidebar)]
- else
- if page['module'].eql? "sitemap"
- ["sitemap", "icons-directions"]
- else
- ["", "icon-minus-sign"]
- end
- end
- end
- end
-
- def self.orbit_impressionist(object)
- impressionist(object)
- end
-
- def self.is_mobile_view
- !$mobile.blank?
- end
-
- def self.set_css_to_render_to_empty
- @css_to_render_in_head = []
- end
-
- def self.render_css_in_head(css=[])
- @css_to_render_in_head.concat(css)
- end
-
- def self.render_js_in_head(js=[])
- @js_to_render_in_head = @js_to_render_in_head || Array(@js_to_render_in_head)
- @js_to_render_in_head.concat(js)
- end
-
- def self.get_css_to_render_in_head
- css_html = "\n" + ActionController::Base.helpers.stylesheet_link_tag(*Array(@css_to_render_in_head))
- css_html = css_html + ActionController::Base.helpers.javascript_include_tag(*Array(@js_to_render_in_head))
- return css_html
- end
-
- def self.render_meta_tags(metas=[])
- @page_meta_tags = metas
- end
-
- def self.meta_tags_html
- html = ""
- if !@page_meta_tags.nil?
- @page_meta_tags.each do |meta|
- html = html + ""
- end
- end
- html
- end
-
- def self.strip_html_tags(string)
- ActionView::Base.full_sanitizer.sanitize(string)
- end
-
- # get feeds for the module
-
- def self.get_feed_for_module(type)
- if ModuleApp.where(:key => "feed").count == 0
- return []
- end
- categories = []
- ma = nil
- if type == "index"
- categories = @categories if !@categories.nil?
- ma = @module_app
- elsif type == "widget"
- categories = @widget_categories if !@widget_categories.nil?
- ma = @widget_module_app
- end
- if categories.first == "all"
- feeds = SiteFeed.where(:channel_key => ma.key).enabled
- else
- feeds = SiteFeed.where(:channel_key => ma.key, :merge_with_category.in => categories).enabled
- end
- data = []
- if feeds.count > 0
- temp_ids = []
- feeds.each do |feed|
- file = File.join(Rails.root,"public","site_feeds",feed.id.to_s,feed.feed_uid.to_s + ".json")
- if File.exist?(file)
- d = File.read(file)
- d = JSON.parse(d) rescue {ma.key.pluralize => []}
- cat = Category.find(feed.merge_with_category).title
- final_d = []
- d[ma.key.pluralize].each{|a|
- a["category"] = cat
- a["source-site"] = feed.remote_site_url
- a["source-site-title"] = (!feed.channel_title.nil? && feed.channel_title != "" ? feed.channel_title : "#{I18n.t("feed.source")}")
- if !temp_ids.include?(a["id"])
- temp_ids << a["id"]
- a["params"] = a["params"] + "_" + feed.id.to_s + "h"
- final_d << a
- end
- }
- data.concat(final_d)
- end
- end
- end
- data
- end
-
- def self.is_object_from_feed?(uid)
- return uid.ends_with?("h")
- end
-
- def self.get_from_feed(uidwithid)
- temp = uidwithid.split("_")
- feed_id = temp[1][0...-1]
- uid = temp[0]
- object = nil
- feed = SiteFeed.find(feed_id) rescue nil
- if !feed.nil?
- file = File.join(Rails.root,"public","site_feeds",feed.id.to_s,feed.feed_uid.to_s + ".json")
- if File.exist?(file)
- d = File.read(file)
- d = JSON.parse(d)
- objects = d[@module_app.key.pluralize]
- object = objects.select{|obj| obj["id"] == uid}.first
- cat = Category.find(feed.merge_with_category)
- object = {} if cat.disable
- end
- end
- object
- end
-
- # ===============================================================
- # Breadcrumbs
- # ===============================================================
- def back_end_breadcrumb
- res = ''
- divider = "/"
- res << "