patch_file/updatefiles/application_helper.rb

648 lines
23 KiB
Ruby

# encoding: utf-8
require "json"
module ApplicationHelper
def render_widget(widget)
file = File.join(Rails.root, "app", "templates", "#{@key}", "modules/#{widget}")
render :partial => file
end
def render_partial(partial)
file = File.join(Rails.root, "app", "templates", "#{@key}", "partial/_#{partial}.html.erb")
render :file => file
end
def link_to_show(module_name)
"/module/#{module_name}/show"
end
def render_header
site = current_site
header_file = File.join(Rails.root, "app", "templates", "#{@key}", "/home/header.html.erb")
header_file_html = render :file => header_file
header = Nokogiri::HTML(header_file_html, nil, "UTF-8")
site_logo = header.css("img[src='{{logo_url}}']")[0]
if !site_logo.nil?
site_logo.remove if site.site_logo.url.nil?
end
sub_menu_html = site.sub_menu
html = header.to_s
t = site.title rescue ""
html = html.gsub("{{site_name}}",(site.display_title_in_frontend ? t : ""))
html = html.gsub("%7B%7Blogo_url%7D%7D",((site.site_logo.url.nil? ? "/assets/default-site-logo.png" : site.site_logo.url) rescue "/assets/default-site-logo.pngs"))
html = html.gsub("%7B%7Blogo_url_1%7D%7D",((site.site_logo_1.url.nil? ? "/assets/default-site-logo.png" : site.site_logo_1.url) rescue "/assets/default-site-logo.pngs"))
html = html.gsub("%7B%7Bhome_link%7D%7D",((site.home_link.strip.empty? ? "/" : site.home_link) rescue "/"))
html = html.gsub("%7B%7Bhome_link_1%7D%7D",((site.home_link_1.strip.empty? ? "/" : site.home_link_1) rescue "/"))
html = html.gsub("{{site_title}}",((site.site_title[I18n.locale.to_s].strip.empty? ? "home_page" : site.site_title[I18n.locale.to_s]) rescue "home_page"))
html = html.gsub("{{site_title_1}}",((site.site_title_1[I18n.locale.to_s].strip.empty? ? "home_page" : site.site_title_1[I18n.locale.to_s]) rescue "home_page"))
if site.sitemap_menu_in_header
sitemap = Page.find_by_key(:sitemap).name rescue "Sitemap"
sub_menu_html = sub_menu_html + "<a href='/#{I18n.locale.to_s}#{site.site_map_link}'>#{sitemap}</a>"
end
sub_menu_html = sub_menu_html.nil? ? "" : sub_menu_html
html = html.gsub("{{header-data}}",sub_menu_html)
html.html_safe
end
def render_site_title
site = current_site
title = site.title rescue ""
if site.title_always_on
if !params[:slug].nil?
temp_title = params[:slug].sub("-#{params[:uid]}","")
temp_title = temp_title.gsub("-"," ")
title = "#{temp_title} | #{title}"
elsif params[:target_action] == "index"
temp_title = Page.find_by(:page_id => params[:page_id]).name
title = "#{temp_title} | #{title}"
end
end
title
end
def render_every_page_sharer
site = current_site
html = "<div class='box-social-share no-print'>"
site.every_page_sharer.each do |share|
case share
when "facebook"
html = html + "<div class='fb-share-button' data-type='button'></div>"
when "twitter"
html = html + "<div class='tw-share-button'><a href='https://twitter.com/share' class='twitter-share-button' data-dnt='true' data-count='none'>Tweet</a></div>"
when "google"
html = html + "<div class='g-plus' data-action='share' data-annotation='bubble' ></div>"
when "printer"
html = html + "<div class='print-button'><a href='#' title='print' onclick='window.print();return false;'><i class='fa fa-print'></i><span class='print-txt'>#{t(:print_this_page)}</span></div>"
end
end
html = html + "</div>"
html.html_safe
end
def render_google_analytics
html = current_site.google_analytics rescue ""
metas = current_site.meta_tags.split("\r\n") rescue []
metas.each do |meta|
m = meta.split(" ::: ")
html = html + "<meta name='#{m.first}' content='#{m.last}'>"
end
html.html_safe rescue ""
end
def render_footer
site = current_site
footer_file = File.join('../templates', "#{@key}", "/home/footer.html.erb")
footer_file_html = render :file => footer_file
footer = Nokogiri::HTML(footer_file_html, nil, "UTF-8")
html = footer.to_s
site_footer = site.footer
if site.enable_terms_of_use
site_footer = site_footer + "<a href='/#{I18n.locale.to_s}#{site.terms_of_use_link}'>Terms of use</a>"
end
site_footer = site_footer.nil? ? "" : site_footer
html = html.gsub("{{footer-data}}",site_footer)
counter = Page.root.view_count.to_s rescue ""
counter = t(:visitors_count) + " : " + counter
html = html.gsub("{{site-counter}}",counter)
if site.enable_last_update
updated_at = get_last_updated.first.updated_at.to_s rescue ""
updated_at = t(:last_updated_at) + " : <span class='last-updated-date' date-format='%Y-%m-%d %H:%M'>" + updated_at + "</span>" if updated_at != ""
html = html.gsub("{{last-updated}}",updated_at)
else
html = html.gsub("{{last-updated}}","")
end
html.html_safe
end
def get_last_updated
apps = ['bulletin', 'page_context', 'web_link']
a = {}
apps.each do |module_app|
module_app_class = module_app.classify.constantize rescue nil
if !module_app_class.nil?
objects = module_app_class.order_by([:updated_at, :desc]).limit(1)
objects.each do |object|
a.merge!(object => object.updated_at) unless (object.archived rescue nil)
end
end
end
sorted_objects = a.sort {|a,b| b[1]<=>a[1]}
return sorted_objects.first
end
def render_social_share
site = current_site
share_file = File.join('../templates', "#{@key}", "/home/socialshare.html.erb")
share_file_html = render :file => share_file
sharer = Nokogiri::HTML(share_file_html, nil, "UTF-8")
html = sharer.to_s
site_sharer = site.social_share
site_sharer = site_sharer.nil? ? "" : site_sharer
html = html.gsub("{{social-share-data}}",site_sharer)
html.html_safe
end
def render_orbit_bar
if is_mobile_layout_active
orbit_bar_file = File.join('../views', "orbit_bar", 'index_mobile.html.erb')
else
orbit_bar_file = File.join('../views', "orbit_bar", 'index.html.erb')
end
orbit_bar_file_html = render :file => orbit_bar_file
orbit_bar_file_html.html_safe
end
def render_menu
# 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)
if $mobile.blank?
@pages = Page.root.sorted_published_child_pages
else
@pages = Page.root.sorted_published_child_pages_for_mobile
end
def create_json(pages)
item = {}
pages.each do |page|
next if !page.user_can_access?(current_user)
if page.child_page.size > 0
if page.page_type == "page"
if $mobile.blank?
item["#{page.page_id}"] = {"name" => page.name, "url"=> "/#{locale.to_s}" + page.url, "children"=>create_json(page.sorted_published_child_pages), "target" => "_self"}
else
item["#{page.page_id}"] = {"name" => page.name, "url"=> "/#{locale.to_s}" + page.url, "children"=>create_json(page.sorted_published_child_pages_for_mobile), "target" => "_self"}
end
elsif page.page_type == "link"
target = get_target(page.external_url)
if $mobile.blank?
item["#{page.page_id}"] = {"name" => page.name, "url"=> page.external_url, "children"=>create_json(page.sorted_published_child_pages), "target" => target}
else
item["#{page.page_id}"] = {"name" => page.name, "url"=> page.external_url, "children"=>create_json(page.sorted_published_child_pages_for_mobile), "target" => target}
end
end
else
if page.page_type == "page"
item["#{page.page_id}"] = {"name" => page.name, "url"=> "/#{locale.to_s}" + page.url, "target" => "_self"}
elsif page.page_type == "link"
item["#{page.page_id}"] = {"name" => page.name, "url"=> page.external_url, "target" => get_target(page.external_url)}
end
end
end
item
end
@items = create_json(@pages)
menu_file = File.open(File.join(Rails.root, 'app', 'templates', "#{@key}", "/home/menu.html.erb"))
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']")
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
def create_menu(items,level)
html = ""
items.each do |key,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 = request.original_fullpath == item['url'] ? li.gsub("{{active}}","active") : li.gsub("{{active}}","")
if item["children"] && !item["children"].empty?
li = li.gsub("{{level}}",create_menu(item["children"],level + 1))
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
end
h = create_menu(@items,0)
h.html_safe
# end
# menu_html
end
def render_view(overridehtml=nil)
def render_link_to_edit(html, url_to_edit)
if html.scan("{{link_to_edit}}").length == 0
html = url_to_edit.blank? ? html : html + "<p class='admin-edit text-right'><a class='btn btn-primary' href='#{url_to_edit}'><i class='icon-edit'></i> #{t(:edit)}</a></p>"
else
html = url_to_edit.blank? ? html.gsub("{{link_to_edit}}","") : html.gsub("{{link_to_edit}}","<p class='admin-edit text-right'><a class='btn btn-primary' href='#{url_to_edit}'><i class='icon-edit'></i> #{t(:edit)}</a></p>")
end
return html
end
def parsing_repeats_again(elements,d,level)
newhtml = []
oldhtml = []
elements.each do |el|
html_to_render = ""
data_name = el.attr("data-list")
wrap_elements = el.css("*[data-list][data-level='#{level}']")
if d[data_name]
d[data_name].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("{{#{key}}}",value.to_s.html_safe)
element = element.gsub("%7B%7B#{key}%7D%7D",value.to_s.html_safe)
element = render_link_to_edit(element, value) if key.eql?("url_to_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"
filename = overridehtml.nil? ? params[:layout_type] : overridehtml
f = File.join(Rails.root, 'app', 'templates', "#{@key}", 'modules', params[:target_controller].singularize, "#{filename}.html.erb")
if !File.exists?f
f = File.join(Rails.root, 'app', 'templates', "#{@key}", 'modules', params[:target_controller].singularize, "index.html.erb")
if !File.exists?f
return "<div class='well'>Maybe the administrator has changed the theme, please select the index page design again from the page settings.</div>".html_safe
end
end
file = File.open(f)
doc = Nokogiri::HTML(file, nil, "UTF-8")
file.close
controller = "#{params[:target_controller].capitalize}_controller".classify.constantize.new
begin
data = controller.send("#{params[:target_action]}")# rescue nil
rescue Exception => e
write_debug_file(e,params[:target_controller],params[:target_action]) if Site::DEBUG
end
if !data.nil?
wrap_elements = doc.css("*[data-list][data-level='0']")
htmls = parsing_repeats_again(wrap_elements,data,1)
html = doc.to_s
htmls[0].each_with_index do |h,i|
html = html.gsub(h,htmls[1][i])
end
extras = data["extras"] || {}
extras["page-title"] = Page.find_by(:page_id => params[:page_id]).name rescue "" if !extras["page-title"]
extras.each do |key,value|
value = value.nil? ? "" : value
html = html.gsub("{{#{key}}}",value.to_s.html_safe)
html = html.gsub("%7B%7B#{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 "<div class='well'>No content to show.</div>".html_safe
end
else
filename = overridehtml.nil? ? params[:target_action] : overridehtml
f = File.join(Rails.root, 'app', 'templates', "#{@key}", 'modules', params[:target_controller].singularize, "#{filename}.html.erb")
if File.exists?f
file = File.open(f)
doc = Nokogiri::HTML(file, nil, "UTF-8")
file.close
controller = "#{params[:target_controller].capitalize}_controller".classify.constantize.new
begin
data = controller.send("#{params[:target_action]}")# rescue nil
rescue Exception => e
write_debug_file(e,params[:target_controller],params[:target_action]) if Site::DEBUG
end
if data.nil?
return "<div class='well'> No content to show. </div>".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
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
impression.session_hash = request.session.id
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 if data["data"].present?
end
wrap_elements = doc.css("*[data-list][data-level='0']")
if wrap_elements.count == 0
wrap_element_html = doc.to_s
el = wrap_element_html
data.each do |key,value|
next if key.eql? 'impressionist'
value = value.nil? ? "" : value
el = el.gsub("{{#{key}}}",value.to_s.html_safe)
el = el.gsub("%7B%7B#{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_s
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("{{#{key}}}",value.to_s)
html = html.gsub("%7B%7B#{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 "<div class='well'>There is a problem with the design. We will try to fix it as soon as possible. Sorry for the inconvenience!! :(</div>".html_safe
end
end
end
def action_data(overrideaction=nil)
overrideaction = overrideaction.nil? ? params[:target_action] : overrideaction
controller = "#{params[:target_controller].capitalize}_controller".classify.constantize.new
begin
data = controller.send("#{overrideaction}")# rescue nil
rescue Exception => e
write_debug_file(e,params[:target_controller],overrideaction) if Site::DEBUG
end
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(user)
image_tag(user.avatar.thumb.url)
end
def render_sitemap
items = action_data
def node(items, level)
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 = "<ul class='#{class_name}'>"
items.each do |key,item|
if item["children"] && !item["children"].empty?
url = item["url"]
target = item["target"]
html = html + "<li><a href='#{url}' target='#{target}'>#{key}</a>"
html = html + node(item["children"],level + 1)
html = html + "</li>"
else
target = item["target"]
url = item["url"]
html = html + "<li><a href='#{url}' target='#{target}'>#{key}</a></li>"
end
end
html = html + "</ul>"
html
end
html = node(items,0)
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.exists?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(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)
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.exists?(directory_name)
fn = "#{directory_name}/#{controller_name}_#{action_name}.html"
error_trace_spans = ""
e.backtrace.each do |bt|
error_trace_spans = error_trace_spans + "<span>#{bt}</span><br />"
end
con = "#{controller_name.capitalize}_controller".classify.constantize
File.open(fn, "w"){ |file|
file.puts "<html>
<head>
<meta content='text/html; charset=UTF-8' http-equiv='Content-Type'>
<meta charset=UTF-8'>
<title>Debug result</title>
</head>
<body>
<h3>Error Message</h3>
<div class='error-message'>
<h2><i>#{e.message}</i></h2>
</div>
<h3>Request Details</h3>
<div class='request-details'>
<span>Url : <b>#{URI.decode(request.url)}</b></span><br />
<span>Controller : <b>#{con.to_s}</b> </span><br />
<span>Action : <b>#{action_name.capitalize}</b> </span>
</div>
<h3>Error Trace</h3>
<div class='error-trace'>
#{error_trace_spans}
</div>
<h3>Params</h3>
<div class='params'>
#{OrbitHelper.params}
</div>
</body>
</html>"
}
end
end