Updates for member and contact import.
authorSteve Sutton <steve@gaslightmedia.com>
Wed, 28 Dec 2016 21:56:55 +0000 (16:56 -0500)
committerSteve Sutton <steve@gaslightmedia.com>
Wed, 28 Dec 2016 21:56:55 +0000 (16:56 -0500)
Imports members with lat lon (added geocode)
Imports member contacts.

classes/helpers/GeocodeYahoo.php [new file with mode: 0644]
models/admin/management/csvimport.php

diff --git a/classes/helpers/GeocodeYahoo.php b/classes/helpers/GeocodeYahoo.php
new file mode 100644 (file)
index 0000000..55982be
--- /dev/null
@@ -0,0 +1,348 @@
+<?php
+/**
+ * Yahoo.php
+ *
+ * PHP versions 5
+ *
+ * @category  Toolkit
+ * @package   PackageName
+ * @author    Steve Sutton <steve@gaslightmedia.com>
+ * @copyright 2010 Gaslight Media
+ * @license   Gaslight Media
+ * @version   CVS: $Id: GeocodeYahoo.php,v 1.5 2010/01/19 15:58:32 jamie Exp $
+ * @link      <>
+ */
+
+/**
+ * Geocache Database Host
+ */
+define('GEOCODE_HOST', 'ds4');
+
+/**
+ * Geocache Database Name
+ */
+define('GEOCODE_DBNAME', 'geocache');
+
+/**
+ * Geocache Database User
+ */
+define('GEOCODE_USER', 'nobody');
+
+/**
+ * Yahoo Development App ID
+ */
+define(
+    'GEOCODE_YAHOO_APID',
+    'h69DBdrV34GpBHDfTOR1N7Pah70QbWNb1sBle2rneGflHOWNrCcbvp_Ddcx3D_hgLWKa1nDsHz0a8SBYxrSnS9PcuA--'
+);
+/**
+ * http_code for good response
+ */
+define('GEOCODE_YAHOO_REQUEST_GOOD', 200);
+
+/**
+ * http_code for bad response:
+ * Bad request. The parameters passed to the service
+ * did not match as expected. The Message should tell
+ * you what was missing or incorrect.
+ */
+define('GEOCODE_YAHOO_REQUEST_BAD', 400);
+
+/**
+ * http_code for request forbidden:
+ * Forbidden. You do not have permission to access this
+ * resource, or are over your rate limit.
+ */
+define('GEOCODE_YAHOO_REQUEST_FORBIDDEN', 403);
+
+/**
+ * Description for define:
+ * Service unavailable. An internal problem prevented us
+ * from returning data to you.
+ */
+define('GEOCODE_YAHOO_REQUEST_SERVICE_UNAVAILABLE', 503);
+
+/**
+ * geocode_Yahoo
+ *
+ * Very simple page that uses php Curl functions PHP5 to grab the result of
+ * yahoo geocoding
+ *
+ * @category  Toolkit
+ * @package   GeocodeYahoo
+ * @author    Steve Sutton <steve@gaslightmedia.com>
+ * @copyright 2010 Steve Sutton
+ * @license   Gaslight Media
+ * @version   Release: @package_version@
+ * @link      http://pear.php.net/package/geocode_Yahoo
+ * @see       References to other sections (if any)...
+ */
+class GeocodeYahoo
+{
+    /**
+     * Currently city and state are the only required variables
+     * that need to be in the address array
+     * 1) Serialized php variable returned directly from yahoo
+     * $response = array(
+     *    [ResultSet] => Array (
+     *        [Result] => Array (
+     *            [precision] => address
+     *            [Latitude] => 45.364991
+     *            [Longitude] => -84.958671
+     *            [Address] => 1231 Emmet St
+     *            [City] => Petoskey
+     *            [State] => MI
+     *            [Zip] => 49770-3014
+     *            [Country] => US
+     *        )
+     *    )
+     *  );
+     *
+     * @param array  $address array with street,city,state,zip
+     * @param string $output  xml or php (default)
+     *
+     * @return string Serialized php variable
+     * @access public
+     * @throws BadMethodCallException if missing 'city' in address parameter array
+     * @throws BadMethodCallException if missing 'state' in address parameter array
+     * @throws Exception if return http_code from curl is 400
+     * @throws Exception if return http_code from curl is 404
+     * @throws Exception if return http_code from curl is 403
+     * @throws Exception if return http_code from curl is 503
+     */
+    function geocodeAddress(array $address, $output = 'php')
+    {
+        if (!isset($address['city'])) {
+            throw new BadMethodCallException(
+                'Must include city in $address array'
+            );
+        } elseif (!isset($address['state'])) {
+//            throw new BadMethodCallException(
+//                'Must include state in $address array'
+//            );
+        }
+        $dsn = 'pgsql:host=' . GEOCODE_HOST
+            . ' dbname=' . GEOCODE_DBNAME
+            . ' user=' . GEOCODE_USER;
+        $driverOptions = array(
+            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
+        );
+        $dbh = new PDO($dsn, null, null, $driverOptions);
+        $dbh->query("SET DATESTYLE = 'SQL,US'");
+        try {
+            $sql = "
+            SELECT *
+              FROM geocode
+             WHERE street = :street
+               AND city = :city
+               AND state = :state
+               AND zip = :zip";
+            $stmt = $dbh->prepare($sql);
+            $stmt->bindParam(':street', $address['street']);
+            $stmt->bindParam(':city', $address['city']);
+            $stmt->bindParam(':state', $address['state']);
+            $stmt->bindParam(':zip', $address['zip']);
+            $stmt->execute();
+            $recordFound = $stmt->fetch();
+            if ($recordFound) {
+                $lastUpdateDate = strtotime($recordFound['last_update']);
+                if ($lastUpdateDate >= strtotime('-1 month')) {
+                    $response = array(
+                        'ResultSet' => array(
+                            'Result' => array(
+                                'Latitude' => $recordFound['lat'],
+                                'Longitude' => $recordFound['lon'],
+                                'Adress' => $recordFound['street'],
+                                'City' => $recordFound['city'],
+                                'State' => $recordFound['state'],
+                                'Zip' => $recordFound['zip']
+                            )
+                        )
+                    );
+                    return serialize($response);
+                }
+            }
+        } catch(PDOException $e) {
+            throw new Exception('Database Query failed');
+        }
+
+        $postFields = array(
+            'output' => $output,
+            'appid' => GEOCODE_YAHOO_APID,
+            'city' => $address['city'],
+            'state' => $address['state'],
+        );
+        if (isset($address['zip'])) {
+            $postFields['zip'] = $address['zip'];
+        }
+        if (isset($address['street'])) {
+            $postFields['street'] = $address['street'];
+        }
+
+        // start up curl session and send data to yahoo for geocoding
+        $ch = curl_init();
+//        $getUrl    = "http://where.yahooapis.com/geocode?";
+        $getUrl    = 'http://maps.googleapis.com/maps/api/geocode/json?sensor=false&';
+//        $getString = "q=";
+        $getString = 'address=';
+        if ($address['street']) {
+            $getString .= urlencode($address['street'].',');
+        }
+        if ($address['city']) {
+            $getString .= urlencode($address['city'].',');
+        }
+        if ($address['state']) {
+            $getString .= urlencode($address['state'].' ');
+        }
+        if ($address['zip']) {
+            $getString .= urlencode($address['zip']);
+        }
+        $getString .= "&flags=C";
+        $getString .= "&appid=".GEOCODE_YAHOO_APID;
+        $curlOptions = array(
+            CURLOPT_URL            => $getUrl . $getString,
+            CURLOPT_HEADER         => 0,
+            CURLOPT_RETURNTRANSFER => 1
+        );
+        curl_setopt_array($ch, $curlOptions);
+
+        // get response from yahoo
+        $response = curl_exec($ch);
+        // get info on curl response
+        $info     = curl_getinfo($ch);
+        // close curl session
+        curl_close($ch);
+
+        $jsonData = json_decode($response, true);
+        $data = array(
+            'ResultSet' => array(
+                'Result' => array(
+                    'Latitude'  => $jsonData['results'][0]['geometry']['location']['lat'],
+                    'Longitude' => $jsonData['results'][0]['geometry']['location']['lng'],
+                    'Adress'    => $address['street'],
+                    'City'      => $address['city'],
+                    'State'     => $address['state'],
+                    'Zip'       => $address['zip']
+                )
+            )
+        );
+//        echo '<pre>'.print_r($jsonData, true).'</pre>';
+//        echo '<pre>'.print_r($data, true).'</pre>';
+//        var_dump($info['http_code']);
+//        exit;
+
+        // if data returned form yahoo is good output data
+//        $p = xml_parser_create();
+//        xml_parse_into_struct($p, $response, $vals, $index);
+//        xml_parser_free($p);
+//
+//        $data = array(
+//            'ResultSet' => array(
+//                'Result' => array(
+//                    'Latitude'  => $vals[$index['LATITUDE'][0]]['value'],
+//                    'Longitude' => $vals[$index['LONGITUDE'][0]]['value'],
+//                    'Adress'    => $address['street'],
+//                    'City'      => $address['city'],
+//                    'State'     => $address['state'],
+//                    'Zip'       => $address['zip']
+//                )
+//            )
+//        );
+
+        switch ($info['http_code']) {
+        case GEOCODE_YAHOO_REQUEST_GOOD:
+            if ($recordFound) {
+                try {
+                    $sql = "
+                    UPDATE geocode
+                       SET last_update = current_date,
+                           lat = :lat,
+                           lon = :lon
+                     WHERE id = :id";
+                    $stmt = $dbh->prepare($sql);
+                    $stmt->bindParam(
+                        ':id',
+                        $recordFound['id'],
+                        PDO::PARAM_INT
+                    );
+                    $stmt->bindParam(
+                        ':lat',
+                        $data['ResultSet']['Result']['Latitude'],
+                        PDO::PARAM_INT
+                    );
+                    $stmt->bindParam(
+                        ':lon',
+                        $data['ResultSet']['Result']['Longitude'],
+                        PDO::PARAM_INT
+                    );
+                    $stmt->execute();
+                    return serialize($data);
+                } catch(PDOException $e) {
+                    throw new Exception('Failed');
+                }
+            }
+            try {
+                $sql = "
+                INSERT INTO geocode
+                (street,city,state,zip,lat,lon)
+                VALUES
+                (:street,:city,:state,:zip,:lat,:lon)";
+                $stmt = $dbh->prepare($sql);
+                $stmt->bindParam(':street', $address['street']);
+                $stmt->bindParam(':city', $address['city']);
+                $stmt->bindParam(':state', $address['state']);
+                $stmt->bindParam(':zip', $address['zip']);
+                $stmt->bindParam(
+                    ':lat',
+                    $data['ResultSet']['Result']['Latitude'],
+                    PDO::PARAM_INT
+                );
+                $stmt->bindParam(
+                    ':lon',
+                    $data['ResultSet']['Result']['Longitude'],
+                    PDO::PARAM_INT
+                );
+                $stmt->execute();
+                return serialize($data);
+            } catch(PDOException $e) {
+                throw new Exception('Query to insert failed');
+            }
+            break;
+
+        case GEOCODE_YAHOO_REQUEST_BAD:
+            throw new Exception(
+                'Bad request:
+                The parameters passed to the service did not match as expected.
+                The Message should tell you what was missing or incorrect.'
+                . 'Message:'
+                . $response
+            );
+            break;
+
+        case GEOCODE_YAHOO_REQUEST_FORBIDDEN:
+            throw new Exception(
+                'Forbidden:
+                You do not have permission to access this resource,
+                or are over your rate limit.'
+            );
+            break;
+
+        case GEOCODE_YAHOO_REQUEST_SERVICE_UNAVAILABLE:
+            throw new Exception(
+                'Service unavailable:
+                An internal problem prevented us from returning data to you.'
+            );
+            break;
+
+        default:
+            throw new Exception(
+                'Unkown Error:
+                An unknown Error code was returned'
+                . 'HTTP_CODE: '
+                . $info['http_code']
+            );
+            break;
+        }
+        return serialize($data);
+    }
+}
index bd6e7b7..936c4f8 100644 (file)
@@ -13,7 +13,7 @@
  * @version  0.1
  */
 
-/*
+/**
  * This class performs the work for the default action of the "Members" menu
  * option, which is to display the members dashboard.
  *
@@ -36,7 +36,7 @@ class GlmMembersAdmin_management_csvimport
      */
     public $config;
 
-    /*
+    /**
      * Constructor
      *
      * This contractor sets up this model. At this time that only includes
@@ -62,7 +62,7 @@ class GlmMembersAdmin_management_csvimport
         $scheme . $url : $url;
     }
 
-    /*
+    /**
      * Perform Model Action
      *
      * This method does the work for this model and returns any resulting data
@@ -115,7 +115,6 @@ class GlmMembersAdmin_management_csvimport
             // We're given a CSV file.
             // We need to parse it out. File must have header line.
             $file_data = $file_headers = $data = $members = array();
-            $resultMessage .= '<pre>$_FILES: ' . print_r( $_FILES, true ) . '</pre>';
 
             if ( isset( $_FILES ) && isset( $_FILES['file_upload'] ) && ( $fh = fopen( $_FILES['file_upload']['tmp_name'], 'r' ) ) !== false ) {
                 $row = 0;
@@ -131,7 +130,8 @@ class GlmMembersAdmin_management_csvimport
                 }
                 fclose( $fh );
             }
-            $resultMessage .= '<pre>$file_data: ' . print_r( $file_data, true ) . '</pre>';
+            $resultMessage .= $this->importMemberData( $file_data );
+            //$resultMessage .= '<pre>$file_data: ' . print_r( $file_data, true ) . '</pre>';
             break;
 
         default:
@@ -157,6 +157,17 @@ class GlmMembersAdmin_management_csvimport
 
     public function importMemberData( $data )
     {
+        // Reset the database
+        $this->resetDataTables();
+
+        // Instantiate member data class
+        require_once GLM_MEMBERS_PLUGIN_CLASS_PATH.'/data/dataMembers.php';
+        require_once GLM_MEMBERS_CONTACTS_PLUGIN_CLASS_PATH.'/data/dataContacts.php';
+        require_once GLM_MEMBERS_PLUGIN_CLASS_PATH.'/helpers/GeocodeYahoo.php';
+        $Members  = new GlmDataMembers( $this->wpdb, $this->config );
+        $Contacts = new GlmDataContacts( $this->wpdb, $this->config );
+        $geocoder = new GeocodeYahoo();
+
         // Get default member type
         $defaultMemberType    = $this->defaultMemberType();
         $numbMembersActive    = 0;
@@ -165,7 +176,9 @@ class GlmMembersAdmin_management_csvimport
         $membImportIssues     = '';
         $haveMembImportIssues = false;
         $dupeNames            = 0;
+        $members              = array();
 
+        // TODO: Need to add category for these members.
         // Loop through the data array of members.
         foreach ( $data as $key => $val ) {
             if ( $val['active'] == '1' ) {
@@ -178,116 +191,344 @@ class GlmMembersAdmin_management_csvimport
             }
 
             // Check for duplicate name
-            $membName = $val['member_name'];
+            $membName = preg_replace( '%[\\\]%', '', $val['member_name'] );
+            // Only add member if not already in database
+            // First is a check for the member in $namesInserted
             if ( isset( $namesInserted[$membName] ) ) {
                 // Bump dupe count and add to name to make this one unique
-                $dupeNames++;
-                $membName            .= ' DUPE-'.$dupeNames;
-                $membImportIssues    .= '<li>Member Duplicate <b>'.$membName.'</b></li>';
-                $haveMembImportIssues = true;
-            }
+                //$dupeNames++;
+                //$membName            .= ' DUPE-'.$dupeNames;
+                //$membImportIssues    .= '<li>Member Duplicate <b>'.$membName.'</b></li>';
+                //$haveMembImportIssues = true;
+            } else {
+                // Add main member record
+                $res = $this->wpdb->insert(
+                    GLM_MEMBERS_PLUGIN_DB_PREFIX.'members',
+                    array(
+                        'access'        => $access,
+                        'member_type'   => $defaultMemberType,
+                        'created'       => date('Y-m-d'),
+                        'name'          => $membName,
+                        'member_slug'   => sanitize_title($val['member_name']),
+                        'old_member_id' => $val['member_id']
+                    ),
+                    array(
+                        '%d',
+                        '%d',
+                        '%s',
+                        '%s',
+                        '%s',
+                        '%d'
+                    )
+                );
+                $members[$key]['new_id'] = $membID = $this->wpdb->insert_id;
 
-            // Add main member record
-            $res = $this->wpdb->insert(
-                GLM_MEMBERS_PLUGIN_DB_PREFIX.'members',
-                array(
-                    'access'        => $access,
-                    'member_type'   => $defaultMemberType,
-                    'created'       => date('Y-m-d'),
-                    'name'          => $membName,
-                    'member_slug'   => sanitize_title($val['member_name']),
-                    'old_member_id' => $val['member_id']
-                ),
-                array(
-                    '%d',
-                    '%d',
-                    '%s',
-                    '%s',
-                    '%s',
-                    '%d'
-                )
-            );
-            $member[$key]['new_id'] = $membID = $this->wpdb->insert_id;
-
-            // Add this member to the names inserted so we can check for duplicates
-            $namesInserted[$membName] = true;
-
-            // Create truncated short_descr from descriptions - Less tags, html encoded characters, newlines, tabs, etc.
-            $stripped = str_replace(
-                PHP_EOL,
-                '',
-                preg_replace(
-                    '/\t+/',
-                    '',
-                    preg_replace(
-                        "/&#?[a-z0-9]{2,8};/i",
-                        "",
-                        strip_tags( $val['description'] )
+                // Add this member to the names inserted so we can check for duplicates
+                $namesInserted[$membName] = $membID;
+
+                // Get the lat lon from the address
+                $address = array(
+                    'street' => $val['street'],
+                    'city'   => $val['city'],
+                    'state'  => 'MI',
+                    'zip'    => $val['zip'],
+                );
+                try {
+                    $response      = $geocoder->geocodeAddress( $address );
+                    $responseArray = unserialize($response);
+                    if ( isset($responseArray['ResultSet']['Result'][0]) && $responseArray['ResultSet']['Result'][0]['Latitude'] ) {
+                        $val['lat'] = $responseArray['ResultSet']['Result'][0]['Latitude'];
+                        $val['lon'] = $responseArray['ResultSet']['Result'][0]['Longitude'];
+                    } else {
+                        $val['lat'] = $responseArray['ResultSet']['Result']['Latitude'];
+                        $val['lon'] = $responseArray['ResultSet']['Result']['Longitude'];
+                    }
+                } catch ( BadMethodCallException $e ) {
+                    echo '<pre>$e: ' . print_r( $e, true ) . '</pre>';
+                } catch ( Exception $e ) {
+                    echo '<pre>$e: ' . print_r( $e, true ) . '</pre>';
+                }
+
+
+                // Insert Member Information Record
+                $res = $this->wpdb->insert(
+                    GLM_MEMBERS_PLUGIN_DB_PREFIX.'member_info',
+                    array(
+                        'member'         => $membID,
+                        'member_name'    => $val['member_name'],
+                        'status'         => $this->config['status_numb']['Active'],
+                        'reference_name' => 'Imported Member Information',
+                        'descr'          => '',
+                        'short_descr'    => '',
+                        'addr1'          => $val['street'],
+                        'addr2'          => '',
+                        'city'           => ( isset( $val['city'] ) ? $this->getCityId( $val['city'] ) : 0 ),
+                        'state'          => 'MI',
+                        'country'        => 'US',
+                        'zip'            => $val['zip'],
+                        'lat'            => ( isset( $val['lat'] ) ? $val['lat'] : null ),
+                        'lon'            => ( isset( $val['lon'] ) ? $val['lon'] : null ),
+                        'region'         => ( isset( $val['region'] ) ? $this->getRegionId( $val['region'] ) : 0 ),
+                        'phone'          => $val['phone'],
+                        'toll_free'      => '',
+                        'url'            => $val['url'],
+                        'email'          => $val['email'],
+                        'logo'           => '',
+                        'cc_type'        => 0,
+                        'notes'          => '',
+                        'create_time'    => null,
+                        'modify_time'    => null,
+                    ),
+                    array(
+                        '%d',
+                        '%s',
+                        '%d',
+                        '%s',
+                        '%s',
+                        '%s',
+                        '%s',
+                        '%s',
+                        '%d',
+                        '%s',
+                        '%s',
+                        '%s',
+                        '%f',
+                        '%f',
+                        '%d',
+                        '%s',
+                        '%s',
+                        '%s',
+                        '%s',
+                        '%s',
+                        '%d',
+                        '%s',
+                        '%s',
+                        '%s',
                     )
-                )
-            );
-            $short_descr = implode( ' ', array_slice( explode( ' ', $stripped ), 0, 30 ) );
-            if ( strlen( $short_descr ) < strlen( $stripped ) ) {
-                $short_descr .= ' ...';
+                );
+                $members[$key]['new_info_id'] = $infoID = $this->wpdb->insert_id;
+            } // End of member and info import.
+            // Start adding contacts.
+
+            // Determine contact type for import
+            $contactType = $this->config['contact_type_numb']['Personal'];
+
+            // Determine the Worpress Role to be used for contact import - Using Entity Manager right now
+            $contactRoleNumb = $this->config['contact_role_numb']['EntityManager'];
+            $wpRole = $this->config['contact_role_wordpress'][$contactRoleNumb];
+
+            if ( $membID ) {
+                $okToImport = true;
+                // Clean up member login to remove restricted characters
+                $memberLogin = preg_replace('/[^a-zA-Z0-9_-]+/', '', $val['username']);
+
+                if ( $memberLogin != $val['username'] ) {
+
+                    // Report that we're stripping illegal characters from the username
+                    $ret['exceptionTable'][] = array(
+                        'exception' => 'Removed invalid characters from this contact\'s username:',
+                        'data' => $val['member_name']
+                        .", Old member id = ".$val['member_id']
+                        .", Username = ".$memberLogin." - was ".$val['username']
+                    );
+
+                    $val['username'] = $memberLogin;
+                }
+
+                // Check that we have a username for this contact
+                if ( trim( $val['username'] ) == '' ) {
+                    $okToImport = false;
+                }
+
+                // Make sure there's no existing contact with this login ID
+                $matchingContact = $Contacts->getSimplified( "T.username = '".addslashes( $val['username'] )."'");
+
+                if ( $matchingContact ) {
+
+                    // Get the first result to use in the report below
+                    $mc = current( $matchingContact );
+
+                    // Tell us what went wrong
+                    $ret['exceptionTable'][] = array(
+                        'exception' => 'A member contact already exists with this Username',
+                        'data' => $val['member_name']
+                        .", Old member id = ".$val['member_id']
+                        .", Username = ".$val['username']
+                        .", Matches existing member contact: ".$mc['fname']." ".$mc['lname']
+                    );
+                    $okToImport = false;
+                }
+
+                // Make sure there's no existing contact with the imported E-Mail address (if there is one, don't use that email address)
+                if ( $okToImport && trim( $val['email'] ) != '' ) {
+
+                    $matchingContact = $Contacts->getSimplified( "email = '".addslashes($val['email'])."'" );
+                    if ( $matchingContact ) {
+
+                        $ret['exceptionTable'][] = array(
+                            'exception' => 'A member contact already exists with this E-Mail address:',
+                            'data' => $val['member_name']
+                                .", Username = ".$val['username']
+                                .", Old member id = ".$val['member_id']
+                                .", E-Mail address = ".$val['email']
+                                ."<br>Contact created without an E-Mail address."
+                        );
+
+                        $val['email'] = '';
+                    }
+
+                }
+                // If contact has an E-Mail address
+                if ( trim( $val['email'] ) != '' ) {
+
+                    // Check if there's an existing WordPress user with this E-Mail address and a different username
+                    $contactCheck = $Contacts->checkContact( $val['email'], $val['username'] );
+                    if ( $contactCheck['wordpressEmail'] && $contactCheck['wordpressLogin']
+                        && $contactCheck['wpUserEmail']->ID != $contactCheck['wpUserLogin']->ID ) {
+
+                        $ret['exceptionTable'][] = array(
+                            'exception' => 'A WordPress user exists with the E-Mail address of the imported contact but the username is different: ',
+                            'data' => $val['member_name']
+                                .", Username = ".$val['username']
+                                .", Old member id = ".$val['member_id']
+                                .", E-mail address = ".$val['username']
+                        );
+                        $okToImport = false;
+                    }
+
+                }
+                // If there's no problems so far
+                if ( $okToImport ) {
+
+                    // Try to create new contact
+                    $this->wpdb->insert(
+                        GLM_MEMBERS_CONTACTS_PLUGIN_DB_PREFIX . 'contacts',
+                        array(
+                            'active'       => true,
+                            'access'       => $this->config['access_numb']['NotDisplayedModerated'],
+                            'fname'        => $val['fname'],
+                            'lname'        => $val['lname'],
+                            'contact_type' => $contactType,
+                            'contact_role' => $contactRoleNumb,
+                            'email'        => $val['email'],
+                            'username'     => preg_replace('/[^a-zA-Z0-9_-]+/', '', $val['username']),
+                            'notes'        => 'Imported from old Web site.',
+                            'create_time'  => date('Y-m-d H:i:s', time()),
+                            'ref_type'     => $this->config['ref_type_numb']['Member'],
+                            'ref_dest'     => $membID,
+                            'addr1'        => $val['street'],
+                            'city'         => ( isset( $val['city'] ) ? $this->getCityId( $val['city'] ) : 0 ),
+                            'state'        => 'MI',
+                            'zip'          => $val['zip'],
+                            'country'      => 'US',
+                            'office_phone' => $val['phone'],
+                            'url'          => $val['url'],
+                        ),
+                        array(
+                            '%d',
+                            '%d',
+                            '%s',
+                            '%s',
+                            '%d',
+                            '%d',
+                            '%s',
+                            '%s',
+                            '%s',
+                            '%s',
+                            '%d',
+                            '%d',
+                            '%s',
+                            '%s',
+                            '%s',
+                            '%s',
+                            '%s',
+                            '%s',
+                            '%s',
+                        )
+                    );
+                    $newContactID = $this->wpdb->insert_id;
+
+                    // If this contact didn't import correctly
+                    if (!$newContactID) {
+                        $ret['exceptionTable'][] = array(
+                            'exception' => 'Unable to create this contact: ',
+                            'data' => $val['member_name']
+                                .", Old member id = ".$val['member_id']
+                                .", E-mail address = ".$val['username']
+                                .", Username = ".$val['username']
+                                .", Name = ".$val['fname']." ".$val['lname']
+                        );
+
+                    // Contact imported correctly, proceed with WordPress user
+                    } else {
+
+                        // Assemble needed user information. We've already verified that they have an E-Mail address.
+                        $userEmail = $val['email'];
+                        $userLogin = false;
+                        if ( trim( $val['username'] ) != '') {
+                            $userLogin = trim( $val['username'] );
+                        }
+                        $userPass = false;
+                        if ( trim( $val['password'] ) != '' ) {
+                            $userPass = trim( $val['password'] );
+                        } else {
+                            $userPass = wp_generate_password( $length=12, $include_standard_special_chars=false );
+                        }
+
+                        // Try to create the WordPress user
+                        $wpUserID = wp_insert_user(
+                            array(
+                                'user_email' => $userEmail,
+                                'user_login' => $userLogin,
+                                'user_pass'  => $userPass,
+                                'first_name' => trim( $val['fname'] ),
+                                'last_name'  => trim( $val['lname'] ),
+                                'role'       => $wpRole
+                            )
+                        );
+
+                        // If the result is an integer that's positive, the user was created
+                        if ( is_int( $wpUserID ) && $wpUserID > 0 ) {
+
+                            // Store the contact ID and active status into user meta data
+                            update_user_meta( $wpUserID, 'glmMembersContactID', $newContactID );
+                            update_user_meta( $wpUserID, 'glmMembersContactActive', true );
+
+                            $ret['numbWpUsersCreated']++;
+
+                        // Else, add a an entry to the exception table for why
+                        } else {
+
+                            $ret['exceptionTable'][] = array(
+                                'exception' => 'Unable to add a WordPress user for this contact: ',
+                                'data' => $val['member_name']
+                                    .", Old member id = ".$val['member_id']
+                                    .", Member Name = ".$val['member_name']
+                                    .", Name = ".$val['fname']." ".$val['lname']
+                                    .", Username = ".$userLogin
+                                    ."<br>Error Message: ".$wpUserID->get_error_message()
+                            );
+
+                        }
+
+                        $ret['numbImported']++;
+
+                    }
+
+                }
             }
-            // Insert Member Information Record
-            $res = $this->wpdb->insert(
-                GLM_MEMBERS_PLUGIN_DB_PREFIX.'member_info',
-                array(
-                    'member'         => $membID,
-                    'member_name'    => $val['member_name'],
-                    'status'         => $this->config['status_numb']['Active'],
-                    'reference_name' => 'Imported Member Information',
-                    'descr'          => preg_replace('%[\n\r]%', '', $val['description']),
-                    'short_descr'    => $short_descr,
-                    'addr1'          => $val['street'],
-                    'addr2'          => '',
-                    'city'           => ( isset( $val['city'] ) ? $this->getCityId( $val['city'] ) : 0 ),
-                    'state'          => 'MI',
-                    'country'        => 'US',
-                    'zip'            => $val['zip'],
-                    'lat'            => $val['lat'],
-                    'lon'            => $val['lon'],
-                    'region'         => ( isset( $val['region'] ) ? $this->getRegionId( $val['region'] ) : 0 ),
-                    'phone'          => $val['phone'],
-                    'toll_free'      => $val['toll_free'],
-                    'url'            => $val['url'],
-                    'email'          => $val['process_email'],
-                    'logo'           => '',
-                    'cc_type'        => 0,
-                    'notes'          => '',
-                    'create_time'    => $val['create_date'],
-                    'modify_time'    => $val['last_update']
-                ),
-                array(
-                    '%d',
-                    '%s',
-                    '%d',
-                    '%s',
-                    '%s',
-                    '%s',
-                    '%s',
-                    '%s',
-                    '%d',
-                    '%s',
-                    '%s',
-                    '%s',
-                    '%f',
-                    '%f',
-                    '%d',
-                    '%s',
-                    '%s',
-                    '%s',
-                    '%s',
-                    '%s',
-                    '%d',
-                    '%s',
-                    '%s',
-                    '%s'
-                )
-            );
-            $member[$key]['new_info_id'] = $infoID = $this->wpdb->insert_id;
+
         }
+        $results  = '<pre>';
+        $results .= "members imported: " . count( $members ) . "\n";
+        $results .= "membImportIssues: $membImportIssues\n";
+        $results .= "haveMembImportIssues: $haveMembImportIssues\n";
+        $results .= "dupeNames: $dupeNames\n";
+        $results .= '<pre>Contacts: ' . print_r( $ret, true ) . '</pre>';
+        //$results .= '<pre>$namesInserted: ' . print_r( $namesInserted, true ) . '</pre>';
+        //$results .= '<pre>$members: ' . print_r( $members, true ) . '</pre>';
+        $results .= '</pre>';
+        return $results;
     }
 
     /**
@@ -386,4 +627,115 @@ class GlmMembersAdmin_management_csvimport
             return $this->wpdb->insert_id;
         }
     }
+    /**
+     * resetDataTables
+     *
+     * @access public
+     * @return void
+     */
+    public function resetDataTables()
+    {
+        // Reset the database
+        if ( !$this->deleteDataTables() ) {
+            glmMembersAdmin::addNotice(
+                '<b>Unable to delete the database tables while resetting the database.</b><br>',
+                'AdminError'
+            );
+            break;
+        }
+        if ( !$this->createDataTables() ) {
+            glmMembersAdmin::addNotice( '<b>Unable to create the database tables while resetting the database.</b><br>', 'AdminError');
+            break;
+        }
+
+        glmMembersAdmin::addNotice('<b>Database tables have been reset in preparation importing members.</b><br>', 'AdminNotice');
+    }
+    /**
+     * Delete Members Database Tables
+     *
+     * @param string $dbVersion Current version of Members Database
+     *
+     * @return boolean
+     * @access public
+     */
+    public function deleteDataTables()
+    {
+        // Get current db version
+        $dbVersion = GLM_MEMBERS_PLUGIN_DB_VERSION;
+
+        // Read in Database deletion script - assumes the current db version.
+        $sqlFile = GLM_MEMBERS_PLUGIN_DB_SCRIPTS.'/drop_database_V'.$dbVersion.'.sql';
+        $sql = file_get_contents( $sqlFile );
+
+        // Replace {prefix} with table name prefix
+        $sql = str_replace('{prefix}', GLM_MEMBERS_PLUGIN_DB_PREFIX, $sql);
+
+        if ( GLM_MEMBERS_PLUGIN_ADMIN_DEBUG ) {
+            glmMembersAdmin::addNotice( 'Dropping all database tables', 'Process' );
+            glmMembersAdmin::addNotice( $sql, 'DataBlock', 'Drop Tables SQL' );
+        }
+
+        // Removing the tables using the script
+        $this->wpdb->query($sql);
+
+        // If there's been an error, display in debug Alert
+        $queryError = $this->wpdb->last_error;
+        if ( $queryError ) {
+            glmMembersAdmin::addNotice(
+                '<b>Error when deleting database: Database tables may not have existed.</b><br>Check following message.<br>'.$queryError,
+                'AdminError'
+            );
+        }
+
+        return true;
+    }
+    /**
+     * Create Members Database Tables
+     *
+     * @param string $dbVersion Current version of Members Database
+     *
+     * @return boolean
+     * @access public
+     */
+    public function createDataTables()
+    {
+        // Get current db version
+        $dbVersion = GLM_MEMBERS_PLUGIN_DB_VERSION;
+
+        // Read in Database creation script
+        $sqlFile = GLM_MEMBERS_PLUGIN_DB_SCRIPTS.'/create_database_V'.$dbVersion.'.sql';
+        $sql = file_get_contents( $sqlFile );
+
+        // Replace {prefix} with table name prefix
+        $sql = str_replace( '{prefix}', GLM_MEMBERS_PLUGIN_DB_PREFIX, $sql );
+
+        // Split script into separate queries by looking for lines with only "---"
+        $queries = preg_split( '/^----$/m', $sql );
+
+        // Try executing all queries to build database
+        $qForDebug = '';
+        do {
+            $q = current( $queries );
+            $this->wpdb->query( $q );
+            $queryError = $this->wpdb->last_error;
+
+            if ( $queryError ) {
+                glmMembersAdmin::addNotice(
+                    '<b>Error when creating database: Database tables may already exist.</b><br>Check following message.<br>'.$queryError,
+                    'AdminError'
+                );
+                return false;
+            }
+            $qForDebug .= $queryError.$q;
+
+        } while ( $queryError == '' && next( $queries ) );
+
+        if ( GLM_MEMBERS_PLUGIN_ADMIN_DEBUG ) {
+            glmMembersAdmin::addNotice( 'Creating database tables', 'Process' );
+            glmMembersAdmin::addNotice( $qForDebug, 'DataBlock', 'Create Tables SQL' );
+        }
+
+        return true;
+
+    }
 }