Jump to content
wellingtonmelo

[Resolvido] Como inserir PHP dentro do HTML que já está dentro do PHP?

Recommended Posts

Olá pessoal, beleza?

 

Bom, eu sou um bisbilhoteiro quando se refere a PHP, com html e css eu faço bastante coisa, mas php eu só uso códigos prontos, não entendo da linguagem.

 

Eu preciso inserir um PHP que é responsável por exibir uma URL que o usuário insere no painel do wordpress.

 

O código que exibe a URL é esse:

<?php echo $settings['defaults']['fb_app_id2'] ?>

e preciso inserir ele dentro do ifreme, botão de curtir do facebook, o código é de um plugin que, por isso o html já está dentro de um PHP.

onde está LINK-PARA-EXIBIR-URL-AQUI entra o código acima. Porém quando tento inserir, da erro no php.

 

Já tentei usar \ antes da aspa simples, mas não funciona.

Usando o código acima,  retorna esse erro na página:

Parse error: syntax error, unexpected 'defaults' (T_STRING) in /home/welg2816/public_html/wp-content/plugins/wp-quiz-pro/inc/class-fb-quiz.php on line 66

 

   
 public function get_html_questions() {
 
        $questions_html = '';
 
        if ( ! empty( $this->questions ) ) {
            foreach ( $this->questions as $key => $question ) {
 
                $desc = ! empty( $question['desc'] ) ? '<p class="desc">' . $question['desc'] . '</p>' : '';
                $questions_html .= ' <iframe class="facebook-like-button" style="cursor: default;" src="https://www.facebook.com/plugins/like.php?locale=pt_BR&href=https://www.facebook.com/plugins/like.php?locale=pt_BR&href=LINK-PARA-EXIBIR-URL-AQUI&layout=button_count&action=like&size=small&show_faces=false&share=false&width=50&height=21" width="97" height="20" style="border:none;overflow:hidden;" scrolling="no" frameborder="0" allowTransparency="true"></iframe>';
            }
        }
 
        return $questions_html;
    }
 

 

Alguém me ajude por favor, já tentei de tudo!

Share this post


Link to post
Share on other sites
<?php

public function get_html_questions() {
  $questions_html = '';

  if ( ! empty( $this->questions ) ) {
    foreach ( $this->questions as $key => $question ) {

      $desc = ! empty( $question['desc'] ) ? '<p class="desc">' . $question['desc'] . '</p>' : '';
      $questions_html .= '<iframe class="facebook-like-button" style="cursor: default;" src="https://www.facebook.com/plugins/like.php?locale=pt_BR&href=https://www.facebook.com/plugins/like.php?locale=pt_BR&href="'.$settings['defaults']['fb_app_id2'].'"&layout=button_count&action=like&size=small&show_faces=false&share=false&width=50&height=21" width="97" height="20" style="border:none;overflow:hidden;" scrolling="no" frameborder="0" allowTransparency="true"></iframe>';
    }
  }

  return $questions_html;
}

Use desta maneira. :)

  • +1 1

Share this post


Link to post
Share on other sites

OPA! Jhess, obrigado por se dispor a ajudar meu parceiro!

 

Bom, infelizmente não funcionou. O erro até sumiu, carregou a página, mas  conteúdo não foi exibido.

 

Mas eu acredito que o erro esteja no meu código, pois eu dei um CTRL C CTRL V monstro no código, alterei os nomes, como pode ver esta fb_app_id2, mas acredito que algo errado não está certo! hahaha

 

O ID do aplicativo (ver no print) o sistema joga de boa lá no código, mas algum detalhe não o deixa ser impresso na página comum, somente la dentro do head, por esse detalhe a função que copiei não é exibida.

 

Olha esse print, por favor:

cbc604cc00.png

 

Você sabe me informar algum jeito (sem plugin) para fazer uma função basicona assim? o usuário insere a url no painel, e através de um shortcode a gente exibe a url la dentro do iframe like do facebook?

 

Trabalhando há dias nesse projeto, personalizando, só falta isso pra encerrar. 

 

Obrigado por sua ajuda amigo! abraço

Share this post


Link to post
Share on other sites

Olha que porcaria, eu coloquei o código la próximo de onde é exibido o "ID do aplicativo", e num é que ta funcionando?!

 

Só não funciona dentro do single.php.

 

b4a1057a4c.png

 

O código onde coloquei é esse:

		public function inline_script() {
			$settings = get_option( 'wp_quiz_pro_default_settings' );
			?>
			<script>
			var quizSiteUrl = '<?php echo home_url( '/' ) ?>';
			<?php if ( ! empty( $settings['analytics']['tracking_id'] ) ) { ?>
				(function(i,s,o,g,r,a,m) {i['GoogleAnalyticsObject']=r;i[r]=i[r]||function() {
				(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
				m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
				})(window,document,'script','//www.google-analytics.com/analytics.js','ga');

				ga('create', '<?php echo $settings['analytics']['tracking_id'] ?>', 'auto');
				ga('send', 'pageview');
			<?php } ?>
			<?php if ( ! empty( $settings['defaults']['fb_app_id'] ) ) { ?>
				window.fbAsyncInit = function() {
					FB.init({
						appId    : '<?php echo $settings['defaults']['fb_app_id'] ?>',
						xfbml    : true,
						version  : 'v2.9'
					});

					FB.getLoginStatus(function( response ) {
						getLogin( response );
					});
				};
				
				(function(d, s, id) {
					var js, fjs = d.getElementsByTagName(s)[0];
					if (d.getElementById(id)) {return;}
					js = d.createElement(s); js.id = id;
					js.src = "//connect.facebook.net/pt_BR/sdk.js";
					fjs.parentNode.insertBefore(js, fjs);
				}(document, 'script', 'facebook-jssdk'));
			<?php } ?>
			</script>
			<?php echo $settings['defaults']['fb_app_id2'] ?>
			<?php
			if ( is_singular( array( 'wp_quiz' ) ) && isset( $settings['defaults']['share_meta'] ) && 1 === $settings['defaults']['share_meta'] ) {
				global $post, $wpseo_og;
				$twitter_desc = $og_desc = str_replace( array( "\r", "\n" ), '', strip_tags( $post->post_excerpt ) );
				if ( defined( 'WPSEO_VERSION' ) ) {
					remove_action( 'wpseo_head', array( $wpseo_og, 'opengraph' ), 30 );
					remove_action( 'wpseo_head', array( 'WPSEO_Twitter', 'get_instance' ), 40 );
					//use description from yoast
					$twitter_desc 	= get_post_meta( $post->ID, '_yoast_wpseo_twitter-description', true );
					$og_desc		= get_post_meta( $post->ID, '_yoast_wpseo_opengraph-description', true );
				}
				?>
				<meta name="twitter:title" content="<?php echo get_the_title(); ?>">
				<meta name="twitter:description" content="<?php echo $twitter_desc; ?>">
				<meta name="twitter:domain" content="<?php echo esc_url( site_url() ); ?>">
				<meta property="og:url" content="<?php the_permalink(); ?>" />
				<meta property="og:title" content="<?php echo get_the_title(); ?>" />
				<meta property="og:description" content="<?php echo $og_desc; ?>" />
				<?php
				if ( has_post_thumbnail() ) {
					$thumb_id = get_post_thumbnail_id();
					$thumb_url_array = wp_get_attachment_image_src( $thumb_id, 'full', true );
					$thumb_url = $thumb_url_array[0];
					?>
					<meta name="twitter:card" content="summary_large_image">
					<meta name="twitter:image:src" content="<?php echo $thumb_url; ?>">
					<meta property="og:image" content="<?php echo $thumb_url; ?>" />
					<meta itemprop="image" content="<?php echo $thumb_url; ?>">
				<?php
				}
			}
		}

Inseri o código <?php echo $settings['defaults']['fb_app_id2'] ?> logo após o fechamento do </script>

 

Olhando assim, tem como ajudar em algo? hehe

 

Abraço

Share this post


Link to post
Share on other sites

pelo o que eu vi a variável não estar recebendo o valor pq você está usando aspas simples acho que a solução seria você concatenar ou então usar aspas duplas e colocar a barra invertida ^_^

  • +1 1

Share this post


Link to post
Share on other sites

Olá thbomfim, obrigado por sua ajuda!

 

Eu testei como você falou, mas ainda sim, retorna em branco.

Eu acredito que deve ter algum detalhe nas configurações que não deixa exibir na página padrão, somente no head sei lá... porque como mostrei no print, ele exibiu o conteudo corretamente, quando coloquei o código que exibe o conteúdo dentro do head.

 

Você sabe me informar como eu consigo criar uma função como expliquei ali anteriormente? criar a função?

 

abraço

Share this post


Link to post
Share on other sites
Em 10/06/2018 at 17:09, wellingtonmelo disse:

Porém quando tento inserir, da erro no php.

 

Qual erro apareceu?

edit - desconsidere, havia pulado direto pro seu código e não havia visto o erro.

Você ta precisando colocar o link dentro do iframe agora? É isso?

  • +1 1

Share this post


Link to post
Share on other sites

Olá Bruno!

 

Isso, preciso colocar dentro do iframe que está dentro do PHP. Porém o plugin que estou usando deve ter algum detalhe que não deixa esse text field ser exibido dentro da single.

 

Exemplo, quando coloco esse código: 

<?php echo $settings['defaults']['fb_app_id2'] ?>

dentro do arquivo que é responsável por carregar os metadados, ele aparece. Porém quando insiro esse exato código dentro do single.php, não exibe nada.

 

eu até consegui colocar esse código dentro do iframe usando assim:

"'.$settings['defaults']['fb_app_id2'].'"

Porém não exibe.

 

Na mensagem acima eu coloquei todo o código da função:

8eb49f0493.png

 

Verde é o código original, o vermelho é a copia que fiz, que está funcionando certo, ele exibe a URL que coloquei, só não a exibe dentro do single.

 

Desculpa aí o textão, estou tentando deixar bem explicado pra você tentar me ajudar.

 

Obrigado!! abraço

Share this post


Link to post
Share on other sites

Esse script é aberto lá no início da função, por favor, olhe o código completo resposta que coloquei acima.

 

Na mensagem acima eu também mostrei que esse código marcado em  vermelho é exibido na página, porém somente quando o insiro onde fica os metadados do site. Quando insiro o código diretamente dentro da single.php ele não aparece.

Share this post


Link to post
Share on other sites

rodei ele aqui e resultou neste erro 

PHP Parse error:  syntax error, unexpected '' (T_STRING) in source_file.php on line 69
 

adicionar esse código no seu arquivo para mostrar todos os erros

  ini_set('display_errors', true);

error_reporting(E_ALL);

  ini_set('display_errors', true);
error_reporting(E_ALL);

 

  • +1 1

Share this post


Link to post
Share on other sites

Troca essa linha que está verde:

appId      : '<?php echo $settings['defaults']['fb_app_id'] ?>',

Por isso:

appId      : '<?php echo $settings["defaults"]["fb_app_id"] ?>',

Faz o teste.

  • +1 1

Share this post


Link to post
Share on other sites

Verdade th, coloquei esse código e mostrou alguns erros ao inserir o código na página single.php , veja por favor: http://testespop.com.br/qual-premio-do-ano-voce-merece-ganhar/

 

Bruno, o código verde não precisamos mexer, ele é responsável por puxar/exibir o ID do aplicativo.

Informo o ID dentro do painel do plugin, veja print:
cbc604cc00.png&key=7dc31608f20ee91ca31249190fc3019faad1c50a1cff0bc4e45b35c9a04ea070

 

O código que tem fb_app_id2 é a cópia, entendeu?

Eu copiei as funções que geram ele, coloquei 2 no final, ele está funcionando certinho, puxando a ULR como no print acima, porém ele só funciona quando inserido no header da página, no arquivo single.php não funciona.

 

Acesse: http://testespop.com.br

Você verá que a ULR informada no print, está exibindo lá acima de toda a página.

 

Dentro da single tem 2 erros sendo exibidos, eles são desse mesmo código que exibe a ULR no topo da página:

 

b81660b1be.png

 

Eu só preciso de um custom field que funcione usando um shortcode na single.php =(

Share this post


Link to post
Share on other sites

Segue:

Nota: essas partes são os widgetes: 

<?php	if ( is_active_sidebar('sidebar-topo') ) { dynamic_sidebar('sidebar-topo');	}	?>

Segue código da single.php

<?php
/**
 * The template for displaying all single posts
 *
 * @link https://developer.wordpress.org/themes/basics/template-hierarchy/#single-post
 *
 * @package sidebar
 */
get_header(); 

if ( ! is_active_sidebar( 'sidebar-main' ) ) {
 	$sidebar_col_class = "col-lg-8 col-md-8 col-xs-12 col-sm-12 col-lg-offset-2 col-md-offset-2";
}
else {
 	$sidebar_col_class = "col-lg-8 col-md-8 col-xs-12 col-sm-12";
}

?>

<?php while ( have_posts() ) : the_post(); //main loop ?>  
<!-- Comentários facebook -->                              
<div id="fb-root"></div>
<script>(function(d, s, id) {
  var js, fjs = d.getElementsByTagName(s)[0];
  if (d.getElementById(id)) return;
  js = d.createElement(s); js.id = id;
  js.src = 'https://connect.facebook.net/pt_BR/sdk.js#xfbml=1&version=v3.0&appId=&autoLogAppEvents=1';
  fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));</script>
<!-- Fim comentários facebook -->


<div id="content" class="site-content">
	<!-- Anúncio topo - Página do teste -->
	<div class="banner-topo">
		<?php	if ( is_active_sidebar('sidebar-topo') ) { dynamic_sidebar('sidebar-topo');	}	?>
	</div>
	<!-- Fim Anúncio topo - Página do teste -->
	</div>
	<div class="container">
		<div class="row" style="margin-bottom:15px;">
			<div class="col-lg-9 col-md-8 col-xs-12 col-sm-12 nopadding">
				<div class="conteudo-single">
					<article id="post-<?php the_ID(); ?>" <?php post_class('single-post-wrapper'); ?>> 
						<div id="primary" class="content-area">
							<main id="main" class="site-main">
								<?php if ( !has_post_thumbnail() ) { ?>
								<div class="no-featuredimage-header">
								<p class="category">
									<?php the_category( ', ' ); ?>                   
								</p>                    
								<h1 class="entry-title"><?php the_title( '', '' ); ?></h1>                    
									<div class="entry-meta">
										<ul>
										<li><?php echo get_the_date(); ?></li>
										<li><?php the_author(); ?></li>
										<li><?php comments_number( 'no responses', 'one response', '% responses' ); ?>.</li>
										</ul>
									</div>
									<div class="clearfix"></div>
								</div>
								<?php } ?>
								<?php get_template_part( 'template-parts/content', 'single' ); ?> 
							</main><!-- #main -->
						</div><!-- #primary -->
						<!-- Anúncio Interno - Página do teste -->
						<center>
							<div class="sidebar-likebutton" style="margin:auto; width:90px; margin-bottom:10px;">
								<center><?php	if ( is_active_sidebar('sidebar-likebutton') ) {dynamic_sidebar('sidebar-likebutton');}?></center>
							</div>
							<div class="sidebar-interna" style="margin-bottom:10px;">
								<?php	if ( is_active_sidebar('sidebar-interna') ) {dynamic_sidebar('sidebar-interna');}?>
							</div>
						</center>
						<!-- Fim Anúncio Interno - Página do teste -->
					</article><!-- #post-<?php the_ID(); ?> -->

					<!-- inicio - testando exibição da função URL Facebook -->
					<?php echo $settings["defaults"]["fb_app_id2"] ?>

					<?php echo $settings['defaults']['fb_app_id2'] ?>
					<!-- fim - testando exibição da função URL Facebook -->

				</div><!-- .conteudo-single -->

					<!-- Inicío Configuração Comentários -->
				<div class="comentarios-single">
					<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.2.js"></script>
					<script>
						$(document).ready(function() {
							$('.nav-toggle').click(function(){
								//get collapse content selector
								var collapse_content_selector = $(this).attr('href');					
								
								//make the collapse content to be shown or hide
								var toggle_switch = $(this);
								$(collapse_content_selector).toggle(function(){
									if($(this).css('display')=='none'){
										toggle_switch.html('<div class="coment-pai"><div class="coment-left"><i class="fa fa-comment" aria-hidden="true"></i>&nbsp;&nbsp;Deixe seu comentário!</div><div class="coment-right"><i class="fa fa-arrow-down" aria-hidden="true"></i></div></div>');//change the button label to be 'Show'
									}else{
										toggle_switch.html('<div class="coment-pai"><div class="coment-left"><i class="fa fa-comment" aria-hidden="true"></i>&nbsp;&nbsp;Deixe seu comentário!</div><div class="coment-right"><i class="fa fa-arrow-up" aria-hidden="true"></i></div></div>');//change the button label to be 'Hide'
									}
								});
							});
						});	
					</script>
					<section class="round-border">
						<div>
							<button class="nav-toggle" href="#collapse1" ><div class="coment-pai"><div class="coment-left"><i class="fa fa-comment" aria-hidden="true"></i>&nbsp;&nbsp;Deixe seu comentário!</div><div class="coment-right"><fb:comments-count href=<?php the_permalink();?>>0</fb:comments-count>&nbsp;&nbsp;<i class="fa fa-arrow-down" aria-hidden="true"></i></div></div></button>
						</div>
						<div id="collapse1" style="display:none">
							<div class="fb-comments" data-href="<?php the_permalink(); ?>" data-width="100%" data-numposts="6"></div>
						</div>
					</section>
					<!-- Fim Configuração Comentários -->
				</div><!-- Fim comentarios-single -->
			</div><!-- Fim col-lg-9 col-md-8 col-xs-12 col-sm-12 -->
			
            <div class="col-lg-3 col-md-3 col-xs-12 col-sm-12 sid-lateral">
				<center>
				<div class="sidebaranuncio1" style="margin-bottom:10px;">
					<?php	if ( is_active_sidebar('sidebar-lateral') ) {dynamic_sidebar('sidebar-lateral');}?>
				</div>
					<?php	if ( is_active_sidebar('sidebar-likebox') ) {dynamic_sidebar('sidebar-likebox');}?>
				</center>
            </div>

		</div><!-- .row -->
	</div><!-- .container -->

	<div class="container-fluid conteudo-relacionado">
		<div class="row">
			<div class="col-lg-12 col-md-12 col-xs-12 col-sm-12">
					<h3 style="padding-left:20px; font-size: 20px;">Recomendamos para você</h3>
					<?php
					$orig_post = $post;
					global $post;
					$tags = wp_get_post_tags($post->ID);
					
					if ($tags) {
					$tag_ids = array();
					foreach($tags as $individual_tag) $tag_ids[] = $individual_tag->term_id;
					$args=array(
					'post_type' => 'post',
					'orderby'   => 'rand',
					'posts_per_page' => 20,
					);
					
					$my_query = new wp_query( $args );
					
					while( $my_query->have_posts() ) {
					$my_query->the_post();
					?>
					
					<div class="col-md-4 col-sm-4 col-xs-12">
						<div class="caixa-teste">
							<a href="<?php the_permalink(); ?>" class="post-thumbnail">
								<div class="caixa-img">
									<?php the_post_thumbnail('arte-thumbnail'); ?>
								</div>
									
								<div class="caixa-titulo">
									<?php the_title(); ?>
								</div>
							</a>
							<?php the_excerpt(); ?>
						</div><!-- .caixa-teste -->
					</div>
					
					
					<? }
					}
					$post = $orig_post;
					wp_reset_query();
					?>
			</div>
		</div><!-- .row -->           
	</div><!-- .container -->
  	
</div><!-- #content -->
<?php endwhile; // End of the loop. ?>                        
        
<?php  get_footer(); ?>

 

Share this post


Link to post
Share on other sites

Vou colocar aqui o arquivo que tem várias vezes essa $settings, é nele que inseri a cópia da função que está exibindo a URL certinha no topo do site.

 

<?php
/**
 * Plugin Name: Testes Pop
 * Plugin URI:  https://testespop.com.br
 * Description: O TestesPop permite que você adicione facilmente testes para o facebook, ágeis e modernos ao seu site ou blog! Aumente o engajamento e os compartilhamentos enquanto fatura continuamente.
 * Version:     1.1.1
 * Author:      TestesPop
 * Author URI:  http://testespop.com.br
 *
 * Text Domain: testes-pop
 * Domain Path: /languages/
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit; // disable direct access
}

if ( ! class_exists( 'WP_Quiz_Pro_Plugin' ) ) :

	/**
	 * Register the plugin.
	 *
	 * Display the administration panel, insert JavaScript etc.
	 */
	class WP_Quiz_Pro_Plugin {

		/**
		 * Hold plugin version
		 *
		 * @var string
		 */
		public $version = '1.1.1';

		/**
		 * Hold an instance of WP_Quiz_Pro_Plugin class.
		 *
		 * @var WP_Quiz_Pro_Plugin
		 */
		protected static $instance = null;

		/**
		 * Hold the current quiz instance
		 *
		 * @var WP_Quiz_Pro
		 */
		public $quiz = null;

		/**
		 * Main WP_Quiz_Pro_Plugin instance.
		 * @return WP_Quiz_Pro_Plugin - Main instance.
		 */
		public static function get_instance() {

			if ( is_null( self::$instance ) ) {
				self::$instance = new WP_Quiz_Pro_Plugin;
			}

			return self::$instance;
		}

		/**
		 * You cannot clone this class.
		 */
		public function __clone() {
			_doing_it_wrong( __FUNCTION__, __( 'Cheatin&#8217; huh?', 'wp-quiz-pro' ), $this->version );
		}

		/**
		 * You cannot unserialize instances of this class.
		 */
		public function __wakeup() {
			_doing_it_wrong( __FUNCTION__, __( 'Cheatin&#8217; huh?', 'wp-quiz-pro' ), $this->version );
		}

		/**
		 * The Constructor
		 */
		private function __construct() {

			$this->define_constants();
			$this->includes();
			$this->hooks();
			$this->setup_shortcode();
		}

		/**
		 * Define WP Quiz constants
		 */
		private function define_constants() {

			define( 'WP_QUIZ_PRO_VERSION',    $this->version );
			define( 'WP_QUIZ_PRO_BASE_URL',   trailingslashit( plugins_url( 'wp-quiz-pro' ) ) );
			define( 'WP_QUIZ_PRO_ASSETS_URL', trailingslashit( WP_QUIZ_PRO_BASE_URL . 'assets' ) );
			define( 'WP_QUIZ_PRO_PATH',       plugin_dir_path( __FILE__ ) );
		}

		/**
		 * Load required classes
		 */
		private function includes() {

			// Auto loader
			spl_autoload_register( array( $this, 'autoloader' ) );

			new WP_Quiz_Pro_Admin;
		}

		/**
		 * Autoload classes
		 */
		public function autoloader( $class ) {

			$dir = WP_QUIZ_PRO_PATH . 'inc' . DIRECTORY_SEPARATOR;
			$class_file_name = 'class-' . str_replace( array( 'wp_quiz_pro_', '_' ), array( '', '-' ), strtolower( $class ) ) . '.php';
			if ( file_exists( $dir . $class_file_name ) ) {
				require $dir . $class_file_name;
			}
		}

		/**
		 * Register the [wp_quiz_pro] shortcode.
		 */
		private function setup_shortcode() {

			add_shortcode( 'wp_quiz_pro', array( $this, 'register_shortcode' ) );
		}

		/**
		 * Hook WP Quiz into WordPress
		 */
		private function hooks() {

			// Common
			add_action( 'init', array( $this, 'load_plugin_textdomain' ) );
			add_action( 'init', array( $this, 'register_post_type' ) );
			add_action( 'init', array( $this, 'embeded_output' ) );

			// Frontend
			add_action( 'wp_head', array( $this, 'inline_script' ), 1 );
			add_filter( 'the_content', array( $this, 'create_quiz_page' ) );

			// Ajax
			add_action( 'wp_ajax_wq_quizResults', array( $this, 'save_quiz_results' ) );
			add_action( 'wp_ajax_nopriv_wq_quizResults', array( $this, 'save_quiz_results' ) );

			add_action( 'wp_ajax_wq_submitInfo', array( $this, 'save_quiz_user_info' ) );
			add_action( 'wp_ajax_nopriv_wq_submitInfo', array( $this, 'save_quiz_user_info' ) );

			add_action( 'wp_ajax_wq_submitFbInfo', array( $this, 'save_quiz_fb_user_info' ) );
			add_action( 'wp_ajax_nopriv_wq_submitFbInfo', array( $this, 'save_quiz_fb_user_info' ) );

			add_action( 'wp_ajax_check_image_file', array( $this, 'check_image_file' ) );
			add_action( 'wp_ajax_check_video_file', array( $this, 'check_video_file' ) );
			add_action( 'wp_ajax_dismiss_imagick_notice', array( $this, 'dismiss_imagick_notice' ) );
			add_action( 'wp_ajax_dismiss_gdlibrary_notice', array( $this, 'dismiss_gdlibrary_notice' ) );
			add_action( 'wp_ajax_wpquiz_get_debug_log', array( $this, 'wp_quiz_pro_get_debug_log' ) );

			add_action( 'wp_ajax_connect_aweber', array( $this, 'connect_aweber' ) );

			// FB SDK version 2.9 fix
			if ( isset( $_GET['fbs'] ) && ! empty( $_GET['fbs'] ) ) {
				add_action( 'template_redirect', array( $this, 'fb_share_fix' ) );
			}
		}

		/**
		 * Initialise translations
		 */
		public function load_plugin_textdomain() {

			load_plugin_textdomain( 'wp-quiz-pro', false, dirname( plugin_basename( __FILE__ ) ) . '/languages/' );
		}

		/**
		 * Register Quiz post type
		 */
		public function register_post_type() {

			$labels = array(
				'name'               => __( 'Testes Pop', 'wp-quiz-pro' ),
				'menu_name'          => __( 'Testes Pop', 'wp-quiz-pro' ),
				'singular_name'      => __( 'TP WP', 'wp-quiz-pro' ),
				'name_admin_bar'     => _x( 'Testes Pop', 'name admin bar', 'wp-quiz-pro' ),
				'all_items'          => __( 'Todos os testes', 'wp-quiz-pro' ),
				'search_items'       => __( 'Procurar teste', 'wp-quiz-pro' ),
				'add_new'            => _x( 'Adicionar', 'quiz', 'wp-quiz-pro' ),
				'add_new_item'       => __( 'Adicionar novo teste', 'wp-quiz-pro' ),
				'new_item'           => __( 'Novo testes', 'wp-quiz-pro' ),
				'view_item'          => __( 'Ver teste', 'wp-quiz-pro' ),
				'edit_item'          => __( 'Editar teste', 'wp-quiz-pro' ),
				'not_found'          => __( 'Nenhum teste encontrado.', 'wp-quiz-pro' ),
				'not_found_in_trash' => __( 'Nenhum teste encontrado na lixeira.', 'wp-quiz-pro' ),
				'parent_item_colon'  => __( 'Teste pai', 'wp-quiz-pro' ),
			);

			$args = array(
				'labels'             => $labels,
				'description'        => __( 'Mantém os testes e seus dados.', 'wp-quiz-pro' ),
				'menu_position'      => 5,
				'menu_icon'			 => 'dashicons-editor-help',
				'public'             => true,
				'publicly_queryable' => true,
				'show_ui'            => true,
				'show_in_menu'       => true,
				'query_var'          => true,
				'capability_type'    => 'post',
				'has_archive'        => true,
				'hierarchical'       => false,
				'supports'           => array( 'title', 'author', 'thumbnail', 'excerpt' ),
			);

			register_post_type( 'wp_quiz', $args );

			if ( false === get_option( 'wp_quiz_pro_version' ) ) {
				flush_rewrite_rules();
				update_option( 'wp_quiz_pro_version', WP_QUIZ_PRO_VERSION );
			}
		}

		/**
		 * Shortcode used to display quiz
		 *
		 * @return string HTML output of the shortcode
		 */
		public function register_shortcode( $atts ) {

			if ( ! isset( $atts['id'] ) ) {
				return false;
			}

			// we have an ID to work with
			$quiz = get_post( $atts['id'] );

			// check if ID is correct
			if ( ! $quiz || 'wp_quiz' !== $quiz->post_type ) {
				return "<!-- wp_quiz {$atts['id']} not found -->";
			}

			// lets go
			$this->set_quiz( $atts['id'] );
			$this->quiz->enqueue_scripts();

			return $this->quiz->render_public_quiz();
		}

		/**
		 * Set the current quiz
		 */
		public function set_quiz( $id ) {
			$quiz_type = get_post_meta( $id, 'quiz_type', true );
			$quiz_type = str_replace( '_quiz', '', $quiz_type );
			$quiz_type = 'WP_Quiz_Pro_' . ucwords( $quiz_type ) . '_Quiz';
			$this->quiz = new $quiz_type( $id );
		}

		/**
		 * [create_quiz_page description]
		 * @param  [type] $content [description]
		 * @return [type]          [description]
		 */
		public function create_quiz_page( $content ) {

			global $post;

			if ( 'wp_quiz' !== $post->post_type ) {
				return $content;
			}

			if ( ! is_single() ) {
				return $content;
			}

			$quiz_html = $this->register_shortcode( array( 'id' => $post->ID ) );

			return $quiz_html . $content;
		}

		/**
		 * [save_quiz_results description]
		 * @return [type] [description]
		 */
		public function save_quiz_results() {

			if ( ! wp_verify_nonce( $_POST['_nonce'], 'ajax-quiz-content' ) ) {
				return;
			}

			$correct   = isset( $_POST['correct'] ) ? absint( $_POST['correct'] ) : 0;
			$rid       = isset( $_POST['rid'] ) ? $_POST['rid'] : '';
			$pid       = absint( $_POST['pid'] );
			$type      = sanitize_text_field( $_POST['type'] );
			$user_ip   = $this->get_ip();
			$user_id   = get_current_user_id();
			$user_info = get_userdata( $user_id );
			$username  = is_user_logged_in() ? $user_info->user_login : 'Guest';
			$result    = '';

			$results = get_post_meta( $pid, 'results', true );

			if ( 'trivia' === $type ) {
				$rid = '';
				foreach ( $results as $result ) {
					if ( $result['min'] <= $correct && $result['max'] >= $correct ) {
						$result = $result['title'];
						break;
					}
				}
			} else if ( 'personality' === $type ) {
				for ( $i = 0; $i < count( $results ); $i++ ) {
					if ( $i == $rid ) {
						$result = $results[ $i ]['title'];
						break;
					}
				}
			} else if ( 'swiper' === $type ) {
				$results = $_POST['results'];
				$questions 	= get_post_meta( $pid, 'questions', true );
				foreach ( $questions as $q_key => $question ) {
					foreach ( $results as $key => $result ) {
						if ( $question['uid'] == $key ) {
							if ( '0' == $result ) {
								$questions[ $q_key ]['votesDown'] = $question['votesDown'] + 1;
							} else {
								$questions[ $q_key ]['votesUp'] = $question['votesUp'] + 1;
							}
						}
					}
				}
				update_post_meta( $pid, 'questions', $questions );
				$result = '';
			}

			// Save Result
			$settings = get_option( 'wp_quiz_pro_default_settings' );
			if ( isset( $settings['players_tracking'] ) && 1 === $settings['players_tracking'] ) {
				global $wpdb;
				$wpdb->insert(
					$wpdb->prefix . 'wp_quiz_players',
					array(
						'pid'               => $pid,
						'date'       		=> date( 'Y-m-d', time() ),
						'user_ip'           => $user_ip,
						'username'          => $username,
						'correct_answered'  => $correct,
						'result'            => $result,
						'quiz_type'         => $type,
					),
					array( '%d', '%s', '%s', '%s', '%d', '%s', '%s' )
				);
			}

			die( 'SUCCESS!' );
		}

		/**
		 * [save_quiz_user_info description]
		 * @return [type] [description]
		 */
		public function save_quiz_user_info() {

			if ( ! wp_verify_nonce( $_POST['_nonce'], 'ajax-quiz-content' ) ) {
				return;
			}

			$output = array( 'status' => 1 );

			if ( is_email( $_POST['email'] ) ) {

				global $wpdb;
				$username	= sanitize_text_field( $_POST['username'] );
				$email		= sanitize_email( $_POST['email'] );
				$pid		= absint( $_POST['pid'] );

				$this->subscribe_user( $pid, $username, $email );
				$result = $wpdb->get_results( "SELECT * FROM {$wpdb->prefix}wp_quiz_emails WHERE email = '" . $email . "'" );

				if ( ! $result ) {
					//Save info
					$wpdb->insert(
						$wpdb->prefix . 'wp_quiz_emails',
						array(
							'pid'      => $pid,
							'username' => $username,
							'email'    => $email,
							'date'     => date( 'Y-m-d', time() ),
						),
						array( '%d', '%s', '%s', '%s' )
					);
				}

				$output['status'] = 2;
			}

			wp_send_json( $output );
		}

		/**
		 * [save_quiz_fb_user_info description]
		 * @return [type] [description]
		 */
		public function save_quiz_fb_user_info() {

			if ( ! wp_verify_nonce( $_POST['_nonce'], 'ajax-quiz-content' ) ) {
				return;
			}

			$output = array( 'status' => 1 );
			if ( ! empty( $_POST['user'] ) ) {
				global $wpdb;

				$user = $_POST['user'];
				$result = $wpdb->get_row( "SELECT * FROM {$wpdb->prefix}wp_quiz_fb_users WHERE uid = '" . $user['id'] . "'" );

				if ( ! $result ) {
					$wpdb->insert(
						$wpdb->prefix . 'wp_quiz_fb_users',
						array(
							'uid'			=> absint( $user['id'] ),
							'email'			=> isset( $user['email'] ) ? $user['email'] : '',
							'first_name'	=> $user['first_name'],
							'last_name'		=> $user['last_name'],
							'gender'		=> isset( $user['gender'] ) ? $user['gender'] : '',
							'picture'		=> isset( $user['picture'] ) ? $user['picture'] : '',
							'friends'		=> isset( $user['friends'] ) ? serialize( $user['friends'] ) : '',
							'created_at'	=> date( 'Y-m-d', time() ),
							'updated_at'	=> date( 'Y-m-d', time() ),
						),
						array( '%d', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s' )
					);

					$user['insert_id'] = $wpdb->insert_id;
				} else {
					$user['insert_id'] = $result->id;
				}

				if ( 'user' === $_POST['profile'] ) {
					$return = $this->generate_result_user_image( $_POST['pid'], $user );
				} else {
					$return = $this->generate_result_friend_image( $_POST['pid'], $user );
				}

				if ( ! empty( $return['src'] ) ) {
					$output['src'] = $return['src'];
					$output['desc'] = $return['desc'];
					$output['key'] = $return['key'];
					$output['status'] = 2;
				} else {
					$output['error'] = $return['error'];
				}
			}

			wp_send_json( $output );
		}

		/**
		 * [generate_result_user_image description]
		 * @param  [type] $post_id [description]
		 * @param  [type] $user    [description]
		 * @return [type]          [description]
		 */
		public function generate_result_user_image( $post_id, $user ) {
			global $wpdb;

			$return		= array();
			$results	= get_post_meta( $post_id, 'results', true );

			if ( extension_loaded( 'imagick' ) && ! empty( $results ) ) {

				$index 	= array_rand( $results );
				$result	= $results[ $index ];
				$result['key'] = $index;

				$play = $wpdb->get_row( "SELECT * FROM {$wpdb->prefix}wp_quiz_fb_plays WHERE user_id = '" . $user['insert_id'] . "' AND pid = '" . $post_id . "'" );

				if ( ! $play ) {
					$wpdb->insert(
						$wpdb->prefix . 'wp_quiz_fb_plays',
						array(
							'user_id'	=> absint( $user['insert_id'] ),
							'pid'		=> absint( $post_id ),
						),
						array( '%d', '%d' )
					);
				}

				$names = array(
					'user_first_name'	=> $user['first_name'],
					'user_last_name'	=> $user['last_name'],
					'friend_first_name'	=> '',
					'friend_last_name'	=> '',
				);

				$profile = 'https://graph.facebook.com/' . $user['id'] . '/picture?width=320&height=320';
				$profile = $this->get_redirect_url( $profile );

				$data 	= $this->generate_fb_result( $post_id, $result, $profile, $names );
				$return	= $data;
			}

			return $return;
		}

		public function generate_result_friend_image( $post_id, $user ) {
			global $wpdb;

			$return 	= array();
			$results 	= get_post_meta( $post_id, 'results', true );

			if ( extension_loaded( 'imagick' ) && ! empty( $results ) && ! empty( $user['friends'] ) ) {

				$index 	= array_rand( $results );
				$result	= $results[ $index ];
				$result['key'] = $index;

				$index_2	= array_rand( $user['friends'] );
				$friend		= $user['friends'][ $index_2 ];

				$play = $wpdb->get_row( "SELECT * FROM {$wpdb->prefix}wp_quiz_fb_plays WHERE user_id = '" . $user['insert_id'] . "' AND pid = '" . $post_id . "'" );

				if ( ! $play ) {
					$wpdb->insert(
						$wpdb->prefix . 'wp_quiz_fb_plays',
						array(
							'user_id'	=> absint( $user['insert_id'] ),
							'pid'		=> absint( $post_id ),
						),
						array( '%d', '%d' )
					);
				}

				$profile = 'https://graph.facebook.com/' . $friend['id'] . '/picture?width=320&height=320';
				$profile = $this->get_redirect_url( $profile );

				$friend_name = explode( ' ', $friend['name'] );

				$names = array(
					'user_first_name'	=> $user['first_name'],
					'user_last_name'	=> $user['last_name'],
					'friend_first_name'	=> $friend_name[0],
					'friend_last_name'	=> $friend_name[1],
				);

				$data 	= $this->generate_fb_result( $post_id, $result, $profile, $names );
				$return	= $data;
			}

			return $return;
		}

		public function generate_fb_result( $post_id, $result, $profile, $names ) {

			$return = array( 'src' => '', 'desc' => '', 'error' => '' );

			try {

				$options 	= get_option( 'wp_quiz_pro_default_settings' );
				$settings	= get_post_meta( $post_id, 'settings', true );
				$find 		= array( '%%nomeusuario%%', '%%sobrenome%%', '%%nomeamigo%%', '%%sobrenomeamigo%%' );
				$replace 	= array( $names['user_first_name'], $names['user_last_name'], $names['friend_first_name'], $names['friend_last_name'] );
				$title 		= str_replace( $find, $replace, $result['title'] );
				$desc		= str_replace( $find, $replace, $result['desc'] );
				$upload_dir = wp_upload_dir();

				// Load images
				$profile = new Imagick( $profile );
				$profile->resizeImage( $result['proImageWidth'], $result['proImageHeight'], imagick::FILTER_LANCZOS, 0.9 );
				$profile->roundCorners( $result['imageRadius'], $result['imageRadius'] );

				// Create new image from result
				$output = new Imagick( str_replace( $upload_dir['baseurl'], $upload_dir['basedir'], $result['image'] ) );
				$output->compositeImage( $profile, Imagick::COMPOSITE_DEFAULT, $result['pos_x'], $result['pos_y'] );

				// Annotate it
				if ( ! empty( $title ) ) {

					$draw = new ImagickDraw();
					$draw->setFillColor( $settings['title_color'] );
					$draw->setGravity( 1 );
					$draw->setFontSize( $settings['title_size'] );

					if ( isset( $options['defaults']['external_font'] ) && ! empty( $options['defaults']['external_font'] ) ) {
						$external_font = str_replace( home_url('/'), '', $options['defaults']['external_font'] );
						$draw->setFont( '../' . $external_font );
					} else {
						$draw->setFontFamily( $settings['title_font'] );
					}

					list( $lines, $line_height ) = $this->word_wrap_annotation( $output, $draw, $title, $result['titleImageWidth'] );

					for ( $i = 0; $i < count( $lines ); $i++ ) {
						$output->annotateImage( $draw, $result['pos_title_x'],  $result['pos_title_y'] + $i * $line_height, 0, $lines[ $i ] );
					}
				}

				// Save to new image
				$upload_dir['basedir'] = $upload_dir['basedir'] . '/wp_quiz-result-images';
				$upload_dir['baseurl'] = $upload_dir['baseurl'] . '/wp_quiz-result-images';
				$output_name = 'image-' . rand( 0, 100000 ) . '.png';
				$output->writeImage(  $upload_dir['basedir'] . '/' . $output_name  );

				// Clean up
				$profile->destroy();
				$output->destroy();

				$return['src']	= $upload_dir['baseurl'] . '/' . $output_name;
				$return['desc']	= $desc;
				$return['key']	= $result['key'];

			} catch ( Exception $ex ) {
				$return['error'] = $ex->getMessage();
			}

			return $return;
		}

		public function get_redirect_url( $url ) {

			$response = wp_remote_head( $url );
			$redirect_url = wp_remote_retrieve_header( $response, 'location' );

			return $redirect_url ? $redirect_url : $url;
		}

		public function word_wrap_annotation( $image, $draw, $text, $max_width ) {

			$words = preg_split( '%\s%', $text, -1, PREG_SPLIT_NO_EMPTY );
			$lines = array();
			$i = 0;
			$line_height = 0;

			while ( count( $words ) > 0 ) {
				$metrics = $image->queryFontMetrics( $draw, implode( ' ', array_slice( $words, 0, ++$i ) ) );
				$line_height = max( $metrics['textHeight'], $line_height );

				if ( $metrics['textWidth'] > $max_width || count( $words ) < $i ) {
					if ( 1 === $i ) {
						$i++;
					}

					$lines[] = implode( ' ', array_slice( $words, 0, --$i ) );
					$words = array_slice( $words, $i );
					$i = 0;
				}
			}

			return array( $lines, $line_height );
		}

		public function subscribe_user( $id, $name, $email ) {

			$settings 	= get_post_meta( $id, 'settings', true );
			$options 	= get_option( 'wp_quiz_pro_default_settings' );
			if ( '1' === $settings['force_action'] ) {
				if ( '1' === $options['mail_service'] ) {
					$this->subscribe_mailchimp( $options, $name, $email );
				} else if ( '2' === $options['mail_service'] ) {
					$this->subscribe_getresponse( $options, $name, $email );
				} else if ( '3' === $options['mail_service'] ) {
					$this->subscribe_aweber( $options, $name, $email );
				}
			}
		}

		private function subscribe_aweber( $options, $name, $email ) {

			// check for valid data
			if ( empty( $email ) ) {
				wp_send_json( array(
					'success' => false,
					'error' => esc_html__( 'No email address found.', 'wp-quiz-pro' ),
				) );
			}

			if ( ! filter_var( $email, FILTER_VALIDATE_EMAIL ) ) {
				wp_send_json( array(
					'success' => false,
					'error' => esc_html__( 'Not a valid email address.', 'wp-quiz-pro' ),
				) );
			}

			// Call service subscription method
			try {
				$service = new WP_Quiz_Pro_Subscription_Aweber();
				$list_id		= $options['aweber']['listid'];
				$status = $service->subscribe( $name, $email, $list_id );

				wp_send_json(array(
					'success' => true,
					'status' => $status['status'],
				));
			} catch ( Exception $e ) {
				wp_send_json(array(
					'success' => false,
					'error' => $e->getMessage(),
				));
			}
		}

		private function subscribe_mailchimp( $options, $name, $email ) {

			$mc_api_key		= $options['mailchimp']['api_key'];
			$mc_list_id		= $options['mailchimp']['list_id'];
			$double_optin	= apply_filters( 'wp_quiz_mailchimp_double_notification', false );

			$vendor_path = $this->get_vendor_path();

			if ( $email && null !== $mc_api_key && null !== $mc_list_id ) {

				try {
					if ( ! class_exists( 'Mailchimp' ) ) {
						require_once( $vendor_path . '/Mailchimp.php' );
					}

					$list = new Mailchimp_Lists( new Mailchimp( $mc_api_key ) );
					$merge_vars = null;
					if ( $name ) {
						$fname = $name;
						$lname = '';
						if ( $space_pos = strpos( $name, ' ' ) ) {
							$fname = substr( $name, 0, $space_pos );
							$lname = substr( $name, $space_pos );
						}
						$merge_vars = array( 'FNAME' => $fname, 'LNAME' => $lname );
					}
					$list->subscribe( $mc_list_id, array( 'email' => $email ), $merge_vars, 'html', (bool) $double_optin, true );

				} catch ( Exception $ex ) {}
			}
		}

		private function subscribe_getresponse( $options, $name, $email ) {

			$gr_api_key = $options['getresponse']['api_key'];
			$gr_list_id = $options['getresponse']['campaign_name'];

			$vendor_path = $this->get_vendor_path();

			if ( $email && null !== $gr_api_key && null !== $gr_list_id ) {
				try {
					if ( ! class_exists( 'GetResponse' ) ) {
						require_once( $vendor_path . '/getresponse.php' );
					}

					$api = new GetResponse( $gr_api_key );
					$campaign_ame		= $gr_list_id;
					$subscriber_name		= $name;
					$subscriber_email	= $email;

					$result 		= $api->getCampaigns( 'EQUALS', $campaign_ame );
					$campaigns		= array_keys( (array) $result );
					$campaign_id	= array_pop( $campaigns );

					$api->addContact( $campaign_id, $subscriber_name, $subscriber_email );
				} catch ( Exception $ex ) {}
			}
		}

		public function get_vendor_path() {

			return plugin_dir_path( __FILE__ ) . 'vendor';
		}

		public function check_image_file() {

			$output = array( 'status' => 1 );
			$check = false;
			if ( @getimagesize( $_POST['url'] ) ) {
				$check = true;
			}

			$output['check'] = $check;
			wp_send_json( $output );
		}

		public function check_video_file() {

			$output = array( 'status' => 1 );
			$check = false;
			$id = $_POST['video_id'];
			$url = "http://www.youtube.com/oembed?url=http://www.youtube.com/watch?v=$id&format=json";
			$headers = get_headers( $url );
			if ( '404' !== substr( $headers[0], 9, 3 ) ) {
				$check = true;
			}

			$output['check'] = $check;
			wp_send_json( $output );
		}

		public static function activate_plugin() {

			// Don't activate on anything less than PHP 5.4.0 or WordPress 3.4
			if ( version_compare( PHP_VERSION, '5.4.0', '<' ) || version_compare( get_bloginfo( 'version' ), '3.4', '<' ) || ! function_exists( 'spl_autoload_register' ) ) {
				require_once ABSPATH . 'wp-admin/includes/plugin.php';
				deactivate_plugins( basename( __FILE__ ) );
				wp_die( __( 'Testes Pop requires PHP version 5.4.0 with spl extension or greater and WordPress 3.4 or greater.', 'wp-quiz-pro' ) );
			}

			//Dont't activate if wp quiz is active
			if ( defined( 'WP_QUIZ_VERSION' ) ) {
				deactivate_plugins( basename( __FILE__ ) );
				wp_die( __( 'Please deactivate WP Quiz plugin first to use the Premium features!', 'wp-quiz-pro' ) );
			}

			include( 'inc/activate-plugin.php' );

		}

		public function get_ip() {

			//Just get the headers if we can or else use the SERVER global
			if ( function_exists( 'apache_request_headers' ) ) {
				$headers = apache_request_headers();
			} else {
				$headers = $_SERVER;
			}

			//Get the forwarded IP if it exists
			if ( array_key_exists( 'X-Forwarded-For', $headers ) && filter_var( $headers['X-Forwarded-For'], FILTER_VALIDATE_IP, FILTER_FLAG_IPV4 ) ) {
				$the_ip = $headers['X-Forwarded-For'];
			} else if ( array_key_exists( 'HTTP_X_FORWARDED_FOR', $headers ) && filter_var( $headers['HTTP_X_FORWARDED_FOR'], FILTER_VALIDATE_IP, FILTER_FLAG_IPV4 ) ) {
				$the_ip = $headers['HTTP_X_FORWARDED_FOR'];
			} else {
				$the_ip = filter_var( $_SERVER['REMOTE_ADDR'], FILTER_VALIDATE_IP, FILTER_FLAG_IPV4 );
			}
			return $the_ip;

		}

		public function dismiss_imagick_notice() {
			add_option( 'wp_dismiss_imagick_notice', 'true' );
		}

		public function dismiss_gdlibrary_notice() {
			add_option( 'wp_dismiss_gdlibrary_notice', 'true' );
		}

		public function wp_quiz_pro_get_debug_log() {
			$page = new WP_Quiz_Pro_Page_Support();
			$page->get_debug_log();
		}

		public function fb_share_fix() {

			$data = array_map( 'urldecode', $_GET );
			$result = get_post_meta( $data['id'], 'results', true );
			$result = isset( $result[ $data['rid'] ] ) ? $result[ $data['rid'] ] : array();

			// Picture
			if ( 'r' === $data['pic'] ) {
				$data['source'] = $result['image'];
			} elseif ( 'f' === $data['pic'] ) {
				$data['source'] = wp_get_attachment_url( get_post_thumbnail_id( $data['id'] ) );
			} elseif ( ( substr( $data['pic'], 0, 6 ) === 'image-' ) ) {
			    $upload_dir = wp_upload_dir();
				$upload_dir['baseurl'] = $upload_dir['baseurl'] . '/wp_quiz-result-images';
				$data['source'] = $upload_dir['baseurl'] . '/' . $data['pic'] . '.png';
			} else {
				$data['source'] = false;
			}

			// Description
			if ( 'r' === $data['desc'] ) {
				$data['description'] = $result['desc'];
			} elseif ( 'e' === $data['desc'] ) {
				$data['description'] = get_post_field( 'post_excerpt', $data['id'] );
			} else {
				$data['description'] = false;
			}

			if ( $data['description'] ) {

			    $first = array( '%%nomeusuario%%', '%%nomeamigo%%' );
			    $last = array( '%%sobrenome%%', '%%sobrenomeamigo%%' );

			    $data['description'] = str_replace( $first, $data['nf'], $data['description'] );
			    $data['description'] = str_replace( $last, $data['nl'], $data['description'] );
			}

			$settings = get_option( 'wp_quiz_pro_default_settings' );
			$url = ( is_ssl() ? 'https' : 'http' ) . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";

			global $post;
			$pid  = $post ? $post->ID : $data['id'];
			$original_url = get_permalink( $pid );
			?>
			<html>
				<head>
					<title><?php wp_title( '' ) ?></title>
					<meta property="fb:app_id" content="<?php echo $settings['defaults']['fb_app_id'] ?>">
					<meta property="og:type" content="website">
					<meta name="twitter:card" content="summary_large_image">
					<meta property="og:url" content="<?php echo esc_url( $url ); ?>">
					<?php if ( ! empty( $data['text'] ) ) : ?>
					<meta property="og:title" content="<?php echo get_the_title( $pid ) ?> - <?php echo esc_attr( $data['text'] ); ?>">
					<meta property="twitter:title" content="<?php echo get_the_title( $pid ) ?> - <?php echo esc_attr( $data['text'] ); ?>">
					<?php endif; ?>
					<?php if ( ! empty( $data['source'] ) ) : ?>
					<meta property="og:image" content="<?php echo esc_url( $data['source'] ); ?>">
					<meta property="twitter:image" content="<?php echo esc_url( $data['source'] ); ?>">
						<?php list( $img_width, $img_height ) = getimagesize( $data['source'] ); ?>
						<?php if ( isset( $img_width ) && $img_width ) : ?>
						<meta property="og:image:width" content="<?php echo $img_width ?>">
						<?php endif; ?>
						<?php if ( isset( $img_height ) && $img_height ) : ?>
						<meta property="og:image:height" content="<?php echo $img_height ?>">
						<?php endif; ?>
					<?php endif; ?>
					<?php if ( ! empty( $data['description'] ) ) : ?>
					<meta property="og:description" content="<?php echo esc_attr( $data['description'] ); ?>">
					<meta property="twitter:description" content="<?php echo esc_attr( $data['description'] ); ?>">
					<?php endif; ?>
					<meta http-equiv="refresh" content="0;url=<?php echo esc_url( $original_url ); ?>">
				</head>
			<body>
				Redirecting please wait....
			</body>
			</html>
			<?php
			exit;
		}

		/**
		 * [inline_script description]
		 * @return [type] [description]
		 */
		public function inline_script() {
			$settings = get_option( 'wp_quiz_pro_default_settings' );
			?>
			<script>
			var quizSiteUrl = '<?php echo home_url( '/' ) ?>';
			<?php if ( ! empty( $settings['analytics']['tracking_id'] ) ) { ?>
				(function(i,s,o,g,r,a,m) {i['GoogleAnalyticsObject']=r;i[r]=i[r]||function() {
				(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
				m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
				})(window,document,'script','//www.google-analytics.com/analytics.js','ga');

				ga('create', '<?php echo $settings['analytics']['tracking_id'] ?>', 'auto');
				ga('send', 'pageview');
			<?php } ?>
			<?php if ( ! empty( $settings['defaults']['fb_app_id'] ) ) { ?>
				window.fbAsyncInit = function() {
					FB.init({
						appId    : '<?php echo $settings['defaults']['fb_app_id'] ?>',
						xfbml    : true,
						version  : 'v2.9'
					});

					FB.getLoginStatus(function( response ) {
						getLogin( response );
					});
				};
				
				(function(d, s, id) {
					var js, fjs = d.getElementsByTagName(s)[0];
					if (d.getElementById(id)) {return;}
					js = d.createElement(s); js.id = id;
					js.src = "//connect.facebook.net/pt_BR/sdk.js";
					fjs.parentNode.insertBefore(js, fjs);
				}(document, 'script', 'facebook-jssdk'));
			<?php } ?>
			</script>

			<!-- Codigo que exibe URL no topo da página -->
			<?php echo $settings['defaults']['fb_app_id2'] ?>
			<!-- fim Codigo que exibe URL no topo da página -->

			<?php
			if ( is_singular( array( 'wp_quiz' ) ) && isset( $settings['defaults']['share_meta'] ) && 1 === $settings['defaults']['share_meta'] ) {
				global $post, $wpseo_og;
				$twitter_desc = $og_desc = str_replace( array( "\r", "\n" ), '', strip_tags( $post->post_excerpt ) );
				if ( defined( 'WPSEO_VERSION' ) ) {
					remove_action( 'wpseo_head', array( $wpseo_og, 'opengraph' ), 30 );
					remove_action( 'wpseo_head', array( 'WPSEO_Twitter', 'get_instance' ), 40 );
					//use description from yoast
					$twitter_desc 	= get_post_meta( $post->ID, '_yoast_wpseo_twitter-description', true );
					$og_desc		= get_post_meta( $post->ID, '_yoast_wpseo_opengraph-description', true );
				}
				?>
				<meta name="twitter:title" content="<?php echo get_the_title(); ?>">
				<meta name="twitter:description" content="<?php echo $twitter_desc; ?>">
				<meta name="twitter:domain" content="<?php echo esc_url( site_url() ); ?>">
				<meta property="og:url" content="<?php the_permalink(); ?>" />
				<meta property="og:title" content="<?php echo get_the_title(); ?>" />
				<meta property="og:description" content="<?php echo $og_desc; ?>" />
				<?php
				if ( has_post_thumbnail() ) {
					$thumb_id = get_post_thumbnail_id();
					$thumb_url_array = wp_get_attachment_image_src( $thumb_id, 'full', true );
					$thumb_url = $thumb_url_array[0];
					?>
					<meta name="twitter:card" content="summary_large_image">
					<meta name="twitter:image:src" content="<?php echo $thumb_url; ?>">
					<meta property="og:image" content="<?php echo $thumb_url; ?>" />
					<meta itemprop="image" content="<?php echo $thumb_url; ?>">
				<?php
				}
			}
		}

		public function embeded_output() {

			if ( ! isset( $_GET['wp_quiz_id'] ) ) {
				return;
			}

			$qid		= absint( $_GET['wp_quiz_id'] );
			$quiz_html	= $this->register_shortcode( array( 'id' => $qid ) );
			$settings	= get_post_meta( $qid, 'settings', true );
			if ( empty( $quiz_html ) ) {
				return;
			}
			?>
				<link rel='stylesheet' href='<?php echo WP_QUIZ_PRO_ASSETS_URL . 'css/main.css'; ?>' type='text/css' media='all' />
				<link rel='stylesheet' href='<?php echo WP_QUIZ_PRO_ASSETS_URL . 'css/transition.min.css'; ?>' type='text/css' media='all' />
				<link rel='stylesheet' href='<?php echo WP_QUIZ_PRO_ASSETS_URL . 'css/embed.min.css'; ?>' type='text/css' media='all' />
				<style>
					.wq_embedToggleQuizCtr{ display: none; }
				</style>
			<?php
			if ( 'traditional' === $settings['skin'] ) {
				?>
					<link rel='stylesheet' href='<?php echo WP_QUIZ_PRO_ASSETS_URL . 'css/traditional-skin.css'; ?>' type='text/css' media='all' />
				<?php
			} else if ( 'flat' === $settings['skin'] ) {
				?>
					<link rel='stylesheet' href='<?php echo WP_QUIZ_PRO_ASSETS_URL . 'css/flat-skin.css'; ?>' type='text/css' media='all' />
				<?php
			}
			$this->inline_script();
			?>
				<script>
					var wq_l10n = {"correct": "Correct !", "wrong": "Wrong !","captionTrivia":"You got %%score%% out of %%total%%","captionTriviaFB":"I got %%score%% out of %%total%%, and you?","youVoted":"You voted","nonce": "<?php echo wp_create_nonce( 'ajax-quiz-content' ) ?>"};
				</script>
			<?php

			echo '<div class="wq_embed">' . $quiz_html . '</div>';
			?>
				<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
				<script src="<?php echo WP_QUIZ_PRO_ASSETS_URL . 'js/embed.min.js'; ?>"></script>
				<script src="<?php echo WP_QUIZ_PRO_ASSETS_URL . 'js/transition.min.js'; ?>"></script>
				<script src="<?php echo WP_QUIZ_PRO_ASSETS_URL . 'js/jquery.flip.min.js'; ?>"></script>
				<script src="<?php echo WP_QUIZ_PRO_ASSETS_URL . 'js/hammer.min.js'; ?>"></script>
				<script src="<?php echo WP_QUIZ_PRO_ASSETS_URL . 'js/dynamics.min.js'; ?>"></script>
				<script src="<?php echo WP_QUIZ_PRO_ASSETS_URL . 'js/jquery.jTinder.min.js'; ?>"></script>
				<script src="<?php echo WP_QUIZ_PRO_ASSETS_URL . 'js/main.min.js'; ?>"></script>
			<?php
			die();
		}

		/**
		 * [connect_aweber description]
		 * @return [type] [description]
		 */
		public function connect_aweber() {

			// check for data
			$aweber_code = isset( $_REQUEST['aweber_code'] ) ? $_REQUEST['aweber_code'] : array();
			if ( empty( $aweber_code ) ) {
				wp_send_json( array(
					'success' => false,
					'error' => esc_html__( 'No aweber authorization code found.', 'wp-quiz-pro' ),
				) );
			}

			try {
				$service = new WP_Quiz_Pro_Subscription_Aweber();
				$data = $service->connect( $aweber_code );

				wp_send_json(array(
					'success' => true,
					'data' => $data,
				));
			} catch ( Exception $e ) {
				wp_send_json(array(
					'success' => false,
					'error' => $e->getMessage(),
				));
			}
		}
	}

	/**
	 * Main instance of WP_Quiz_Pro_Plugin.
	 *
	 * Returns the main instance of WP_Quiz_Pro_Plugin to prevent the need to use globals.
	 *
	 * @return WP_Quiz_Pro_Plugin
	 */

	function wp_quiz_pro() {
		return WP_Quiz_Pro_Plugin::get_instance();
	}

endif;

add_action( 'plugins_loaded', 'wp_quiz_pro', 10 );
register_activation_hook( __FILE__, array( 'WP_Quiz_Pro_Plugin', 'activate_plugin' ) );

Obrigado por sua ajuda irmão!

Share this post


Link to post
Share on other sites

São 2 arquivos pra alterar, single.php e esse segundo que você enviou que foi importante pra encontrar o problema também, segue os códigos aí abaixo.

 

Antes de fazer a ateração:

Obs1: Faça o backup dos dois arquivo

Obs2: As 2 alterações que fiz estão marcadas entre as tags /////// ALTEREI AQUI ////// pra facilitar pra você ver onde alterei.

Obs3: É um teste, não é uma alteração definitiva, é só pra atestar onde ta o problema.

 

Faz o teste aí e informa se foi.

 

Troque o código inteiro do seu single.php por esse:

<?php
/**
 * The template for displaying all single posts
 *
 * @link https://developer.wordpress.org/themes/basics/template-hierarchy/#single-post
 *
 * @package sidebar
 */
get_header(); 

if ( ! is_active_sidebar( 'sidebar-main' ) ) {
 	$sidebar_col_class = "col-lg-8 col-md-8 col-xs-12 col-sm-12 col-lg-offset-2 col-md-offset-2";
}
else {
 	$sidebar_col_class = "col-lg-8 col-md-8 col-xs-12 col-sm-12";
}

?>

<?php while ( have_posts() ) : the_post(); //main loop ?>  
<!-- Comentários facebook -->                              
<div id="fb-root"></div>
<script>(function(d, s, id) {
  var js, fjs = d.getElementsByTagName(s)[0];
  if (d.getElementById(id)) return;
  js = d.createElement(s); js.id = id;
  js.src = 'https://connect.facebook.net/pt_BR/sdk.js#xfbml=1&version=v3.0&appId=&autoLogAppEvents=1';
  fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));</script>
<!-- Fim comentários facebook -->


<div id="content" class="site-content">
	<!-- Anúncio topo - Página do teste -->
	<div class="banner-topo">
		<?php	if ( is_active_sidebar('sidebar-topo') ) { dynamic_sidebar('sidebar-topo');	}	?>
	</div>
	<!-- Fim Anúncio topo - Página do teste -->
	</div>
	<div class="container">
		<div class="row" style="margin-bottom:15px;">
			<div class="col-lg-9 col-md-8 col-xs-12 col-sm-12 nopadding">
				<div class="conteudo-single">
					<article id="post-<?php the_ID(); ?>" <?php post_class('single-post-wrapper'); ?>> 
						<div id="primary" class="content-area">
							<main id="main" class="site-main">
								<?php if ( !has_post_thumbnail() ) { ?>
								<div class="no-featuredimage-header">
								<p class="category">
									<?php the_category( ', ' ); ?>                   
								</p>                    
								<h1 class="entry-title"><?php the_title( '', '' ); ?></h1>                    
									<div class="entry-meta">
										<ul>
										<li><?php echo get_the_date(); ?></li>
										<li><?php the_author(); ?></li>
										<li><?php comments_number( 'no responses', 'one response', '% responses' ); ?>.</li>
										</ul>
									</div>
									<div class="clearfix"></div>
								</div>
								<?php } ?>
								<?php get_template_part( 'template-parts/content', 'single' ); ?> 
							</main><!-- #main -->
						</div><!-- #primary -->
						<!-- Anúncio Interno - Página do teste -->
						<center>
							<div class="sidebar-likebutton" style="margin:auto; width:90px; margin-bottom:10px;">
								<center><?php	if ( is_active_sidebar('sidebar-likebutton') ) {dynamic_sidebar('sidebar-likebutton');}?></center>
							</div>
							<div class="sidebar-interna" style="margin-bottom:10px;">
								<?php	if ( is_active_sidebar('sidebar-interna') ) {dynamic_sidebar('sidebar-interna');}?>
							</div>
						</center>
						<!-- Fim Anúncio Interno - Página do teste -->
					</article><!-- #post-<?php the_ID(); ?> -->
<!-- 
////////////////////////////////////// ALTEREI AQUI ////////////////////////////////////
////////////////////////////////////// ALTEREI AQUI ////////////////////////////////////
////////////////////////////////////// ALTEREI AQUI ////////////////////////////////////
////////////////////////////////////// ALTEREI AQUI ////////////////////////////////////
////////////////////////////////////// ALTEREI AQUI ////////////////////////////////////
////////////////////////////////////// ALTEREI AQUI ////////////////////////////////////
 -->
					<!-- inicio - testando exibição da função URL Facebook -->
					<?php echo $get_facebook_url ?>

					<?php echo $get_facebook_url ?>
					<!-- fim - testando exibição da função URL Facebook -->
<!-- 
////////////////////////////////////// ALTEREI AQUI ////////////////////////////////////
////////////////////////////////////// ALTEREI AQUI ////////////////////////////////////
////////////////////////////////////// ALTEREI AQUI ////////////////////////////////////
////////////////////////////////////// ALTEREI AQUI ////////////////////////////////////
////////////////////////////////////// ALTEREI AQUI ////////////////////////////////////
////////////////////////////////////// ALTEREI AQUI ////////////////////////////////////
 -->
				</div><!-- .conteudo-single -->

					<!-- Inicío Configuração Comentários -->
				<div class="comentarios-single">
					<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.2.js"></script>
					<script>
						$(document).ready(function() {
							$('.nav-toggle').click(function(){
								//get collapse content selector
								var collapse_content_selector = $(this).attr('href');					
								
								//make the collapse content to be shown or hide
								var toggle_switch = $(this);
								$(collapse_content_selector).toggle(function(){
									if($(this).css('display')=='none'){
										toggle_switch.html('<div class="coment-pai"><div class="coment-left"><i class="fa fa-comment" aria-hidden="true"></i>&nbsp;&nbsp;Deixe seu comentário!</div><div class="coment-right"><i class="fa fa-arrow-down" aria-hidden="true"></i></div></div>');//change the button label to be 'Show'
									}else{
										toggle_switch.html('<div class="coment-pai"><div class="coment-left"><i class="fa fa-comment" aria-hidden="true"></i>&nbsp;&nbsp;Deixe seu comentário!</div><div class="coment-right"><i class="fa fa-arrow-up" aria-hidden="true"></i></div></div>');//change the button label to be 'Hide'
									}
								});
							});
						});	
					</script>
					<section class="round-border">
						<div>
							<button class="nav-toggle" href="#collapse1" ><div class="coment-pai"><div class="coment-left"><i class="fa fa-comment" aria-hidden="true"></i>&nbsp;&nbsp;Deixe seu comentário!</div><div class="coment-right"><fb:comments-count href=<?php the_permalink();?>>0</fb:comments-count>&nbsp;&nbsp;<i class="fa fa-arrow-down" aria-hidden="true"></i></div></div></button>
						</div>
						<div id="collapse1" style="display:none">
							<div class="fb-comments" data-href="<?php the_permalink(); ?>" data-width="100%" data-numposts="6"></div>
						</div>
					</section>
					<!-- Fim Configuração Comentários -->
				</div><!-- Fim comentarios-single -->
			</div><!-- Fim col-lg-9 col-md-8 col-xs-12 col-sm-12 -->
			
            <div class="col-lg-3 col-md-3 col-xs-12 col-sm-12 sid-lateral">
				<center>
				<div class="sidebaranuncio1" style="margin-bottom:10px;">
					<?php	if ( is_active_sidebar('sidebar-lateral') ) {dynamic_sidebar('sidebar-lateral');}?>
				</div>
					<?php	if ( is_active_sidebar('sidebar-likebox') ) {dynamic_sidebar('sidebar-likebox');}?>
				</center>
            </div>

		</div><!-- .row -->
	</div><!-- .container -->

	<div class="container-fluid conteudo-relacionado">
		<div class="row">
			<div class="col-lg-12 col-md-12 col-xs-12 col-sm-12">
					<h3 style="padding-left:20px; font-size: 20px;">Recomendamos para você</h3>
					<?php
					$orig_post = $post;
					global $post;
					$tags = wp_get_post_tags($post->ID);
					
					if ($tags) {
					$tag_ids = array();
					foreach($tags as $individual_tag) $tag_ids[] = $individual_tag->term_id;
					$args=array(
					'post_type' => 'post',
					'orderby'   => 'rand',
					'posts_per_page' => 20,
					);
					
					$my_query = new wp_query( $args );
					
					while( $my_query->have_posts() ) {
					$my_query->the_post();
					?>
					
					<div class="col-md-4 col-sm-4 col-xs-12">
						<div class="caixa-teste">
							<a href="<?php the_permalink(); ?>" class="post-thumbnail">
								<div class="caixa-img">
									<?php the_post_thumbnail('arte-thumbnail'); ?>
								</div>
									
								<div class="caixa-titulo">
									<?php the_title(); ?>
								</div>
							</a>
							<?php the_excerpt(); ?>
						</div><!-- .caixa-teste -->
					</div>
					
					
					<? }
					}
					$post = $orig_post;
					wp_reset_query();
					?>
			</div>
		</div><!-- .row -->           
	</div><!-- .container -->
  	
</div><!-- #content -->
<?php endwhile; // End of the loop. ?>                        
        
<?php  get_footer(); ?>

Troque o segundo código que você enviou por esse:

<?php
/**
 * Plugin Name: Testes Pop
 * Plugin URI:  https://testespop.com.br
 * Description: O TestesPop permite que você adicione facilmente testes para o facebook, ágeis e modernos ao seu site ou blog! Aumente o engajamento e os compartilhamentos enquanto fatura continuamente.
 * Version:     1.1.1
 * Author:      TestesPop
 * Author URI:  http://testespop.com.br
 *
 * Text Domain: testes-pop
 * Domain Path: /languages/
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit; // disable direct access
}

if ( ! class_exists( 'WP_Quiz_Pro_Plugin' ) ) :

	/**
	 * Register the plugin.
	 *
	 * Display the administration panel, insert JavaScript etc.
	 */
	class WP_Quiz_Pro_Plugin {

		/**
		 * Hold plugin version
		 *
		 * @var string
		 */
		public $version = '1.1.1';

		/**
		 * Hold an instance of WP_Quiz_Pro_Plugin class.
		 *
		 * @var WP_Quiz_Pro_Plugin
		 */
		protected static $instance = null;

		/**
		 * Hold the current quiz instance
		 *
		 * @var WP_Quiz_Pro
		 */
		public $quiz = null;

		/**
		 * Main WP_Quiz_Pro_Plugin instance.
		 * @return WP_Quiz_Pro_Plugin - Main instance.
		 */
		public static function get_instance() {

			if ( is_null( self::$instance ) ) {
				self::$instance = new WP_Quiz_Pro_Plugin;
			}

			return self::$instance;
		}

		/**
		 * You cannot clone this class.
		 */
		public function __clone() {
			_doing_it_wrong( __FUNCTION__, __( 'Cheatin&#8217; huh?', 'wp-quiz-pro' ), $this->version );
		}

		/**
		 * You cannot unserialize instances of this class.
		 */
		public function __wakeup() {
			_doing_it_wrong( __FUNCTION__, __( 'Cheatin&#8217; huh?', 'wp-quiz-pro' ), $this->version );
		}

		/**
		 * The Constructor
		 */
		private function __construct() {

			$this->define_constants();
			$this->includes();
			$this->hooks();
			$this->setup_shortcode();
		}

		/**
		 * Define WP Quiz constants
		 */
		private function define_constants() {

			define( 'WP_QUIZ_PRO_VERSION',    $this->version );
			define( 'WP_QUIZ_PRO_BASE_URL',   trailingslashit( plugins_url( 'wp-quiz-pro' ) ) );
			define( 'WP_QUIZ_PRO_ASSETS_URL', trailingslashit( WP_QUIZ_PRO_BASE_URL . 'assets' ) );
			define( 'WP_QUIZ_PRO_PATH',       plugin_dir_path( __FILE__ ) );
		}

		/**
		 * Load required classes
		 */
		private function includes() {

			// Auto loader
			spl_autoload_register( array( $this, 'autoloader' ) );

			new WP_Quiz_Pro_Admin;
		}

		/**
		 * Autoload classes
		 */
		public function autoloader( $class ) {

			$dir = WP_QUIZ_PRO_PATH . 'inc' . DIRECTORY_SEPARATOR;
			$class_file_name = 'class-' . str_replace( array( 'wp_quiz_pro_', '_' ), array( '', '-' ), strtolower( $class ) ) . '.php';
			if ( file_exists( $dir . $class_file_name ) ) {
				require $dir . $class_file_name;
			}
		}

		/**
		 * Register the [wp_quiz_pro] shortcode.
		 */
		private function setup_shortcode() {

			add_shortcode( 'wp_quiz_pro', array( $this, 'register_shortcode' ) );
		}

		/**
		 * Hook WP Quiz into WordPress
		 */
		private function hooks() {

			// Common
			add_action( 'init', array( $this, 'load_plugin_textdomain' ) );
			add_action( 'init', array( $this, 'register_post_type' ) );
			add_action( 'init', array( $this, 'embeded_output' ) );

			// Frontend
			add_action( 'wp_head', array( $this, 'inline_script' ), 1 );
			add_filter( 'the_content', array( $this, 'create_quiz_page' ) );

			// Ajax
			add_action( 'wp_ajax_wq_quizResults', array( $this, 'save_quiz_results' ) );
			add_action( 'wp_ajax_nopriv_wq_quizResults', array( $this, 'save_quiz_results' ) );

			add_action( 'wp_ajax_wq_submitInfo', array( $this, 'save_quiz_user_info' ) );
			add_action( 'wp_ajax_nopriv_wq_submitInfo', array( $this, 'save_quiz_user_info' ) );

			add_action( 'wp_ajax_wq_submitFbInfo', array( $this, 'save_quiz_fb_user_info' ) );
			add_action( 'wp_ajax_nopriv_wq_submitFbInfo', array( $this, 'save_quiz_fb_user_info' ) );

			add_action( 'wp_ajax_check_image_file', array( $this, 'check_image_file' ) );
			add_action( 'wp_ajax_check_video_file', array( $this, 'check_video_file' ) );
			add_action( 'wp_ajax_dismiss_imagick_notice', array( $this, 'dismiss_imagick_notice' ) );
			add_action( 'wp_ajax_dismiss_gdlibrary_notice', array( $this, 'dismiss_gdlibrary_notice' ) );
			add_action( 'wp_ajax_wpquiz_get_debug_log', array( $this, 'wp_quiz_pro_get_debug_log' ) );

			add_action( 'wp_ajax_connect_aweber', array( $this, 'connect_aweber' ) );

			// FB SDK version 2.9 fix
			if ( isset( $_GET['fbs'] ) && ! empty( $_GET['fbs'] ) ) {
				add_action( 'template_redirect', array( $this, 'fb_share_fix' ) );
			}
		}

		/**
		 * Initialise translations
		 */
		public function load_plugin_textdomain() {

			load_plugin_textdomain( 'wp-quiz-pro', false, dirname( plugin_basename( __FILE__ ) ) . '/languages/' );
		}

		/**
		 * Register Quiz post type
		 */
		public function register_post_type() {

			$labels = array(
				'name'               => __( 'Testes Pop', 'wp-quiz-pro' ),
				'menu_name'          => __( 'Testes Pop', 'wp-quiz-pro' ),
				'singular_name'      => __( 'TP WP', 'wp-quiz-pro' ),
				'name_admin_bar'     => _x( 'Testes Pop', 'name admin bar', 'wp-quiz-pro' ),
				'all_items'          => __( 'Todos os testes', 'wp-quiz-pro' ),
				'search_items'       => __( 'Procurar teste', 'wp-quiz-pro' ),
				'add_new'            => _x( 'Adicionar', 'quiz', 'wp-quiz-pro' ),
				'add_new_item'       => __( 'Adicionar novo teste', 'wp-quiz-pro' ),
				'new_item'           => __( 'Novo testes', 'wp-quiz-pro' ),
				'view_item'          => __( 'Ver teste', 'wp-quiz-pro' ),
				'edit_item'          => __( 'Editar teste', 'wp-quiz-pro' ),
				'not_found'          => __( 'Nenhum teste encontrado.', 'wp-quiz-pro' ),
				'not_found_in_trash' => __( 'Nenhum teste encontrado na lixeira.', 'wp-quiz-pro' ),
				'parent_item_colon'  => __( 'Teste pai', 'wp-quiz-pro' ),
			);

			$args = array(
				'labels'             => $labels,
				'description'        => __( 'Mantém os testes e seus dados.', 'wp-quiz-pro' ),
				'menu_position'      => 5,
				'menu_icon'			 => 'dashicons-editor-help',
				'public'             => true,
				'publicly_queryable' => true,
				'show_ui'            => true,
				'show_in_menu'       => true,
				'query_var'          => true,
				'capability_type'    => 'post',
				'has_archive'        => true,
				'hierarchical'       => false,
				'supports'           => array( 'title', 'author', 'thumbnail', 'excerpt' ),
			);

			register_post_type( 'wp_quiz', $args );

			if ( false === get_option( 'wp_quiz_pro_version' ) ) {
				flush_rewrite_rules();
				update_option( 'wp_quiz_pro_version', WP_QUIZ_PRO_VERSION );
			}
		}

		/**
		 * Shortcode used to display quiz
		 *
		 * @return string HTML output of the shortcode
		 */
		public function register_shortcode( $atts ) {

			if ( ! isset( $atts['id'] ) ) {
				return false;
			}

			// we have an ID to work with
			$quiz = get_post( $atts['id'] );

			// check if ID is correct
			if ( ! $quiz || 'wp_quiz' !== $quiz->post_type ) {
				return "<!-- wp_quiz {$atts['id']} not found -->";
			}

			// lets go
			$this->set_quiz( $atts['id'] );
			$this->quiz->enqueue_scripts();

			return $this->quiz->render_public_quiz();
		}

		/**
		 * Set the current quiz
		 */
		public function set_quiz( $id ) {
			$quiz_type = get_post_meta( $id, 'quiz_type', true );
			$quiz_type = str_replace( '_quiz', '', $quiz_type );
			$quiz_type = 'WP_Quiz_Pro_' . ucwords( $quiz_type ) . '_Quiz';
			$this->quiz = new $quiz_type( $id );
		}

		/**
		 * [create_quiz_page description]
		 * @param  [type] $content [description]
		 * @return [type]          [description]
		 */
		public function create_quiz_page( $content ) {

			global $post;

			if ( 'wp_quiz' !== $post->post_type ) {
				return $content;
			}

			if ( ! is_single() ) {
				return $content;
			}

			$quiz_html = $this->register_shortcode( array( 'id' => $post->ID ) );

			return $quiz_html . $content;
		}

		/**
		 * [save_quiz_results description]
		 * @return [type] [description]
		 */
		public function save_quiz_results() {

			if ( ! wp_verify_nonce( $_POST['_nonce'], 'ajax-quiz-content' ) ) {
				return;
			}

			$correct   = isset( $_POST['correct'] ) ? absint( $_POST['correct'] ) : 0;
			$rid       = isset( $_POST['rid'] ) ? $_POST['rid'] : '';
			$pid       = absint( $_POST['pid'] );
			$type      = sanitize_text_field( $_POST['type'] );
			$user_ip   = $this->get_ip();
			$user_id   = get_current_user_id();
			$user_info = get_userdata( $user_id );
			$username  = is_user_logged_in() ? $user_info->user_login : 'Guest';
			$result    = '';

			$results = get_post_meta( $pid, 'results', true );

			if ( 'trivia' === $type ) {
				$rid = '';
				foreach ( $results as $result ) {
					if ( $result['min'] <= $correct && $result['max'] >= $correct ) {
						$result = $result['title'];
						break;
					}
				}
			} else if ( 'personality' === $type ) {
				for ( $i = 0; $i < count( $results ); $i++ ) {
					if ( $i == $rid ) {
						$result = $results[ $i ]['title'];
						break;
					}
				}
			} else if ( 'swiper' === $type ) {
				$results = $_POST['results'];
				$questions 	= get_post_meta( $pid, 'questions', true );
				foreach ( $questions as $q_key => $question ) {
					foreach ( $results as $key => $result ) {
						if ( $question['uid'] == $key ) {
							if ( '0' == $result ) {
								$questions[ $q_key ]['votesDown'] = $question['votesDown'] + 1;
							} else {
								$questions[ $q_key ]['votesUp'] = $question['votesUp'] + 1;
							}
						}
					}
				}
				update_post_meta( $pid, 'questions', $questions );
				$result = '';
			}

			// Save Result
			$settings = get_option( 'wp_quiz_pro_default_settings' );
			if ( isset( $settings['players_tracking'] ) && 1 === $settings['players_tracking'] ) {
				global $wpdb;
				$wpdb->insert(
					$wpdb->prefix . 'wp_quiz_players',
					array(
						'pid'               => $pid,
						'date'       		=> date( 'Y-m-d', time() ),
						'user_ip'           => $user_ip,
						'username'          => $username,
						'correct_answered'  => $correct,
						'result'            => $result,
						'quiz_type'         => $type,
					),
					array( '%d', '%s', '%s', '%s', '%d', '%s', '%s' )
				);
			}

			die( 'SUCCESS!' );
		}

		/**
		 * [save_quiz_user_info description]
		 * @return [type] [description]
		 */
		public function save_quiz_user_info() {

			if ( ! wp_verify_nonce( $_POST['_nonce'], 'ajax-quiz-content' ) ) {
				return;
			}

			$output = array( 'status' => 1 );

			if ( is_email( $_POST['email'] ) ) {

				global $wpdb;
				$username	= sanitize_text_field( $_POST['username'] );
				$email		= sanitize_email( $_POST['email'] );
				$pid		= absint( $_POST['pid'] );

				$this->subscribe_user( $pid, $username, $email );
				$result = $wpdb->get_results( "SELECT * FROM {$wpdb->prefix}wp_quiz_emails WHERE email = '" . $email . "'" );

				if ( ! $result ) {
					//Save info
					$wpdb->insert(
						$wpdb->prefix . 'wp_quiz_emails',
						array(
							'pid'      => $pid,
							'username' => $username,
							'email'    => $email,
							'date'     => date( 'Y-m-d', time() ),
						),
						array( '%d', '%s', '%s', '%s' )
					);
				}

				$output['status'] = 2;
			}

			wp_send_json( $output );
		}

		/**
		 * [save_quiz_fb_user_info description]
		 * @return [type] [description]
		 */
		public function save_quiz_fb_user_info() {

			if ( ! wp_verify_nonce( $_POST['_nonce'], 'ajax-quiz-content' ) ) {
				return;
			}

			$output = array( 'status' => 1 );
			if ( ! empty( $_POST['user'] ) ) {
				global $wpdb;

				$user = $_POST['user'];
				$result = $wpdb->get_row( "SELECT * FROM {$wpdb->prefix}wp_quiz_fb_users WHERE uid = '" . $user['id'] . "'" );

				if ( ! $result ) {
					$wpdb->insert(
						$wpdb->prefix . 'wp_quiz_fb_users',
						array(
							'uid'			=> absint( $user['id'] ),
							'email'			=> isset( $user['email'] ) ? $user['email'] : '',
							'first_name'	=> $user['first_name'],
							'last_name'		=> $user['last_name'],
							'gender'		=> isset( $user['gender'] ) ? $user['gender'] : '',
							'picture'		=> isset( $user['picture'] ) ? $user['picture'] : '',
							'friends'		=> isset( $user['friends'] ) ? serialize( $user['friends'] ) : '',
							'created_at'	=> date( 'Y-m-d', time() ),
							'updated_at'	=> date( 'Y-m-d', time() ),
						),
						array( '%d', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s' )
					);

					$user['insert_id'] = $wpdb->insert_id;
				} else {
					$user['insert_id'] = $result->id;
				}

				if ( 'user' === $_POST['profile'] ) {
					$return = $this->generate_result_user_image( $_POST['pid'], $user );
				} else {
					$return = $this->generate_result_friend_image( $_POST['pid'], $user );
				}

				if ( ! empty( $return['src'] ) ) {
					$output['src'] = $return['src'];
					$output['desc'] = $return['desc'];
					$output['key'] = $return['key'];
					$output['status'] = 2;
				} else {
					$output['error'] = $return['error'];
				}
			}

			wp_send_json( $output );
		}

		/**
		 * [generate_result_user_image description]
		 * @param  [type] $post_id [description]
		 * @param  [type] $user    [description]
		 * @return [type]          [description]
		 */
		public function generate_result_user_image( $post_id, $user ) {
			global $wpdb;

			$return		= array();
			$results	= get_post_meta( $post_id, 'results', true );

			if ( extension_loaded( 'imagick' ) && ! empty( $results ) ) {

				$index 	= array_rand( $results );
				$result	= $results[ $index ];
				$result['key'] = $index;

				$play = $wpdb->get_row( "SELECT * FROM {$wpdb->prefix}wp_quiz_fb_plays WHERE user_id = '" . $user['insert_id'] . "' AND pid = '" . $post_id . "'" );

				if ( ! $play ) {
					$wpdb->insert(
						$wpdb->prefix . 'wp_quiz_fb_plays',
						array(
							'user_id'	=> absint( $user['insert_id'] ),
							'pid'		=> absint( $post_id ),
						),
						array( '%d', '%d' )
					);
				}

				$names = array(
					'user_first_name'	=> $user['first_name'],
					'user_last_name'	=> $user['last_name'],
					'friend_first_name'	=> '',
					'friend_last_name'	=> '',
				);

				$profile = 'https://graph.facebook.com/' . $user['id'] . '/picture?width=320&height=320';
				$profile = $this->get_redirect_url( $profile );

				$data 	= $this->generate_fb_result( $post_id, $result, $profile, $names );
				$return	= $data;
			}

			return $return;
		}

		public function generate_result_friend_image( $post_id, $user ) {
			global $wpdb;

			$return 	= array();
			$results 	= get_post_meta( $post_id, 'results', true );

			if ( extension_loaded( 'imagick' ) && ! empty( $results ) && ! empty( $user['friends'] ) ) {

				$index 	= array_rand( $results );
				$result	= $results[ $index ];
				$result['key'] = $index;

				$index_2	= array_rand( $user['friends'] );
				$friend		= $user['friends'][ $index_2 ];

				$play = $wpdb->get_row( "SELECT * FROM {$wpdb->prefix}wp_quiz_fb_plays WHERE user_id = '" . $user['insert_id'] . "' AND pid = '" . $post_id . "'" );

				if ( ! $play ) {
					$wpdb->insert(
						$wpdb->prefix . 'wp_quiz_fb_plays',
						array(
							'user_id'	=> absint( $user['insert_id'] ),
							'pid'		=> absint( $post_id ),
						),
						array( '%d', '%d' )
					);
				}

				$profile = 'https://graph.facebook.com/' . $friend['id'] . '/picture?width=320&height=320';
				$profile = $this->get_redirect_url( $profile );

				$friend_name = explode( ' ', $friend['name'] );

				$names = array(
					'user_first_name'	=> $user['first_name'],
					'user_last_name'	=> $user['last_name'],
					'friend_first_name'	=> $friend_name[0],
					'friend_last_name'	=> $friend_name[1],
				);

				$data 	= $this->generate_fb_result( $post_id, $result, $profile, $names );
				$return	= $data;
			}

			return $return;
		}

		public function generate_fb_result( $post_id, $result, $profile, $names ) {

			$return = array( 'src' => '', 'desc' => '', 'error' => '' );

			try {

				$options 	= get_option( 'wp_quiz_pro_default_settings' );
				$settings	= get_post_meta( $post_id, 'settings', true );
				$find 		= array( '%%nomeusuario%%', '%%sobrenome%%', '%%nomeamigo%%', '%%sobrenomeamigo%%' );
				$replace 	= array( $names['user_first_name'], $names['user_last_name'], $names['friend_first_name'], $names['friend_last_name'] );
				$title 		= str_replace( $find, $replace, $result['title'] );
				$desc		= str_replace( $find, $replace, $result['desc'] );
				$upload_dir = wp_upload_dir();

				// Load images
				$profile = new Imagick( $profile );
				$profile->resizeImage( $result['proImageWidth'], $result['proImageHeight'], imagick::FILTER_LANCZOS, 0.9 );
				$profile->roundCorners( $result['imageRadius'], $result['imageRadius'] );

				// Create new image from result
				$output = new Imagick( str_replace( $upload_dir['baseurl'], $upload_dir['basedir'], $result['image'] ) );
				$output->compositeImage( $profile, Imagick::COMPOSITE_DEFAULT, $result['pos_x'], $result['pos_y'] );

				// Annotate it
				if ( ! empty( $title ) ) {

					$draw = new ImagickDraw();
					$draw->setFillColor( $settings['title_color'] );
					$draw->setGravity( 1 );
					$draw->setFontSize( $settings['title_size'] );

					if ( isset( $options['defaults']['external_font'] ) && ! empty( $options['defaults']['external_font'] ) ) {
						$external_font = str_replace( home_url('/'), '', $options['defaults']['external_font'] );
						$draw->setFont( '../' . $external_font );
					} else {
						$draw->setFontFamily( $settings['title_font'] );
					}

					list( $lines, $line_height ) = $this->word_wrap_annotation( $output, $draw, $title, $result['titleImageWidth'] );

					for ( $i = 0; $i < count( $lines ); $i++ ) {
						$output->annotateImage( $draw, $result['pos_title_x'],  $result['pos_title_y'] + $i * $line_height, 0, $lines[ $i ] );
					}
				}

				// Save to new image
				$upload_dir['basedir'] = $upload_dir['basedir'] . '/wp_quiz-result-images';
				$upload_dir['baseurl'] = $upload_dir['baseurl'] . '/wp_quiz-result-images';
				$output_name = 'image-' . rand( 0, 100000 ) . '.png';
				$output->writeImage(  $upload_dir['basedir'] . '/' . $output_name  );

				// Clean up
				$profile->destroy();
				$output->destroy();

				$return['src']	= $upload_dir['baseurl'] . '/' . $output_name;
				$return['desc']	= $desc;
				$return['key']	= $result['key'];

			} catch ( Exception $ex ) {
				$return['error'] = $ex->getMessage();
			}

			return $return;
		}

		public function get_redirect_url( $url ) {

			$response = wp_remote_head( $url );
			$redirect_url = wp_remote_retrieve_header( $response, 'location' );

			return $redirect_url ? $redirect_url : $url;
		}

		public function word_wrap_annotation( $image, $draw, $text, $max_width ) {

			$words = preg_split( '%\s%', $text, -1, PREG_SPLIT_NO_EMPTY );
			$lines = array();
			$i = 0;
			$line_height = 0;

			while ( count( $words ) > 0 ) {
				$metrics = $image->queryFontMetrics( $draw, implode( ' ', array_slice( $words, 0, ++$i ) ) );
				$line_height = max( $metrics['textHeight'], $line_height );

				if ( $metrics['textWidth'] > $max_width || count( $words ) < $i ) {
					if ( 1 === $i ) {
						$i++;
					}

					$lines[] = implode( ' ', array_slice( $words, 0, --$i ) );
					$words = array_slice( $words, $i );
					$i = 0;
				}
			}

			return array( $lines, $line_height );
		}

		public function subscribe_user( $id, $name, $email ) {

			$settings 	= get_post_meta( $id, 'settings', true );
			$options 	= get_option( 'wp_quiz_pro_default_settings' );
			if ( '1' === $settings['force_action'] ) {
				if ( '1' === $options['mail_service'] ) {
					$this->subscribe_mailchimp( $options, $name, $email );
				} else if ( '2' === $options['mail_service'] ) {
					$this->subscribe_getresponse( $options, $name, $email );
				} else if ( '3' === $options['mail_service'] ) {
					$this->subscribe_aweber( $options, $name, $email );
				}
			}
		}

		private function subscribe_aweber( $options, $name, $email ) {

			// check for valid data
			if ( empty( $email ) ) {
				wp_send_json( array(
					'success' => false,
					'error' => esc_html__( 'No email address found.', 'wp-quiz-pro' ),
				) );
			}

			if ( ! filter_var( $email, FILTER_VALIDATE_EMAIL ) ) {
				wp_send_json( array(
					'success' => false,
					'error' => esc_html__( 'Not a valid email address.', 'wp-quiz-pro' ),
				) );
			}

			// Call service subscription method
			try {
				$service = new WP_Quiz_Pro_Subscription_Aweber();
				$list_id		= $options['aweber']['listid'];
				$status = $service->subscribe( $name, $email, $list_id );

				wp_send_json(array(
					'success' => true,
					'status' => $status['status'],
				));
			} catch ( Exception $e ) {
				wp_send_json(array(
					'success' => false,
					'error' => $e->getMessage(),
				));
			}
		}

		private function subscribe_mailchimp( $options, $name, $email ) {

			$mc_api_key		= $options['mailchimp']['api_key'];
			$mc_list_id		= $options['mailchimp']['list_id'];
			$double_optin	= apply_filters( 'wp_quiz_mailchimp_double_notification', false );

			$vendor_path = $this->get_vendor_path();

			if ( $email && null !== $mc_api_key && null !== $mc_list_id ) {

				try {
					if ( ! class_exists( 'Mailchimp' ) ) {
						require_once( $vendor_path . '/Mailchimp.php' );
					}

					$list = new Mailchimp_Lists( new Mailchimp( $mc_api_key ) );
					$merge_vars = null;
					if ( $name ) {
						$fname = $name;
						$lname = '';
						if ( $space_pos = strpos( $name, ' ' ) ) {
							$fname = substr( $name, 0, $space_pos );
							$lname = substr( $name, $space_pos );
						}
						$merge_vars = array( 'FNAME' => $fname, 'LNAME' => $lname );
					}
					$list->subscribe( $mc_list_id, array( 'email' => $email ), $merge_vars, 'html', (bool) $double_optin, true );

				} catch ( Exception $ex ) {}
			}
		}

		private function subscribe_getresponse( $options, $name, $email ) {

			$gr_api_key = $options['getresponse']['api_key'];
			$gr_list_id = $options['getresponse']['campaign_name'];

			$vendor_path = $this->get_vendor_path();

			if ( $email && null !== $gr_api_key && null !== $gr_list_id ) {
				try {
					if ( ! class_exists( 'GetResponse' ) ) {
						require_once( $vendor_path . '/getresponse.php' );
					}

					$api = new GetResponse( $gr_api_key );
					$campaign_ame		= $gr_list_id;
					$subscriber_name		= $name;
					$subscriber_email	= $email;

					$result 		= $api->getCampaigns( 'EQUALS', $campaign_ame );
					$campaigns		= array_keys( (array) $result );
					$campaign_id	= array_pop( $campaigns );

					$api->addContact( $campaign_id, $subscriber_name, $subscriber_email );
				} catch ( Exception $ex ) {}
			}
		}

		public function get_vendor_path() {

			return plugin_dir_path( __FILE__ ) . 'vendor';
		}

		public function check_image_file() {

			$output = array( 'status' => 1 );
			$check = false;
			if ( @getimagesize( $_POST['url'] ) ) {
				$check = true;
			}

			$output['check'] = $check;
			wp_send_json( $output );
		}

		public function check_video_file() {

			$output = array( 'status' => 1 );
			$check = false;
			$id = $_POST['video_id'];
			$url = "http://www.youtube.com/oembed?url=http://www.youtube.com/watch?v=$id&format=json";
			$headers = get_headers( $url );
			if ( '404' !== substr( $headers[0], 9, 3 ) ) {
				$check = true;
			}

			$output['check'] = $check;
			wp_send_json( $output );
		}

		public static function activate_plugin() {

			// Don't activate on anything less than PHP 5.4.0 or WordPress 3.4
			if ( version_compare( PHP_VERSION, '5.4.0', '<' ) || version_compare( get_bloginfo( 'version' ), '3.4', '<' ) || ! function_exists( 'spl_autoload_register' ) ) {
				require_once ABSPATH . 'wp-admin/includes/plugin.php';
				deactivate_plugins( basename( __FILE__ ) );
				wp_die( __( 'Testes Pop requires PHP version 5.4.0 with spl extension or greater and WordPress 3.4 or greater.', 'wp-quiz-pro' ) );
			}

			//Dont't activate if wp quiz is active
			if ( defined( 'WP_QUIZ_VERSION' ) ) {
				deactivate_plugins( basename( __FILE__ ) );
				wp_die( __( 'Please deactivate WP Quiz plugin first to use the Premium features!', 'wp-quiz-pro' ) );
			}

			include( 'inc/activate-plugin.php' );

		}

		public function get_ip() {

			//Just get the headers if we can or else use the SERVER global
			if ( function_exists( 'apache_request_headers' ) ) {
				$headers = apache_request_headers();
			} else {
				$headers = $_SERVER;
			}

			//Get the forwarded IP if it exists
			if ( array_key_exists( 'X-Forwarded-For', $headers ) && filter_var( $headers['X-Forwarded-For'], FILTER_VALIDATE_IP, FILTER_FLAG_IPV4 ) ) {
				$the_ip = $headers['X-Forwarded-For'];
			} else if ( array_key_exists( 'HTTP_X_FORWARDED_FOR', $headers ) && filter_var( $headers['HTTP_X_FORWARDED_FOR'], FILTER_VALIDATE_IP, FILTER_FLAG_IPV4 ) ) {
				$the_ip = $headers['HTTP_X_FORWARDED_FOR'];
			} else {
				$the_ip = filter_var( $_SERVER['REMOTE_ADDR'], FILTER_VALIDATE_IP, FILTER_FLAG_IPV4 );
			}
			return $the_ip;

		}

		public function dismiss_imagick_notice() {
			add_option( 'wp_dismiss_imagick_notice', 'true' );
		}

		public function dismiss_gdlibrary_notice() {
			add_option( 'wp_dismiss_gdlibrary_notice', 'true' );
		}

		public function wp_quiz_pro_get_debug_log() {
			$page = new WP_Quiz_Pro_Page_Support();
			$page->get_debug_log();
		}

		public function fb_share_fix() {

			$data = array_map( 'urldecode', $_GET );
			$result = get_post_meta( $data['id'], 'results', true );
			$result = isset( $result[ $data['rid'] ] ) ? $result[ $data['rid'] ] : array();

			// Picture
			if ( 'r' === $data['pic'] ) {
				$data['source'] = $result['image'];
			} elseif ( 'f' === $data['pic'] ) {
				$data['source'] = wp_get_attachment_url( get_post_thumbnail_id( $data['id'] ) );
			} elseif ( ( substr( $data['pic'], 0, 6 ) === 'image-' ) ) {
			    $upload_dir = wp_upload_dir();
				$upload_dir['baseurl'] = $upload_dir['baseurl'] . '/wp_quiz-result-images';
				$data['source'] = $upload_dir['baseurl'] . '/' . $data['pic'] . '.png';
			} else {
				$data['source'] = false;
			}

			// Description
			if ( 'r' === $data['desc'] ) {
				$data['description'] = $result['desc'];
			} elseif ( 'e' === $data['desc'] ) {
				$data['description'] = get_post_field( 'post_excerpt', $data['id'] );
			} else {
				$data['description'] = false;
			}

			if ( $data['description'] ) {

			    $first = array( '%%nomeusuario%%', '%%nomeamigo%%' );
			    $last = array( '%%sobrenome%%', '%%sobrenomeamigo%%' );

			    $data['description'] = str_replace( $first, $data['nf'], $data['description'] );
			    $data['description'] = str_replace( $last, $data['nl'], $data['description'] );
			}

			$settings = get_option( 'wp_quiz_pro_default_settings' );
			$url = ( is_ssl() ? 'https' : 'http' ) . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";

			global $post;
			$pid  = $post ? $post->ID : $data['id'];
			$original_url = get_permalink( $pid );
			?>
			<html>
				<head>
					<title><?php wp_title( '' ) ?></title>
					<meta property="fb:app_id" content="<?php echo $settings['defaults']['fb_app_id'] ?>">
					<meta property="og:type" content="website">
					<meta name="twitter:card" content="summary_large_image">
					<meta property="og:url" content="<?php echo esc_url( $url ); ?>">
					<?php if ( ! empty( $data['text'] ) ) : ?>
					<meta property="og:title" content="<?php echo get_the_title( $pid ) ?> - <?php echo esc_attr( $data['text'] ); ?>">
					<meta property="twitter:title" content="<?php echo get_the_title( $pid ) ?> - <?php echo esc_attr( $data['text'] ); ?>">
					<?php endif; ?>
					<?php if ( ! empty( $data['source'] ) ) : ?>
					<meta property="og:image" content="<?php echo esc_url( $data['source'] ); ?>">
					<meta property="twitter:image" content="<?php echo esc_url( $data['source'] ); ?>">
						<?php list( $img_width, $img_height ) = getimagesize( $data['source'] ); ?>
						<?php if ( isset( $img_width ) && $img_width ) : ?>
						<meta property="og:image:width" content="<?php echo $img_width ?>">
						<?php endif; ?>
						<?php if ( isset( $img_height ) && $img_height ) : ?>
						<meta property="og:image:height" content="<?php echo $img_height ?>">
						<?php endif; ?>
					<?php endif; ?>
					<?php if ( ! empty( $data['description'] ) ) : ?>
					<meta property="og:description" content="<?php echo esc_attr( $data['description'] ); ?>">
					<meta property="twitter:description" content="<?php echo esc_attr( $data['description'] ); ?>">
					<?php endif; ?>
					<meta http-equiv="refresh" content="0;url=<?php echo esc_url( $original_url ); ?>">
				</head>
			<body>
				Redirecting please wait....
			</body>
			</html>
			<?php
			exit;
		}

		/**
		 * [inline_script description]
		 * @return [type] [description]
		 */
		public function inline_script() {
			$settings = get_option( 'wp_quiz_pro_default_settings' );
			?>
			<script>
			var quizSiteUrl = '<?php echo home_url( '/' ) ?>';
			<?php if ( ! empty( $settings['analytics']['tracking_id'] ) ) { ?>
				(function(i,s,o,g,r,a,m) {i['GoogleAnalyticsObject']=r;i[r]=i[r]||function() {
				(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
				m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
				})(window,document,'script','//www.google-analytics.com/analytics.js','ga');

				ga('create', '<?php echo $settings['analytics']['tracking_id'] ?>', 'auto');
				ga('send', 'pageview');
			<?php } ?>
			<?php if ( ! empty( $settings['defaults']['fb_app_id'] ) ) { ?>
				window.fbAsyncInit = function() {
					FB.init({
						appId    : '<?php echo $settings['defaults']['fb_app_id'] ?>',
						xfbml    : true,
						version  : 'v2.9'
					});

					FB.getLoginStatus(function( response ) {
						getLogin( response );
					});
				};
				
				(function(d, s, id) {
					var js, fjs = d.getElementsByTagName(s)[0];
					if (d.getElementById(id)) {return;}
					js = d.createElement(s); js.id = id;
					js.src = "//connect.facebook.net/pt_BR/sdk.js";
					fjs.parentNode.insertBefore(js, fjs);
				}(document, 'script', 'facebook-jssdk'));

			<?php 
/*
////////////////////////////////////// ALTEREI AQUI ////////////////////////////////////
////////////////////////////////////// ALTEREI AQUI ////////////////////////////////////
////////////////////////////////////// ALTEREI AQUI ////////////////////////////////////
////////////////////////////////////// ALTEREI AQUI ////////////////////////////////////
////////////////////////////////////// ALTEREI AQUI ////////////////////////////////////
////////////////////////////////////// ALTEREI AQUI ////////////////////////////////////
*/
				global $get_facebook_url;
				$get_facebook_url = $settings['defaults']['fb_app_id2'];
		
/*
////////////////////////////////////// ALTEREI AQUI ////////////////////////////////////
////////////////////////////////////// ALTEREI AQUI ////////////////////////////////////
////////////////////////////////////// ALTEREI AQUI ////////////////////////////////////
////////////////////////////////////// ALTEREI AQUI ////////////////////////////////////
////////////////////////////////////// ALTEREI AQUI ////////////////////////////////////
////////////////////////////////////// ALTEREI AQUI ////////////////////////////////////
*/

					} ?>
			</script>

			<!-- Codigo que exibe URL no topo da página -->
			<?php echo $settings['defaults']['fb_app_id2'] ?>
			<!-- fim Codigo que exibe URL no topo da página -->

			<?php
			if ( is_singular( array( 'wp_quiz' ) ) && isset( $settings['defaults']['share_meta'] ) && 1 === $settings['defaults']['share_meta'] ) {
				global $post, $wpseo_og;
				$twitter_desc = $og_desc = str_replace( array( "\r", "\n" ), '', strip_tags( $post->post_excerpt ) );
				if ( defined( 'WPSEO_VERSION' ) ) {
					remove_action( 'wpseo_head', array( $wpseo_og, 'opengraph' ), 30 );
					remove_action( 'wpseo_head', array( 'WPSEO_Twitter', 'get_instance' ), 40 );
					//use description from yoast
					$twitter_desc 	= get_post_meta( $post->ID, '_yoast_wpseo_twitter-description', true );
					$og_desc		= get_post_meta( $post->ID, '_yoast_wpseo_opengraph-description', true );
				}
				?>
				<meta name="twitter:title" content="<?php echo get_the_title(); ?>">
				<meta name="twitter:description" content="<?php echo $twitter_desc; ?>">
				<meta name="twitter:domain" content="<?php echo esc_url( site_url() ); ?>">
				<meta property="og:url" content="<?php the_permalink(); ?>" />
				<meta property="og:title" content="<?php echo get_the_title(); ?>" />
				<meta property="og:description" content="<?php echo $og_desc; ?>" />
				<?php
				if ( has_post_thumbnail() ) {
					$thumb_id = get_post_thumbnail_id();
					$thumb_url_array = wp_get_attachment_image_src( $thumb_id, 'full', true );
					$thumb_url = $thumb_url_array[0];
					?>
					<meta name="twitter:card" content="summary_large_image">
					<meta name="twitter:image:src" content="<?php echo $thumb_url; ?>">
					<meta property="og:image" content="<?php echo $thumb_url; ?>" />
					<meta itemprop="image" content="<?php echo $thumb_url; ?>">
				<?php
				}
			}
		}

		public function embeded_output() {

			if ( ! isset( $_GET['wp_quiz_id'] ) ) {
				return;
			}

			$qid		= absint( $_GET['wp_quiz_id'] );
			$quiz_html	= $this->register_shortcode( array( 'id' => $qid ) );
			$settings	= get_post_meta( $qid, 'settings', true );
			if ( empty( $quiz_html ) ) {
				return;
			}
			?>
				<link rel='stylesheet' href='<?php echo WP_QUIZ_PRO_ASSETS_URL . 'css/main.css'; ?>' type='text/css' media='all' />
				<link rel='stylesheet' href='<?php echo WP_QUIZ_PRO_ASSETS_URL . 'css/transition.min.css'; ?>' type='text/css' media='all' />
				<link rel='stylesheet' href='<?php echo WP_QUIZ_PRO_ASSETS_URL . 'css/embed.min.css'; ?>' type='text/css' media='all' />
				<style>
					.wq_embedToggleQuizCtr{ display: none; }
				</style>
			<?php
			if ( 'traditional' === $settings['skin'] ) {
				?>
					<link rel='stylesheet' href='<?php echo WP_QUIZ_PRO_ASSETS_URL . 'css/traditional-skin.css'; ?>' type='text/css' media='all' />
				<?php
			} else if ( 'flat' === $settings['skin'] ) {
				?>
					<link rel='stylesheet' href='<?php echo WP_QUIZ_PRO_ASSETS_URL . 'css/flat-skin.css'; ?>' type='text/css' media='all' />
				<?php
			}
			$this->inline_script();
			?>
				<script>
					var wq_l10n = {"correct": "Correct !", "wrong": "Wrong !","captionTrivia":"You got %%score%% out of %%total%%","captionTriviaFB":"I got %%score%% out of %%total%%, and you?","youVoted":"You voted","nonce": "<?php echo wp_create_nonce( 'ajax-quiz-content' ) ?>"};
				</script>
			<?php

			echo '<div class="wq_embed">' . $quiz_html . '</div>';
			?>
				<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
				<script src="<?php echo WP_QUIZ_PRO_ASSETS_URL . 'js/embed.min.js'; ?>"></script>
				<script src="<?php echo WP_QUIZ_PRO_ASSETS_URL . 'js/transition.min.js'; ?>"></script>
				<script src="<?php echo WP_QUIZ_PRO_ASSETS_URL . 'js/jquery.flip.min.js'; ?>"></script>
				<script src="<?php echo WP_QUIZ_PRO_ASSETS_URL . 'js/hammer.min.js'; ?>"></script>
				<script src="<?php echo WP_QUIZ_PRO_ASSETS_URL . 'js/dynamics.min.js'; ?>"></script>
				<script src="<?php echo WP_QUIZ_PRO_ASSETS_URL . 'js/jquery.jTinder.min.js'; ?>"></script>
				<script src="<?php echo WP_QUIZ_PRO_ASSETS_URL . 'js/main.min.js'; ?>"></script>
			<?php
			die();
		}

		/**
		 * [connect_aweber description]
		 * @return [type] [description]
		 */
		public function connect_aweber() {

			// check for data
			$aweber_code = isset( $_REQUEST['aweber_code'] ) ? $_REQUEST['aweber_code'] : array();
			if ( empty( $aweber_code ) ) {
				wp_send_json( array(
					'success' => false,
					'error' => esc_html__( 'No aweber authorization code found.', 'wp-quiz-pro' ),
				) );
			}

			try {
				$service = new WP_Quiz_Pro_Subscription_Aweber();
				$data = $service->connect( $aweber_code );

				wp_send_json(array(
					'success' => true,
					'data' => $data,
				));
			} catch ( Exception $e ) {
				wp_send_json(array(
					'success' => false,
					'error' => $e->getMessage(),
				));
			}
		}
	}

	/**
	 * Main instance of WP_Quiz_Pro_Plugin.
	 *
	 * Returns the main instance of WP_Quiz_Pro_Plugin to prevent the need to use globals.
	 *
	 * @return WP_Quiz_Pro_Plugin
	 */

	function wp_quiz_pro() {
		return WP_Quiz_Pro_Plugin::get_instance();
	}

endif;

add_action( 'plugins_loaded', 'wp_quiz_pro', 10 );
register_activation_hook( __FILE__, array( 'WP_Quiz_Pro_Plugin', 'activate_plugin' ) );

 

  • +1 1

Share this post


Link to post
Share on other sites

Eu havia editado o segundo arquivo pq eu tinha colocado as 2 variáveis fora da tag do php, aí editei e coloquei dentro, mas acho que não deu tempo e você pegou o outro arquivo que tava errado. Mantém o single.php que eu enviei e poem esse aqui que ta corrigido:

obs: me informa o nome desse segundo arquivo que você enviou pra melhorar a comunicação.

Troca o segundo arquivo por esse que ta corrigido:

<?php
/**
 * Plugin Name: Testes Pop
 * Plugin URI:  https://testespop.com.br
 * Description: O TestesPop permite que você adicione facilmente testes para o facebook, ágeis e modernos ao seu site ou blog! Aumente o engajamento e os compartilhamentos enquanto fatura continuamente.
 * Version:     1.1.1
 * Author:      TestesPop
 * Author URI:  http://testespop.com.br
 *
 * Text Domain: testes-pop
 * Domain Path: /languages/
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit; // disable direct access
}

if ( ! class_exists( 'WP_Quiz_Pro_Plugin' ) ) :

	/**
	 * Register the plugin.
	 *
	 * Display the administration panel, insert JavaScript etc.
	 */
	class WP_Quiz_Pro_Plugin {

		/**
		 * Hold plugin version
		 *
		 * @var string
		 */
		public $version = '1.1.1';

		/**
		 * Hold an instance of WP_Quiz_Pro_Plugin class.
		 *
		 * @var WP_Quiz_Pro_Plugin
		 */
		protected static $instance = null;

		/**
		 * Hold the current quiz instance
		 *
		 * @var WP_Quiz_Pro
		 */
		public $quiz = null;

		/**
		 * Main WP_Quiz_Pro_Plugin instance.
		 * @return WP_Quiz_Pro_Plugin - Main instance.
		 */
		public static function get_instance() {

			if ( is_null( self::$instance ) ) {
				self::$instance = new WP_Quiz_Pro_Plugin;
			}

			return self::$instance;
		}

		/**
		 * You cannot clone this class.
		 */
		public function __clone() {
			_doing_it_wrong( __FUNCTION__, __( 'Cheatin&#8217; huh?', 'wp-quiz-pro' ), $this->version );
		}

		/**
		 * You cannot unserialize instances of this class.
		 */
		public function __wakeup() {
			_doing_it_wrong( __FUNCTION__, __( 'Cheatin&#8217; huh?', 'wp-quiz-pro' ), $this->version );
		}

		/**
		 * The Constructor
		 */
		private function __construct() {

			$this->define_constants();
			$this->includes();
			$this->hooks();
			$this->setup_shortcode();
		}

		/**
		 * Define WP Quiz constants
		 */
		private function define_constants() {

			define( 'WP_QUIZ_PRO_VERSION',    $this->version );
			define( 'WP_QUIZ_PRO_BASE_URL',   trailingslashit( plugins_url( 'wp-quiz-pro' ) ) );
			define( 'WP_QUIZ_PRO_ASSETS_URL', trailingslashit( WP_QUIZ_PRO_BASE_URL . 'assets' ) );
			define( 'WP_QUIZ_PRO_PATH',       plugin_dir_path( __FILE__ ) );
		}

		/**
		 * Load required classes
		 */
		private function includes() {

			// Auto loader
			spl_autoload_register( array( $this, 'autoloader' ) );

			new WP_Quiz_Pro_Admin;
		}

		/**
		 * Autoload classes
		 */
		public function autoloader( $class ) {

			$dir = WP_QUIZ_PRO_PATH . 'inc' . DIRECTORY_SEPARATOR;
			$class_file_name = 'class-' . str_replace( array( 'wp_quiz_pro_', '_' ), array( '', '-' ), strtolower( $class ) ) . '.php';
			if ( file_exists( $dir . $class_file_name ) ) {
				require $dir . $class_file_name;
			}
		}

		/**
		 * Register the [wp_quiz_pro] shortcode.
		 */
		private function setup_shortcode() {

			add_shortcode( 'wp_quiz_pro', array( $this, 'register_shortcode' ) );
		}

		/**
		 * Hook WP Quiz into WordPress
		 */
		private function hooks() {

			// Common
			add_action( 'init', array( $this, 'load_plugin_textdomain' ) );
			add_action( 'init', array( $this, 'register_post_type' ) );
			add_action( 'init', array( $this, 'embeded_output' ) );

			// Frontend
			add_action( 'wp_head', array( $this, 'inline_script' ), 1 );
			add_filter( 'the_content', array( $this, 'create_quiz_page' ) );

			// Ajax
			add_action( 'wp_ajax_wq_quizResults', array( $this, 'save_quiz_results' ) );
			add_action( 'wp_ajax_nopriv_wq_quizResults', array( $this, 'save_quiz_results' ) );

			add_action( 'wp_ajax_wq_submitInfo', array( $this, 'save_quiz_user_info' ) );
			add_action( 'wp_ajax_nopriv_wq_submitInfo', array( $this, 'save_quiz_user_info' ) );

			add_action( 'wp_ajax_wq_submitFbInfo', array( $this, 'save_quiz_fb_user_info' ) );
			add_action( 'wp_ajax_nopriv_wq_submitFbInfo', array( $this, 'save_quiz_fb_user_info' ) );

			add_action( 'wp_ajax_check_image_file', array( $this, 'check_image_file' ) );
			add_action( 'wp_ajax_check_video_file', array( $this, 'check_video_file' ) );
			add_action( 'wp_ajax_dismiss_imagick_notice', array( $this, 'dismiss_imagick_notice' ) );
			add_action( 'wp_ajax_dismiss_gdlibrary_notice', array( $this, 'dismiss_gdlibrary_notice' ) );
			add_action( 'wp_ajax_wpquiz_get_debug_log', array( $this, 'wp_quiz_pro_get_debug_log' ) );

			add_action( 'wp_ajax_connect_aweber', array( $this, 'connect_aweber' ) );

			// FB SDK version 2.9 fix
			if ( isset( $_GET['fbs'] ) && ! empty( $_GET['fbs'] ) ) {
				add_action( 'template_redirect', array( $this, 'fb_share_fix' ) );
			}
		}

		/**
		 * Initialise translations
		 */
		public function load_plugin_textdomain() {

			load_plugin_textdomain( 'wp-quiz-pro', false, dirname( plugin_basename( __FILE__ ) ) . '/languages/' );
		}

		/**
		 * Register Quiz post type
		 */
		public function register_post_type() {

			$labels = array(
				'name'               => __( 'Testes Pop', 'wp-quiz-pro' ),
				'menu_name'          => __( 'Testes Pop', 'wp-quiz-pro' ),
				'singular_name'      => __( 'TP WP', 'wp-quiz-pro' ),
				'name_admin_bar'     => _x( 'Testes Pop', 'name admin bar', 'wp-quiz-pro' ),
				'all_items'          => __( 'Todos os testes', 'wp-quiz-pro' ),
				'search_items'       => __( 'Procurar teste', 'wp-quiz-pro' ),
				'add_new'            => _x( 'Adicionar', 'quiz', 'wp-quiz-pro' ),
				'add_new_item'       => __( 'Adicionar novo teste', 'wp-quiz-pro' ),
				'new_item'           => __( 'Novo testes', 'wp-quiz-pro' ),
				'view_item'          => __( 'Ver teste', 'wp-quiz-pro' ),
				'edit_item'          => __( 'Editar teste', 'wp-quiz-pro' ),
				'not_found'          => __( 'Nenhum teste encontrado.', 'wp-quiz-pro' ),
				'not_found_in_trash' => __( 'Nenhum teste encontrado na lixeira.', 'wp-quiz-pro' ),
				'parent_item_colon'  => __( 'Teste pai', 'wp-quiz-pro' ),
			);

			$args = array(
				'labels'             => $labels,
				'description'        => __( 'Mantém os testes e seus dados.', 'wp-quiz-pro' ),
				'menu_position'      => 5,
				'menu_icon'			 => 'dashicons-editor-help',
				'public'             => true,
				'publicly_queryable' => true,
				'show_ui'            => true,
				'show_in_menu'       => true,
				'query_var'          => true,
				'capability_type'    => 'post',
				'has_archive'        => true,
				'hierarchical'       => false,
				'supports'           => array( 'title', 'author', 'thumbnail', 'excerpt' ),
			);

			register_post_type( 'wp_quiz', $args );

			if ( false === get_option( 'wp_quiz_pro_version' ) ) {
				flush_rewrite_rules();
				update_option( 'wp_quiz_pro_version', WP_QUIZ_PRO_VERSION );
			}
		}

		/**
		 * Shortcode used to display quiz
		 *
		 * @return string HTML output of the shortcode
		 */
		public function register_shortcode( $atts ) {

			if ( ! isset( $atts['id'] ) ) {
				return false;
			}

			// we have an ID to work with
			$quiz = get_post( $atts['id'] );

			// check if ID is correct
			if ( ! $quiz || 'wp_quiz' !== $quiz->post_type ) {
				return "<!-- wp_quiz {$atts['id']} not found -->";
			}

			// lets go
			$this->set_quiz( $atts['id'] );
			$this->quiz->enqueue_scripts();

			return $this->quiz->render_public_quiz();
		}

		/**
		 * Set the current quiz
		 */
		public function set_quiz( $id ) {
			$quiz_type = get_post_meta( $id, 'quiz_type', true );
			$quiz_type = str_replace( '_quiz', '', $quiz_type );
			$quiz_type = 'WP_Quiz_Pro_' . ucwords( $quiz_type ) . '_Quiz';
			$this->quiz = new $quiz_type( $id );
		}

		/**
		 * [create_quiz_page description]
		 * @param  [type] $content [description]
		 * @return [type]          [description]
		 */
		public function create_quiz_page( $content ) {

			global $post;

			if ( 'wp_quiz' !== $post->post_type ) {
				return $content;
			}

			if ( ! is_single() ) {
				return $content;
			}

			$quiz_html = $this->register_shortcode( array( 'id' => $post->ID ) );

			return $quiz_html . $content;
		}

		/**
		 * [save_quiz_results description]
		 * @return [type] [description]
		 */
		public function save_quiz_results() {

			if ( ! wp_verify_nonce( $_POST['_nonce'], 'ajax-quiz-content' ) ) {
				return;
			}

			$correct   = isset( $_POST['correct'] ) ? absint( $_POST['correct'] ) : 0;
			$rid       = isset( $_POST['rid'] ) ? $_POST['rid'] : '';
			$pid       = absint( $_POST['pid'] );
			$type      = sanitize_text_field( $_POST['type'] );
			$user_ip   = $this->get_ip();
			$user_id   = get_current_user_id();
			$user_info = get_userdata( $user_id );
			$username  = is_user_logged_in() ? $user_info->user_login : 'Guest';
			$result    = '';

			$results = get_post_meta( $pid, 'results', true );

			if ( 'trivia' === $type ) {
				$rid = '';
				foreach ( $results as $result ) {
					if ( $result['min'] <= $correct && $result['max'] >= $correct ) {
						$result = $result['title'];
						break;
					}
				}
			} else if ( 'personality' === $type ) {
				for ( $i = 0; $i < count( $results ); $i++ ) {
					if ( $i == $rid ) {
						$result = $results[ $i ]['title'];
						break;
					}
				}
			} else if ( 'swiper' === $type ) {
				$results = $_POST['results'];
				$questions 	= get_post_meta( $pid, 'questions', true );
				foreach ( $questions as $q_key => $question ) {
					foreach ( $results as $key => $result ) {
						if ( $question['uid'] == $key ) {
							if ( '0' == $result ) {
								$questions[ $q_key ]['votesDown'] = $question['votesDown'] + 1;
							} else {
								$questions[ $q_key ]['votesUp'] = $question['votesUp'] + 1;
							}
						}
					}
				}
				update_post_meta( $pid, 'questions', $questions );
				$result = '';
			}

			// Save Result
			$settings = get_option( 'wp_quiz_pro_default_settings' );
			if ( isset( $settings['players_tracking'] ) && 1 === $settings['players_tracking'] ) {
				global $wpdb;
				$wpdb->insert(
					$wpdb->prefix . 'wp_quiz_players',
					array(
						'pid'               => $pid,
						'date'       		=> date( 'Y-m-d', time() ),
						'user_ip'           => $user_ip,
						'username'          => $username,
						'correct_answered'  => $correct,
						'result'            => $result,
						'quiz_type'         => $type,
					),
					array( '%d', '%s', '%s', '%s', '%d', '%s', '%s' )
				);
			}

			die( 'SUCCESS!' );
		}

		/**
		 * [save_quiz_user_info description]
		 * @return [type] [description]
		 */
		public function save_quiz_user_info() {

			if ( ! wp_verify_nonce( $_POST['_nonce'], 'ajax-quiz-content' ) ) {
				return;
			}

			$output = array( 'status' => 1 );

			if ( is_email( $_POST['email'] ) ) {

				global $wpdb;
				$username	= sanitize_text_field( $_POST['username'] );
				$email		= sanitize_email( $_POST['email'] );
				$pid		= absint( $_POST['pid'] );

				$this->subscribe_user( $pid, $username, $email );
				$result = $wpdb->get_results( "SELECT * FROM {$wpdb->prefix}wp_quiz_emails WHERE email = '" . $email . "'" );

				if ( ! $result ) {
					//Save info
					$wpdb->insert(
						$wpdb->prefix . 'wp_quiz_emails',
						array(
							'pid'      => $pid,
							'username' => $username,
							'email'    => $email,
							'date'     => date( 'Y-m-d', time() ),
						),
						array( '%d', '%s', '%s', '%s' )
					);
				}

				$output['status'] = 2;
			}

			wp_send_json( $output );
		}

		/**
		 * [save_quiz_fb_user_info description]
		 * @return [type] [description]
		 */
		public function save_quiz_fb_user_info() {

			if ( ! wp_verify_nonce( $_POST['_nonce'], 'ajax-quiz-content' ) ) {
				return;
			}

			$output = array( 'status' => 1 );
			if ( ! empty( $_POST['user'] ) ) {
				global $wpdb;

				$user = $_POST['user'];
				$result = $wpdb->get_row( "SELECT * FROM {$wpdb->prefix}wp_quiz_fb_users WHERE uid = '" . $user['id'] . "'" );

				if ( ! $result ) {
					$wpdb->insert(
						$wpdb->prefix . 'wp_quiz_fb_users',
						array(
							'uid'			=> absint( $user['id'] ),
							'email'			=> isset( $user['email'] ) ? $user['email'] : '',
							'first_name'	=> $user['first_name'],
							'last_name'		=> $user['last_name'],
							'gender'		=> isset( $user['gender'] ) ? $user['gender'] : '',
							'picture'		=> isset( $user['picture'] ) ? $user['picture'] : '',
							'friends'		=> isset( $user['friends'] ) ? serialize( $user['friends'] ) : '',
							'created_at'	=> date( 'Y-m-d', time() ),
							'updated_at'	=> date( 'Y-m-d', time() ),
						),
						array( '%d', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s' )
					);

					$user['insert_id'] = $wpdb->insert_id;
				} else {
					$user['insert_id'] = $result->id;
				}

				if ( 'user' === $_POST['profile'] ) {
					$return = $this->generate_result_user_image( $_POST['pid'], $user );
				} else {
					$return = $this->generate_result_friend_image( $_POST['pid'], $user );
				}

				if ( ! empty( $return['src'] ) ) {
					$output['src'] = $return['src'];
					$output['desc'] = $return['desc'];
					$output['key'] = $return['key'];
					$output['status'] = 2;
				} else {
					$output['error'] = $return['error'];
				}
			}

			wp_send_json( $output );
		}

		/**
		 * [generate_result_user_image description]
		 * @param  [type] $post_id [description]
		 * @param  [type] $user    [description]
		 * @return [type]          [description]
		 */
		public function generate_result_user_image( $post_id, $user ) {
			global $wpdb;

			$return		= array();
			$results	= get_post_meta( $post_id, 'results', true );

			if ( extension_loaded( 'imagick' ) && ! empty( $results ) ) {

				$index 	= array_rand( $results );
				$result	= $results[ $index ];
				$result['key'] = $index;

				$play = $wpdb->get_row( "SELECT * FROM {$wpdb->prefix}wp_quiz_fb_plays WHERE user_id = '" . $user['insert_id'] . "' AND pid = '" . $post_id . "'" );

				if ( ! $play ) {
					$wpdb->insert(
						$wpdb->prefix . 'wp_quiz_fb_plays',
						array(
							'user_id'	=> absint( $user['insert_id'] ),
							'pid'		=> absint( $post_id ),
						),
						array( '%d', '%d' )
					);
				}

				$names = array(
					'user_first_name'	=> $user['first_name'],
					'user_last_name'	=> $user['last_name'],
					'friend_first_name'	=> '',
					'friend_last_name'	=> '',
				);

				$profile = 'https://graph.facebook.com/' . $user['id'] . '/picture?width=320&height=320';
				$profile = $this->get_redirect_url( $profile );

				$data 	= $this->generate_fb_result( $post_id, $result, $profile, $names );
				$return	= $data;
			}

			return $return;
		}

		public function generate_result_friend_image( $post_id, $user ) {
			global $wpdb;

			$return 	= array();
			$results 	= get_post_meta( $post_id, 'results', true );

			if ( extension_loaded( 'imagick' ) && ! empty( $results ) && ! empty( $user['friends'] ) ) {

				$index 	= array_rand( $results );
				$result	= $results[ $index ];
				$result['key'] = $index;

				$index_2	= array_rand( $user['friends'] );
				$friend		= $user['friends'][ $index_2 ];

				$play = $wpdb->get_row( "SELECT * FROM {$wpdb->prefix}wp_quiz_fb_plays WHERE user_id = '" . $user['insert_id'] . "' AND pid = '" . $post_id . "'" );

				if ( ! $play ) {
					$wpdb->insert(
						$wpdb->prefix . 'wp_quiz_fb_plays',
						array(
							'user_id'	=> absint( $user['insert_id'] ),
							'pid'		=> absint( $post_id ),
						),
						array( '%d', '%d' )
					);
				}

				$profile = 'https://graph.facebook.com/' . $friend['id'] . '/picture?width=320&height=320';
				$profile = $this->get_redirect_url( $profile );

				$friend_name = explode( ' ', $friend['name'] );

				$names = array(
					'user_first_name'	=> $user['first_name'],
					'user_last_name'	=> $user['last_name'],
					'friend_first_name'	=> $friend_name[0],
					'friend_last_name'	=> $friend_name[1],
				);

				$data 	= $this->generate_fb_result( $post_id, $result, $profile, $names );
				$return	= $data;
			}

			return $return;
		}

		public function generate_fb_result( $post_id, $result, $profile, $names ) {

			$return = array( 'src' => '', 'desc' => '', 'error' => '' );

			try {

				$options 	= get_option( 'wp_quiz_pro_default_settings' );
				$settings	= get_post_meta( $post_id, 'settings', true );
				$find 		= array( '%%nomeusuario%%', '%%sobrenome%%', '%%nomeamigo%%', '%%sobrenomeamigo%%' );
				$replace 	= array( $names['user_first_name'], $names['user_last_name'], $names['friend_first_name'], $names['friend_last_name'] );
				$title 		= str_replace( $find, $replace, $result['title'] );
				$desc		= str_replace( $find, $replace, $result['desc'] );
				$upload_dir = wp_upload_dir();

				// Load images
				$profile = new Imagick( $profile );
				$profile->resizeImage( $result['proImageWidth'], $result['proImageHeight'], imagick::FILTER_LANCZOS, 0.9 );
				$profile->roundCorners( $result['imageRadius'], $result['imageRadius'] );

				// Create new image from result
				$output = new Imagick( str_replace( $upload_dir['baseurl'], $upload_dir['basedir'], $result['image'] ) );
				$output->compositeImage( $profile, Imagick::COMPOSITE_DEFAULT, $result['pos_x'], $result['pos_y'] );

				// Annotate it
				if ( ! empty( $title ) ) {

					$draw = new ImagickDraw();
					$draw->setFillColor( $settings['title_color'] );
					$draw->setGravity( 1 );
					$draw->setFontSize( $settings['title_size'] );

					if ( isset( $options['defaults']['external_font'] ) && ! empty( $options['defaults']['external_font'] ) ) {
						$external_font = str_replace( home_url('/'), '', $options['defaults']['external_font'] );
						$draw->setFont( '../' . $external_font );
					} else {
						$draw->setFontFamily( $settings['title_font'] );
					}

					list( $lines, $line_height ) = $this->word_wrap_annotation( $output, $draw, $title, $result['titleImageWidth'] );

					for ( $i = 0; $i < count( $lines ); $i++ ) {
						$output->annotateImage( $draw, $result['pos_title_x'],  $result['pos_title_y'] + $i * $line_height, 0, $lines[ $i ] );
					}
				}

				// Save to new image
				$upload_dir['basedir'] = $upload_dir['basedir'] . '/wp_quiz-result-images';
				$upload_dir['baseurl'] = $upload_dir['baseurl'] . '/wp_quiz-result-images';
				$output_name = 'image-' . rand( 0, 100000 ) . '.png';
				$output->writeImage(  $upload_dir['basedir'] . '/' . $output_name  );

				// Clean up
				$profile->destroy();
				$output->destroy();

				$return['src']	= $upload_dir['baseurl'] . '/' . $output_name;
				$return['desc']	= $desc;
				$return['key']	= $result['key'];

			} catch ( Exception $ex ) {
				$return['error'] = $ex->getMessage();
			}

			return $return;
		}

		public function get_redirect_url( $url ) {

			$response = wp_remote_head( $url );
			$redirect_url = wp_remote_retrieve_header( $response, 'location' );

			return $redirect_url ? $redirect_url : $url;
		}

		public function word_wrap_annotation( $image, $draw, $text, $max_width ) {

			$words = preg_split( '%\s%', $text, -1, PREG_SPLIT_NO_EMPTY );
			$lines = array();
			$i = 0;
			$line_height = 0;

			while ( count( $words ) > 0 ) {
				$metrics = $image->queryFontMetrics( $draw, implode( ' ', array_slice( $words, 0, ++$i ) ) );
				$line_height = max( $metrics['textHeight'], $line_height );

				if ( $metrics['textWidth'] > $max_width || count( $words ) < $i ) {
					if ( 1 === $i ) {
						$i++;
					}

					$lines[] = implode( ' ', array_slice( $words, 0, --$i ) );
					$words = array_slice( $words, $i );
					$i = 0;
				}
			}

			return array( $lines, $line_height );
		}

		public function subscribe_user( $id, $name, $email ) {

			$settings 	= get_post_meta( $id, 'settings', true );
			$options 	= get_option( 'wp_quiz_pro_default_settings' );
			if ( '1' === $settings['force_action'] ) {
				if ( '1' === $options['mail_service'] ) {
					$this->subscribe_mailchimp( $options, $name, $email );
				} else if ( '2' === $options['mail_service'] ) {
					$this->subscribe_getresponse( $options, $name, $email );
				} else if ( '3' === $options['mail_service'] ) {
					$this->subscribe_aweber( $options, $name, $email );
				}
			}
		}

		private function subscribe_aweber( $options, $name, $email ) {

			// check for valid data
			if ( empty( $email ) ) {
				wp_send_json( array(
					'success' => false,
					'error' => esc_html__( 'No email address found.', 'wp-quiz-pro' ),
				) );
			}

			if ( ! filter_var( $email, FILTER_VALIDATE_EMAIL ) ) {
				wp_send_json( array(
					'success' => false,
					'error' => esc_html__( 'Not a valid email address.', 'wp-quiz-pro' ),
				) );
			}

			// Call service subscription method
			try {
				$service = new WP_Quiz_Pro_Subscription_Aweber();
				$list_id		= $options['aweber']['listid'];
				$status = $service->subscribe( $name, $email, $list_id );

				wp_send_json(array(
					'success' => true,
					'status' => $status['status'],
				));
			} catch ( Exception $e ) {
				wp_send_json(array(
					'success' => false,
					'error' => $e->getMessage(),
				));
			}
		}

		private function subscribe_mailchimp( $options, $name, $email ) {

			$mc_api_key		= $options['mailchimp']['api_key'];
			$mc_list_id		= $options['mailchimp']['list_id'];
			$double_optin	= apply_filters( 'wp_quiz_mailchimp_double_notification', false );

			$vendor_path = $this->get_vendor_path();

			if ( $email && null !== $mc_api_key && null !== $mc_list_id ) {

				try {
					if ( ! class_exists( 'Mailchimp' ) ) {
						require_once( $vendor_path . '/Mailchimp.php' );
					}

					$list = new Mailchimp_Lists( new Mailchimp( $mc_api_key ) );
					$merge_vars = null;
					if ( $name ) {
						$fname = $name;
						$lname = '';
						if ( $space_pos = strpos( $name, ' ' ) ) {
							$fname = substr( $name, 0, $space_pos );
							$lname = substr( $name, $space_pos );
						}
						$merge_vars = array( 'FNAME' => $fname, 'LNAME' => $lname );
					}
					$list->subscribe( $mc_list_id, array( 'email' => $email ), $merge_vars, 'html', (bool) $double_optin, true );

				} catch ( Exception $ex ) {}
			}
		}

		private function subscribe_getresponse( $options, $name, $email ) {

			$gr_api_key = $options['getresponse']['api_key'];
			$gr_list_id = $options['getresponse']['campaign_name'];

			$vendor_path = $this->get_vendor_path();

			if ( $email && null !== $gr_api_key && null !== $gr_list_id ) {
				try {
					if ( ! class_exists( 'GetResponse' ) ) {
						require_once( $vendor_path . '/getresponse.php' );
					}

					$api = new GetResponse( $gr_api_key );
					$campaign_ame		= $gr_list_id;
					$subscriber_name		= $name;
					$subscriber_email	= $email;

					$result 		= $api->getCampaigns( 'EQUALS', $campaign_ame );
					$campaigns		= array_keys( (array) $result );
					$campaign_id	= array_pop( $campaigns );

					$api->addContact( $campaign_id, $subscriber_name, $subscriber_email );
				} catch ( Exception $ex ) {}
			}
		}

		public function get_vendor_path() {

			return plugin_dir_path( __FILE__ ) . 'vendor';
		}

		public function check_image_file() {

			$output = array( 'status' => 1 );
			$check = false;
			if ( @getimagesize( $_POST['url'] ) ) {
				$check = true;
			}

			$output['check'] = $check;
			wp_send_json( $output );
		}

		public function check_video_file() {

			$output = array( 'status' => 1 );
			$check = false;
			$id = $_POST['video_id'];
			$url = "http://www.youtube.com/oembed?url=http://www.youtube.com/watch?v=$id&format=json";
			$headers = get_headers( $url );
			if ( '404' !== substr( $headers[0], 9, 3 ) ) {
				$check = true;
			}

			$output['check'] = $check;
			wp_send_json( $output );
		}

		public static function activate_plugin() {

			// Don't activate on anything less than PHP 5.4.0 or WordPress 3.4
			if ( version_compare( PHP_VERSION, '5.4.0', '<' ) || version_compare( get_bloginfo( 'version' ), '3.4', '<' ) || ! function_exists( 'spl_autoload_register' ) ) {
				require_once ABSPATH . 'wp-admin/includes/plugin.php';
				deactivate_plugins( basename( __FILE__ ) );
				wp_die( __( 'Testes Pop requires PHP version 5.4.0 with spl extension or greater and WordPress 3.4 or greater.', 'wp-quiz-pro' ) );
			}

			//Dont't activate if wp quiz is active
			if ( defined( 'WP_QUIZ_VERSION' ) ) {
				deactivate_plugins( basename( __FILE__ ) );
				wp_die( __( 'Please deactivate WP Quiz plugin first to use the Premium features!', 'wp-quiz-pro' ) );
			}

			include( 'inc/activate-plugin.php' );

		}

		public function get_ip() {

			//Just get the headers if we can or else use the SERVER global
			if ( function_exists( 'apache_request_headers' ) ) {
				$headers = apache_request_headers();
			} else {
				$headers = $_SERVER;
			}

			//Get the forwarded IP if it exists
			if ( array_key_exists( 'X-Forwarded-For', $headers ) && filter_var( $headers['X-Forwarded-For'], FILTER_VALIDATE_IP, FILTER_FLAG_IPV4 ) ) {
				$the_ip = $headers['X-Forwarded-For'];
			} else if ( array_key_exists( 'HTTP_X_FORWARDED_FOR', $headers ) && filter_var( $headers['HTTP_X_FORWARDED_FOR'], FILTER_VALIDATE_IP, FILTER_FLAG_IPV4 ) ) {
				$the_ip = $headers['HTTP_X_FORWARDED_FOR'];
			} else {
				$the_ip = filter_var( $_SERVER['REMOTE_ADDR'], FILTER_VALIDATE_IP, FILTER_FLAG_IPV4 );
			}
			return $the_ip;

		}

		public function dismiss_imagick_notice() {
			add_option( 'wp_dismiss_imagick_notice', 'true' );
		}

		public function dismiss_gdlibrary_notice() {
			add_option( 'wp_dismiss_gdlibrary_notice', 'true' );
		}

		public function wp_quiz_pro_get_debug_log() {
			$page = new WP_Quiz_Pro_Page_Support();
			$page->get_debug_log();
		}

		public function fb_share_fix() {

			$data = array_map( 'urldecode', $_GET );
			$result = get_post_meta( $data['id'], 'results', true );
			$result = isset( $result[ $data['rid'] ] ) ? $result[ $data['rid'] ] : array();

			// Picture
			if ( 'r' === $data['pic'] ) {
				$data['source'] = $result['image'];
			} elseif ( 'f' === $data['pic'] ) {
				$data['source'] = wp_get_attachment_url( get_post_thumbnail_id( $data['id'] ) );
			} elseif ( ( substr( $data['pic'], 0, 6 ) === 'image-' ) ) {
			    $upload_dir = wp_upload_dir();
				$upload_dir['baseurl'] = $upload_dir['baseurl'] . '/wp_quiz-result-images';
				$data['source'] = $upload_dir['baseurl'] . '/' . $data['pic'] . '.png';
			} else {
				$data['source'] = false;
			}

			// Description
			if ( 'r' === $data['desc'] ) {
				$data['description'] = $result['desc'];
			} elseif ( 'e' === $data['desc'] ) {
				$data['description'] = get_post_field( 'post_excerpt', $data['id'] );
			} else {
				$data['description'] = false;
			}

			if ( $data['description'] ) {

			    $first = array( '%%nomeusuario%%', '%%nomeamigo%%' );
			    $last = array( '%%sobrenome%%', '%%sobrenomeamigo%%' );

			    $data['description'] = str_replace( $first, $data['nf'], $data['description'] );
			    $data['description'] = str_replace( $last, $data['nl'], $data['description'] );
			}

			$settings = get_option( 'wp_quiz_pro_default_settings' );
			$url = ( is_ssl() ? 'https' : 'http' ) . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";

			global $post;
			$pid  = $post ? $post->ID : $data['id'];
			$original_url = get_permalink( $pid );
			?>
			<html>
				<head>
					<title><?php wp_title( '' ) ?></title>
					<meta property="fb:app_id" content="<?php echo $settings['defaults']['fb_app_id'] ?>">
					<meta property="og:type" content="website">
					<meta name="twitter:card" content="summary_large_image">
					<meta property="og:url" content="<?php echo esc_url( $url ); ?>">
					<?php if ( ! empty( $data['text'] ) ) : ?>
					<meta property="og:title" content="<?php echo get_the_title( $pid ) ?> - <?php echo esc_attr( $data['text'] ); ?>">
					<meta property="twitter:title" content="<?php echo get_the_title( $pid ) ?> - <?php echo esc_attr( $data['text'] ); ?>">
					<?php endif; ?>
					<?php if ( ! empty( $data['source'] ) ) : ?>
					<meta property="og:image" content="<?php echo esc_url( $data['source'] ); ?>">
					<meta property="twitter:image" content="<?php echo esc_url( $data['source'] ); ?>">
						<?php list( $img_width, $img_height ) = getimagesize( $data['source'] ); ?>
						<?php if ( isset( $img_width ) && $img_width ) : ?>
						<meta property="og:image:width" content="<?php echo $img_width ?>">
						<?php endif; ?>
						<?php if ( isset( $img_height ) && $img_height ) : ?>
						<meta property="og:image:height" content="<?php echo $img_height ?>">
						<?php endif; ?>
					<?php endif; ?>
					<?php if ( ! empty( $data['description'] ) ) : ?>
					<meta property="og:description" content="<?php echo esc_attr( $data['description'] ); ?>">
					<meta property="twitter:description" content="<?php echo esc_attr( $data['description'] ); ?>">
					<?php endif; ?>
					<meta http-equiv="refresh" content="0;url=<?php echo esc_url( $original_url ); ?>">
				</head>
			<body>
				Redirecting please wait....
			</body>
			</html>
			<?php
			exit;
		}

		/**
		 * [inline_script description]
		 * @return [type] [description]
		 */
		public function inline_script() {
			$settings = get_option( 'wp_quiz_pro_default_settings' );
			?>
			<script>
			var quizSiteUrl = '<?php echo home_url( '/' ) ?>';
			<?php if ( ! empty( $settings['analytics']['tracking_id'] ) ) { ?>
				(function(i,s,o,g,r,a,m) {i['GoogleAnalyticsObject']=r;i[r]=i[r]||function() {
				(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
				m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
				})(window,document,'script','//www.google-analytics.com/analytics.js','ga');

				ga('create', '<?php echo $settings['analytics']['tracking_id'] ?>', 'auto');
				ga('send', 'pageview');
			<?php } ?>
			<?php if ( ! empty( $settings['defaults']['fb_app_id'] ) ) { ?>
				window.fbAsyncInit = function() {
					FB.init({
						appId    : '<?php echo $settings['defaults']['fb_app_id'] ?>',
						xfbml    : true,
						version  : 'v2.9'
					});

					FB.getLoginStatus(function( response ) {
						getLogin( response );
					});
				};
				
				(function(d, s, id) {
					var js, fjs = d.getElementsByTagName(s)[0];
					if (d.getElementById(id)) {return;}
					js = d.createElement(s); js.id = id;
					js.src = "//connect.facebook.net/pt_BR/sdk.js";
					fjs.parentNode.insertBefore(js, fjs);
				}(document, 'script', 'facebook-jssdk'));

			<?php 
/*
////////////////////////////////////// ALTEREI AQUI ////////////////////////////////////
////////////////////////////////////// ALTEREI AQUI ////////////////////////////////////
////////////////////////////////////// ALTEREI AQUI ////////////////////////////////////
////////////////////////////////////// ALTEREI AQUI ////////////////////////////////////
////////////////////////////////////// ALTEREI AQUI ////////////////////////////////////
////////////////////////////////////// ALTEREI AQUI ////////////////////////////////////
*/
				global $get_facebook_url;
				$get_facebook_url = $settings['defaults']['fb_app_id2'];
		
/*
////////////////////////////////////// ALTEREI AQUI ////////////////////////////////////
////////////////////////////////////// ALTEREI AQUI ////////////////////////////////////
////////////////////////////////////// ALTEREI AQUI ////////////////////////////////////
////////////////////////////////////// ALTEREI AQUI ////////////////////////////////////
////////////////////////////////////// ALTEREI AQUI ////////////////////////////////////
////////////////////////////////////// ALTEREI AQUI ////////////////////////////////////
*/

					} ?>
			</script>

			<!-- Codigo que exibe URL no topo da página -->
			<?php echo $settings['defaults']['fb_app_id2'] ?>
			<!-- fim Codigo que exibe URL no topo da página -->

			<?php
			if ( is_singular( array( 'wp_quiz' ) ) && isset( $settings['defaults']['share_meta'] ) && 1 === $settings['defaults']['share_meta'] ) {
				global $post, $wpseo_og;
				$twitter_desc = $og_desc = str_replace( array( "\r", "\n" ), '', strip_tags( $post->post_excerpt ) );
				if ( defined( 'WPSEO_VERSION' ) ) {
					remove_action( 'wpseo_head', array( $wpseo_og, 'opengraph' ), 30 );
					remove_action( 'wpseo_head', array( 'WPSEO_Twitter', 'get_instance' ), 40 );
					//use description from yoast
					$twitter_desc 	= get_post_meta( $post->ID, '_yoast_wpseo_twitter-description', true );
					$og_desc		= get_post_meta( $post->ID, '_yoast_wpseo_opengraph-description', true );
				}
				?>
				<meta name="twitter:title" content="<?php echo get_the_title(); ?>">
				<meta name="twitter:description" content="<?php echo $twitter_desc; ?>">
				<meta name="twitter:domain" content="<?php echo esc_url( site_url() ); ?>">
				<meta property="og:url" content="<?php the_permalink(); ?>" />
				<meta property="og:title" content="<?php echo get_the_title(); ?>" />
				<meta property="og:description" content="<?php echo $og_desc; ?>" />
				<?php
				if ( has_post_thumbnail() ) {
					$thumb_id = get_post_thumbnail_id();
					$thumb_url_array = wp_get_attachment_image_src( $thumb_id, 'full', true );
					$thumb_url = $thumb_url_array[0];
					?>
					<meta name="twitter:card" content="summary_large_image">
					<meta name="twitter:image:src" content="<?php echo $thumb_url; ?>">
					<meta property="og:image" content="<?php echo $thumb_url; ?>" />
					<meta itemprop="image" content="<?php echo $thumb_url; ?>">
				<?php
				}
			}
		}

		public function embeded_output() {

			if ( ! isset( $_GET['wp_quiz_id'] ) ) {
				return;
			}

			$qid		= absint( $_GET['wp_quiz_id'] );
			$quiz_html	= $this->register_shortcode( array( 'id' => $qid ) );
			$settings	= get_post_meta( $qid, 'settings', true );
			if ( empty( $quiz_html ) ) {
				return;
			}
			?>
				<link rel='stylesheet' href='<?php echo WP_QUIZ_PRO_ASSETS_URL . 'css/main.css'; ?>' type='text/css' media='all' />
				<link rel='stylesheet' href='<?php echo WP_QUIZ_PRO_ASSETS_URL . 'css/transition.min.css'; ?>' type='text/css' media='all' />
				<link rel='stylesheet' href='<?php echo WP_QUIZ_PRO_ASSETS_URL . 'css/embed.min.css'; ?>' type='text/css' media='all' />
				<style>
					.wq_embedToggleQuizCtr{ display: none; }
				</style>
			<?php
			if ( 'traditional' === $settings['skin'] ) {
				?>
					<link rel='stylesheet' href='<?php echo WP_QUIZ_PRO_ASSETS_URL . 'css/traditional-skin.css'; ?>' type='text/css' media='all' />
				<?php
			} else if ( 'flat' === $settings['skin'] ) {
				?>
					<link rel='stylesheet' href='<?php echo WP_QUIZ_PRO_ASSETS_URL . 'css/flat-skin.css'; ?>' type='text/css' media='all' />
				<?php
			}
			$this->inline_script();
			?>
				<script>
					var wq_l10n = {"correct": "Correct !", "wrong": "Wrong !","captionTrivia":"You got %%score%% out of %%total%%","captionTriviaFB":"I got %%score%% out of %%total%%, and you?","youVoted":"You voted","nonce": "<?php echo wp_create_nonce( 'ajax-quiz-content' ) ?>"};
				</script>
			<?php

			echo '<div class="wq_embed">' . $quiz_html . '</div>';
			?>
				<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
				<script src="<?php echo WP_QUIZ_PRO_ASSETS_URL . 'js/embed.min.js'; ?>"></script>
				<script src="<?php echo WP_QUIZ_PRO_ASSETS_URL . 'js/transition.min.js'; ?>"></script>
				<script src="<?php echo WP_QUIZ_PRO_ASSETS_URL . 'js/jquery.flip.min.js'; ?>"></script>
				<script src="<?php echo WP_QUIZ_PRO_ASSETS_URL . 'js/hammer.min.js'; ?>"></script>
				<script src="<?php echo WP_QUIZ_PRO_ASSETS_URL . 'js/dynamics.min.js'; ?>"></script>
				<script src="<?php echo WP_QUIZ_PRO_ASSETS_URL . 'js/jquery.jTinder.min.js'; ?>"></script>
				<script src="<?php echo WP_QUIZ_PRO_ASSETS_URL . 'js/main.min.js'; ?>"></script>
			<?php
			die();
		}

		/**
		 * [connect_aweber description]
		 * @return [type] [description]
		 */
		public function connect_aweber() {

			// check for data
			$aweber_code = isset( $_REQUEST['aweber_code'] ) ? $_REQUEST['aweber_code'] : array();
			if ( empty( $aweber_code ) ) {
				wp_send_json( array(
					'success' => false,
					'error' => esc_html__( 'No aweber authorization code found.', 'wp-quiz-pro' ),
				) );
			}

			try {
				$service = new WP_Quiz_Pro_Subscription_Aweber();
				$data = $service->connect( $aweber_code );

				wp_send_json(array(
					'success' => true,
					'data' => $data,
				));
			} catch ( Exception $e ) {
				wp_send_json(array(
					'success' => false,
					'error' => $e->getMessage(),
				));
			}
		}
	}

	/**
	 * Main instance of WP_Quiz_Pro_Plugin.
	 *
	 * Returns the main instance of WP_Quiz_Pro_Plugin to prevent the need to use globals.
	 *
	 * @return WP_Quiz_Pro_Plugin
	 */

	function wp_quiz_pro() {
		return WP_Quiz_Pro_Plugin::get_instance();
	}

endif;

add_action( 'plugins_loaded', 'wp_quiz_pro', 10 );
register_activation_hook( __FILE__, array( 'WP_Quiz_Pro_Plugin', 'activate_plugin' ) );

 

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

  • Similar Content

    • By Elisame Araújo
      Seguinte, estou criando uma página dinâmica para um site de clã de jogos e essa página vai listar todos os membros. Até aí, tudo bem, eu consegui buscar dentro do banco de dados os nomes dos membros, mas, quando preciso com que uma div que abre um lightbox com resumo do perfil do membro, acaba retornando apenas o resultado referente a primeira ID, no caso a 1. O que rola é todos os membros, ficam com a mesma informação de resumo curto e UF, por exemplo, mesmo que no banco de dados isso seja individual. Para explicar melhor:
       
      Este código, busca os membros e algumas colunas no banco de dados.
      $conecta = mysqli_connect($servidor,$usuario,$senha,$banco); if(mysqli_connect_errno()) { die("Falha ao se conectar com: " . mysqli_connect_errno()); } //Consulta Membros $membros = "SELECT m.id, m.nick, m.estado, m.idstatus, m.resumocurto, m.resumolongo, m.data_cadastro, m.canalyt, assalto, medico, suporte, atirador, pilotoaviao, tanque, pilotoheli "; $membros .= " FROM membros as m "; $membros .= " JOIN afinclasse as af "; $membros .= " on m.id = af.id "; $membros .= " where af.id and m.id "; $resultados = mysqli_query($conecta,$membros); if(!$resultados) { die("Falha na consulta de dados. A coluna da tabela selecionada não existe ou seu nome está incorreto."); } ?> Que em seguida são exibidos dentro de:
      <h3 style="margin-top: 25px;"><strong>Membros Ativos</strong></h3> <div class="agileinfo-team-grids"> <?php while($membros = mysqli_fetch_assoc($resultados)) { ?> <!--- INÍCIO----> <div class="col-md-3 wthree-team-grid usuario-foto"> <img src="images/profile-pic/pic-temp.png" alt="" /> <h4><a href="perfil.php?usuario=<?php echo $membros['nick'] ?>"><?php echo $membros['nick'] ?></a> #<?php echo $membros['id'] ?><br> <span class="badge-membro">Membro</span> </h4> <div class="badge alinhamento-mais"><a href="#" data-toggle="modal" data-target="#adbr_killer">Resumo</a></div> </div> <div class="modal about-modal fade" id="adbr_killer" tabindex="-1" role="dialog"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button> <h4 class="modal-title">Resumo Rápido</h4> </div> <div class="modal-body"> <div class="agileits-w3layouts-info"> <p><strong>Apresentação Curta:</strong> <?php echo $membros["resumocurto"] ?></p> <p><strong>Estado:</strong> <?php echo $membros['estado'] ?></p> <p><strong>Classe Preferida:</strong> Médico <img src="images/classes/medic.png" width="26" class="alinhamento-estado"></p> <p><strong>Jogos:</strong> <div class="Qtip"> <img src="images/jogos/bf2.png" width="26" class="alinhamento-estado"> <span class="Qtiptext">Battlefield 2</span> </div> <div class="Qtip"> <img src="images/jogos/bf3.png" width="26" class="alinhamento-estado"> <span class="Qtiptext">Battlefield 3</span> </div> <div class="Qtip"> <img src="images/jogos/bf4.png" width="26" class="alinhamento-estado"> <span class="Qtiptext">Battlefield 4</span> </div> <div class="Qtip"> <img src="images/jogos/bf1.png" width="26" class="alinhamento-estado"> <span class="Qtiptext">Battlefield 1</span> </div> <div class="Qtip"> <img src="images/jogos/bfv.png" width="26" class="alinhamento-estado"> <span class="Qtiptext">Battlefield V</span> </div> </p> <p><strong>Patente na Platoon:</strong> Cabo</p> </div> </div> </div> </div> </div> <!--- FIM ----> </div> Porém, quando dentro deste código em específico (abaixo), no caso, que abre um lightbox, ele repete os dados da ID 1 do BD, não seguindo, pra ID 2, ID 3, etc.
      No caso são as variáveis "resumocurto" e "estado" que se repetem igualmente para todos.
      <div class="modal about-modal fade" id="adbr_killer" tabindex="-1" role="dialog"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button> <h4 class="modal-title">Resumo Rápido</h4> </div> <div class="modal-body"> <div class="agileits-w3layouts-info"> <p><strong>Apresentação Curta:</strong> <?php echo $membros["resumocurto"] ?></p> <p><strong>Estado:</strong> <?php echo $membros['estado'] ?></p> <p><strong>Classe Preferida:</strong> Médico <img src="images/classes/medic.png" width="26" class="alinhamento-estado"></p> <p><strong>Jogos:</strong> "Lista de Jogos"</p> <p><strong>Patente na Platoon:</strong> Cabo</p> O mais engraçado é, quando eu faço essa busca dentro de uma lista <ul> ou <ol>, ele retorna os dados normalmente para cada perfil.
      <ul> <li>Nick: <?php echo $membros["nick"] ?> <strong>#<?php echo $membros["id"] ?></strong></li> <li>Ativo: <?php echo $membros["idstatus"] ?></li> <li>Estado: <?php echo $membros["estado"] ?></li> <li>Resumo Curto: <?php echo $membros["resumocurto"] ?></li> <li>Resumo Longo: <?php echo $membros["resumolongo"] ?></li> <li>Assalto: <?php echo $membros["assalto"] ?></li> <li>Médico: <?php echo $membros["medico"] ?></li> <li>Suporte: <?php echo $membros["suporte"] ?></li> <li>Atirador: <?php echo $membros["atirador"] ?></li> <li>Piloto de Avião: <?php echo $membros["pilotoaviao"] ?></li> <li>Tanque: <?php echo $membros["tanque"] ?></li> <li>Piloto de Heli: <?php echo $membros["pilotoheli"] ?></li> <li>Canal Youtube: <a href="<?php echo $membros['canalyt'] ?>" target="_blank">Link</a></li> <li>Adicionado Em: <?php echo date('d-m-Y / H:i:s', strtotime($membros['data_cadastro'])) ?></li> </ul> Existe alguma limitação no PHP para ele exibir dados numa DIV que abre a partir de um lightbox? Porque ele só retorna esses dados normalmente através de uma lista? O que eu preciso modificar no código em si para fazer com que ele apareça normalmente?
       
      Não sei se ficou claro...
    • By alh
      Olá Pessoal,
       
      Tenho um script em javascript do mercado livre, que é um botão que vem no formato de script, o código que vou postar abaixo é o script, que ao ser inserido dentro do site vira um botão de "Comprar".

      Preciso fazer com que este botão se inicie automáticamente sem ser clicado pode ser em PHP ou Javascript o comando!!
       
      <script    src="https://www.mercadopago.com.br/integrations/v1/web-payment-checkout.js"    data-preference-id="<?php echo $preference2->id; ?>" data-elements-color="#0D55E7"  data-button-label-color="#0D55E7"    data-button-label="CONTINUAR" >   </script>  
    • By Giovanird
      Olá a todos!

      Abaixo lista minha estrutura em Json. Há grupos que faltam um objeto (TIPO) e ao listar recebo o erro  por não encontrá-lo.
      Existe alguma maneira de verificar se este objeto existe e caso não, ignorar?

      Desde já agradeço a atenção.

       
      ESTUTURA JSON: [ { “titulo”: “JSON”, “data”: “20/10/2020”, “ano”: 2020, “tipo”: novo }, { “titulo”: “HTML”, “data”: “20/10/2020”, “ano”: 2020, “tipo”: usado }, { “titulo”: “PHP”, “data”: “20/10/2020”, “ano”: 2020 } ] CAPTURANDO OS DADOS: $titulo = $decode->titulo; $data = $decode->data; $ano = $decode->ano; $tipo = $decode->tipo;  
       
    • By maurohpg
      Estou fazendo uma gravação dos dados no banco e ao mesmo tempo eu faço upload de um arquivo pdf. 

      Acontece que a gravação do dados está ok, grava o nome do arquivo pdf no banco, mas não grava o arquivo pdf na pasta, e não me retorna nenhum erro, segue no script ou no log.
       
      Alguém pode dar uma luz no que estou fazendo errado? É bem simples, nas não encontro o erro.
       
      <?php include("../config.php"); include("verifica.php"); include("../tags.php"); $acao = strip_tags( $_GET['acao'] ); /* Informa o nível dos erros que serao exibidos */ error_reporting(E_ALL); /* Habilita a exibiçao de erros */ ini_set("display_errors", 1); ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <?php echo "<?xml version=\"1.0\" encoding=\"iso-8859-2\"?".">"; ?> <title><?php echo $nomeL ?></title> <link href="css/css.css" rel="stylesheet" type="text/css" /> <!-- desenvolvido por Mauro Garcia --> <script type="text/javascript" src="../js/funcoes.js"></script> <script src="ckeditor/ckeditor.js"></script> </head> <body> <?php include("topo.php"); ?> <div id="content_interno"> <?php include("menu.php"); ?> <div id="admin"> <table width="774" border="0" cellspacing="0" cellpadding="0"> <tr> <td width="82%"><p>INSERIR REGISTRO</p></td> <td width="18%"><a href="privacidade_add.php"><br /> </a></td> </tr> </table> <br /> <br /> <?php if( empty( $acao ) ) { ?> <form name="add" action="privacidade_add.php?acao=add" method="post" enctype="multipart/form-data"> <div class="form_add"> <table width="650" border="0" align="left" cellpadding="5" cellspacing="5"> <tr> <td colspan="4"><strong>Mostrar no site</strong></td> </tr> <tr> <td colspan="4"><select name="ativo"> <option value="1">Sim</option> <option value="0">N&atilde;o</option> </select></td> </tr> <tr> <td height="5" colspan="4"><img src="img/spacer.gif" width="5" height="5" /></td> </tr> <tr> <td colspan="4"><strong>C&oacute;digo, se n&atilde;o houver deixe em branco</strong></td> </tr> <tr> <td colspan="4"><input name="codigo" type="text" id="codigo" onfocus="dentro(this, 'Código')" onblur="fora(this, 'Código')" value="Código" size="20" maxlength="10"/></td> </tr> <tr> <td colspan="4"><img src="img/spacer.gif" width="5" height="5" /></td> </tr> <tr> <td colspan="4"><input name="hora" type="text" id="hora" onfocus="dentro(this, 'Data')" onblur="fora(this, 'Data')" value="Data" size="20" maxlength="10"/> dd/mm/aaaa</td> </tr> <tr> <td colspan="4"><img src="img/spacer.gif" width="5" height="5" /></td> </tr> <tr> <td colspan="4"><strong>T&iacute;tulo (At&eacute; 200 caracteres): </strong></td> </tr> <tr> <td colspan="4"><input name="nome_imovel" type="text" id="nome_imovel" onfocus="dentro(this, 'Título')" onblur="fora(this, 'Título')" value="T&iacute;tulo" size="80" maxlength="200"/></td> </tr> <tr> <td colspan="4"><img src="img/spacer.gif" alt="" width="5" height="5" /></td> </tr> <tr> <td colspan="4"><strong><font color="#FF0000">N</font><font color="#FF0000">&atilde;o esquecer de selecionar</font></strong></td> </tr> <tr> <td width="174"><select name="id_negocio_tipo"> <option value="">Categoria</option> <?php $sql = mysql_query("SELECT id, tipo FROM negocio_tipo ORDER BY tipo ASC"); while( $linha = mysql_fetch_array( $sql ) ){ echo '<option value="' . $linha['id'] . '"> ' . $linha['tipo'] . '</option>'; } ?> </select></td> <td width="192">&nbsp;</td> <td width="184">&nbsp;</td> <td width="184">&nbsp;</td> </tr> <tr> <td colspan="4"><img src="img/spacer.gif" alt="" width="5" height="5" /></td> </tr> <tr> <td colspan="4"><strong>Resumo</strong></td> </tr> <tr> <td colspan="4"><textarea name="msg" id="msg" cols="60" rows="5" onfocus="dentro(this, 'Texto')" onblur="fora(this, 'Texto')"></textarea></td> </tr> <tr> <td colspan="4"><img src="img/spacer.gif" alt="" width="5" height="5" /></td> </tr> <tr> <td colspan="4"><strong>PDF</strong></td> </tr> <tr> <td colspan="4"><input id="fakeupload" name="fakeupload" class="fakeupload" type="text" /> <input id="arquivo" name="arquivo" class="foto" type="file" onchange="this.form.fakeupload.value = this.value;" /></td> </tr> <tr> <td><a href="javascript:document.add.submit();"><img src="img/bt_gravar.png" width="74" height="26" /></a></td> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> </tr> <tr> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> </tr> </table> </div> </form> <?php } // fim da açao EMPTY if( $acao == 'add') { extract( $_POST, EXTR_OVERWRITE); // extrai os dados do POST, transformando os indices em nomes. Sobrescreve as variaveis existentes, se houver $sql1 = mysql_query("SELECT id FROM privacidade WHERE codigo='$codigo'"); $ttlCodigo = mysql_num_rows($sql1); if( !empty( $codigo ) && $ttlCodigo > 0){ echo "<script language='JavaScript'> alert('Código duplicado, informe outro código'); window.location.href='javascript:history.go(-1)' </script>"; exit; } ///////////////// TRATA if( !empty( $arquivo['name'] ) ) { if(preg_match( '/\.(pdf)+$/', $arquivo["type"])){ echo "<script language='JavaScript'> alert('Arquivo em formato inválido! Formato aceito: PDF'); window.location.href='javascript:history.go(-1)' </script>"; exit; } // Verifica tamanho do arquivo if($arquivo["size"] > 200000000) { echo "<script language='JavaScript'> alert('A imagem deve ser de no máximo 2020680 bytes'); window.location.href='javascript:history.go(-1)' </script>"; exit; } preg_match("/\.(pdf)+$/", $arquivo["name"], $ext); $imagem_nome = md5(uniqid(time())) . "." . $ext[1]; $imagem_dir = "../uploads/pdf/" . $imagem_nome; }else{ // se nao for informado nenhum arquivo echo "<script language='JavaScript'> alert('A imagem da notícia esta faltando'); window.location.href='javascript:history.go(-1)' </script>"; exit; // Repassa a variável do upload $arquivo = isset($_FILES["arquivo"]) ? $_FILES["arquivo"] : FALSE; // Caso a variável $arquivo contenha o valor FALSE, esse script foi acessado // diretamente, então mostra um alerta para o usuário if(!$arquivo) { echo "Não acesse esse arquivo diretamente!"; } // Imagem foi enviada, então a move para o diretório desejado else { // Diretório para onde o arquivo será movido $imagem_dir = "../uploads/pdf/"; // Move o arquivo // Lembrando que se $arquivo não fosse declarado no começo do script, // você estaria usando $_FILES["arquivo"]["tmp_name"] e $_FILES["arquivo"]["name"] if (move_uploaded_file($arquivo["tmp_name"], $imagem_dir . $arquivo["name"])) { echo "Arquivo Enviado com sucesso!"; } else { echo "Erro ao enviar seu arquivo!"; } } } $sql = mysql_query("INSERT INTO privacidade (id_negocio_tipo, codigo, foto_exibicao, msg, ativo, nome_imovel, hora) VALUES ('$id_negocio_tipo','$codigo','$imagem_nome','$msg','$ativo','$nome_imovel','$hora')") or print(mysql_error()); $ultimo_id = mysql_insert_id(); echo '<div id="sucesso"><font color="#5a5a5a" size="3" face="Arial, Helvetica, sans-serif"><font color="#009900" size="4"><b>Registro inserido com sucesso</b></font><br /><br /> <a href="privacidade_add.php">CADASTRAR OUTRO</a><br><br> <a href=privacidade.php>clique aqui para voltar</a> </font></div>'; } ?> </div> </div> <script> // This call can be placed at any point after the // <textarea>, or inside a <head><script> in a // window.onload event handler. // Replace the <textarea id="editor"> with an CKEditor // instance, using default configurations. CKEDITOR.replace( 'msg' ); </script> <?php include("rodape.php"); ?> </body> </html>  
    • By anabeatrizzz
      2. Por que PHP é a mais utilizada em projetos? Explique.
       
      3. São 24 anos de desenvolvimento em PHP, o que faz ele durar tanto na área da programação? Explique.
       
      4. Você acredita que o PHP vai morrer ou não? Explique.
       
      5. Explique o que seria esta HHVM que as empresas utilizam.
       
      6. PHP tem a facilidade de criar APIs, quais seriam as vantagens na hora de desenvolver aplicativos para celular? Explique.
       
      7. Explique um pouco sobre o Laravel, Zend Framework, Sympony, lumen, codelgniter que foram surgindo ao decorrer dos anos.
       
      8. “O PHP veio da WEB e da WEB ele permanecerá”. O que essa frase significaria para você? Explique.
       
      9. Como funcionariam as comunidades em PHP? Por que existem tantas pessoas ainda usando a linguagem? Explique.
       
      10. O PHP vem se modernizando durante anos, quais seriam estas evoluções dele? Explique.