Skip to content

Instantly share code, notes, and snippets.

@owen2345
Last active August 29, 2015 14:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save owen2345/7dd09f0947f58eceba79 to your computer and use it in GitHub Desktop.
Save owen2345/7dd09f0947f58eceba79 to your computer and use it in GitHub Desktop.
Rails code
class FrontController < ApplicationController
protect_from_forgery with: :exception
protect_from_forgery except: :ajax
include Front::CommonHelper
include Front::PagesHelper
include Front::SearchHelper
include Front::HtmlHelper
include PageMethods
before_action :check_status_site
before_action :check_session, :only => [:save_comment, :save_answer_comment, :save_like, :save_unlike, :save_rating, :save_follow, :save_unfollow, :follow_category]
prepend_before_action :skip_session_visit, only: :ajax
def index
go_to_page("home")
end
def page
store_location
if @page.nil? #pagina no existe
return render :inline => "no esta permitido", :status => 404 if params[:key_page] == "undefined"
go_to_page("not_found")
else
redirect_ = @page.redirects.first
if redirect_.present?
redirect_to redirect_.kind == "page" ? front_page_url(current_site.page.find(redirect_.url)) : _redirect.url
return
end
if !@page.visible_front?
go_to_page("not_found")
elsif @page.can_visited_by?(current_site, current_user) || (params[:syspreview].present? && @page.can_admin_by?(current_site, current_user))
track_visit(@page)
post_type = @site_post_types.find_by(@page.post_type_id)
@post_type = post_type
layout = "application"
set_tree_cookie_page(@page);
r_file = ""
if lookup_context.template_exists?("page_#{@page.id}", "pages", false)
r_file = "/pages/page_#{@page.id}"
elsif @page.template.present? && lookup_context.template_exists?("template_#{@page.template}", "pages", false)
r_file = "/pages/template_#{@page.template}"
elsif @page.id.to_s == @site_custom_settings["home_page"].to_s
r_file = "/pages/index"
layout = "home"
elsif lookup_context.template_exists?("post_type_#{post_type.key}", "pages", false)
r_file = "/pages/post_type_#{post_type.key}"
elsif lookup_context.template_exists?("#{post_type.key}", "pages", false)
r_file = "/pages/#{post_type.key}"
else
r_file = "/pages/post"
end
if params[:export].present?
html = render_to_string r_file, :layout => layout
html = html.to_s.gsub("'#{root_path}assets/", "'#{root_url}assets").gsub("'#{root_path}uploads/", "'#{root_url}uploads/").gsub("\"#{root_path}assets/", "\"#{root_url}assets").gsub("\"#{root_path}uploads/", "\"#{root_url}uploads/")
Rails.logger.debug "=======================pdf ========#{html}"
page = Nokogiri::HTML(html)
page.css('.hidden, .hidden_section, header, .breadcrumb, .internal_search, footer, #tree-tools-panel, #tree-categories-panel, #site-select-panel, .page_sidebar, #comments').remove
html = page.to_html
export_title = "#{current_user.id}-#{params[:export_section].present? ? @page.article.find(params[:export_section]).title.parameterize.underscore.humanize.downcase.gsub(" ", "-") : @page.url_key}"
html_file = Rails.root.join('public', "export_files", "#{export_title}.html").to_s
if params[:export] == "pdf"
if !(@site_custom_settings["article_export_pdf"].to_s == "1") &&
!(params[:perm].present? && AESCrypt.decrypt(params[:perm], Rails.application.config.page_key_encrypt) == "send_email" && @site_custom_settings["article_send_email"].to_s == "1")
go_to_page("private", "No tiene permisos")
end
pdf_file = Rails.root.join('public', "export_files", "#{export_title}.pdf")
File.open(html_file, 'wb'){|file| file << html }
system("wkhtmltopdf --orientation 'Landscape' '#{html_file.to_s}' '#{pdf_file.to_s}'")
if params[:as_url].present?
FileUtils.mv pdf_file.to_s, Rails.root.join('public', "uploads", "#{@page.url_key}.pdf").to_s, :force => true
render :inline => path_to_url(Rails.root.join('public', "uploads", "#{@page.url_key}.pdf").to_s)
elsif params[:as_page].present? # saving to be sent by email
image = MiniMagick::Image.open(pdf_file.to_s)
image.resize "800x500"
image.format("png", 0)
send_data(image.to_blob, :type => 'image/png', :disposition => 'inline')
else
setReport('export_page','pdf',{id:@page.id,section_id:params[:export_section]})
send_file(pdf_file)
end
elsif params[:export] == "excel"
if !(@site_custom_settings["article_export_excel"].to_s == "1")
go_to_page("private", "No tiene permisos")
end
html = page.css("table").to_html
send_xls_data "#{export_title}.xls", :inline => html
elsif params[:export] == "word"
if !(@site_custom_settings["article_export_word"].to_s == "1")
go_to_page("private", "No tiene permisos")
end
page.css("script").remove
html = page.to_html
setReport('export_page','word',{id:@page.id,section_id:params[:export_section]})
doc_file = Rails.root.join('public', "export_files", export_title).to_s
File.open(html_file, 'wb'){|file| file << html }
## libreoffice
command = "#{Rails.application.config.soffice_path} --headless --convert-to docx:\"MS Word 2007 XML\" '#{html_file.to_s}' --outdir '#{doc_file}'"
Rails.logger.debug "command: #{command}"
system(command)
send_file(doc_file+"/#{html_file.get_file_name}.docx", filename: "#{export_title}.docx")
end
else
@page_title = "#{@page.title} :: #{@post_type.title}"
render r_file, :layout => layout
end
else # private page
go_to_page("private")
end
end
end
def preview_draft
@post_type = @site_post_types[params[:post_type]]
if params[:section_of].nil?
previous_draft = @post_type.draft_pages.where({:page_id => nil, :owner_id => current_user.id}).first
else
previous_draft = @post_type.pages.where({:id => params[:section_of]}).first
@secction_draft = @post_type.draft_articles.where({:page_id => nil, :owner_id => current_user.id, :section_of => params[:section_of]}).first
end
if previous_draft.nil?
go_to_page("not_found")
else
@page = previous_draft
post_type = @page.post_type
template = "application"
template = @page.template if @page.template.present?
r_file = ""
if lookup_context.template_exists?("page_#{@page.id}", "pages", false)
r_file = "/pages/page_#{@page.id}"
elsif @site_custom_settings["home_page"].present? && @page.id.to_s == @site_custom_settings["home_page"].to_s
r_file = "/index"
elsif lookup_context.template_exists?("post_type_#{post_type.key}", "pages", false)
r_file = "/pages/post_type_#{post_type.key}"
elsif post_type.key == "pages"
r_file = "/pages/page"
else
r_file = "/pages/post"
end
@page_title = "Borrador :: #{@page.title}"
render r_file, :template => template
end
end
def test
#render "/test", :pdf => "my_pdf", :layout => "pdf"
respond_to do |format|
format.docx do
file = Htmltoword::Document.create "<h1>Hello</h1><ul><li>1 hello</li><li>1 hello 22222</li></ul><img src=\"https://fbcdn-sphotos-f-a.akamaihd.net/hphotos-ak-prn1/s403x403/1017627_10152258431087150_1023624584_n.jpg\">", "file_name.docx"
send_file file.path, :disposition => "attachment"
end
end
end
def category
begin
@category = Admin::Category.find(params[:category_id])
rescue
go_to_page("not_found", "Categoria no encontrada")
return
end
@post_type = @site_post_types.find_by(@category.post_type_id)
if @category.can_visited_by?(current_site, current_user) #si se puede visitar
pages = @category.available_visit_pages(current_user)
@pages_popular = pages.reorder("page_visits_count DESC").limit(12)
if !params[:sort_by].nil?
pages = pages.reorder("pages.#{params[:sort_by]} #{params[:order_by]}")
end
@pages = pages.paginate(page: params[:page], :per_page => @site_custom_settings["list_qty_results"].to_i)
@subcategories = @category.children_can_visited_by?(current_site, current_user)
set_tree_cookie_category(@category)
track_visit_category(@category)
@page_title = "#{@category.name} :: #{@post_type.title}"
render "/categories/category", :layout=> "application"
elsif !@category.visible_front? #hidden
go_to_page("not_found", "Categoria no encontrada")
else # private
go_to_page("private")
end
end
def post_type
begin
@post_type = @site_post_types.find_by(params[:id])
rescue
go_to_page("not_found", "Grupo de contenido no encontrado")
return
end
if @post_type.present?
pages = current_site.pages_to_visit_by(current_user).where(:post_type_id => @post_type.id)
if !params[:sort_by].nil?
pages = pages.reorder("pages.#{params[:sort_by]} #{params[:order_by]}")
end
@pages = pages.paginate(page: params[:page], :per_page => @site_custom_settings["list_qty_results"].to_i)
@categories = current_site.categories_to_visit_by(current_user).where(:post_type_id => @post_type).main
@page_title = "#{@post_type.title}"
if lookup_context.template_exists?("#{@post_type.key}", "post_type", false)
render "/post_type/#{@post_type.key}"
else
render "/post_type/default"
end
else
go_to_page("not_found")
end
end
def custom_page
key = params[:key]
if lookup_context.template_exists?("custom_#{key}", "pages", false)
render "/pages/custom_#{key}"
else
go_to_page("not_found")
end
end
def search
@categories_search = []
@pages_attached_file = []
@pages_ids = nil
@categories_ids = nil
@per_page = @site_custom_settings["search_qty_results"].to_i
@q = params[:search][:s]
@search = @q
q = @q.size < 4 ? "#{@q.gsub("*", "")}*" : "#{@q}" #exact
q = '' unless @q.present?
@pages = search_extra_advanced_query(q)
if params[:search][:in_cat].present? && q.present?
@categories_search = Admin::Category.visible_front.where("MATCH (name) AGAINST ('#{q}' IN BOOLEAN MODE) and categories.id in (#{current_site.get_cache_ids_to_visit_by(current_user, "categories").fix_in_sql.join(",")})")
unless params[:page].present?
@categories_ids = @categories_search.reorder("categories.id DESC").pluck("categories.id")
end
end
if params[:search][:adj].present? && q.present?
@pages_attached_file = Admin::AttachedFile.where("MATCH (file) AGAINST ('#{q}' IN BOOLEAN MODE) and page_id in(#{current_site.get_cache_ids_to_visit_by(current_user, "pages").fix_in_sql.join(",")})")
end
@page_title = "Busqueda"
render "/search"
end
def ajax
case params[:content_for]
when "sessions"
save_session
render inline: 'yes'
when "modal_search"
render :partial => "/advanced_search_list", :layout => false
when "modal_tools"
render :partial => "/link_tools", :layout => false
when "tree_home"
json = tree_list_categories
render json: (json.blank?) ? [{id:0,label:"(Vacio)"}] : json
when "glossaries"
render json: current_site.glossaries.actives.collect { |t| [t.term,t.strip_definition] }
when "list_channel"
json = list_channels(params[:channel_id])
render json: (json.blank?) ? [{id:0,label:"(Vacio)"}] : json
when "get_trans"
json = get_trans(params[:channel_type_id])
render json: (json.blank?) ? [{id:0,label:"(Vacio)"}] : json
when "list_city"
json = list_cities(params[:country])
render json: (json.blank?) ? [{id:0,label:"(Vacio)"}] : json
when "list_type_plans"
json = list_type_plans(params[:type_plans_id])
render json: (json.blank?) ? [{id:0,label:"(Vacio)"}] : json
when "get_plans"
json = get_plans(params[:plan_id])
render json: (json.blank?) ? [{id:0,label:"(Vacio)"}] : json
when "list_plans"
json = list_plans()
render json: (json.blank?) ? [{id:0,label:"(Vacio)"}] : json
when "list_cels"
json = list_cels(params[:plan_id])
render json: (json.blank?) ? [{id:0,label:"(Vacio)"}] : json
when "get_cels"
json = get_cels(params[:cel_id])
render json: (json.blank?) ? [{id:0,label:"(Vacio)"}] : json
when "list_celulares"
json = list_celulares(params[:id])
render json: (json.blank?) ? [{id:0,label:"(Vacio)"}] : json
when "list_plans_type"
json = list_plans_type(params[:id])
render json: (json.blank?) ? [{id:0,label:"(Vacio)"}] : json
when "verifyDate"
json = verifyDate(params[:date])
render json: (json.blank?) ? [{id:0,label:"(Vacio)"}] : json
when "save_modifications_visit"
user_update_visited_email_notifications(params[:id])
render :inline => ""
when "users_chosen"
html = ""
checked = params[:selected].present? ? params[:selected].split(",").to_i : []
current_site.user_enabled.includes(:profile).references(:profile).each do |user|
html += '<option '+(checked.include?(user.id)?"selected=''":"")+' value="'+user.id.to_s+'">'+user.fullname + '</option>'
end
render :inline => html
when "notifications"
if signed_in?
dates = {}
end_date = Time.now.strftime("%Y-%m-%d 23:59").to_s
@site_post_types.each do |post_type_key, post_type|
dates["#{post_type_key}"] = {:ini => user_update_visited_email_notifications(post_type_key, true).updated_at, :end=> Time.now }
end
@noti = user_email_notifications(current_user, nil, nil, dates)
@comments = user_comments_email_notifications(current_user, user_update_visited_email_notifications("comments", true).updated_at, end_date)
@tickets = user_tickets_notifications(current_user, user_update_visited_email_notifications("tickets", true).updated_at, end_date)
@specialist_pages = user_specialist_pages_email_notifications(current_user, (user_update_visited_email_notifications("specialist", true).updated_at), end_date).to_a
render :partial => "/notifications"
else
render :partial => "/notifications"
end
when "auto_complete"
rr = []
if params[:keywords].present? #only keywords
rr = Admin::Page.visible_front.where("id in (#{current_site.get_cache_ids_to_visit_by(current_user).fix_in_sql.join(",")})").visible_front.pluck("keywords").join(",").split(",")
elsif params[:titles].present?
rr = Admin::Page.visible_front.where("id in (#{current_site.get_cache_ids_to_visit_by(current_user).fix_in_sql.join(",")})").visible_front.pluck("title")
rr += Admin::Page.where("id in (#{current_site.get_cache_ids_to_visit_by(current_user, "sections").fix_in_sql.join(",")})").visible_front.pluck("title")
else #both
Admin::Page.visible_front.where("id in (#{current_site.get_cache_ids_to_visit_by(current_user).fix_in_sql.join(",")})").visible_front.pluck("title", "keywords").each do |t_k|
rr << t_k[0]
rr += t_k[1].gsub(",", " ").split(" ") unless t_k[1].nil?
end
rr += Admin::Page.where("id in (#{current_site.get_cache_ids_to_visit_by(current_user, "sections").fix_in_sql.join(",")})").visible_front.pluck("title")
end
render json: rr.clean_empty.uniq.to_json
when "setReport"
#setReport(typee = nil,action = 'Alerta', content = {}, description = '')
setReport(params[:type],params[:action_report],{id:params[:idd]},params[:desc])
render json: {ok:true}
when "modal_message"
render :partial => "/sharing_article", :layout => false, :locals => {page: params[:page], page_id: params[:page_id], page_title: params[:page_title], user_id: params[:user_id], fullname: params[:fullname], type_page: params[:type_page], type: params[:type], action: params[:action], id: params[:id], desc: params[:desc]}
#render :partial => "/sharing_article", :layout => false
when "list_meses"
json = list_meses(params[:anio])
render json: (json.blank?) ? [{id:0,label:"(Vacio)"}] : json
when "list_modelscels"
json = list_modelscels(params[:anio], params[:mes])
render json: (json.blank?) ? [{id:0,label:"(Vacio)"}] : json
when "list_forms"
json = list_forms()
render json: (json.blank?) ? [{id:0,label:"(Vacio)"}] : json
when "bookmarks"
render json: bookmarks
end
end
def login
set_current_admin_site(current_site.id)
redirect_to admin_signin_url(:redirect_to =>url_to("root_url"))
end
private
def check_status_site
@site_custom_values = get_site_settings
@site_custom_settings = @site_custom_values["custom_settings"]
if signed_in?
unless isSiteSuperAdmin?
if current_user.isDisabledFor?(current_site)
flash[:warning] = "Su cuenta esta deshabilitada para este sitio: <b>'#{current_site.title}'</b>"
redirect_to admin_root_url
return
end
bool_not_access = false
bool_internet = current_user.assigned_visit_role?('access_internet', current_site)
bool_not_access = true unless bool_internet
bool_intranet = current_user.assigned_visit_role?('access_intranet', current_site)
if bool_intranet
if security_valid_ip?
bool_not_access &&= false
end
end
if bool_not_access && !current_user.isSuperAdmin
redirect_to admin_root_url
return
end
end
end
# trying to access to :page()
if params[:key_page].present?
@page = current_site.page.find_by_url_key(params[:key_page])
if @page.present? && @page.id.to_s == @site_custom_settings["maintenance_page"].to_s
return
end
end
if current_site.in_maintenance?
unless @site_custom_settings["ips_for_maintenance"].split(/ |,|\n/).include?(request.remote_ip)
go_to_page("maintenance")
end
end
end
def check_session
unless signed_in?
store_location
flash[:error] = "Necesita estar logeado para realizar esta accion. #{link_to "Ingresar", admin_signin_path}"
redirect_to(admin_signin_path)
end
end
# track page visitors
def track_visit(page)
begin
if session[:ip_info].nil?
#Thread.new do
# data = Curl::Easy.perform("http://ipinfo.io/"+request.remote_ip).body_str
# session[:ip_info] = data.force_encoding("ISO-8859-1").encode("UTF-8")
# ActiveRecord::Base.connection.close
#end
end
visit = page.page_visit.create(:ip => request.remote_ip.to_s, :data => session[:ip_info], :user_agent => request.user_agent.force_encoding("ISO-8859-1").encode("UTF-8"), :referrer => request.referer, :remote_host => request.remote_host, :user_id => ((signed_in?) ? current_user.id : nil))
rescue
end
end
# track category visitors
def track_visit_category(category)
begin
if session[:ip_info].nil?
Thread.new do
data = Curl::Easy.perform("http://ipinfo.io/"+request.remote_ip).body_str
session[:ip_info] = data.force_encoding("ISO-8859-1").encode("UTF-8")
ActiveRecord::Base.connection.close
end
end
visit = category.category_visit.create(:ip => request.remote_ip.to_s, :data => session[:ip_info], :user_agent => request.user_agent.force_encoding("ISO-8859-1").encode("UTF-8"), :referrer => request.referer, :remote_host => request.remote_host, :user_id => ((signed_in?) ? current_user.id : nil))
rescue
end
end
def go_to_page(key, msg = "")
case key
when "not_found"
begin
not_found_page = current_site.page.find(@site_custom_settings["not_found_page"])
rescue ActiveRecord::RecordNotFound
@page_title = 'Pagina no encontrada'
render "/pages/page_not_found"
else
redirect_to front_page_url(not_found_page)
end
when "private"
begin
private_page = current_site.page.find(@site_custom_settings["private_page"])
rescue ActiveRecord::RecordNotFound
@page_title = 'Pagina privada'
render "/pages/page_private"
else
redirect_to front_page_url(private_page)
end
when "maintenance"
begin
maintenance_page = current_site.page.find(@site_custom_settings["maintenance_page"])
rescue ActiveRecord::RecordNotFound
@page_title = 'Pagina en mantenimiento'
render "/pages/page_maintanance"
else
redirect_to front_page_url(maintenance_page)
end
when "home"
begin
home_page = current_site.page.find(@site_custom_settings["home_page"])
rescue ActiveRecord::RecordNotFound
render "/pages/index", layout: "home"
else
redirect_to front_page_url(home_page)
end
end
end
def skip_session_visit
@_skip_visit = true if params[:content_for] == "sessions"
end
end
@owen2345
Copy link
Author

Sample controller code

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment