<?php

/*
Plugin Name: WPSA email2list addon
Plugin URI: http://wpsalesautomator.com/
Description: WP SalesAutomator addon to add functionality of a autoresponder mailing lists.
Version: 0.3
Author: wordpressLAB
*/

/*
Copyright 2010 Neil Harvey - nineMarketing.com
*/

require_once(dirname(__FILE__).'/'. 'email2list_admin.php');

/**************************************************************
    PLUGIN ACTIVATION HOOK
**************************************************************/
register_activation_hook(__FILE__, 'wpsa_el_activate');

function wpsa_el_activate() {
    global $wpdb;

    $wpsa_el_log = $wpdb->prefix . 'wpsa_el_log' ;
//    $new_installation = $wpdb->get_var("show tables like '$wpsa_el_log'" ) ;
    if($wpdb->get_var("show tables like '$wpsa_el_log'") != $wpsa_el_log) {
//    if ( !$new_installation ) {
        $qry = "CREATE TABLE $wpsa_el_log (
                  `id` int(11) NOT NULL auto_increment,
                  `user_id` int(11) NOT NULL ,
                  `user_name` varchar(200) NOT NULL,
                   `send_subsc_mail`  ENUM( 'yes', 'no' ) NOT NULL DEFAULT 'no',
                  PRIMARY KEY  (id)
                );";
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        dbDelta($qry);
    }
}

/**************************************************************
    PLUGIN UNINSTALL HOOK
**************************************************************/
register_uninstall_hook(__FILE__, 'wpsa_el_deactivate');

function wpsa_el_deactivate() {
    global $wpdb;
    $wp_sa_setting = get_option('wp_sa_setting');

    if ( $wp_sa_setting['wp_sa_keep_data'] != 1) {
        $result = $wpdb->query("DROP TABLE IF EXISTS {$wpdb->prefix}wpsa_el_log");
    }
}

//get email 2 list setting
$e2l_settings = get_option('e2l_settings');
/**************************************************************
    ADD CEKCBOX TO REGISTRATION FORM
**************************************************************/
add_action('register_form', 'wpsa_el_add_registration_form', 10, 0);

function wpsa_el_add_registration_form() {
    global $e2l_settings;
    $userm = new WP_User($id);
    //print_r($userm );
    
    ?>
    <style type="text/css">
        #user_fname, #user_lname{background:#FBFBFB none repeat scroll 0 0;border:1px solid #E5E5E5;font-size:24px;margin:2px 6px 16px 0;padding:3px;width:97%;}
    </style>
    <?php

    if($e2l_settings['e2l_fname'] == 'checked') {

    ?>
    <p>
        <label>First Name<br>
            <input type="text" tabindex="21" size="25" value="<?php if(trim($_POST['user_fname'])!='') echo trim($_POST['user_fname']);?>" class="input" id="user_fname" name="user_fname">
        </label>
    </p>
     <?php
     
    }
    if($e2l_settings['e2l_lname'] == 'checked') {
    ?>
    <p>
        <label>Last Name<br>
            <input type="text" tabindex="22" size="25" value="<?php if(trim($_POST['user_lname'])!='') echo trim($_POST['user_lname']);?>" class="input" id="user_lname" name="user_lname">
        </label>
    </p>
    
    <?php
    }
    if($e2l_settings['e2l_subscribe_message_show'] == 'checked') {
    ?>
    
    <p>
    <table cellpadding="0" cellspacing="0" style="background-color: #f8f8f8; border-top: 1px solid #bbbbbb; border-bottom: 1px solid #bbbbbb">
        <tr>
            <td width="15px" valign="top" nowrap style="padding: 3px 3px 0 0;"><input type="checkbox" name="e2l_opt_in" id="e2l_opt_in" class="input" value="checked" <?php if(!isset($_POST["e2l_opt_in"]) || ( isset($_POST["e2l_opt_in"]) && $_POST["e2l_opt_in"] != "" )) {
            echo("checked=\"checked\"");
        } ?> tabindex="99"/></td>
            <td width="95%" valign="top" style="padding: 3px 0 3px 0;"><?php echo stripslashes(get_option('e2l_subscribe_message')); ?></td>
        </tr>
    </table>
    </p>
    <br class="clear" />
    <?php
    }
}

/**************************************************************
    SAVE CEKCBOX OF REGISTRATION FORM
**************************************************************/
add_action('register_post', 'wpsa_el_add_check_member_op', 10, 3);

function wpsa_el_add_check_member_op($login, $email, $errors) {
    global $wpdb, $e2l_settings;
    
    if( isset($e2l_settings['e2l_fname_required']) && isset($e2l_settings['e2l_fname']) && trim($_POST['user_fname'])==''){
        $errors->add('fname_error',__('<b>ERROR</b>: Please enter a first name'));
    }

    if( isset($e2l_settings['e2l_lname_required']) && isset($e2l_settings['e2l_lname']) && trim($_POST['user_lname'])==''){
        $errors->add('lname_error',__('<b>ERROR</b>: Please enter a last name'));
    }
    
    $send_mail = 'no';
    if(isset($_POST["e2l_opt_in"]) && $_POST["e2l_opt_in"] == "checked") {
        $send_mail = 'yes';
    }

    $result = $wpdb->query("INSERT INTO {$wpdb->prefix}wpsa_el_log(user_name, send_subsc_mail) VALUES('$login', '$send_mail')");
}

/**************************************************************
    Registration Process Hooks
**************************************************************/
add_action('user_register', 'e2l_subscribe');

function e2l_subscribe($id) {        
    global $wpdb, $user;
    $user = $wpdb->get_row("SELECT * FROM $wpdb->users WHERE ID = $id");
    //update user_id in wpsa_el_log
    $wpdb->query("UPDATE {$wpdb->prefix}wpsa_el_log SET user_id = $id  WHERE user_name = '".$wpdb->escape($user->user_login)."'");
    if( isset($_POST['user_fname']) ) update_usermeta($id, 'first_name', trim($_POST['user_fname']));
    if( isset($_POST['user_lname']) ) update_usermeta($id, 'last_name', trim($_POST['user_lname']));
}

/**************************************************************
    Add user to mailing list
**************************************************************/
//if new (non-logged in ) user subscribe
add_action('wpsa_add_suscr_log', 'e2l_add_user_to_subsc_list', 10, 2);
//if logged in user subscribe
add_action('wpsa_subscr_signup', 'e2l_add_user_to_subsc_list', 10, 2);
//when admin adds users from backend through subscription log
add_action('wpsa_suscr_add_log', 'e2l_add_user_to_subsc_list', 10, 2);

function e2l_add_user_to_subsc_list($user_id, $subsc_id) {
    if (!function_exists('wpsa_install')) return;
    global $wpdb, $user;

    $userm = new WP_User($user_id);
    $user = $wpdb->get_row("SELECT * FROM ". $wpdb->prefix. "users WHERE ID = $user_id");

    // Exit if Email2List Info is Absent
    $e2l_mailing_list_service = get_option("e2l_mailing_list_service");
    $e2l_settings = get_option("e2l_settings");
    
    if($e2l_mailing_list_service == "" || $e2l_mailing_list_service === false) return;
    if($e2l_settings == "" || $e2l_settings === false) return;

    //get all subscription of user
    $sql = "SELECT item_number FROM ". $wpdb->prefix. "wpsa_subscription_transaction WHERE user_ID = $user_id and subscr_status = 'active' and subscriber_id = '" .$subsc_id. "'";
    $subscription = $wpdb->get_row($sql);

    // Get wpsa-el setting
    $e2l_settings = get_option('e2l_settings');

    // $list_nbr = e2l_get_list_nbr($e2l_settings, $id);

    if($e2l_mailing_list_service == 'AWEBER') {
            //get list and form id, associated with subscription (each subsc associated with a list saved in option table)
            $list = $e2l_settings['e2l_list_name']['AWEBER'][$subscription->item_number];
            $form_id = $e2l_settings['e2l_list_form']['AWEBER'][$subscription->item_number];

            $params = array(
              "meta_web_form_id" =>$form_id,
              "meta_split_id" => "",
              "listname" => $list,
              "redirect" => "http://www.aweber.com/form/thankyou_vo.html",
              "meta_redirect_onlist" => "",
              "meta_adtracking" => "",
              "meta_message" => "1",
              "meta_required" => "name,from",
              "meta_forward_vars" => "0",
              //"name" => ( strlen(trim($userm->user_firstname)) > 0 ? trim($userm->user_firstname) . ' ' . trim($userm->user_lastname) : $user->user_nicename ),
                "name" => ( strlen(trim($userm->first_name)) > 0 ? trim($userm->first_name) . ' ' . trim($userm->last_name) : $user->user_nicename ),
              "from" => $user->user_email,
              "submit" => "Submit"
            );
            
            $r = _post('http://www.aweber.com/scripts/addlead.pl', $params);
    }
    else if($e2l_mailing_list_service == 'GETRESPONSE') {

            //get list and , associated with subscription (each subsc associated with a list saved in option table)
            $list = $e2l_settings['e2l_list_name']['GETRESPONSE'][$subscription->item_number];

            $params = array(
              //"subscriber_name" => ( strlen(trim($userm->user_firstname)) > 0 ? trim($userm->user_firstname) . ' ' . trim($userm->user_lastname) : $user->user_nicename ),
              "subscriber_name" => ( strlen(trim($userm->first_name)) > 0 ? trim($userm->first_name) . ' ' . trim($userm->last_name) : $user->user_nicename ),
              "subscriber_email" => $user->user_email,
              "confirmation_url" => "",
              "campaign_name" => $list,
              "custom_ref" => ""
            );
            $r = _post('http://www.getresponse.com/cgi-bin/add.cgi', $params);
        
    }
    else if($e2l_mailing_list_service == 'GENERIC') {

            //get list and , associated with subscription (each subsc associated with a list saved in option table)
            $list = $e2l_settings['e2l_list_name']['GENERIC'][$subscription->item_number];

            $headers  = 'Reply-To: ' . $user->user_email . "\r\n";
            //$headers .= "From: " . ( strlen(trim($userm->user_firstname)) > 0 ? trim($userm->user_firstname) . ' ' . trim($userm->user_lastname) : $user->user_nicename ) . " <{$user->user_email}>\r\n";
            $headers .= "From: " . ( strlen(trim($userm->first_name)) > 0 ? trim($userm->first-name) . ' ' . trim($userm->last_name) : $user->user_nicename ) . " <{$user->user_email}>\r\n";
            //need to test it
            wp_mail( $list, 'Subscribe', '', $headers );
        }
}

/**************************************************************
    AFTER REGISTRATION ADD USER TO FREE SUBSCRIPTION
**************************************************************/
add_action('user_register', 'wpsa_el_add_user_to_free_subsc_list', 20, 3);

function wpsa_el_add_user_to_free_subsc_list($id) {
    if (!function_exists('wpsa_install')) return;
    global $wpdb, $user;

    $userm = new WP_User($id);
    //print_r($userm);exit;
    $user = $wpdb->get_row("SELECT * FROM ". $wpdb->prefix. "users WHERE ID = $id");

    // Exit if Email2List Info is Absent
    $e2l_mailing_list_service = get_option("e2l_mailing_list_service");
    $e2l_settings = get_option("e2l_settings");

    if($e2l_mailing_list_service == "" || $e2l_mailing_list_service === false) return;
    if($e2l_settings == "" || $e2l_settings === false) return;

    if($e2l_mailing_list_service == 'AWEBER') {
            //get list and form id, associated with subscription (each subsc associated with a list saved in option table)
            $list = $e2l_settings['e2l_list_name']['AWEBER']['free'];
            $form_id = $e2l_settings['e2l_list_form']['AWEBER']['free'];

            $params = array(
              "meta_web_form_id" =>$form_id,
              "meta_split_id" => "",
              "listname" => $list,
              "redirect" => "http://www.aweber.com/form/thankyou_vo.html",
              "meta_redirect_onlist" => "",
              "meta_adtracking" => "",
              "meta_message" => "1",
              "meta_required" => "name,from",
              "meta_forward_vars" => "0",
              //"name" => ( strlen(trim($userm->user_firstname)) > 0 ? trim($userm->user_firstname) . ' ' . trim($userm->user_lastname) : $user->user_nicename ),
                "name" => ( strlen(trim($userm->first_name)) > 0 ? trim($userm->first_name) . ' ' . trim($userm->last_name) : $user->user_nicename ),
              "from" => $user->user_email,
              "submit" => "Submit"
            );

            $r = _post('http://www.aweber.com/scripts/addlead.pl', $params);
    }
    else if($e2l_mailing_list_service == 'GETRESPONSE') {

            //get list and , associated with subscription (each subsc associated with a list saved in option table)
            $list = $e2l_settings['e2l_list_name']['GETRESPONSE']['free'];

            $params = array(
              //"subscriber_name" => ( strlen(trim($userm->user_firstname)) > 0 ? trim($userm->user_firstname) . ' ' . trim($userm->user_lastname) : $user->user_nicename ),
              "subscriber_name" => ( strlen(trim($userm->first_name)) > 0 ? trim($userm->first_name) . ' ' . trim($userm->last_name) : $user->user_nicename ),
              "subscriber_email" => $user->user_email,
              "confirmation_url" => "",
              "campaign_name" => $list,
              "custom_ref" => ""
            );
            $r = _post('http://www.getresponse.com/cgi-bin/add.cgi', $params);

    }
    else if($e2l_mailing_list_service == 'GENERIC') {

            //get list and , associated with subscription (each subsc associated with a list saved in option table)
            $list = $e2l_settings['e2l_list_name']['GENERIC']['free'];

            $headers  = 'Reply-To: ' . $user->user_email . "\r\n";
            //$headers .= "From: " . ( strlen(trim($userm->user_firstname)) > 0 ? trim($userm->user_firstname) . ' ' . trim($userm->user_lastname) : $user->user_nicename ) . " <{$user->user_email}>\r\n";
            $headers .= "From: " . ( strlen(trim($userm->first_name)) > 0 ? trim($userm->first-name) . ' ' . trim($userm->last_name) : $user->user_nicename ) . " <{$user->user_email}>\r\n";
            //need to test it
            wp_mail( $list, 'Subscribe', '', $headers );
        }
}
/**************************************************************
    Post Registration Method
**************************************************************/
/*
function _post($url, $fields) {
    $postfields = array();
    if(count($fields)) {
        foreach($fields as $i => $f) {
            $postfields[] = urlencode($i) . '=' . urlencode($f);
        }
    }
    $fields = implode('&', $postfields);

    preg_match('~http://([^/]+)(/.*)~', $url, $subs);
    $host = $subs[1];
    $uri = $subs[2];
    $header .= "POST $uri HTTP/1.1\r\n";
    $header .= "Host: $host\r\n";
    $header .= "Content-Type: application/x-www-form-urlencoded\r\n";
    $header .= "Content-Length: " . strlen($fields) . "\r\n\r\n";
    $fp = fsockopen ($host, 80, $errno, $errstr, 30);
    if($fp) {
        fputs($fp, $header . $fields);
        $result = '';
        while(!feof($fp)) $result .= fgets($fp, 4096);
    }
    fclose($fp);
    return $result;
}
*/

function _post($url, $fields) {

        foreach($fields as $name => $value) {
          $encoded .= urlencode($name).'='.urlencode($value).'&';
        }
        $channel = curl_init( );
        // you might want the headers for http codes
        curl_setopt( $channel, CURLOPT_HEADER, true );
        // you may need to set the http useragent for curl to operate as
        curl_setopt( $channel, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
        // you wanna follow stuff like meta and location headers
        curl_setopt( $channel, CURLOPT_FOLLOWLOCATION, true );
        // you want all the data back to test it for errors
        curl_setopt( $channel, CURLOPT_RETURNTRANSFER, true );


        // setup the url to post / get from / to
        curl_setopt( $channel, CURLOPT_URL, $url);
        // the actual post bit

        curl_setopt( $channel, CURLOPT_POST, true );
        curl_setopt( $channel, CURLOPT_POSTFIELDS, $encoded  );

        // return data
        curl_exec( $channel );
        curl_close($channel);
}



/**************************************************************
    Delete User
**************************************************************/
add_action('delete_user', 'r21_delete_user');

function r21_delete_user($id) {
    global $wpdb;
    $wpdb->query("DELETE FROM {$wpdb->prefix}wpsa_el_log WHERE user_id = $id");
}
?>