Updates for management of contact roles.
authorSteve Sutton <steve@gaslightmedia.com>
Thu, 26 Apr 2018 20:38:13 +0000 (16:38 -0400)
committerSteve Sutton <steve@gaslightmedia.com>
Thu, 26 Apr 2018 20:38:13 +0000 (16:38 -0400)
To be able to modify the wordpress user role and contact_role.

classes/data/dataContacts.php
setup/commonHooks.php

index 0b662a8..0a27159 100644 (file)
@@ -697,6 +697,45 @@ class GlmDataContacts extends GlmDataAbstract
 
     }
 
+    /**
+     * Given a contact id change the role of both the contact
+     * and the wordpress user assigned to that contact.
+     */
+    public function updateContactRole( $contact_id, $old_role, $new_role )
+    {
+        $user_id = $this->getWpUserId( $contact_id );
+        $wpUser  = get_user_by( 'id', $user_id );
+        $wpUser->remove_role( $old_role );
+        $wpUser->add_role( $new_role );
+    }
+
+    public function getContactIdByRefDest( $ref_dest )
+    {
+        return $this->wpdb->get_var(
+            $this->wpdb->prepare(
+                "SELECT id
+                   FROM " . GLM_MEMBERS_CONTACTS_PLUGIN_DB_PREFIX . "contacts
+                  WHERE ref_dest = %d",
+                $ref_dest
+            )
+        );
+    }
+
+    /**
+     * Find the wordpress user for a given contact.
+     */
+    public function getWpUserId( $contact_id )
+    {
+        if ( $contact_id = filter_var( $contact_id, FILTER_VALIDATE_INT ) ) {
+            return $this->wpdb->get_var(
+                "SELECT user_id
+                   FROM " . $this->wpdb->prefix . "usermeta
+                  WHERE meta_key = 'glmMembersContactID'
+                    AND meta_value = '$contact_id'"
+            );
+
+        }
+    }
 
 }
 
index 2907290..f78b67f 100644 (file)
@@ -64,4 +64,14 @@ add_filter( 'glm_contact_has_employees', function( $content, $member_id ){
     }
     return $employees;
 }, 10, 2 );
+
+add_filter( 'glm_contact_update_user_role_by_ref_dest', function( $content, $ref_dest, $old_role, $new_role ) {
+    require_once GLM_MEMBERS_CONTACTS_PLUGIN_CLASS_PATH . '/data/dataContacts.php';
+    $Contact = new GlmDataContacts( $this->wpdb, $this->config );
+    $contact_id = $Contact->getContactIdByRefDest( $ref_dest );
+    if ( $contact_id ) {
+        $Contact->updateContactRole( $contact_id, $old_role, $new_role );
+    }
+    return $content;
+}, 10, 4);
 ?>