<?php

if (! defined('ABSPATH') ) { exit;
}
if (!class_exists('legalPages') ) 
{
class legalPages
{
    var $plugin_url;
    var $plugin_image_url;
    var $tablename;
    var $popuptable;

    function __construct()
    {
        global $table_prefix;

        $this->plugin_url = trailingslashit(WP_PLUGIN_URL.'/'.dirname(plugin_basename(__FILE__)));
        $this->plugin_image_url = trailingslashit(WP_PLUGIN_URL.'/'.dirname(plugin_basename(__FILE__))).'images/';
        $this->tablename = $table_prefix . "legal_pages";
        $this->popuptable = $table_prefix . "lp_popups";
        $this->add_actions();
        add_action('admin_menu', array($this, 'admin_menu'));
        //add_action('admin_head', array($this, 'wpgattack_enqueue_editor'));
        add_shortcode('wp-legalpage', array($this, 'shortCode'));
        add_shortcode('wp-legalpopup', array($this, 'popupshortCode'));
        add_filter('the_content', array($this,'lpShortcode'));
        add_filter('the_excerpt', array($this,'lpShortcode'));
        add_action('wp_head', array($this,'lp_css'));
        add_action('wp_enqueue_scripts', array($this,'enqueue_frontend_script'));
        add_action('wp_footer', array($this,'wp_legalpages_show_eu_cookie_message'));
        add_action('wp_head', array($this, 'disable_legal_pages_comments'));
        add_action('wp_head', array($this, 'disable_legal_pages_adults'));

            
        $general = get_option('lp_general');

        //add_action('add_meta_boxes', array($this, 'lp_add_custom_box'));
        //add_action('save_post', array($this, 'lp_save_postdata'));

        add_action('admin_notices', array($this,'legal_pages_admin_notices'));

        add_action('wp_dashboard_setup', array($this, 'lp_dashboard_setup'));

        $general = get_option('lp_general');

        /*if(isset($general['is_adult']) && $general['is_adult'] == 1 && !isset($_COOKIE['is_user_adult'])) {
            add_action('wp_enqueue_scripts', array($this , 'lp_is_adult_scripts'));
            add_action('wp_footer', array($this , 'print_is_adult_popup' ));
        }*/
    }


    function disable_legal_pages_adults()
    { 
        $post_id = get_the_ID();
        $general = get_option('lp_general'); 
        $adult_value = get_option("lp_eu_adult_page_enable_".$post_id);
        $age_vefi_popup_setting = get_option('_lp_require_for');
        if(   trim($adult_value) != "" ) {
            if($adult_value == 'ON' && !isset($_COOKIE['is_user_adult']) )
            {              
                add_action('wp_enqueue_scripts', array($this , 'lp_is_adult_scripts'));
                add_action('wp_footer', array($this , 'print_is_adult_popup' ));
            }
           
        }  else  {           
            $general = get_option('lp_general');             
            $age_vefi_popup_setting = get_option('_lp_require_for');
            if(isset($general['is_adult']) && $general['is_adult'] == 1 && !isset($_COOKIE['is_user_adult']) ) {
                add_action('wp_enqueue_scripts', array($this , 'lp_is_adult_scripts'));
                add_action('wp_footer', array($this , 'print_is_adult_popup' ));
            }
        }
    }

    //Disable comments for legalpages
    function disable_legal_pages_comments()
    {
        $post_id=get_the_ID();
        $meta=get_post_meta($post_id, 'is_legal', true);

        $general = get_option('lp_general');
        if(isset($general['disable_comments']) && $general['disable_comments'] == 1 && $meta=='yes') {
            add_filter('comments_open', array($this ,'legal_disable_comments'));
        }
    }

    function legal_pages_admin_notices()
    {
        if (!get_option('legal_pages_notice_shown') && !is_plugin_active(LP_PLUGIN_DIR."/legal-pages-pro.php") ) {
            echo "<div class='updated'><p>If you have recently updated to Version 4.5 or greater , please de-activate and activate WPLegalPages once, in order to refresh your legal page templates.</p></div>";
            update_option('legal_pages_notice_shown', 'true');
        }
    }

    function legal_disable_comments( $open )
    {
        $post = get_post_meta(get_the_ID(), 'is_legal');

        if ($post[0] == 'yes' ) {
            $open = false;
        }

        return $open;
    }

    function lp_dashboard()
    {
        echo '<span style="line-height:18px;">WP Legal Eagle plugin is the easiest method to create WP legal Eagle for your website.</span>';
    }

    function lp_dashboard_setup()
    {
        wp_add_dashboard_widget('lp_dashboard_widget', 'WP Legal Eagle', array($this, 'lp_dashboard'));
    }

    function install()
    {
        global $wpdb;

        //echo dirname(__FILE__) . '/templates/Terms.php';exit;
        $terms_forced = file_get_contents(dirname(__FILE__) . '/templates/Terms-latest.html');
        $terms = file_get_contents(dirname(__FILE__) . '/templates/Terms.html');
        $privacyCalifornia = file_get_contents(dirname(__FILE__) . '/templates/privacyCalifornia.html');
        $privacy = file_get_contents(dirname(__FILE__) . '/templates/privacy.html');
        $earnings = '<div style="text-align: center; font-weight: bold;">Earnings Disclaimer<br></div><br><br>EVERY EFFORT HAS BEEN MADE TO ACCURATELY REPRESENT THIS PRODUCT AND IT\'S POTENTIAL. EVEN THOUGH THIS INDUSTRY IS ONE OF THE FEW WHERE ONE CAN WRITE THEIR OWN CHECK IN TERMS OF EARNINGS, THERE IS NO GUARANTEE THAT YOU WILL EARN ANY MONEY USING THE TECHNIQUES AND IDEAS IN THESE MATERIALS. EXAMPLES IN THESE MATERIALS ARE NOT TO BE INTERPRETED AS A PROMISE OR GUARANTEE OF EARNINGS. EARNING POTENTIAL IS ENTIRELY DEPENDENT ON THE PERSON USING OUR PRODUCT, IDEAS AND TECHNIQUES. WE DO NOT PURPORT THIS AS A "GET RICH SCHEME."<br> <br> ANY CLAIMS MADE OF ACTUAL EARNINGS OR EXAMPLES OF ACTUAL RESULTS CAN BE VERIFIED UPON REQUEST. YOUR LEVEL OF SUCCESS IN ATTAINING THE RESULTS CLAIMED IN OUR MATERIALS DEPENDS ON THE TIME YOU DEVOTE TO THE PROGRAM, IDEAS AND TECHNIQUES MENTIONED, YOUR FINANCES, KNOWLEDGE AND VARIOUS SKILLS. SINCE THESE FACTORS DIFFER ACCORDING TO INDIVIDUALS, WE CANNOT GUARANTEE YOUR SUCCESS OR INCOME LEVEL. NOR ARE WE RESPONSIBLE FOR ANY OF YOUR ACTIONS.<br> <br> MATERIALS IN OUR PRODUCT AND OUR WEBSITE MAY CONTAIN INFORMATION THAT INCLUDES OR IS BASED UPON FORWARD-LOOKING STATEMENTS WITHIN THE MEANING OF THE SECURITIES LITIGATION REFORM ACT OF 1995. FORWARD-LOOKING STATEMENTS GIVE OUR EXPECTATIONS OR FORECASTS OF FUTURE EVENTS. YOU CAN IDENTIFY THESE STATEMENTS BY THE FACT THAT THEY DO NOT RELATE STRICTLY TO HISTORICAL OR CURRENT FACTS. THEY USE WORDS SUCH AS "ANTICIPATE," "ESTIMATE," "EXPECT," "PROJECT," "INTEND," "PLAN," "BELIEVE," AND OTHER WORDS AND TERMS OF SIMILAR MEANING IN CONNECTION WITH A DESCRIPTION OF POTENTIAL EARNINGS OR FINANCIAL PERFORMANCE.<br> <br> ANY AND ALL FORWARD LOOKING STATEMENTS HERE OR ON ANY OF OUR SALES MATERIAL ARE INTENDED TO EXPRESS OUR OPINION OF EARNINGS POTENTIAL. MANY FACTORS WILL BE IMPORTANT IN DETERMINING YOUR ACTUAL RESULTS AND NO GUARANTEES ARE MADE THAT YOU WILL ACHIEVE RESULTS SIMILAR TO OURS OR ANYBODY ELSES, IN FACT NO GUARANTEES ARE MADE THAT YOU WILL ACHIEVE ANY RESULTS FROM OUR IDEAS AND TECHNIQUES IN OUR MATERIAL.<br>  <br> The author and publisher disclaim any warranties (express or implied), merchantability, or fitness for any particular purpose. The author and publisher shall in no event be held liable to any party for any direct, indirect, punitive, special, incidental or other consequential damages arising directly or indirectly from any use of this material, which is provided "as is", and without warranties.<br> <br> As always, the advice of a competent legal, tax, accounting or other  professional should be sought.<br> <br> [Domain] does not warrant the performance, effectiveness or applicability of any sites listed or linked to on [Domain]<br> <br> All links are for information purposes only and are not warranted for content, accuracy or any other implied or explicit purpose.<br> <br>';

        $disclaimer = file_get_contents(dirname(__FILE__) . '/templates/disclaimer.html');
        $testimonials = file_get_contents(dirname(__FILE__) . '/templates/testimonial-disclosure.html');
        $linking = file_get_contents(dirname(__FILE__) . '/templates/linking-policy.html');
        $refund = file_get_contents(dirname(__FILE__) . '/templates/refund-policy.html');
        $return_refund = file_get_contents(dirname(__FILE__) . '/templates/return-refund-policy.html');
        $affiliate = file_get_contents(dirname(__FILE__) . '/templates/affiliate-agreement.html');
        $disclosure = file_get_contents(dirname(__FILE__) . '/templates/affiliate-disclosure.html');
        $antispam = file_get_contents(dirname(__FILE__) . '/templates/antispam.html');
        $ftc = file_get_contents(dirname(__FILE__) . '/templates/ftcstatement.html');
        $medical = file_get_contents(dirname(__FILE__) . '/templates/medical-disclaimer.html');
        $amazon = file_get_contents(dirname(__FILE__) . '/templates/amazon-affiliate.html');
        $dart = file_get_contents(dirname(__FILE__) . '/templates/double-dart-cookie.html');
        $external = file_get_contents(dirname(__FILE__) . '/templates/external-links.html');
        $fbpolicy = file_get_contents(dirname(__FILE__) . '/templates/fbpolicy.html');
        $about_us = file_get_contents(dirname(__FILE__) . '/templates/about-us.html');
        $dmca = file_get_contents(dirname(__FILE__) . '/templates/dmca.html');
        $gigitalGoods = file_get_contents(dirname(__FILE__) . '/templates/digital-goods-refund-policy.html');
        $coppa = file_get_contents(dirname(__FILE__) . '/templates/COPPA.html');
        $blogPolicy = file_get_contents(dirname(__FILE__) . '/templates/blog-comments-policy.html');
        $newsletter = file_get_contents(dirname(__FILE__) . '/templates/Newsletter-Subscription-and-Disclaimer.html');
        $gdpr_request_form = file_get_contents(dirname(__FILE__) . '/templates/gdpr-request-form.html');

        // Turn off age verification while install
        update_option( '_lp_require_for', 'content' );

        add_option('lp_excludePage', 'true');
        add_option('lp_general', '');
        add_option('lp_accept_terms', '0');
        add_option('lp_eu_cookie_title', __('A note to our visitors','wpekalegalpage'));
        $message_body="This website has updated its privacy policy in compliance with EU Cookie legislation. Please read this to review the updates about which cookies we use and what information we collect on our site. By continuing to use this site, you are agreeing to our updated privacy policy.";
        add_option('lp_eu_cookie_message', htmlentities($message_body));
        add_option('lp_eu_cookie_enable', 'OFF');
        add_option('lp_eu_box_color', '#000000');
        add_option('lp_eu_button_color', '#e3e3e3');
        add_option('lp_eu_button_text_color', '#333333');
        add_option('lp_eu_text_color', '#FFFFFF');
        add_option('lp_eu_link_color', '#8f0410');
        add_option('lp_eu_text_size', '12');
        update_option( '_lp_heading', __( 'You must be atleast {age} years of age to visit this site.', 'wplegalpages' ) );

        $sql = "CREATE TABLE IF NOT EXISTS `$this->tablename` (
                  `id` int(11) NOT NULL AUTO_INCREMENT,
                  `title` text NOT NULL,
                  `content` longtext NOT NULL,
                  `notes` text NOT NULL,
                  `contentfor` varchar(200) NOT NULL,
                  PRIMARY KEY (`id`)
                ) ENGINE=MyISAM;";
        $sqlpopup = "CREATE TABLE IF NOT EXISTS `$this->popuptable` (
                  `id` int(11) NOT NULL AUTO_INCREMENT,
                  `popupName` text NOT NULL,
                  `content` longtext NOT NULL,
                  PRIMARY KEY (`id`)
                ) ENGINE=MyISAM;";
        $wpdb->query($sql);
        $wpdb->query($sqlpopup);
        $wpdb->insert($this->tablename, array('title'=>'Terms(forced agreement)','content'=>$terms,'contentfor'=>'1a2b3c4d5e6f7g8h9i'), array('%s','%s','%s'));
        $wpdb->insert($this->tablename, array('title'=>'Terms of Use','content'=>$terms_forced,'contentfor'=>'1a2b3c4d5e6f7g8h9i'), array('%s','%s','%s'));
        $wpdb->insert($this->tablename, array('title'=>'California Privacy Rights','content'=>$privacyCalifornia,'contentfor'=>'1a2b3c4d5e6f7g8h9i10j'), array('%s','%s','%s'));
        $wpdb->insert($this->tablename, array('title'=>'Privacy Policy','content'=>$privacy,'contentfor'=>'1a2b3c4d5e6f7g8h9i'), array('%s','%s','%s'));
        $wpdb->insert($this->tablename, array('title'=>'Earnings Disclaimer','content'=>$earnings,'contentfor'=>'4d5e6f7g8h'), array('%s','%s','%s'));
        $wpdb->insert($this->tablename, array('title'=>'Disclaimer','content'=>$disclaimer,'contentfor'=>'1a2b3c4d5e6f7g8h9i'), array('%s','%s','%s'));
        $wpdb->insert($this->tablename, array('title'=>'Testimonials Disclosure','content'=>$testimonials,'contentfor'=>'1a2b3c4d5e6f7g8h9i'), array('%s','%s','%s'));
        $wpdb->insert($this->tablename, array('title'=>'Linking Policy','content'=>$linking,'contentfor'=>'1a2b3c9i'), array('%s','%s','%s'));
        $wpdb->insert($this->tablename, array('title'=>'Refund-Policy','content'=>$refund,'contentfor'=>'2b3c9i'), array('%s','%s','%s'));
        $wpdb->insert($this->tablename, array('title'=>'Return and Refund Policy','content'=>$return_refund,'contentfor'=>'2b3c9i'), array('%s','%s','%s'));
        $wpdb->insert($this->tablename, array('title'=>'Affiliate Agreement','content'=>$affiliate,'contentfor'=>'3c'), array('%s','%s','%s'));
        $wpdb->insert($this->tablename, array('title'=>'Antispam','content'=>$antispam,'contentfor'=>'3c'), array('%s','%s','%s'));
        $wpdb->insert($this->tablename, array('title'=>'FTC Statement','content'=>$ftc,'contentfor'=>'4d5e7g'), array('%s','%s','%s'));
        $wpdb->insert($this->tablename, array('title'=>'Medical Disclaimer','content'=>$medical,'contentfor'=>'6f'), array('%s','%s','%s'));
        $wpdb->insert($this->tablename, array('title'=>'Amazon Affiliate','content'=>$amazon,'contentfor'=>'7g'), array('%s','%s','%s'));
        $wpdb->insert($this->tablename, array('title'=>'Double Dart Cookie','content'=>$dart,'contentfor'=>'8h'), array('%s','%s','%s'));
        $wpdb->insert($this->tablename, array('title'=>'External Links Policy','content'=>$external,'contentfor'=>'4d5e6f7g8h9i'), array('%s','%s','%s'));
        $wpdb->insert($this->tablename, array('title'=>'Affiliate Disclosure','content'=>$disclosure,'contentfor'=>'4d'), array('%s','%s','%s'));
        $wpdb->insert($this->tablename, array('title'=>'FB Policy','content'=>$fbpolicy,'contentfor'=>'4d'), array('%s','%s','%s'));
        $wpdb->insert($this->tablename, array('title'=>'About Us','content'=>$about_us,'contentfor'=>'1a2b3c4d5e6f7g8h9i'), array('%s','%s','%s'));
        $wpdb->insert($this->tablename, array('title'=>'DMCA','content'=>$dmca,'contentfor'=>'10j'), array('%s','%s','%s'));
        $wpdb->insert($this->tablename, array('title'=>'Digital Goods Refund Policy','content'=>$gigitalGoods,'contentfor'=>'2b3c9i'), array('%s','%s','%s'));
        $wpdb->insert($this->tablename, array('title'=>'COPPA - Children’s Online Privacy Policy','content'=>$coppa,'contentfor'=>'1a2b3c4d5e'), array('%s','%s','%s'));
        $wpdb->insert($this->tablename, array('title'=>'Blog Comments Policy','content'=>$blogPolicy,'contentfor'=>'1a2b3c4d'), array('%s','%s','%s'));
        $wpdb->insert($this->tablename, array('title'=>'Newsletter : Subscription and Disclaimer','content'=>$newsletter,'contentfor'=>'1a2b3c4d5e6f7g8h9i10j'), array('%s','%s','%s'));
        $wpdb->insert($this->tablename, array('title'=>'GDPR Request Form','content'=>$gdpr_request_form,'contentfor'=>'1a2b3c4d5e6f7g8h9i10j'), array('%s','%s','%s'));
    }

    function admin_menu()
    {
        add_menu_page('WP Legal Eagle', 'WP Legal Eagle', 'manage_options', 'legal-pages', array($this, 'adminSetting'));
        $terms = get_option('lp_accept_terms');
        if($terms == 1) {
            add_submenu_page('legal-pages', 'Settings', __('Settings','wplegalpages'), 'manage_options', 'legal-pages', array($this, 'adminSetting'));
            add_submenu_page('legal-pages', 'WP Legal Eagle', __('WP Legal Eagle','wplegalpages'), 'manage_options', 'showpages', array($this, 'showpages'));
            add_submenu_page('legal-pages', 'Create Page', __('Create Page','wplegalpages'), 'manage_options', 'lp-create', array($this, 'createPage'));
            add_submenu_page('legal-pages', 'Create/Edit Templates', __('Create/Edit Templates','wplegalpages'), 'manage_options', 'lp-templates', array($this, 'createTemplates'));
            add_submenu_page('legal-pages', 'Create Popups', __('Create Popups','wplegalpages'), 'manage_options', 'lp-popups', array($this, 'createPopups'));
            add_submenu_page('legal-pages', 'EU Cookies', __('EU Cookies','wplegalpages'), 'manage_options', 'lp-eu-cookies', array($this, 'update_eu_cookies'));
            add_submenu_page('legal-pages', 'Age verification', __('Age verification','wplegalpages'), 'manage_options', 'lp-age-verify', array($this, 'ageVerify'));
        }


    }

    function createPage()
    {
        include_once 'createPage.php';
    }

    function showpages()
    {
        include_once 'showpages.php';
    }
    function createPage1()
    {
        include_once 'createPage1.php';
    }
    function createTemplates()
    {
        include_once 'createTemplates.php';
    }
    function createPopups()
    {
        include_once 'createPopups.php';
    }
    function adminSetting()
    {
        include_once "adminSetting.php";
    }

    function adminTerms()
    {
        include_once "adminTerms.php";
    }

    function adminPrivacy()
    {
        include_once "adminPrivacy.php";
    }

    function adminDisclaimer()
    {
        include_once "adminDisclaimer.php";
    }

    function update_eu_cookies()
    {
        include_once "updateEUCookies.php";
    }

    function ageVerify ()
    {
        include_once "ageVerify.php";
    }

    function deactivate()
    {
        global $wpdb;

        delete_option('lp_excludePage');
        delete_option('lp_accept_terms');
        delete_option('lp_eu_cookie_title');
        delete_option('lp_eu_cookie_message');
        delete_option('lp_eu_cookie_enable');
        delete_option('lp_eu_box_color');
        delete_option('lp_eu_button_color');
        delete_option('lp_eu_button_text_color');
        delete_option('lp_eu_text_color');

        // Delete age verifaction option
        delete_option( '_lp_require_for' );
        
        remove_meta_box('lp_dashboard_widget', 'dashboard', 'side');
        remove_meta_box('lp_dashboard_widget', 'dashboard', 'normal');
        $wpdb->query("Drop table $this->tablename");
        $wpdb->query("Drop table $this->popuptable");
    }

    function lpShortcode($content)
    {
        //$lp_find = array("[Domain]","[Business Name]","[Phone]","[Street]","[City, State, Zip code]","[Country]","[Email]","[Address]","[Niche]","[facebook-url]","[google-url]","[twitter-url]","[linkedin-url]");
        $lp_find = array("[Domain]","[Business Name]","[Phone]","[Street]","[City, State, Zip code]","[Country]","[Email]","[Address]","[Niche]");

        $lp_general = get_option('lp_general');

        $cont = str_replace($lp_find, $lp_general, stripslashes($content));

        /*
        *   Get social icons shortcode content and maps Latitude Longitude from page-content
        *   Added by Kaustubh
        */

        $latitude = '';
        $longitude = '';
        $facebook = '';
        $google = '';
        $twitter = '';
        $linkedin = '';

        $pos = strpos($cont, "[latitude]");
        if($pos !== false) {

            include_once 'map.php';
            $output=add_map();

            if(!empty($output->results)) {
                 $latitude = $output->results[0]->geometry->location->lat;
                 $longitude = $output->results[0]->geometry->location->lng;
            }
            $lp_map_find=array("[latitude]","[longitude]");
            $map_dimension=array("latitude"=>$latitude,"longitude"=>$longitude);
            $cont = str_replace($lp_map_find, $map_dimension, stripslashes($cont));
        }

        $url=(plugins_url()."/wplegalpages/image");

        $facebook_url = isset($lp_general['facebook-url']) ? $lp_general['facebook-url'] : '';

        if($facebook_url) {

            $facebook=array("facebook"=>'<a style="width: 30px; height: 30px; display:inline-block" href="'. $facebook_url.'"><img src="'.$url.'/facebook.png"/></a>');
        }
        $lp_find_facebook=array("[facebook]");
        $cont = str_replace($lp_find_facebook, $facebook, stripslashes($cont));

        $google_url = isset($lp_general['google-url']) ? $lp_general['google-url'] : '';

        if($google_url) {

            $google=array("google"=> '<a style="width: 30px; height: 30px; display:inline-block" href="'. $google_url.'"><img src="'.$url.'/google.png"/></a>');
        }
        $lp_find_google=array("[google]");
        $cont = str_replace($lp_find_google, $google, stripslashes($cont));

        $twitter_url = isset($lp_general['twitter-url']) ? $lp_general['twitter-url'] : '';
        if($twitter_url) {

            $twitter=array("twitter"=>'<a style="width: 30px; height: 30px; display:inline-block" href="'.$twitter_url.'"><img src="'.$url.'/twitter.png"/></a>');
        }
        $lp_find_twitter=array("[twitter]");
        $cont = str_replace($lp_find_twitter, $twitter, stripslashes($cont));

        $linkedin_url = isset($lp_general['linkedin-url']) ? $lp_general['linkedin-url'] : '';
        if($linkedin_url) {
            $linkedin=array("linkedin"=>'<a style="width: 30px; height: 30px; display:inline-block" href="'. $linkedin_url.'"><img src="'.$url.'/linkedin.png"/></a>');
        }
        $lp_find_linkedin=array("[linkedin]");
        $cont = str_replace($lp_find_linkedin, $linkedin, stripslashes($cont));

        return $cont;
    }


    function lp_enqueue_editor()
    {
        wp_enqueue_script('common');
        wp_enqueue_script('jquery-affect');
        wp_admin_css('thickbox');
        wp_print_scripts('post');
        wp_print_scripts('media-upload');
        wp_print_scripts('jquery');
        wp_print_scripts('jquery-ui-core');
        wp_print_scripts('jquery-ui-tabs');

        wp_print_scripts('editor');

        //self bootstrap style sheet
        wp_enqueue_style('bootstrap-min', $this->plugin_url. 'css/bootstrap.min.css');

        //self style sheet
        wp_enqueue_style('style', $this->plugin_url. 'css/style.css');

        wp_enqueue_script('jscolor', $this->plugin_url. 'js/jscolor/jscolor.js');
        wp_enqueue_script('jscolor');

         wp_enqueue_script('jquery-min', $this->plugin_url. 'js/jquery.min.js');
         wp_enqueue_script('bootstrap-min-js', $this->plugin_url. 'js/bootstrap.min.js');

        wp_enqueue_script('tooltip-js', $this->plugin_url. 'js/tooltip.js');

        /* Include the link dialog functions */
        //include ABSPATH . 'wp-admin/includes/internal-linking.php';
        wp_print_scripts('wplink');
        wp_print_styles('wplink');
        add_thickbox();
        wp_admin_css();
        wp_enqueue_script('utils');
        do_action("admin_print_styles-post-php");
        do_action('admin_print_styles');

        //remove_all_filters('mce_external_plugins');
    }

    function shortCode($atts)
    {
        global $wpdb;
        global $post;
        global $wp_query;

        extract(
            shortcode_atts(
                array(
                'tid' => 1
                ), $atts
            )
        );

         $res = $wpdb->get_row($wpdb->prepare('SELECT * from '.$this->tablename.' where id= %d', $tid));


         $content = do_shortcode( $this->lpShortcode($res->content) );
         //$content = "select * from $this->tablename where id='$tid'";


        if(is_single() || is_page()) {
           return html_entity_decode($content);
        }
    }

    function popupshortCode($atts)  {
          //local popup template from template file.
        $post_id = get_the_ID();
        $popup_shortcut_value = get_option('popups_shortcode_'. $post_id);          
        if ($popup_shortcut_value != "") {
            // if value is 1 it means popup is setup for this page.
            //now check if cookies value for popup is "ACCEPTED"
            //if cookies value is alraedy accepted skip again if not setup cookies to 'NOT_ACCEPTED'

            $cookies_var_name = "lp_eu_terms_condition__popup_" . $post_id;


            if ($_COOKIE[$cookies_var_name] != 'ACCEPTED') {
                // echo "&&&";
               // setcookie($cookies_var_name, "NOT_ACCEPTED", time()+60*60*24*365, '/'); 
                $setup_page_cookie = true;
                $show_pop_up = true;
                
            }
            include( dirname( __FILE__ ) . '/templates/popup_shortcode_template.php' );
        }
    }

    function footerPages()
    {
        $general = get_option('lp_general');

        remove_filter('get_pages', 'lp_exclude_pages');
        echo "<ul class='legalfooter'>";
        wp_list_pages("title_li=&include=$general[pagefooter]");
        echo "</ul>";
        add_filter('get_pages', 'lp_exclude_pages');
    }

   

    function lp_css()
    {
        ?>
        <style type="text/css">
           ul.legalfooter li{
            list-style:none;
            float:left;
            padding-right:20px;
           }
           .accept{
            display:none;
            border: 1px solid #000;
            background:#000;
            color:#fff;
            border-radius:3px;
            -moz-border-radius:3px;
            -webkit-border-radius:3px;
            padding:5px;
           }
        </style>
        <?php
    }
   
    function enqueue_frontend_script()
    {
        wp_enqueue_script('jquery-cookie',  $this->plugin_url. 'js/jquery.cookie.js', array('jquery'));

    }

    function wp_legalpages_show_eu_cookie_message() {
        // echo "testing hereee";
        // echo dirname( __FILE__ ) . '/templates/wp_legalpages_show_eu_cookie_message.php' ;
        // exit;

        load_template( dirname( __FILE__ ) . '/templates/wp_legalpages_show_eu_cookie_message.php' );
    }

   /*Adult content site Customo popup */
    function print_is_adult_popup()
    {
        load_template( dirname( __FILE__ ) . '/templates/wp_legalpages_print_is_adult_popup.php' );
    }

  /* Adult content site popup code End*/
        /*function print_is_adult_popup_bk()
        {
            $general = get_option('lp_general');
            ?>
            <a id="inline" style="display:none" href="#data">This shows content of element who has id="data"</a>

            <div id="is_adult_thickbox" style="display:none">
                 <div id="data">
                   <p>This website contains content suitable for adults only . Please proceed only if you are above your country's legal age limit.</p>
                   <a href="#" id="enter_site" style="text-decoration:none;">Yes,I am above my country's legal age limit (Enter)</a>
                   <a href="<?php echo $general['leave-url']; ?>" style="text-decoration:none;" id="leave_site">Leave</a>
                </div>
            </div>

           <script type="text/javascript">
           jQuery(document).ready(function($) {

            window.onload=function(){tb_show("", "#TB_inline?width=570&height=250&inlineId=is_adult_thickbox&modal=true", false);}

            jQuery(window).load(function() {
                if( jQuery(window).width() == 640 ){
                    window_width = 629;
                }else
                    window_width = jQuery(window).width();

                if( TB_WIDTH > window_width ){
                    jQuery("#TB_window").css({marginTop: 0, marginLeft: 0, width: '90%', left: '5%',  top:'10%', height:'80%'});
                    jQuery("#TB_ajaxContent, #TB_iframeContent").css({width: 'auto', height:'80%'});
                    jQuery("#TB_closeWindowButton").css({fontSize: '1.2em', marginRight: '5px'});
                }
                else{
                    jQuery("#TB_window").css({marginLeft: '-' + parseInt((TB_WIDTH / 2),10) + 'px', width: 'auto'});
                }
            });

            //set design to box
            jQuery('#data').css( { 'font-size'   : '0.9em',
                                    'margin'     : '5% 1% 10%',
                                    'font-weight':  'normal',
                                    'line-height':  '2em'
                                 } );

            jQuery('#leave_site').css( { 'background-color' : '#e84c3d',
                                         'color'            : '#fff',
                                         'font-size'        : '1em',
                                         'margin'           : '10px 6px 0 0',
                                         'padding'          : '6px 10px',
                                        'border-radius'     : '4px',
                                        'float'             : 'left'
                                    });

            jQuery('#enter_site').css( { 'background-color' : '#000',
                                         'color'            : '#fff',
                                         'font-size'        : '1em',
                                         'margin'           : '10px 6px 0 0',
                                         'padding'          : '6px 10px',
                                         'border-radius'    : '4px',
                                         'float'            : 'left'
                                    });

            $('#enter_site').click(function(){
             $.cookie("is_user_adult", 1);
                self.parent.tb_remove();
            });

           });
           </script>
            <?php
        }*/

    function lp_is_adult_scripts()
    {
        add_thickbox();
    }
   

 /********************Age Verification Fucntion*****************************/

    private function add_actions()
    {
        $_lp_require_for = get_option('_lp_require_for');
        if($_lp_require_for == 'site')
        {
            add_action( 'wp_footer', array( $this, 'verify_overlay' ) );
        }

        add_action( 'the_content', array( $this, 'restrict_content' ) );

        add_action( 'template_redirect', array( $this, 'verify' ) );

        if ($this->lp_confirmation_required() ) {

            add_action( 'register_form', 'lp_register_form' );

            add_action( 'register_post', 'lp_register_check', 10, 3 );

        }
    }

    public function verify_overlay() {

        if ( !$this->lp_needs_verification() ) {
            return;
        }

        if ( get_option( 'lp_accept_terms' ) != '1' ) {
            return;
        }

        $this->lp_enqueue_editor();
        ?>

        <div id="lp-overlay-wrap">

            <?php do_action( 'lp_before_modal' ); ?>

            <div id="lp-overlay">

                <h1><?php esc_html_e( $this->lp_get_the_heading() ); ?></h1>

                <?php if ( $this->lp_get_the_desc() )
                    echo '<p>' . esc_html( $this->lp_get_the_desc() ). '</p>'; ?>

                <?php do_action( 'lp_before_form' ); ?>

                <?php $this->lp_verify_form(); ?>

                <?php do_action( 'lp_after_form' ); ?>

            </div>

            <?php do_action( 'lp_after_modal' ); ?>

        </div>
    <?php }

    function lp_age_verification(){

        $return = true;

        if ( get_option( 'lp_age_verification') == 'yes' )
            $return = true;
        return (bool) apply_filters( 'lp_age_verification', $return );



    }


    public function restrict_content( $content ) {

        if ( !$this->lp_only_content_restricted() ) {
            return $content;
        }

        if ( is_singular() ) {
            return $content;
        }

        if ( !$this->lp_content_is_restricted() ) {
            return $content;
        }

        return sprintf( apply_filters( 'lp_restricted_content_message', __( 'You must be atleast {age} years of age to view this content.', 'wplegalpages' ) . ' <a href="%2s">' . __( 'Please verify your age', 'wplegalpages' ) . '</a>.' ),
            esc_html( $this->lp_get_minimum_age() ),
            esc_url( get_permalink( get_the_ID() ) )
        );
    }


    function lp_the_heading() {

        echo $this->lp_get_the_heading();
    }

    function lp_the_desc() {

        echo $this->lp_get_the_desc();
    }

    public function verify() {

        if ( ! isset( $_POST['lp-nonce'] ) || ! wp_verify_nonce( $_POST['lp-nonce'], 'verify-age' ) )
            return;

        $redirect_url = remove_query_arg( array( 'wplegalpages', 'verify-error' ), wp_get_referer() );

        $is_verified  = false;

        $error = 1;

        $input_type   = $this->lp_get_input_type();

        switch ( $input_type ) {


            case 'checkbox' :

                if ( isset( $_POST['lp_verify_confirm'] ) && (int) $_POST['lp_verify_confirm'] == 1 )
                    $is_verified = true;
                else
                    $error = 2;

                break;

            default :

                if ( checkdate( (int) $_POST['lp_verify_m'], (int) $_POST['lp_verify_d'], (int) $_POST['lp_verify_y'] ) ) :

                    $age = $this->lp_get_visitor_age( $_POST['lp_verify_y'], $_POST['lp_verify_m'], $_POST['lp_verify_d'] );

                    if ( $age >= $this->lp_get_minimum_age() )
                        $is_verified = true;
                    else
                        $error = 3;

                else :

                    $error = 4;

                endif;

                break;
        }

        $is_verified = apply_filters( 'lp_passed_verify', $is_verified );

        if ( $is_verified == true ) :

            do_action( 'lp_was_verified' );

            if ( isset( $_POST['lp_verify_remember'] ) )
                $cookie_duration = time() +  ( $this->lp_get_cookie_duration() * 60 );
            else
                $cookie_duration = 0;

            setcookie( 'wplegalpages', 1, $cookie_duration, COOKIEPATH, COOKIE_DOMAIN, false );

            wp_redirect( esc_url_raw( $redirect_url ) . '?wplegalpages=' . wp_create_nonce( 'wplegalpages' ) );
            exit;

        else :

            do_action( 'lp_was_not_verified' );

            wp_redirect( esc_url_raw( add_query_arg( 'verify-error', $error, $redirect_url ) ) );
            exit;

        endif;
    }



    function lp_needs_verification() {


        $return = true;


        if ( $this->lp_only_content_restricted() ) :

            $return = false;


            if ( is_singular() && $this->lp_content_is_restricted() )
                $return = true;

        endif;


        $nonce = ( isset( $_REQUEST['wplegalpages'] ) ) ? $_REQUEST['wplegalpages'] : '';

        if ( wp_verify_nonce( $nonce, 'wplegalpages' ) )
            $return = false;


        if ( get_option( '_lp_always_verify', 'guests' ) == 'guests' && is_user_logged_in() )
            $return = false;


        if ( isset( $_COOKIE['wplegalpages'] ) )
            $return = false;

        return (bool) apply_filters( 'lp_needs_verification', $return );
    }


    function lp_content_is_restricted( $id = null ) {

        if ( is_null( $id ) ) {
            $id = get_the_ID();
        }

        $is_restricted = ( 1 == get_post_meta( $id, '_lp_needs_verify', true ) ) ? true : false;

        $is_restricted = apply_filters( 'lp_is_restricted', $is_restricted, $id );

        return $is_restricted;
    }


    function lp_get_the_heading() {
          $find = array('{age}');
          $replace = array($this->lp_get_minimum_age());
          $str = get_option( '_lp_heading', __( 'You must be atleast {age} years of age to visit this site.', 'wplegalpages' ) );
          $strre=str_replace($find, $replace, $str);
//        $age = array("age" => $this->lp_get_minimum_age());
        return sprintf( apply_filters( 'lp_heading', $strre ) );
    }

    function lp_get_the_desc() {

        $desc = apply_filters( 'lp_description', get_option( '_lp_description', __( 'Please verify your age', 'wplegalpages' ) ) );

        if ( ! empty( $desc ) )
            return $desc;
        else
            return false;
    }

    function lp_get_input_type() {

        return apply_filters( 'lp_input_type', get_option( '_lp_input_type', 'dropdowns' ) );
    }


    function lp_get_minimum_age() {

        $minimum_age = get_option( '_lp_minimum_age', 21 );

        $minimum_age = apply_filters( 'lp_minimum_age', $minimum_age );

        return (int) $minimum_age;
    }


    function lp_get_visitor_age( $year, $month, $day ) {

        $age = 0;

        $birthday = new DateTime( $year . '-' . $month . '-' . $day );

        $phpversion = phpversion();

        if ( $phpversion >= '5.3' ) :

            $current  = new DateTime( current_time( 'mysql' ) );
            $age      = $birthday->diff( $current );
            $age      = $age->format( '%y' );

        else :

            list( $year, $month, $day ) = explode( '-', $birthday->format( 'Y-m-d' ) );

            $year_diff  = date_i18n( 'Y' ) - $year;
            $month_diff = date_i18n( 'm' ) - $month;
            $day_diff   = date_i18n( 'd' ) - $day;

            if ( $month_diff < 0 )
                $year_diff--;
            elseif ( ( $month_diff == 0 ) && ( $day_diff < 0 ) )
                $year_diff--;

            $age = $year_diff;

        endif;

        return (int) $age;
    }



    function lp_get_cookie_duration() {

        $cookie_duration = get_option( '_lp_cookie_duration', 720 );

        $cookie_duration = (int) apply_filters( 'lp_cookie_duration', $cookie_duration );

        return $cookie_duration;
    }


    function lp_only_content_restricted() {

        $only_content_restricted = ( 'content' == get_option( '_lp_require_for' ) ) ? true : false;


        $only_content_restricted = apply_filters( 'lp_only_content_restricted', $only_content_restricted );

        return (bool) $only_content_restricted;
    }



    function lp_verify_form() {

        echo $this->lp_get_verify_form();
    }


    function lp_get_verify_form() {

        $input_type = $this->lp_get_input_type();

        $submit_button_label = apply_filters( 'lp_form_submit_label', __( 'VERIFY AGE &raquo;', 'wplegalpages' ) );

        $form = '';

        $form .= '<form id="lp_verify_form" action="' . esc_url( home_url( '/' ) ) . '" method="post">';



        $error = ( isset( $_GET['verify-error'] ) ) ? $_GET['verify-error'] : false;

        if ( $error ) :


            $error_string = apply_filters( 'lp_error_text_general', __( 'Sorry, something must have gone wrong. Please try again', 'wplegalpages' ) );


            if ( $error == 2 )
                $error_string = apply_filters( 'lp_error_text_not_checked', __( 'Check the box to confirm your age before continuing', 'wplegalpages' ) );


            if ( $error == 3 )
                $error_string = apply_filters( 'lp_error_text_too_young', __( 'Sorry, it doesn\'t look like you\'re old enough', 'wplegalpages' ) );


            if ( $error == 4 )
                $error_string = apply_filters( 'lp_error_text_bad_date', __( 'Please enter a valid date', 'wplegalpages' ) );

            $form .= '<p class="error">' . esc_html( $error_string ) . '</p>';

        endif;

        do_action( 'lp_form_before_inputs' );


        $form .= wp_nonce_field( 'verify-age', 'lp-nonce' );

        switch ( $input_type ) {


            case 'dropdowns' :

                $form .= '<p><select name="lp_verify_m" id="lp_verify_m">';

                foreach ( range( 1, 12 ) as $month ) :

                    $month_name = date( 'F', mktime( 0, 0, 0, $month, 1 ) );

                    $form .= '<option value="' . $month . '">' . $month_name . '</option>';

                endforeach;

                $form .= '</select> - <select name="lp_verify_d" id="lp_verify_d">';

                foreach ( range( 1, 31 ) as $day ) :

                    $form .= '<option value="' . $day . '">' . esc_html( zeroise( $day, 2 ) ) . '</option>';

                endforeach;

                $form .= '</select> - <select name="lp_verify_y" id="lp_verify_y">';

                foreach ( range( 1910, date( 'Y' ) ) as $year ) :

                    $selected = ( $year == date( 'Y' ) ) ? 'selected="selected"' : '';

                    $form .= '<option value="' . $year . '" ' . $selected . '>' . $year . '</option>';

                endforeach;

                $form .= '</select></p>';

                break;


            case 'inputs' :

                $form .= '<p><input type="text" name="lp_verify_m" id="lp_verify_m" maxlength="2" value="" placeholder="MM" /> - <input type="text" name="lp_verify_d" id="lp_verify_d" maxlength="2" value="" placeholder="DD" /> - <input type="text" name="lp_verify_y" id="lp_verify_y" maxlength="4" value="" placeholder="YYYY" /></p>';

                break;


            case 'checkbox' :

                $form .= '<p><label for="lp_verify_confirm"><input type="checkbox" name="lp_verify_confirm" id="lp_verify_confirm" value="1" /> ';

                $form .= esc_html( sprintf( apply_filters( 'lp_confirm_text', __( 'I am at least %s years old', 'wplegalpages' ) ), $this->lp_get_minimum_age() ) ) . '</label></p>';

                break;

        };

        do_action( 'lp_form_after_inputs' );

        $form .= '<p class="submit"><label for="lp_verify_remember"><input type="checkbox" name="lp_verify_remember" id="lp_verify_remember" value="1" /> ' . esc_html__( 'Remember me', 'wplegalpages' ) . '</label>' ;

        $form .= '<input type="submit" name="lp_verify" id="lp_verify" value="' . esc_attr( $submit_button_label ) . '" /></p>';

        $form .= '</form>';

        return apply_filters( 'lp_verify_form', $form );
    }



    function lp_confirmation_required() {

        if ( get_option( '_lp_membership', 1 ) == 1 )
        {
            $return = true;
        }
        else{
            $return = false;
        }

        return (bool) apply_filters( 'lp_confirmation_required', $return );
    }


    function lp_register_form() {

        $text = '<p class="wplegalpages"><label for="_lp_confirm_age"><input type="checkbox" name="_lp_confirm_age" id="_lp_confirm_age" value="1" /> ';

        $text .= esc_html( sprintf( apply_filters( 'lp_registration_text', __( 'I am at least %s years old', 'wplegalpages' ) ), $this->lp_get_minimum_age() ) );

        $text .= '</label></p><br />';

        echo $text;
    }

}
}
else {
    exit("Class legalPages already declared!");
}
    



    

/************* widget code - start ***********/
class WP_Legal_Pages extends WP_Widget
{


    public function __construct()
    {
        $widget_ops = array(
          'classname' => 'wp_legal_pages',
          'description' => 'WP Legal Eagle Widget is awesome',
        );
        parent::__construct('wp_legal_pages', 'WP Legal Eagle', $widget_ops);

    }


    public function widget( $args, $instance )
    {
        global $wpdb;
        $resultcontent = $wpdb->get_results("select title,content from wp_legal_pages where id=".$instance['lpSelect']);

        echo $args['before_widget'];
        foreach($resultcontent as $ras){
            _e('<h5>'.$ras->title.'</h5><hr>');
            _e($ras->content);
        }
        echo $args['after_widget'];

    }


    public function form( $instance )
    {
        global $wpdb;
   ?>
    <h3> <?php _e('Choose Template','wplegalpages'); ?> </h3><br/>


        <div>
         <select id="lpSelect" name="lpSelect">
            <?php
            $result = $wpdb->get_results("select id,title from wp_legal_pages");


            foreach($result as $ras){

                $lpvalue = isset($instance['lpSelect']) ? $instance['lpSelect'] : '';

                if($lpvalue==$ras->id) {
                    ?><option value="<?php echo $ras->id;?>" selected><?php echo $ras->title;?></option>
                <?php }else{ ?>
                   <option value="<?php echo $ras->id;?>"><?php echo $ras->title;?></option>
                <?php }
            }?>
            </select>
           </div><br><br>
        <?php
        return $instance;
    }

    public function update( $new_instance, $old_instance )
    {
        $new_instance['lpSelect']=$_POST['lpSelect'];
        return $new_instance;

    }

}

function WP_Legal_Pages_register_widgets()
{
    register_widget('WP_Legal_Pages');
}
add_action('widgets_init', 'WP_Legal_Pages_register_widgets');



/* Adult site Popup Css*/

function wpt_theme_styles() {

    $plugin_url = plugin_dir_url( __FILE__ );

    wp_enqueue_style( 'style1', $plugin_url . 'css/popup.css' );

    // wp_enqueue_style( 'popup_stykle', plugins_url() . '/wplegaleagle/css/popup.css' );

   //wp_enqueue_script( 'popup.css' );
    
}
// add_action('wp_enqueue_scripts','wpt_theme_styles');
 
add_action( 'wp_enqueue_scripts', 'wpt_theme_styles' );