My PHP sample


/**
  * Syncs CMS user with CM (Campaign Monitor) list
  * Newsletters and emails are managed CM
  * these newsletter contains special URL links
  * that allows subscribers to view special contents.
  * This links are invalid after specified number of days/weeks and
  * also after number of view.
  */


/** 
  * gets the neccessary functions and value stored for CM (Campaign Monitor)
  * such as CM id, other key settings
  */
require_once plugin_dir_path( __FILE__ ) . 'api-functions.php'; 

/**
  * This function gets triggered by external CRON job ...
  * when it hits this page
  */
function CM_sync1(){
  /** stores date in db to make sure it only runs once a day.
    * just incase it got triggered multiple times.
    */
  $check = get_option('cron_cm_sync') ? get_option('cron_cm_sync') : '';

require_once CM_PLUGIN_PATH . 'campaign-monitor-api/csrest_general.php';
require_once CM_PLUGIN_PATH . 'campaign-monitor-api/csrest_subscribers.php';
require_once CM_PLUGIN_PATH . 'campaign-monitor-api/csrest_lists.php';

/*************  GENARETE PATH KEY *************/
$api_key='secret_salt_for_the_secret_key';

/**
  * generate a key using algorithm
  * which is used to send a request to another server.
  * key generated using this special algorithmn, 
  * (which is combined in a special way later to generate URL)
  * The URL is authenticated by the other server to allow 
  * the user to view special stuffs
  */
function generete_secret_key($emails){

global $api_key;

  if($emails){
    // using magical methods to create secure key here
    return $latest_key;
  }
}

// echo generete_secret_key('test email here');

/**
  * Syncs the CMS user with the CM.
  */
class CM_sync_site {
      // init few stufss
      var $site_id;
      var $site_abbr;
      var $users;
      var $user_role;
      var $api_settings;
      var $expired_users;
      var $deleted_subs;
      var $results = array();
      var $pdmauth_arr = array();

  function __construct( $site_id, $site_abbr, $user_role ) {
	   $this->site_id = $site_id;
	   $this->site_abbr = $site_abbr;
	   $this->user_role = $user_role;
	   // $this->users = get_users( array( 'fields' => array( 'ID' ) ) );
	   
	}

	function get_site_abbr(){
		return $this->site_abbr;
	}

	function CM_init(){ //initialization

      // gets the cm settings
		  $this->api_settings();

      // gets lists of users from CMS and CM
		  $cm_lists = $this->get_list()->Results;
    	$active_users = $this->get_users();

      /* gets deleted subs in CM
       * So, if the user existed and was deleted/inactive,
       * it will move to active subscriber list
       */ 
      $cm_deleted_lists = $this->deleted_subs->Results;
      // echo 'deleted: '; var_dump( count($cm_deleted_lists) );

      /**
        * Decides and adds to relevant CM lists
        */
    	$result = $this->compare_users($active_users, $cm_lists, $cm_deleted_lists);

      /**
        * Updates the CMS table with new credentials generated by the magical function
        */
      $this->update_campaign_table($this->pdmauth_arr);

      // var_dump(count($active_users));
     
    	return ($this->results);
    }

    /**
      * Gets the CM settings
      */
    function api_settings(){
    	switch_to_blog($this->site_id); // switch to relevant blog/site

    	$this->api_settings = get_option('api_settings', array());

    	restore_current_blog();
    }


    /**
      * Function to compare the CMS and CM.
      * This decides how to sync the CMS and CM.
      */
    function compare_users($active_users, $cm_lists, $cm_deleted_lists){

    	$subs_to_be_updated = array();
      $subs_to_active = array();

      $subs_to_be_deleted = array();
      $expired_users = array();

    	switch_to_blog($this->site_id); // switch to relevant site

    if( $active_users && $cm_lists){
      $i=0;
      $active_users_last_i = count($active_users) - 1;

    	foreach( $active_users as $user_key => $user ){
    		$user_email = sanitize_email( get_userdata( (int) $user->ID )->user_email );

    		
        $j=0; //index subscribers
        $cm_last_j = count($cm_lists) - 1;
    		foreach( $cm_lists as $sub_key => $sub ){
          
          // echo 'expiry_date: '; 
          // var_dump($sub->CustomFields);
          // $expiry_date = $this->get_subscriptionenddate($sub->CustomFields);

          $cm_email = sanitize_email($sub->EmailAddress);

  				if( $cm_email == $user_email ){ // if exists in both CMS and CM
  					$subs_to_be_updated[] = $active_users[$user_key];

  					unset( $active_users[$user_key] ); //removes the subscriber from local CM list
  					unset( $cm_lists[$sub_key] ); //removes from subscriber from the local CMS list

  				}
  				$j++;
  			}// ends foreach for cm_lists

        $k = 0;
        if( $cm_deleted_lists ){
          foreach( $cm_deleted_lists as $del_sub_key => $sub ){
            $cm_deleted_email = sanitize_email($sub->EmailAddress);
            // $expiry_date = $this->get_subscriptionenddate($sub->CustomFields);

            if( $cm_deleted_email == $user_email ){
              $subs_to_active[] = $active_users[$user_key]; // need to be activated
            }
            $k++;
          } //ends foreach for cm_deleted_lists
        }

    	}// ends foreach for active_users
    }

    	if( $active_users ){ // adds new valid subscriber to CM active list
			  $added_user = $this->add_subscriber($active_users);
		  }

      if( $subs_to_be_updated ){ // updates existing valid subscribers in CM active list
        $updated_subs = $this->add_subscriber($subs_to_be_updated); //updates the existing subscribers
      }


      if( $cm_lists ){ // removes expired subsribers from active and adds it to deleted list in CM
        $deleted_subs = $this->delete_expired_subscriber( $cm_lists );
      }

      if( $subs_to_active ){ // adds valid resubscribed users to CM active list
        $deleted_to_active = $this->add_subscriber($subs_to_active, true);
      }

    	restore_current_blog();

    	// return ($deleted_subs);
    }
      
    function get_users(){

      /** 
        * gets the relevant users from CMS
        */

    	return $active_users;

    }

    /**
      * This functions adds/updates user the list in CM
      */
    function add_subscriber($subscribers, $resubscribe=false){ //updates as well
  		// $users = $this->users;

  		// var_dump( count($subscribers);

  		switch_to_blog($this->site_id); // switch to relevant blog/site

  		$i = 0;
  		$subscribers_list = array();
  		foreach( $subscribers as $subscriber ){
  			$subscriber_obj = get_userdata( (int) $subscriber->ID );

  			$company = get_user_meta( (int) $subscriber->ID, 'company', true );

  			$email = $subscriber_obj->user_email;
  			$name = $subscriber_obj->user_nicename;

        //generates the special key
  			$pdm_auth = generete_secret_key($email);
        $this->pdmauth_arr[] = array('stuff1' => $pdm_auth, 'stuff2' => $email, 'stuff3'=> strtotime( date("Y-m-d H:i:s") ) );


  			$user_sub_start = (get_user_option( 'sub_start_date', (int) $subscriber->ID ) ) ? get_user_option( 'sub_start_date', (int) $subscriber->ID ) : '';
  			$user_sub_expiry = (get_user_option( 'sub_expiry_date', (int) $subscriber->ID ) ) ? get_user_option( 'sub_expiry_date', (int) $subscriber->ID ) : '';

  			$company = (get_user_meta( (int) $subscriber->ID, 'comp', true ) ) ? get_user_meta( (int) $subscriber->ID, 'comp', true ) : '';


  			$cm_customfields = array(
                          // array of custom fields to be transfered to CM list
                      );
  			$subscribers_list[] = array( 
  									'EmailAddress' 	=> $email,
  									'Name'			=> $name,
  									'CustomFields'	=> $cm_customfields,
  								 );

  		}

      // gets the key
  		$CM_api_key =  $this->api_settings['api_key'];
		  $list_id = $this->api_settings['list_id'];

      // calls the CMS api
  		$wrap = new CS_REST_Subscribers($list_id, $CM_api_key); 

      $results = array();

      /**
        * Sends max 1000 subscribers at a time. 
        */
      if($subscribers_list){
        if( count( $subscribers_list ) > 1000 ){
          $subscribers_lists = (array_chunk($subscribers_list, 1000, false) );
          $i=1;
          if( $subscribers_lists ){
            foreach( $subscribers_lists as $subscribers_list ){

              $result = $wrap->import($subscribers_list, $resubscribe);

              if($result->was_successful()) {
                  //logs the result
                  $results["SubImported in $this->site_abbr $i: "][] = $result->response;

                }
                $i++;
            }
            // logs
            $this->results["Imported in $this->site_abbr : "] = $results;
          }
        }else {
          $result = $wrap->import($subscribers_list, $resubscribe);

          if($result->was_successful()) {
              $result = $result->response;
              // logs
              $this->results["Imported in $this->site_abbr : "] = $result;
            }
        }

      }

      	restore_current_blog(); //restore blog/site

        
      	return $this->results;

    }

    /**
      * Gets active and deleted subscribers from CM
      */
    function get_list(){

  		$CM_api_key =  $this->api_settings['api_key'];
		  $list_id = $this->api_settings['list_id'];
    	
      // gets active subscribers
    	$list = new CS_REST_Lists($list_id, $CM_api_key);
    	$result = $list->get_active_subscribers();


    	if($result->was_successful()) {
    		$result = $result->response;
    	}

      // gets all deleted subscriber
      $deleted_subs = $list->get_deleted_subscribers();

      if($deleted_subs->was_successful()) {
        $deleted_subs_result = $deleted_subs->response;
      }

      // stores deleted subs to use for compare later
      $this->deleted_subs = $deleted_subs_result;


    	return $result;

    }

    /**
      * Updates the table with new credentials.
      *
      */
    function update_campaign_table($campaign_table_data){
      global $wpdb;

      $update_user = array(); //updates the rows pdmauth

      $q = "securly get data from the relevant table";

      $existing_emails = $wpdb->get_results($q);

      $data = $campaign_table_data;

      $site_id = $this->site_id;

      /**
        * Compares the email in CMS and CM
        */
      if( $existing_emails && $data ){
        foreach( $existing_emails as $mail ){
          foreach( $data as $key => $row ){
            if( $mail->mail == $row['mail'] && $site_id == $mail->site ){
              $update_user[] = $row;
              unset( $data[$key] ); //removes the user from the list
            }
          }
        }
      }

      $site_id = $this->site_id;

      // user data that needs to be inserted/added.
      if( $data ){ //adds the new users in the campaign table
        $query = "first half of the query which includes the column names";

        $sql = array(); 
        foreach( $data as $row ) {
          $sql[] = '("' . $row["col1"] . '", "' . $row['col2'] . '", ' . $row['col3'] . ', ' . 0 . ', ' . 0 . ', ' . $site_id . ')';
        }

        /**
          * inserts multiple rows of user data at a same time to improve performance.
          */
        $query .= implode(', ', $sql);

        $wpdb->query( $query );
      }

      /**
        * existing users in the table
        * It only needs to be updated
        */
      if( $update_user ){
        foreach( $update_user as $user ){
          $q = "query to update data here";
          $wpdb->query( $wpdb->prepare( $q, $user['col1'], $user['col2'],0, 0, $user['col3'], $site_id ) );
        }
        
      }

    }

    /**
      * This functions removes the users in the CM active 
      * that are not valid subscribers or doesn't exists in the CMS anymore.
      */
    function delete_expired_subscriber( $expired_sub ){

      $CM_api_key =  $this->api_settings['api_key'];
      $list_id = $this->api_settings['list_id'];

      $wrap = new CS_REST_Subscribers($list_id, $CM_api_key); 

      // removes the expired subs
      if($expired_sub){
        foreach( $expired_sub as $sub_email ){

          $result = $wrap->delete($sub_email->EmailAddress);
        }
      }

        $this->results["Deleted in $this->site_abbr : "] = $result;

      }

      /**** might use this function later ***/
      function get_subscriptionenddate($customfields){
        if($customfields){
          foreach( $customfields as $cf){
            if( $cf->Key == "[SubscriptionEndDate]" ){
            $expiry_date = new DateTime($cf->Value);
            break;
            }
          }
        }

        return $expiry_date;
      }

   }

// gets the current date
$c_date = date_create();
$current_date = date_format($c_date,"Y-m-d");

// checks if the custom field is initialized
if( $check == '' ){
  $check = $current_date;
  update_option( 'cron_cm_sync', $check ); 
}

// makes sure it doesn't run multiple times a day
if( strtotime($check) >= strtotime($current_date) ){
    return $check;
}elseif( strtotime($check) < strtotime($current_date) ){

  /** 
    * runs the sync for multiple sites
    * only syncs certain user with specific roles
    */
  $site1 = new CM_sync_site(2, 'site1', array('role1', 'role2', 'role3', 'role4') );
  $site2   = new CM_sync_site(3, 'site2', array('role1', 'role2', 'role3', 'role4') );
  $site3  = new CM_sync_site(4, 'site3', array('role1', 'role2', 'role3', 'role4') );
  $site4  = new CM_sync_site(5, 'site4', array('role1', 'role2', 'role3', 'role4') );
  $site5   = new CM_sync_site(6, 'site5', array('role1', 'role2', 'role3', 'role4') );
  $site6   = new CM_sync_site(7, 'site6', array('role1', 'role2', 'role3', 'role4') );

  $results = array();

  $results[] = ( $site1->CM_init() ); 
  $results[] =( $site2->CM_init() );
  $results[] =( $site3->CM_init() );
  $results[] =( $site4->CM_init() );
  $results[] =( $site5->CM_init() );
  $results[] =( $site6->CM_init() );


  var_dump( $results );
  // emails me the log
  wp_mail('my email here', sprintf(__('[%s] Campaign Monitor Results'), 'CM API'), print_r($results, true) );

  // updates to current date so, it doesn't run multiple times
  update_option( 'cron_cm_sync', $current_date ); 

}

}
// add_action('init', 'CM_sync1');

?>
Post Meta

Created at: Dec 15, 2017

Category: My Repo

php api oop