From: Chuck Scott Date: Thu, 28 Apr 2016 17:24:40 +0000 (-0400) Subject: Encueue scripts only when needed, Contacts now importing X-Git-Tag: v1.0.8^2~9 X-Git-Url: http://cvs2.gaslightmedia.com/gitweb/?a=commitdiff_plain;h=883f047bc244fc671be1abc722534898e3a48761;p=WP-Plugins%2Fglm-member-db-contacts.git Encueue scripts only when needed, Contacts now importing --- diff --git a/classes/data/dataContacts.php b/classes/data/dataContacts.php index a1acb0e..6e08ada 100644 --- a/classes/data/dataContacts.php +++ b/classes/data/dataContacts.php @@ -72,6 +72,7 @@ class GlmDataContacts extends GlmDataAbstract * @access public */ public $fields = false; + public $postProcess = true; /** * Constructor @@ -347,7 +348,7 @@ class GlmDataContacts extends GlmDataAbstract 'field' => 'username', 'type' => 'text', 'required' => 'text', - 'use' => 'ni' + 'use' => 'nil' ), // User Name - display only @@ -441,8 +442,8 @@ class GlmDataContacts extends GlmDataAbstract public function entryPostProcessing($r, $a) { - // Only run these tests for list, get, edit, and delete - if (in_array($a, array('l', 'g', 'e', 'd', 'u'))) { + // Only run these tests for list, get, edit, and delete and only if $postProcess is true + if ($this->postProcess && in_array($a, array('l', 'g', 'e', 'd', 'u'))) { // Select proper table $table = GLM_MEMBERS_PLUGIN_DB_PREFIX.$this->config['ref_type_table'][$r['ref_type']['value']]; @@ -501,6 +502,11 @@ class GlmDataContacts extends GlmDataAbstract public function checkContact($email, $username = false) { + // Clean up username for WorkPress (no punctuation other than _ and - + if ($username != false) { + $username = preg_replace('/[^a-zA-Z0-9_-]+/', '', $username); + } + $r = array( 'wpUserEmail' => false, 'wordpressEmail' => false, @@ -512,11 +518,6 @@ class GlmDataContacts extends GlmDataAbstract 'active' => false ); - // If E-mail address is not supplied - if (trim($email) == '') { - return false; - } - // Check Wordpress $r['wpUserEmail'] = get_user_by( 'email', $email ); If ($r['wpUserEmail']) { @@ -528,12 +529,12 @@ class GlmDataContacts extends GlmDataAbstract } // Check Contacts - $contact = $this->wpdb->get_row("SELECT * FROM ".GLM_MEMBERS_CONTACTS_PLUGIN_DB_PREFIX . "contacts WHERE email = '$email';", ARRAY_A); + $contact = $this->wpdb->get_row("SELECT * FROM ".GLM_MEMBERS_CONTACTS_PLUGIN_DB_PREFIX . "contacts WHERE email = '".addslashes($email)."';", ARRAY_A); if ($contact !== null) { $r['contactsEmail'] = true; $r['active'] = ($r['active'] > 0); } - $contact = $this->wpdb->get_row("SELECT * FROM ".GLM_MEMBERS_CONTACTS_PLUGIN_DB_PREFIX . "contacts WHERE username = '$username';", ARRAY_A); + $contact = $this->wpdb->get_row("SELECT * FROM ".GLM_MEMBERS_CONTACTS_PLUGIN_DB_PREFIX . "contacts WHERE username = '".addslashes($username)."';", ARRAY_A); if ($contact !== null) { $r['contactsUsername'] = true; $r['active'] = ($r['active'] > 0); @@ -543,8 +544,51 @@ class GlmDataContacts extends GlmDataAbstract } + /** + * Get simplified list + * + * @param string $where + * @param boolean Flag indicating that WordPress user data is requested + * + * @return array Simplified contact list or false if nothing returned + */ + public function getSimplified($where = 'true', $wpData = false) + { + $savedFields = $this->fields; + $savedPostProcess = $this->postProcess; + + $this->postProcess = false; + $this->fields = array( + 'id' => $savedFields['id'], + 'fname' => $savedFields['fname'], + 'lname' => $savedFields['lname'], + 'email' => $savedFields['email'], + 'username' => $savedFields['username'] + ); + + $contacts = $this->getList($where); + + // If nothing returned + if (!$contacts) { + return false; + } + + // If wordpress user data is requested, check if there's a match for the Email and/or username for any WP user. + if ($wpData) { + foreach ($contacts as $c) { + $contacts[$c['id']]['wpUser'] = $this->checkContact($c['email'], $c['username']); + } + } + + $this->fields = $savedFields; + $this->postProcess = $savedPostProcess; + + return $contacts; + + } } + ?> \ No newline at end of file diff --git a/models/admin/management/contacts.php b/models/admin/management/contacts.php index a9b8d13..c1a9b84 100644 --- a/models/admin/management/contacts.php +++ b/models/admin/management/contacts.php @@ -98,38 +98,6 @@ class GlmMembersAdmin_management_contacts extends GlmDataContacts } -/* - 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 '
$results: ' . print_r($results, true) . '
'; - $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 * @@ -140,13 +108,17 @@ class GlmMembersAdmin_management_contacts extends GlmDataContacts 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']; @@ -154,150 +126,60 @@ class GlmMembersAdmin_management_contacts extends GlmDataContacts 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 = '
$_REQUEST: ' . print_r( $_REQUEST, true ) . '
'; - $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 .= '
$this->settings: ' . print_r($this->settings, true) . '
'; - $this->addCategories(); - $importResult .= $this->addEvents(); - - $importResult .= '
$this->categories: ' . print_r($this->categories, true) . '
'; - - - 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("  /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 @@ -323,385 +205,437 @@ class GlmMembersAdmin_management_contacts extends GlmDataContacts * @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 '
$e: ' . print_r($e, true) . '
'; - 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 .= '
$events: ' . print_r($events, true) . '
'; - 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 '
$found: ' . print_r($found, true) . '
'; - $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 '
$eventData: ' . print_r($eventData, true) . '
'; - echo ''; - $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 '
$eventId: from insert ' . print_r($eventId, true) . '
'; - if ( !$eventId ) { - echo '
SQL Error: ' . $this->wpdb->last_error . '
'; + $okToImport = false; } - } - // checking for $eventId - //echo '
$eventId: ' . print_r($eventId, true) . '
'; - 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'] + ."
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 '
' . print_r( $recurData, true) . '
'; - echo '
$recurData: ' . print_r($recurData, true) . '
'; - $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 + ."
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 '
$locationData: ' . print_r($locationData, true) . '
'; - die('no return id for location'); - } } + } - } catch(PDOException $e) { - echo '
$e: ' . print_r($e, true) . '
'; - 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; + } } diff --git a/models/admin/member/contacts.php b/models/admin/member/contacts.php index e016716..f43475b 100644 --- a/models/admin/member/contacts.php +++ b/models/admin/member/contacts.php @@ -173,6 +173,11 @@ class GlmMembersAdmin_member_contacts extends GlmDataContacts case 'addNew': + // Clean up username to be compatible with WordPress + if (isset($_REQUEST['username'])) { + $_REQUEST['username'] = preg_replace('/[^a-zA-Z0-9_-]+/', '', $_REQUEST['username']); + } + // Check for existing contact in Wordpress and Contacts $contactCheck = $this->checkContact($_REQUEST['email'], $_REQUEST['username']); @@ -192,7 +197,6 @@ class GlmMembersAdmin_member_contacts extends GlmDataContacts // Try to insert the new contact $this->contactInfo = $this->insertEntry(); - // If that was successful if ($this->contactInfo['status']) { @@ -219,7 +223,22 @@ class GlmMembersAdmin_member_contacts extends GlmDataContacts // Add appropriate user role $wpUser = new WP_User($contactCheck['wpUserEmail']->ID); - $wpUser->add_role($wpRole); + + /* + * If the current wp user is not an administrator, add their contact role + * + * Note that adding the contact role to an administrator limits the + * administrators capabilities. In otherwords, with multiple roles in + * WordPress it looks like all of the user's roles need to have a + * capability for it to be considered as set. Because of this we can't + * add the contact role or the administrator will be crippled. + */ + // + if (!in_array('administrator', $contactCheck['wpUserEmail']->roles)) { + $wpUser->add_role($wpRole); + } else { + + } $usingExistingWPContact = true; @@ -375,8 +394,8 @@ class GlmMembersAdmin_member_contacts extends GlmDataContacts // Otherwise we need to drop the user meta data we added to the WP user. } else { - delete_user_meta($userID->ID, 'glmMembersContactID'); - delete_user_meta($userID->ID, 'glmMembersContactActive'); + delete_user_meta($wpUser->ID, 'glmMembersContactID'); + delete_user_meta($wpUser->ID, 'glmMembersContactActive'); } // Return to list by falling through here. diff --git a/setup/adminTabs.php b/setup/adminTabs.php index 8bc578f..bd12f1c 100644 --- a/setup/adminTabs.php +++ b/setup/adminTabs.php @@ -56,7 +56,7 @@ if (apply_filters('glm_members_permit_admin_member_contacts_tab', true)) { function($addOnTabs) { $newTabs = array( array( - 'text' => 'Member Contacts', + 'text' => 'Contacts', 'menu' => 'member', 'action' => 'contacts' ) diff --git a/setup/permissions.php b/setup/permissions.php index f597909..4259939 100644 --- a/setup/permissions.php +++ b/setup/permissions.php @@ -118,23 +118,6 @@ add_filter('glm_members_locked_to_member_id', * Of course any of these may test more than one capability if that's desired. */ -// glm-member-db, Menu "Members" -add_filter('glm_members_menu_members', - function($permit) { - if (!$permit) { return false; } - return current_user_can('glm_members_view_any_member'); - } -); - -// glm-member-db, Menu "Member", use glm_members_menu_member - -// glm-member-db, Menu "Configure", use glm_members_menu_configure - -// glm-member-db, Menu "Management", use glm_members_menu_mangement - -// glm-member-db, Menu "Shortcodes", use glm_members_menu_shortcodes - - // glm-member-db, views/admin/members/index.html, Display config data warnings add_filter('glm_members_permit_admin_members_index_member_config_warning', function($permit) { diff --git a/views/admin/footer.html b/views/admin/footer.html new file mode 100644 index 0000000..6029dc1 --- /dev/null +++ b/views/admin/footer.html @@ -0,0 +1,11 @@ + + + + + + \ No newline at end of file diff --git a/views/admin/management/contacts.html b/views/admin/management/contacts.html index 7b9146f..22f6129 100644 --- a/views/admin/management/contacts.html +++ b/views/admin/management/contacts.html @@ -1,47 +1,109 @@ {include file='admin/management/header.html'} - +{if $errorMsg != false} +

Your import failed because ...

+

{$errorMsg}

+{/if} + +{if $importResult.status} +

Contact Import Results

+ + + + +
Number of contacts from old database:{$importResult.numbContacts}
Number of contacts imported:{$importResult.numbImported}
Number of contacts with WordPress users created:{$importResult.numbWpUsersCreated}
+ Return to Import Events +{else} + +

 Option 1: Import contacts from legacy site database.

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
 Please provide information on the database from which you will be importing data.
Host:
Database Name:
User:
Password:
Clear Contacts before Import: + + WARNING: This will permanently delete all existing contacts! +
 
+ +
+ +

 

- +

 Option 2: Import contacts from a CSV file.

+ +
+ + + - - {if $importResult} - - - - - {else} - - - - {/if} -
Return to Import Events
- {$importResult} -
- - - - - -
-
- Database to import from: - - - - - - - - -
- -
- -
+ + + + + + + + + + + + + + + + + +
  + (format specification or link to sample file here) +
Host:
Clear Contacts before Import: + + WARNING: This will permanently delete all existing contacts! +
 
+ + + +{/if} + +{if $importResult.exceptionTable} +
+

Import Exception Report

+ + {foreach $importResult.exceptionTable as $e} + + {/foreach} +
{$e.exception}{$e.data}
+
+{/if} + + +{include file='admin/footer.html'} + \ No newline at end of file