).)*)<\/tbody>(?:(?!<\/table>).)*<\/table>/m) do |tbody|
					tmp = $1
					tmp = tmp.scan(/).)*)>((?:(?!<\/td>).)*)<\/td>/m).map{|v| "#{v[1]}<\/span><\/div>"}.join
					"#{hide_sharer_button}#{tmp}<\/div>"
				end
				floating_class = site[:floating_window].blank? ? "" : " reactable"
				hide_in_menu_class = site[:social_share_hide_in_menu] ? " mobile-diff" : ""
				" ".html_safe
			end
		else
			""
		end.html_safe
	end
	def render_orbit_bar
		if $making_cache
			return "{{render_orbit_bar}}".html_safe
		else
			if @orbit_bar_not_display
				orbit_bar_file = File.join(Rails.root,'app/views', "orbit_bar", 'no_orbit_bar.html.erb')
			elsif is_mobile_layout_active
				orbit_bar_file = File.join(Rails.root,'app/views', "orbit_bar", 'index_mobile.html.erb')
			else
				orbit_bar_file = File.join(Rails.root,'app/views', "orbit_bar", 'index.html.erb')
			end		
			orbit_bar_file_html = render(:file => orbit_bar_file, :formats => [:html])
			orbit_bar_file_html.html_safe
		end
	end
	def render_menu(tmp_mobile=nil)
		@site ||= CurrentSite
		@mobile = tmp_mobile.nil? ? $mobile : tmp_mobile
		# cache_data = (@site.get_cache_menu_data(@mobile) rescue nil)
		# if !cache_data.blank?
		# 	return cache_data.html_safe
		# end
		# menu_html = Rails.cache.fetch(['main_menu',request.original_fullpath, I18n.locale], race_condition_ttl: 2.seconds) do
		# json_file = File.read(File.join(Rails.root, 'public', "menu.json"))
		# @items = JSON.parse(json_file)
		root_page = @sub_home ? @sub_home : Page.root
		def create_json(root_page)
			can_access_levels = current_user.nil? ? [nil,"none"] : [nil,"none","users",*(current_user.member_profile.role_ids.collect{|role| role.to_s} rescue [])]
			can_access_levels << "ip" if @need_process_ip
			match_cond = {"menu_enabled_for"=>{"$in"=>[locale.to_s]},
						"access_level"=>{"$in"=>can_access_levels},
						"parent_page_id"=>{"$nin"=>[nil,""]}
						}
			if !@mobile.blank?
				match_cond = match_cond.merge({"enabled_for_mobile"=>true})
			end
			if !root_page.parent_page_id.blank?
				match_cond = match_cond.merge({"url" => /^#{root_page.url}\//})
			end
			project1 = {"name" => "$name.#{locale}",
						"url" => {"$cond" => [{"$gt"=>["$external_url.#{locale}", ""]},
												"$external_url.#{locale}",
												{"$concat" =>[{"$literal"=> (@custom_prefix_url ? @custom_prefix_url : "/#{locale.to_s}")},"$url"]},
											]},
						"parent_page_id" => "$parent_page_id"
						}
			project2 = {"name" => "$name",
						"url"=>"$url",
						"target"=>{"$cond" => [{"$eq" => [{"$substr" => ["$url",0,4]}, "http"]},
												{"$literal"=> "_blank"},
												{"$literal"=> "_self"},
											]},
						"parent_page_id" => "$parent_page_id"
						}
			if @process_ip_later
				project1['access_level'] = "$access_level"
				project1["is_ip"] = {"$eq" => ['$access_level','ip']}
				project2['access_level'] = "$access_level"
				project2["is_ip"] = {"$eq" => ['$access_level','ip']}
			end
			return Page.collection.aggregate([
				{"$sort" => {"number" => 1}},
				{"$match" => match_cond},
				{"$project" => project1},
				{"$project" => project2},
				{"$group" => {"_id"=>"$parent_page_id","children"=>{"$push"=>"$$ROOT"}}}
			]).inject({}) do |r, s|
				r.merge!({s['_id'] => s['children']})
			end
		end
		@need_process_ip = @site.need_process_ip
		@has_privileged_page = @site.has_privileged_page
		@process_ip_later = false
		if @need_process_ip
			@process_ip_later = OrbitHelper.current_user.nil? && @site.enable_cache unless @no_cache_for_this_request
			unless @process_ip_later
				@need_process_ip = @site.check_ip_is_privileged?((OrbitHelper.request.remote_ip rescue ""))
			end
		end
		@items = create_json(root_page)
		if @custom_menu
			menu_file = File.open(@custom_menu)
		else
			menu_file = File.open(File.join(Rails.root, 'app', 'templates', "#{@key}", "/home/menu.html.erb"))
		end
		doc = Nokogiri::HTML(menu_file, nil, "UTF-8")
		menu_file.close
		temp = []
		@menus = []
		@menus_items = []
		temp << doc.css("*[data-menu-level='0']")
		temp << doc.css("*[data-menu-level='1']")
		temp << doc.css("*[data-menu-level='2']")
		@extra_script = doc.css("script").to_s
		temp[0] = temp[0].to_s.gsub(temp[1].to_s,"{{level}}")
		temp[1] = temp[1].to_s.gsub(temp[2].to_s,"{{level}}")
		temp[2] = temp[2].to_s
		temp.each_with_index do |menu,i|
			t = Nokogiri::HTML(menu, nil, "UTF-8")
			a = t.css("*[data-menu-link='true']")
			a[0]["href"] = "href_here"
			a[0]["target"] = "target_here"
			li = t.css("*[data-menu-level='#{i}'] > *")
			@menus_items << li.to_html
			ul = t.css("*[data-menu-level='#{i}']")
			ul[0].inner_html = "{{here}}"
			@menus << ul[0].to_html
		end
		current_path = request.original_fullpath
		def create_menu(level,root_id)
			html = ""
			Array(@items[root_id]).each do |item|
				next if  @menus_items[level].nil?
				li = @menus_items[level].gsub("href_here",(item["url"] || ""))
				li = li.gsub("{{link_name}}",(item["name"] || ""))
				li = li.gsub("target_here",(item["target"] || ""))
				li = (current_path == item['url'] rescue @url == item['url']) ? li.gsub("{{active}}","active") : li.gsub("{{active}}","")
				if @items[item['_id']]
					li = li.gsub("{{level}}",create_menu(level + 1,item['_id']))
				else
					li = li.gsub("{{level}}","")
				end
				html = html + li
			end
			html = @menus[level].to_s.gsub("{{here}}",html)
			html = html.to_s.gsub("{{class_level}}",level.to_s)
			html += @extra_script
			html
		end
		def create_menu_process_ip_later(level,root_id)
			html = ""
			Array(@items[root_id]).each do |item|
				next if  @menus_items[level].nil?
				li = @menus_items[level]
				if item['is_ip']
					li = li.sub('  #{t(:edit)}"
			else
				html = url_to_edit.blank? ? html.gsub("{{link_to_edit}}","") : html.gsub("{{link_to_edit}}"," #{t(:edit)} ")
			end
			return html
		end
		def get_list_data(list_data, i)
			if i.is_i?
				[list_data[eval(i)]]
			else
				list_data[eval(i)]
			end
		end
		def parsing_repeats_again(elements,d,level)
			newhtml = []
			oldhtml = []
			elements.each do |el|
				html_to_render = ""
				data_name = el.attr("data-list")
				data_no_edit = el.attr("data-no-edit") == 'true'
				if data_no_edit
					# el.remove_attribute("data-no-edit")
				end
				wrap_elements = el.css("*[data-list][data-level='#{level}']")
				tmp_data = d[data_name]
				if tmp_data
					data_range = el.attr("data-range")
					data_reverse = (el.attr("data-reverse") == 'true')
					if data_range
						# el.remove_attribute("data-range")
						if data_range.include?(",")
							data_range = data_range.split(",")
							tmp_data = data_range.flat_map{|i| get_list_data(tmp_data,i)}.compact
						else
							tmp_data = get_list_data(tmp_data,data_range).compact
						end
					end
					if data_reverse
						tmp_data = tmp_data.reverse
					end
					tmp_data.each_with_index do |item,i|
						element = el.inner_html
						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])
							end
						end
						item.each do |key,value|
							if !value.kind_of?(Array)
								value = value.nil? ? "" : value
								element = element.gsub(/(%7B%7B|{{)#{::Regexp.escape(key)}(%7D%7D|}})/,value.to_s.html_safe)
								element = render_link_to_edit(element, value) if key.eql?("url_to_edit") && !data_no_edit
							end
						end
						html_to_render = html_to_render + element
					end
					temp = el.to_s
					oldhtml << temp
					temp = temp.gsub(el.inner_html, html_to_render)
					newhtml << temp
				end
			end
			[oldhtml,newhtml]
		end
		if params[:target_action] == "index"
			page = Page.where(:page_id=>params[:page_id]).first
			@plugins = OrbitApp::Plugin::Registration.all
			@plugins = @plugins.map{|plugin| plugin.module_app_name.underscore rescue nil}.compact
			override_data = {}
			if @plugins.include? page.module
				plugin = OrbitApp::Plugin::Registration.find_by_module_app_name(page.module.classify) || OrbitApp::Plugin::Registration.find_by_module_app_name(page.module)
				override_data = {'widget-title'=>plugin.name}
			end
			filename = overridehtml.nil? ? File.basename(params[:layout_type]) : overridehtml
			module_name = File.basename(params[:target_controller]).singularize
			f = File.join(Rails.root, 'app', 'templates', "#{@key}", 'modules', module_name, "#{filename}.html.erb")
			if !File.exist?(f)
				f = File.join(Rails.root, 'app', 'templates', "#{@key}", 'modules', module_name, "index.html.erb")
				if !File.exist?(f)
					return "Maybe the administrator has changed the theme, please select the index page design again from the page settings. ".html_safe
				end
			end
			f = File.join("#{@key}", 'modules', module_name, "#{filename}.html.erb")
			begin
				@ac = @ac || ActionController::Base.new()
				@ac.prepend_view_path "app/templates"
				doc = Nokogiri::HTML.parse(@ac.render_to_string(:file=>f, :formats => [:html]))
			rescue => e
				doc = Nokogiri::HTML.parse(e.to_s)
				write_debug_file(e,params[:target_controller],params[:target_action])
			end
			# file =  File.open(f)
			# doc = Nokogiri::HTML(file, nil, "UTF-8")
			# file.close
			data = action_data
			if !data.nil?
				OrbitHelper.get_page_controller.redirect_to data['redirect_to'] and return if data['redirect_to']
				data["extras"] = data["extras"] || {}
				data["extras"] = data["extras"].merge(override_data)
				wrap_elements = doc.css("*[data-list][data-level='0']")
				htmls = parsing_repeats_again(wrap_elements,data,1)
				html = doc.to_html
				htmls[0].each_with_index do |h,i|
					html = html.gsub(h,htmls[1][i])
				end
				extras = data["extras"] || {}
				unless extras["page-title"]
					if params[:current_page_id]
						extras["page-title"] = Page.find(params[:current_page_id]).name rescue ""
					else
						extras["page-title"] = Page.find_by(:page_id => params[:page_id]).name rescue ""
					end
					if extras["page-title"].blank?
						extras["page-title"] = (I18n.t("module_name.#{OrbitHelper.this_module_app.key}") rescue "")
						if extras["page-title"].class != String || extras["page-title"].include?("translation missing")
							extras["page-title"] = ""
						end
					end
				end
				extras.each do |key,value|
					value = value.nil? ? "" : value
					html = html.gsub(/(%7B%7B|{{)#{::Regexp.escape(key)}(%7D%7D|}})/,value.to_s.html_safe)
				end
				total_pages = data['total_pages'].to_i rescue 1
				if total_pages > 1
					html = html.gsub("{{pagination_goes_here}}",create_pagination(total_pages))
				else
					html = html.gsub("{{pagination_goes_here}}","");
				end
				html.html_safe
			else
				return "No content to show. ".html_safe
			end
		else
			filename = overridehtml.nil? ? File.basename(params[:target_action]) : overridehtml
			module_name = File.basename(params[:target_controller]).singularize
			f = File.join(Rails.root, 'app', 'templates', "#{@key}", 'modules', module_name, "#{filename}.html.erb")
			if File.exist?(f)
				file =  File.open(f)
				doc = Nokogiri::HTML(file, nil, "UTF-8")
				file.close
				data = action_data
				if data.nil?
					return " No content to show.  ".html_safe
				end
				if data.blank? || data.empty?
					file =  File.open("#{Rails.root}/app/views/errors/404.html")
					doc = Nokogiri::HTML(file, nil, "UTF-8")
					file.close
					doc.to_html.html_safe
				else
					OrbitHelper.get_page_controller.redirect_to data['redirect_to'] and return if data['redirect_to']
					unless data['impressionist'].blank?
						Thread.new do
							impression = data['impressionist'].impressions.create
							impression.user_id = request.session['user_id']
							impression.controller_name = params[:target_controller]
							impression.action_name = params[:target_action]
							impression.ip_address = request.remote_ip
							#session id class: string in ruby 2.1, Rack::Session::SessionId in ruby 2.7. Rack::Session::SessionId cannot stored into db.
							impression.session_hash = request.session.id.to_s
							impression.request_hash = @impressionist_hash
							impression.referrer = request.referrer
							impression.save
						end
						data['impressionist'].inc(view_count: 1)
						data["data"]["view_count"] = (data["impressionist"].view_count+(@site.view_count_start rescue 0)) if data["data"].present?
					end
					wrap_elements = doc.css("*[data-list][data-level='0']")
					if wrap_elements.count == 0
						wrap_element_html = doc.to_html
						el = wrap_element_html
						data.each do |key,value|
							next if key.eql? 'impressionist'
							value = value.nil? ? "" : value
							el = el.gsub(/(%7B%7B|{{)#{::Regexp.escape(key)}(%7D%7D|}})/,value.to_s.html_safe)
						end
						el.html_safe
					else
						keys = data.keys
						not_array_key = nil
						data.keys.each do |key|
							not_array_key = key if data["#{key}"].kind_of?(Hash)
						end
						htmls = parsing_repeats_again(wrap_elements,data,1)
						html = doc.to_html
						htmls[0].each_with_index do |h,i|
							html = html.gsub(h,htmls[1][i])
						end
						extras = data["#{not_array_key}"] || {}
						extras.each do |key,value|
							next if key.eql? 'impressionist'
							value = value.nil? ? "" : value
							html = html.gsub(/(%7B%7B|{{)#{::Regexp.escape(key)}(%7D%7D|}})/,value.to_s)
						end
						html = render_link_to_edit(html, data["url_to_edit"]) if !data["url_to_edit"].nil?
						total_pages = data['total_pages'].to_i rescue 1
						if total_pages > 1
							html = html.gsub("{{pagination_goes_here}}",create_pagination(total_pages))
						else
							html = html.gsub("{{pagination_goes_here}}","");
						end
						html.html_safe
					end
				end
			else
				return "There is a problem with the design. We will try to fix it as soon as possible. Sorry for the inconvenience!! :( ".html_safe
			end
		end
	end
	def action_data(overrideaction=nil, extra_instance_variables=nil)
		overrideaction = overrideaction.nil? ? params[:target_action].to_s : overrideaction
		target_controller = params[:target_controller]
		action_data_variable_name = "@#{target_controller}_#{overrideaction}_action_data"
		tmp_value = instance_variable_get(action_data_variable_name)
		if tmp_value
			return tmp_value
		end
		controller_class = "#{target_controller.capitalize}_controller".classify.constantize
		@index_controller = controller = controller_class.new
		if extra_instance_variables
			extra_instance_variables.each do |k, v|
				controller.instance_variable_set(k, v)
			end
		end
		begin
			can_send_methods = ["index", "show"]
			if controller_class.const_defined?(:FrontendMethods)
				can_send_methods += controller_class.const_get(:FrontendMethods)
			end
			if can_send_methods.include?(overrideaction)
				data = controller.send("#{overrideaction}")# rescue nil
			else
				data = nil
			end
		rescue Mongoid::Errors::DocumentNotFound => e
			data = nil
		rescue Exception => e
			puts [e,e.backtrace]
			write_debug_file(e,target_controller,overrideaction) if Site::DEBUG
		end
		instance_variable_set(action_data_variable_name, data)
	end
	def active_for_controllers(*controller_names)
		(controller_names.include?(controller.controller_name) || controller_names.include?(request.fullpath)) ? 'active' : nil
	end
	def visible_for_controllers(*controller_names)
		(controller_names.include?(controller.controller_name) || controller_names.include?(request.fullpath)) ? '' : 'hide'
	end
	def active_for_action(controller_name, action_name)
		((controller.controller_name.eql?(controller_name) || request.fullpath.eql?(controller_name)) && controller.action_name.eql?(action_name)) ? 'active' : nil
	end
	def link_back(custom_class=nil, params="")
		case custom_class
		when nil
			link_to t('back'), get_go_back + params, :class => 'nav'
		else
			link_to t('back'), get_go_back + params, :class => custom_class
		end
	end
	def switch_language(loc)
		url = request.original_fullpath
		locale = url.include?("zh_cn") ? :zh_cn : I18n.locale
		url = url.gsub("/#{locale.to_s}/","/#{loc.to_s}/")
		url = url.gsub("locale=#{locale.to_s}","locale=#{loc.to_s}") if url == request.original_fullpath
		url = url + "#{url.include?("?") ? "&" : "?"}locale=#{loc.to_s}" if url == request.original_fullpath and (!url.include?('/'+locale.to_s) or !url.include?(locale.to_s+'='))
		url
	end
	# Clean the link back
	def get_go_back
		begin
			if request.url.include?('locale=')
			session[:last_page]
		else
			session[:last_page] = remove_locale(request.referer)
		end
		rescue
			"/#{params[:controller]}"
		end
	end
	def show_avatar(member)
		image_tag(member.avatar.thumb.url)
	end
	def render_sitemap
		data = action_data(nil, {:@no_cache_for_this_request=>@no_cache_for_this_request})
		@items = data[:items]
		root_page = data[:root_page]
		def node(level,root_id)
			class_name = nil
			case level
			when 0
				class_name = "sitemap-list level-1"
			when 1
				class_name = "sitemap-list level-2"
			when 2
				class_name = "sitemap-list level-3"
			end
			html = ""
			Array(@items[root_id]).each do |item|
				target = item["target"]
				url = item["url"]
				key = item['name']
				if @items[item['_id']]
					html = html + "- #{key}"
					html = html + node(level + 1,item['_id'])
					html = html + "
 "
				else
					html = html + "- #{key}
 "
				end
			end
			html = html + " "
			html
		end
		html = node(0,root_page.id)
		html.html_safe
	end
	def show_attribute_value(value)
		if value.kind_of? Hash
			result = []
			value.each{|t| result.push(t.last)}
			result.join ","
		else
			value
		end
	end
	def create_pagination(total_pages)
		file = File.join(Rails.root, 'app', 'templates', "#{@key}", 'home', "pagination.html.erb")
		html = ""
		if File.exist?(file)
			file =  File.open(file)
			doc = Nokogiri::HTML(file, nil, "UTF-8")
			file.close
			querystring = request.GET rescue {}
			querystring.delete("page_no")
			paginationobj = doc.css("*[data-pagination='true']").first
			in_html = first = last = nextpage = prevpage = paginationobj.inner_html
			f_html = ""
			current_page_number = OrbitHelper.page_number
			if current_page_number > 1
				first = first.gsub("%7B%7Bpagination_link%7D%7D","?page_no=1{querystring.to_query}")
				first = first.gsub("{{page_number}}",t(:pagination_first))
				first = first.gsub("{{pagination_active}}","")
				f_html = f_html +  first
			end
			start_number = current_page_number - 2
			end_number = current_page_number + 2
			if end_number > total_pages
				end_number = total_pages
				start_number = total_pages - 4
			end
			if start_number < 1
				start_number = 1
				end_number = 5
			end
			end_number = end_number > total_pages ? total_pages : end_number
			(start_number..end_number).each do |i|
				h = in_html
				h = h.gsub("%7B%7Bpagination_link%7D%7D","?page_no=#{i.to_s}{querystring.to_query}")
				h = h.gsub("{{page_number}}",i.to_s)
				h = h.gsub("{{pagination_active}}",(i == current_page_number ? "active" : ""))
				f_html = f_html + h
			end
			if current_page_number > 1
				prevpage = prevpage.gsub("%7B%7Bpagination_link%7D%7D","?page_no=#{current_page_number - 1}{querystring.to_query}")
				prevpage = prevpage.gsub("{{page_number}}",(I18n.locale == :zh_tw) ? "上一頁" : "Prevpage")
				prevpage = prevpage.gsub("{{pagination_active}}","")
				f_html = f_html +  prevpage
			end
			if current_page_number < total_pages
				nextpage = nextpage.gsub("%7B%7Bpagination_link%7D%7D","?page_no=#{current_page_number + 1}{querystring.to_query}")
				nextpage = nextpage.gsub("{{page_number}}",(I18n.locale == :zh_tw) ? "下一頁" : "Nextpage")
				nextpage = nextpage.gsub("{{pagination_active}}","")
				f_html = f_html +  nextpage
				last = last.gsub("%7B%7Bpagination_link%7D%7D","?page_no=#{total_pages}{querystring.to_query}")
				last = last.gsub("{{page_number}}",t(:pagination_last))
				last = last.gsub("{{pagination_active}}","")
				f_html = f_html +  last
			end
			paginationobj.inner_html = f_html
			html = paginationobj.to_s
		end
		html
	end
	def get_target(link)
		target = "_blank"
		if !link.nil? && link.starts_with?("http")
			link = link.split("?").first
			temp_url = URI.parse(URI.encode(link))
			if temp_url.host.nil?
				target = "_self"
			end
		elsif !link.nil? && !link.starts_with?("http")
			target = "_self"
		end
		target
	end
	def write_debug_file(e,controller_name,action_name)
		controller_name = File.basename(controller_name)
		action_name = File.basename(action_name)
		url_dir_name = request.fullpath.split("?")[0]
		url_dir_name = URI.decode(url_dir_name)
		url_dir_name = (url_dir_name  == "/" ? "home" : url_dir_name.sub("/","").gsub("/","_").gsub("-","_").gsub(" ","_"))
		directory_name = "tmp/debug/#{url_dir_name}"
		FileUtils.mkdir_p(directory_name) unless File.exist?(directory_name)
		fn = "#{directory_name}/#{controller_name}_#{action_name}.html"
		error_trace_spans = ""
		e.backtrace.each do |bt|
			error_trace_spans = error_trace_spans + "#{bt} "
		end
		con = "#{controller_name.capitalize}_controller".classify.constantize
		File.open(fn, "w"){ |file|
			file.puts "
						
							
						
							Debug result
						
						
							Error Message
							
								 #{e.message}
							
							Request Details
							
								Url : #{URI.decode(request.url)} 
								Controller : #{con.to_s}  
								Action : #{action_name.capitalize} 
							 
							Error Trace
							
								#{error_trace_spans}
							 
							Params
							
								#{OrbitHelper.params}
							 
						
						"
		}
	end
end  |