<?php
// -------------------------------------------------------//
// Misc Support/Required Functions for the plugin to work //
// -------------------------------------------------------//
// checking validity - run this code snippet and return 1 or 0 //
// NOT implemented yet //
function subm_register() {
  $url="http://subscriptionmate.com/subm_registrations.php";
  $lic = getcontent($url);
  if($lic == "1") {   // valid, do nothing.
    $subm_softlic = 1;    
  } else {
    $subm_softlic = 0; // invalid, refunded/revoked.
    $q="UPDATE wp_options SET option_value='0' WHERE option_name='subm_enabled' LIMIT 1";
    $wpdb->query($q);
  }
}

// Custom/Membership Roles //
// ------------------------//
function subm_add_roles() {  
  $subscriber = get_role('subscriber');
  $caps = $subscriber->capabilities;
  $subm_mbrs = get_option('subm_members_option');
  $level1 = $subm_mbr_arr[level1];
  $level2 = $subm_mbr_arr[level2];
  $level3 = $subm_mbr_arr[level3];
  $level4 = $subm_mbr_arr[level4];
  $level5 = $subm_mbr_arr[level5];
  add_role('subm_level5', 'Platinum Member', array(
            'read' => 1,
            'level_0' => 1,
            'read_private_pages' => 1,
            'read_private_posts' => 1,
            'subm_members' => 1,
            'read_level1' => 1,
            'read_level2' => 1,
            'read_level3' => 1,
            'read_level4' => 1,
            'read_level5' => 1
            )
          );
    add_role('subm_level4', 'Gold Member', array(
            'read' => 1,
            'level_0' => 1,
            'read_private_pages' => 1,
            'read_private_posts' => 1,
            'subm_members' => 1,
            'read_level1' => 1,
            'read_level2' => 1,
            'read_level3' => 1,
            'read_level4' => 1
            )
          );
    add_role('subm_level3', 'Silver Member', array(
            'read' => 1,
            'level_0' => 1,
            'read_private_pages' => 1,
            'read_private_posts' => 1,
            'subm_members' => 1,            
            'read_level1' => 1,
            'read_level2' => 1,
            'read_level3' => 1
            )
          );
    add_role('subm_level2', 'Bronze Member', array(
            'read' => 1,
            'level_0' => 1,
            'read_private_pages' => 1,
            'read_private_posts' => 1,
            'subm_members' => 1,            
            'read_level1' => 1,
            'read_level2' => 1
            )
          );
    add_role('subm_level1', 'Basic Member', array(
            'read' => 1,'level_0' => 1,
            'read_private_pages' => 1,
            'read_private_posts' => 1,
            'subm_members' => 1,            
            'read_level1' => 1
            )
          );
}
// --------------------------------------//
// remove Roles IF plugin is deactivated //
// --------------------------------------//
function subm_deactivate() {  
  remove_role('subm_level1');
  remove_role('subm_level2');
  remove_role('subm_level3');
  remove_role('subm_level4');
  remove_role('subm_level5');
  // need to remove the custom table "CBPress" ? 
  
}

// create custom users table - when plugin is 1st activated//
// --------------------------------------------------------//
function subm_activate() {
  // currently not used in the script //  
  global $wpdb;
  $q="CREATE table IF NOT EXISTS cbpress (
  cID int(11) NOT NULL auto_increment,
  wpID int(11),
  cName char(50) default NULL,
  cEmail char(100) default NULL,
  cbreceipt char(16),
  pid  char(15) default NULL,
  status char(1) default NULL,
  country char(20) default NULL,
  state  char(30) default NULL,
  date date,
  cancel date,
  num_rebil int,
  tid char(20),
  PRIMARY KEY (cID),
  INDEX cEmail_idx (cEmail),
  INDEX rcpt_idx (cbreceipt)
 )";
// $wpdb->query($q); 
 // set 'subm_enabled' to 1
 $q="INSERT INTO wp_options (option_name,option_value) VALUES ('subm_enabled','1')";
 //$wpdb->query($q);
}

// --------- Redirect Member upon login ---------------- //
function redirect_after_login($redirect_to, $request, $user) {
  $ID = $user->ID; $name = $user->display_name;
  if($ID!='')  {
    $user_cap = get_user_meta($ID, 'wp_capabilities', false);
    $subm_mbrs = get_option('subm_members_option');
    //echo "CAP: ". $user_cap[0][subm_level5] . "URL: $url<hr>";
    if($user_cap[0][subm_level5]) { $redirect_to = $subm_mbrs[welcome5];}
    if($user_cap[0][subm_level4]) { $redirect_to = $subm_mbrs[welcome4];}
    if($user_cap[0][subm_level3]) { $redirect_to = $subm_mbrs[welcome3];}
    if($user_cap[0][subm_level2]) { $redirect_to = $subm_mbrs[welcome2];}
    if($user_cap[0][subm_level1]) { $redirect_to = $subm_mbrs[welcome1];}
    // if USER IS ADMIN, do nothing - send to dashboard => admin_url();! 
    if($user_cap[0][administrator]) { $redirect_to = admin_url(); }
       
  } else {   
      $redirect_to = get_option('siteurl'); 
  }
  return $redirect_to;  
}

// ---------- hide priv. posts from the Loop -------------//
$subm_tags = array('level1','level2','level3','level4','level5');
function subm_exclude_tags( $query ) {
    // if ( $query->is_home && !current_user_can('manage_options')) {
    if ( $query->is_home && !is_user_logged_in()) {
          $tags  = subm_get_tags_ids();
          $query->set( 'tag__not_in', $tags );
    }
}
function subm_get_tags_ids(){
  $temp = array();
  global $subm_tags;
  $tags = array_map('trim',$subm_tags);
  $tags = array_map('strtolower',$subm_tags);
  $posttags = get_tags();

  if ($posttags):
  foreach ($posttags as $tag){
    if (in_array($tag->name,$tags))
        $temp[] = $tag->term_id;
  }
  endif;
  return $temp;
}


// ---------- Welcome Mesg ------------//
function subm_welcome_page() {
  if( is_user_logged_in() ) {
    $user = wp_get_current_user();
    $name = $user->display_name;    $ID = $user->ID;
    $subm_mbrs = get_option('subm_members_option');
    if( current_user_can('subm_level5') ) { $msg = "Platinum Member - $subm_mbrs[welcome5]"; }
    if( current_user_can('subm_level4') ) { $msg = "Gold Member"; }
    if( current_user_can('subm_level3') ) { $msg = "Silver Member"; }
    if( current_user_can('subm_level2') ) { $msg = "Bronze Member"; }
    if( current_user_can('subm_level1') ) { $msg = "Basic Member"; }
    echo "Hello $name ($ID - $msg), welcome!";
  } else {     echo "You're not logged in ...";   }
}


// ---------------------------//
//  (#3) subm_metabox_init(); //
// -------------------------//
function subm_metabox_init() { // create our custom meta box, displayed on the 'post' page.
   //add_action('add_meta_boxes', 'subm_metabox');
   add_meta_box('subm-meta','SubscriptionMate Drip Content', 'subm_metabox','post','side','high'); 
   // added 7 Jun 2012 for 'Pages'
   add_meta_box('subm-meta2','SubscriptionMate Drip Content', 'subm_metabox','page','side','high'); 
   // hook to save our meta box data when the post is saved
   add_action('save_post','subm_metabox_save'); 
}

// -----------------------------//
// (#3b) function subm_metabox() //
// -----------------------------//
function subm_metabox($post) {
    // retrieve our custom meta box values
    $subm_days = get_post_meta($post->ID,'_subm_days',true);
    echo '<p>' .__('Delay num. of days','subm-plugin'). ': 
    <input type="text" name="subm_days" value="'.esc_attr($subm_days).'" size="5">
    </p>';
}

// ---------------------------//
//  (#4) subm_metabox_save(); //
// -------------------------//
function subm_metabox_save($post_id) {
    if($post->post_type == 'revision') { return; } // if post is revision, skip.    
    // process form data if $_POST is set
    if(isset($_POST['subm_days'])) {
        // save the meta box data as post meta using the post ID as a unique prefix
        update_post_meta($post_id,'_subm_days', esc_attr($_POST['subm_days']));
    }
}


// ----------------------------------//
// Shortcode function dwnld protect //
// ------------------------------- //
/*
usage ==> [dprotect file='filename.zip' level='X'] where "X" = 1,2,3,4 or 5 (platinum)
*/
function subm_download_protect($attr, $content) {
  $filename = $attr['file'];    $level = $attr['level'];
  $file_enc = base64_encode("$filename|$level");
 
  $subm_dwnld = get_option('subm_members_dwnld'); //echo "$subm_dwnld[dwndir]<hr>";
  if($content == '') { 
    if($subm_dwnld[dwnld_txt]!='') { $content = $subm_dwnld[dwnld_txt];} 
    else { $content = 'Click Here to Download'; } 
  }
  
  $wpdir = WP_CONTENT_DIR; 
  $dwnld_dir = str_replace("wp-content", "$subm_dwnld[dwndir]", $wpdir); // To chk if file exist
  
  $actual_url = site_url() . '/'. $subm_dwnld[dwndir] . "/$filename"; 
  $protect_url = plugins_url('',__FILE__) . "/subm_download.php?f=$file_enc";
  
  if(file_exists("$dwnld_dir/$filename")) {
      $download = base64_encode(urlencode("$dwnld_url/$filename>"));
      $url = "<a href=$protect_url>$content</a>";
      return($url);
  } else {
      $dprotect_err = "Oops, unable to locate the file specified";
      return($dprotect_err);// do nothing.
  }
}

// ----------------------------------//
// Shortcode to create level1 Mbr   //
// ------------------------------- //
function subm_confirm_optin($attr, $content) {
   if($_REQUEST[email]!='' && $_REQUEST[passwd]!="") {
      $username = $email = $_REQUEST[email];   $password = $_REQUEST[passwd];       
      $fname = trim($_REQUEST[fname]); $lname = trim($_REQUEST[lname]); 
      $displayname = "$fname $lname";
      $u_role = "subm_level1";  $login_url = home_url() . "/wp-login.php";
   
      // check if current 'user_login'(email) exist //
      // -------------------------------------------//
      global $wpdb;
      $q = "SELECT ID, user_login FROM wp_users WHERE user_login='$username'";
      $results = $wpdb->get_row($wpdb->prepare($q));
      $userID = $results->ID;

      // current user (email) does not exist, create new user account //
      // ------------------------------------------------------------//
      if($userID == '') {
          $userdata = array(
              'user_login'  => $username,
              'user_pass'   => $password,
              'user_email'  => $email,
              'first_name'  => $fname,
              'last_name'   => $lname,
              'display_name'=> $displayname
              );
          $user_id = wp_insert_user($userdata);
          add_metadata('user', $user_id, 'cbreceipt', 'level1_member', $unique='false');
          // -----------------//          
          $user = new WP_User($user_id); // create new user object to update user role.       
          $user->set_role($u_role); // set member's role
           
          $ret_data = "<h2>Congratulations!</h2>
                      You may <a href=$login_url target=_new>login here</a><BR />
                      Login ID: $username<BR />Password: $password<BR />";
          
          // auto-subscribe new member //
          // --------------------------//
          $subm_mbrs = get_option('subm_members_option'); $listname = $subm_mbrs[listname1];
          $admin_email = get_option('admin_email');
          
          if($listname!="") {
            $cbreceipt = 'level1_member'; $level = 'subm_level1'; // hardcoded //
            $subtype = "Customers";       $prodname = "Membership Level $level";
            $key="501"; 
   
            $subdata = "$email|$displayname|$cbreceipt|$key|$admin_email|$level";            
   
            $api    = $subm_mbrs[api_key]; $artype = $subm_mbrs[artype]; 
            include_once('subm_autores.php');
            switch($artype) {
              case "1": // aweber //
                subm_aweber($subdata, $api, $listname, $prodname, $subtype);break;
              case "2": // getresponse
                subm_getresponse( $subdata, $api, $listname, $prodname, $subtype);break;
              case "3": // not implemented
                break;
              case "4": // others, subs via email, eg AutoresponsePlus
                subm_emailsub( $subdata, $api, $listname, $prodname, $subtype);break;
              case "5": // MailChimp
                subm_mailchimp( $subdata, $api, $listname, $prodname, $subtype);break; 
              case "8": // custom API - customer needs to create their own //
                if(file_exists('subm_customAPI.php')) { include_once('subm_customAPI.php'); }             
            }
          }
       // ----------------------------------//                  
       // User already exist - display mesg //
       // ----------------------------------//
       } else { 
          $user_id = $userID;     
          $xuser_cap = get_user_meta($user_id, 'wp_capabilities', false);
          if( !empty($xuser_cap)) {
              $mbr_level = '';  // reset to null.
              foreach($xuser_cap as $xcap) {
                  if($xcap[subm_level1]==1) { $mbr_level = "Basic Member";}
                  if($xcap[subm_level2]==1) { $mbr_level = "Bronze Member";}
                  if($xcap[subm_level3]==1) { $mbr_level = "Silver Member";}
                  if($xcap[subm_level4]==1) { $mbr_level = "Gold Member";}
                  if($xcap[subm_level5]==1) { $mbr_level = "Platinum Member";}
              }
              if($mbr_level == '') { // user is a WP blog subscriber, but not a Basic member yet 
                    add_metadata('user', $user_id, 'cbreceipt', 'level1_member', $unique='false');
                    $user = new WP_User($user_id); // create new user object to update user role.       
                    $user->set_role($u_role); // set member's role
                    $ret_data = "<h2>Congratulations!</h2>You have been upgraded to a Free Basic Membership.
                    <BR /> You may <a href=$login_url target=_new>login here</a><BR />";
                    
              } else { // display friendly err. mesg //
                    $ret_data = "<h2>Oops ...</h2>
                    You are already a <B><font color=red>$mbr_level</font></b>.<BR />
                    You may <a href=$login_url target=_new>login here</a><BR /><BR />
                     If you need assistance, please contact us and we'll be happy to help you out";   
              }
          }
       }
      // return login & passwd data for display //
      return($ret_data);
 
   // If Visitor access this page directly (without submitting form data), display Err. //
   // ----------------------------------------------------------------------------------//
   } else {
      $ret_data = "<h2>Oops ... you may have forgotten to enter your sign-up details!</h2>";
      return($ret_data);
   }
}

// ---------------------------------------------------//
// Shortcode to display "THankyou" (CB thankyou page) //
// ------------------------------------------------- //
function subm_thankyou($attr,$content) {
  // contains func & code to verify purchase & create mbr account //
  $login_url = home_url() . "/wp-login.php"; $contact = get_bloginfo('admin_email');
  include_once('subm_members.php');
  if($pay_processor=="CLICKBANK") { $payment_processor = "CLKBANK*COM"; }
  if($pay_processor=="PAYPAL") { $payment_processor = "Paypal"; }
  if($pay_processor=="2CO") { $payment_processor = "2CheckOut"; }
  
  //if($login!='' && $passwd !=0 ) {
  if($passwd!="0") { 
    $wploginurl = get_bloginfo('wpurl');
    $cb_thanks = "<h2>Thank you for your purchase</h2>
    Please note that your credit card will show a charge by $payment_processor<BR /><BR />
    Here are your membership login details. Please copy the following membership info 
    and keep it in a safe place:<BR /><BR />
    Your login ID: <b><font color=red>$login</font></b><BR>
    Your Password: <b><font color=red>$passwd</font></b><BR><BR />
    Please click here to <a href=$wploginurl/wp-login.php><b>login to the members area.</b></a>";
  } else { // error handling here //
    if($login=='') { 
      $login='<b><font color=red>Unable to locate your purchase receipt.</font></b><BR />If you want 
      to test your links, please do a test purchase by creating a temporary CC num in your Clickbank account.'; 
    }
    $cb_thanks = "<h2>Oops ... we ran into some problem here ...</h2>$login<BR /><BR /> Please contact 
    us at <a href=mailto:$contact>$contact</a>for assistance!<BR /><BR />We apologize for any inconvenience caused!";
  }
  return($cb_thanks); 
}

// ----------------------------------//
// Shortcode to display Optin Form  //
// ------------------------------- //
function subm_show_optin($attr) {
  $optin_url = $attr[url];
  $optin_pg = "<form action=$optin_url method=post>
  <table>
  <tr><td>First name:</td><td><input type=text name=fname></td></tr>
  <tr><td>Last name: </td><td><input type=text name=lname></td></tr>
  <tr><td>Email:  </td><td><input type=text name=email></td></tr>
  <tr><td>Preferred Password: </td><td><input type=text name=passwd></td></tr>
  <tr><td colspan=2 align=center><input type=submit name=submit value='Sign up'></td></tr></table></form>"; 
  return($optin_pg);
}

// =================== list of non-WP "support" functions ========================= //

if (!function_exists('is_vector')) {
   function is_vector( &$array ) {
      if ( !is_array($array) || empty($array) ) { return -1; }
      $next = 0;
      foreach ( $array as $k => $v ) {
         if ( $k !== $next ) return false;
         $next++;
      }
      return true;
   }
}
// -------------------//
// TEXT BOX function //
// -----------------//
function subm_textbox($name, $value="") {
   if (get_option($name)) { $value = get_option($name); }

   ?>
   <input type="text" name="<?php echo $name ?>" size="15" value="<?php echo $value ?>" />
   <?php
}
// -------------------//
// CHECKBOX function //
// -----------------//
function subm_checkbox($name) {
   ?>
   <?php if (get_option($name)): ?>
   <input type="checkbox" name="<?php echo $name ?>" checked="checked" />
   <?php else: ?>
   <input type="checkbox" name="<?php echo $name ?>" />
   <?php endif; ?>
   <?php
}
// -------------------//
// TEXTAREA function //
// -----------------//
function subm_textarea($name, $value="") {
   if (get_option($name)) { $value = get_option($name); }
   ?>
   <textarea name="<?php echo $name ?>" cols="80" rows="8"><?php echo $value ?></textarea>
   <?php
}
// -------------//
// getcontent() //
// -------------//
function getcontent($url,$timeout=10) {  $ch=curl_init($url); 
  if($ch) {
    curl_setopt($ch,CURLOPT_TIMEOUT,$timeout);
    curl_setopt($ch,CURLOPT_HEADER,0);  curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
    curl_setopt($ch,CURLOPT_USERAGENT,'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)');
    curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,FALSE);
    $data=curl_exec($ch); $res=curl_getinfo($ch,CURLINFO_HTTP_CODE);
    curl_close($ch);  return $data;
  } else { $curlflag = 0; return("$curlflag");   }
}
?>