event_news/app/helpers/event_news_helper.rb

595 lines
23 KiB
Ruby

module EventNewsHelper
extend self
def data_to_human_type(a,set_tag_ids=nil)
statuses = a.statuses_with_classname.collect do |status|
{
"status" => status["name"],
"status-class" => "status-#{status['classname']}"
}
end
files = a.event_news_files.map{|file| { "file_url" => file.file.url, "file_title" => (file.title.blank? ? File.basename(file.file.path) : file.title rescue '') } if file.enabled_for?(locale) } rescue []
files.delete(nil)
links = a.event_news_links.map{|link| { "link_url" => link.url, "link_title" => (link.title.blank? ? link.url : link.title) } } rescue []
author = User.find(a.create_user_id).member_profile.name rescue ""
desc = a.image_description
desc = (desc.nil? || desc == "" ? "event_news image" : desc)
link_to_show = (a.is_external_link? ? a.external_link : OrbitHelper.widget_item_url(a.to_param)) rescue ""
target = a.is_external_link ? "_blank" : "_self"
if @image_version == 'thumb'
image_url = a.image.thumb.url
elsif @image_version == 'mobile'
image_url = a.image.mobile.url
else
image_url = a.image.url
end
event_time_formated = a.event_time_formated
{
"event_news_links" => links,
"event_news_files" => files,
"title" => a.title,
"speaker-css" => (a.speaker.blank? ? "display: none;" : ""),
"host-css" => (a.host.blank? ? "display: none;" : ""),
"place-css" => (a.place.blank? ? "display: none;" : ""),
"event-time-css" => (event_time_formated.blank? ? "display: none;" : ""),
"notes-css" => (a.notes.blank? ? "display: none;" : ""),
"event-time-formated" => event_time_formated,
"speaker" => a.speaker,
"place" => a.place,
"host" => a.host,
"notes" => a.notes,
"source-site" => "",
"source-site-title" => "",
"source-site-link" => "",
"subtitle" => a.subtitle,
"statuses" => statuses,
"category" => (a.category.title rescue ""),
"tag_ids" => (set_tag_ids.nil? ? (a.tag_ids.map{|id| id.to_s}.to_s.gsub('"',"'") rescue '[]') : set_tag_ids),
"postdate" => event_time_formated,
"event_start_date" => a.event_date_frontend,
"event_end_date" => a.event_end_date_frontend,
"event_date" => event_time_formated,
"author" => author,
"link_to_show" => link_to_show,
"target" => target,
"img_src" => image_url || "/assets/announcement-default.jpg",
"img_description" => desc
}
end
def get_feed_annc(type,site_source,locale,categories=nil,max_len=nil,sort_maps=nil,extra_match_cond=nil)
ma_key = 'event_news_mod'
if categories.nil?
if type == "index"
categories = Array(OrbitHelper.page_categories)
elsif type == "widget"
categories = Array(OrbitHelper.widget_categories)
else
categories = []
end
end
categories = ["all"] if categories.length==0
data = SiteFeedAnnc.get_feed_cache(
ma_key,
categories,
site_source,
locale,
type=='widget',
max_len,
sort_maps,
extra_match_cond
)
data
end
def get_feed_event_news(type,site_source=nil,categories=nil,max_len=nil,extra_match_cond=[])
locale = OrbitHelper.get_site_locale.to_s
feeds = []
feeds_count = 0
if !(defined? SiteFeedAnnc).nil?
sort_maps = nil
if @show_today_data_first
sort_maps = {event_date: :asc, is_top: :desc, postdate: :asc, id: :asc}
else
sort_maps = {is_top: :desc}
if is_postdate_sort_first
sort_maps = sort_maps.merge({postdate: :desc, event_date: :desc, id: :desc})
else
sort_maps = sort_maps.merge({event_date: :desc, postdate: :desc, id: :desc})
end
end
match_cond = {
"is_hidden" => {"$ne" => true},
"$and" => [
{"postdate" => {"$lte"=> Time.now}},
{
"$or" => [
{"deadline" => {"$gte"=> Time.now}},
{"deadline" => nil}
]
}
],
"title" => {"$gt"=>""}
}
if !extra_match_cond.empty?
match_cond["$and"] += extra_match_cond
end
if @show_today_data_first
match_cond["event_date"] = {"$gte" => Date.today.to_time}
end
feeds, feeds_count = get_feed_annc(type,site_source,locale,categories,max_len,sort_maps,match_cond)
end
return feeds, feeds_count
end
def get_sorted_event_news(data_count=nil)
params = OrbitHelper.params
locale = OrbitHelper.get_site_locale.to_s
page_number = OrbitHelper.page_number.to_i
page_number = 1 if page_number == 0
page_data_count = data_count || OrbitHelper.page_data_count.to_i
feeds_anns = []
if @type == "show_widget"
tags = @tags
categories = @categories
else
page = OrbitHelper.page
tags = page.tags
tags = params[:tags] if params[:tags].present?
categories = params['category']=='all' ? (page.categories || []) : (Array(params['category']) rescue (page.categories || []))
if params['category'].present? && tags.blank?
tags = ["all"]
end
module_app = ModuleApp.where(key: 'event_news_mod').first
@enable_search_flag = false
@show_option_items = nil
@show_today_data_first = false
if module_app && page.respond_to?(:select_option_items)
@show_option_items = module_app.show_option_items
if !@show_option_items.nil?
page.select_option_items.each do |select_option_item|
value = YAML.load(select_option_item.value)[I18n.locale]
case select_option_item.field_name
when @show_option_items.keys[1].to_s
if value == I18n.t('yes_')
@enable_search_flag = true
end
when @show_option_items.keys[3].to_s
if value == I18n.t('yes_')
@show_today_data_first = true
end
end
end
end
end
if @enable_search_flag
if categories.include? 'all'
@categories = module_app.categories
else
cat_maps = Category.where(:id.in => categories).collect{|cat| [cat.id.to_s, cat]}.to_h
@categories = categories.map{|v| cat_maps[v.to_s]}.compact
end
end
end
event_news_list = []
event_news = []
feeds_count = 0
extra_match_cond = []
if !params[:keywords].blank?
extra_match_cond << {
"title_plain_text" => OrbitHelper.get_keyword_regex(params[:keywords])
}
end
if !params[:stime].blank?
stime = OrbitHelper.get_time_from_str(params[:stime])
extra_match_cond << {
"event_date" => {"$gte" => stime}
}
end
if !params[:etime].blank?
etime = OrbitHelper.get_time_from_str(params[:etime]) + 1.days
extra_match_cond << {
"event_date" => {"$lt" => etime}
}
end
if !extra_match_cond.empty?
event_news = event_news.and(extra_match_cond)
end
if !params["source"].present?
event_news = @show_today_data_first ?
EventNews.can_display_and_sorted_according_today :
EventNews.can_display_and_sorted
event_news = event_news
.filter_by_categories(categories, false).filter_by_tags(tags)
.where(:title.nin => ["",nil])
if @type == "show_widget"
if !params[:uids].blank?
member_profile = MemberProfile.any_in(:uid=>params[:uids])
user_ids = member_profile.map{|m| m.user.id rescue nil}.select{|id| !id.nil?}
event_news = event_news.where(:create_user_id.in=>user_ids)
end
end
event_news = event_news.limit(page_number*page_data_count)
event_news_list = event_news.to_a
if !(defined? SiteFeed).nil? && @type != "show_widget"
feeds_anns, feeds_count = get_feed_event_news("index",nil,nil,page_number*page_data_count, extra_match_cond)
end
elsif @type != "show_widget"
feeds_anns, feeds_count = get_feed_event_news("index",params["source"],nil,page_number*page_data_count, extra_match_cond)
end
if !feeds_anns.blank?
top_anns = event_news_list.select{|v| v.is_top} + feeds_anns.select{|v| v['is_top']}
rest_all_anns = event_news_list.select{|v| !v.is_top} + feeds_anns.select{|v| v['is_top'] != true}
all_filter = sort_event_news(top_anns) + sort_event_news(rest_all_anns)
else
all_filter = event_news_list
end
if page_data_count != 0
sorted = all_filter[(page_number-1)*page_data_count...page_number*page_data_count]
else
sorted = all_filter
end
annc_count = event_news.count + feeds_count
total_pages = page_data_count == 0 ? 1 : (annc_count.to_f / page_data_count).ceil
[sorted,total_pages]
end
def sort_event_news(event_news_list)
if @show_today_data_first || !is_postdate_sort_first
if enable_manually_sort
event_news_list = event_news_list.sort_by { |event_news|
tmp1 = event_news["event_date"].blank?
tmp2 = event_news["postdate"].blank?
[
(@show_today_data_first ? event_news['sort_number'].to_i : -event_news['sort_number'].to_i),
tmp1 ? 0 : 1, tmp1 ? nil : event_news["event_date"].to_time,
tmp2 ? 0 : 1, tmp2 ? nil : event_news["postdate"].to_time
]
}
else
event_news_list = event_news_list.sort_by { |event_news|
tmp1 = event_news["event_date"].blank?
tmp2 = event_news["postdate"].blank?
[
tmp1 ? 0 : 1, tmp1 ? nil : event_news["event_date"].to_time,
tmp2 ? 0 : 1, tmp2 ? nil : event_news["postdate"].to_time
]
}
end
if !@show_today_data_first
event_news_list = event_news_list.reverse
end
else
if enable_manually_sort
event_news_list = event_news_list.sort_by { |event_news|
tmp1 = event_news["event_date"].blank?
tmp2 = event_news["postdate"].blank?
[
-a['sort_number'].to_i,
tmp2 ? 0 : 1, tmp2 ? nil : event_news["postdate"].to_time,
tmp1 ? 0 : 1, tmp1 ? nil : event_news["event_date"].to_time
]
}.reverse
else
event_news_list = event_news_list.sort_by { |event_news|
tmp1 = event_news["event_date"].blank?
tmp2 = event_news["postdate"].blank?
[
tmp2 ? 0 : 1, tmp2 ? nil : event_news["postdate"].to_time,
tmp1 ? 0 : 1, tmp1 ? nil : event_news["event_date"].to_time
]
}.reverse
end
end
return event_news_list
end
def render_view_for_event_news(overridehtml=nil)
@key = Site.first.template
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 @target_action == "index"
filename = File.basename(overridehtml.nil? ? params[:layout_type] : overridehtml)
f = File.join(Rails.root, 'app', 'templates', "#{@key}", 'modules', 'event_news_mod', "#{filename}.html.erb")
if !File.exist?(f)
f = File.join(Rails.root, 'app', 'templates', "#{@key}", 'modules', 'event_news_mod', "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
file = File.open(f)
doc = Nokogiri::HTML(file, nil, "UTF-8")
file.close
controller = EventNewsController.new
begin
data = @data# rescue nil
rescue Exception => e
write_debug_file(e,'event_news_mod',@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? ? @target_action : overridehtml
f = File.join(Rails.root, 'app', 'templates', "#{@key}", 'modules', 'event_news_mod', "#{filename}.html.erb")
if File.exist?(f)
file = File.open(f)
doc = Nokogiri::HTML(file, nil, "UTF-8")
file.close
controller = EventNewsController.new
begin
data = @data# rescue nil
rescue Exception => e
write_debug_file(e,'event_news_mod',@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 = 'event_news'
impression.action_name = @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 @show_page == "false"
html = html.gsub("{{pagination_goes_here}}","")
else
if total_pages > 1
html = html.gsub("{{pagination_goes_here}}",create_pagination(total_pages))
else
html = html.gsub("{{pagination_goes_here}}","")
end
end
html = Nokogiri::HTML.parse(html)
html.css('.i-event_news__page-title').remove
dates = html.css("*[date-format]")
if !dates.blank?
dates.each do |d|
begin
format = d.attributes["date-format"].value
date = DateTime.parse(d.inner_text)
d.inner_html = d.inner_html.gsub(d.inner_text.strip, " " + date.strftime(format))
rescue
next
end
end
end
html.css("body")[0].inner_html = html.css("body")[0].inner_html.gsub("{{page-title}}","")
html.css("body").to_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 get_layouts(module_app)
layout_types = []
@key = Site.first.template
f = File.join("#{Rails.root}/app/templates/#{@key}/modules/#{module_app}/info.json")
if File.exist?(f)
info = File.read(f)
hash = JSON.parse(info) rescue {}
frontends = hash["frontend"] || []
frontends.each do |frontend|
frontend["thumbnail"] = "/assets/#{module_app}/thumbs/#{frontend["thumbnail"]}"
layout_types << frontend
end
end
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, ".*")
if w[0,1] != "_" && w[0,1] != "s" && w != "info"
layout_types << w
end
end
end
layout_types
end
def render_ad_banner(event_carousel_images,data)
("<div class=\"carousel_images\">
<div class=\"w-ba-banner ba-banner-widget-1\">
<div class=\"w-ba-banner__wrap cycle-slideshow\"
data-list=\"event_carousel_images\"
data-level=\"0\"
data-cycle-slides=\".event_carousel_slide\"
data-cycle-log=\"false\"
data-cycle-auto-height=\"0\"
data-cycle-speed=\"300\"
data-cycle-timeout=\"5000\"
data-cycle-fx=\"fade\"
data-pager-active-class=\"active-slide\"
data-cycle-swipe=true
data-cycle-swipe-fx=\"scrollHorz\"
>" +
event_carousel_images.collect do |e|
"<div class=\"w-ba-banner__slide event_carousel_slide\"
data-cycle-title=\"#{e['description_text']}\"
>
<img class=\"w-ba-banner__image banner-responsive\" src=\"#{e['src']}\" alt=\"#{e['description_text']}\">
<div class=\"ad-overlay w-ad-banner__overlay event_carousel__overlay\">
<p><strong class=\"carousel__description\">#{e['description']}</strong></p>
</div>
<div class=\"transitionfade\"></div>
</div>"
end.join+
"</div>
<ul class=\"controlplay\"><a class=\"resume-slide\" title = \"#{data['resume_btn_title']}\"><i></i></a><a class=\"pause-slide\" title = \"#{data['pause_btn_title']}\"><i></i></a></ul>
<ul class=\"button-mid\">
<i class=\"fa fa-angle-left prev-button\" aria-hidden=\"true\" title = \"#{data['prev_btn_title']}\"></i>
<i class=\"fa fa-angle-right next-button\" aria-hidden=\"true\" title = \"#{data['next_btn_title']}\"></i>
</ul>
</div>
<div style=\"position: relative;\">
<h4><span class=\"active_slide\">1</span>/#{data['carousel_count']}</h4>
<ul class=\"carousel_images_slide w-annc__list row list-unstyled\" data-level=\"0\" data-list=\"event_carousel_images\">" +
event_carousel_images.collect do |e|
"<li class=\"carousel_img_item col-sm-3\">
<div class=\"carousel_img-wrap\">
<img class=\"carousel_img\" src=\"#{e['src']}\" alt=\"#{e['description_text']}\">
</div>
</li>"
end.join +
"</ul>
<ul class=\"button-mid\">
<i class=\"fa fa-angle-left prev-button prev_img\" aria-hidden=\"true\" title = \"#{data['prev_btn_title']}\"></i>
<i class=\"fa fa-angle-right next-button next_img\" aria-hidden=\"true\" title = \"#{data['next_btn_title']}\"></i>
</ul>
</div>
</div>").html_safe
end
def complementaryColor(my_hex)
if my_hex[0] == '#'
my_hex = my_hex[1..-1]
end
rgb = my_hex.split(//).each_slice(my_hex.length/3).map{|v| v.join}
comp = rgb.map{|a| (255 - a.to_i(16)).to_s(16).rjust(2,'0')}
'#'+comp.join
end
def lighten_color(my_hex,percent)
if my_hex[0] == '#'
my_hex = my_hex[1..-1]
end
rgb = my_hex.split(//).each_slice(my_hex.length/3).map{|v| v.join}
comp = rgb.collect do |a|
tmp = a.to_i(16)*(1+percent/100.0)
tmp = 255 if tmp>255
tmp = 0 if tmp < 0
tmp.to_i.to_s(16).rjust(2,'0')
end
'#'+comp.join
end
def enable_manually_sort
if defined?(OrbitHelper::SharedHash) && OrbitHelper::SharedHash
OrbitHelper::SharedHash['event_news_mod'][:enable_manually_sort]
else
EventNewsSetting.first.enable_manually_sort rescue false
end
end
def is_postdate_sort_first
if defined?(OrbitHelper::SharedHash) && OrbitHelper::SharedHash
OrbitHelper::SharedHash['event_news_mod'][:is_postdate_sort_first]
else
EventNewsSetting.first.is_postdate_sort_first rescue false
end
end
end