patch_file/updatefiles/application_helper.rb

1098 lines
40 KiB
Ruby

# encoding: utf-8
require "json"
module ApplicationHelper
CurrentSite = Site.first #(OrbitHelper::SharedHash['current_site']['site'] rescue Site.first)
def self.CurrentSite
(OrbitHelper::SharedHash['current_site']['site'] rescue Site.first)
end
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, :formats => [:html])
end
def link_to_show(module_name)
"/module/#{module_name}/show"
end
def self.render_header_for_extend(data_only=false)
$making_cache = data_only
if @site.nil?
@site = CurrentSite
@orbit_bar_not_display = @site.orbit_bar_not_display
end
@key = @site.template
if @custom_header
header_file = @custom_header
else
header_file = File.join(Rails.root, "app", "templates", "#{@key}", "/home/header.html.erb")
end
view = ActionView::Base.new(Orbit::Application.config.paths["app/views"].first)
view.extend ApplicationHelper
view.instance_variable_set(:@site,@site)
view.instance_eval{def current_site; @site; end}
view.instance_variable_set(:@key,@key)
view.instance_variable_set(:@url, (OrbitHelper.params[:url] rescue "/") )
header_file_html = view.render(:file => header_file, :locals =>{:current_user => OrbitHelper.current_user}) rescue nil
if header_file_html.nil? && data_only
$making_cache = false
raise "#{header_file} not found"
end
header = Nokogiri::HTML(header_file_html, nil, "UTF-8")
site_logo = header.css("a[title='{{site_title}}']")[0]
if !site_logo.nil?
if @site.site_logo.url.nil?
if @site[:title_always_on].blank? #blank include false
site_logo.remove
site_logo = nil
else
site_logo.css("img").remove
end
end
end
site_logo_1 = header.css("a[title='{{site_title_1}}']")[0]
if !site_logo_1.nil?
if @site.site_logo_1.url.nil?
site_logo_1.remove
site_logo_1 = nil
end
end
t = @site.title rescue ""
site_logo_alt = ""
if t.blank?
site_logo_alt = "Site Logo"
else
site_logo_alt = t + (I18n.locale.to_s == "zh_tw" ? "的Logo" : " Logo")
end
already_fix_h2 = false
h2_element = nil
default_site_title = @site.title
h2_tag = "h2"
if @orbit_bar_not_display
h2_tag = 'h1'
end
if site_logo_1
site_logo_1.css("img").attr("alt", site_logo_alt)
if (site_logo_1.parent.name.match(/h1/i) rescue false)
h2_element = site_logo.parent
elsif site_logo_1.css('h1').length != 0
h2_element = site_logo_1.css('h1')[0]
elsif site_logo_1.css('h2').length == 0
site_logo_1.inner_html = "<#{h2_tag} class=\"default_site_h1\">" + site_logo_1.inner_html + "<span style=\"display: none;\">#{default_site_title}</span></#{h2_tag}>"
end
already_fix_h2 = true
end
if site_logo
site_logo.css("img").attr("alt", site_logo_alt)
unless already_fix_h2
if (site_logo.parent.name.match(/h1/i) rescue false)
h2_element = site_logo.parent
elsif site_logo.css('h1').length != 0
h2_element = site_logo.css('h1')[0]
elsif site_logo.css('h2').length == 0
site_logo.inner_html = "<h2 class=\"default_site_h1\">" + site_logo.inner_html + "<span style=\"display: none;\">#{default_site_title}</span></h2>"
end
already_fix_h2 = true
end
end
if h2_element
h2_element.name = h2_tag
h2_element['class'] = "default_site_h1"
end
html = header.to_s
html = html.gsub("{{site_name}}",(@site.display_title_in_frontend ? t : (already_fix_h2 ? "" : "<span style=\"display: none;\">#{t}</span>")))
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? ? default_site_title : @site.site_title[I18n.locale.to_s]) rescue default_site_title))
html = html.gsub("{{site_title_1}}",((@site.site_title_1[I18n.locale.to_s].strip.empty? ? default_site_title : @site.site_title_1[I18n.locale.to_s]) rescue default_site_title))
if data_only
$making_cache = false
return html
end
if @custom_header_data
html = html.gsub("{{header-data}}",@custom_header_data)
else
sub_menu_html = @site.sub_menu
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)
end
html.html_safe + view.instance_eval{render_social_share + render_popup_window(@page)}
end
def render_header
$making_cache = false
site = @site
cache_data = nil
if @custom_header
header_file = @custom_header
else
header_file = File.join(Rails.root, "app", "templates", "#{@key}", "/home/header.html.erb")
# cache_data = (site.get_cache_header_data($mobile) rescue nil)
end
if cache_data.blank?
header_file_html = render(:file => header_file, :formats => [:html])
header = Nokogiri::HTML(header_file_html, nil, "UTF-8")
site_logo = header.css("a[title='{{site_title}}']")[0]
if !site_logo.nil?
if site.site_logo.url.nil?
if site[:title_always_on].blank? #blank include false
site_logo.remove
site_logo = nil
else
site_logo.css("img").remove
end
end
end
site_logo_1 = header.css("a[title='{{site_title_1}}']")[0]
if !site_logo_1.nil?
if site.site_logo_1.url.nil?
site_logo_1.remove
site_logo_1 = nil
end
end
t = site.title rescue ""
site_logo_alt = ""
if t.blank?
site_logo_alt = "Site Logo"
else
site_logo_alt = t + (I18n.locale.to_s == "zh_tw" ? "的Logo" : " Logo")
end
already_fix_h2 = false
h2_element = nil
default_site_title = site.title
h2_tag = "h2"
if @orbit_bar_not_display
h2_tag = 'h1'
end
if site_logo_1
site_logo_1.css("img").attr("alt", site_logo_alt)
if (site_logo_1.parent.name.match(/h1/i) rescue false)
h2_element = site_logo.parent
elsif site_logo_1.css('h1').length != 0
h2_element = site_logo_1.css('h1')[0]
elsif site_logo_1.css('h2').length == 0
site_logo_1.inner_html = "<h2 class=\"default_site_h1\">" + site_logo_1.inner_html + "<span style=\"display: none;\">#{default_site_title}</span></h2>"
end
already_fix_h2 = true
end
if site_logo
site_logo.css("img").attr("alt", site_logo_alt)
unless already_fix_h2
if (site_logo.parent.name.match(/h1/i) rescue false)
h2_element = site_logo.parent
elsif site_logo.css('h1').length != 0
h2_element = site_logo.css('h1')[0]
elsif site_logo.css('h2').length == 0
site_logo.inner_html = "<#{h2_tag} class=\"default_site_h1\">" + site_logo.inner_html + "<span style=\"display: none;\">#{default_site_title}</span></#{h2_tag}>"
end
already_fix_h2 = true
end
end
if h2_element
h2_element.name = h2_tag
h2_element['class'] = "default_site_h1"
end
html = header.to_s
html = html.gsub("{{site_name}}",(site.display_title_in_frontend ? t : (already_fix_h2 ? "" : "<span style=\"display: none;\">#{t}</span>")))
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? ? default_site_title : site.site_title[I18n.locale.to_s]) rescue default_site_title))
html = html.gsub("{{site_title_1}}",((site.site_title_1[I18n.locale.to_s].strip.empty? ? default_site_title : site.site_title_1[I18n.locale.to_s]) rescue default_site_title))
else
html = cache_data.sub("{{render_orbit_bar}}",render_orbit_bar)
end
if @custom_header_data
html = html.sub("{{header-data}}",@custom_header_data)
else
sub_menu_html = site.sub_menu
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.sub("{{header-data}}",sub_menu_html)
end
html.html_safe + render_social_share + render_popup_window(@page)
end
def render_site_title
site = @site
title = site.title rescue ""
if site.title_always_on || site.accessibility_mode
if !params[:slug].nil?
temp_title = params[:slug].sub("-#{params[:uid]}","")
temp_title = Nokogiri::HTML(temp_title.gsub("-"," ")).text
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 = @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 "line"
line_share_text = I18n.t('site.share')
line_title = I18n.t('site.line_share_title')
line_share_url = "https://social-plugins.line.me/lineit/share"
line_share_img_src = "https://www.line-website.com/social-plugins/img/common/line_v3@3x.png"
html = html + "<a class=\"line-it-button\" title=\"#{line_title}\" href=\"#{line_share_url}?#{{url: request.base_url+request.original_fullpath.to_s.gsub(/\"|\%22|\'/,'')}.to_query}\" target=\"_blank\">
<img src=\"#{line_share_img_src}\">
<span class=\"label\">
<span class=\"lang\">
#{line_share_text}
</span>
</span>
</a>
<script style=\"display: none !important;\">
$('.line-it-button').attr('href','#{line_share_url}?url='+encodeURIComponent(document.location.href)+\"&text=\"+document.title)
</script>"
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 = @site.google_analytics rescue ""
metas = @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 = @site
footer_file = File.join(Rails.root,'app/templates', "#{@key}", "/home/footer.html.erb")
footer_file_html = render(:file => footer_file, :formats => [:html])
footer_file_html = footer_file_html.gsub("ruling-logo-icon",I18n.t(:ruling_digital))
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
if @custom_footer
html = html.gsub("{{footer-data}}",@custom_footer)
else
html = html.gsub("{{footer-data}}",site_footer)
end
#counter = Page.root.view_count.to_s rescue ""
counter = Impression.collection.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_popup_window(page=nil,editmode=false)
def render_edit_block(subpart,c)
"<div class='editmode-ps' title='#{subpart.module}'>#{c}<a href='/page_parts/edit_sub_part?site_info=1&sub_part_id=#{subpart.id.to_s}#{(!$mobile.blank? ? '&mobile_view=1' : '')}'> </a></div>"
end
def get_popup_text(page,editmode)
site = @site
if editmode || site[:render_popup_only_on_root]!=true || (site[:render_popup_only_on_root] && !page.nil? && page.url=='/')
sub_parts = site.popup_subparts rescue []
if !sub_parts.blank? #not nil or []
sub_parts.map do |subpart|
next if !subpart.link_sub_part_id.nil?
link_subpart = site.popup_subparts.where(:link_sub_part_id=>subpart.id,:locale=>I18n.locale.to_s).first
subpart = link_subpart if !link_subpart.nil?
if subpart.kind == "module_widget"
OrbitHelper.set_current_widget subpart
OrbitHelper.set_widget_data_count subpart.data_count
OrbitHelper.set_widget_module_app subpart.module
OrbitHelper.set_widget_item_url subpart
OrbitHelper.render_meta_tags []
OrbitHelper.set_widget_title subpart.title
OrbitHelper.set_widget_categories subpart.categories || ["all"]
OrbitHelper.set_widget_tags subpart.tags || ["all"]
custom_value = subpart.custom_string_field || subpart.custom_array_field || subpart.custom_data_field rescue nil
if !custom_value.nil?
OrbitHelper.set_widget_custom_value custom_value
else
OrbitHelper.set_widget_custom_value nil
end
c = render_widget_for_frontend(subpart.module,subpart.widget_method,subpart.widget_type,subpart.id.to_s)
if editmode
render_edit_block(subpart,c)
else
c
end
elsif subpart.kind == "none"
if editmode
render_edit_block(subpart,nil)
end
elsif subpart.kind == "text"
c = subpart.content
if editmode
render_edit_block(subpart,c)
else
if c.blank?
nil
else
"<div>#{c}</div>"
end
end
else
nil
end
end.compact.join("\n")
end
end
end
if page.nil?
page = @page
end
tmp = get_popup_text(page,editmode)
if editmode
tmp = (tmp||"") + "<a href='/page_parts/new?site_info=1#{(!$mobile.blank? ? '&mobile_view=1' : '')}'> </a>"
end
if !tmp.blank?
close_btn = editmode ? "" : "<a href=\"javascript:;\" class=\"close-screen-btn\" title=\"Close\">
<i class=\"fa fa-times\"></i><span style=\"display: none;\">Close</span>
</a >"
"<div class=\"black-screen-popup-window\">
<div class=\"content\">
#{tmp}
#{close_btn}
</div>
</div>
"
else
""
end.html_safe
end
def render_social_share
site = @site
site_sharer = site.social_share.to_s.gsub(/<!--((?:(?!-->).)*)-->/m,'') rescue ""
if !site_sharer.blank?
share_file = File.join(Rails.root,"app/templates/#{site.template}/home/socialshare.html.erb")
if Dir[share_file].length>0
share_file_html = render(:file => share_file, :formats => [:html])
html = share_file_html.encode("UTF-8", "UTF-8", invalid: :replace, replace: "")
html = html.gsub("{{social-share-data}}",site_sharer)
html.html_safe
else
pos = site[:social_share_position]==1 ? "left" : "right"
trans_hide_social_share_buttons = I18n.t('hide_social_share_buttons')
trans_show_social_share_buttons = I18n.t('show_social_share_buttons')
hide_sharer_button = "<button class=\"hide_sharer_button\" title=\"#{trans_hide_social_share_buttons}\" data-hide-title=\"#{trans_hide_social_share_buttons}\" data-show-title=\"#{trans_show_social_share_buttons}\"><span class=\"fa fa-angle-#{pos} hide_fa\"></span></button>"
site_sharer = site_sharer.gsub(/<table(?:(?!>).)*>(?:(?!<\/table>|<tbody>).)*<tbody(?:(?!>).)*>((?:(?!<\/table>|<tbody>).)*)<\/tbody>(?:(?!<\/table>).)*<\/table>/m) do |tbody|
tmp = $1
tmp = tmp.scan(/<td((?:(?!>).)*)>((?:(?!<\/td>).)*)<\/td>/m).map{|v| "<div><span#{v[0]}>#{v[1]}<\/span><\/div>"}.join
"<div class=\"social_wrap\">#{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" : ""
"<div class=\"black-screen-social-window #{pos}#{floating_class}#{hide_in_menu_class}\">
<div class=\"content-social\">
#{site_sharer}
</div>
</div>".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('<li', '<li data-ip="true"')
end
li = li.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
if @process_ip_later
h = create_menu_process_ip_later(0,root_page.id)
else
h = create_menu(0,root_page.id)
end
# begin
# @site.store_cache_menu_data(@mobile,h)
# @site.save
# rescue
# puts "Make menu cache failed"
# end
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 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 "<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
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 "<div class='well'>No content to show.</div>".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 "<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
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 "<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, 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 = "<ul class='#{class_name}'>"
Array(@items[root_id]).each do |item|
target = item["target"]
url = item["url"]
key = item['name']
if @items[item['_id']]
html = html + "<li#{item['is_ip'] ? ' data-ip="true"' : ''}><a href='#{url}' target='#{target}'>#{key}</a>"
html = html + node(level + 1,item['_id'])
html = html + "</li>"
else
html = html + "<li#{item['is_ip'] ? ' data-ip="true"' : ''}><a href='#{url}' target='#{target}'>#{key}</a></li>"
end
end
html = html + "</ul>"
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 + "<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