class Admin::SitesController < OrbitAdminController before_filter :get_site before_filter :set_git_branch, :only=>[:check_updates, :update_orbit] include Admin::GmailHelper 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' => current_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" => current_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 /`.gsub("\n","
").html_safe @nginx_version = %x[/usr/sbin/nginx -v 2>&1].gsub("\n","
").html_safe @mongo_version = `mongod --version`.split("\n")[0].html_safe @linux_version = `lsb_release -d`.split(":")[1].html_safe rescue "Not Applicable" @user_actions = UserAction.all.desc(:created_at).page(params[:page]).per(10) @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 :nothing => true 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) if params[:site][:enable_language_detection].eql?("0") Site.update_all({:enable_language_detection => false}) elsif params[:site][: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(current_site) else redirect_to :back 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 ." 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 :text => 'waiting' else render :json => store_permissions.to_json end elsif params['type'] == 'restore' git_reset(params['id'],'restore') render :text => 'waiting' elsif params['type'] == 'get_result' render :text => 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 :nothing => true end def restart_server mode = Rails.env unicorn_rails = %x[which unicorn_rails].sub("\n",'') render :nothing => true 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 get_site @site = @current_site.nil? ? Site.first : @current_site end def dashboard_is_first_run? !current_user.is_tour_completed?("tickets") end def site_params if params[:site][:default_bar_color] params[:site][:mobile_bar_color] = [] end # if params[:site][:enable_language_detection] # Site.update_all({:default_locale => nil}) # end unless params[:site][:in_use_locales].nil? in_user_locales = [] I18n.available_locales.each do |locale| in_user_locales << locale if params[:site][:in_use_locales][locale].eql?("1") end params[:site][:in_use_locales] = in_user_locales end if params[:site][:phone_number].nil? params[:site][:phone_number] = [] # else # params[:site][:phone_number] = params[:site][:phone_number] end params[:site][:sign_up_roles] = [] if !params[:site][:sign_up_roles].present? params.require(:site).permit! end def set_git_branch @branch = %x(git rev-parse --abbrev-ref HEAD).gsub("\n","") end end