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੐)|#o0aڱ$I>}k&1`U#V?YsV x>{t1[I~D&(I$I/{H0fw"q"y%4 IXyE~M3 8XψL}qE$I[> nD?~sf ]o΁ cT6"?'_Ἣ $I>~.f|'!N?⟩0G KkXZE]ޡ;/&?k OۘH$IRۀwXӨ<7@PnS04aӶp.:@\IWQJ6sS%I$e5ڑv`3:x';wq_vpgHyXZ 3gЂ7{{EuԹn±}$I$8t;b|591nءQ"P6O5i }iR̈́%Q̄p!I䮢]O{H$IRϻ9s֧ a=`- aB\X0"+5"C1Hb?߮3x3&gşggl_hZ^,`5?ߎvĸ%̀M!OZC2#0x LJ0 Gw$I$I}<{Eb+y;iI,`ܚF:5ܛA8-O-|8K7s|#Z8a&><a&/VtbtLʌI$I$I$I$I$I$IRjDD%tEXtdate:create2022-05-31T04:40:26+00:00!Î%tEXtdate:modify2022-05-31T04:40:26+00:00|{2IENDB`Mini Shell

HOME


Mini Shell 1.0
DIR:/home/psrcpvtltd.com/www/wp-content/plugins/newsletter/subscription/
Upload File :
Current File : /home/psrcpvtltd.com/www/wp-content/plugins/newsletter/subscription/subscription.php
<?php

defined('ABSPATH') || exit;

class NewsletterSubscription extends NewsletterModule {

    const MESSAGE_CONFIRMED = 'confirmed';
    const OPTIN_DOUBLE = 0;
    const OPTIN_SINGLE = 1;

    static $instance;

    /**
     * @var array
     */
    var $options_profile;

    /**
     * Contains the options for the current language to build a subscription form. Must be initialized with
     * setup_form_options() before use.
     * 
     * @var array
     */
    var $form_options = null;

    /**
     * Contains the antibot/antispam options. Must be initialized with
     * setup_antibot_options() before use.
     * 
     * @var array
     */
    var $antibot_options = null;

    /**
     * @var array
     */
    var $options_lists;

    /**
     * @return NewsletterSubscription
     */
    static function instance() {
        if (self::$instance == null) {
            self::$instance = new NewsletterSubscription();
        }
        return self::$instance;
    }

    function __construct() {

        parent::__construct('subscription', '2.2.7', null, array('lists', 'template', 'profile', 'antibot'));
        $this->options_profile = $this->get_options('profile');
        $this->options_lists = $this->get_options('lists');

        // Must be called after the Newsletter::hook_init, since some constants are defined
        // there.
        add_action('init', array($this, 'hook_init'), 90);
    }

    function hook_init() {
        add_action('newsletter_action', array($this, 'hook_newsletter_action'), 10, 3);
        if (is_admin()) {
            add_action('admin_init', array($this, 'hook_admin_init'));
        } else {
            add_action('wp_enqueue_scripts', array($this, 'hook_wp_enqueue_scripts'));
            // Shortcode for the Newsletter page
            add_shortcode('newsletter', array($this, 'shortcode_newsletter'));
            add_shortcode('newsletter_form', array($this, 'shortcode_newsletter_form'));
            add_shortcode('newsletter_field', array($this, 'shortcode_newsletter_field'));
        }
    }

    function hook_admin_init() {
        // So the user can add JS and other code
        if (isset($_GET['page']) && $_GET['page'] === 'newsletter_subscription_forms') {
            header('X-XSS-Protection: 0');
        }

        if (function_exists('register_block_type')) {
            // Add custom blocks to Gutenberg
            wp_register_script('tnp-blocks', NEWSLETTER_URL . '/includes/tnp-blocks.js', array('wp-blocks', 'wp-element', 'wp-editor'), NEWSLETTER_VERSION);
            register_block_type('tnp/minimal', array('editor_script' => 'tnp-blocks'));
        }
    }

    function hook_wp_enqueue_scripts() {

        wp_enqueue_script('newsletter-subscription', plugins_url('newsletter') . '/subscription/validate.js', array(), NEWSLETTER_VERSION, true);

        $options = $this->get_options('profile', $this->get_current_language());

        $data = array();
        $data['messages'] = array();
        if (isset($options['email_error'])) {
            $data['messages']['email_error'] = $options['email_error'];
        }
        if (isset($options['name_error'])) {
            $data['messages']['name_error'] = $options['name_error'];
        }
        if (isset($options['surname_error'])) {
            $data['messages']['surname_error'] = $options['surname_error'];
        }
        if (isset($options['profile_error'])) {
            $data['messages']['profile_error'] = $options['profile_error'];
        }
        if (isset($options['privacy_error'])) {
            $data['messages']['privacy_error'] = $options['privacy_error'];
        }
        $data['profile_max'] = NEWSLETTER_PROFILE_MAX;
        wp_localize_script('newsletter-subscription', 'newsletter', $data);
    }

    function ip_match($ip, $range) {
        if (strpos($range, '/')) {
            list ($subnet, $bits) = explode('/', $range);
            $ip = ip2long($ip);
            $subnet = ip2long($subnet);
            $mask = -1 << (32 - $bits);
            $subnet &= $mask; # nb: in case the supplied subnet wasn't correctly aligned
            return ($ip & $mask) == $subnet;
        } else {
            return strpos($range, $ip) === 0;
        }
    }

    function is_address_blacklisted($email) {
        $this->setup_antibot_options();

        if (empty($this->antibot_options['address_blacklist'])) {
            return false;
        }

        //$this->logger->debug('Address blacklist check');
        $rev_email = strrev($email);
        foreach ($this->antibot_options['address_blacklist'] as $item) {
            if (strpos($rev_email, strrev($item)) === 0) {
                return true;
            }
        }
        return false;
    }

    function is_ip_blacklisted($ip) {
        $this->setup_antibot_options();

        if (empty($this->antibot_options['ip_blacklist'])) {
            return false;
        }
        //$this->logger->debug('IP blacklist check');
        foreach ($this->antibot_options['ip_blacklist'] as $item) {
            if ($this->ip_match($ip, $item)) {
                return true;
            }
        }
        return false;
    }

    function is_missing_domain_mx($email) {
        // Actually not fully implemented
        return false;

        if (empty($this->options['domain_check'])) {
            return false;
        }

        $this->logger->debug('Domain MX check');
        list($local, $domain) = explode('@', $email);

        $hosts = array();
        if (!getmxrr($domain, $hosts)) {
            return true;
        }
        return false;
    }

    function is_flood($email, $ip) {
        global $wpdb;

        $this->setup_antibot_options();

        if (empty($this->antibot_options['antiflood'])) {
            return false;
        }

        //$this->logger->debug('Antiflood check');

        $updated = $wpdb->get_var($wpdb->prepare("select updated from " . NEWSLETTER_USERS_TABLE . " where ip=%s or email=%s order by updated desc limit 1", $ip, $email));

        if ($updated && time() - $updated < $this->antibot_options['antiflood']) {
            return true;
        }

        return false;
    }

    function is_spam_text($text) {
        if (stripos($text, 'http:') !== false || stripos($text, 'https:') !== false) {
            return true;
        }
        if (stripos($text, 'www.') !== false) {
            return true;
        }

        return false;
    }

    function is_spam_by_akismet($email, $name, $ip, $agent, $referrer) {

        if (!class_exists('Akismet')) {
            return false;
        }

        $this->setup_antibot_options();

        if (empty($this->antibot_options['akismet'])) {
            return false;
        }


        $this->logger->debug('Akismet check');
        $request = 'blog=' . urlencode(home_url()) . '&referrer=' . urlencode($referrer) .
                '&user_agent=' . urlencode($agent) .
                '&comment_type=signup' .
                '&comment_author_email=' . urlencode($email) .
                '&user_ip=' . urlencode($ip);
        if (!empty($name)) {
            $request .= '&comment_author=' . urlencode($name);
        }

        $response = Akismet::http_post($request, 'comment-check');

        if ($response && $response[1] == 'true') {
            return true;
        }
        return false;
    }

    /**
     * $email must be cleaned using the is_email() function.
     *
     * @param type $email
     * @param type $full_name
     * @param type $ip
     */
    function valid_subscription_or_die($email, $full_name, $ip) {
        $antibot_logger = new NewsletterLogger('antibot');

        $antibot_logger->info($_REQUEST);

        if (empty($email)) {
            echo 'Wrong email';
            header("HTTP/1.0 400 Bad request");
            die();
        }

        if ($this->is_spam_text($full_name)) {
            $antibot_logger->fatal($email . ' - ' . $ip . ' - Name with http: ' . $full_name);
            header("HTTP/1.0 404 Not Found");
            die();
        }

        if ($this->is_missing_domain_mx($email)) {
            $antibot_logger->fatal($email . ' - ' . $ip . ' - MX check failed');
            header("HTTP/1.0 404 Not Found");
            die();
        }

        if ($this->is_ip_blacklisted($ip)) {
            $antibot_logger->fatal($email . ' - ' . $ip . ' - IP blacklisted');
            header("HTTP/1.0 404 Not Found");
            die();
        }

        if ($this->is_address_blacklisted($email)) {
            $antibot_logger->fatal($email . ' - ' . $ip . ' - Address blacklisted');
            header("HTTP/1.0 404 Not Found");
            die();
        }

        // Akismet check
        if ($this->is_spam_by_akismet($email, $full_name, $ip, $_SERVER['HTTP_USER_AGENT'], $_SERVER['HTTP_REFERER'])) {
            $antibot_logger->fatal($email . ' - ' . $ip . ' - Akismet blocked');
            header("HTTP/1.0 404 Not Found");
            die();
        }

        // Flood check
        if ($this->is_flood($email, $ip)) {
            $antibot_logger->fatal($email . ' - ' . $ip . ' - Antiflood triggered');
            header("HTTP/1.0 404 Not Found");
            die('Too quick. Check the antiflood on security page.');
        }
    }

    /**
     *
     * @global wpdb $wpdb
     * @return mixed
     */
    function hook_newsletter_action($action, $user, $email) {
        global $wpdb;

        switch ($action) {
            case 'profile-change':
                if ($this->antibot_form_check()) {

                    if (!$user || $user->status != TNP_user::STATUS_CONFIRMED) {
                        $this->dienow('Subscriber not found or not confirmed.');
                    }

                    if (!$email) {
                        $this->dienow('Newsletter not found');
                    }

                    if (isset($_REQUEST['list'])) {
                        $list_id = (int) $_REQUEST['list'];

                        // Check if the list is public
                        $list = $this->get_list($list_id);
                        if (!$list || $list->status == TNP_List::STATUS_PRIVATE) {
                            $this->dienow('List change not allowed.', 'Please check if the list is marked as "private".');
                        }

                        $url = esc_url_raw($_REQUEST['redirect']);

                        $this->set_user_list($user, $list_id, $_REQUEST['value']);

                        $user = $this->get_user($user->id);
                        $this->add_user_log($user, 'cta');
                        NewsletterStatistics::instance()->add_click($url, $user->id, $email->id);
                        wp_redirect($url);
                        die();
                    }
                } else {
                    $this->request_to_antibot_form('Continue');
                }

                die();

            case 'm':
            case 'message':
                include dirname(__FILE__) . '/page.php';
                die();

            // normal subscription
            case 's':
            case 'subscribe':

                if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
                    $this->dienow('Invalid request');
                }

                $options_antibot = $this->get_options('antibot');

                $captcha = !empty($options_antibot['captcha']);

                if (!empty($options_antibot['disabled']) || $this->antibot_form_check($captcha)) {

                    $user = $this->subscribe();

                    if ($user->status == 'E')
                        $this->show_message('error', $user);
                    if ($user->status == 'C')
                        $this->show_message('confirmed', $user);
                    if ($user->status == 'A')
                        $this->show_message('already_confirmed', $user);
                    if ($user->status == 'S')
                        $this->show_message('confirmation', $user);
                } else {
                    // Temporary store data
                    //$data_key =  wp_generate_password(16, false, false);
                    //set_transient('newsletter_' . $data_key, $_REQUEST, 60);
                    //$this->antibot_redirect($data_key);
                    $this->request_to_antibot_form('Subscribe', $captcha);
                }
                die();

            // AJAX subscription
            case 'ajaxsub':

                if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
                    //$antibot_logger->fatal('HTTP method invalid');
                    $this->dienow('Invalid request');
                }

                $user = $this->subscribe();

                if ($user->status == 'E')
                    $key = 'error';
                if ($user->status == 'C')
                    $key = 'confirmed';
                if ($user->status == 'A')
                    $key = 'already_confirmed';
                if ($user->status == 'S')
                    $key = 'confirmation';


                $message = $this->replace($this->options[$key . '_text'], $user);
                if (isset($this->options[$key . '_tracking'])) {
                    $message .= $this->options[$key . '_tracking'];
                }
                echo $message;
                die();

            case 'c':
            case 'confirm':
                if ($this->antibot_form_check()) {
                    // TODO: Change to accept $user
                    $user = $this->confirm();
                    if ($user->status == 'E') {
                        $this->show_message('error', $user->id);
                    } else {
                        setcookie('newsletter', $user->id . '-' . $user->token, time() + 60 * 60 * 24 * 365, '/');
                        $this->show_message('confirmed', $user);
                    }
                } else {
                    $this->request_to_antibot_form('Confirm');
                }
                die();
                break;

            default:
                return;
        }
    }

    function upgrade() {
        global $wpdb, $charset_collate;

        parent::upgrade();

        $newsletter = Newsletter::instance();
        $lists_options = $this->get_options('lists');
        $profile_options = $this->get_options('profile');

        if (empty($lists_options)) {
            foreach ($profile_options as $key => $value) {
                if (strpos($key, 'list_') === 0) {
                    $lists_options[$key] = $value;
                }
            }
        }

        for ($i = 1; $i <= NEWSLETTER_LIST_MAX; $i++) {
            // Options migration to the new set
            if (!empty($profile_options['list_' . $i]) && empty($lists_options['list_' . $i])) {
                $lists_options['list_' . $i] = $profile_options['list_' . $i];
                $lists_options['list_' . $i . '_checked'] = $profile_options['list_' . $i . '_checked'];
                $lists_options['list_' . $i . '_forced'] = $profile_options['list_' . $i . '_forced'];
            }

            if (!isset($profile_options['list_' . $i . '_forced'])) {
                $profile_options['list_' . $i . '_forced'] = empty($this->options['preferences_' . $i]) ? 0 : 1;
                $lists_options['list_' . $i . '_forced'] = empty($this->options['preferences_' . $i]) ? 0 : 1;
            }
        }

        $this->save_options($profile_options, 'profile');
        $this->save_options($lists_options, 'lists');


        $default_options = $this->get_default_options();

        if (empty($this->options['error_text'])) {
            $this->options['error_text'] = $default_options['error_text'];
            $this->save_options($this->options);
        }

        $this->init_options('template', false);

        global $wpdb, $charset_collate;

        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');

        $sql = "CREATE TABLE `" . $wpdb->prefix . "newsletter_user_logs` (
            `id` int(11) NOT NULL AUTO_INCREMENT,
            `user_id` int(11) NOT NULL DEFAULT 0,
            `ip` varchar(50) NOT NULL DEFAULT '',
            `source` varchar(50) NOT NULL DEFAULT '',
            `data` longtext,
            `created` int(11) NOT NULL DEFAULT 0,
            PRIMARY KEY (`id`)
          ) $charset_collate;";

        dbDelta($sql);

        return true;
    }

    function first_install() {
        
    }

    function admin_menu() {
        $this->add_menu_page('options', 'List building');
        $this->add_menu_page('antibot', 'Security');
        $this->add_admin_page('profile', 'Subscription Form');
        $this->add_admin_page('forms', 'Forms');
        $this->add_admin_page('lists', 'Lists');
        $this->add_admin_page('template', 'Template');
    }

    /**
     * This method has been redefined for compatibility with the old options naming. It would
     * be better to change them instead. The subscription options should be named
     * "newsletter_subscription" while the form field options, actually named
     * "newsletter_profile", should be renamed "newsletter_subscription_profile" (since
     * they are retrived with get_options('profile')) or "newsletter_subscription_fields" or
     * "newsletter_subscription_form".
     *
     * @param array $options
     * @param string $sub
     */
    function save_options($options, $sub = '', $autoload = null, $language = '') {
        if (empty($sub) && empty($language)) {
            // For compatibility the options are wrongly named
            return update_option('newsletter', $options, $autoload);
        }

        if (empty($sub) && !empty($language)) {
            return update_option('newsletter_' . $language, $options, $autoload);
        }

        if ($sub == 'profile') {
            if (empty($language)) {
                $this->options_profile = $options;
                return update_option('newsletter_profile', $options, $autoload);
            } else {
                return update_option('newsletter_profile_' . $language, $options, $autoload);
            }
            // For compatibility the options are wrongly named
        }

        if ($sub == 'forms') {
            // For compatibility the options are wrongly named
            return update_option('newsletter_forms', $options, $autoload);
        }

        if ($sub == 'lists') {
            $this->options_lists = $options;
        }
        return parent::save_options($options, $sub, $autoload, $language);
    }

    function get_options($sub = '', $language = '') {
        if ($sub == '') {
            // For compatibility the options are wrongly named
            if ($language) {
                $options = get_option('newsletter_' . $language, array());
                $options = array_merge(get_option('newsletter', array()), $options);
            } else {
                $options = get_option('newsletter', array());
            }
            if (!is_array($options)) {
                $options = array();
            }

            return $options;
        }
        if ($sub == 'profile') {
            if ($language) {
                // All that because for unknown reasome, sometime the options are returned as string, maybe a WPML
                // interference...
                $i18n_options = get_option('newsletter_profile_' . $language, array());
                if (!is_array($i18n_options))
                    $i18n_options = array();
                $options = get_option('newsletter_profile', array());
                if (!is_array($options))
                    $options = array();
                $options = array_merge($options, array_filter($i18n_options));
            } else {
                $options = get_option('newsletter_profile', array());
            }
            // For compatibility the options are wrongly named
            return $options;
        }
        if ($sub == 'forms') {
            // For compatibility the options are wrongly named
            return get_option('newsletter_forms', array());
        }
        return parent::get_options($sub, $language);
    }

    /**
     * Prepares the options used to build a subscription form for the current language
     * in internal variable $form_options (for optimization). Can be called many times.
     */
    function setup_form_options() {
        if (empty($this->form_options)) {
            $this->form_options = $this->get_options('profile', $this->get_current_language());
        }
    }

    function setup_antibot_options() {
        if (empty($this->antibot_options)) {
            $this->antibot_options = $this->get_options('antibot');
        }
    }

    function get_form_options($language = '') {
        return $this->get_options('profile', $language);
    }

    function set_updated($user, $time = 0, $ip = '') {
        global $wpdb;
        if (!$time) {
            $time = time();
        }

        if (!$ip) {
            $ip = $this->get_remote_ip();
        }
        $ip = $this->process_ip($ip);

        if (is_object($user)) {
            $id = $user->id;
        } else if (is_array($user)) {
            $id = $user['id'];
        }

        $id = (int) $id;

        $wpdb->update(NEWSLETTER_USERS_TABLE, array('updated' => $time, 'ip' => $ip, 'geo' => 0), array('id' => $id));
    }

    /**
     * Create a subscription using the $_REQUEST data. Does security checks.
     *
     * @param string $status The status to use for this subscription (confirmed, not confirmed, ...)
     * @param bool $emails If the confirmation/welcome email should be sent or the subscription should be silent
     * @return TNP_User
     */
    function subscribe($status = null, $emails = true) {

        $options_profile = $this->get_options('profile');
        /*
          if ($options_profile['name_status'] == 0 && isset($_REQUEST['nn'])) {
          // Name injection
          die();
          }
          if ($options_profile['surname_status'] == 0 && isset($_REQUEST['ns'])) {
          // Last name injection
          die();
          }
         */

        // Validation
        $ip = $this->get_remote_ip();
        $email = $this->normalize_email(stripslashes($_REQUEST['ne']));
        $first_name = '';
        if (isset($_REQUEST['nn'])) {
            $first_name = $this->normalize_name(stripslashes($_REQUEST['nn']));
        }

        $last_name = '';
        if (isset($_REQUEST['ns'])) {
            $last_name = $this->normalize_name(stripslashes($_REQUEST['ns']));
        }

        $full_name = trim($first_name . ' ' . $last_name);

        $this->valid_subscription_or_die($email, $full_name, $ip);

        $opt_in = (int) $this->options['noconfirmation']; // 0 - double, 1 - single
        if (!empty($this->options['optin_override']) && isset($_REQUEST['optin'])) {
            switch ($_REQUEST['optin']) {
                case 'single': $opt_in = self::OPTIN_SINGLE;
                    break;
                case 'double': $opt_in = self::OPTIN_DOUBLE;
                    break;
            }
        }

        if ($status != null) {
            // If a status is forced and it is requested to be "confirmed" is like a single opt in
            // $status here can only be confirmed or not confirmed
            // TODO: Add a check on status values
            if ($status == Newsletter::STATUS_CONFIRMED) {
                $opt_in = self::OPTIN_SINGLE;
            } else {
                $opt_in = self::OPTIN_DOUBLE;
            }
        }

        $user = $this->get_user($email);


        if ($user != null) {
            // Email already registered in our database
            $this->logger->info('Subscription of an address with status ' . $user->status);

            // Bounced
            // TODO: Manage other cases when added
            if ($user->status == 'B') {
                // Non persistent status to decide which message to show (error)
                $user->status = 'E';
                return $user;
            }

            // Is there any relevant data change? If so we can proceed otherwise if repeated subscriptions are disabled
            // show an already subscribed message

            if (empty($this->options['multiple'])) {
                $user->status = 'E';
                return $user;
            }

            // If the subscriber is confirmed, we cannot change his data in double opt in mode, we need to
            // temporary store and wait for activation
            if ($user->status == Newsletter::STATUS_CONFIRMED && $opt_in == self::OPTIN_DOUBLE) {

                set_transient($this->get_user_key($user), $_REQUEST, 3600 * 48);

                // This status is *not* stored it indicate a temporary status to show the correct messages
                $user->status = 'S';

                $this->send_message('confirmation', $user);

                return $user;
            }
        }

        // Here we have a new subscription or we can process the subscription even with a pre-existant user for example
        // because it is not confirmed
        if ($user != null) {
            $this->logger->info("Email address subscribed but not confirmed");
            $user = array('id' => $user->id);
        } else {
            $this->logger->info("New email address");
            $user = array('email' => $email);
        }

        $user = $this->update_user_from_request($user);


        $user['token'] = $this->get_token();
        $ip = $this->process_ip($ip);
        $user['ip'] = $ip;
        $user['geo'] = 0;
        $user['status'] = $opt_in == self::OPTIN_SINGLE ? Newsletter::STATUS_CONFIRMED : Newsletter::STATUS_NOT_CONFIRMED;

        $user['updated'] = time();

        $user = apply_filters('newsletter_user_subscribe', $user);

        $user = $this->save_user($user);

        $this->add_user_log($user, 'subscribe');

        // Notification to admin (only for new confirmed subscriptions)
        if ($user->status == Newsletter::STATUS_CONFIRMED) {
            do_action('newsletter_user_confirmed', $user);
            $this->notify_admin_on_subscription($user);
            setcookie('newsletter', $user->id . '-' . $user->token, time() + 60 * 60 * 24 * 365, '/');
        }

        if ($emails) {
            $this->send_message(($user->status == Newsletter::STATUS_CONFIRMED) ? 'confirmed' : 'confirmation', $user);
        }

        $user = apply_filters('newsletter_user_post_subscribe', $user);

        return $user;
    }

    function add_microdata($message) {
        return $message . '<span itemscope itemtype="http://schema.org/EmailMessage"><span itemprop="description" content="Email address confirmation"></span><span itemprop="action" itemscope itemtype="http://schema.org/ConfirmAction"><meta itemprop="name" content="Confirm Subscription"><span itemprop="handler" itemscope itemtype="http://schema.org/HttpActionHandler"><meta itemprop="url" content="{subscription_confirm_url}"><link itemprop="method" href="http://schema.org/HttpRequestMethod/POST"></span></span></span>';
    }

    /**
     * Processes the request and fill in the *array* representing a subscriber with submitted values
     * (filtering when necessary).
     *
     * @param array $user An array partially filled with subscriber data
     * @return array The filled array representing a subscriber
     */
    function update_user_from_request($user) {

        if (isset($_REQUEST['nn'])) {
            $user['name'] = $this->normalize_name(stripslashes($_REQUEST['nn']));
        }
        // TODO: required checking

        if (isset($_REQUEST['ns'])) {
            $user['surname'] = $this->normalize_name(stripslashes($_REQUEST['ns']));
        }
        // TODO: required checking

        if (!empty($_REQUEST['nx'])) {
            $user['sex'] = $this->normalize_sex($_REQUEST['nx'][0]);
        }
        // TODO: valid values check

        if (isset($_REQUEST['nr'])) {
            $user['referrer'] = strip_tags(trim($_REQUEST['nr']));
        }

        $language = '';
        if (!empty($_REQUEST['nlang'])) {
            $language = strtolower(strip_tags($_REQUEST['nlang']));
            // TODO: Check if it's an allowed language code
            $user['language'] = $language;
        } else {
            $language = $this->get_current_language();
            $user['language'] = $language;
        }

        // From the antibot form
        if (isset($_REQUEST['nhr'])) {
            $user['http_referer'] = strip_tags(trim($_REQUEST['nhr']));
        } else if (isset($_SERVER['HTTP_REFERER'])) {
            $user['http_referer'] = strip_tags(trim($_SERVER['HTTP_REFERER']));
        }

        if (strlen($user['http_referer']) > 200) {
            $user['http_referer'] = mb_substr($user['http_referer'], 0, 200);
        }

        // New profiles
        for ($i = 1; $i <= NEWSLETTER_PROFILE_MAX; $i++) {
            // If the profile cannot be set by  subscriber, skip it.
            if ($this->options_profile['profile_' . $i . '_status'] == 0) {
                continue;
            }
            if (isset($_REQUEST['np' . $i])) {
                $user['profile_' . $i] = trim(stripslashes($_REQUEST['np' . $i]));
            }
        }

        // Extra validation to explain the administrator while the submitted data could
        // be interpreted only partially
        if (current_user_can('administrator')) {
            if (isset($_REQUEST['nl']) && is_array($_REQUEST['nl'])) {
                foreach ($_REQUEST['nl'] as $list_id) {
                    $list = $this->get_list($list_id);
                    if ($list && $list->status == TNP_List::STATUS_PRIVATE) {
                        $this->dienow('Invalid list', 'List ' . $list_id . ' has been submitted but it is set as private. Please fix the subscription form.');
                    }
                }
            }
        }

        // Preferences (field names are nl[] and values the list number so special forms with radio button can work)
        if (isset($_REQUEST['nl']) && is_array($_REQUEST['nl'])) {
            $lists = $this->get_lists_public();
            //$this->logger->debug($_REQUEST['nl']);
            foreach ($lists as $list) {
                if (in_array('' . $list->id, $_REQUEST['nl'])) {
                    $user['list_' . $list->id] = 1;
                }
            }
        } else {
            $this->logger->debug('No lists received');
        }

        // Forced lists (general or by language)
        $lists = $this->get_lists();
        foreach ($lists as $list) {
            if ($list->forced) {
                $user['list_' . $list->id] = 1;
            }
            if (in_array($language, $list->languages)) {
                $user['list_' . $list->id] = 1;
            }
        }

        // TODO: should be removed!!!
        if (defined('NEWSLETTER_FEED_VERSION')) {
            $options_feed = get_option('newsletter_feed', array());
            if ($options_feed['add_new'] == 1) {
                $user['feed'] = 1;
            }
        }
        return $user;
    }

    /**
     * Sends a service message applying the template.
     *
     * @param TNP_User $user
     * @param string $subject
     * @param string $message
     * @return type
     */
    function mail($user, $subject, $message) {
        $language = $this->get_user_language($user);

        $options_template = $this->get_options('template', $language);

        $template = trim($options_template['template']);
        if (empty($template) || strpos($template, '{message}') === false) {
            $template = '{message}';
        }
        $message = str_replace('{message}', $message, $template);

        //$headers = array('Auto-Submitted' => 'auto-generated');

        $headers = array();

        // Replaces tags from the template
        $message = $this->replace($message, $user);
        $subject = $this->replace($subject, $user);

        return Newsletter::instance()->mail($user->email, $subject, $message, $headers);
    }

    /**
     * Confirms a subscription changing the user status and, possibly, merging the
     * temporary data if present.
     *
     * @param int $user_id Optional. If null the user is extracted from the request.
     * @return TNP_User
     */
    function confirm($user_id = null, $emails = true) {

        if ($user_id == null) {
            $user = $this->get_user_from_request(true);
            // Is there any temporary data from a subscription to be confirmed?
            $data = get_transient($this->get_user_key($user));
            if ($data !== false) {
                $_REQUEST = $data;
                // Update the user profile since it's now confirmed
                $user = $this->update_user_from_request((array) $user);
                $user = $this->save_user($user);
                delete_transient($this->get_user_key($user));
                // Forced a fake status so the welcome email is sent
                $user->status = Newsletter::STATUS_NOT_CONFIRMED;
            }
        } else {
            $user = $this->get_user($user_id);
            if ($user == null) {
                die('No subscriber found.');
            }
        }

        $this->update_user_last_activity($user);

        setcookie('newsletter', $user->id . '-' . $user->token, time() + 60 * 60 * 24 * 365, '/');

        if ($user->status == TNP_User::STATUS_CONFIRMED) {
            $this->add_user_log($user, 'activate');
            do_action('newsletter_user_confirmed', $user);
            return $user;
        }

        $this->set_user_status($user, TNP_User::STATUS_CONFIRMED);

        $user = $this->get_user($user);

        $this->add_user_log($user, 'activate');

        do_action('newsletter_user_confirmed', $user);
        $this->notify_admin_on_subscription($user);

        if ($emails) {
            $this->send_message('confirmed', $user);
        }

        return $user;
    }

    /**
     * Sends a message (activation, welcome, cancellation, ...) with the correct template
     * and checking if the message itself is disabled
     *
     * @param string $type
     * @param TNP_User $user
     */
    function send_message($type, $user, $force = false) {
        if (!$force && !empty($this->options[$type . '_disabled'])) {
            return true;
        }

        $language = $this->get_user_language($user);

        $options = $this->get_options('', $language);
        $message = $options[$type . '_message'];
        if ($user->status == Newsletter::STATUS_NOT_CONFIRMED) {
            $message = $this->add_microdata($message);
        }
        $subject = $options[$type . '_subject'];

        return $this->mail($user, $subject, $message);
    }

    function is_double_optin() {
        return $this->options['noconfirmation'] == 0;
    }

    /**
     * Sends the activation email without conditions.
     *
     * @param stdClass $user
     * @return bool
     */
    function send_activation_email($user) {
        return $this->send_message('confirmation', $user, true);
    }

    /**
     * Finds the right way to show the message identified by $key (welcome, unsubscription, ...) redirecting the user to the
     * WordPress page or loading the configured url or activating the standard page.
     */
    function show_message($key, $user, $alert = '', $email = null) {
        $url = '';

        if (isset($_REQUEST['ncu'])) {
            // Custom URL from the form
            $url = $_REQUEST['ncu'];
        } else {
            // Per message custom URL from configuration (language variants could not be supported)
            $options = $this->get_options('', $this->get_user_language($user));
            if (!empty($options[$key . '_url'])) {
                $url = $options[$key . '_url'];
            }
        }

        $url = Newsletter::instance()->build_message_url($url, $key, $user, $email, $alert);
        wp_redirect($url);

        die();
    }

    function get_message_key_from_request() {
        if (empty($_GET['nm'])) {
            return 'subscription';
        }
        $key = $_GET['nm'];
        switch ($key) {
            case 's': return 'confirmation';
            case 'c': return 'confirmed';
            case 'u': return 'unsubscription';
            case 'uc': return 'unsubscribed';
            case 'p':
            case 'pe':
                return 'profile';
            default: return $key;
        }
    }

    var $privacy_url = false;

    /**
     * Generates the privacy URL and cache it.
     * 
     * @return string
     */
    function get_privacy_url() {
        if ($this->privacy_url === false) {
            $this->setup_form_options();
            if (!empty($this->form_options['privacy_use_wp_url']) && function_exists('get_privacy_policy_url')) {
                $this->privacy_url = get_privacy_policy_url();
            } else {
                $this->privacy_url = $this->form_options['privacy_url'];
            }
        }
        return $this->privacy_url;
    }

    function get_form_javascript() {
        $this->setup_form_options();

        $buffer = "\n\n";
        $buffer .= '<script type="text/javascript">' . "\n";
        $buffer .= '//<![CDATA[' . "\n";
        $buffer .= 'if (typeof newsletter_check !== "function") {' . "\n";
        $buffer .= 'window.newsletter_check = function (f) {' . "\n";
        $buffer .= '    var re = /^([a-zA-Z0-9_\.\-\+])+\@(([a-zA-Z0-9\-]{1,})+\.)+([a-zA-Z0-9]{2,})+$/;' . "\n";
        $buffer .= '    if (!re.test(f.elements["ne"].value)) {' . "\n";
        $buffer .= '        alert("' . addslashes($this->form_options['email_error']) . '");' . "\n";
        $buffer .= '        return false;' . "\n";
        $buffer .= '    }' . "\n";
        if ($this->form_options['name_status'] == 2 && $this->form_options['name_rules'] == 1) {
            $buffer .= '    if (f.elements["nn"] && (f.elements["nn"].value == "" || f.elements["nn"].value == f.elements["nn"].defaultValue)) {' . "\n";
            $buffer .= '        alert("' . addslashes($this->form_options['name_error']) . '");' . "\n";
            $buffer .= '        return false;' . "\n";
            $buffer .= '    }' . "\n";
        }
        if ($this->form_options['surname_status'] == 2 && $this->form_options['surname_rules'] == 1) {
            $buffer .= '    if (f.elements["ns"] && (f.elements["ns"].value == "" || f.elements["ns"].value == f.elements["ns"].defaultValue)) {' . "\n";
            $buffer .= '        alert("' . addslashes($this->form_options['surname_error']) . '");' . "\n";
            $buffer .= '        return false;' . "\n";
            $buffer .= '    }' . "\n";
        }
        $buffer .= '    for (var i=1; i<' . NEWSLETTER_PROFILE_MAX . '; i++) {' . "\n";
        $buffer .= '    if (f.elements["np" + i] && f.elements["np" + i].required && f.elements["np" + i].value == "") {' . "\n";
        $buffer .= '        alert("' . addslashes($this->form_options['profile_error']) . '");' . "\n";
        $buffer .= '        return false;' . "\n";
        $buffer .= '    }' . "\n";
        $buffer .= '    }' . "\n";

        $buffer .= '    if (f.elements["ny"] && !f.elements["ny"].checked) {' . "\n";
        $buffer .= '        alert("' . addslashes($this->form_options['privacy_error']) . '");' . "\n";
        $buffer .= '        return false;' . "\n";
        $buffer .= '    }' . "\n";
        $buffer .= '    return true;' . "\n";
        $buffer .= '}' . "\n";
        $buffer .= '}' . "\n";
        $buffer .= '//]]>' . "\n";
        $buffer .= '</script>' . "\n\n";
        return $buffer;
    }

    /**
     * Manages the custom forms made with [newsletter_form] and internal [newsletter_field] shorcodes.
     * 
     * @param array $attrs
     * @param string $content
     * @return string
     */
    function get_subscription_form_custom($attrs = [], $content = '') {
        if (!is_array($attrs)) {
            $attrs = [];
        }

        $this->setup_form_options();

        $attrs = array_merge(['class' => 'newsletter', 'style' => ''], $attrs);

        $action = esc_attr($this->build_action_url('s'));
        $class = esc_attr($attrs['class']);
        $style = esc_attr($attrs['style']);
        $buffer = '<form method="post" action="' . $action . '" class="' . $class . '" style="' . $style . '">' . "\n";

        $language = $this->get_current_language();

        $buffer .= '<input type="hidden" name="nlang" value="' . esc_attr($language) . '">' . "\n";

        if (isset($attrs['referrer'])) {
            $buffer .= '<input type="hidden" name="nr" value="' . esc_attr($attrs['referrer']) . '">' . "\n";
        }

        if (isset($attrs['optin'])) {
            $buffer .= $this->build_optin_field($attrs['optin']);
        }

        if (isset($attrs['confirmation_url'])) {
            if ($attrs['confirmation_url'] == '#') {
                $attrs['confirmation_url'] = $_SERVER['REQUEST_URI'];
            }
            $buffer .= "<input type='hidden' name='ncu' value='" . esc_attr($attrs['confirmation_url']) . "'>\n";
        }

        // Compatibility
        if (isset($attrs['list'])) {
            $attrs['lists'] = $attrs['list'];
        }

        if (isset($attrs['lists'])) {
            $arr = explode(',', $attrs['lists']);
            foreach ($arr as $a) {
                $buffer .= "<input type='hidden' name='nl[]' value='" . esc_attr(trim($a)) . "'>\n";
            }
        }

        $buffer .= do_shortcode($content);

        if (isset($attrs['button_label'])) {
            $label = $attrs['button_label'];
        } else {
            $label = $this->form_options['subscribe'];
        }

        if (!empty($label)) {
            $buffer .= '<div class="tnp-field tnp-field-button">';
            if (strpos($label, 'http') === 0) {
                $buffer .= '<input class="tnp-button-image" type="image" src="' . $label . '">';
            } else {
                $buffer .= '<input class="tnp-button" type="submit" value="' . $label . '">';
            }
            $buffer .= '</div>';
        }

        $buffer .= '</form>';

        return $buffer;
    }

    /**
     * Internal use only
     *
     * @param type $name
     * @param type $attrs
     * @param type $suffix
     * @return string
     */
    function _shortcode_label($name, $attrs, $suffix = null) {
        //$this->setup_form_options();

        if (!$suffix) {
            $suffix = $name;
        }
        $buffer = '<label for="tnp-' . $suffix . '">';
        if (isset($attrs['label'])) {
            if (empty($attrs['label'])) {
                return;
            } else {
                $buffer .= esc_html($attrs['label']);
            }
        } else {
            $buffer .= esc_html($this->form_options[$name]);
        }
        $buffer .= "</label>\n";
        return $buffer;
    }

    function build_field_admin_notice($message) {
        if (!current_user_can('administrator')) {
            return '';
        }
        return '<p style="background-color: #eee; color: #000; padding: 10px; margin: 10px 0">' . $message . ' <strong>This notice is shown only to administrators.</strong></p>';
    }

    function shortcode_newsletter_field($attrs, $content) {
        $this->setup_form_options();
        $language = $this->get_current_language();

        $name = $attrs['name'];

        $buffer = '';

        if ($name == 'email') {
            $buffer .= '<div class="tnp-field tnp-field-email">';
            $buffer .= $this->_shortcode_label('email', $attrs);

            $buffer .= '<input class="tnp-email" type="email" name="ne" value=""';
            if (isset($attrs['placeholder']))
                $buffer .= ' placeholder="' . esc_attr($attrs['placeholder']) . '"';
            $buffer .= ' required>';
            if (isset($attrs['button_label'])) {
                $label = $attrs['button_label'];
                if (strpos($label, 'http') === 0) {
                    $buffer .= ' <input class="tnp-submit-image" type="image" src="' . esc_attr(esc_url_raw($label)) . '">';
                } else {
                    $buffer .= ' <input class="tnp-submit" type="submit" value="' . esc_attr($label) . '" style="width: 29%">';
                }
            }
            $buffer .= "</div>\n";
            return $buffer;
        }

        if ($name == 'first_name' || $name == 'name') {
            $buffer .= '<div class="tnp-field tnp-field-firstname">';
            $buffer .= $this->_shortcode_label('name', $attrs);

            $buffer .= '<input class="tnp-name" type="text" name="nn" value=""';
            if (isset($attrs['placeholder'])) {
                $buffer .= ' placeholder="' . esc_attr($attrs['placeholder']) . '"';
            }
            if ($this->form_options['name_rules'] == 1) {
                $buffer .= ' required';
            }
            $buffer .= '>';
            $buffer .= "</div>\n";
            return $buffer;
        }

        if ($name == 'last_name' || $name == 'surname') {
            $buffer .= '<div class="tnp-field tnp-field-surname">';
            $buffer .= $this->_shortcode_label('surname', $attrs);

            $buffer .= '<input class="tnp-surname" type="text" name="ns" value=""';
            if (isset($attrs['placeholder'])) {
                $buffer .= ' placeholder="' . esc_attr($attrs['placeholder']) . '"';
            }
            if ($this->form_options['surname_rules'] == 1) {
                $buffer .= ' required';
            }
            $buffer .= '>';
            $buffer .= '</div>';
            return $buffer;
        }

        // Single list
        if ($name == 'preference' || $name == 'list') {
            if (!isset($attrs['number'])) {
                return $this->build_field_admin_notice('List number not specified.');
            }
            $number = (int) $attrs['number'];
            $list = $this->get_list($number, $language);
            if (!$list) {
                return $this->build_field_admin_notice('List ' . $number . ' is not configured, cannot be shown.');
            }

            if ($list->status == 0 || $list->forced) {
                return $this->build_field_admin_notice('List ' . $number . ' is private or enforced cannot be shown.');
            }

            if (isset($attrs['hidden'])) {
                return '<input type="hidden" name="nl[]" value="' . esc_attr($list->id) . '">';
            }

            $buffer .= '<div class="tnp-field tnp-field-checkbox tnp-field-list"><label for="nl' . esc_attr($list->id) . '">';
            $buffer .= '<input type="checkbox" id="nl' . esc_attr($list->id) . '" name="nl[]" value="' . esc_attr($list->id) . '"';
            if (isset($attrs['checked'])) {
                $buffer .= ' checked';
            }
            $buffer .= '>';
            if (isset($attrs['label'])) {
                if ($attrs['label'] != '')
                    $buffer .= '&nbsp;' . esc_html($attrs['label']) . '</label>';
            } else {
                $buffer .= '&nbsp;' . esc_html($list->name) . '</label>';
            }
            $buffer .= "</div>\n";

            return $buffer;
        }

        // All lists
        if ($name == 'lists' || $name == 'preferences') {
            $tmp = '';
            $lists = $this->get_lists_for_subscription($language);
            foreach ($lists as $list) {
                $tmp .= '<div class="tnp-field tnp-field-checkbox tnp-field-list"><label for="nl' . $list->id . '">';
                $tmp .= '<input type="checkbox" id="nl' . $list->id . '" name="nl[]" value="' . $list->id . '"';
                if ($list->checked) {
                    $tmp .= ' checked';
                }
                $tmp .= '>&nbsp;' . esc_html($list->name) . '</label>';
                $tmp .= "</div>\n";
            }
            return $tmp;
        }

        // TODO: add the "not specified"
        if ($name == 'sex' || $name == 'gender') {
            $buffer .= '<div class="tnp-field tnp-field-gender">';
            $buffer .= $this->_shortcode_label('sex', $attrs);

            $buffer .= '<select name="nx" class="tnp-gender" id="tnp-gender">';
            $buffer .= '<option value="m">' . esc_html($this->form_options['sex_male']) . '</option>';
            $buffer .= '<option value="f">' . esc_html($this->form_options['sex_female']) . '</option>';
            $buffer .= '</select>';
            $buffer .= "</div>\n";
            return $buffer;
        }

        if ($name == 'profile') {
            if (!isset($attrs['number'])) {
                return $this->build_field_admin_notice('Extra profile number not specified.');
            }

            $number = (int) $attrs['number'];

            $profile = TNP_Profile_Service::get_profile_by_id($number, $language);

            if (!$profile) {
                return $this->build_field_admin_notice('Extra profile ' . $number . ' is not configured, cannot be shown.');
            }

            if ($profile->status == 0) {
                return $this->build_field_admin_notice('Extra profile ' . $number . ' is private, cannot be shown.');
            }

            $size = isset($attrs['size']) ? $attrs['size'] : '';
            $buffer .= '<div class="tnp-field tnp-field-profile">';
            $buffer .= $this->_shortcode_label('profile_' . $profile->id, $attrs);

            $placeholder = isset($attrs['placeholder']) ? $attrs['placeholder'] : $profile->placeholder;

            // Text field
            if ($profile->type == TNP_Profile::TYPE_TEXT) {
                $buffer .= '<input class="tnp-profile tnp-profile-' . $number . '" id="tnp-profile_' . $number . '" type="text" size="' . esc_attr($size) . '" name="np' . $number . '" placeholder="' . esc_attr($placeholder) . '"';
                if ($profile->is_required()) {
                    $buffer .= ' required';
                }
                $buffer .= '>';
            }

            // Select field
            if ($profile->type == TNP_Profile::TYPE_SELECT) {
                $buffer .= '<select class="tnp-profile tnp-profile-' . $number . '" id="tnp-profile_' . $number . '" name="np' . $number . '"';
                if ($profile->is_required()) {
                    $buffer .= ' required';
                }
                $buffer .= '>';
                if (!empty($placeholder)) {
                    $buffer .= '<option value="" selected disabled>' . esc_html($placeholder) . '</option>';
                }
                foreach ($profile->options as $option) {
                    $buffer .= '<option>' . esc_html(trim($option)) . '</option>';
                }
                $buffer .= "</select>\n";
            }

            $buffer .= "</div>\n";

            return $buffer;
        }

        if (strpos($name, 'privacy') === 0) {
            if (!isset($attrs['url'])) {
                $attrs['url'] = $this->get_privacy_url();
            }

            if (!isset($attrs['label'])) {
                $attrs['label'] = $this->form_options['privacy'];
            }

            $buffer .= '<div class="tnp-field tnp-field-checkbox tnp-field-privacy">';

            $buffer .= '<input type="checkbox" name="ny" required class="tnp-privacy" id="tnp-privacy"> ';
            $buffer .= '<label for="tnp-privacy">';
            if (!empty($attrs['url'])) {
                $buffer .= '<a target="_blank" href="' . esc_attr($attrs['url']) . '">';
            }
            $buffer .= $attrs['label'];
            if (!empty($attrs['url'])) {
                $buffer .= '</a>';
            }
            $buffer .= '</label>';
            $buffer .= '</div>';

            return $buffer;
        }
    }

    /**
     * Returns the form html code for subscription.
     *
     * @return string The html code of the subscription form
     * @deprecated since version 6.6.0
     */
    function get_subscription_form_html5($referrer = null, $action = null, $attrs = array()) {
        return $this->get_subscription_form($referrer, $action, $attrs);
    }

    /**
     * Builds the privacy field only for completely generated forms.
     * 
     * @return string Empty id the privacy filed is not configured
     */
    function get_privacy_field($pre_html = '', $post_html = '') {
        $this->setup_form_options();
        $privacy_status = (int) $this->form_options['privacy_status'];
        if (empty($privacy_status)) {
            return '';
        }

        $buffer = '<label>';
        if ($privacy_status === 1) {
            $buffer .= '<input type="checkbox" name="ny" required class="tnp-privacy">&nbsp;';
        }
        $url = $this->get_privacy_url();
        if (!empty($url)) {
            $buffer .= '<a target="_blank" href="' . esc_attr($url) . '">';
            $buffer .= esc_attr($this->form_options['privacy']) . '</a>';
        } else {
            $buffer .= esc_html($this->form_options['privacy']);
        }

        $buffer .= "</label>";

        return $pre_html . $buffer . $post_html;
    }

    /**
     * Creates the hidden alternative optin field on custom form showing notices if used in the wrong
     * way.
     * 
     * @since 6.8.3
     * @param string $optin Could be single or double, lowercase
     * @return string The complete HTML field
     */
    function build_optin_field($optin) {
        if (empty($optin)) {
            return '';
        }

        if ($optin !== 'double' && $optin !== 'single') {
            return $this->build_field_admin_notice('The optin is set to an invalid value.');
        }

        if ($optin !== 'double' && $this->is_double_optin() && empty($this->options['optin_override'])) {
            return $this->build_field_admin_notice('The optin is specified but cannot be overridden (see the subscription configiraton page).');
        }

        $b = '<input type="hidden" name="optin" value="' . esc_attr($optin) . '">' . "\n";

        return $b;
    }

    /**
     * The new standard form.
     *
     * @param type $referrer
     * @param type $action
     * @param type $attrs
     * @return string
     */
    function get_subscription_form($referrer = null, $action = null, $attrs = array()) {
        $language = $this->get_current_language();
        $options_profile = $this->get_options('profile', $language);

        // Possible alternative form actions (used by...?)
        if (isset($attrs['action'])) {
            $action = $attrs['action'];
        }

        if (isset($attrs['referrer'])) {
            $referrer = $attrs['referrer'];
        }

        $buffer = '';



        if (empty($action)) {
            $action = $this->build_action_url('s');
        }

        if ($referrer != 'widget') {
            if (isset($attrs['class'])) {
                $buffer .= '<div class="tnp tnp-subscription ' . $attrs['class'] . '">' . "\n";
            } else {
                $buffer .= '<div class="tnp tnp-subscription">' . "\n";
            }
        }
        $buffer .= '<form method="post" action="' . esc_attr($action) . '" onsubmit="return newsletter_check(this)">' . "\n\n";

        $buffer .= '<input type="hidden" name="nlang" value="' . esc_attr($language) . '">' . "\n";

        if (!empty($attrs['optin'])) {
            $buffer .= $this->build_optin_field($attrs['optin']);
        }

        if (!empty($referrer)) {
            $buffer .= '<input type="hidden" name="nr" value="' . esc_attr($referrer) . '">' . "\n";
        }
        if (isset($attrs['confirmation_url'])) {
            $buffer .= "<input type='hidden' name='ncu' value='" . esc_attr($attrs['confirmation_url']) . "'>\n";
        }

        // Compatibility
        if (isset($attrs['list'])) {
            $attrs['lists'] = $attrs['list'];
        }

        // Hidden lists
        if (isset($attrs['lists'])) {
            $arr = explode(',', $attrs['lists']);
            foreach ($arr as $a) {
                $buffer .= "<input type='hidden' name='nl[]' value='" . ((int) trim($a)) . "'>\n";
            }
        }

        if ($options_profile['name_status'] == 2) {
            $buffer .= '<div class="tnp-field tnp-field-firstname"><label>' . esc_html($options_profile['name']) . '</label>';
            $buffer .= '<input class="tnp-firstname" type="text" name="nn" ' . ($options_profile['name_rules'] == 1 ? 'required' : '') . '></div>';
            $buffer .= "\n";
        }

        if ($options_profile['surname_status'] == 2) {
            $buffer .= '<div class="tnp-field tnp-field-lastname"><label>' . esc_html($options_profile['surname']) . '</label>';
            $buffer .= '<input class="tnp-lastname" type="text" name="ns" ' . ($options_profile['surname_rules'] == 1 ? 'required' : '') . '></div>';
            $buffer .= "\n";
        }

        $buffer .= '<div class="tnp-field tnp-field-email"><label>' . esc_html($options_profile['email']) . '</label>';
        $buffer .= '<input class="tnp-email" type="email" name="ne" required></div>';
        $buffer .= "\n";

        if (isset($options_profile['sex_status']) && $options_profile['sex_status'] == 2) {
            $buffer .= '<div class="tnp-field tnp-field-gender"><label>' . esc_html($options_profile['sex']) . '</label>';
            $buffer .= '<select name="nx" class="tnp-gender"';
            if ($options_profile['sex_rules'] == 1) {
                $buffer .= ' required><option value=""></option>';
            } else {
                $buffer .= '><option value="n">' . esc_html($options_profile['sex_none']) . '</option>';
            }
            $buffer .= '<option value="m">' . esc_html($options_profile['sex_male']) . '</option>';
            $buffer .= '<option value="f">' . esc_html($options_profile['sex_female']) . '</option>';
            $buffer .= '</select></div>';
            $buffer .= "\n";
        }

        $tmp = '';
        $lists = $this->get_lists_for_subscription($language);
        if (!empty($attrs['lists_field_layout']) && $attrs['lists_field_layout'] == 'dropdown') {
            foreach ($lists as $list) {

                $tmp .= '<option value="' . $list->id . '"';
                if ($list->checked) {
                    $tmp .= ' selected';
                }
                $tmp .= '>' . esc_html($list->name) . '</option>';
                $tmp .= "\n";
            }
            if (!empty($attrs['lists_field_empty_label'])) {
                $tmp = '<option value="">' . $attrs['lists_field_empty_label'] . '</option>' . $tmp;
            }
            if (!empty($tmp)) {
                $tmp = '<select class="tnp-lists" name="nl[]" required>' . $tmp . '</select>';
            }
            if (!empty($tmp)) {
                $buffer .= '<div class="tnp-field tnp-lists">';
                if (!empty($attrs['lists_field_label'])) {
                    $buffer .= '<label>' . $attrs['lists_field_label'] . '</label>';
                }
                $buffer .= $tmp . '</div>';
            }
        } else {

            foreach ($lists as $list) {

                $tmp .= '<div class="tnp-field tnp-field-list"><label><input class="tnp-preference" type="checkbox" name="nl[]" value="' . $list->id . '"';
                if ($list->checked) {
                    $tmp .= ' checked';
                }
                $tmp .= '/>&nbsp;' . esc_html($list->name) . '</label></div>';
            }
            if (!empty($tmp)) {
                $buffer .= '<div class="tnp-lists">';
                if (!empty($attrs['lists_field_label'])) {
                    $buffer .= '<label>' . $attrs['lists_field_label'] . '</label>';
                }
                $buffer .= $tmp . '</div>';
            }
        }

        // Extra profile fields
        for ($i = 1; $i <= NEWSLETTER_PROFILE_MAX; $i++) {
            // Not for subscription form
            if ($options_profile['profile_' . $i . '_status'] != 2) {
                continue;
            }


            $buffer .= '<div class="tnp-field tnp-field-profile"><label>' .
                    esc_html($options_profile['profile_' . $i]) . '</label>';

            // Text field
            if ($options_profile['profile_' . $i . '_type'] == 'text') {
                $buffer .= '<input class="tnp-profile tnp-profile-' . $i . '" type="text"' . ($options_profile['profile_' . $i . '_rules'] == 1 ? ' required' : '') . ' name="np' . $i . '">';
            }

            // Select field
            if ($options_profile['profile_' . $i . '_type'] == 'select') {
                $buffer .= '<select class="tnp-profile tnp-profile-' . $i . '" name="np' . $i . '" ' . ($options_profile['profile_' . $i . '_rules'] == 1 ? ' required' : '') . '>' . "\n";
                $buffer .= "<option></option>\n";
                $opts = explode(',', $options_profile['profile_' . $i . '_options']);
                for ($j = 0; $j < count($opts); $j++) {
                    $buffer .= "<option>" . esc_html(trim($opts[$j])) . "</option>\n";
                }
                $buffer .= "</select>\n";
            }
            $buffer .= '</div>';
        }

        $extra = apply_filters('newsletter_subscription_extra', array());
        foreach ($extra as $x) {
            $label = $x['label'];
            if (empty($label)) {
                $label = '&nbsp;';
            }
            $name = '';
            if (!empty($x['name'])) {
                $name = $x['name'];
            }
            $buffer .= '<div class="tnp-field tnp-field-' . $name . '"><label>' . $label . "</label>";
            $buffer .= $x['field'] . "</div>\n";
        }

        $buffer .= $this->get_privacy_field('<div class="tnp-field tnp-privacy-field">', '</div>');

        $buffer .= '<div class="tnp-field tnp-field-button">';

        $button_style = '';
        if (!empty($attrs['button_color'])) {
            $button_style = 'style="background-color:' . esc_attr($attrs['button_color']) . '"';
        }

        if (strpos($options_profile['subscribe'], 'http') === 0) {
            $buffer .= '<input class="tnp-submit-image" type="image" src="' . esc_attr($options_profile['subscribe']) . '">' . "\n";
        } else {
            $buffer .= '<input class="tnp-submit" type="submit" value="' . esc_attr($options_profile['subscribe']) . '" ' . $button_style . '>' . "\n";
        }

        $buffer .= "</div>\n</form>\n";
        if ($referrer != 'widget') {
            $buffer .= "</div>\n";
        }
        return $buffer;
    }

    function get_profile_form($user) {
        return NewsletterProfile::instance()->get_profile_form($user);
    }

    function get_form($number) {
        $options = get_option('newsletter_forms');

        $form = $options['form_' . $number];

        $form = do_shortcode($form);

        $action = $this->build_action_url('s');

        if (stripos($form, '<form') === false) {
            $form = '<form method="post" action="' . $action . '">' . $form . '</form>';
        }

        // For compatibility
        $form = str_replace('{newsletter_url}', $action, $form);

        $form = $this->replace_lists($form);

        return $form;
    }

    /** Replaces on passed text the special tag {lists} that can be used to show the preferences as a list of checkbox.
     * They are called lists but on configuration panel they are named preferences!
     *
     * @param string $buffer
     * @return string
     */
    function replace_lists($buffer) {
        $checkboxes = '';
        $lists = $this->get_lists_for_subscription($this->get_current_language());
        foreach ($lists as $list) {
            $checkboxes .= '<input type="checkbox" name="nl[]" value="' . $list->id . '"/>&nbsp;' . $list->name . '<br />';
        }
        $buffer = str_replace('{lists}', $checkboxes, $buffer);
        $buffer = str_replace('{preferences}', $checkboxes, $buffer);
        return $buffer;
    }

    function notify_admin_on_subscription($user) {

        if (empty($this->options['notify'])) {
            return;
        }

        $message = $this->generate_admin_notification_message($user);
        $email = trim($this->options['notify_email']);
        $subject = $this->generate_admin_notification_subject('Newsletter subscription');

        Newsletter::instance()->mail($email, $subject, array('html' => $message));
    }

    function get_subscription_form_minimal($attrs) {

        $language = $this->get_current_language();
        $this->setup_form_options();

        if (!is_array($attrs)) {
            $attrs = [];
        }

        $attrs = array_merge(array('class' => '', 'referrer' => 'minimal',
            'button' => $this->form_options['subscribe'], 'button_color' => '',
            'button_radius' => '', 'placeholder' => $this->form_options['email']), $attrs);

        $form = '';


        $form .= '<div class="tnp tnp-subscription-minimal ' . $attrs['class'] . '">';
        $form .= '<form action="' . esc_attr($this->build_action_url('s')) . '" method="post">';

        if (isset($attrs['optin'])) {
            $form .= $this->build_optin_field($attrs['optin']);
        }
        
        if (isset($attrs['confirmation_url'])) {
            $form .= "<input type='hidden' name='ncu' value='" . esc_attr($attrs['confirmation_url']) . "'>\n";
        }        

        if (isset($attrs['lists'])) {
            $arr = explode(',', $attrs['lists']);
            foreach ($arr as $a) {
                $form .= "<input type='hidden' name='nl[]' value='" . ((int) trim($a)) . "'>\n";
            }
        }
        $form .= '<input type="hidden" name="nr" value="' . esc_attr($attrs['referrer']) . '">';
        $form .= '<input type="hidden" name="nlang" value="' . esc_attr($language) . '">' . "\n";
        $form .= '<input class="tnp-email" type="email" required name="ne" value="" placeholder="' . esc_attr($attrs['placeholder']) . '">';
        $form .= '<input class="tnp-submit" type="submit" value="' . esc_attr($attrs['button']) . '"'
                . ' style="background-color:' . esc_attr($attrs['button_color']) . '">';

        $form .= $this->get_privacy_field('<div class="tnp_field tnp-privacy-field">', '</div>');

        $form .= "</form></div>\n";

        return $form;
    }

    function shortcode_newsletter_form($attrs, $content) {

        if (isset($attrs['type']) && $attrs['type'] == 'minimal') {
            return $this->get_subscription_form_minimal($attrs);
        }

        // Custom form using the [newsletter_field] shortcodes
        if (!empty($content)) {
            return $this->get_subscription_form_custom($attrs, $content);
        }

        // Custom form hand coded and saved in the custom forms option
        if (isset($attrs['form'])) {
            return $this->get_form((int) $attrs['form']);
        }

        // Custom hand coded form (as above, new syntax)
        if (isset($attrs['number'])) {
            return $this->get_form((int) $attrs['number']);
        }

        return $this->get_subscription_form(null, null, $attrs);
    }

    /**
     *
     * @global wpdb $wpdb
     * @param array $attrs
     * @param string $content
     * @return string
     */
    function shortcode_newsletter($attrs, $content) {
        global $wpdb;

        $message_key = $this->get_message_key_from_request();
        if ($message_key == 'confirmation') {
            $user = $this->get_user_from_request(false, 'preconfirm');
        } else {
            $user = $this->get_user_from_request();
        }

        $message = apply_filters('newsletter_page_text', '', $message_key, $user);

        $options = $this->get_options('', $this->get_current_language($user));

        if (empty($message)) {
            $message = $options[$message_key . '_text'];

            // TODO: the if can be removed
            if ($message_key == 'confirmed') {
                $message .= $options[$message_key . '_tracking'];
            }
        }


        // Now check what form must be added
        if ($message_key == 'subscription') {

            // Compatibility check
            if (stripos($message, '<form') !== false) {
                $message .= $this->get_form_javascript();
                $message = str_ireplace('<form', '<form method="post" action="' . esc_attr($this->get_subscribe_url()) . '" onsubmit="return newsletter_check(this)"', $message);
            } else {

                if (strpos($message, '{subscription_form') === false) {
                    $message .= '{subscription_form}';
                }

                if (isset($attrs['form'])) {
                    $message = str_replace('{subscription_form}', $this->get_form($attrs['form']), $message);
                } else {
                    $message = str_replace('{subscription_form}', $this->get_subscription_form('page', null, $attrs), $message);
                }
            }
        }

        $email = $this->get_email_from_request();

        $message = $this->replace($message, $user, $email, 'page');

        $message = do_shortcode($message);

        if (isset($_REQUEST['alert'])) {
            // slashes are already added by wordpress!
            $message .= '<script>alert("' . esc_js(strip_tags($_REQUEST['alert'])) . '");</script>';
        }

        return $message;
    }

}

NewsletterSubscription::instance();

// Compatibility code

/**
 * @deprecated 
 * @param int $number
 */
function newsletter_form($number = null) {
    if ($number != null) {
        echo NewsletterSubscription::instance()->get_form($number);
    } else {
        echo NewsletterSubscription::instance()->get_subscription_form();
    }
}