}
-/*
- public function importContactImages()
- {
- require_once(GLM_MEMBERS_PLUGIN_PATH.'/models/admin/ajax/imageUpload.php');
- $ImageUpload = new GlmMembersAdmin_ajax_imageUpload($this->wpdb, $this->config);
- // get all events with images
- $sql = "
- SELECT id,image,old_event_id
- FROM " . GLM_MEMBERS_EVENTS_PLUGIN_DB_PREFIX. "events
- WHERE image != '' AND image IS NOT NULL";
- $results = $this->wpdb->get_results($sql, ARRAY_A);
- echo '<pre>$results: ' . print_r($results, true) . '</pre>';
- $imgUrl = 'http://is0.gaslightmedia.com/discoverkalamazoo/CKImage/';
- foreach ( $results as $event ) {
- $imageFullUrl = $imgUrl . $event['image'];
- $res = $ImageUpload->storeImage($imageFullUrl);
-
- if ( $res['newFileName'] ) {
- $this->wpdb->update(
- GLM_MEMBERS_EVENTS_PLUGIN_DB_PREFIX . 'events',
- array(
- 'image' => $res['newFileName']
- ),
- array( 'id' => $event['id'] ),
- array( '%s' ),
- array( '%d' )
- );
- }
- }
- }
-*/
-
/**
* modelAction
*
public function modelAction($actionData = false)
{
-/*
- $option = false;
- $testResult = false;
- $importResult = false;
- $settingsUpdated = false;
- $settingsUpdateError = false;
- $eventsSettings = false;
+ $option = 'importSetup';
+ $importResult = array(
+ 'status' => false,
+ 'exceptionTable' => false
+ );
+ $errorMsg = false;
+ $db_host = false;
+ $db_name = false;
+ $db_user = false;
+ $db_password = false;
+
if (isset($_REQUEST['option'])) {
$option = $_REQUEST['option'];
switch ($option) {
- case 'tests':
-
- $test = false;
- if (isset($_REQUEST['test'])) {
- $test = $_REQUEST['test'];
- }
+ case 'doDbImport':
- switch ($test) {
+ // Get database parameters
+ $db_host = filter_var( $_REQUEST['db_host'], FILTER_SANITIZE_STRING );
+ $db_name = filter_var( $_REQUEST['db_name'], FILTER_SANITIZE_STRING );
+ $db_user = filter_var( $_REQUEST['db_user'], FILTER_SANITIZE_STRING );
+ $db_password = filter_var( $_REQUEST['db_password'], FILTER_SANITIZE_STRING );
- case 'recurrence':
+ // Connect to the database, if false, we failed, so redisplay form and error message
+ $error = $this->connectPostgresDb($db_host, $db_name, $db_user, $db_password);
+ if ($error != false) {
+ $errorMsg = $error;
+ $option = "importSetup";
+ break;
+ }
- $testResult = $this->testRecurrence();
+ // Delete current contact list if requested.
+ $this->checkContactDelete();
- break;
+ // Do contact import
+ $importResult = $this->importContacts();
- default:
- break;
+ // Check status and error message
+ if ($importResult['status'] == false) {
+ $option = "importSetup";
+ break;
}
- break;
-
- case 'eventImagesImport':
-
- $this->importEventImages();
+ $option = "importSetup";
break;
- case 'eventimport':
+ case 'doCsvImport':
- $import = false;
- if (isset($_REQUEST['import'])) {
- $import = filter_var( $_REQUEST['import'], FILTER_VALIDATE_BOOLEAN );
- }
- switch ($import) {
- case 'true':
- $importResult = '<pre>$_REQUEST: ' . print_r( $_REQUEST, true ) . '</pre>';
- $db_host = filter_var( $_REQUEST['db_host'], FILTER_SANITIZE_STRING );
- $db_name = filter_var( $_REQUEST['db_name'], FILTER_SANITIZE_STRING );
- $db_user = filter_var( $_REQUEST['db_user'], FILTER_SANITIZE_STRING );
- $db_password = filter_var( $_REQUEST['db_password'], FILTER_SANITIZE_STRING );
- $this->connectPostgresDb($db_host, $db_name, $db_user, $db_password);
-
- $this->settings = filter_var_array(
- $_REQUEST,
- array(
- 'schema' => FILTER_SANITIZE_STRING,
- 'cattablename' => FILTER_SANITIZE_STRING,
- 'tablename' => FILTER_SANITIZE_STRING,
- 'sdate' => array(
- 'filter' => FILTER_VALIDATE_REGEXP,
- 'options' => array(
- 'regexp' => '%[0-9]{2}/[0-9]{2}/[0-9]{4}%'
- )
- )
+ $this->checkContactDelete();
- )
- );
- $importResult .= '<pre>$this->settings: ' . print_r($this->settings, true) . '</pre>';
- $this->addCategories();
- $importResult .= $this->addEvents();
-
- $importResult .= '<pre>$this->categories: ' . print_r($this->categories, true) . '</pre>';
-
-
- break;
- default:
- break;
- }
break;
- case 'settings':
-
+ case 'importSetup':
default:
- // Make sure option is set if default
- $option = 'settings';
-
- // Determine if current user can edit configurations
- if (!current_user_can('glm_members_management')) {
- return array(
- 'status' => false,
- 'menuItemRedirect' => 'error',
- 'modelRedirect' => 'index',
- 'view' => 'admin/error/index.html',
- 'data' => array(
- 'reason' => 'User does not have rights to make configuration changes.'
- )
- );
- }
-
- // Check for submission option
- $option2 = '';
- if (isset($_REQUEST['option2'])) {
- $option2 = $_REQUEST['option2'];
- }
-
- switch($option2) {
-
- // Update the settings and redisplay the form
- case 'submit':
-
- // Update the event management settings
- $eventsSettings = $this->updateEntry(1);
- if ($eventsSettings['status']) {
- $settingsUpdated = true;
- } else {
- $settingsUpdateError = true;
- }
-
- break;
-
- // Default is to get the current settings and display the form
- default:
-
- // Try to get the first (should be only) entry for general settings.
- $eventsSettings = $this->editEntry(1);
-
- if ($eventsSettings === false) {
-
- if (GLM_MEMBERS_PLUGIN_ADMIN_DEBUG) {
- glmMembersAdmin::addNotice("<b> /models/admin/management/events.php: Unable to load events management settings.", 'Alert');
- }
-
- }
-
- break;
-
- }
-
break;
}
-*/
// Compile template data
$templateData = array(
-/*
- 'option' => $option,
- 'testResult' => $testResult,
- 'importResult' => $importResult,
- 'settingsUpdated' => $settingsUpdated,
- 'settingsUpdateError' => $settingsUpdateError,
- 'eventsSettings' => $eventsSettings
-*/
+ 'option' => $option,
+ 'importResult' => $importResult,
+ 'errorMsg' => $errorMsg,
+ 'db_host' => $db_host,
+ 'db_name' => $db_name,
+ 'db_user' => $db_user,
+ 'db_password' => $db_password
);
// Return status, suggested view, and data to controller
* @param mixed $db_user
* @param mixed $db_password
* @access public
- * @return void
+ *
+ * @return string False if successful connection (no error), otherwise return error message
+ *
*/
public function connectPostgresDb($db_host, $db_name, $db_user, $db_password)
{
+
+ // Build connection string
$connStr = "pgsql:";
+
if ( $db_host ) {
$connPart[] = "host={$db_host}";
+ } else {
+ return 'Host name or IP address not provided.';
}
+
if ( $db_name ) {
$connPart[] = "dbname={$db_name}";
+ } else {
+ return 'Database name not provided.';
}
+
if ( $db_user ) {
$connPart[] = "user={$db_user}";
+ } else {
+ return 'Database user not specified.';
}
+
if ( $db_password ) {
$connPart[] = "password={$db_password}";
}
- if ( !empty($connPart) ) {
- $connStr .= implode( " ", $connPart );
- }
+
+ $connStr .= implode( " ", $connPart );
+
$driverOptions = array(
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_BOTH,
);
+
+ // Try connecting to the database
try {
$this->dbh = new PDO($connStr, null, null, $driverOptions);
$this->dbh->setAttribute(
PDO::ATTR_ERRMODE,
PDO::ERRMODE_EXCEPTION
);
+
+ // If there's an error, return with the error message
} catch(PDOException $e) {
- echo '<pre>$e: ' . print_r($e, true) . '</pre>';
- wp_die();
+ return $e->getMessage();
}
+
+ // Must not be any errors, so return false
+ return false;
+ }
+
+ /**
+ * Check for request to delete contacts and, if requested, do so.
+ *
+ * This function checks the "import_clear_contacts" checkbox form field
+ * to determine if it should delete all existing contacts.
+ *
+ * @access public
+ * @return boolean True if contacts have been deleted, otherwise false
+ */
+ public function checkContactDelete()
+ {
+
+ // If there's a valid request to clear contacts
+ if (isset($_REQUEST['import_clear_contacts']) && $_REQUEST['import_clear_contacts'] == 'on') {
+
+ // Get list of contacts
+ $contacts = $this->getSimplified(false, true);
+
+ // Check if we have any existing contacts
+ if ($contacts) {
+
+ // For each contact found
+ reset($contacts);
+ foreach ($contacts as $c) {
+
+ // We should have data on WordPress user
+ $cWpUser = false;
+ if (isset($c['wpUser']['wpUserEmail']) && $c['wpUser']['wpUserEmail']) {
+ $cWpUser = $c['wpUser']['wpUserEmail'];
+ } elseif (isset($c['wpUser']['wpUserLogin']) && $c['wpUser']['wpUserLogin']) {
+ $cWpUser = $c['wpUser']['wpUserLogin'];
+ }
+
+ // If there's a WP user
+ if ($cWpUser) {
+
+ $wpUserID = $cWpUser->ID;
+ $userHasOtherRole = false;
+
+ // Check for other roles assigned to this user and remove our roles
+ foreach ($cWpUser->roles as $r) {
+
+ // Is this role not one of ours?
+ if (!in_array($r, $this->config['contact_role_wordpress'])) {
+
+ // Apparently not, so we need to keep the Wordpress user
+ $userHasOtherRole = true;
+
+ //Otherwise, this is one of our roles so we should remove it just in case the Wordpress user isn't deleted
+ } else {
+ $cWpUser->remove_role($r);
+ }
+
+ }
+
+ // If WordPress user doens't have a non-contact role, it should be deleted
+ if (!$userHasOtherRole) {
+
+ wp_delete_user($wpUserID);
+
+ // Otherwise we need to drop the user meta data we added to the WP user.
+ } else {
+ delete_user_meta($wpUserID, 'glmMembersContactID');
+ delete_user_meta($wpUserID, 'glmMembersContactActive');
+ }
+
+ }
+
+ // Delete the contact
+ $this->deleteEntry($c['id'], true);
+
+ }
+
+ }
+
+ // Say we deleted contacts
+ return true;
+
+ }
+
+ // We're not deleting contacts, so return false
+ return false;
+
}
/**
- * addContacts
+ * importContacts
*
* Start with contacts tables. ( delete all contact data )
* Grab all contacts
* Enter them into the new contact tables and as WordPress users as required.
*
* @access public
- * @return void
+ * @return array Results or false if no contacts to import
+ * array(
+ * 'errorMsg',
+ * 'exceptionTable',
+ * )
+ *
*/
- public function addContacts()
+ public function importContacts()
{
- return false;
- // clear the contactss tables first
- $this->wpdb->query( "DELETE FROM " . GLM_MEMBERS_EVENTS_PLUGIN_DB_PREFIX . "events" );
- $this->wpdb->query( "DELETE FROM " . GLM_MEMBERS_EVENTS_PLUGIN_DB_PREFIX . "recurrences" );
- $this->wpdb->query( "DELETE FROM " . GLM_MEMBERS_EVENTS_PLUGIN_DB_PREFIX . "times" );
- $this->wpdb->query( "DELETE FROM " . GLM_MEMBERS_EVENTS_PLUGIN_DB_PREFIX . "event_categories" );
- $this->wpdb->query( "DELETE FROM " . GLM_MEMBERS_EVENTS_PLUGIN_DB_PREFIX . "locations" );
- $Recurrences = new GlmDataEventsRecurrences($this->wpdb, $this->config);
- $return = '';
- $sql = "
- SELECT *
- FROM {$this->settings['schema']}.{$this->settings['tablename']}
- WHERE edate >= '{$this->settings['sdate']}'::DATE";
- //$sql .=" AND reacur ";
+
+
+ // Initialize our return status/data array
+ $ret = array(
+ 'status' => false,
+ 'errorMsg' => false,
+ 'numbContacts' => false,
+ 'numbImported' => 0,
+ 'numbWpUsersCreated' => 0,
+ 'exceptionTable' => array()
+ );
+
+ // Get list of contacts from specified database table
+ $sql = "
+ SELECT member_id, member_name, member_login, member_passwd, member_contact_email,
+ primary_contact, primary_contact_fname, primary_contact_lname
+ FROM members.member
+ WHERE member_login != '';
+ ";
try {
- $events = $this->dbh->query($sql)->fetchAll(PDO::FETCH_ASSOC);
- $return .= '<pre>$events: ' . print_r($events, true) . '</pre>';
- foreach ( $events as $event ) {
- $foundMemberId = $refType = null;
- if ( $event['member_id'] ) {
- // get the new member id
- $sql = "
- SELECT id
- FROM " . GLM_MEMBERS_PLUGIN_DB_PREFIX . "members
- WHERE old_member_id = '" . esc_sql( trim($event['member_id']) ) . "'";
- $foundMemberId = $this->wpdb->get_row($sql, ARRAY_A);
- if ( $foundMemberId ) {
- $foundMemberId = $foundMemberId['id'];
- $refType = $this->config['ref_type_numb']['Member'];
- }
- }
- var_dump($foundMemberId);
- // see if event is in there by old_event_id
- $sql = "
- SELECT id
- FROM " . GLM_MEMBERS_EVENTS_PLUGIN_DB_PREFIX . "events
- WHERE old_event_id = '" . esc_sql( trim($event['id']) ) . "'";
- $found = $this->wpdb->get_row($sql, ARRAY_A);
- //echo '<pre>$found: ' . print_r($found, true) . '</pre>';
- $intro = substr(strip_tags($event['descr']), 0, 250);
- if ( isset($found) ) {
- $this->wpdb->update(
- GLM_MEMBERS_EVENTS_PLUGIN_DB_PREFIX . 'events',
- array(
- 'status' => (($event['visable'])
- ? $this->config['status_numb']['Active']
- : $this->config['status_numb']['Inactive']),
- 'created' => $event['create_date'],
- 'updated' => $event['create_date'],
- 'approved' => $event['approved_date'],
- 'name' => $event['header'],
- 'intro' => $intro,
- 'descr' => $event['descr'],
- 'image' => $event['img'],
- 'cost' => $event['cost'],
- 'url' => $event['url'],
- 'ref_type' => $refType,
- 'ref_dest' => $foundMemberId,
- 'admin_name' => $event['admin_contact_name'],
- 'admin_org' => $event['admin_org_name'],
- 'admin_email' => $event['admin_email'],
- 'admin_phone' => $event['admin_phone'],
- 'contact_email' => $event['email'],
- 'contact_name' => $event['contact'],
- 'contact_phone' => $event['phone'],
- 'notes' => $event['notes'],
- 'hide_address' => $event['notes'],
- ),
- array( 'old_event_id' => $event['id'] ),
- array(
- '%d',
- '%s',
- '%s',
- '%s',
- '%s',
- '%s',
- '%s',
- '%s',
- '%s',
- '%s',
- '%d',
- '%d',
- '%s',
- '%s',
- '%s',
- '%s',
- '%s',
- '%s',
- '%s',
- '%s',
- '%s',
- ),
- array( '%d' )
- );
- $eventId = $found['id'];
- } else {
- $eventData = array(
- 'status' => (($event['visable'] == '1')
- ? $this->config['status_numb']['Active']
- : $this->config['status_numb']['Inactive']),
- 'created' => $event['create_date'],
- 'updated' => $event['create_date'],
- 'approved' => $event['approved_date'],
- 'name' => $event['header'],
- 'intro' => $intro,
- 'descr' => $event['descr'],
- 'image' => $event['img'],
- 'cost' => $event['cost'],
- 'url' => $event['url'],
- 'old_event_id' => $event['id'],
- 'ref_type' => $refType,
- 'ref_dest' => $foundMemberId,
- 'admin_name' => $event['admin_contact_name'],
- 'admin_org' => $event['admin_org_name'],
- 'admin_email' => $event['admin_email'],
- 'admin_phone' => $event['admin_phone'],
- 'contact_email' => $event['email'],
- 'contact_name' => $event['contact'],
- 'contact_phone' => $event['phone'],
- 'notes' => $event['notes'],
- 'hide_address' => $event['notes'],
+ $oldContacts = $this->dbh->query($sql)->fetchAll(PDO::FETCH_ASSOC);
+
+ // If there was a problem, return the error message
+ } catch(PDOException $e) {
+ $ret['errorMsg'] = 'There was an error getting contacts from the database: '.$e->getMessage();
+ return $ret;
+ }
+
+ $numbContacts = count($oldContacts);
+ $ret['numbContacts'] = $numbContacts;
+
+ // If there's no contacts returned, say so
+ if ($numbContacts == 0) {
+ $ret['errorMsg'] = 'No contacts were returned from the specified database.';
+ return $ret;
+ }
+
+ // 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];
+
+ // Instantiate member data class
+ require_once GLM_MEMBERS_PLUGIN_CLASS_PATH.'/data/dataMembers.php';
+ $Members = new GlmDataMembers($this->wpdb, $this->config);
+
+ // Do import for each old contact
+ foreach ($oldContacts as $c) {
+
+ $okToImport = true;
+
+ // Clean up member login to remove restricted characters
+ $memberLogin = preg_replace('/[^a-zA-Z0-9_-]+/', '', $c['member_login']);
+ if ($memberLogin != $c['member_login']) {
+
+ // Report that we're stripping illegal characters from the username
+ $ret['exceptionTable'][] = array(
+ 'exception' => 'Removed invalid characters from this contact\'s username:',
+ 'data' => $c['member_name']
+ .", Old member id = ".$c['member_id']
+ .", Username = ".$memberLogin." - was ".$c['member_login']
+ );
+
+ $c['member_login'] = $memberLogin;
+ }
+
+ // Check that we have a username for this contact
+ if (trim($c['member_login']) == '') {
+ $okToImport = false;
+ }
+
+ if ($okToImport) {
+
+ // Check to see if the old contact ID matches one of the member's stored old IDs
+ $memb = $Members->getEntry(false, 'id', "T.old_member_id = ".$c['member_id']);
+
+ // If we match a member then we can proceed with the contact import
+ if ($memb) {
+
+ // Make sure there's no existing contact with this login ID
+ $matchingContact = $this->getSimplified("T.username = '".addslashes($c['member_login'])."'");
+
+ 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' => $c['member_name']
+ .", Old member id = ".$c['member_id']
+ .", Username = ".$c['member_login']
+ .", Matches existing member contact: ".$mc['fname']." ".$mc['lname']
);
- echo '<pre>$eventData: ' . print_r($eventData, true) . '</pre>';
- echo '</pre>';
- $this->wpdb->insert(
- GLM_MEMBERS_EVENTS_PLUGIN_DB_PREFIX . 'events',
- $eventData,
- array(
- '%d',
- '%s',
- '%s',
- '%s',
- '%s',
- '%s',
- '%s',
- '%s',
- '%s',
- '%s',
- '%d',
- '%d',
- '%d',
- '%s',
- '%s',
- '%s',
- '%s',
- '%s',
- '%s',
- '%s',
- '%s',
- '%s',
- )
- );
- $eventId = $this->wpdb->insert_id;
- //var_dump( $eventId );
- //echo '<pre>$eventId: from insert ' . print_r($eventId, true) . '</pre>';
- if ( !$eventId ) {
- echo '<pre>SQL Error: ' . $this->wpdb->last_error . '</pre>';
+ $okToImport = false;
}
- }
- // checking for $eventId
- //echo '<pre>$eventId: ' . print_r($eventId, true) . '</pre>';
- if (!$eventId) {
- die('something is wrong no eventId');
- }
- // generate the slug name for this new event
- $eventAbstract = new GlmDataEvents($this->wpdb, $this->config);
- $eventAbstract->updateSlug($eventId);
- // category for event
- if ( $event['topicid'] ) {
- $this->wpdb->insert(
- GLM_MEMBERS_EVENTS_PLUGIN_DB_PREFIX . 'event_categories',
- array(
- 'event' => $eventId,
- 'category' => $this->oldCatMap[$event['topicid']]
- ),
- array(
- '%d',
- '%d'
- )
- );
- }
- // recurrences for the event
- $allDates = $event['reacur'];
- if ( $allDates && ( $event['bdate'] == $event['edate'] ) ) {
- $allDates = 0;
- }
- $allDay = $event['all_day'];
- $dayOfWeek =
- $monthOfYear =
- $weekOfMonth =
- $byDayOfMonth =
- $lastDayOfMonth = null;
- if ( $allDates ) {
- if ( $event['daysow'] ) {
- $dayOfWeek = $event['daysow'];
- }
- if ( $event['weekom'] ) {
- switch ($event['weekom']) {
- case '1':
- $weekOfMonth = 1;
- break;
- case '2':
- $weekOfMonth = 2;
- break;
- case '3':
- $weekOfMonth = 4;
- break;
- case '4':
- $weekOfMonth = 8;
- break;
- case '5':
- $weekOfMonth = 16;
- break;
+
+ // 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($c['member_contact_email']) != '') {
+
+ $matchingContact = $this->getSimplified("email = '".addslashes($c['member_contact_email'])."'");
+ if ($matchingContact) {
+
+ $ret['exceptionTable'][] = array(
+ 'exception' => 'A member contact already exists with this E-Mail address:',
+ 'data' => $c['member_name']
+ .", Username = ".$c['member_login']
+ .", Old member id = ".$c['member_id']
+ .", E-Mail address = ".$c['member_contact_email']
+ ."<br>Contact created without an E-Mail address."
+ );
+
+ $c['member_contact_email'] = '';
}
- } else {
- $weekOfMonth = 63;
- }
- $monthOfYear = 4095;
- }
- $btime = $this->getTime($event['btime']);
- $etime = $this->getTime($event['etime']);
- $recurData =array(
- 'event' => $eventId,
- 'start_time' => $btime,
- 'end_time' => $etime,
- 'from_date' => $event['bdate'],
- 'to_date' => $event['edate'],
- 'all_day' => $allDay,
- 'recurring' => $allDates,
- 'month_of_year' => $monthOfYear,
- 'week_of_month' => $weekOfMonth,
- 'day_of_week' => $dayOfWeek,
- 'by_day_of_month' => $byDayOfMonth,
- 'last_day_of_month' => $lastDayOfMonth
- );
- //echo '<pre>' . print_r( $recurData, true) . '</pre>';
- echo '<pre>$recurData: ' . print_r($recurData, true) . '</pre>';
- $this->wpdb->insert(
- GLM_MEMBERS_EVENTS_PLUGIN_DB_PREFIX . 'recurrences',
- $recurData,
- array(
- '%d',
- '%s',
- '%s',
- '%s',
- '%s',
- '%d',
- '%d',
- '%d',
- '%d',
- '%d',
- '%d',
- '%d',
- )
- );
- $recurId = $this->wpdb->insert_id;
- $Recurrences->createRecurrenceTimesEntries( $recurId, true, true );
- // location for the event
- $hasLocation = (
- ($event['loc'])
- || ($event['contact'])
- || ($event['phone'])
- || ($event['url'])
- || ($event['email'])
- );
- if ( $hasLocation ) {
- $locationData = $locationFormat = array();
- $locationData['event'] = $eventId;
- $locationFormat[] = '%d';
- if ($event['loc']) {
- $locationData['name'] = $event['loc'];
- $locationFormat[] = '%s';
- }
- if ($event['address']) {
- $locationData['address'] = $event['address'];
- $locationFormat[] = '%s';
- }
- if ($event['city']) {
- $locationData['city'] = $this->getCityId( $event['city'] );
- $locationFormat[] = '%s';
- }
- if ($event['state']) {
- $locationData['state'] = $event['state'];
- $locationFormat[] = '%s';
- }
- if ($event['zip']) {
- $locationData['zip'] = $event['zip'];
- $locationFormat[] = '%s';
- }
- if ($event['lat']) {
- $locationData['lat'] = $event['lat'];
- $locationFormat[] = '%s';
- }
- if ($event['lon']) {
- $locationData['lon'] = $event['lon'];
- $locationFormat[] = '%s';
- }
- if ($event['contact']) {
- // break up the contact name db is expecting first and
- // last name separately
- list( $firstName, $lastName ) = explode( ' ', $event['contact'], 2 );
- $locationData['contact_fname'] = $firstName;
- $locationFormat[] = '%s';
- $locationData['contact_lname'] = $lastName;
- $locationFormat[] = '%s';
+
}
- if ($event['phone']) {
- $locationData['contact_phone'] = $event['phone'];
- $locationFormat[] = '%s';
+
+ // If contact has an E-Mail address
+ if (trim($c['member_contact_email']) != '') {
+
+ //Check if there's an existing WordPress user with this E-Mail address and a different username
+ $contactCheck = $this->checkContact($c['member_contact_email'], $c['member_login']);
+ 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' => $c['member_name']
+ .", Username = ".$c['member_login']
+ .", Old member id = ".$c['member_id']
+ .", E-mail address = ".$c['member_login']
+ );
+ $okToImport = false;
+ }
+
}
- if ($event['email']) {
- $locationData['contact_email'] = $event['email'];
- $locationFormat[] = '%s';
+
+ // If there's no problems so far
+ if ($okToImport) {
+
+ // If there's no contact names, use member name
+ if (trim($c['primary_contact_fname']) == '' && trim($c['primary_contact_lname']) == '') {
+ $c['primary_contact_fname'] = $memb['name'];
+ $c['primary_contact_lname'] = '(contact name not provided)';
+ }
+
+ // 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' => $c['primary_contact_fname'],
+ 'lname' => $c['primary_contact_lname'],
+ 'contact_type' => $contactType,
+ 'contact_role' => $contactRoleNumb,
+ 'email' => $c['member_contact_email'],
+ 'username' => preg_replace('/[^a-zA-Z0-9_-]+/', '', $c['member_login']),
+ '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' => $memb['id']
+ ),
+ array(
+ '%d',
+ '%d',
+ '%s',
+ '%s',
+ '%d',
+ '%d',
+ '%s',
+ '%s',
+ '%s',
+ '%s',
+ '%d',
+ '%d'
+ )
+ );
+ $newContactID = $this->wpdb->insert_id;
+
+ // If this contact didn't import correctly
+ if (!$newContactID) {
+ $ret['exceptionTable'][] = array(
+ 'exception' => 'Unable to create this contact: ',
+ 'data' => $c['member_name']
+ .", Old member id = ".$c['member_id']
+ .", E-mail address = ".$c['member_login']
+ .", Username = ".$c['member_login']
+ .", Name = ".$c['primary_contact_fname']." ".$c['primary_contact_lname']
+ );
+
+ // Put WordPress user stuff here.....
+
+
+ // Contact imported correctly, proceed with WordPress user
+ } else {
+
+ // Assemble needed user information. We've already verified that they have an E-Mail address.
+ $userEmail = $c['member_contact_email'];
+ $userLogin = false;
+ if (trim($c['member_login']) != '') {
+ $userLogin = trim($c['member_login']);
+ }
+ $userPass = false;
+ if (trim($c['member_passwd']) != '') {
+ $userPass = trim($c['member_passwd']);
+ } 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($c['primary_contact_fname']),
+ 'last_name' => trim($c['primary_contact_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' => $c['member_name']
+ .", Old member id = ".$c['member_id']
+ .", Member Name = ".$c['member_name']
+ .", Name = ".$c['primary_contact_fname']." ".$c['primary_contact_lname']
+ .", Username = ".$userLogin
+ ."<br>Error Message: ".$wpUserID->get_error_message()
+ );
+
+ }
+
+ $ret['numbImported']++;
+
+ }
+
}
- $this->wpdb->insert(
- GLM_MEMBERS_EVENTS_PLUGIN_DB_PREFIX . 'locations',
- $locationData,
- $locationFormat
+
+ // Imported contact did not match an existing member by old_member_id
+ } else {
+ $ret['exceptionTable'][] = array(
+ 'exception' => 'No member exists matching member for imported contact:',
+ 'data' => $c['member_name'].", Old member id = ".$c['member_id']
);
- $locationId = $this->wpdb->insert_id;
- if ( !$locationId ) {
- echo '<pre>$locationData: ' . print_r($locationData, true) . '</pre>';
- die('no return id for location');
- }
}
+
}
- } catch(PDOException $e) {
- echo '<pre>$e: ' . print_r($e, true) . '</pre>';
- die('end here');
}
- return $return;
+
+ // If it was OK to import contacts, consider this success - excptions in exceptionTable
+ if ($okToImport) {
+ $ret['status'] = true;
+ }
+
+ return $ret;
+
}
}