Location: PHPKode > projects > MembersGear > membersgear/cronjobs/update_product_membership_status_expirestatus.php
<?php
  
  require_once "../config/config.php";
  require_once INCLUDE_DIR."/users_class.php";
  require_once INCLUDE_DIR."/product_class.php";
  require_once INCLUDE_DIR."/product_protection_class.php";
  require_once INCLUDE_DIR."/cannedemail_class.php";
  require_once INCLUDE_DIR."/autoresponder.php";
  require_once INCLUDE_DIR."/master_class.php"; 
  require_once  INCLUDE_DIR."/folderProtection.php";
  require_once INCLUDE_DIR."/passgen.php";
  require_once INCLUDE_DIR."/users_signup_class.php"; 
  require_once PHYSICAL_DIR."/includes/system_get_set_options_class.php";
  require_once INCLUDE_DIR."/PaygearWebserviceClient.php";
  
  
  $option_obj=new system_get_set_options_class();
 
  
  if(function_exists('wordpress_check_Plugin_structure') and function_exists('wordpress_getWordpress_status')  )
 {
  
    $wordpressStatus=wordpress_getWordpress_status();
    if($wordpressStatus){

        $dirWordpress=wordpress_physical_path_dir()."wp-config.php";
        if(file_exists($dirWordpress)){
            require_once($dirWordpress);  
            assign_sessions();  
        
        }
        
     }
   
 } 
  
  function ProductMemberShipStatus()
  {
      $loUserClass = new users_class();
      $loProductClass = new product_class();
      $loMasterClass = new master_class();
      $loCannedEmail = new cannedemail_class();
      
      $expiredDate = strtotime(date("Y/m/d"));
      
      $MasterID = $loMasterClass->getMasterId('productmembershipstatus');  
      $statusID = $loMasterClass->getMasterValuesId('Expire',(int)$MasterID);  
                  
      $query = 'select * from '.TABLE_PREFIX.'product_users where uptodate <= ? and islifetime = ? and productmembershipstatusid <> ?';
      $lsTempProductUsers = array($expiredDate,0,$statusID);
      $laResult = $loUserClass->View($query,$lsTempProductUsers,null);
      
      if(is_array($laResult) and sizeof($laResult) > 0)
      {
              foreach($laResult as $key=>$value)
              {
                  
                  $updateQuery = 'UPDATE '.TABLE_PREFIX.'product_users SET productmembershipstatusid=? WHERE id=?';
                  $laUpdateValues = array((int)$statusID,$value['id']);
                  $updateResult = $loUserClass->Insert($updateQuery,$laUpdateValues,null);
                  
                  
                  if($updateResult > 0)
                  {
                         
                         /* updated by nikunj for phpBB settigs */
                         
                            $userQuery = 'SELECT username FROM '.TABLE_PREFIX.'users WHERE id=?';
                            $lsUsersValues = array($value['userid']);
                            $laUserData = $loUserClass->View($userQuery,$lsUsersValues,null);
                          
                            $productobj=new product_class();
                            $users_signup_class=new users_signup_class();
                            if($users_signup_class->phpbbStatuscheck())
                              {
                                    $phpBBProduct=phpBB_get_product_id();
                                    mysql_select_db(MEMBERSGEAR_DB_NAME);  
                                    if($phpBBProduct==$value['productid'])
                                    {
                                      phpBB_activate_deactivate_user($laUserData[0]['username'],1);
                                      mysql_select_db(MEMBERSGEAR_DB_NAME);  
                                    }
                              }
                              
                            if($users_signup_class->wordpressStatuscheck()){
                                                     
                                $wordpressReqquiredFile= wordpress_physical_path();
                              
                                if(file_exists($wordpressReqquiredFile)){
                                                
                                    $proID=$value['productid'];
                                    
                                    $userQuery1 = 'SELECT * FROM '.TABLE_PREFIX.'users WHERE id=?';
                                    $lsUsersValues1 = array(trim($value['userid']));
                                    $laUserData1 = $users_signup_class->View($userQuery1,$lsUsersValues1,null);
                                    $user_name=$laUserData1[0]['username'];
                                         
                                     $user_id = wordpress_username_exists( $user_name );  

                                     if ( $user_id ) {
                                     
                                        $savedRoles=wordpress_get_option('membersgear_roles'); 
                                         
                                                 
                                         if(array_key_exists($proID,$savedRoles)){
                                         
                                            $rolename=strtolower($savedRoles[$proID]);
                                            wordpress_remove_user_role($user_id,$rolename);
                                           
                                          }
                                   
                                         $savedRoles=wordpress_get_option('membersgear_roles'); 
                                         $wp_role=array('subscriber'=>0,'contributor'=>1,'author'=>4,'editor'=>7,'administrator'=>10);
                                         $wp_role_byname=array(0=>'subscriber',1=>'contributor',4=>'author',7=>'editor',10=>'administrator');
                                            
                                         $userSubscribedProducts=$users_signup_class->getAlluserSubscribedProduct($value['userid']);
                                         $rolArr=array();
                                         if(count($userSubscribedProducts) > 0 and $userSubscribedProducts!=false){
                                         
                                         for($i=0;$i<=count($userSubscribedProducts)-1;$i++)
                                          {
                                              if(array_key_exists($userSubscribedProducts[$i]['id'],$savedRoles)){
                                              
                                                if(array_key_exists($savedRoles[$userSubscribedProducts[$i]['id']],$wp_role)){
                                                
                                                   if($userSubscribedProducts[$i]['id']!= $proID){  
                                                   
                                                         $rolArr[]=$wp_role[$savedRoles[$userSubscribedProducts[$i]['id']]];
                                                   }
                                                 }
                                              
                                              }
                                          }
                                        } 
                                        $maxRole=max($rolArr);
                                        $roleName=$wp_role_byname[$maxRole];  

                                        if($roleName!=''){

                                           wordpress_add_user_role($user_id,$roleName);
                                        
                                        }
                                           
                                   
                                   
                                     
                                   }  
                                   
                                    
                                        
                               }
                                              
                                                         
                           }   
                          
                          /***************************************/
                  
                          if(EMAIL_SUBSCRIPTION_IS_EXPIRED == 'true' and EMAIL_SUBSCRIPTION_IS_EXPIRED_DAYS == 0)
                          {
                              
                               $templateQuery = 'SELECT id,status FROM '.TABLE_PREFIX.'email_templates WHERE productid=? AND name=?';
                               $lstemplateValues = array($value['productid'],EMAIL_SUBSCRIPTION_IS_EXPIRED_TEMPLATE_NAME);
                               $laTemplateData = $loCannedEmail->View($templateQuery,$lstemplateValues,null);
                               $templateID = 0;
                                if($laTemplateData != '')
                                {
                                       $templateID = $laTemplateData[0]['id'];
                                       $productID  = $value['productid'];
                                }
                                else
                                { 
                                        $templateID = EMAIL_SUBSCRIPTION_IS_EXPIRED_TEMPLATE_ID;
                                        $productID  = 0;
                                }
                               
                               $userQuery = 'SELECT username,password,email,firstname,lastname,isunsubscribedfromemails FROM '.TABLE_PREFIX.'users WHERE id=?';
                               $lsUsersValues = array($value['userid']);
                               $laUserData = $loUserClass->View($userQuery,$lsUsersValues,null);
                               
                               $productTableQuery = 'SELECT name,protectedurl,expirationemail FROM '.TABLE_PREFIX.'products WHERE id=?';
                               $laProductValues = array($value['productid']+0);
                               $laProductData = $loProductClass->View($productTableQuery,$laProductValues,null);
                               
                                 if($laUserData[0]['isunsubscribedfromemails'] == 0 and $laProductData[0]['expirationemail'] != 'DONOTSEND')
                                 {
                                     SendCannedEmailsAutoresponse($templateID,$productID,EMAIL_SUBSCRIPTION_IS_EXPIRED_TEMPLATE_NAME,$laProductData[0]['name'],$laProductData[0]['protectedurl'],$laUserData[0]['username'],$laUserData[0]['password'],$laUserData[0]['email'],$laUserData[0]['firstname'],$laUserData[0]['lastname']);
                                 }
                          }   
                  }
                  
              }
      }
      //print_r($laResult);
      unset($loUserClass);                
      unset($loProductClass);                
      unset($loMasterClass);
      unset($loCannedEmail);
         
  }
  
  
    function UpdateProductStatus()
  {
      $loUserClass = new users_class();
      $loMasterClass = new master_class();
      
      $PaygearWebserviceClient = new PaygearWebserviceClient();
      
      $paymentStatusQuery = 'SELECT paygear_id FROM '.TABLE_PREFIX.'paygear_mastervalues WHERE paygear_master = \'ePaymentStatus\' AND (paygear_value=\'Pending\' OR paygear_value=\'Failed\')';
      $paymentStatusID = $loUserClass->View($paymentStatusQuery,null,null);
      
      $query = 'select * from '.TABLE_PREFIX.'product_users where paygear_epaymentstatus = ? or paygear_epaymentstatus = ?';
      $lsTempProductUsers = array((int)$paymentStatusID[0]['paygear_id'],(int)$paymentStatusID[1]['paygear_id']);
      $laResult = $loUserClass->View($query,$lsTempProductUsers,null);
      
      if(is_array($laResult) and sizeof($laResult) > 0)
      {
              foreach($laResult as $key=>$value)
              {
                  $liPaygearETransactionID = ($value['paygear_etransactionid'] != '') ? (int)$value['paygear_etransactionid'] : 0;     
                  $liPaygearOrderID = ($value['paygear_orderid'] != '') ? (int)$value['paygear_orderid'] : 0;
                  
                  $response = $PaygearWebserviceClient->GetPaygearTransactionDetailByOrderIdAndEtransactionID($liPaygearOrderID,$liPaygearETransactionID);
                  
                  if(is_array($response) and sizeof($response) > 0)
                  {
                        $response = str_replace("!@#$%^*()","=",$response);
                        $paygear_epaymentstatus = explode("=",$response[0]);
                        $paygear_vendorpaymentstatus = explode("=",$response[1]);
                        
//                        echo $paygear_epaymentstatus[1]."<br/>";
//                        echo $paygear_vendorpaymentstatus[1]."<br/>";
                        $updateQuery = 'UPDATE '.TABLE_PREFIX.'product_users SET paygear_epaymentstatus=?,paygear_vendorpaymentstatus=? WHERE id=?';
                        $laUpdateValues = array($paygear_epaymentstatus[1],$paygear_vendorpaymentstatus[1],$value['id']);
                        $updateResult = $loUserClass->Update($updateQuery,$laUpdateValues,null);
                  }
                  //echo "<br/><br/>";
              }
      }   
  }
  
  function autoUpdateHtacessForExpiredAccounts()
  {
     $objProdProtection=new product_protection_class();
     $allProtectedproducts=$objProdProtection->getAllProtectedProducts();
     $masterclassObj=new master_class();
     $len=sizeof($allProtectedproducts);
     if($allProtectedproducts!=false)
     {
         for($i=0;$i<$len;$i++)
         {
            
             $protectedProduct=$allProtectedproducts[$i]['allowed_productid'];
             $protectionMethod=$allProtectedproducts[$i]['protection_method'];
             $lsFolder_path=$allProtectedproducts[$i]['folder'];
             $lsUrl=trim(PHYSICAL_DIR.$lsFolder_path."/");
             $mastervalue=$masterclassObj->getValueFromID($protectionMethod);
             if($mastervalue==".htaccess")
             {
               $objFolderProtection=new ProtecfolderProtection_Class();
               $objSignupclass=new users_signup_class();
               $products=$objSignupclass->getAllowedProductsFromProtectedFolder($lsFolder_path);
               $objFolderProtection->updatePasswdfile($lsUrl,$products);
                 
             }
         
         
         }
     }
      
  }
 
   function SendEmailWhenSubcriptionAboutToExpire()
  {
      //Fetch data for send email from prefix_product_users 
      
      $loUserClass = new users_class();
      $loProductClass = new product_class();
      $loCannedEmail = new cannedemail_class();
      
      $query = 'select * from '.TABLE_PREFIX.'product_users where islifetime = ?';
      $lsTempProductUsers = array(0);
      $laResult = $loUserClass->View($query,$lsTempProductUsers,null);
      
      if(is_array($laResult) and sizeof($laResult) > 0)
      {
              foreach($laResult as $key=>$value)
              {
                    //print_r($value)."<br/>";
                    if($value != '')
                    {
                        
                        if(EMAIL_SUBSCRIPTION_ABOUT_TO_EXPIRED_DAYS >= 0)
                        {
                            $recorddate = date('Y/m/d',strtotime(date("Y/m/d",$value['uptodate'])." +".EMAIL_SUBSCRIPTION_ABOUT_TO_EXPIRED_DAYS." day"));
                            $currentdate = date("Y/m/d");                                                                                   
                        }
                        elseif(EMAIL_SUBSCRIPTION_ABOUT_TO_EXPIRED_DAYS < 0)
                        {
                            $addDay = substr(EMAIL_SUBSCRIPTION_ABOUT_TO_EXPIRED_DAYS,1);
                            $recorddate = date('Y/m/d',strtotime(date("Y/m/d",$value['uptodate'])." -".$addDay." day"));   
                            $currentdate = date("Y/m/d");
                        }
                        if(isset($recorddate) and isset($currentdate))
                        {
                                if($recorddate == $currentdate)
                                {
                                      //echo "send email to ".$value['id']." id number.<br/>";
                                      if(EMAIL_SUBSCRIPTION_ABOUT_TO_EXPIRED == 'true')
                                      {
                                          /*
                                           $templateQuery = 'SELECT id,status FROM '.TABLE_PREFIX.'email_templates WHERE userid=? AND productid=?';
                                           $lstemplateValues = array($value['userid'],$value['productid']);
                                           $laTemplateData = $loCannedEmail->View($templateQuery,$lstemplateValues,null);
                                     
                                            if($laTemplateData != '')
                                            {                                              
                                                   $templateID = $laTemplateData['id'];
                                            }
                                            else
                                            { */
                                                    $templateQuery = 'SELECT id,status FROM '.TABLE_PREFIX.'email_templates WHERE name=\'Subscription about to expire\' AND productid=0';
                                                    $laTemplateData = $loCannedEmail->View($templateQuery);
                                                    
                                            //}
                                           
                                           $userQuery = 'SELECT username,password,email,firstname,lastname,isunsubscribedfromemails FROM '.TABLE_PREFIX.'users WHERE id=?';
                                           $lsUsersValues = array($value['userid']);
                                           $laUserData = $loUserClass->View($userQuery,$lsUsersValues,null);
                                           
                                           $productTableQuery = 'SELECT name,protectedurl FROM '.TABLE_PREFIX.'products WHERE id=?';
                                           $laProductValues = array($value['productid']+0);
                                           $laProductData = $loProductClass->View($productTableQuery,$laProductValues,null);
                                           
                                           if($laTemplateData[0]['status'] == 1 and $laUserData[0]['isunsubscribedfromemails'] == 0)
                                           {
                                                 SendCannedEmailsAutoresponse(EMAIL_SUBSCRIPTION_ABOUT_TO_EXPIRED_TEMPLATE_ID,0,EMAIL_SUBSCRIPTION_ABOUT_TO_EXPIRED_TEMPLATE_NAME,$laProductData[0]['name'],$laProductData[0]['protectedurl'],$laUserData[0]['username'],$laUserData[0]['password'],$laUserData[0]['email'],$laUserData[0]['firstname'],$laUserData[0]['lastname']);
                                           }

                                           
                                      }
                                }
                        }
                    }
                   // echo "<br/><br/>";   
              }
      }
      //print_r($laResult);
      unset($loUserClass);                
      unset($loProductClass);                
      unset($loCannedEmail);                
  }
  
  /**************************************************************************************************/
  //                       For Send email when subscription expired                                 //
  /**************************************************************************************************/
  function SendEmailWhenSubcriptionExpired()
  {
      //Fetch data for send email from prefix_product_users 
      
      $loUserClass = new users_class();
      $loProductClass = new product_class();
      $loCannedEmail = new cannedemail_class();
      
      $expiredDate = strtotime(date("Y/m/d")." -".EMAIL_SUBSCRIPTION_IS_EXPIRED_DAYS." day");
      
      $query = 'select * from '.TABLE_PREFIX.'product_users where uptodate = ? and islifetime = ?';
      $lsTempProductUsers = array($expiredDate,0);
      
      $laResult = $loUserClass->View($query,$lsTempProductUsers,null);
      
      if(is_array($laResult) and sizeof($laResult) > 0)
      {
              foreach($laResult as $key=>$value)
              {
                    //print_r($value)."<br/>";
                    if($value != '')
                    {
                        
                        
                        
                            //echo "send email to ".$value['id']." id number.<br/>";
                              if(EMAIL_SUBSCRIPTION_IS_EXPIRED == 'true')
                              {
                                  
                                   $templateQuery = 'SELECT id,status FROM '.TABLE_PREFIX.'email_templates WHERE productid=? AND name=?';
                                   $lstemplateValues = array($value['productid'],EMAIL_SUBSCRIPTION_IS_EXPIRED_TEMPLATE_NAME);
                                   $laTemplateData = $loCannedEmail->View($templateQuery,$lstemplateValues,null);
                                   $templateID = 0;
                                    if($laTemplateData != '')
                                    {
                                           $templateID = $laTemplateData[0]['id'];
                                           $productID  = $value['productid'];
                                    }
                                    else
                                    { 
                                            $templateID = EMAIL_SUBSCRIPTION_IS_EXPIRED_TEMPLATE_ID;
                                            $productID  = 0;
                                    }
                                   
                                   $userQuery = 'SELECT username,password,email,firstname,lastname,isunsubscribedfromemails FROM '.TABLE_PREFIX.'users WHERE id=?';
                                   $lsUsersValues = array($value['userid']);
                                   $laUserData = $loUserClass->View($userQuery,$lsUsersValues,null);
                                   
                                   $productTableQuery = 'SELECT name,protectedurl,expirationemail FROM '.TABLE_PREFIX.'products WHERE id=?';
                                   $laProductValues = array($value['productid']+0);
                                   $laProductData = $loProductClass->View($productTableQuery,$laProductValues,null);
                                   
                                     if($laUserData[0]['isunsubscribedfromemails'] == 0 and $laProductData[0]['expirationemail'] != 'DONOTSEND')
                                     {
                                         SendCannedEmailsAutoresponse($templateID,$productID,EMAIL_SUBSCRIPTION_IS_EXPIRED_TEMPLATE_NAME,$laProductData[0]['name'],$laProductData[0]['protectedurl'],$laUserData[0]['username'],$laUserData[0]['password'],$laUserData[0]['email'],$laUserData[0]['firstname'],$laUserData[0]['lastname']);
                                     }

                                   
                              }
                       
                    }
                   // echo "<br/><br/>";   
              }
      }
      //print_r($laResult);
      unset($loUserClass);                
      unset($loProductClass);                
      unset($loCannedEmail);                
  }
   
 
  ProductMemberShipStatus();
  UpdateProductStatus(); 
  SendEmailWhenSubcriptionExpired();
  SendEmailWhenSubcriptionAboutToExpire();
  autoUpdateHtacessForExpiredAccounts(); 
  $option_obj->update_option('CRON_LAST_EXECUTED_ON',date("m/d/Y g:i a") );
?>
Return current item: MembersGear