From dde55be3c6cf2cbd56dc9d652099d6282b3cc7eb Mon Sep 17 00:00:00 2001
From: Davis <remeizs@hotmail.fr>
Date: Tue, 7 Jun 2011 13:17:20 +0200
Subject: [PATCH] Complete the update issue

---
 emf.db.inc                                  |   32 +++++++++++---
 emf.helpers.inc                             |   18 ++++++++-
 emf.install                                 |   23 +---------
 emf.module                                  |   21 ++++++++-
 emf.sync.inc                                |   50 +++++++++++++---------
 plugins/emf_mailchimp/emf_mailchimp.api.inc |   59 ++++++++++++++++++++++++--
 6 files changed, 145 insertions(+), 58 deletions(-)

diff --git a/emf.db.inc b/emf.db.inc
index 9b96b80..5983624 100644
--- a/emf.db.inc
+++ b/emf.db.inc
@@ -1,4 +1,5 @@
 <?php
+// $Id$
 
 /**
  * @file
@@ -35,17 +36,16 @@ function emf_db_get_requests() {
  * @param $fields
  *   Array; Values for fields to subscribe.
  */
-function emf_db_save_request($type, $mail, $lid, $fields = array(), $fails = 0) {
-  $exists = db_result(db_query("SELECT count(mail) FROM {emf_request} WHERE mail = '%s' AND lid = '%s'", $mail, $lid));
+function emf_db_save_request($type, $mail, $lid, $fields = array()) {
+  $exists = db_result(db_query("SELECT mail FROM {emf_request} WHERE mail = '%s' AND lid = '%s'", $mail, $lid));
   if ($exists) {
-    db_query("UPDATE {emf_request} SET type = '%s', fields = '%s', timestamp = %d, fails = %d WHERE mail = '%s' AND lid = '%s'", array($type, serialize($fields), time(), $fails, $mail, $lid));
+    db_query("UPDATE {emf_request} SET type = '%s', fields = '%s', timestamp = UNIX_TIMESTAMP() WHERE mail = '%s' AND lid = '%s'", $type, serialize($fields), $mail, $lid);
   }
   else {
-    db_query("INSERT INTO {emf_request} (type, mail, lid, fields, timestamp, fails) VALUES ('%s', '%s', '%s', '%s', %d, %d)", array($type, $mail, $lid, serialize($fields), time(), $fails));
+    db_query("INSERT INTO {emf_request} (type, mail, lid, fields, timestamp) VALUES ('%s', '%s', '%s', '%s', UNIX_TIMESTAMP())", $type, $mail, $lid, serialize($fields));
   }
 }
 
-
 /**
  * Delete a request from database.
  *
@@ -82,11 +82,29 @@ function emf_db_get_subscriptions($mail) {
  *   String; The mail address to save the subscription for.
  * @param $lid
  *   String; The list id save the subscription for.
+ * @param $fields
+ *   Array; The user'account data with fname, lname, etc...
  */
-function emf_db_save_subscription($mail, $lid) {
+function emf_db_save_subscription($mail, $lid, $fields = array()) {
   $exists = db_result(db_query("SELECT mail FROM {emf_subscription} WHERE mail = '%s' AND lid = '%s'", $mail, $lid));
   if (!$exists) {
-    db_query("INSERT INTO {emf_subscription} (mail, lid) VALUES ('%s', '%s')", $mail, $lid);
+    db_query("INSERT INTO {emf_subscription} (mail, lid, fields) VALUES ('%s', '%s', '%s')", $mail, $lid, serialize($fields));
+  }
+}
+/*
+ * Update a user's detail for a given address to a given list.
+ *
+ * @param $mail
+ *   String; The mail address to save the subscription for.
+ * @param $lid
+ *   String; The list id save the subscription for.
+ * @param $fields
+ *   Array; The user's fields values
+ */
+function emf_db_save_update($mail, $lid, $fields){
+  $exists = db_result(db_query("SELECT mail FROM {emf_subscription} WHERE mail = '%s' AND lid = '%s' AND fields = '%s'", $mail, $lid, serialize($fields)));
+  if (!$exists) {
+    db_query("UPDATE {emf_subscription} SET mail = '%s', lid = '%s', fields = '%s' WHERE mail = '%s' AND lid = '%s'", $mail, $lid, serialize($fields), $mail, $lid);
   }
 }
 
diff --git a/emf.helpers.inc b/emf.helpers.inc
index 84a1642..e93f016 100644
--- a/emf.helpers.inc
+++ b/emf.helpers.inc
@@ -1,4 +1,5 @@
 <?php
+// $Id$
 
 /**
  * @file
@@ -66,7 +67,22 @@ function emf_helpers_parse_field_values($lid, $account = NULL) {
  */
 function emf_helpers_subscribe($mail, $lid, $fields) {
   emf_db_save_request('subscribe', $mail, $lid, $fields);
-  emf_db_save_subscription($mail, $lid);
+  emf_db_save_subscription($mail, $lid, $fields);
+}
+
+/**
+ * Update a user to a list.
+ *
+ * @param $mail
+ *   String; E-mail address to subscribe
+ * @param $lid
+ *   String; List ID of the list to subscribe to.
+ * @param $fields
+ *   Array; Array of custom field values.
+ */
+function emf_helpers_update($mail, $lid, $fields) {
+  emf_db_save_request('updateMember', $mail, $lid, $fields);
+  emf_db_save_update($mail, $lid, $fields);
 }
 
 /**
diff --git a/emf.install b/emf.install
index 8e21b98..1aae87a 100644
--- a/emf.install
+++ b/emf.install
@@ -1,4 +1,5 @@
 <?php
+// $Id$
 
 /**
  * @file
@@ -57,12 +58,6 @@ function emf_schema() {
       'type'      => array('type' => 'varchar', 'length' => '32', 'not null' => TRUE),
       'fields'    => array('type' => 'text', 'not null' => TRUE),
       'timestamp' => array('type' => 'int', 'not null' => TRUE),
-      'fails'    => array(
-        'description' => 'Number of failed attempt(s) to push the request to the service.',
-        'type' => 'int',
-        'not null' => TRUE,
-        'default' => 0
-      ),
     ),
     'primary key' => array('mail', 'lid'),
     'indexes' => array(
@@ -76,6 +71,7 @@ function emf_schema() {
     'fields' => array(
       'mail'   => array('type' => 'varchar', 'length' => '128', 'not null' => TRUE),
       'lid'    => array('type' => 'varchar', 'length' => '64', 'not null' => TRUE),
+	  'fields' => array('type' => 'text', 'not null' => TRUE),
     ),
     'primary key' => array('mail', 'lid'),
   );
@@ -166,7 +162,6 @@ function _emf_schema_list_roles() {
   );
 }
 
-
 /**
  * Adding list roles table.
  */
@@ -227,18 +222,4 @@ function emf_update_6004() {
   }
 
   return $ret;
-}
-
-/**
- * Adding {emf_request}.fails column.
- */
-function emf_update_6005() {
-  $return = array();
-  db_add_field($return, 'emf_request', 'fails', array(
-    'description' => 'Number of failed attempt(s) to push the request to the service.',
-    'type' => 'int',
-    'not null' => TRUE,
-    'default' => 0
-  ));
-  return $return;
 }
\ No newline at end of file
diff --git a/emf.module b/emf.module
index b24d67f..c42f03b 100644
--- a/emf.module
+++ b/emf.module
@@ -1,4 +1,5 @@
 <?php
+// $Id$
 
 /**
  * @file
@@ -18,7 +19,7 @@ function emf_perm() {
   $permissions = array();
 
   $permissions[] = 'administer lists';
-  $permissions[] = 'view emf reports';
+  $permissions[] = 'view reports';
 
   return $permissions;
 }
@@ -122,7 +123,7 @@ function emf_menu() {
     'title' => 'E-mail Marketing Framework',
     'description' => 'View your e-mail marketing service subscriber and request reports.',
     'page callback' => 'emf_reports_subscriptions',
-    'access arguments' => array('view emf reports'),
+    'access arguments' => array('view reports'),
     'file' => 'emf.reports.inc',
   );
   $items['admin/reports/emf/subscriptions'] = array(
@@ -135,7 +136,7 @@ function emf_menu() {
     'page callback' => 'emf_reports_requests',
     'type' => MENU_LOCAL_TASK,
     'weight' => 1,
-    'access arguments' => array('view emf reports'),
+    'access arguments' => array('view reports'),
     'file' => 'emf.reports.inc',
   );
 
@@ -281,6 +282,20 @@ function emf_block($op = 'list', $delta = 0, $edit = array()) {
  * Implementation of hook_user().
  */
 function emf_user($op, &$edit, &$user) {
+  /*Adding the after_update condition to update the user account and to save in the request table*/
+  if($op == 'after_update') {
+    $mail = $user->mail;
+	
+	//deleting all pending requests
+	db_query("DELETE FROM {emf_request} WHERE mail = '%s'",$mail);
+	
+	//update from all known lists
+    $lists = emf_db_get_lists();
+    foreach ($lists as $list) {
+	  $fields = emf_helpers_parse_field_values($list->lid, $user);
+	  emf_db_save_request('updateMember',$mail, $list->lid, $fields);
+	}
+  }
   if ($op == 'delete') {
     $mail = $user->mail;
 
diff --git a/emf.sync.inc b/emf.sync.inc
index dd02db0..644cd94 100644
--- a/emf.sync.inc
+++ b/emf.sync.inc
@@ -1,4 +1,5 @@
 <?php
+// $Id$
 
 /**
  * @file
@@ -171,25 +172,17 @@ function emf_sync_push_requests() {
     if ($request->type == 'subscribe') {
       $success = emf_plugin_invoke('subscribe', array($request->mail, $fields, $request->lid));
     }
-    else {
-      $success = emf_plugin_invoke('unsubscribe', array($request->mail, $request->lid));
-    }
-
-    // if push succeeded or failed too many times, request can be deleted
-    if ($success || $request->fails > variable_get('emf_max_request_fails', 5)) {
+	// Request type -> Update
+	if ($request->type == 'updateMember') {
+	  $success = emf_plugin_invoke('update',array($request->mail, $fields, $request->lid));
+	}
+    if($request->type == 'unsubscribe') {
+       $success = emf_plugin_invoke('unsubscribe', array($request->mail, $request->lid));
+     }
+
+    // if push succeeded, request can be deleted
+    if ($success) {
       emf_db_delete_request($request->mail, $request->lid);
-      if ($request->fails > variable_get('emf_max_request_fail', 5)) {
-        watchdog('emf', t('%type request to %list cancelled for %mail after @count failed push attempts.', array(
-          '%type' => $request->type,
-          '%list' => $list->name_clean,
-          '%mail' => $request->mail,
-          '@count' => $request->fails,
-        )), WATCHDOG_ERROR);
-      }
-    }
-    else {
-      $request->fails += 1;
-      emf_db_save_request($request->type, $request->mail, $request->lid, $request->fields, $request->fails);
     }
 
     // count up
@@ -211,18 +204,33 @@ function emf_sync_subscriptions() {
     // fetching subscriptions
     $subscribed = emf_plugin_invoke('get_subscribers_subscribed', array($last_sync, $lid));
     $unsubscribed = emf_plugin_invoke('get_subscribers_unsubscribed', array($last_sync, $lid));
-
+    $updated = emf_plugin_invoke('get_subscribers_updated', array($last_sync, $lid));
+	
     // check subscriptions
     if ($subscribed !== FALSE && count($subscribed) > 0) {
       foreach ($subscribed as $mail) {
         // if a request is pending for this address, ignore subscription status
         if (in_array($mail, $requests)) continue;
 
+		// Set the member account details
+		$fields = emf_plugin_invoke('get_member_info', array($lid, $mail));
         // set address as subscripted to
-        emf_db_save_subscription($mail, $lid);
+        //$fields['merges'] contains the data of an user
+        emf_db_save_subscription($mail, $lid, $fields['merges']);
       }
     }
-
+	//check updates
+	if ($updated !== FALSE && count($updated) > 0) {
+	  foreach ($updated as $mail) {
+	    //if a request is pending for this address, ignore update status
+		if (in_array($mail, $requests)) continue;
+		
+		// Set the member account details
+        $fields = emf_plugin_invoke('get_member_info', array($lid, $mail));
+		// set address as updated to
+		emf_db_save_update($mail, $lid, $fields['merges']);
+	  }
+	}
     // check unsubscriptions
     if ($unsubscribed !== FALSE && count($unsubscribed) > 0) {
       foreach ($unsubscribed as $mail) {
diff --git a/plugins/emf_mailchimp/emf_mailchimp.api.inc b/plugins/emf_mailchimp/emf_mailchimp.api.inc
index a2171b9..a07f2e6 100644
--- a/plugins/emf_mailchimp/emf_mailchimp.api.inc
+++ b/plugins/emf_mailchimp/emf_mailchimp.api.inc
@@ -1,4 +1,5 @@
 <?php
+// $Id$
 
 /**
  * @file
@@ -33,7 +34,32 @@ function emf_mailchimp_api_subscribe($email, $fields, $lid) {
 
   return TRUE;
 }
+/**
+ * Update a user to a list.
+ *
+ * @param $email
+ *   String; E-mail address to update
+ * @param $fields
+ *   Array; Array of custom field values. Key is field. Value is value for the field.
+ * @param $lid
+ *   String; List ID of the list to update to.
+ * @return
+ *   Boolean; TRUE if user is updated. If not the user is subscribed.
+ */
+function emf_mailchimp_api_update($email, $fields, $lid) {
+  // mailchimp update can't handle blank merge_var arrays
+  if (empty($fields)) {
+    $fields = array('');
+  }
 
+  // do api call
+  $result = _emf_mailchimp_api_call('listUpdateMember', array($lid, $email, $fields));
+  if (!$result) {
+    return emf_mailchimp_api_subscribe($email, $fields, $lid);
+  }
+  
+  return TRUE;
+}
 /**
  * Unsubscribe a user from a list.
  *
@@ -80,7 +106,19 @@ function emf_mailchimp_api_get_subscribers_subscribed($date = 0, $lid = NULL) {
 function emf_mailchimp_api_get_subscribers_unsubscribed($date = 0, $lid = NULL) {
   return _emf_mailchimp_api_get_subscribers_active($date, $lid, 'unsubscribed');
 }
-
+/**
+  * Fetch Updated subscribers from API
+  *
+  * @param $date
+  *   Mixed; If a string, should be in the date() format of 'Y-m-d H:i:s', otherwise, a Unix timestamp.
+  * @param $lid
+  *   String; List ID
+  * @return
+  *   Array; List of subscriber lists
+  */
+function emf_mailchimp_api_get_subscribers_updated($date = 0, $lid = NULL) {
+  return _emf_mailchimp_api_get_subscribers_active($date, $lid, 'updated');
+}
 /**
  * Fetch subscribers from API.
  *
@@ -111,7 +149,20 @@ function emf_mailchimp_api_get_lists() {
 
   return _emf_mailchimp_api_get_array_call('lists', array(), $fields, 'lid');
 }
-
+/**
+  * Get all the information for particular members of a list from API
+  *
+  * @param $lid
+  *    String; List ID of the list.
+  * @param $mail
+  *    String; Mail of the member
+  * @return 
+  *    Array; List MergeVars values of specified member.
+  */
+function emf_mailchimp_api_get_member_info($lid, $mail){
+  $result = _emf_mailchimp_api_call('listMemberInfo', array($lid, $mail));
+  return $result;
+}
 /**
  * Fetch custom fields for some list from API.
  *
@@ -195,9 +246,7 @@ function _emf_mailchimp_api_get_array_call($method, $params, $fields, $key = NUL
   foreach ($results as $result) {
     $object = new stdClass();
     foreach ($fields as $local_field => $api_field) {
-      if (isset($result[$api_field])) {
-        $object->{$local_field} = $result[$api_field];
-      }
+      $object->{$local_field} = $result[$api_field];
     }
     if ($key) {
       $items[$object->{$key}] = $object;
-- 
1.7.4.msysgit.0

