Sh3ll
OdayForums


Server : LiteSpeed
System : Linux premium84.web-hosting.com 4.18.0-553.44.1.lve.el8.x86_64 #1 SMP Thu Mar 13 14:29:12 UTC 2025 x86_64
User : claqxcrl ( 523)
PHP Version : 8.1.32
Disable Function : NONE
Directory :  /home/claqxcrl/confenda.com/wp-content/plugins/poll-maker/admin/

Upload File :
current_dir [ Writeable ] document_root [ Writeable ]

 

Current File : /home/claqxcrl/confenda.com/wp-content/plugins/poll-maker/admin/class-poll-maker-ays-admin.php
<?php

/**
 * The admin-specific functionality of the plugin.
 *
 * @link       https://ays-pro.com/
 * @since      1.0.0
 *
 * @package    Poll_Maker_Ays
 * @subpackage Poll_Maker_Ays/admin
 */

/**
 * The admin-specific functionality of the plugin.
 *
 * Defines the plugin name, version, and two examples hooks for how to
 * enqueue the admin-specific stylesheet and JavaScript.
 *
 * @package    Poll_Maker_Ays
 * @subpackage Poll_Maker_Ays/admin
 * @author     Poll Maker Team <info@ays-pro.com>
 */
class Poll_Maker_Ays_Admin {

	/**
	 * The ID of this plugin.
	 *
	 * @since    1.0.0
	 * @access   private
	 * @var      string $plugin_name The ID of this plugin.
	 */
	private $plugin_name;

	/**
	 * The version of this plugin.
	 *
	 * @since    1.0.0
	 * @access   private
	 * @var      string $version The current version of this plugin.
	 */
	private $version;

	public $polls_obj;
	private $cats_obj;
	private $formfields_obj;
	private $results_obj;
	private $each_results_obj;
	private $settings_obj;
	private $requests_obj;
	private $all_results_obj;

	/**
	 * Initialize the class and set its properties.
	 *
	 * @param string $plugin_name The name of this plugin.
	 * @param string $version The version of this plugin.
	 *
	 * @since    1.0.0
	 */
	public function __construct( $plugin_name, $version ) {

		$this->plugin_name = $plugin_name;
		$this->version     = $version;
		add_filter('set-screen-option', array(__CLASS__, 'set_screen'), 10, 3);
		// add_filter( 'cron_schedules','cron_add_five_min' );
		$per_page_array = array(
            'polls_per_page',
            'cats_per_page',
            'poll_results_per_page',
            'poll_each_results_per_page',
            'formfields_per_page',
            'poll_requests_per_page',
            'poll_all_results_per_page',
        );
        foreach($per_page_array as $option_name){
            add_filter('set_screen_option_'.$option_name, array(__CLASS__, 'set_screen'), 10, 3);
        }
	}

	/**
	 * Register the styles for the admin menu area.
	 *
	 * @since    1.5.5
	 */
	public function admin_menu_styles() {
		echo "
        <style>
            #adminmenu a.toplevel_page_poll-maker-ays div.wp-menu-image img {
                width: 28px;
                padding-top: 2px;
            }

			#adminmenu li.toplevel_page_poll-maker-ays ul.wp-submenu.wp-submenu-wrap li:last-child a {
                color: #f50057;
            }

            .apm-badge {
                position: relative;
                top: -1px;
                right: -3px;
            }

            .apm-badge.badge-danger {
                color: #fff;
                background-color: #ca4a1f;
            }

            .apm-badge.badge {
                display: inline-block;
                vertical-align: top;
                margin: 1px 0 0 2px;
                padding: 0 5px;
                min-width: 7px;
                height: 17px;
                border-radius: 11px;
                font-size: 9px;
                line-height: 17px;
                text-align: center;
                z-index: 26;
            }

            .wp-first-item .apm-badge {
                display: none;
            }

            .apm-badge.badge.apm-no-results {
                display: none;
            }
        </style>
		";
	}

	/**
	 * Register the stylesheets for the admin area.
	 *
	 * @since    1.0.0
	 */
	public function enqueue_styles( $hook_suffix ) {
		wp_enqueue_style($this->plugin_name . '-admin', plugin_dir_url(__FILE__) . 'css/admin.css', array(), $this->version, 'all');
		wp_enqueue_style($this->plugin_name . '-sweetalert-css', POLL_MAKER_AYS_PUBLIC_URL . '/css/poll-maker-sweetalert2.min.css', array(), $this->version, 'all');
		if (false === strpos($hook_suffix, $this->plugin_name)) {
			return;
		}

		/**
		 * This function is provided for demonstration purposes only.
		 *
		 * An instance of this class should be passed to the run() function
		 * defined in Poll_Maker_Ays_Loader as all of the hooks are defined
		 * in that particular class.
		 *
		 * The Poll_Maker_Ays_Loader will then create the relationship
		 * between the defined hooks and the functions defined in this
		 * class.
		 */

		// You need styling for the datepicker. For simplicity I've linked to the jQuery UI CSS on a CDN.
        // wp_register_style( 'jquery-ui', 'https://code.jquery.com/ui/1.12.1/themes/smoothness/jquery-ui.css' );
        wp_register_style( 'jquery-ui', plugin_dir_url(__FILE__) . 'css/poll-maker-jquery-ui.css' );
        wp_enqueue_style( 'jquery-ui' );
		wp_enqueue_style('wp-color-picker');
		wp_enqueue_style( $this->plugin_name . '-animate.css', plugin_dir_url(__FILE__) . 'css/animate.min.css', array(), $this->version, 'all');
		// wp_enqueue_style( $this->plugin_name . '-font_awesome', 'https://use.fontawesome.com/releases/v5.6.3/css/all.css', array(), $this->version, 'all');
		wp_enqueue_style( $this->plugin_name . '-font-awesome', plugin_dir_url(__FILE__) . 'css/poll-maker-font-awesome-all.css', array(), $this->version, 'all');
		// wp_enqueue_style('ays_poll_fa_v4_shims', plugin_dir_url(__FILE__) . 'css/font_awesome_v4-shims.css', array(), '5.6.3', 'all');
		wp_enqueue_style( $this->plugin_name . '-bootstrap', plugin_dir_url(__FILE__) . 'css/bootstrap.min.css', array(), $this->version, 'all');
		wp_enqueue_style( $this->plugin_name . '-jquery-datetimepicker', plugin_dir_url(__FILE__) . 'css/jquery-ui-timepicker-addon.css', array(), $this->version, 'all');
		wp_enqueue_style( $this->plugin_name . '-select2', plugin_dir_url(__FILE__) . 'css/select2.min.css', array(), $this->version, 'all');
		wp_enqueue_style( $this->plugin_name , plugin_dir_url(__FILE__) . 'css/poll-maker-ays-admin.css', array(), $this->version, 'all');

	}

	/**
	 * Register the JavaScript for the admin area.
	 *
	 * @since    1.0.0
	 */
	public function enqueue_scripts( $hook_suffix ) {
		global $wp_version;
		if (false !== strpos($hook_suffix, "plugins.php")){
			wp_enqueue_script( $this->plugin_name . '-sweetalert-js', POLL_MAKER_AYS_PUBLIC_URL . '/js/poll-maker-sweetalert2.all.min.js', array('jquery'), $this->version, true );
			wp_enqueue_script( $this->plugin_name . '-admin', plugin_dir_url(__FILE__) . 'js/admin.js', array('jquery'), $this->version, true);
			wp_localize_script($this->plugin_name . '-admin', 'apm_admin_ajax_obj', array('ajaxUrl' => admin_url('admin-ajax.php')));
		}
		if (false === strpos($hook_suffix, $this->plugin_name)) {
			return;
		}

		/**
		 * This function is provided for demonstration purposes only.
		 *
		 * An instance of this class should be passed to the run() function
		 * defined in Poll_Maker_Ays_Loader as all of the hooks are defined
		 * in that particular class.
		 *
		 * The Poll_Maker_Ays_Loader will then create the relationship
		 * between the defined hooks and the functions defined in this
		 * class.
		 */

		$version1 = $wp_version;
        $operator = '>=';
        $version2 = '5.5';
        $versionCompare = $this->versionCompare($version1, $operator, $version2);
        if ($versionCompare) {	
            wp_enqueue_script( $this->plugin_name.'-wp-load-scripts', plugin_dir_url(__FILE__) . 'js/ays-wp-load-scripts.js', array(), $this->version, true);
		}	
		
		if (strpos($hook_suffix, 'results')) {
			wp_enqueue_script( $this->plugin_name . 'charts-core', plugin_dir_url(__FILE__) . 'js/core.js', array('jquery'), $this->version, true);
			wp_enqueue_script( $this->plugin_name . 'charts-main', plugin_dir_url(__FILE__) . 'js/charts.js', array('jquery'), $this->version, true);
			wp_enqueue_script( $this->plugin_name . 'charts-animated', plugin_dir_url(__FILE__) . 'js/animated.js', array('jquery'), $this->version, true);
			wp_enqueue_script( $this->plugin_name . 'chart-pie-js', plugin_dir_url(__FILE__) . 'js/charts-client-pie.js', array('jquery'), $this->version, true);
			if (strpos($_SERVER['REQUEST_URI'], 'title') === false) {
				wp_enqueue_script( $this->plugin_name . 'chart-js', plugin_dir_url(__FILE__) . 'js/charts-client.js', array('jquery'), $this->version, true);
			}
		}

		wp_enqueue_script('jquery');
		wp_enqueue_script('jquery-ui-datepicker');
		wp_enqueue_media();
		wp_enqueue_script( $this->plugin_name . '-wp-color-picker-alpha', plugin_dir_url(__FILE__) . 'js/wp-color-picker-alpha.min.js', array('wp-color-picker'), $this->version, true);
		wp_enqueue_script( $this->plugin_name . '-popper', plugin_dir_url(__FILE__) . 'js/popper.min.js', array('jquery'), $this->version, true);
		wp_enqueue_script( $this->plugin_name . '-bootstrap', plugin_dir_url(__FILE__) . 'js/bootstrap.min.js', array('jquery'), $this->version, true);
		wp_enqueue_script( $this->plugin_name . '-select2', plugin_dir_url(__FILE__) . 'js/select2.min.js', array('jquery'), $this->version, true);
		wp_enqueue_script( $this->plugin_name . '-charts-google', plugin_dir_url(__FILE__) . 'js/google-chart.js', array('jquery'), $this->version, true);
		wp_enqueue_script( $this->plugin_name . '-jquery.datetimepicker.js', plugin_dir_url( __FILE__ ) . 'js/jquery-ui-timepicker-addon.js', array( 'jquery' ), $this->version, true );
		wp_enqueue_script( $this->plugin_name . '-admin-js', plugin_dir_url(__FILE__) . 'js/poll-maker-ays-admin.js', array('jquery', 'wp-color-picker'), $this->version, true);
		wp_localize_script($this->plugin_name . '-admin-js', 'pollLangObj', array(
            'add' 				=> __( 'Add', $this->plugin_name),
            'proVersionText'    => __( 'This property aviable only in pro version', $this->plugin_name),
            'answersMinCount'   => __( 'Sorry minimum count of answers should be 2', $this->plugin_name),
            'copied'        	=> __( 'Copied!', $this->plugin_name),
            'clickForCopy'  	=> __( 'Click for copy.', $this->plugin_name),
            'removeImage'  	    => POLL_MAKER_AYS_ADMIN_URL . '/images/remove-normal.png',
            'removeImageHover'  => POLL_MAKER_AYS_ADMIN_URL . '/images/remove-hover.png',
        ) );

		wp_enqueue_script( $this->plugin_name . 'sweetalert-js', plugin_dir_url(__FILE__) . 'js/sweetalert2.all.min.js', array('jquery'), $this->version, true);
		wp_enqueue_script( $this->plugin_name . '-admin-ajax', plugin_dir_url(__FILE__) . 'js/poll-maker-ays-ajax-admin.js', array('jquery'), $this->version, true);
		wp_localize_script($this->plugin_name . '-admin-ajax', 'apm_ajax_obj', array('ajaxUrl' => admin_url('admin-ajax.php')));

		$color_picker_strings = array(
			'clear'            => __( 'Clear', $this->plugin_name ),
			'clearAriaLabel'   => __( 'Clear color', $this->plugin_name ),
			'defaultString'    => __( 'Default', $this->plugin_name ),
			'defaultAriaLabel' => __( 'Select default color', $this->plugin_name ),
			'pick'             => __( 'Select Color', $this->plugin_name ),
			'defaultLabel'     => __( 'Color value', $this->plugin_name ),
		);
		wp_localize_script( $this->plugin_name . '-wp-color-picker-alpha', 'wpColorPickerL10n', $color_picker_strings );


	}

	public function versionCompare($version1, $operator, $version2) {
   
        $_fv = intval ( trim ( str_replace ( '.', '', $version1 ) ) );
        $_sv = intval ( trim ( str_replace ( '.', '', $version2 ) ) );
       
        if (strlen ( $_fv ) > strlen ( $_sv )) {
            $_sv = str_pad ( $_sv, strlen ( $_fv ), 0 );
        }
       
        if (strlen ( $_fv ) < strlen ( $_sv )) {
            $_fv = str_pad ( $_fv, strlen ( $_sv ), 0 );
        }
       
        return version_compare ( ( string ) $_fv, ( string ) $_sv, $operator );
    }

	public function codemirror_enqueue_scripts($hook) {
        if(strpos($hook, $this->plugin_name) !== false){
            if(function_exists('wp_enqueue_code_editor')){
                $cm_settings['codeEditor'] = wp_enqueue_code_editor(array(
                    'type' => 'text/css',
                    'codemirror' => array(
                        'inputStyle' => 'contenteditable',
                        'theme' => 'cobalt',
                    )
                ));

                wp_enqueue_script('wp-theme-plugin-editor');
                wp_localize_script('wp-theme-plugin-editor', 'cm_settings', $cm_settings);

                wp_enqueue_style('wp-codemirror');
            }
        }
    }

	public function add_plugin_admin_menu() {
		
		global $wpdb;
		$sql            = "SELECT COUNT(unread) FROM {$wpdb->prefix}ayspoll_reports WHERE unread=1";
		$unread_results = $wpdb->get_var($sql);
		$show           = $unread_results > 0 ? '' : "apm-no-results";
		/*
		 * Add a settings page for this plugin to the Settings menu.
		 *
		 * NOTE:  Alternative menu locations are available via WordPress administration menu functions.
		 *
		 *        Administration Menus: http://codex.wordpress.org/Administration_Menus
		 *
		 */		

		$menu_item = ($unread_results == 0) ? 'Poll Maker' : 'Poll Maker' . '<span class="apm-badge badge badge-danger '.$show.'">' . $unread_results . '</span>';

		$this->capability = $this->poll_maker_capabilities();
        $capability = $this->poll_maker_capabilities();

		$hook_poll = add_menu_page(
			'Poll Maker', 
			$menu_item,
			$capability,
			$this->plugin_name, 
			array($this,'display_plugin_polls_page'),
			POLL_MAKER_AYS_ADMIN_URL . '/images/icons/icon-128x128.png', '6.33'
		);

		add_action("load-$hook_poll", array($this, 'screen_option_polls'));

		$hook_results_each = add_submenu_page(
			null,
			__('Results per poll', $this->plugin_name),
			__('Results per poll', $this->plugin_name),
			$capability,
			$this->plugin_name . '-results-each',
			array($this, 'display_plugin_results_each_page')
		);
		add_action("load-$hook_results_each", array($this, 'screen_option_each_results'));
		$hook_requests_each = add_submenu_page(
			null,
			__('Requests per poll', $this->plugin_name),
			__('Requests per poll', $this->plugin_name),
			"manage_options",
			$this->plugin_name . '-requests-each',
			array($this, 'display_plugin_each_requests_page')
		);

		add_filter('parent_file', array($this,'poll_maker_select_submenu'));
		// add_action("load-$hook_requests_each", array($this, 'screen_option_each_requests'));	
	}

	public function add_plugin_polls_submenu() {
		$capability = $this->poll_maker_capabilities();

		$hook_polls = add_submenu_page(
			$this->plugin_name,
			__('Polls', $this->plugin_name),
			__('Polls', $this->plugin_name),
			$capability,
			$this->plugin_name,
			array($this, 'display_plugin_polls_page')
		);
		add_action("load-$hook_polls", array($this, 'screen_option_polls'));
	}

	public function add_plugin_categories_submenu() {
		$capability = $this->poll_maker_capabilities();

		$hook_cats = add_submenu_page(
			$this->plugin_name,
			__('Categories', $this->plugin_name),
			__('Categories', $this->plugin_name),
			$capability,
			$this->plugin_name . '-cats',
			array($this, 'display_plugin_cats_page')
		);
		add_action("load-$hook_cats", array($this, 'screen_option_cats'));
	}

	public function add_plugin_results_submenu() {
		/*
		 * Check unread results
		 *
		 */
		global $wpdb;
		$sql            = "SELECT COUNT(unread) FROM {$wpdb->prefix}ayspoll_reports WHERE unread=1";
		$unread_results = $wpdb->get_var($sql);
		$show           = $unread_results > 0 ? '' : "apm-no-results";

		$capability = $this->poll_maker_capabilities();

		$hook_results = add_submenu_page(
			$this->plugin_name,
			__('Results', $this->plugin_name),
			__('Results', $this->plugin_name) . " <span class=\"apm-badge badge badge-danger $show\">$unread_results</span>",
			$capability,
			$this->plugin_name . '-results',
			array($this, 'display_plugin_results_page')
		);
		add_action("load-$hook_results", array($this, 'screen_option_results'));

		$hook_all_results = add_submenu_page(
            'all_results_slug',
            __('Results', $this->plugin_name),
            $capability,
            $this->capability,
            $this->plugin_name . '-all-results',
            array($this, 'display_plugin_all_results_page')
		);
		
		add_action("load-$hook_all_results", array($this, 'screen_option_all_poll_results'));

		add_filter('parent_file', array($this,'poll_maker_select_submenu'));
	}

	public function add_plugin_formfields_submenu() {
		$capability = $this->poll_maker_capabilities();

		$hook_formfields = add_submenu_page(
			$this->plugin_name,
			__('Custom Fields', $this->plugin_name),
			__('Custom Fields', $this->plugin_name),
			$capability,
			$this->plugin_name . '-formfields',
			array($this, 'display_plugin_formfields_page')
		);
		add_action("load-$hook_formfields", array($this, 'screen_option_formfields'));
	}

	public function add_plugin_general_settings_submenu() {
		$hook_settings = add_submenu_page($this->plugin_name,
			__('General Settings', $this->plugin_name),
			__('General Settings', $this->plugin_name),
			'manage_options',
			$this->plugin_name . '-settings',
			array($this, 'display_plugin_settings_page')
		);
		add_action("load-$hook_settings", array($this, 'screen_option_settings'));
	}

	public function add_plugin_how_to_use_submenu() {
		$capability = $this->poll_maker_capabilities();
		$hook_pro_features = add_submenu_page(
			$this->plugin_name,
			__('How to use', $this->plugin_name),
			__('How to use', $this->plugin_name),
			$capability,
			$this->plugin_name . '-how-to-use',
			array($this, 'display_plugin_how_to_use_page')
		);
	}

	public function add_plugin_our_products_submenu(){
		$capability = $this->poll_maker_capabilities();
        add_submenu_page( $this->plugin_name,
            __('Our products', $this->plugin_name),
            __('Our products', $this->plugin_name),
            $capability,
            $this->plugin_name . '-our-products',
            array($this, 'display_plugin_our_products_page') 
        );
    }

	public function add_plugin_requests_submenu() {
		/*
		 * Check unread results
		 *
		 */
		global $wpdb;
		$sql            = "SELECT COUNT(unread) FROM {$wpdb->prefix}ayspoll_requests WHERE unread=1";
		$unread_results = $wpdb->get_var($sql);
		$show           = $unread_results > 0 ? '' : "apm-no-results";

		$capability = $this->poll_maker_capabilities();

		$hook_requests = add_submenu_page(
			$this->plugin_name,
			__('Requests', $this->plugin_name),
			__('Requests', $this->plugin_name) . " <span class=\"apm-badge badge badge-danger $show\">$unread_results</span>",
			"manage_options",
			$this->plugin_name . '-requests',
			array($this, 'display_plugin_requests_page')
		);
		add_action("load-$hook_requests", array($this, 'screen_option_requests'));
	}

	public function poll_maker_select_submenu($file) {
        global $plugin_page;
        if ("poll-maker-ays-results-each" == $plugin_page) {
            $plugin_page = $this->plugin_name."-results";
        }else if ("poll-maker-ays-all-results" == $plugin_page) {
            $plugin_page = $this->plugin_name."-results";
        }else if ("poll-maker-ays-requests-each" == $plugin_page) {
            $plugin_page = $this->plugin_name."-requests";
        }

        return $file;
    }

	protected function poll_maker_capabilities(){
        global $wpdb;
		$sql    = "SELECT meta_value FROM {$wpdb->prefix}ayspoll_settings WHERE `meta_key` = 'user_roles'";
		$result = $wpdb->get_var($sql);
		
        $capability = 'manage_options';
        if($result !== null){
            $ays_user_roles = json_decode($result, true);
            if(is_user_logged_in()){
                $current_user = wp_get_current_user();
                $current_user_roles = $current_user->roles;
                $ishmar = 0;
                foreach($current_user_roles as $r){
                    if(in_array($r, $ays_user_roles)){
                        $ishmar++;
                    }
                }
                if($ishmar > 0){
                    $capability = "read";
                }
            }
        }
        return $capability;
    }

	/**
	 * Add settings action link to the plugins page.
	 *
	 * @since    1.0.0
	 */

	public function add_action_links( $links ) {
		/*
		 *  Documentation : https://codex.wordpress.org/Plugin_API/Filter_Reference/plugin_action_links_(plugin_file_name)
		 */
		$settings_link = array(
			'<a href="' . admin_url('admin.php?page=' . $this->plugin_name) . '">' . __('Settings', $this->plugin_name) . '</a>',
			'<a href="https://poll-plugin.com/wordpress-poll-plugin-free-demo/" target="_blank">' . __('Demo', $this->plugin_name) . '</a>'
		);

		return array_merge($settings_link, $links);

	}

	/**
	 * Render the settings page for this plugin.
	 *
	 * @since    1.0.0
	 */

	public function display_plugin_polls_page() {
		$action = (isset($_GET['action'])) ? sanitize_text_field($_GET['action']) : '';

		include_once 'partials/polls/actions/poll-maker-ays-countries.php';
		switch ($action) {
            case 'add':
                include_once('partials/polls/actions/poll-maker-ays-polls-actions.php');
                break;
            case 'edit':
                include_once('partials/polls/actions/poll-maker-ays-polls-actions.php');
                break;
            default:
                include_once('partials/polls/poll-maker-ays-admin-display.php');
        }
	}

	public function display_plugin_cats_page() {
		$action = (isset($_GET['action'])) ? sanitize_text_field($_GET['action']) : '';

		switch ( $action ) {
			case 'add':
				include_once 'partials/categories/actions/poll-maker-ays-categories-actions.php';
				break;
			case 'edit':
				include_once 'partials/categories/actions/poll-maker-ays-categories-actions.php';
				break;
			default:
				include_once 'partials/categories/poll-maker-ays-categories-display.php';
		}
	}

	public function display_plugin_results_page() {
		include_once 'partials/results/poll-maker-ays-results-display.php';
	}

	public function display_plugin_results_each_page() {
		include_once 'partials/results/poll-maker-ays-each-results-display.php';
	}

	public function display_plugin_requests_page() {
		include_once 'partials/requests/poll-maker-ays-requests-display.php';
	}

	public function display_plugin_each_requests_page() {
		include_once 'partials/requests/poll-maker-ays-each-requests-display.php';
	}

	public function display_plugin_how_to_use_page() {
		include_once 'partials/features/poll-maker-how-to-use-display.php';
	}

	public function display_plugin_our_products_page(){
        include_once('partials/features/poll-maker-our-products-display.php');
    }

	public function display_plugin_formfields_page() {
		$action = (isset($_GET['action'])) ? sanitize_text_field($_GET['action']) : '';

		switch ( $action ) {
			case 'add':
				include_once 'partials/formfields/actions/poll-maker-ays-formfields-actions.php';
				break;
			case 'edit':
				include_once 'partials/formfields/actions/poll-maker-ays-formfields-actions.php';
				break;
			default:
				include_once 'partials/formfields/poll-maker-ays-formfields-display.php';
		}
	}

	public function display_plugin_settings_page() {
		include_once('partials/settings/poll-maker-settings.php');
	}

	public function display_plugin_all_results_page(){
        include_once('partials/results/poll-maker-ays-all-results-display.php');
    }

	public static function set_screen( $status, $option, $value ) {
		return $value;
	}

	public function screen_option_polls() {
		$option = 'per_page';
		$args   = array(
			'label'   => __('Polls', $this->plugin_name),
			'default' => 20,
			'option'  => 'polls_per_page',
		);

		add_screen_option($option, $args);
		$this->polls_obj    = new Polls_List_Table($this->plugin_name);
		$this->settings_obj = new Poll_Maker_Settings_Actions($this->plugin_name);
	}

	public function screen_option_cats() {
		$option = 'per_page';
		$args   = array(
			'label'   => __('Categories', $this->plugin_name),
			'default' => 20,
			'option'  => 'cats_per_page',
		);

		add_screen_option($option, $args);
		$this->cats_obj = new Pma_Categories_List_Table($this->plugin_name);
	}

	public function screen_option_results() {
		$option = 'per_page';
		$args   = array(
			'label'   => __('Results', $this->plugin_name),
			'default' => 50,
			'option'  => 'poll_results_per_page',
		);

		add_screen_option($option, $args);
		$this->results_obj = new Pma_Results_List_Table($this->plugin_name);
		// $this->answer_results_obj = new Poll_Answer_Results($this->plugin_name);
	}

	public function screen_option_each_results() {
		$option = 'per_page';
		$args   = array(
			'label'   => __('Results per poll', $this->plugin_name),
			'default' => 50,
			'option'  => 'poll_each_results_per_page',
		);

		add_screen_option($option, $args);
		$this->each_results_obj = new Pma_Each_Results_List_Table($this->plugin_name);
	}

	public function screen_option_settings() {
		$this->polls_obj = new Polls_List_Table($this->plugin_name);
		$this->settings_obj = new Poll_Maker_Settings_Actions($this->plugin_name);
	}

	public function screen_option_formfields() {
		$option = 'per_page';
		$args   = array(
			'label'   => __('Formfields', $this->plugin_name),
			'default' => 20,
			'option'  => 'formfields_per_page',
		);

		add_screen_option($option, $args);
		$this->formfields_obj = new Pma_Formfields_List_Table($this->plugin_name);
		$this->settings_obj = new Poll_Maker_Settings_Actions($this->plugin_name);
	}

	public function screen_option_requests() {
		$option = 'per_page';
		$args   = array(
			'label'   => __('Requests', $this->plugin_name),
			'default' => 20,
			'option'  => 'poll_requests_per_page',
		);

		add_screen_option($option, $args);
		$this->requests_obj = new Pma_Requests_List_Table($this->plugin_name);
	}

	public function screen_option_all_poll_results(){
        $option = 'per_page';
        $args = array(
            'label'   => __('All Results', $this->plugin_name),
            'default' => 50,
            'option'  => 'poll_all_results_per_page'
        );

        add_screen_option($option, $args);
        $this->all_results_obj = new Poll_All_Results_List_Table($this->plugin_name);
    }	

	public function register_poll_ays_widget() {
		global $wpdb;

		$sql = "SELECT COUNT(*) FROM {$wpdb->prefix}ayspoll_polls";

		$c = $wpdb->get_var($sql);
		if ($c == 0) {
			return;
		} else {
			register_widget('Poll_Maker_Widget');
		}
	}

	public function poll_maker_el_widgets_registered() {
        wp_enqueue_style($this->plugin_name . '-admin', plugin_dir_url(__FILE__) . 'css/admin.css', array(), $this->version, 'all');
        // We check if the Elementor plugin has been installed / activated.
        if ( defined( 'ELEMENTOR_PATH' ) && class_exists( 'Elementor\Widget_Base' ) ) {
            // get our own widgets up and running:
            // copied from widgets-manager.php
            if ( class_exists( 'Elementor\Plugin' ) ) {
                if ( is_callable( 'Elementor\Plugin', 'instance' ) ) {
                    $elementor = Elementor\Plugin::instance();
                    if ( isset( $elementor->widgets_manager ) ) {
                        if ( method_exists( $elementor->widgets_manager, 'register_widget_type' ) ) {
                            $widget_file   = 'plugins/elementor/poll_maker_elementor.php';
                            $template_file = locate_template( $widget_file );
                            if ( !$template_file || !is_readable( $template_file ) ) {
                                $template_file = POLL_MAKER_AYS_DIR.'pb_templates/poll_maker_elementor.php';
                            }
                            if ( $template_file && is_readable( $template_file ) ) {
                                require_once $template_file;
                                Elementor\Plugin::instance()->widgets_manager->register_widget_type( new Elementor\Widget_Poll_Maker_Elementor() );
                            }
                        }
                    }
                }
            }
        }
    }

	public function apm_deactivate_plugin_option() {
		$request_value  = $_REQUEST['upgrade_plugin'];
		$upgrade_option = get_option('ays_poll_maker_upgrade_plugin', '');
		if ($upgrade_option === '') {
			add_option('ays_poll_maker_upgrade_plugin', $request_value);
		} else {
			update_option('ays_poll_maker_upgrade_plugin', $request_value);
		}
		ob_end_clean();
		$ob_get_clean = ob_get_clean();
		echo json_encode(array('option' => get_option('ays_poll_maker_upgrade_plugin', '')));
		wp_die();
	}

	public function apm_show_results() {
		global $wpdb;
		$results_table = $wpdb->prefix . "ayspoll_reports";
		// $polls_obj     = new Polls_List_Table($this->plugin_name);
		if (isset($_POST['action']) && $_POST['action'] == 'apm_show_results') {

			$id         = isset($_POST['result']) ? absint($_POST['result']) : 0;
			$is_details = isset($_POST['is_details']) && absint($_POST['is_details']) > 0 ? true : false;
			$row        = '';
			$wpdb->update($results_table,
				array('unread' => 0),
				array('id' => $id),
				array('%d'),
				array('%d')
			);
			if ($id > 0 && $is_details) {
				$result     = $wpdb->get_row("SELECT * FROM $results_table WHERE id=$id", "ARRAY_A");
				$multivote_res = false;
				$result['multi_answer_id'] = json_decode($result['multi_answer_id']);
				if (isset($result['multi_answer_id']) && count($result['multi_answer_id']) > 0) {
					$multivote_res = true;
				}
				$multivote_answers = array();
				if ($multivote_res) {
					foreach ($result['multi_answer_id'] as $m_key => $m_val) {
						$multi_answer    = $wpdb->get_row("SELECT * FROM {$wpdb->prefix}ayspoll_answers WHERE id=".$m_val, "ARRAY_A");
						$multivote_answers[] = $multi_answer['answer'];
					}
					$answ_poll_id = $multi_answer['poll_id'];
				} else {
					$answer     = $wpdb->get_row("SELECT * FROM {$wpdb->prefix}ayspoll_answers WHERE id={$result['answer_id']}", "ARRAY_A");
					$multivote_answers[] = $answer['answer'];
					$answ_poll_id = $answer['poll_id'];
				}
				
				$poll       = $this->get_poll_by_id($answ_poll_id);
				$user_ip    = $result['user_ip'];
				$info = ($result['other_info'] == '' || $result['other_info'] === null || $result['other_info'] === 0) ? array() : json_decode($result['other_info'], true);
				
				$time       = $result['vote_date'];
				$user_email = $result['user_email'];
				$country = '';
				$region = '';
				$city = '';
            	$json    = isset($user_ip) && $user_ip != '' ? json_decode(file_get_contents("http://ipinfo.io/{$user_ip}/json")) : null;

				if ($json !== null) {
					$country = isset($json->country) && $json->country != '' ? $json->country : '';
					$region = isset($json->region) && $json->region != '' ? $json->region : '';
					$city = isset($json->city) && $json->city != '' ? $json->city : '';
				}
				$from    = "$city, $region, $country, $user_ip";
				$row     = '<tr><td colspan="4"><h1>' . __('Poll Information', $this->plugin_name) . "</h1></td></tr>
                    <tr class='ays_result_element'>
                        <td>". __('Poll Title', $this->plugin_name)."</td>
                        <td>{$poll['title']}</td>
                        <td></td>
                        <td></td>
                    </tr>";
				$row     .= "<tr class='ays_result_element'>
                        <td>". __('Poll Type', $this->plugin_name)."</td>
                        <td>" . ucfirst($poll['type']) . "</td>
                        <td></td>
                        <td></td>
                    </tr>";
				switch ( $poll['type'] ) {
					case 'versus':
					case 'choosing':
					case 'text':
						$row .= "<tr class='ays_result_element'>
                        <td>". __('Answer', $this->plugin_name)."</td>
                        <td>" . (in_array($poll['answers'][0]['answer'], $multivote_answers) ? "<b><em>" . stripslashes($poll['answers'][0]['answer']) . "</em></b>" : stripslashes($poll['answers'][0]['answer'])) . "</td>
                        <td></td>
                        <td></td>
                    </tr>";
						foreach ( $poll['answers'] as $index => $ans ) {
							if ($index == 0) {
								continue;
							}
							$row .= "<tr class='ays_result_element'>
                            <td></td>
                            <td>" . (in_array($ans['answer'], $multivote_answers) ? "<b><em>" . stripslashes($ans['answer']) . "</em></b>" : stripslashes($ans['answer'])) . "</td>
                            <td></td>
                            <td></td>
                        </tr>";
						}
						break;
					case 'rating':
						$row .= "<tr class='ays_result_element'>
                            <td>". __('Answer', $this->plugin_name)."</td>
                            <td><div class='apm-rating-res'>";
						if ($poll['view_type'] == 'star') {
							foreach ( $poll['answers'] as $ans ) {
								$row .= "<i class='" . ($ans['answer'] <= $answer['answer'] ? "ays_poll_fas" : "ays_poll_far") . " ays_poll_fa-star'></i>";
							}
						} elseif ('emoji') {
							$emoji = array(
								"ays_poll_fa-dizzy",
								"ays_poll_fa-smile",
								"ays_poll_fa-meh",
								"ays_poll_fa-frown",
								"ays_poll_fa-tired",
							);
							foreach ( $poll['answers'] as $i => $ans ) {
								$index = (count($poll['answers']) / 2 - $i + 1.5);
								$row   .= "<i class='" . ($ans['answer'] == $answer['answer'] ? "ays_poll_fas " : "ays_poll_far ") . $emoji[$index] . "'></i>";
							}
						}
						$row .= "</div></td>
                            <td></td>
                            <td></td>
                        </tr>";
						break;
					case 'voting':
						$row   .= "<tr class='ays_result_element'>
                            <td>". __('Answer', $this->plugin_name)."</td>
                            <td><div class='apm-rating-res'>";
						$icons = array(
							'hand'  => array(
								"ays_poll_fa-thumbs-up",
								"ays_poll_fa-thumbs-down",
							),
							'emoji' => array(
								"ays_poll_fa-smile",
								"ays_poll_fa-frown",
							),
						);
						$view  = $poll['view_type'];
						$row   .= "<i class='" . (1 == $answer['answer'] ? "ays_poll_fas " : "ays_poll_far ") . $icons[$view][0] . "'></i>
                        <i class='" . (-1 == $answer['answer'] ? "ays_poll_fas " : "ays_poll_far ") . $icons[$view][1] . "'></i>";
						$row   .= "</div></td>
                            <td></td>
                            <td></td>
                        </tr>";
						break;
						case 'dropdown':
							$row .= "<tr class='ays_result_element'>
							<td>". __('Answer', $this->plugin_name)."</td>
							<td>" . (in_array($poll['answers'][0]['answer'], $multivote_answers) ? "<b><em>" . stripslashes($poll['answers'][0]['answer']) . "</em></b>" : stripslashes($poll['answers'][0]['answer'])) . "</td>
							<td></td>
							<td></td>
						</tr>";
							foreach ( $poll['answers'] as $index => $ans ) {
								if ($index == 0) {
									continue;
								}
								$row .= "<tr class='ays_result_element'>
								<td></td>
								<td>" . (in_array($ans['answer'], $multivote_answers) ? "<b><em>" . stripslashes($ans['answer']) . "</em></b>" : stripslashes($ans['answer'])) . "</td>
								<td></td>
								<td></td>
							</tr>";
							}
						break;

				}
				$row .= "<tr class='ays_result_element'>
                        <td>". __('Answer Datetime', $this->plugin_name)."</td>
                        <td>" . (date('H:i:s d.m.Y', strtotime($time))) . "</td>
                        <td></td>
                        <td></td>
                    </tr>";
				$row .= "<tr class='hr-line'><td colspan='4'><hr></td></tr>";
				$row .= '<tr><td colspan="4"><h1>' . __('User Information', $this->plugin_name) . "</h1></td></tr>";
					if ($json !== null) {
                    	$row .= "<tr class='ays_result_element'>
		                            <td>". __('User IP', $this->plugin_name)."</td>
		                            <td>$from</td>
		                            <td></td>
		                            <td></td>
		                        </tr>";
                    }
                if(!empty($user_email)){
                	$row .= "<tr class='ays_result_element'>
		                        <td>". __('User E-mail', $this->plugin_name)."</td>
		                        <td>$user_email</td>
		                        <td></td>
		                        <td></td>
		                	 </tr>";
            	}
				foreach ( $info as $key => $value ) {
					if ($key == 'not_show_user_id') {
						continue;
					}
					$row .= "<tr class='ays_result_element'>
                            <td>". $key ."</td>
                            <td>". $value ."</td>
                            <td></td>
                            <td></td>
                        </tr>";
				}
			}
			ob_end_clean();
			$ob_get_clean = ob_get_clean();
			echo json_encode([
				"status" => true,
				"rows"   => $row,
			]);
			wp_die();
		}
	}


	public function get_poll_by_id( $id, $decode = true ) {
		global $wpdb;

		$sql  = "SELECT * FROM {$wpdb->prefix}ayspoll_polls WHERE id=" . absint(intval($id));
		$poll = $wpdb->get_row($sql, 'ARRAY_A');
		if (empty($poll)) {
			return array();
		}
		$sql             = "SELECT * FROM {$wpdb->prefix}ayspoll_answers WHERE poll_id=" . absint(intval($id)) . " ORDER BY id ASC";
		$poll['answers'] = $wpdb->get_results($sql, 'ARRAY_A');

		if ($decode) {
			$json               = $poll['styles'];
			$poll['styles']     = json_decode($json, true);
			$poll['categories'] = trim($poll['categories'], ',');
			$cats               = explode(',', $poll['categories']);
			$poll['categories'] = !empty($cats) ? $cats : [];
			$all_fields         = $this->get_all_formfields();
			if (isset($poll['styles']['fields'])) {
				$poll['fields'] = array();
				$fields         = explode(',', $poll['styles']['fields']);
				foreach ( $fields as $field ) {
					$index = array_search($field, array_column($all_fields, 'slug'));
					if ($index !== false) {
						$poll['fields'][] = $all_fields[$index];
					}
				}
			}
			if (isset($poll['styles']['required_fields'])) {
				$poll['required_fields'] = array();
				$fields                  = explode(',', $poll['styles']['required_fields']);
				foreach ( $fields as $field ) {
					$index = array_search($field, array_column($all_fields, 'slug'));
					if ($index !== false) {
						$poll['required_fields'][] = $all_fields[$index];
					}
				}
			}
		}

		return $poll;
	}

	public function get_all_formfields() {
		global $wpdb;
		$all = array(
			array(
				"id"        => 0,
				"name"      => "Name",
				"type"      => "text",
				"slug"      => "apm-name",
				"published" => 1,
			),
			array(
				"id"        => 0,
				"name"      => "E-mail",
				"type"      => "email",
				"slug"      => "apm-email",
				"published" => 1,
			),
		);
		$sql = "SELECT * FROM {$wpdb->prefix}ayspoll_formfields WHERE published='1'";
		$res = $wpdb->get_results($sql, 'ARRAY_A');

		return array_merge($all, $res);
	}


    // Campaign Monitor - Get subscribe lists
    public function ays_get_active_camp_data( $data, $url, $api_key ) {
        error_reporting(0);
        if ($url == "" || $api_key == "") {
            return array(
                'Code' => 0
            );
        }


        $curl = curl_init();

        curl_setopt_array($curl, array(
            CURLOPT_URL            => "$url/api/3/$data",
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING       => "",
            CURLOPT_MAXREDIRS      => 10,
            CURLOPT_TIMEOUT        => 30,
            CURLOPT_SSL_VERIFYPEER => false,
            CURLOPT_HTTP_VERSION   => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST  => "GET",
            CURLOPT_HTTPAUTH       => CURLAUTH_BASIC,
            CURLOPT_HTTPHEADER     => array(
                "Content-Type: application/json",
                "cache-control: no-cache",
                "Api-Token: $api_key"
            ),
        ));

        $response = curl_exec($curl);
        $err      = curl_error($curl);

        curl_close($curl);

        if ($err) {
            return array(
                'Code'       => 0,
                'cURL Error' => $err
            );
        } else {
            return json_decode($response, true);
        }
    }

    // Slack - Get channels
    public function ays_get_slack_conversations( $token ) {
        error_reporting(0);
        if ($token == "") {
            return array(
                'Code' => 0
            );
        }

        $curl = curl_init();

        curl_setopt_array($curl, array(
            CURLOPT_URL            => "https://slack.com/api/conversations.list?token=$token",
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING       => "",
            CURLOPT_MAXREDIRS      => 10,
            CURLOPT_TIMEOUT        => 30,
            CURLOPT_SSL_VERIFYPEER => false,
            CURLOPT_HTTP_VERSION   => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST  => "GET",
            CURLOPT_HTTPAUTH       => CURLAUTH_BASIC,
            CURLOPT_HTTPHEADER     => array(
                "Content-Type: application/x-www-form-urlencoded",
                "cache-control: no-cache"
            ),
        ));

        $response = curl_exec($curl);
        $err      = curl_error($curl);

        curl_close($curl);

        if ($err) {
            return array(
                'Code'       => 0,
                'cURL Error' => $err
            );
        } else {
            return json_decode($response, true)['channels'];
        }
    }

    // Campaign Monitor - Get subscribe lists
    public function ays_get_monitor_lists($client, $api_key){
        error_reporting(0);
        if ($client == "" || $api_key == "") {
            return array(
                'Code' => 0
            );
        }


        $curl = curl_init();

        curl_setopt_array($curl, array(
            CURLOPT_URL => "https://api.createsend.com/api/v3.2/clients/$client/lists.json",
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => "",
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 30,
            CURLOPT_SSL_VERIFYPEER => false,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => "GET",
            CURLOPT_USERPWD => "$api_key:x",
            CURLOPT_HTTPAUTH => CURLAUTH_BASIC,
            CURLOPT_HTTPHEADER => array(
                "Content-Type: application/json",
                "cache-control: no-cache"
            ),
        ));

        $response = curl_exec($curl);
        $err = curl_error($curl);

        curl_close($curl);

        if ($err) {
            return array(
                'Code'       => 0,
                'cURL Error' => $err
            );
        } else {
            return json_decode($response,true);
        }
    }

    // MailChimp
    public function ays_get_mailchimp_lists( $username, $api_key ) {
		if (!empty($api_key) && strpos($api_key, '-') !== false) {
			$api_postfix = explode("-", $api_key)[1];

			$curl = curl_init();

			curl_setopt_array($curl, array(
				CURLOPT_URL            => "https://" . $api_postfix . ".api.mailchimp.com/3.0/lists",
				CURLOPT_RETURNTRANSFER => true,
				CURLOPT_ENCODING       => "",
				CURLOPT_MAXREDIRS      => 10,
				CURLOPT_TIMEOUT        => 30,
				CURLOPT_SSL_VERIFYPEER => false,
				CURLOPT_HTTP_VERSION   => CURL_HTTP_VERSION_1_1,
				CURLOPT_CUSTOMREQUEST  => "GET",
				CURLOPT_USERPWD        => "$username:$api_key",
				CURLOPT_HTTPAUTH       => CURLAUTH_BASIC,
		// CURLOPT_POSTFIELDS => "undefined=",
				CURLOPT_HTTPHEADER     => array(
					"Content-Type: application/json",
					"cache-control: no-cache"
				),
			));

			$response = curl_exec($curl);
			$err      = curl_error($curl);

			curl_close($curl);

			if ($err) {
				echo "cURL Error #:" . $err;
			} else {
				return json_decode($response, true);
			}
		}

		return array();
	}

	// SendGrid
	public function ays_poll_sendgrid_templates($api_key){		
		$curl = curl_init();

		curl_setopt_array($curl, array(
		  CURLOPT_URL => "https://api.sendgrid.com/v3/templates",
		  CURLOPT_RETURNTRANSFER => true,
		  CURLOPT_ENCODING => "",
		  CURLOPT_MAXREDIRS => 10,
		  CURLOPT_TIMEOUT => 30,
		  CURLOPT_SSL_VERIFYPEER => false,
		  // CURLOPT_FOLLOWLOCATION => true,
		  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
		  CURLOPT_CUSTOMREQUEST => "GET",
		  CURLOPT_HTTPHEADER => array(
		    "Content-Type: application/json",
		    "Authorization: Bearer ".$api_key
		  ),
		));

		$response = curl_exec($curl);
		$err      = curl_error($curl);
		curl_close($curl);
		if ($err) {
			echo "cURL Error #:" . $err;
		} else {
			return json_decode($response, true);
		}
	}

	public function ays_poll_mad_mimi_lists($user_name , $api_key){
        $bad_request = array();

		if ($user_name == "" || $api_key == "") {
			return $bad_request;
		}

        $url = "https://madmimi.com/api/v3/subscriberLists?";
        $data = array(
            "username" => $user_name,
            "api_key"  => $api_key
        );

        $url .= http_build_query($data);

        $headers = array(
            "headers" => array(
                "Accept"  => "application/json",
            ),
        );
        
        $api_call = wp_remote_get( $url , $headers);
        if(wp_remote_retrieve_response_code( $api_call ) == 200){
            $subscriber_lists = wp_remote_retrieve_body($api_call);
            if($subscriber_lists == ""){
                return $bad_request;
            }
            else{
                $response = json_decode($subscriber_lists , true);
                $lists = isset($response['subscriberLists']) ? $response['subscriberLists'] : array();
                return $lists;
            }
        }
        else{
            return $bad_request;
        }
    }

	// Mad mimi
	public static function validateDate($date, $format = 'Y-m-d H:i:s'){
        $d = DateTime::createFromFormat($format, $date);
        return $d && $d->format($format) == $date;
    }

	// GetResponse
	public function ays_poll_getResposne_lists($api_key){
		$bad_request = array();
		if($api_key == ""){
			return $bad_request;
		}

		$url = "https://api.getresponse.com/v3/campaigns";
		$headers = array(
			"headers" => array(
				"X-Auth-Token" => "api-key ".$api_key, 
			)
		);
		$api_call = wp_remote_get($url , $headers);
		$response = wp_remote_retrieve_body( $api_call );
		$new_response = array();
		if($response != ""){
			$new_response = json_decode($response , true);
		}
		if(wp_remote_retrieve_response_code( $api_call ) == 200){
			$new_response['status'] = true;
		}
		else{
			$new_response['status'] = false;
		}
		return $new_response;
	}
	//

	// ConvertKit Lists
	public function ays_poll_get_convertKit_forms( $api_key ) {
		if ($api_key == "") {
			return array();
		}
		$url = "https://api.convertkit.com/v3/forms?api_key=".$api_key;
		$api_call = wp_remote_get($url);
		$body = array();
		$response = array();
		if ( wp_remote_retrieve_response_code( $api_call ) === 200 ){
			$body = wp_remote_retrieve_body( $api_call );
			if($body != ""){
				$body = json_decode($body , true);
				$response['forms'] = isset($body['forms']) && !empty($body['forms']) ? $body['forms'] : array();
				$response['status'] = true;
			}
			else{
				$response['forms'] = array();
				$response['status'] = false;
			}
		}
		else{
			$response['forms'] = array();
			$response['status'] = false;
		}
		return $response;
		
	}
	
	

	// EXPORT FILTERS AV
    public function ays_poll_show_filters(){
        error_reporting(0);
        global $wpdb;
        $poll_table = $wpdb->prefix . "ayspoll_polls";

        if (isset($_REQUEST['action']) && $_REQUEST['action'] == 'ays_poll_show_filters') {          
        	$poll_sql = "SELECT * FROM $poll_table";

        	$current_user = get_current_user_id();
        	$check_owner = false;
	        if( ! current_user_can( 'manage_options' ) ){
	            $poll_sql .= " WHERE author_id = ".$current_user;
	            $check_owner = true;
	        }

			$polls = $wpdb->get_results($poll_sql, "ARRAY_A");

			$poll_ids = array();
			foreach ($polls as $polls_value) {
				$poll_ids[] =  $polls_value['id'];
			}
			$ids = implode(',', $poll_ids);

			$poll_id_report = '';
			if ($check_owner) {
	            $poll_id_report .= " WHERE poll_id IN (".$ids.") ";
			}

            $sql = "SELECT COUNT(*) FROM {$wpdb->prefix}ayspoll_reports ".$poll_id_report." ORDER BY id DESC";
            $qanak = $wpdb->get_var($sql);
            if(!isset($qanak)){
				$qanak = 0;
			}

            echo json_encode(array(
                "polls" => $polls,
                "count" => $qanak
            ));
            wp_die();
        }
    }

    public function get_poll_title( $item ) {
		global $wpdb;

		$result = $wpdb->get_row("SELECT * FROM {$wpdb->prefix}ayspoll_answers WHERE id={$item['answer_id']}", "ARRAY_A");

		$res = $wpdb->get_row("SELECT * FROM {$wpdb->prefix}ayspoll_polls WHERE id={$result['poll_id']}", "ARRAY_A");

		return stripslashes($res['title']);
	}

	public function column_answer( $item ) {
		global $wpdb;

		$result = $wpdb->get_row("SELECT * FROM {$wpdb->prefix}ayspoll_answers WHERE id={$item['answer_id']}", "ARRAY_A");		

		return stripslashes($result['answer']);
	}

	public function ays_poll_results_export_file(){
    	global $wpdb;
		error_reporting(0);
		$id = $_REQUEST['poll_id'];
		$get_poll_query = '';
		$where = '';
		$poll_table 			= esc_sql( $wpdb->prefix . "ayspoll_polls" );
		$poll_answers_table 	= esc_sql( $wpdb->prefix . "ayspoll_answers" );
		$poll_reports_table 	= esc_sql( $wpdb->prefix . "ayspoll_reports" );
		$poll_formfields_table 	= esc_sql( $wpdb->prefix . "ayspoll_formfields" );

		if (isset($id) && !empty($id)) {
			$ids = implode(',', $id);
			$get_poll_query = ' WHERE a.poll_id IN ('.$ids.')';
			$where = ' WHERE poll_id IN ('.$ids.')';
		}

		$current_user = get_current_user_id();
		$check_owner = false;
		$ids = '';
		if( ! current_user_can( 'manage_options' ) ){
			$poll_sql   = "SELECT * FROM ".$poll_table." WHERE author_id =".$current_user;
			$polls = $wpdb->get_results($poll_sql, "ARRAY_A");
			$poll_ids = array();
			foreach ($polls as $polls_value) {
				$poll_ids[] =  $polls_value['id'];
			}
			$ids = implode(',', $poll_ids);
			$check_owner = true;
		}
		if($check_owner){
			if(isset($ids) && !empty($ids)){
				$poll_filtered_ids = $ids;
				if(!empty($_REQUEST)){
					$poll_filtered_ids_arr = isset($_REQUEST['poll_id']) && $_REQUEST['poll_id'] != '' ? $_REQUEST['poll_id'] : array();
					if(!empty($poll_filtered_ids_arr)){
						$poll_filtered_ids = array();
						foreach($poll_filtered_ids_arr as $f_key => $f_value){
							$poll_filtered_ids[] = $f_value;
						}
						$poll_filtered_ids = implode(',' , $poll_filtered_ids);
					}
				}
				$get_poll_query = ' WHERE a.poll_id IN ('.$poll_filtered_ids.')';
				$where = ' WHERE poll_id IN ('.$poll_filtered_ids.')';
			}
			if($get_poll_query == '' && $where == ''){
				echo json_encode(array(
					'status' => false
				));
				wp_die();
			}
		}

    	$path = plugin_dir_path(__FILE__) . "partials/results/";

		$sql                = "SELECT r.*, a.poll_id, a.id FROM `{$poll_reports_table}` AS r JOIN `{$poll_answers_table}` AS a ON r.answer_id = a.id ".$get_poll_query ." ORDER BY r.id DESC";
		$results            = $wpdb->get_results($sql);

		$sql                = "SELECT `name` FROM {$poll_formfields_table}";
		$formfields         = $wpdb->get_results($sql);
		$file_path          = $path . 'export_file/poll_results_export.csv';
		$export_file        = fopen($file_path, 'wa');

		$results_sql = "SELECT * FROM {$poll_reports_table} ". $where ." ORDER BY id DESC";

		$results_arr = $wpdb->get_results( $results_sql , "ARRAY_A");
		$count = count( $results_arr );

		$all_answers_arr = array();
		if ( ! is_null( $results_arr ) && isset( $results_arr ) && ! empty( $results_arr ) ) {
			$all_answers_arr = $this->ays_poll_get_multi_answer( $results_arr );
		}

		if (!$export_file) {
			echo json_encode(array(
				'status' => false
			));
			wp_die();
		}

		$export_file_fields = array('user','poll', 'answer', 'vote_date', 'user_ip', 'user_email', 'Name', 'Vote Reason');
		foreach ( $formfields as $formfield ) {
			array_push($export_file_fields, $formfield->name);
		}
		
		fputcsv($export_file, $export_file_fields);

		foreach ( $results as $r_key => $result ) {
			$result            = (array) $result;
			$result_option     = (array) json_decode($result['other_info']);

			if (isset($result_option)) {
				if (isset($result_option[0]) && $result_option[0] == 0) {
					$result_formfield_correct = array();
				}else{
					if (!empty($result_option)) {
						$result_formfield_correct = (array) $result_option;
					}else{
						$result_formfield_correct = array();
					}		
				}		
			}else{
				$result_formfield_correct = array();
			}

			$user_id 				 = (isset($result['user_id']) && $result['user_id'] != '') ? absint(intval($result['user_id'])) : '';
			$get_user 				 = get_user_by('id',$user_id);
			$user_name               = ($user_id === 0) ? 'Guest' : $get_user->data->display_name;
			
			$poll_title        		 = $this->get_poll_title($result);
			$answer            		 = (isset( $all_answers_arr[ $r_key ] ) && $all_answers_arr[ $r_key ] != '' ) ? sanitize_text_field( $all_answers_arr[ $r_key ] ) : '';
			$other_info_name   		 = isset($result_option['Name']) ? $result_option['Name'] : '';		
			$other_info_voteReason   = isset($result_option['voteReason']) ? $result_option['voteReason'] : '';
			$results_array_csv = [
				$user_name,
				$poll_title,
				$answer,
				$result['vote_date'],
				$result['user_ip'],
				$result['user_email'],
				$other_info_name,
				$other_info_voteReason
			];
			foreach ( $formfields as $formfield ) {
				$formfield = (array) $formfield;
				if (isset($result_formfield_correct[$formfield['name']])) {
					array_push($results_array_csv, $result_formfield_correct[$formfield['name']]);
				} else {
					array_push($results_array_csv, '');
				}

			}
			fputcsv($export_file, $results_array_csv);
		}
		fclose($export_file);

		echo json_encode(array(
			'status' => true,
			'file' => $file_path,
			'count' => $count,
		));

        wp_die();
    }

	public function ays_poll_get_multi_answer( $results ) {
		global $wpdb;
		$poll_answers_table = esc_sql( $wpdb->prefix . "ayspoll_answers" );

		$all_answers_arr = array();
		if (  isset( $results ) && ! empty( $results ) ) {
			foreach ($results as $res_key => $result_arr) {
				$multivote_res = false;
				$result_arr['multi_answer_id'] = json_decode($result_arr['multi_answer_id']);
				if (isset($result_arr['multi_answer_id']) && count($result_arr['multi_answer_id']) > 0) {
					$multivote_res = true;
				}

				if ($multivote_res) {
					$multivote_answers_arr = array();
					foreach ($result_arr['multi_answer_id'] as $m_key => $m_val) {
						$multi_answer = $wpdb->get_row("SELECT * FROM {$poll_answers_table} WHERE id=".$m_val, "ARRAY_A");

						if ( ! is_null( $multi_answer ) && isset( $multi_answer ) ) {
							if ( isset( $multi_answer['answer'] ) ) {
								$multivote_answers_arr[] = $multi_answer['answer'];
							}
						}
					}

					$multivote_answers_str = implode( ', ' ,  $multivote_answers_arr );

					$all_answers_arr[] = $multivote_answers_str;
				} else {
					$answer = $wpdb->get_row("SELECT * FROM {$poll_answers_table} WHERE id={$result_arr['answer_id']}", "ARRAY_A");

					if ( ! is_null( $answer ) && isset( $answer ) ) {
						if ( isset( $answer['answer'] ) ) {
							$all_answers_arr[] = $answer['answer'];
						}
					}
				}
			}
		}

		return $all_answers_arr;
	}

	public static function is_classic_editor_plugin_active() {
        if ( ! function_exists( 'is_plugin_active' ) ) {
            include_once ABSPATH . 'wp-admin/includes/plugin.php';
        }

        if ( is_plugin_active( 'classic-editor/classic-editor.php' ) ) {
            return true;
        }

        return false;
    }
	
	public static function is_active_gutenberg() {
        // Gutenberg plugin is installed and activated.
        $gutenberg = ! ( false === has_filter( 'replace_editor', 'gutenberg_init' ) );
        // Block editor since 5.0.
        $block_editor = version_compare( $GLOBALS['wp_version'], '5.0-beta', '>' );

        if ( ! $gutenberg && ! $block_editor ) {
            return false;
        }

        if ( self::is_classic_editor_plugin_active() ) {
            $editor_option       = get_option( 'classic-editor-replace' );
            $block_editor_active = array( 'no-replace', 'block' );

            return in_array( $editor_option, $block_editor_active, true );
        }

        return true;
    }

    public function ays_poll_google_get_refresh_token($data){
    	error_reporting(0);
		if (empty($data)) {
			return array(
				'Code' => 0
			);
        }

        $refresh_token = isset($data['refresh_token']) && $data['refresh_token'] != '' ? $data['refresh_token'] : '';
        $google_client = isset($data['google_client']) && $data['google_client'] != '' ? $data['google_client'] : '';
        $google_secret = isset($data['google_secret']) && $data['google_secret'] != '' ? $data['google_secret'] : '';

        $url = "https://accounts.google.com/o/oauth2/token?grant_type=refresh_token&refresh_token=".$refresh_token."&client_id=".$google_client."&client_secret=".$google_secret."&scope=https://www.googleapis.com/auth/spreadsheets";
        
        $curl = curl_init();
        
        curl_setopt_array($curl, array(
            CURLOPT_URL => $url,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => "",
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 0,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_SSL_VERIFYPEER => false,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => "POST",
            CURLOPT_POSTFIELDS => NULL,
        	CURLOPT_HTTPHEADER => array(
	            "response_type: webapplications",
	            "Content-Type: application/json"
	        ),
	    ));
    
        $response_refresh = curl_exec($curl);
        $err = curl_error($curl);
        $response = json_decode($response_refresh, true);
        curl_close($curl);
        $new_access_token = $response['access_token'];

        if ($err) {
            return "cURL Error #: " . $err;
        } else {
            return $new_access_token;
        }
    }

    public function ays_poll_get_google_sheet_id( $data ) {
		global $wpdb;	
		error_reporting(0);
		if (empty($data)) {
			return array(
				'Code' => 0
			);
        }
        $new_token = '';
        $get_this_poll = array();
        $question = '';
        $refresh_token = isset($data['refresh_token']) && $data['refresh_token'] != '' ? $data['refresh_token'] : '';
        $google_client = isset($data['google_client']) && $data['google_client'] != '' ? $data['google_client'] : '';
        $google_secret = isset($data['google_secret']) && $data['google_secret'] != '' ? $data['google_secret'] : '';
        $poll_title    = isset($data['poll_title']) && $data['poll_title'] != '' ? $data['poll_title'] : '';
        $id            = isset($data['id']) && $data['id'] != '' ? $data['id'] : null;
        if($refresh_token != ''){
        	$new_token = self::ays_poll_google_get_refresh_token($data);
        }

        $url = "https://sheets.googleapis.com/v4/spreadsheets?access_token=".$new_token;
        $properties = array(
        	"properties" => array(
        		"title"  => $poll_title        		
        	),
        	"sheets" => array(
	        	"data" => array(
				  "rowData" => array(
				  	"values" => array(
				  			array(
					  			"userEnteredValue" => array(
					  				"stringValue" => 'Poll Question',
					  			)
				  			),
				  			array(
					  			"userEnteredValue" => array(
					  				"stringValue" => "Answer"
					  			)
				  			),
				  			array(
					  			"userEnteredValue" => array(
					  				"stringValue" => "Vote Date"
					  			)
				  			),
				  			array(
					  			"userEnteredValue" => array(
					  				"stringValue" => "User IP"
					  			)
				  			),
				  			array(
					  			"userEnteredValue" => array(
					  				"stringValue" => "User Email"
					  			)
				  			),
				  			array(
					  			"userEnteredValue" => array(
					  				"stringValue" => "User Name"
					  			)
				  			),
				  			array(
					  			"userEnteredValue" => array(
					  				"stringValue" => "Vote Reason"
					  			)
				  			)
				  		)
				  	)				  
	        	)
        	)
        );

        $properties = json_encode($properties);

        $curl = curl_init();

        curl_setopt_array($curl, array(
	        CURLOPT_URL => $url,
	        CURLOPT_RETURNTRANSFER => true,
	        CURLOPT_ENCODING => "",
	        CURLOPT_MAXREDIRS => 10,
	        CURLOPT_TIMEOUT => 0,
	        CURLOPT_FOLLOWLOCATION => true,
	        CURLOPT_SSL_VERIFYPEER => false,
	        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
	        CURLOPT_CUSTOMREQUEST => "POST",
	        CURLOPT_POSTFIELDS => $properties,
	        CURLOPT_HTTPHEADER => array(           
	            "response_type: webapplications",
	            "Content-Type: application/json"
	        ),
        ));

        $response = curl_exec($curl);
        $err = curl_error($curl);
        $google_sheet_values = json_decode($response, true);
        curl_close($curl);
        $spreadsheet_id = $google_sheet_values['spreadsheetId'];

        if ($err) {
            return "cURL Error #: " . $err;
        } else {
            return $spreadsheet_id;
        }
	}


    public function ays_poll_add_request() {
    	error_reporting(0);
        global $wpdb;
        $polls_table    = $wpdb->prefix . 'ayspoll_polls';
        $answers_table  = $wpdb->prefix . 'ayspoll_answers';
        $requests_table = $wpdb->prefix . 'ayspoll_requests';

        if (isset($_REQUEST['action']) && $_REQUEST['action'] == 'ays_poll_add_request') {
	        $request_id = (isset($_REQUEST['id']) && $_REQUEST['id'] != null) ? absint(intval($_REQUEST['id'])) : null;
	        $data = '';
	        if ($request_id == null) {
		    	$result = array(
		            'status' => false,
		            'data'   => $data,
		        );
		        ob_end_clean();
		        $ob_get_clean = ob_get_clean();
		        echo json_encode($result);
		        wp_die();
	        }
	        $sql = "SELECT * FROM {$requests_table} WHERE id = {$request_id};";
	        $results = $wpdb->get_row($sql,'ARRAY_A');

	        $poll_title = (isset($results['title']) && $results['title'] != '') ? $results['title'] : __( "Default title" , $this->plugin_name );
	        $question = (isset($results['question']) && $results['question'] != '') ? $results['question'] : '';
	        $answers = (isset($results['answers']) && ! empty($results['answers'])) ? json_decode($results['answers']) : array();
			$cat_ids    = (isset($results['category_id'])) && $results['category_id'] != 1 ? ',1,'.strval($results['category_id']).',' : ',1,';

	        $styles = $this->ays_poll_generate_default_options();

	        $user_id = get_current_user_id();
			$user = get_userdata($user_id);
			$author_id = $user->ID;

	        $poll_res = $wpdb->insert(
	        	$polls_table, 
	        	array(
	                'title'       => $poll_title,
	                'author_id'   => $author_id,
					'description' => '',
					'categories'  => $cat_ids,
					'image'       => '',
					'question'    => $question,
					'type'        => 'choosing',
					'view_type'   => 'list',
					'show_title'  => 1,
					'styles'      => json_encode($styles),
					'custom_css'  => '',
					'theme_id'    => 1,
	            ),
	            array(
					'%s', // title
					'%d', // author_id
					'%s', // description
					'%s', // categories
					'%s', // image
					'%s', // question
					'%s', // type
					'%s', // view_type
					'%d', // show_title
					'%s', // styles
					'%s', // custom_css
					'%d', // theme_id
				)
            );

            $poll_id = $wpdb->insert_id;

            if (! empty($answers)) {
	        	foreach ( $answers as $key => $answer ) {
					if (empty($answer)) {
						continue;
					}

					$ans_res = $wpdb->insert(
						$answers_table,
						array(
							'poll_id' => $poll_id,
							'answer'  => wp_filter_kses($answer),
							'votes'   => 0,
						),
						array(
							'%d', // poll_id
							'%s', // answer
							'%d', // votes
						)
					);

				}
	        }

	        $update_approved_val = $wpdb->update(
                $requests_table,
                array( 
                	'approved' => 1,
                	'poll_id'  => $poll_id,
                 ),
                array( 'id' => $request_id ),
                array( 
                	'%d', // approved
                	'%d', // poll_id
                ),
                array( '%d' )
            );

	        $data = sprintf('<a href="?page=%s&action=%s&poll=%s" target="_blank">%s</a>', 'poll-maker-ays', 'edit', absint($poll_id) , __( 'Go to Poll' , $this->plugin_name ) );

	        $result = array(
	            'status' => true,
	            'data'   => $data,
	        );

	        ob_end_clean();
	        $ob_get_clean = ob_get_clean();
	        echo json_encode($result);
	        wp_die();
        }

	}

	public static function ays_poll_generate_default_options() {

		/*$user_id = get_current_user_id();
		$user = get_userdata($user_id);
		$author = array(
		    'id' => $user->ID,
		    'name' => $user->data->display_name
		);*/

		$default_options = array(
			"main_color"       		   => "#0C6291",
			"text_color"       		   => "#0C6291",
			"icon_color"       		   => "#0C6291",
			"box_shadow_color" 		   => "#000000",
			"bg_color"         		   => "#FBFEF9",
			"title_bg_color"   		   => "rgba(255,255,255,0)",
			"answer_bg_color"  		   => "#FBFEF9",
			"randomize_answers"        => 'off',
			"icon_size"                => 24,
			"width"                    => 600,
			"btn_text"                 => __('Vote', POLL_MAKER_AYS_NAME),
			"see_res_btn_text"         => __('See Results', POLL_MAKER_AYS_NAME),
			"border_style"             => "ridge",
			"border_radius"            => 0,
			"border_width"             => 1,
			"enable_box_shadow"        => "",
			"bg_image"                 => "",
			"hide_results"             => 0,
			"hide_results_text"        => __("Thanks for your answer!", POLL_MAKER_AYS_NAME),
			"allow_not_vote"           => 0,
			"show_social"              => 0,
			"poll_show_social_ln"      => "on",
			"poll_show_social_fb"      => "on",
			"poll_show_social_tr"      => "on",
			"load_effect"              => "load_gif",
			"load_gif"                 => "plg_pro1",
			'limit_users'              => 0,
			"limitation_message"       => __("You have already voted", POLL_MAKER_AYS_NAME),
			'redirect_url'             => '',
			'redirection_delay'        => '',
			'user_role'                => 0,
			'enable_restriction_pass'  => 0,
			'restriction_pass_message' => __("You don't have permissions for passing the poll", POLL_MAKER_AYS_NAME),
			'enable_logged_users'         => 0,
			'enable_logged_users_message' => __('You must sign in for passing the poll', POLL_MAKER_AYS_NAME),
			'notify_email_on'             => 0,
			'notify_email'                => '',
			'result_sort_type'            => 'none',
			'redirect_after_submit'       => 0,
			'redirect_users'              => 0,
			'redirect_after_vote_url'     => '',
			'redirect_after_vote_delay'   => '',
			'published'                   => 1,
			'enable_pass_count'           => 'on',
			'create_date' 				  => current_time( 'mysql' ),
		    // 'author' 					  => $author,
			'activeInterval'              => '',
			'deactiveInterval'            => '',
			'activeIntervalSec'           => '',
			'deactiveIntervalSec'         => '',
			'enable_background_gradient'  => 'off',
		    'background_gradient_color_1' => '#103251',
		    'background_gradient_color_2' => '#607593',
		    'poll_gradient_direction' 	  => 'vertical',
			'active_date_check'           => '',
			'active_date_message_soon'    => "<p style='text-align: center'>" . __("The poll will be available soon!", POLL_MAKER_AYS_NAME) . "</p>",
			'active_date_message'         => __("The poll has expired!", POLL_MAKER_AYS_NAME),
			'enable_restart_button'       => 0,
			'enable_vote_btn'             => 1,
			'show_votes_count'            => 1,
			'show_res_percent'            => 1,
			'poll_direction'              => 'ltr',
			'allow_multivote'             => 'off',
			'user_add_answer'             => 0,
			'result_in_rgba'              => 0,
			'enable_password'             => 'off',
			'password_poll'               => '',
			'background_size'             => 'cover',
			'disable_answer_hover'        => 0,
			'fake_votes'                  => 'off',
		);
		$default_options_val = Poll_Maker_Settings_Actions::ays_get_setting('poll_default_options');

		$poll_default_options = ($default_options_val === false) ? array() : $default_options_val;
        if (!empty($poll_default_options)) {
            $default_options = json_decode($poll_default_options , true);
        }

		return $default_options;
	}

	public static function ays_restriction_string($type, $x, $length){
        $output = "";
        switch($type){
            case "char":                
                if(strlen($x)<=$length){
                    $output = $x;
                } else {
                    $output = substr($x,0,$length) . '...';
                }
                break;
            case "word":
                $res = explode(" ", $x);
                if(count($res)<=$length){
                    $output = implode(" ",$res);
                } else {
                    $res = array_slice($res,0,$length);
                    $output = implode(" ",$res) . '...';
                }
            break;
        }
        return $output;
    }

    public static function get_listtables_title_length( $listtable_name ) {
        global $wpdb;

        $settings_table = $wpdb->prefix . "ayspoll_settings";
        $sql = "SELECT meta_value FROM ".$settings_table." WHERE meta_key = 'options'";
        $result = $wpdb->get_var($sql);
        $options = ($result == "") ? array() : json_decode($result, true);

        $listtable_title_length = 5;
        if(! empty($options) ){
            switch ( $listtable_name ) {
                case 'polls':
                    $listtable_title_length = (isset($options['poll_title_length']) && intval($options['poll_title_length']) != 0) ? absint(intval($options['poll_title_length'])) : 5;
                    break;  
				case 'categories':
					$listtable_title_length = (isset($options['poll_category_title_length']) && intval($options['poll_category_title_length']) != 0) ? absint(intval($options['poll_category_title_length'])) : 5;
					break;      
				case 'results':
					$listtable_title_length = (isset($options['poll_results_title_length']) && intval($options['poll_results_title_length']) != 0) ? absint(intval($options['poll_results_title_length'])) : 5;
					break;      
		
                default:
                    $listtable_title_length = 5;
                    break;
            }
            return $listtable_title_length;
        }
        return $listtable_title_length;
    }

    public function gamipress_ays_poll_maker_activity_triggers( $triggers ) {

	    $triggers[__( 'Poll Maker', 'gamipress-ays-poll-maker-integration' )] = array(
	        'gamipress_ays_poll_maker_vote_poll' => __( 'Vote on a poll', 'gamipress-ays-poll-maker-integration' ),
	    );

	    return $triggers;
    }

    public function gamipress_ays_poll_maker_vote_poll() {

	    // Get the poll ID

	    $poll_id = ( isset($_REQUEST['poll_id'] ) ? (int) sanitize_key( $_REQUEST['poll_id'] ) : 0 );
	    
	    if( $poll_id === 0 ) return;

	    $user_id = get_current_user_id();

	    // Guests not allowed yet
	    if( $user_id === 0 ) return;

	    // Award user for vote a poll
	    do_action( 'gamipress_ays_poll_maker_vote_poll', $poll_id, $user_id );

	}

	public function gamipress_ays_poll_maker_trigger_get_user_id( $user_id, $trigger, $args ) {

	    switch ( $trigger ) {
	        case 'gamipress_ays_poll_maker_vote_poll':
	            $user_id = $args[1];
	            break;
	    }

	    return $user_id;

	}

	public function ays_import_answers(){
		global $wpdb;
		$answers_table = $wpdb->prefix . "ayspoll_answers";
		$status = false;
		$answers = array();
		$message = '';
		if ($_SERVER['REQUEST_METHOD'] == 'POST') {
			if (isset($_FILES['ays_poll_import_answers']) && $_FILES['ays_poll_import_answers']['error'] == 0) {
				$name = $_FILES['ays_poll_import_answers']['name'];
				$arr  = explode('.', $name);
				$ext  = $arr[count($arr) - 1];
				$status = true;
				if ($ext !== 'csv' && $ext !== 'CSV') {
					$status  = false;
					$message = __('You selected wrong file. Select *.csv file, please.', $this->plugin_name);
				}				
				if($status){
					$csv_data = array();
					if (!file_exists('import')) {
						mkdir(plugin_dir_path(__FILE__) . '/import');
					}
					$upload_dir = plugin_dir_path(__FILE__) . "/import/" . uniqid('apm-import-answers-') . $name;
					move_uploaded_file($_FILES['ays_poll_import_answers']['tmp_name'], $upload_dir);
					
					if (($csv_file = fopen($upload_dir, 'r')) !== false) {
						while ( ($row = fgetcsv($csv_file)) !== false ) {
							$csv_data[] = $row;
						}
						fclose($csv_file);
						unlink($upload_dir);
						rmdir(plugin_dir_path(__FILE__) . '/import');
						$status = false;
						if(!empty($csv_data)){
							foreach($csv_data as $c_key => $c_value){
								$csv_value_check = isset($c_value[0]) && $c_value[0] != '' ? trim($c_value[0]) : false;
								if($csv_value_check){
									$answers[] = $csv_value_check;
								}
							}
							if(isset($answers) && !empty($answers)){
								$status  = true;
								$message = __("Answers has been imported successfully", $this->plugin_name);
							}
						}
					}
				}
			}
		}
		
		echo json_encode(array(
			"status"  => $status,
			"results" => $answers,
			"message" => $message,
		));
		wp_die();
	}

}

ZeroDay Forums Mini