diff --git a/ZeroBSCRM.php b/ZeroBSCRM.php index 39868147..cfbb30fa 100644 --- a/ZeroBSCRM.php +++ b/ZeroBSCRM.php @@ -3,7 +3,7 @@ * Plugin Name: Jetpack CRM * Plugin URI: https://jetpackcrm.com * Description: Jetpack CRM is the simplest CRM for WordPress. Self host your own Customer Relationship Manager using WP. - * Version: 6.8.6 + * Version: 6.8.7 * Author: Automattic - Jetpack CRM team * Author URI: https://jetpackcrm.com * Text Domain: zero-bs-crm @@ -26,7 +26,7 @@ // Plugin version. Single source of truth, bumped by the release tooling // (release.config.json "versionConstant"). ZeroBSCRM::VERSION reads from this, // so this define must be set before the autoloader loads that class below. -define( 'JPCRM_VERSION', '6.8.6' ); +define( 'JPCRM_VERSION', '6.8.7' ); // Enabling THIS will start LOGGING PERFORMANCE TESTS // NOTE: This will do for EVERY page load, so just add temporarily else adds rolling DRAIN on sys diff --git a/includes/ZeroBSCRM.AJAX.php b/includes/ZeroBSCRM.AJAX.php index 16c740f4..77812a5c 100644 --- a/includes/ZeroBSCRM.AJAX.php +++ b/includes/ZeroBSCRM.AJAX.php @@ -1101,7 +1101,7 @@ function ZeroBSCRM_accept_quote() { wp_send_json_error( array( 'access' => 1 ), 403, JSON_UNESCAPED_SLASHES ); } // Resolve IDs safely - $customer_id = (int) zeroBS_getCustomerIDWithEmail( $uinfo->user_email ); + $customer_id = jpcrm_portal_contact_id_for_user( get_current_user_id() ); $quote_contact_id = (int) $zbs->DAL->quotes->getQuoteContactID( $quoteID ); // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase,WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase // Both IDs must exist and match if ( $customer_id <= 0 || $quote_contact_id <= 0 || $customer_id !== $quote_contact_id ) { diff --git a/includes/ZeroBSCRM.Core.php b/includes/ZeroBSCRM.Core.php index 792b6ce6..fb3548ff 100644 --- a/includes/ZeroBSCRM.Core.php +++ b/includes/ZeroBSCRM.Core.php @@ -1181,6 +1181,9 @@ public function includes() { // Generic CRM exceptions require_once ZEROBSCRM_INCLUDE_PATH . 'class-crm-exception.php'; + // Which contact a WordPress user is (Client Portal identity). + require_once ZEROBSCRM_INCLUDE_PATH . 'jpcrm-portal-identity.php'; + // WordPress user integrations require_once ZEROBSCRM_INCLUDE_PATH . 'class-wordpress-user-integration.php'; diff --git a/includes/ZeroBSCRM.DAL3.Helpers.php b/includes/ZeroBSCRM.DAL3.Helpers.php index 08c0ec65..69ab392d 100644 --- a/includes/ZeroBSCRM.DAL3.Helpers.php +++ b/includes/ZeroBSCRM.DAL3.Helpers.php @@ -522,25 +522,11 @@ function zeroBSCRM_getClientPortalUserID( $cID = -1 ) { global $zbs; - // first lets check if a user already exists with that email.. - $email = $zbs->DAL->contacts->getContactEmail( $cID ); - if ( ! empty( $email ) ) { - $userID = email_exists( $email ); - if ( $userID != null ) { - // update_post_meta($cID, 'zbs_portal_wpid', $userID); - $zbs->DAL->contacts->addUpdateContactWPID( - array( - 'id' => $cID, - 'WPID' => $userID, - ) - ); - } - } else { - // no email in meta, but might be linked? - // $userID = get_post_meta($cID, 'zbs_portal_wpid', true); - $userID = $zbs->DAL->contacts->getContactWPID( $cID ); - } - return $userID; + // The user this contact is linked to. A user who merely has the contact's email + // address is not linked by looking: see includes/jpcrm-portal-identity.php. + $linked_user_id = (int) $zbs->DAL->contacts->getContactWPID( $cID ); // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase,WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase + + return $linked_user_id > 0 ? $linked_user_id : false; } return false; } @@ -626,6 +612,10 @@ function zeroBSCRM_createClientPortalUser( $cID = -1, $email = '', $passwordLeng ) ); + // The account was made for this contact, with the contact's email address, and its + // password goes to that address: there is nothing further for the user to confirm. + update_user_meta( $user_id, JPCRM_PORTAL_CONFIRMED_EMAIL_META, jpcrm_portal_normalise_email( $email ) ); + // any extra assigned role? (from settings) $extraRole = zeroBSCRM_getSetting( 'portalusers_extrarole' ); diff --git a/includes/ZeroBSCRM.DAL3.Obj.Contacts.php b/includes/ZeroBSCRM.DAL3.Obj.Contacts.php index fc993aad..3b7591da 100644 --- a/includes/ZeroBSCRM.DAL3.Obj.Contacts.php +++ b/includes/ZeroBSCRM.DAL3.Obj.Contacts.php @@ -2753,7 +2753,7 @@ public function addUpdateContact( $args = array() ) { */ if ( is_array( $do_not_overwrite_populated ) && count( $do_not_overwrite_populated ) > 0 && ! empty( $id ) && $id > 0 ) { - $existing_contact = $this->getContact( $id, array( 'withCustomFields' => false ) ); + $existing_contact = $this->getContact( $id, array( 'withCustomFields' => true ) ); if ( is_array( $existing_contact ) ) { @@ -3093,6 +3093,24 @@ public function addUpdateContact( $args = array() ) { ) ); + // tags, outside the limitedFields check below, for the same reason. + // + // An update that leaves blanks alone is a limitedFields update, and the + // tags the caller sent with it used to be dropped. They are added to the + // contact's tags here, never swapped for them: this path exists so that + // what a contact already has is kept. + if ( $do_not_update_blanks && isset( $limitedFields ) && is_array( $limitedFields ) && isset( $data['tags'] ) && is_array( $data['tags'] ) ) { // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase + + $this->addUpdateContactTags( + array( + 'id' => $id, + 'tag_input' => $data['tags'], + 'mode' => 'append', + ) + ); + + } + // if passing limitedFields instead of data, we ignore the following // this doesn't work, because data is in args default as arr // if (isset($data) && is_array($data)){ diff --git a/includes/ZeroBSCRM.DAL3.php b/includes/ZeroBSCRM.DAL3.php index 17310c48..d240098c 100644 --- a/includes/ZeroBSCRM.DAL3.php +++ b/includes/ZeroBSCRM.DAL3.php @@ -3788,6 +3788,13 @@ public function addUpdateTag( $args = array() ) { if ( ! isset( $data['name'] ) || empty( $data['name'] ) ) { return false; } + + // Tag names are plain text, whichever caller they arrive from. + $data['name'] = sanitize_text_field( $data['name'] ); + if ( '' === $data['name'] ) { + return false; + } + if ( empty( $data['slug'] ) ) { $potential_slug = sanitize_key( $data['name'] ); // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UndefinedVariable diff --git a/includes/ZeroBSCRM.ExternalSources.php b/includes/ZeroBSCRM.ExternalSources.php index 21443417..defc00a2 100644 --- a/includes/ZeroBSCRM.ExternalSources.php +++ b/includes/ZeroBSCRM.ExternalSources.php @@ -115,6 +115,10 @@ function jpcrm_get_external_source_info( $source_key ) { // Returns a simplified 1 line explanation of an external source function zeroBS_getExternalSourceTitle( $srcKey = '', $srcUID = '' ) { + // The ID is whatever the source gave us (an order number, an email address + // typed into a form), and is shown as text. + $srcUID = esc_html( (string) $srcUID ); // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase + // some old hard typed: switch ( $srcKey ) { @@ -165,12 +169,12 @@ function zeroBS_getExternalSourceTitle( $srcKey = '', $srcUID = '' ) { $name = $zbs->external_sources[ $srcKey ][0]; } - return ' ' . $name . ':
' . $srcUID . ''; + return ' ' . esc_html( $name ) . ':
' . $srcUID . ''; // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase } else { #} Generic for now - return ' ' . ucwords( str_replace( '_', ' ', $srcKey ) ) . ':
' . $srcUID . ''; + return ' ' . esc_html( ucwords( str_replace( '_', ' ', $srcKey ) ) ) . ':
' . $srcUID . ''; // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase } diff --git a/includes/ZeroBSCRM.FormatHelpers.php b/includes/ZeroBSCRM.FormatHelpers.php index e082b5b2..d73efed6 100644 --- a/includes/ZeroBSCRM.FormatHelpers.php +++ b/includes/ZeroBSCRM.FormatHelpers.php @@ -527,7 +527,7 @@ function zeroBSCRM_html_companyIntroSentence( $company ) { $return = ''; if ( isset( $company['email'] ) && ! empty( $company['email'] ) ) { $return .= __( 'Email:', 'zero-bs-crm' ); - $return .= ' ' . $company['email'] . '
'; + $return .= ' ' . esc_html( $company['email'] ) . '
'; } if ( is_array( $company ) && $company['created'] > 0 && isset( $company['created_date'] ) ) { diff --git a/includes/ZeroBSCRM.IntegrationFuncs.php b/includes/ZeroBSCRM.IntegrationFuncs.php index 3ad3b40e..e5d8ae94 100644 --- a/includes/ZeroBSCRM.IntegrationFuncs.php +++ b/includes/ZeroBSCRM.IntegrationFuncs.php @@ -58,6 +58,40 @@ function zeroBS_integrations_getCustomer( $externalSource = '', $externalID = '' return false; } +/** + * The contact fields a submission from the public may fill in but not replace. + * + * A form or donation that anyone can submit names a contact by its email + * address, without showing the address is theirs. So when the contact already + * exists, what was sent fills in fields that are empty and leaves the rest as + * they are. Tags are added to, and the source is recorded, as before. + * + * @param array $contact_data The contact data built from the submission. + * @param string $source Where it came from, e.g. 'jetpack_form'. + * @return string[] Keys of `$contact_data` to pass as `do_not_overwrite_populated`. + */ +function jpcrm_public_submission_fields_to_protect( $contact_data, $source ) { + + $fields = array_values( + array_diff( + array_keys( (array) $contact_data ), + array( 'email', 'externalSources', 'tags', 'tag_mode' ) + ) + ); + + /** + * Filters the contact fields a public submission may fill in but not replace. + * + * Returning an empty array restores the previous behaviour, where a submission + * replaced these fields on whichever contact held the email address. + * + * @param string[] $fields Field keys to protect. + * @param array $contact_data The contact data built from the submission. + * @param string $source Where it came from, e.g. 'jetpack_form'. + */ + return (array) apply_filters( 'jpcrm_public_submission_fields_to_protect', $fields, $contact_data, $source ); +} + /* |======================================= | zeroBS_integrations_addOrUpdateCustomer diff --git a/includes/ZeroBSCRM.Jetpack.php b/includes/ZeroBSCRM.Jetpack.php index 5bfc133f..182926c7 100644 --- a/includes/ZeroBSCRM.Jetpack.php +++ b/includes/ZeroBSCRM.Jetpack.php @@ -36,6 +36,26 @@ add_action( 'grunion_after_feedback_post_inserted', 'zero_bs_crm_capture_jetpack_form', 10, 4 ); +/** + * A value submitted through a Jetpack form, as the text to store on a contact. + * + * @param mixed $value The submitted value. Choice fields submit an array. + * @param bool $multi_line Whether to keep line breaks. + * @return string + */ +function jpcrm_jetpack_form_text_value( $value, $multi_line = false ) { + + if ( is_array( $value ) ) { + $value = implode( ', ', array_filter( $value, 'is_scalar' ) ); + } + + if ( ! is_scalar( $value ) ) { + return ''; + } + + return $multi_line ? sanitize_textarea_field( (string) $value ) : sanitize_text_field( (string) $value ); +} + /** * Creates a ZBS contact from a Jetpack form submission. * @@ -69,6 +89,9 @@ function zero_bs_crm_capture_jetpack_form( $post_id, $all_field_data, $is_spam, 'lastcontacted', 'created', 'aliases', + 'id', + 'wpid', + 'owner', ); /* @@ -92,10 +115,11 @@ function zero_bs_crm_capture_jetpack_form( $post_id, $all_field_data, $is_spam, } else { $contact_data[ $data_key ] = explode( ',', $field_data->value ); } + $contact_data[ $data_key ] = array_map( 'jpcrm_jetpack_form_text_value', $contact_data[ $data_key ] ); } elseif ( $field_data->get_attribute( 'type' ) === 'date' ) { $contact_data[ $data_key ] = jpcrm_date_str_wp_format_to_uts( $field_data->value, true ); } else { - $contact_data[ $data_key ] = $field_data->value; + $contact_data[ $data_key ] = jpcrm_jetpack_form_text_value( $field_data->value, $field_data->get_attribute( 'type' ) === 'textarea' ); } } } @@ -112,7 +136,7 @@ function zero_bs_crm_capture_jetpack_form( $post_id, $all_field_data, $is_spam, && ! empty( $field_data->value ) ) { // Use the first email field that's found. - $contact_data['email'] = $field_data->value; + $contact_data['email'] = jpcrm_jetpack_form_text_value( $field_data->value ); } if ( 'telephone' === $field_data->get_attribute( 'type' ) @@ -120,7 +144,7 @@ function zero_bs_crm_capture_jetpack_form( $post_id, $all_field_data, $is_spam, && ! empty( $field_data->value ) ) { // Use the first phone field that's found. - $contact_data['hometel'] = $field_data->value; + $contact_data['hometel'] = jpcrm_jetpack_form_text_value( $field_data->value ); } if ( 'name' === $field_data->get_attribute( 'type' ) @@ -128,7 +152,7 @@ function zero_bs_crm_capture_jetpack_form( $post_id, $all_field_data, $is_spam, && ! empty( $field_data->value ) ) { // Use the first name field that's found. - $name = explode( ' ', $field_data->value, 2 ); + $name = explode( ' ', jpcrm_jetpack_form_text_value( $field_data->value ), 2 ); $contact_data['fname'] = $name[0]; if ( ! empty( $name[1] ) ) { $contact_data['lname'] = $name[1]; @@ -142,6 +166,12 @@ function zero_bs_crm_capture_jetpack_form( $post_id, $all_field_data, $is_spam, return; } + // The contact is matched on this, and it becomes the ID of its source, so it has + // to be an email address whichever kind of field it was typed into. + if ( ! zeroBSCRM_validateEmail( $contact_data['email'] ) ) { + return; + } + // Add the external source. $contact_data['externalSources'] = array( array( @@ -190,10 +220,14 @@ function zero_bs_crm_capture_jetpack_form( $post_id, $all_field_data, $is_spam, //phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase $zbs->DAL->contacts->addUpdateContact( array( - 'data' => $contact_data, - 'automatorPassthrough' => $success_log, - 'fallBackLog' => $exists_log, - 'extraMeta' => $extra_meta, + 'data' => $contact_data, + 'automatorPassthrough' => $success_log, + 'fallBackLog' => $exists_log, + 'extraMeta' => $extra_meta, + // Anyone can submit the form, against any email address: fill in what an + // existing contact is missing, and leave what it has. + 'do_not_overwrite_populated' => jpcrm_public_submission_fields_to_protect( $contact_data, 'jetpack_form' ), + 'do_not_update_blanks' => true, ) ); } diff --git a/includes/ZeroBSCRM.MetaBoxes3.Companies.php b/includes/ZeroBSCRM.MetaBoxes3.Companies.php index d58a7dab..83e60579 100644 --- a/includes/ZeroBSCRM.MetaBoxes3.Companies.php +++ b/includes/ZeroBSCRM.MetaBoxes3.Companies.php @@ -266,6 +266,16 @@ public function save_data( $company_id, $company ) { } } + // Only an email address is kept as the company's email. The posted value is still + // slashed here; it is unslashed below, before it is stored. + $posted_email = isset( $dataArr['email'] ) ? stripslashes( (string) $dataArr['email'] ) : ''; // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase + if ( '' !== $posted_email && ! zeroBSCRM_validateEmail( $posted_email ) ) { + + // Say so, and leave the email as it was. + $this->update_invalid_email( $posted_email ); + $dataArr['email'] = $company_id > 0 ? (string) zeroBS_companyEmail( $company_id ) : ''; // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase + } + // now we check whether a user with this email already exists (separate to this company id), so we can warn them // ... that it wont have changed the email if ( isset( $dataArr['email'] ) && ! empty( $dataArr['email'] ) ) { @@ -394,6 +404,24 @@ public function updateMessage( $created = false ) { $zbs->pageMessages[] = $msg; } + /** + * Queue a notice saying the email entered for the company was not saved. + * + * @param string $invalid_email The value that was entered. + */ + public function update_invalid_email( $invalid_email ) { + global $zbs; + + $zbs->pageMessages[] = zeroBSCRM_UI2_messageHTML( // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase + 'info orange mini', + /* translators: %s: the email address that was entered. */ + sprintf( __( 'The company email specified (%s) is not valid.', 'zero-bs-crm' ), esc_html( $invalid_email ) ), + '', + 'address book outline', + 'companyUpdated' + ); + } + public function updateEmailDupeMessage( $otherCompanyID = -1 ) { global $zbs; @@ -508,7 +536,7 @@ public function html( $company, $metabox ) { #} Description $contactDesc = '' . __( 'Contact since', 'zero-bs-crm' ) . ' ' . zeroBSCRM_date_i18n( zeroBSCRM_getDateFormat(), $contact['createduts'], true, false ); if ( isset( $contact['email'] ) && ! empty( $contact['email'] ) ) { - $contactDesc .= '
' . $contact['email'] . ''; + $contactDesc .= '
' . esc_html( $contact['email'] ) . ''; // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase } ?> diff --git a/includes/ZeroBSCRM.Permissions.php b/includes/ZeroBSCRM.Permissions.php index 8e51b2e2..bf659bd2 100644 --- a/includes/ZeroBSCRM.Permissions.php +++ b/includes/ZeroBSCRM.Permissions.php @@ -1247,7 +1247,7 @@ function jpcrm_can_wp_user_view_object( $wp_user, $obj_id, $obj_type_id ) { } // verify current user is assigned user - $contact_id = zeroBS_getCustomerIDWithEmail( $wp_user->user_email ); + $contact_id = jpcrm_portal_contact_id_for_user( $wp_user->ID ); if ( $assigned_contact_id != $contact_id ) { return false; } diff --git a/includes/class-wordpress-user-integration.php b/includes/class-wordpress-user-integration.php index e4629243..129e11ff 100644 --- a/includes/class-wordpress-user-integration.php +++ b/includes/class-wordpress-user-integration.php @@ -61,127 +61,51 @@ public function wordpress_profile_update( $user_id, $old_user_data, $new_user_da // This var will be defined as JPCRM_PROFILE_UPDATE_CHANGES, which will allow WooSync's save_my_account_crm_field_changes to sidestep repeating changes $profile_update_changes = array(); - // retrieve id's + // The contact this user is. Only a user who has confirmed their email address, and + // is linked to the contact that has it, changes a contact from their profile. $old_user_contact_id = false; - $new_user_contact_id = false; $email_conflict = false; - if ( isset( $old_user_data->data->user_email ) ) { - // check if we have contacts with emails - $old_user_contact_id = $zbs->DAL->contacts->getContact( - -1, - array( - - 'email' => $old_user_data->data->user_email, - 'onlyID' => true, - 'ignoreowner' => zeroBSCRM_DAL2_ignoreOwnership( ZBS_TYPE_CONTACT ), - - ) - ); - - } - - if ( isset( $new_user_data['user_email'] ) ) { - - $new_user_contact_id = $zbs->DAL->contacts->getContact( - -1, - array( - - 'email' => $new_user_data['user_email'], - 'onlyID' => true, - 'ignoreowner' => zeroBSCRM_DAL2_ignoreOwnership( ZBS_TYPE_CONTACT ), - - ) - ); - - } + $old_email = isset( $old_user_data->data->user_email ) ? jpcrm_portal_normalise_email( $old_user_data->data->user_email ) : ''; + $new_email = isset( $new_user_data['user_email'] ) ? jpcrm_portal_normalise_email( $new_user_data['user_email'] ) : $old_email; - // Email change (For Client Portal Users & WooSync originated contacts) - if ( $old_user_data->data->user_email != $new_user_data['user_email'] ) { + if ( $old_email === $new_email ) { - // if we had a contact with this users email... - if ( $old_user_contact_id > 0 ) { + $old_user_contact_id = jpcrm_portal_contact_id_for_user( $user_id ); - // if we don't already have a contact with this new email (no collision) - if ( ! $new_user_contact_id ) { + } elseif ( jpcrm_portal_email_is_confirmed( $user_id ) ) { - // update contacts email address: - $zbs->DAL->contacts->update_contact_email( $old_user_contact_id, $new_user_data['user_email'] ); + // An administrator made the change, which confirms the new address: the contact + // has already followed it (see jpcrm_portal_admin_email_change_confirms()). + $old_user_contact_id = jpcrm_portal_contact_id_for_user( $user_id ); - // flag so woosync doesn't also update - $profile_update_changes[] = 'email'; - - // Add log noting the email change - $note_type = 'contact_changed_details_via_wpprofile'; - $short_description = __( 'Email changed', 'zero-bs-crm' ); - if ( $change_via_woo_account ) { - $note_type = 'contact_changed_details_via_woomyacc'; - } - $zbs->DAL->logs->addUpdateLog( - array( - - 'id' => -1, - 'owner' => -1, - 'data' => array( - - 'objtype' => ZBS_TYPE_CONTACT, - 'objid' => $old_user_contact_id, - 'type' => $note_type, // contact_changed_details_via_wpprofile or contact_changed_details_via_woomyacc - 'shortdesc' => $short_description, - 'longdesc' => sprintf( __( 'Contact email changed from `%1$s` to `%2$s`', 'zero-bs-crm' ), $old_user_data->data->user_email, $new_user_data['user_email'] ), - - ), - - ) - ); - - } else { - - // the email this contact has changed their email to is already in use - // on another contact :o - - // flag so that we don't also update the new users details below - $email_conflict = true; - - // Add a log to both contacts. - $short_description = __( 'Attempted email Change', 'zero-bs-crm' ); - $zbs->DAL->logs->addUpdateLog( - array( - - 'id' => -1, - 'owner' => -1, - 'data' => array( - - 'objtype' => ZBS_TYPE_CONTACT, - 'objid' => $old_user_contact_id, - 'type' => 'contact_change_details_attempt', - 'shortdesc' => $short_description, - 'longdesc' => sprintf( __( 'There was an attempt to change this contacts email from `%1$s` to `%2$s`, unfortunately this was not possible because another contact (#%3$d) already uses that email address.', 'zero-bs-crm' ), $old_user_data->data->user_email, $new_user_data['user_email'], $new_user_contact_id ), + // Flag so woosync doesn't also update. + $profile_update_changes[] = 'email'; - ), + } else { - ) - ); - $zbs->DAL->logs->addUpdateLog( - array( - - 'id' => -1, - 'owner' => -1, - 'data' => array( - - 'objtype' => ZBS_TYPE_CONTACT, - 'objid' => $new_user_contact_id, - 'type' => 'contact_change_details_attempt', - 'shortdesc' => $short_description, - 'longdesc' => sprintf( __( 'There was an attempt to change another contact\'s (#%1$d) email from `%2$s` to `%3$s`, this was not possible because this contact already uses that email address.', 'zero-bs-crm' ), $old_user_contact_id, $old_user_data->data->user_email, $new_user_data['user_email'] ), + // The user changed their own address. Their contact keeps the address it has until + // the new one is confirmed, and until then they are not that contact. + $previous_contact = false; + if ( jpcrm_portal_normalise_email( get_user_meta( $user_id, JPCRM_PORTAL_CONFIRMED_EMAIL_META, true ) ) === $old_email ) { + $previous_contact = jpcrm_portal_contact_with_email( $old_email ); + } - ), + if ( $previous_contact && (int) $previous_contact['wpid'] === (int) $user_id ) { - ) - ); + jpcrm_portal_identity_log( + $previous_contact['id'], + 'contact_change_details_attempt', + __( 'Email change awaiting confirmation', 'zero-bs-crm' ), + /* translators: 1: old email address, 2: new email address. */ + sprintf( __( 'The WordPress user for this contact changed their email from `%1$s` to `%2$s`. The contact keeps its email address until the new one is confirmed, and a confirmation email has been sent to it.', 'zero-bs-crm' ), $old_email, $new_email ) + ); - } + jpcrm_portal_send_email_confirmation( $user_id ); } + + // Flag so woosync doesn't also update. + $profile_update_changes[] = 'email'; } // First and last names are available in $new_user_data but not in old. diff --git a/includes/jpcrm-portal-identity.php b/includes/jpcrm-portal-identity.php new file mode 100644 index 00000000..9b32d8b7 --- /dev/null +++ b/includes/jpcrm-portal-identity.php @@ -0,0 +1,553 @@ +user_email ) : ''; +} + +/** + * Whether a user has confirmed the email address their account has now. + * + * @param int $user_id WordPress user ID. Defaults to the current user. + * @return bool + */ +function jpcrm_portal_email_is_confirmed( $user_id = 0 ) { + $user_id = $user_id ? (int) $user_id : get_current_user_id(); + $email = jpcrm_portal_user_email( $user_id ); + + if ( '' === $email ) { + return false; + } + + return jpcrm_portal_normalise_email( get_user_meta( $user_id, JPCRM_PORTAL_CONFIRMED_EMAIL_META, true ) ) === $email; +} + +/** + * The contact with this address as its own email, not as an alias. + * + * @param string $email An email address. + * @return array|false The contact, or false. + */ +function jpcrm_portal_contact_with_email( $email ) { + global $zbs; + + $email = jpcrm_portal_normalise_email( $email ); + if ( '' === $email ) { + return false; + } + + $contact = $zbs->DAL->contacts->getContact( // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase + -1, + array( + 'email' => $email, + 'withCustomFields' => false, + 'ignoreowner' => true, + ) + ); + + if ( ! is_array( $contact ) || jpcrm_portal_normalise_email( $contact['email'] ) !== $email ) { + return false; + } + + return $contact; +} + +/** + * The contact a WordPress user is, for the Client Portal and anywhere else a + * logged-in customer acts on their own record. + * + * @param int $user_id WordPress user ID. Defaults to the current user. + * @return int Contact ID, or 0 when the user is not (yet) any contact. + */ +function jpcrm_portal_contact_id_for_user( $user_id = 0 ) { + $user_id = $user_id ? (int) $user_id : get_current_user_id(); + + if ( $user_id < 1 || ! jpcrm_portal_email_is_confirmed( $user_id ) ) { + return 0; + } + + $contact = jpcrm_portal_contact_with_email( jpcrm_portal_user_email( $user_id ) ); + + if ( ! $contact ) { + return 0; + } + + // The link is kept in step with what has been proved. Syncs and imports also write + // it, on the strength of an email address alone, and can point it at another user. + if ( (int) $contact['wpid'] !== $user_id ) { + global $zbs; + + $zbs->DAL->contacts->addUpdateContactWPID( // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase + array( + 'id' => (int) $contact['id'], + 'WPID' => $user_id, + ) + ); + } + + return (int) $contact['id']; +} + +/** + * Add a line to a contact's activity log. + * + * @param int $contact_id Contact ID. + * @param string $type Log type. + * @param string $short Short description. + * @param string $description Long description. + * @return void + */ +function jpcrm_portal_identity_log( $contact_id, $type, $short, $description ) { + global $zbs; + + $zbs->DAL->logs->addUpdateLog( // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase + array( + 'id' => -1, + 'owner' => -1, + 'data' => array( + 'objtype' => ZBS_TYPE_CONTACT, + 'objid' => (int) $contact_id, + 'type' => $type, + 'shortdesc' => $short, + 'longdesc' => $description, + ), + ) + ); +} + +/** + * Record that a user's current email address is confirmed, and bring their + * contact into line with it. + * + * - A contact that has the confirmed address is linked to the user. + * - Otherwise, a contact the user was already confirmed for follows them to the + * new address. + * - When both exist, neither is changed: the user becomes the contact that has + * the address, and both records get a note for staff. + * + * @param int $user_id WordPress user ID. + * @param string[] $also_previously Further addresses the user's contact may still hold, besides the + * one they last confirmed, if it is to follow them. + * @return int The contact the user now is, or 0. + */ +function jpcrm_portal_mark_email_confirmed( $user_id, $also_previously = array() ) { + global $zbs; + + $user_id = (int) $user_id; + $email = jpcrm_portal_user_email( $user_id ); + + if ( '' === $email ) { + return 0; + } + + // The address they last confirmed comes first: that is the contact they were. + $previous_emails = array_merge( + array( get_user_meta( $user_id, JPCRM_PORTAL_CONFIRMED_EMAIL_META, true ) ), + (array) $also_previously + ); + + update_user_meta( $user_id, JPCRM_PORTAL_CONFIRMED_EMAIL_META, $email ); + delete_user_meta( $user_id, JPCRM_PORTAL_CONFIRMATION_META ); + + $contact_with_email = jpcrm_portal_contact_with_email( $email ); + + // The contact this user was, under the address they had confirmed before. + $previous_contact = false; + $previous_email = ''; + foreach ( $previous_emails as $candidate_email ) { + $candidate_email = jpcrm_portal_normalise_email( $candidate_email ); + if ( '' === $candidate_email || $candidate_email === $email ) { + continue; + } + $candidate = jpcrm_portal_contact_with_email( $candidate_email ); + if ( $candidate && (int) $candidate['wpid'] === $user_id ) { + $previous_contact = $candidate; + $previous_email = $candidate_email; + break; + } + } + + if ( $contact_with_email ) { + + if ( (int) $contact_with_email['wpid'] !== $user_id ) { + $zbs->DAL->contacts->addUpdateContactWPID( // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase + array( + 'id' => (int) $contact_with_email['id'], + 'WPID' => $user_id, + ) + ); + } + + if ( $previous_contact && (int) $previous_contact['id'] !== (int) $contact_with_email['id'] ) { + $short = __( 'Attempted email change', 'zero-bs-crm' ); + jpcrm_portal_identity_log( + $previous_contact['id'], + 'contact_change_details_attempt', + $short, + /* translators: 1: old email address, 2: new email address, 3: contact ID. */ + sprintf( __( 'The WordPress user for this contact changed their email from `%1$s` to `%2$s` and confirmed it. This contact was not changed, because another contact (#%3$d) already uses that email address. The user now signs in to the Client Portal as that contact.', 'zero-bs-crm' ), $previous_email, $email, (int) $contact_with_email['id'] ) + ); + jpcrm_portal_identity_log( + $contact_with_email['id'], + 'contact_change_details_attempt', + $short, + /* translators: 1: contact ID, 2: old email address, 3: new email address. */ + sprintf( __( 'The WordPress user for another contact (#%1$d) changed their email from `%2$s` to `%3$s`, which is this contact\'s email address, and confirmed it. The user now signs in to the Client Portal as this contact.', 'zero-bs-crm' ), (int) $previous_contact['id'], $previous_email, $email ) + ); + } + + return (int) $contact_with_email['id']; + } + + if ( $previous_contact ) { + + $zbs->DAL->contacts->update_contact_email( (int) $previous_contact['id'], $email ); // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase + + jpcrm_portal_identity_log( + $previous_contact['id'], + 'contact_changed_details_via_wpprofile', + __( 'Email changed', 'zero-bs-crm' ), + /* translators: 1: old email address, 2: new email address. */ + sprintf( __( 'Contact email changed from `%1$s` to `%2$s`', 'zero-bs-crm' ), $previous_email, $email ) + ); + + return (int) $previous_contact['id']; + } + + return 0; +} + +/** + * Where a confirmation link leads, and where the user lands afterwards: the + * Client Portal, or WooCommerce My Account on a site that only uses that. + * + * @return string + */ +function jpcrm_portal_confirmation_url() { + + if ( zeroBSCRM_isExtensionInstalled( 'portal' ) ) { + $url = zeroBS_portal_link( 'dash' ); + } elseif ( function_exists( 'wc_get_page_permalink' ) ) { + $url = wc_get_page_permalink( 'myaccount' ); + } + + if ( empty( $url ) ) { + $url = home_url( '/' ); + } + + /** + * Filters where Client Portal email confirmation links lead. + * + * @param string $url A front-end URL on this site. + */ + return (string) apply_filters( 'jpcrm_portal_confirmation_url', $url ); +} + +/** + * How long a confirmation link works for, in seconds. + * + * @return int + */ +function jpcrm_portal_confirmation_lifetime() { + /** + * Filters how long a Client Portal email confirmation link works for. + * + * @param int $seconds Lifetime in seconds. Default one day. + */ + return (int) apply_filters( 'jpcrm_portal_confirmation_lifetime', DAY_IN_SECONDS ); +} + +/** + * How long a user has to wait before asking for another confirmation email. + * + * @return int + */ +function jpcrm_portal_confirmation_resend_wait() { + /** + * Filters the wait between Client Portal confirmation emails to one user. + * + * @param int $seconds Wait in seconds. Default one minute. + */ + return (int) apply_filters( 'jpcrm_portal_confirmation_resend_wait', MINUTE_IN_SECONDS ); +} + +/** + * The confirmation waiting for a user, if it is for their current address and + * has not expired. + * + * @param int $user_id WordPress user ID. + * @return array|false Keys `hash`, `email`, `expires`, `sent`. + */ +function jpcrm_portal_pending_confirmation( $user_id ) { + $pending = get_user_meta( (int) $user_id, JPCRM_PORTAL_CONFIRMATION_META, true ); + + if ( + ! is_array( $pending ) + || empty( $pending['hash'] ) + || empty( $pending['email'] ) + || empty( $pending['expires'] ) + || (int) $pending['expires'] < time() + || $pending['email'] !== jpcrm_portal_user_email( $user_id ) + ) { + return false; + } + + return $pending; +} + +/** + * Seconds until a user may ask for another confirmation email. + * + * @param int $user_id WordPress user ID. + * @return int 0 when they may ask now. + */ +function jpcrm_portal_confirmation_wait_remaining( $user_id ) { + $pending = jpcrm_portal_pending_confirmation( $user_id ); + + if ( ! $pending || empty( $pending['sent'] ) ) { + return 0; + } + + return max( 0, (int) $pending['sent'] + jpcrm_portal_confirmation_resend_wait() - time() ); +} + +/** + * Send a user a link to confirm their account email address. + * + * @param int $user_id WordPress user ID. + * @return true|WP_Error + */ +function jpcrm_portal_send_email_confirmation( $user_id ) { + global $zbs; + + $user_id = (int) $user_id; + $email = jpcrm_portal_user_email( $user_id ); + + if ( '' === $email || ! zeroBSCRM_validateEmail( $email ) ) { + return new WP_Error( 'jpcrm_no_email', __( 'This account has no email address to confirm.', 'zero-bs-crm' ) ); + } + + if ( jpcrm_portal_confirmation_wait_remaining( $user_id ) > 0 ) { + return new WP_Error( 'jpcrm_wait', __( 'An email was sent a moment ago. Please wait before asking for another.', 'zero-bs-crm' ) ); + } + + $token = wp_generate_password( 40, false ); + + update_user_meta( + $user_id, + JPCRM_PORTAL_CONFIRMATION_META, + array( + 'hash' => hash( 'sha256', $token ), + 'email' => $email, + 'expires' => time() + jpcrm_portal_confirmation_lifetime(), + 'sent' => time(), + ) + ); + + $link = add_query_arg( JPCRM_PORTAL_CONFIRMATION_QUERY_ARG, rawurlencode( $token ), jpcrm_portal_confirmation_url() ); + + $paragraph = '

'; + $title = __( 'Confirm your email address', 'zero-bs-crm' ); + $body = $paragraph . esc_html__( 'Please confirm your email address so you can access your details and documents.', 'zero-bs-crm' ) . '

' + . $paragraph . '' . esc_html__( 'Confirm my email address', 'zero-bs-crm' ) . '

' + . $paragraph . esc_html__( 'You may be asked to log in first.', 'zero-bs-crm' ) . '

' + . $paragraph . esc_html__( 'The link can only be used once and expires after 24 hours.', 'zero-bs-crm' ) . '

' + . $paragraph . esc_html__( 'If you didn\'t request this, you can safely ignore this email.', 'zero-bs-crm' ) . '

'; + + // Our standard email wrapper, as the other portal emails use. + $html = $body; + $templated = jpcrm_retrieve_template( 'emails/default-email.html', false ); + if ( ! empty( $templated ) ) { + $templating = $zbs->get_templating(); + $html = $templating->replace_single_placeholder( 'msg-content', $body, $templated ); + $replacements = $templating->get_generic_replacements(); + $replacements['title'] = $title; + $html = $templating->replace_placeholders( array( 'global' ), $html, $replacements ); + } + + $sent = zeroBSCRM_mailDelivery_sendMessage( + -1, + array( + 'toEmail' => $email, + 'toName' => '', + 'subject' => $title, + 'headers' => array( 'Content-Type: text/html; charset=UTF-8' ), + 'body' => $html, + 'textbody' => '', + 'options' => array( + 'html' => 1, + ), + ) + ); + + if ( ! $sent || ( is_array( $sent ) && isset( $sent[0] ) && false === $sent[0] ) ) { + return new WP_Error( 'jpcrm_not_sent', __( 'We could not send the email. Please try again later.', 'zero-bs-crm' ) ); + } + + return true; +} + +/** + * Check a confirmation token for a user and, if it is theirs, confirm their + * email address. + * + * @param int $user_id WordPress user ID. + * @param string $token The token from the link. + * @return bool Whether the address was confirmed. + */ +function jpcrm_portal_confirm_email_with_token( $user_id, $token ) { + $pending = jpcrm_portal_pending_confirmation( $user_id ); + + if ( ! $pending || ! is_string( $token ) || '' === $token ) { + return false; + } + + if ( ! hash_equals( $pending['hash'], hash( 'sha256', $token ) ) ) { + return false; + } + + jpcrm_portal_mark_email_confirmed( $user_id ); + + return true; +} + +/** + * Catch a confirmation link being opened. + * + * The link only works for the user it was sent to, so somebody who is not + * logged in is sent to log in first and brought back. + * + * @return void + */ +function jpcrm_portal_catch_email_confirmation() { + + if ( ! isset( $_GET[ JPCRM_PORTAL_CONFIRMATION_QUERY_ARG ] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- the token is the credential. + return; + } + + $token = sanitize_text_field( wp_unslash( $_GET[ JPCRM_PORTAL_CONFIRMATION_QUERY_ARG ] ) ); // phpcs:ignore WordPress.Security.NonceVerification.Recommended + + if ( ! is_user_logged_in() ) { + $return_to = add_query_arg( JPCRM_PORTAL_CONFIRMATION_QUERY_ARG, rawurlencode( $token ), jpcrm_portal_confirmation_url() ); + wp_safe_redirect( wp_login_url( $return_to ) ); + exit( 0 ); + } + + $confirmed = jpcrm_portal_confirm_email_with_token( get_current_user_id(), $token ); + + nocache_headers(); + wp_safe_redirect( add_query_arg( 'jpcrm_email_confirmed', $confirmed ? '1' : '0', jpcrm_portal_confirmation_url() ) ); + exit( 0 ); +} +add_action( 'template_redirect', 'jpcrm_portal_catch_email_confirmation', 1 ); + +/** + * Whether the Client Portal should ask the current user to confirm their email + * address before showing them anything. + * + * Staff reach the portal without being a contact, so they are not asked. + * + * @return bool + */ +function jpcrm_portal_user_needs_email_confirmation() { + + if ( ! is_user_logged_in() || zeroBSCRM_isZBSAdminOrAdmin() ) { + return false; + } + + return ! jpcrm_portal_email_is_confirmed( get_current_user_id() ); +} + +/** + * An administrator changing somebody else's email address confirms it. + * + * This is how a user who can no longer reach their old address gets back in. + * It runs before the profile sync, which then finds the contact up to date. + * + * @param int $user_id WordPress user ID. + * @param WP_User $old_user_data The user before the update. + * @return void + */ +function jpcrm_portal_admin_email_change_confirms( $user_id, $old_user_data ) { + $user_id = (int) $user_id; + $old_email = isset( $old_user_data->user_email ) ? jpcrm_portal_normalise_email( $old_user_data->user_email ) : ''; + $new_email = jpcrm_portal_user_email( $user_id ); + + if ( '' === $new_email || $old_email === $new_email ) { + return; + } + + $actor_id = get_current_user_id(); + if ( $actor_id < 1 || $actor_id === $user_id || ! current_user_can( 'edit_users' ) ) { + return; + } + + jpcrm_portal_mark_email_confirmed( $user_id, array( $old_email ) ); +} +add_action( 'profile_update', 'jpcrm_portal_admin_email_change_confirms', 5, 2 ); + +/** + * WooCommerce confirming a customer's email address confirms it for us too. + * + * WooCommerce (11.0+) fires this once the customer has proved the address their + * account has at that moment, which is the same thing our own link proves. + * + * @param int $user_id WordPress user ID. + * @return void + */ +function jpcrm_portal_woocommerce_email_verified( $user_id ) { + jpcrm_portal_mark_email_confirmed( (int) $user_id ); +} +add_action( 'woocommerce_customer_email_verified', 'jpcrm_portal_woocommerce_email_verified' ); diff --git a/js/ZeroBSCRM.admin.global.js b/js/ZeroBSCRM.admin.global.js index 5582c8a8..7d2e80e6 100644 --- a/js/ZeroBSCRM.admin.global.js +++ b/js/ZeroBSCRM.admin.global.js @@ -1610,7 +1610,15 @@ function empty( str ) { * @param extraClasses */ function zeroBSCRMJS_telLinkFromNo( telno, internalHTML, extraClasses ) { - return '' + internalHTML + ''; + return ( + '' + + internalHTML + + '' + ); } // returns a click 2 call url diff --git a/js/ZeroBSCRM.admin.listview.js b/js/ZeroBSCRM.admin.listview.js index 436fa92d..a28e6621 100644 --- a/js/ZeroBSCRM.admin.listview.js +++ b/js/ZeroBSCRM.admin.listview.js @@ -2369,7 +2369,7 @@ function zeroBSCRMJS_listView_generic_phonelink( dataLine ) { if ( typeof dataLine.hometel !== 'undefined' && dataLine.hometel != '' ) { phoneLinkStr += ' ' + jpcrm.esc_html( dataLine.hometel ) + ' (' + @@ -2379,7 +2379,7 @@ function zeroBSCRMJS_listView_generic_phonelink( dataLine ) { if ( typeof dataLine.worktel !== 'undefined' && dataLine.worktel != '' ) { phoneLinkStr += ' ' + jpcrm.esc_html( dataLine.worktel ) + ' (' + @@ -2389,7 +2389,7 @@ function zeroBSCRMJS_listView_generic_phonelink( dataLine ) { if ( typeof dataLine.mobtel !== 'undefined' && dataLine.mobtel != '' ) { phoneLinkStr += ' ' + jpcrm.esc_html( dataLine.mobtel ) + ' (' + @@ -2745,7 +2745,7 @@ function zeroBSCRMJS_listView_customer_phonelink( dataLine ) { if ( typeof dataLine.hometel !== 'undefined' && dataLine.hometel != '' ) { phoneLinkStr += ' ' + jpcrm.esc_html( dataLine.hometel ) + ' (' + @@ -2755,7 +2755,7 @@ function zeroBSCRMJS_listView_customer_phonelink( dataLine ) { if ( typeof dataLine.worktel !== 'undefined' && dataLine.worktel != '' ) { phoneLinkStr += ' ' + jpcrm.esc_html( dataLine.worktel ) + ' (' + @@ -2765,7 +2765,7 @@ function zeroBSCRMJS_listView_customer_phonelink( dataLine ) { if ( typeof dataLine.mobtel !== 'undefined' && dataLine.mobtel != '' ) { phoneLinkStr += ' ' + jpcrm.esc_html( dataLine.mobtel ) + ' (' + @@ -3263,7 +3263,7 @@ function zeroBSCRMJS_listView_company_phonelink( dataLine ) { if ( typeof dataLine.maintel !== 'undefined' && dataLine.maintel != '' ) { phoneLinkStr += ' ' + jpcrm.esc_html( dataLine.maintel ) + ''; @@ -3271,7 +3271,7 @@ function zeroBSCRMJS_listView_company_phonelink( dataLine ) { if ( typeof dataLine.sectel !== 'undefined' && dataLine.sectel != '' ) { phoneLinkStr += ' ' + jpcrm.esc_html( dataLine.sectel ) + ''; @@ -4558,13 +4558,13 @@ function zeroBSCRMJS_listView_transaction_bulkActionFire_addtag() { jQuery.each( window.zbsTagsForBulkActions, function ( ind, tag ) { tagSelectList += '
'; } ); } else { diff --git a/modules/givewp/class-jpcrm-givewp.php b/modules/givewp/class-jpcrm-givewp.php index bd8e9e05..ca745f6d 100644 --- a/modules/givewp/class-jpcrm-givewp.php +++ b/modules/givewp/class-jpcrm-givewp.php @@ -212,12 +212,6 @@ private function add_update_donor( $givewp_donation_id, $payment_data ) { } } - // If this is an existing WordPress user, make sure not to lose that association. - $wp_user = get_user_by( 'email', $new_contact_data['email'] ); - if ( is_object( $wp_user ) ) { - $new_contact_data['wpid'] = $wp_user->ID; - } - // specify contact source $new_contact_data['externalSources'] = array( array( @@ -248,10 +242,15 @@ private function add_update_donor( $givewp_donation_id, $payment_data ) { // add or update contact $contact_id = $zbs->DAL->contacts->addUpdateContact( array( - 'data' => $new_contact_data, - 'automatorPassthrough' => $created_meta, - 'fallBackLog' => $exists_meta, - 'extraMeta' => array(), + 'data' => $new_contact_data, + 'automatorPassthrough' => $created_meta, + 'fallBackLog' => $exists_meta, + 'extraMeta' => array(), + // A donation names its donor by email address only: fill in what an existing + // contact is missing, and leave what it has, its status included. A new + // contact gets the Donor status. + 'do_not_overwrite_populated' => jpcrm_public_submission_fields_to_protect( $new_contact_data, 'givewp' ), + 'do_not_update_blanks' => true, ) ); return $contact_id; diff --git a/modules/mailpoet/includes/class-mailpoet-background-sync-job.php b/modules/mailpoet/includes/class-mailpoet-background-sync-job.php index 843ad3c7..73936e58 100644 --- a/modules/mailpoet/includes/class-mailpoet-background-sync-job.php +++ b/modules/mailpoet/includes/class-mailpoet-background-sync-job.php @@ -471,13 +471,47 @@ public function import_subscriber( $subscriber ) { // $this->debug( 'Add/Update contact:
' . var_export( $contact_args ) . '
' ); + $update_args = array( + 'data' => $contact_args['data'], + 'do_not_update_blanks' => true, + ); + + // Anyone can subscribe, with any email address. Until a contact is this + // subscriber's own, fill in what it is missing and leave what it has. + if ( ! $this->subscriber_has_contact( $subscriber ) ) { + $update_args['do_not_overwrite_populated'] = jpcrm_public_submission_fields_to_protect( $contact_args['data'], 'mailpoet' ); + } + // Add/update the contact & return id - return $zbs->DAL->contacts->addUpdateContact( // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase + return $zbs->DAL->contacts->addUpdateContact( $update_args ); // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase + } + + /** + * Whether a contact is already recorded as this subscriber, under the same email address. + * + * @param array $subscriber MailPoet subscriber. + * + * @return bool + */ + private function subscriber_has_contact( $subscriber ) { + + global $zbs; + + if ( empty( $subscriber['id'] ) || empty( $subscriber['email'] ) ) { + return false; + } + + $contact = $zbs->DAL->contacts->getContact( // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase + -1, array( - 'data' => $contact_args['data'], - 'do_not_update_blanks' => true, + 'externalSource' => 'mailpoet', + 'externalSourceUID' => $subscriber['id'], ) ); + + return is_array( $contact ) + && isset( $contact['email'] ) + && strtolower( trim( $contact['email'] ) ) === strtolower( trim( sanitize_email( $subscriber['email'] ) ) ); } /** diff --git a/modules/portal/class-client-portal-endpoint.php b/modules/portal/class-client-portal-endpoint.php index f0073b4d..2d266ac4 100644 --- a/modules/portal/class-client-portal-endpoint.php +++ b/modules/portal/class-client-portal-endpoint.php @@ -55,11 +55,26 @@ public function perform_endpoint_action() { return $this->portal->get_template( 'login.php' ); } + // A user is only shown a contact's records once they have confirmed their email address. + if ( jpcrm_portal_user_needs_email_confirmation() ) { + return $this->portal->get_template( 'confirm-email.php' ); + } + if ( ! $this->portal->is_user_enabled() ) { return $this->portal->get_template( 'disabled.php' ); } } + // Back from the link in the confirmation email. + if ( + $this->should_check_user_permission + && isset( $_GET['jpcrm_email_confirmed'] ) // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- display only. + && '1' === $_GET['jpcrm_email_confirmed'] // phpcs:ignore WordPress.Security.NonceVerification.Recommended + && jpcrm_portal_email_is_confirmed() + ) { + echo "
" . esc_html__( 'Thank you. Your email address is confirmed.', 'zero-bs-crm' ) . '
'; + } + $this->pre_content_action(); $this->output_html(); $this->post_content_action(); diff --git a/modules/portal/class-client-portal.php b/modules/portal/class-client-portal.php index 79f3782f..7ffb5070 100644 --- a/modules/portal/class-client-portal.php +++ b/modules/portal/class-client-portal.php @@ -319,17 +319,7 @@ function is_user_enabled() { return false; } - global $wpdb; - $uid = get_current_user_id(); - $cID = zeroBS_getCustomerIDFromWPID( $uid ); - - // these ones definitely work - $uinfo = get_userdata( $uid ); - $potentialEmail = ''; - if ( isset( $uinfo->user_email ) ) { - $potentialEmail = $uinfo->user_email; - } - $cID = zeroBS_getCustomerIDWithEmail( $potentialEmail ); + $cID = jpcrm_portal_contact_id_for_user( get_current_user_id() ); // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase $disabled = zeroBSCRM_isCustomerPortalDisabled( $cID ); diff --git a/modules/portal/endpoints/class-details-endpoint.php b/modules/portal/endpoints/class-details-endpoint.php index a0f70b15..c8c829e2 100644 --- a/modules/portal/endpoints/class-details-endpoint.php +++ b/modules/portal/endpoints/class-details-endpoint.php @@ -39,7 +39,7 @@ public function save_details() { // phpcs:ignore Squiz.Commenting.FunctionCommen ) { $uid = get_current_user_id(); $uinfo = get_userdata( $uid ); - $cID = zeroBS_getCustomerIDWithEmail( $uinfo->user_email ); + $cID = jpcrm_portal_contact_id_for_user( $uid ); // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase // added !empty check - because if logged in as admin, saved deets, it made a new contact for them if ( (int) $_POST['customer_id'] == $cID && ! empty( $cID ) ) { diff --git a/modules/portal/endpoints/class-invoices-endpoint.php b/modules/portal/endpoints/class-invoices-endpoint.php index e0d4e8f3..a0dff5bb 100644 --- a/modules/portal/endpoints/class-invoices-endpoint.php +++ b/modules/portal/endpoints/class-invoices-endpoint.php @@ -59,7 +59,7 @@ function list_invoices_html_output( $link = '', $endpoint = '' ) { $uid = get_current_user_id(); $uinfo = get_userdata( $uid ); - $cID = zeroBS_getCustomerIDWithEmail( $uinfo->user_email ); + $cID = jpcrm_portal_contact_id_for_user( $uid ); // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase $is_invoice_admin = $uinfo->has_cap( 'admin_zerobs_invoices' ); // if the current is a valid contact or a WP user with permissions to view invoices... diff --git a/modules/portal/templates/confirm-email.php b/modules/portal/templates/confirm-email.php new file mode 100644 index 00000000..e5ef0e63 --- /dev/null +++ b/modules/portal/templates/confirm-email.php @@ -0,0 +1,77 @@ +get_error_message(); + } else { + $jpcrm_notice = __( 'We have sent the email again.', 'zero-bs-crm' ); + } +} elseif ( ! jpcrm_portal_pending_confirmation( $jpcrm_user_id ) ) { + // First visit, or the last link has expired: send one. + $jpcrm_sent = jpcrm_portal_send_email_confirmation( $jpcrm_user_id ); + if ( is_wp_error( $jpcrm_sent ) ) { + $jpcrm_error = $jpcrm_sent->get_error_message(); + } +} + +// A link that did not work. +if ( isset( $_GET['jpcrm_email_confirmed'] ) && '0' === $_GET['jpcrm_email_confirmed'] && '' === $jpcrm_notice ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- display only. + $jpcrm_error = __( 'That link did not work. It may have expired, or been opened while logged in to a different account. Please use the newest email we sent you.', 'zero-bs-crm' ); +} + +?> +
+
+ +
+
diff --git a/modules/portal/templates/details.php b/modules/portal/templates/details.php index 960dbfe3..4088ece4 100644 --- a/modules/portal/templates/details.php +++ b/modules/portal/templates/details.php @@ -24,7 +24,7 @@ $uid = get_current_user_id(); $uinfo = get_userdata( $uid ); -$contact_id = zeroBS_getCustomerIDWithEmail( $uinfo->user_email ); +$contact_id = jpcrm_portal_contact_id_for_user( $uid ); ?>
diff --git a/modules/portal/templates/quotes.php b/modules/portal/templates/quotes.php index 423e3d8e..41d9f52b 100644 --- a/modules/portal/templates/quotes.php +++ b/modules/portal/templates/quotes.php @@ -46,7 +46,7 @@ user_email ); + $contact_id = jpcrm_portal_contact_id_for_user( $uid ); $is_quote_admin = $uinfo->has_cap( 'admin_zerobs_quotes' ); diff --git a/modules/portal/templates/transactions.php b/modules/portal/templates/transactions.php index ec285c65..a0ce4ee5 100644 --- a/modules/portal/templates/transactions.php +++ b/modules/portal/templates/transactions.php @@ -36,7 +36,7 @@ user_email ); + $contact_id = jpcrm_portal_contact_id_for_user( $uid ); if ( $contact_id > 0 || $uinfo->has_cap( 'admin_zerobs_transactions' ) ) { // TODO: use pagination while getting from the db. diff --git a/modules/woo-sync/includes/class-woo-sync-background-sync.php b/modules/woo-sync/includes/class-woo-sync-background-sync.php index 08a35393..facef075 100644 --- a/modules/woo-sync/includes/class-woo-sync-background-sync.php +++ b/modules/woo-sync/includes/class-woo-sync-background-sync.php @@ -412,12 +412,7 @@ public function update_contact_address_from_wp_user( $user_id = -1, $address_typ global $zbs; // retrieve contact ID from WP user ID - $contact_id = $zbs->DAL->contacts->getContact( - array( - 'WPID' => $user_id, - 'onlyID' => true, - ) - ); + $contact_id = jpcrm_portal_contact_id_for_user( $user_id ); if ( $contact_id > 0 ) { diff --git a/modules/woo-sync/includes/class-woo-sync-my-account-integration.php b/modules/woo-sync/includes/class-woo-sync-my-account-integration.php index 44d5d69b..55cb1f00 100644 --- a/modules/woo-sync/includes/class-woo-sync-my-account-integration.php +++ b/modules/woo-sync/includes/class-woo-sync-my-account-integration.php @@ -71,6 +71,86 @@ private function init_hooks() { add_action( 'woocommerce_save_account_details', array( $this, 'save_my_account_crm_field_changes' ), 10, 1 ); // See also $zbs->wordpress_user_integration->wordpress_profile_update (catches woo my account + wp profile update changes) + + // A customer sees their CRM details and invoices here once they have confirmed their + // email address. Ask them to, and send the email when they say so. + add_action( 'template_redirect', array( $this, 'catch_email_confirmation_request' ), 5 ); + add_action( 'woocommerce_account_content', array( $this, 'render_email_confirmation_notice' ), 5 ); + } + + /** + * Whether the current customer should be asked to confirm their email address + * on My Account: only when something here depends on it. + * + * @return bool + */ + private function should_ask_for_email_confirmation() { + global $zbs; + + if ( ! jpcrm_portal_user_needs_email_confirmation() ) { + return false; + } + + $settings = $zbs->modules->woosync->settings->getAll(); + + return ! empty( $settings['wcport'] ) || ( isset( $settings['wcinv'] ) && 1 === (int) $settings['wcinv'] ); + } + + /** + * Send the confirmation email when a customer asks for it from My Account. + * + * @return void + */ + public function catch_email_confirmation_request() { + + if ( ! isset( $_GET['jpcrm_send_confirmation'], $_GET['_wpnonce'] ) || ! is_user_logged_in() ) { + return; + } + + if ( ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_GET['_wpnonce'] ) ), 'jpcrm-send-email-confirmation' ) ) { + return; + } + + $sent = jpcrm_portal_send_email_confirmation( get_current_user_id() ); + + if ( is_wp_error( $sent ) ) { + wc_add_notice( $sent->get_error_message(), 'error' ); + } else { + wc_add_notice( __( 'We have sent you an email. Open the link in it to confirm your email address.', 'zero-bs-crm' ), 'success' ); + } + + wp_safe_redirect( wc_get_page_permalink( 'myaccount' ) ); + exit( 0 ); + } + + /** + * Ask a customer who has not confirmed their email address to do so, and thank + * one who just has. + * + * @return void + */ + public function render_email_confirmation_notice() { + + if ( isset( $_GET['jpcrm_email_confirmed'] ) && '1' === $_GET['jpcrm_email_confirmed'] && jpcrm_portal_email_is_confirmed() ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- display only. + wc_print_notice( esc_html__( 'Thank you. Your email address is confirmed.', 'zero-bs-crm' ), 'success' ); + return; + } + + if ( ! $this->should_ask_for_email_confirmation() ) { + return; + } + + $send_url = wp_nonce_url( add_query_arg( 'jpcrm_send_confirmation', '1', wc_get_page_permalink( 'myaccount' ) ), 'jpcrm-send-email-confirmation' ); + + wc_print_notice( + sprintf( + '%1$s %3$s', + esc_html__( 'Please confirm your email address to access your invoices and other account details.', 'zero-bs-crm' ), + esc_url( $send_url ), + esc_html__( 'Send me the confirmation email', 'zero-bs-crm' ) + ), + 'notice' + ); } /** @@ -110,7 +190,7 @@ private function check_customer_has_invoices() { $wordpress_user_id = get_current_user_id(); $uinfo = get_userdata( $wordpress_user_id ); - $contact_id = zeroBS_getCustomerIDWithEmail( $uinfo->user_email ); + $contact_id = jpcrm_portal_contact_id_for_user( $wordpress_user_id ); if ( $contact_id > 0 ) { @@ -187,8 +267,15 @@ public function render_additional_crm_fields_on_my_account() { // Retrieve current user data $wordpress_user_id = get_current_user_id(); $uinfo = get_userdata( $wordpress_user_id ); - $contact_id = zeroBS_getCustomerIDWithEmail( $uinfo->user_email ); - $crm_contact = zeroBS_getCustomerMeta( $contact_id ); + $contact_id = jpcrm_portal_contact_id_for_user( $wordpress_user_id ); + + // Nobody's details to show: the customer is not a contact, or has yet to confirm + // their email address (see render_email_confirmation_notice()). + if ( $contact_id < 1 ) { + return; + } + + $crm_contact = zeroBS_getCustomerMeta( $contact_id ); // Field models/settings @@ -598,7 +685,7 @@ public function render_additional_crm_fields_on_my_account() { public function save_my_account_crm_field_changes( $wordpress_user_id ) { global $zbs, $zbsCustomerFields; - $contact_id = zeroBS_getCustomerIDFromWPID( $wordpress_user_id ); + $contact_id = jpcrm_portal_contact_id_for_user( $wordpress_user_id ); $old_contact_data = $zbs->DAL->contacts->getContact( $contact_id ); // Downgrade to old-style second address keys so field names match the object diff --git a/package-lock.json b/package-lock.json index 0f33ff3d..8addfecb 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "@automattic/jetpack-crm", - "version": "6.8.6", + "version": "6.8.7", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@automattic/jetpack-crm", - "version": "6.8.6", + "version": "6.8.7", "license": "GPL-2.0", "devDependencies": { "@automattic/babel-plugin-preserve-i18n": "^1.0.0", diff --git a/package.json b/package.json index bc159e00..a4354c66 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "private": true, "name": "@automattic/jetpack-crm", - "version": "6.8.6", + "version": "6.8.7", "description": "The CRM for WordPress", "repository": { "type": "git", diff --git a/readme.txt b/readme.txt index 550073f8..2f52d67e 100644 --- a/readme.txt +++ b/readme.txt @@ -2,7 +2,7 @@ Contributors: automattic, kallehauge, cleacos, diegogarciarodrigues, bradshawtm, wpkaren, robertf4, woodyhayday, mikemayhem3030 Tags: CRM, Woocommerce CRM, Client Portal, Marketing Automation, Lead Generation Tested up to: 7.1 -Stable tag: 6.8.6 +Stable tag: 6.8.7 Requires at least: 6.0 Requires PHP: 7.4 License: GPLv2 diff --git a/tests/php/ajax/Quote_Accept_Test.php b/tests/php/ajax/Quote_Accept_Test.php index 283e4a3d..3ce6951a 100644 --- a/tests/php/ajax/Quote_Accept_Test.php +++ b/tests/php/ajax/Quote_Accept_Test.php @@ -146,6 +146,7 @@ private function contact_user(): array { $user_id = self::factory()->user->create( array( 'user_email' => $email ) ); $contact_id = (int) $this->add_contact( array( 'email' => $email ) ); zeroBS_setCustomerWPID( $contact_id, $user_id ); + $this->confirm_user_email( $user_id ); return array( 'wp_user' => new \WP_User( $user_id ), diff --git a/tests/php/class-jpcrm-base-integration-testcase.php b/tests/php/class-jpcrm-base-integration-testcase.php index 1714b983..040ad2e6 100644 --- a/tests/php/class-jpcrm-base-integration-testcase.php +++ b/tests/php/class-jpcrm-base-integration-testcase.php @@ -32,6 +32,17 @@ public function tear_down(): void { zeroBSCRM_database_reset( false ); } + /** + * Mark a user's current email address as confirmed, as opening the link in + * the confirmation email does. + * + * @param int $user_id WordPress user ID. + * @return void + */ + public function confirm_user_email( $user_id ) { + update_user_meta( $user_id, JPCRM_PORTAL_CONFIRMED_EMAIL_META, jpcrm_portal_user_email( $user_id ) ); + } + /** * Add a contact. * diff --git a/tests/php/dal/Tag_Name_Test.php b/tests/php/dal/Tag_Name_Test.php new file mode 100644 index 00000000..e180a972 --- /dev/null +++ b/tests/php/dal/Tag_Name_Test.php @@ -0,0 +1,68 @@ +DAL->addUpdateTag( // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase + array( + 'data' => array( + 'objtype' => ZBS_TYPE_TRANSACTION, + 'name' => $name, + ), + ) + ); + + if ( empty( $tag_id ) ) { + return false; + } + + $tag = $zbs->DAL->getTag( $tag_id, array( 'objtype' => ZBS_TYPE_TRANSACTION ) ); // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase + + return $tag['name']; + } + + /** + * @testdox An ordinary tag name is stored as it was given. + */ + #[TestDox( 'An ordinary tag name is stored as it was given.' )] + public function test_plain_name_is_unchanged() { + $this->assertSame( 'Annual plan & support', $this->stored_tag_name( 'Annual plan & support' ) ); + } + + /** + * @testdox Markup in a tag name is removed before it is stored. + */ + #[TestDox( 'Markup in a tag name is removed before it is stored.' )] + public function test_markup_is_removed() { + $this->assertSame( 'Annual plan', $this->stored_tag_name( 'Annual plan' ) ); + } + + /** + * @testdox A tag name with nothing but markup in it makes no tag. + */ + #[TestDox( 'A tag name with nothing but markup in it makes no tag.' )] + public function test_markup_only_name_makes_no_tag() { + $this->assertFalse( $this->stored_tag_name( '
' ) ); + } +} diff --git a/tests/php/entities/Jetpack_Form_Capture_Values_Test.php b/tests/php/entities/Jetpack_Form_Capture_Values_Test.php new file mode 100644 index 00000000..5e90e869 --- /dev/null +++ b/tests/php/entities/Jetpack_Form_Capture_Values_Test.php @@ -0,0 +1,215 @@ +value = $value; + $this->form = (object) array( 'attributes' => array() ); + $this->attributes = array( + 'id' => $id, + 'type' => $type, + ); + } + + /** + * Read an attribute, as Contact_Form_Field does. + * + * @param string $key The attribute name. + * @return mixed + */ + public function get_attribute( $key ) { + return isset( $this->attributes[ $key ] ) ? $this->attributes[ $key ] : null; + } + }; + } + + /** + * Put a submission through the Jetpack Forms capture. + * + * @param object[] $fields The submitted fields. + * @return void + */ + private function submit( array $fields ) { + zero_bs_crm_capture_jetpack_form( 1, $fields, false, array() ); + } + + /** + * The contact with the given email, or false. + * + * @param string $email The email address. + * @return array|false + */ + private function contact_with_email( string $email ) { + global $zbs; + + return $zbs->DAL->contacts->getContact( -1, array( 'email' => $email ) ); // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase + } + + /** + * @testdox An ordinary submission is stored as it was sent. + */ + #[TestDox( 'An ordinary submission is stored as it was sent.' )] + public function test_an_ordinary_submission_is_stored_as_sent() { + + $this->submit( + array( + $this->form_field( 'g1-name', 'name', "Siobhán O'Neill-Byrne" ), + $this->form_field( 'g1-email', 'email', 'siobhan@example.test' ), + $this->form_field( 'g1-phone', 'telephone', '+353 (21) 427-0000' ), + ) + ); + + $contact = $this->contact_with_email( 'siobhan@example.test' ); + + $this->assertIsArray( $contact, 'No contact was created.' ); + $this->assertSame( 'Siobhán', $contact['fname'] ); + $this->assertSame( "O'Neill-Byrne", $contact['lname'] ); + $this->assertSame( '+353 (21) 427-0000', $contact['hometel'] ); + } + + /** + * @testdox Submitted values are stored as plain text. + */ + #[TestDox( 'Submitted values are stored as plain text.' )] + public function test_submitted_values_are_stored_as_plain_text() { + + $this->submit( + array( + $this->form_field( 'jetpackcrm-email', 'email', 'sam@example.test' ), + $this->form_field( 'jetpackcrm-fname', 'text', 'Sam Other' ), + $this->form_field( 'jetpackcrm-city', 'select', array( 'Cork', 'Galway' ) ), + ) + ); + + $contact = $this->contact_with_email( 'sam@example.test' ); + + $this->assertIsArray( $contact, 'No contact was created.' ); + $this->assertSame( 'Sam Other', $contact['fname'], 'Markup was stored in the first name.' ); + $this->assertSame( 'Cork, Galway', $contact['city'], 'A field with several values was not stored as text.' ); + } + + /** + * @testdox Form fields cannot set a contact's ID, linked user or owner. + */ + #[TestDox( 'Form fields cannot set a contact\'s ID, linked user or owner.' )] + public function test_fields_cannot_set_id_linked_user_or_owner() { + + $other_id = $this->add_contact( + array( + 'email' => 'other@example.test', + 'fname' => 'Other', + ) + ); + + $this->submit( + array( + $this->form_field( 'jetpackcrm-email', 'email', 'pat@example.test' ), + $this->form_field( 'jetpackcrm-fname', 'text', 'Pat' ), + $this->form_field( 'jetpackcrm-id', 'text', (string) $other_id ), + $this->form_field( 'jetpackcrm-wpid', 'text', '4242' ), + $this->form_field( 'jetpackcrm-owner', 'text', '4243' ), + ) + ); + + $contact = $this->contact_with_email( 'pat@example.test' ); + + $this->assertIsArray( $contact, 'No contact was created.' ); + $this->assertNotEquals( $other_id, $contact['id'], 'The submission was written to another contact.' ); + $this->assertNotEquals( 4242, $contact['wpid'], 'A form field set the linked user.' ); + $this->assertNotEquals( 4243, $contact['owner'], 'A form field set the owner.' ); + + $other = $this->contact_with_email( 'other@example.test' ); + $this->assertSame( 'Other', $other['fname'], 'Another contact was changed.' ); + } + + /** + * @testdox A submission whose email is not an email address creates no contact. + */ + #[TestDox( 'A submission whose email is not an email address creates no contact.' )] + public function test_a_submission_without_an_email_address_creates_no_contact() { + global $zbs; + + $before = (int) $zbs->DAL->contacts->getContactCount(); // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase + + $this->submit( + array( + $this->form_field( 'jetpackcrm-email', 'text', 'sam at example test' ), + $this->form_field( 'jetpackcrm-fname', 'text', 'Sam' ), + ) + ); + + $this->assertSame( $before, (int) $zbs->DAL->contacts->getContactCount(), 'A contact was created without an email address.' ); // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase + } + + /** + * @testdox The ID of a contact's source is shown as text. + */ + #[TestDox( 'The ID of a contact\'s source is shown as text.' )] + public function test_the_id_of_a_source_is_shown_as_text() { + + $this->assertSame( + ' Form Capture:
a<i>b</i>@example.test', + zeroBS_getExternalSourceTitle( 'form', 'ab@example.test' ) + ); + + $this->assertSame( + ' Form Capture:
sam@example.test', + zeroBS_getExternalSourceTitle( 'form', 'sam@example.test' ), + 'An ordinary ID is no longer shown as it was.' + ); + } +} diff --git a/tests/php/entities/Public_Capture_Existing_Contact_Test.php b/tests/php/entities/Public_Capture_Existing_Contact_Test.php new file mode 100644 index 00000000..3accf06f --- /dev/null +++ b/tests/php/entities/Public_Capture_Existing_Contact_Test.php @@ -0,0 +1,539 @@ +add_contact( + array_merge( + array( + 'email' => self::CONTACT_EMAIL, + 'status' => 'Customer', + 'fname' => 'Alex', + 'lname' => 'Murphy', + 'addr1' => '19 Prospect Hill', + 'city' => 'Cork', + 'postcode' => 'T12 XY45', + 'hometel' => '+353 21 427 0000', + 'mobtel' => '+353 87 000 0000', + ), + $overrides + ) + ); + + $this->assertGreaterThan( 0, $id, 'Failed to create the contact under test.' ); + + return $id; + } + + /** + * A stand-in for a Jetpack Forms field: an id, a type and a value. + * + * @param string $id The field id, e.g. 'jetpackcrm-city'. + * @param string $type The field type, e.g. 'email'. + * @param mixed $value The submitted value. + * @return object + */ + private function form_field( string $id, string $type, $value ) { + return new class( $id, $type, $value ) { + + /** + * The submitted value. + * + * @var mixed + */ + public $value; + + /** + * The form the field belongs to. + * + * @var object + */ + public $form; + + /** + * The field's attributes. + * + * @var array + */ + private $attributes; + + /** + * Set the field up. + * + * @param string $id The field id. + * @param string $type The field type. + * @param mixed $value The submitted value. + */ + public function __construct( $id, $type, $value ) { + $this->value = $value; + $this->form = (object) array( 'attributes' => array() ); + $this->attributes = array( + 'id' => $id, + 'type' => $type, + ); + } + + /** + * Read an attribute, as Contact_Form_Field does. + * + * @param string $key The attribute name. + * @return mixed + */ + public function get_attribute( $key ) { + return isset( $this->attributes[ $key ] ) ? $this->attributes[ $key ] : null; + } + }; + } + + /** + * Put a submission through the Jetpack Forms capture. + * + * @param object[] $fields The submitted fields. + * @return void + */ + private function submit_jetpack_form( array $fields ) { + zero_bs_crm_capture_jetpack_form( + 1, + $fields, + false, + array( + 'entry_title' => 'Contact us', + 'entry_permalink' => 'https://example.test/contact/', + 'feedback_id' => 'abc123', + ) + ); + } + + /** + * A plain contact form: name, email and telephone, found by field type. + * + * @return object[] + */ + private function plain_form_fields(): array { + return array( + $this->form_field( 'g1-name', 'name', 'Sam Other' ), + $this->form_field( 'g1-email', 'email', self::CONTACT_EMAIL ), + $this->form_field( 'g1-phone', 'telephone', '000' ), + ); + } + + /** + * Run a donation's donor info through the GiveWP integration. + * + * @param array $user_info GiveWP user_info. + * @return int Contact ID. + */ + private function add_donor( array $user_info ): int { + $integration = new JPCRM_GiveWP(); + $method = new \ReflectionMethod( $integration, 'add_update_donor' ); + if ( PHP_VERSION_ID < 80100 ) { + $method->setAccessible( true ); // A no-op from PHP 8.1, and deprecated in 8.5. + } + + return (int) $method->invoke( + $integration, + 123, + array( + 'user_info' => $user_info, + 'give_form_title' => 'Test form', + ) + ); + } + + /** + * @testdox A Jetpack form submission leaves an existing contact's details as they are. + */ + #[TestDox( 'A Jetpack form submission leaves an existing contact\'s details as they are.' )] + public function test_jetpack_form_leaves_existing_details() { + global $zbs; + + $contact_id = $this->create_contact_with_details(); + + $this->submit_jetpack_form( $this->plain_form_fields() ); + + $contact = $zbs->DAL->contacts->getContact( $contact_id ); // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase + + $this->assertSame( 'Alex', $contact['fname'], 'A submission replaced the first name.' ); + $this->assertSame( 'Murphy', $contact['lname'], 'A submission replaced the last name.' ); + $this->assertSame( '+353 21 427 0000', $contact['hometel'], 'A submission replaced the telephone number.' ); + $this->assertSame( '19 Prospect Hill', $contact['addr1'], 'A submission emptied the address.' ); + $this->assertSame( 'Cork', $contact['city'], 'A submission emptied the city.' ); + $this->assertSame( '+353 87 000 0000', $contact['mobtel'], 'A submission emptied the mobile number.' ); + $this->assertSame( 'Customer', $contact['status'], 'A submission changed the status.' ); + } + + /** + * @testdox A Jetpack form submission still fills in what an existing contact is missing. + */ + #[TestDox( 'A Jetpack form submission still fills in what an existing contact is missing.' )] + public function test_jetpack_form_fills_in_missing_details() { + global $zbs; + + $contact_id = $this->create_contact_with_details( + array( + 'hometel' => '', + 'city' => '', + ) + ); + + $this->submit_jetpack_form( + array( + $this->form_field( 'jetpackcrm-email', 'email', self::CONTACT_EMAIL ), + $this->form_field( 'jetpackcrm-hometel', 'telephone', '+353 21 111 1111' ), + $this->form_field( 'jetpackcrm-city', 'text', 'Galway' ), + $this->form_field( 'jetpackcrm-addr1', 'text', '1 Other Street' ), + ) + ); + + $contact = $zbs->DAL->contacts->getContact( $contact_id ); // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase + + $this->assertSame( '+353 21 111 1111', $contact['hometel'], 'A blank telephone number was not filled in.' ); + $this->assertSame( 'Galway', $contact['city'], 'A blank city was not filled in.' ); + $this->assertSame( '19 Prospect Hill', $contact['addr1'], 'A submission replaced the address.' ); + } + + /** + * @testdox A Jetpack form submission leaves an existing contact's custom field as it is. + */ + #[TestDox( 'A Jetpack form submission leaves an existing contact\'s custom field as it is.' )] + public function test_jetpack_form_leaves_existing_custom_field() { + global $zbs; + + $this->register_custom_field( 'account-ref', 'text', 'Account reference', array( 'customers' => ZBS_TYPE_CONTACT ) ); + + $contact_id = $this->create_contact_with_details( array( 'account-ref' => 'A-100' ) ); + + $this->submit_jetpack_form( + array( + $this->form_field( 'jetpackcrm-email', 'email', self::CONTACT_EMAIL ), + $this->form_field( 'jetpackcrm-account-ref', 'text', 'B-200' ), + ) + ); + + $contact = $zbs->DAL->contacts->getContact( $contact_id ); // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase + + $this->assertSame( 'A-100', $contact['account-ref'], 'A submission replaced the custom field.' ); + } + + /** + * @testdox A Jetpack form submission still records the form and adds its tags. + */ + #[TestDox( 'A Jetpack form submission still records the form and adds its tags.' )] + public function test_jetpack_form_still_records_source_and_tags() { + global $zbs; + + $contact_id = $this->create_contact_with_details(); + + $zbs->DAL->contacts->addUpdateContactTags( // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase + array( + 'id' => $contact_id, + 'tag_input' => array( 'VIP' ), + 'mode' => 'append', + ) + ); + + $this->submit_jetpack_form( + array( + $this->form_field( 'jetpackcrm-email', 'email', self::CONTACT_EMAIL ), + $this->form_field( 'jetpackcrm-tags', 'text', 'Newsletter' ), + ) + ); + + $contact = $zbs->DAL->contacts->getContact( // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase + $contact_id, + array( + 'withExternalSources' => true, + 'withTags' => true, + ) + ); + + $this->assertContains( 'jetpack_form', wp_list_pluck( $contact['external_sources'], 'source' ), 'The form was not recorded as a source.' ); + $this->assertContains( 'Newsletter', wp_list_pluck( $contact['tags'], 'name' ), 'The tag was not added.' ); + $this->assertContains( 'VIP', wp_list_pluck( $contact['tags'], 'name' ), 'A submission removed a tag the contact already had.' ); + } + + /** + * @testdox A Jetpack form submission still creates a new contact with everything it sent. + */ + #[TestDox( 'A Jetpack form submission still creates a new contact with everything it sent.' )] + public function test_jetpack_form_still_creates_new_contacts() { + global $zbs; + + $this->submit_jetpack_form( $this->plain_form_fields() ); + + $contact = $zbs->DAL->contacts->getContact( -1, array( 'email' => self::CONTACT_EMAIL ) ); // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase + + $this->assertIsArray( $contact, 'No contact was created.' ); + $this->assertSame( 'Sam', $contact['fname'] ); + $this->assertSame( 'Other', $contact['lname'] ); + $this->assertSame( '000', $contact['hometel'] ); + } + + /** + * @testdox The filter can let submissions replace fields again. + */ + #[TestDox( 'The filter can let submissions replace fields again.' )] + public function test_filter_can_let_submissions_replace_fields() { + global $zbs; + + $contact_id = $this->create_contact_with_details(); + + add_filter( 'jpcrm_public_submission_fields_to_protect', '__return_empty_array' ); + try { + $this->submit_jetpack_form( $this->plain_form_fields() ); + } finally { + remove_filter( 'jpcrm_public_submission_fields_to_protect', '__return_empty_array' ); + } + + $contact = $zbs->DAL->contacts->getContact( $contact_id ); // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase + + $this->assertSame( 'Sam', $contact['fname'], 'The filter did not restore the previous behaviour.' ); + $this->assertSame( '19 Prospect Hill', $contact['addr1'], 'Fields the form did not send are still kept.' ); + } + + /** + * Import a MailPoet subscriber the way the MailPoet sync does. + * + * @param array $subscriber Subscriber fields. + * @return int The contact ID. + */ + private function import_mailpoet_subscriber( array $subscriber ): int { + global $zbs; + + $had_module = isset( $zbs->modules->mailpoet ); + $real_module = $had_module ? $zbs->modules->mailpoet : null; + + // The job only asks the module for its settings. + $zbs->modules->mailpoet = (object) array( + 'settings' => new class() { + /** + * The settings the import reads. + * + * @return array + */ + public function getAll() { // phpcs:ignore WordPress.NamingConventions.ValidFunctionName.MethodNameInvalid + return array( + 'tag_with_list' => 0, + 'tag_with_tags' => 0, + ); + } + }, + ); + + $job = new Mailpoet_Background_Sync_Job(); + $contact_id = (int) $job->import_subscriber( + array_merge( + array( + 'id' => 7001, + 'created_at' => '2026-01-05 10:00:00', + ), + $subscriber + ) + ); + + if ( $had_module ) { + $zbs->modules->mailpoet = $real_module; + } else { + unset( $zbs->modules->mailpoet ); + } + + return $contact_id; + } + + /** + * @testdox A new MailPoet subscriber leaves an existing contact's name as it is. + */ + #[TestDox( 'A new MailPoet subscriber leaves an existing contact\'s name as it is.' )] + public function test_mailpoet_subscriber_leaves_existing_name() { + global $zbs; + + $contact_id = $this->create_contact_with_details(); + + $imported_id = $this->import_mailpoet_subscriber( + array( + 'email' => self::CONTACT_EMAIL, + 'first_name' => 'Sam', + 'last_name' => 'Other', + 'wp_user_id' => 4242, + ) + ); + + $this->assertSame( $contact_id, $imported_id, 'The subscriber did not match the existing contact.' ); + + $contact = $zbs->DAL->contacts->getContact( $contact_id ); // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase + + $this->assertSame( 'Alex', $contact['fname'], 'A new subscriber replaced the first name.' ); + $this->assertSame( 'Murphy', $contact['lname'], 'A new subscriber replaced the last name.' ); + $this->assertNotEquals( 4242, $contact['wpid'], 'A new subscriber changed the linked user.' ); + + $linked = $zbs->DAL->contacts->getContact( // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase + -1, + array( + 'externalSource' => 'mailpoet', + 'externalSourceUID' => 7001, + ) + ); + $this->assertSame( $contact_id, (int) $linked['id'], 'The subscriber was not recorded as a source.' ); + } + + /** + * @testdox A new MailPoet subscriber fills in a name the contact is missing. + */ + #[TestDox( 'A new MailPoet subscriber fills in a name the contact is missing.' )] + public function test_mailpoet_subscriber_fills_in_missing_name() { + global $zbs; + + $contact_id = $this->create_contact_with_details( + array( + 'fname' => '', + 'lname' => '', + ) + ); + + $this->import_mailpoet_subscriber( + array( + 'email' => self::CONTACT_EMAIL, + 'first_name' => 'Sam', + 'last_name' => 'Other', + ) + ); + + $contact = $zbs->DAL->contacts->getContact( $contact_id ); // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase + + $this->assertSame( 'Sam', $contact['fname'], 'A missing first name was not filled in.' ); + $this->assertSame( 'Other', $contact['lname'], 'A missing last name was not filled in.' ); + } + + /** + * @testdox A MailPoet subscriber already recorded on a contact still updates its name. + */ + #[TestDox( 'A MailPoet subscriber already recorded on a contact still updates its name.' )] + public function test_mailpoet_known_subscriber_still_updates_name() { + global $zbs; + + $contact_id = $this->import_mailpoet_subscriber( + array( + 'email' => 'sam.other@example.test', + 'first_name' => 'Sam', + 'last_name' => 'Other', + ) + ); + $this->assertGreaterThan( 0, $contact_id, 'The subscriber was not imported.' ); + + $this->import_mailpoet_subscriber( + array( + 'email' => 'sam.other@example.test', + 'first_name' => 'Samantha', + 'last_name' => 'Other', + ) + ); + + $contact = $zbs->DAL->contacts->getContact( $contact_id ); // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase + + $this->assertSame( 'Samantha', $contact['fname'], 'A known subscriber could not update their own name.' ); + } + + /** + * @testdox A GiveWP donation leaves an existing contact's details and status as they are. + */ + #[TestDox( 'A GiveWP donation leaves an existing contact\'s details and status as they are.' )] + public function test_givewp_donation_leaves_existing_details() { + global $zbs; + + $contact_id = $this->create_contact_with_details( array( 'country' => '' ) ); + + $donor_contact_id = $this->add_donor( + array( + 'email' => self::CONTACT_EMAIL, + 'first_name' => 'Sam', + 'last_name' => 'Other', + 'address' => array( + 'line1' => '1 Other Street', + 'line2' => '', + 'city' => 'Galway', + 'state' => '', + 'zip' => 'H91 0000', + 'country' => 'IE', + ), + ) + ); + + $this->assertSame( $contact_id, $donor_contact_id, 'The donation did not match the existing contact.' ); + + $contact = $zbs->DAL->contacts->getContact( $contact_id ); // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase + + $this->assertSame( 'Alex', $contact['fname'], 'A donation replaced the first name.' ); + $this->assertSame( 'Murphy', $contact['lname'], 'A donation replaced the last name.' ); + $this->assertSame( '19 Prospect Hill', $contact['addr1'], 'A donation replaced the address.' ); + $this->assertSame( 'Cork', $contact['city'], 'A donation replaced the city.' ); + $this->assertSame( 'T12 XY45', $contact['postcode'], 'A donation replaced the postcode.' ); + $this->assertSame( '+353 87 000 0000', $contact['mobtel'], 'A donation emptied the mobile number.' ); + $this->assertSame( 'IE', $contact['country'], 'A blank country was not filled in.' ); + $this->assertSame( 'Customer', $contact['status'], 'A donation changed the status of an existing contact.' ); + + $tagged = $zbs->DAL->contacts->getContact( $contact_id, array( 'withTags' => true ) ); // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase + $this->assertContains( 'GiveWP', wp_list_pluck( $tagged['tags'], 'name' ), 'The GiveWP tag was not added.' ); + } + + /** + * @testdox A GiveWP donation from somebody new creates a contact with the Donor status. + */ + #[TestDox( 'A GiveWP donation from somebody new creates a contact with the Donor status.' )] + public function test_givewp_donation_creates_a_donor() { + global $zbs; + + $contact_id = $this->add_donor( + array( + 'email' => 'new.donor@example.test', + 'first_name' => 'Dana', + ) + ); + + $contact = $zbs->DAL->contacts->getContact( $contact_id, array( 'withTags' => true ) ); // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase + + $this->assertSame( 'Donor', $contact['status'] ); + $this->assertSame( 'Dana', $contact['fname'] ); + $this->assertContains( 'GiveWP', wp_list_pluck( $contact['tags'], 'name' ) ); + } +} diff --git a/tests/php/format-helpers/Company_Intro_Sentence_Test.php b/tests/php/format-helpers/Company_Intro_Sentence_Test.php new file mode 100644 index 00000000..7d51eae9 --- /dev/null +++ b/tests/php/format-helpers/Company_Intro_Sentence_Test.php @@ -0,0 +1,60 @@ + 1, + 'email' => $email, + 'created' => 0, + ) + ); + } + + /** + * @testdox An email address is linked as before. + */ + #[TestDox( 'An email address is linked as before.' )] + public function test_an_email_address_is_linked() { + $this->assertSame( + 'Email: hello@example.test
', + $this->render( 'hello@example.test' ) + ); + } + + /** + * @testdox A stored value with markup characters is printed as text. + */ + #[TestDox( 'A stored value with markup characters is printed as text.' )] + public function test_a_value_with_markup_characters_is_printed_as_text() { + $html = $this->render( 'a"b title="c' ); + + $document = new \DOMDocument(); + $document->loadHTML( '
' . $html . '
', LIBXML_NOERROR ); + $link = $document->getElementsByTagName( 'a' )->item( 0 ); + + $this->assertNotNull( $link, 'The email is no longer linked.' ); + $this->assertSame( array( 'href', 'class' ), array_keys( iterator_to_array( $link->attributes ) ), 'The stored value added an attribute to the link.' ); + $this->assertSame( ' a"b title="c', $link->textContent, 'The stored value is not shown as it was entered.' ); + } +} diff --git a/tests/php/metabox/Company_Email_Save_Test.php b/tests/php/metabox/Company_Email_Save_Test.php new file mode 100644 index 00000000..67501045 --- /dev/null +++ b/tests/php/metabox/Company_Email_Save_Test.php @@ -0,0 +1,57 @@ +user->create( array( 'role' => 'administrator' ) ) ); + + $company_id = $this->add_company( array( 'email' => 'hello@example.test' ) ); + $this->assertGreaterThan( 0, $company_id, 'Failed to create the company under test.' ); + + $original_post = $_POST; // phpcs:ignore WordPress.Security.NonceVerification.Missing -- simulating the edit screen's save. + $_POST = wp_slash( + array( + 'zbsco_name' => 'My Company', + 'zbsco_email' => 'not an "email" address', + ) + ); + + $zbs->pageMessages = array(); // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase + + try { + ( new zeroBS__Metabox_Company( ZBS_ROOTFILE ) )->save_data( $company_id, array() ); + } finally { + $_POST = $original_post; + } + + $this->assertSame( 'hello@example.test', $zbs->DAL->companies->getCompanyEmail( $company_id ), 'The company email was replaced by a value that is not an email address.' ); // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase + + $messages = implode( '', $zbs->pageMessages ); // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase + $this->assertStringContainsString( 'is not valid', $messages, 'The screen did not say the email was not saved.' ); + $this->assertStringContainsString( 'not an "email" address', $messages, 'The notice does not show the value as text.' ); + } +} diff --git a/tests/php/portal/Portal_Identity_Test.php b/tests/php/portal/Portal_Identity_Test.php new file mode 100644 index 00000000..8b0c6b4b --- /dev/null +++ b/tests/php/portal/Portal_Identity_Test.php @@ -0,0 +1,491 @@ +sent = array(); + add_filter( 'pre_wp_mail', array( $this, 'catch_mail' ), 10, 2 ); + wp_set_current_user( 0 ); + } + + /** + * Stop catching email. + */ + public function tear_down(): void { + remove_filter( 'pre_wp_mail', array( $this, 'catch_mail' ), 10 ); + wp_set_current_user( 0 ); + parent::tear_down(); + } + + /** + * Record an email and report it as sent. + * + * @param null|bool $short_circuit Whether to short-circuit wp_mail(). + * @param array $atts The email. + * @return bool + */ + public function catch_mail( $short_circuit, $atts ) { + unset( $short_circuit ); + // WordPress sends its own notices when an account's email changes; only ours are of interest. + if ( false !== strpos( $atts['message'], JPCRM_PORTAL_CONFIRMATION_QUERY_ARG . '=' ) ) { + $this->sent[] = $atts; + } + return true; + } + + /** + * A WordPress user with the given email address. + * + * @param string $email Email address. + * @param string $role Role. + * @return int User ID. + */ + private function user( string $email, string $role = 'subscriber' ): int { + return self::factory()->user->create( + array( + 'user_email' => $email, + 'role' => $role, + ) + ); + } + + /** + * A contact with the given email address, optionally linked to a user. + * + * @param string $email Email address. + * @param int $user_id User to link, or 0. + * @return int Contact ID. + */ + private function contact( string $email, int $user_id = 0 ): int { + $contact_id = (int) $this->add_contact( + array( + 'email' => $email, + 'fname' => 'Alex', + 'lname' => 'Murphy', + ) + ); + if ( $user_id ) { + zeroBS_setCustomerWPID( $contact_id, $user_id ); + } + return $contact_id; + } + + /** + * The email address a contact has now. + * + * @param int $contact_id Contact ID. + * @return string + */ + private function contact_email( int $contact_id ): string { + global $zbs; + return (string) $zbs->DAL->contacts->getContactEmail( $contact_id ); // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase + } + + /** + * The token in the last confirmation email sent. + * + * @return string + */ + private function last_token(): string { + $this->assertNotEmpty( $this->sent, 'No email was sent.' ); + $last = end( $this->sent ); + $this->assertSame( 1, preg_match( '/' . JPCRM_PORTAL_CONFIRMATION_QUERY_ARG . '=([A-Za-z0-9]+)/', $last['message'], $matches ), 'The email has no confirmation link.' ); + return $matches[1]; + } + + /** + * @testdox A user who has not confirmed their email address is no contact, even when linked to one. + */ + #[TestDox( 'A user who has not confirmed their email address is no contact, even when linked to one.' )] + public function test_unconfirmed_user_is_no_contact() { + $user_id = $this->user( 'alex@example.test' ); + $this->contact( 'alex@example.test', $user_id ); + + $this->assertSame( 0, jpcrm_portal_contact_id_for_user( $user_id ) ); + } + + /** + * @testdox A user who has confirmed their email address is the contact that has it. + */ + #[TestDox( 'A user who has confirmed their email address is the contact that has it.' )] + public function test_confirmed_linked_user_is_the_contact() { + $user_id = $this->user( 'alex@example.test' ); + $contact_id = $this->contact( 'alex@example.test', $user_id ); + $this->confirm_user_email( $user_id ); + + $this->assertSame( $contact_id, jpcrm_portal_contact_id_for_user( $user_id ) ); + } + + /** + * @testdox A confirmed user linked to a contact with a different email address is not that contact. + */ + #[TestDox( 'A confirmed user linked to a contact with a different email address is not that contact.' )] + public function test_link_to_a_contact_with_another_address_gives_nothing() { + $user_id = $this->user( 'sam@example.test' ); + $this->contact( 'alex@example.test', $user_id ); + $this->confirm_user_email( $user_id ); + + $this->assertSame( 0, jpcrm_portal_contact_id_for_user( $user_id ) ); + } + + /** + * @testdox A confirmed user is the contact with their address even after something else re-pointed its link. + */ + #[TestDox( 'A confirmed user is the contact with their address even after something else re-pointed its link.' )] + public function test_confirmed_user_keeps_their_contact_when_the_link_is_overwritten() { + global $zbs; + + $user_id = $this->user( 'alex@example.test' ); + $contact_id = $this->contact( 'alex@example.test', $user_id ); + $this->confirm_user_email( $user_id ); + + // A sync that matched the contact by email links it to whoever placed the order. + $other_id = $this->user( 'mallory@example.test' ); + $this->confirm_user_email( $other_id ); + zeroBS_setCustomerWPID( $contact_id, $other_id ); + + $this->assertSame( 0, jpcrm_portal_contact_id_for_user( $other_id ), 'The link alone made another user this contact.' ); + $this->assertSame( $contact_id, jpcrm_portal_contact_id_for_user( $user_id ) ); + $this->assertSame( $user_id, (int) $zbs->DAL->contacts->getContactWPID( $contact_id ) ); // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase + } + + /** + * @testdox Looking up a contact's portal user does not link it to a user with the same email address. + */ + #[TestDox( 'Looking up a contact\'s portal user does not link it to a user with the same email address.' )] + public function test_looking_up_the_portal_user_does_not_link() { + global $zbs; + + $this->user( 'alex@example.test' ); + $contact_id = $this->contact( 'alex@example.test' ); + + $this->assertFalse( zeroBSCRM_getClientPortalUserID( $contact_id ) ); + $this->assertLessThan( 1, (int) $zbs->DAL->contacts->getContactWPID( $contact_id ) ); // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase + } + + /** + * @testdox Opening the emailed link confirms the address and links the contact that has it. + */ + #[TestDox( 'Opening the emailed link confirms the address and links the contact that has it.' )] + public function test_confirming_links_the_contact_with_that_address() { + $user_id = $this->user( 'alex@example.test' ); + $contact_id = $this->contact( 'alex@example.test' ); + + $this->assertTrue( jpcrm_portal_send_email_confirmation( $user_id ) ); + $this->assertSame( 'alex@example.test', end( $this->sent )['to'] ); + + $this->assertFalse( jpcrm_portal_confirm_email_with_token( $user_id, 'not-the-token' ) ); + $this->assertSame( 0, jpcrm_portal_contact_id_for_user( $user_id ) ); + + $this->assertTrue( jpcrm_portal_confirm_email_with_token( $user_id, $this->last_token() ) ); + $this->assertSame( $contact_id, jpcrm_portal_contact_id_for_user( $user_id ) ); + } + + /** + * @testdox A link works once, and only for the user it was sent to. + */ + #[TestDox( 'A link works once, and only for the user it was sent to.' )] + public function test_a_link_works_once_and_for_one_user() { + $user_id = $this->user( 'alex@example.test' ); + $other_id = $this->user( 'sam@example.test' ); + + jpcrm_portal_send_email_confirmation( $user_id ); + $token = $this->last_token(); + + $this->assertFalse( jpcrm_portal_confirm_email_with_token( $other_id, $token ), 'Another user confirmed with the link.' ); + $this->assertTrue( jpcrm_portal_confirm_email_with_token( $user_id, $token ) ); + $this->assertFalse( jpcrm_portal_confirm_email_with_token( $user_id, $token ), 'The link worked twice.' ); + } + + /** + * @testdox A link stops working when it expires, or when the user changes their address. + */ + #[TestDox( 'A link stops working when it expires, or when the user changes their address.' )] + public function test_a_link_expires_and_is_tied_to_the_address() { + $user_id = $this->user( 'alex@example.test' ); + + jpcrm_portal_send_email_confirmation( $user_id ); + $token = $this->last_token(); + $pending = get_user_meta( $user_id, JPCRM_PORTAL_CONFIRMATION_META, true ); + + update_user_meta( $user_id, JPCRM_PORTAL_CONFIRMATION_META, array_merge( $pending, array( 'expires' => time() - 1 ) ) ); + $this->assertFalse( jpcrm_portal_confirm_email_with_token( $user_id, $token ), 'An expired link worked.' ); + + update_user_meta( $user_id, JPCRM_PORTAL_CONFIRMATION_META, $pending ); + wp_update_user( + array( + 'ID' => $user_id, + 'user_email' => 'someone-else@example.test', + ) + ); + $this->assertFalse( jpcrm_portal_confirm_email_with_token( $user_id, $token ), 'A link sent to the old address confirmed the new one.' ); + $this->assertFalse( jpcrm_portal_email_is_confirmed( $user_id ) ); + } + + /** + * @testdox A second email cannot be asked for straight away. + */ + #[TestDox( 'A second email cannot be asked for straight away.' )] + public function test_resending_has_a_wait() { + $user_id = $this->user( 'alex@example.test' ); + + $this->assertTrue( jpcrm_portal_send_email_confirmation( $user_id ) ); + $this->assertWPError( jpcrm_portal_send_email_confirmation( $user_id ) ); + $this->assertCount( 1, $this->sent ); + } + + /** + * @testdox A user who changes their own address to another contact's is neither contact, and neither contact changes. + */ + #[TestDox( 'A user who changes their own address to another contact\'s is neither contact, and neither contact changes.' )] + public function test_changing_to_another_contacts_address_gives_nothing() { + $user_id = $this->user( 'mallory@example.test' ); + $own_contact = $this->contact( 'mallory@example.test', $user_id ); + $this->confirm_user_email( $user_id ); + $other_contact = $this->contact( 'alex@example.test' ); + + wp_set_current_user( $user_id ); + wp_update_user( + array( + 'ID' => $user_id, + 'user_email' => 'alex@example.test', + ) + ); + + $this->assertSame( 0, jpcrm_portal_contact_id_for_user( $user_id ) ); + $this->assertSame( 'mallory@example.test', $this->contact_email( $own_contact ), 'Their own contact moved to the new address.' ); + $this->assertSame( 'alex@example.test', $this->contact_email( $other_contact ) ); + $this->assertSame( 'alex@example.test', end( $this->sent )['to'], 'The confirmation did not go to the new address.' ); + } + + /** + * @testdox A contact follows its user to a new address once the user confirms it. + */ + #[TestDox( 'A contact follows its user to a new address once the user confirms it.' )] + public function test_contact_follows_a_confirmed_change() { + $user_id = $this->user( 'alex@example.test' ); + $contact_id = $this->contact( 'alex@example.test', $user_id ); + $this->confirm_user_email( $user_id ); + + wp_set_current_user( $user_id ); + wp_update_user( + array( + 'ID' => $user_id, + 'user_email' => 'alex@new.example.test', + ) + ); + + $this->assertSame( 'alex@example.test', $this->contact_email( $contact_id ), 'The contact moved before the new address was confirmed.' ); + $this->assertSame( 0, jpcrm_portal_contact_id_for_user( $user_id ) ); + + $this->assertTrue( jpcrm_portal_confirm_email_with_token( $user_id, $this->last_token() ) ); + + $this->assertSame( 'alex@new.example.test', $this->contact_email( $contact_id ) ); + $this->assertSame( $contact_id, jpcrm_portal_contact_id_for_user( $user_id ) ); + } + + /** + * @testdox An administrator changing a user's address confirms it, and the contact follows. + */ + #[TestDox( 'An administrator changing a user\'s address confirms it, and the contact follows.' )] + public function test_admin_change_confirms_and_moves_the_contact() { + $user_id = $this->user( 'alex@example.test' ); + $contact_id = $this->contact( 'alex@example.test', $user_id ); + + wp_set_current_user( $this->user( 'admin@example.test', 'administrator' ) ); + wp_update_user( + array( + 'ID' => $user_id, + 'user_email' => 'alex@new.example.test', + ) + ); + + $this->assertSame( 'alex@new.example.test', $this->contact_email( $contact_id ) ); + $this->assertSame( $contact_id, jpcrm_portal_contact_id_for_user( $user_id ) ); + $this->assertEmpty( $this->sent, 'A confirmation email was sent for a change an administrator made.' ); + } + + /** + * @testdox An administrator can bring back a user who changed their own address and could not confirm it. + */ + #[TestDox( 'An administrator can bring back a user who changed their own address and could not confirm it.' )] + public function test_admin_change_recovers_a_user_with_an_unconfirmed_address() { + $user_id = $this->user( 'alex@example.test' ); + $contact_id = $this->contact( 'alex@example.test', $user_id ); + $this->confirm_user_email( $user_id ); + + // The user mistypes their new address, so can never confirm it. + wp_set_current_user( $user_id ); + wp_update_user( + array( + 'ID' => $user_id, + 'user_email' => 'alex@typo.example.test', + ) + ); + $this->assertSame( 0, jpcrm_portal_contact_id_for_user( $user_id ) ); + + // An administrator sets the right one. + wp_set_current_user( $this->user( 'admin@example.test', 'administrator' ) ); + wp_update_user( + array( + 'ID' => $user_id, + 'user_email' => 'alex@new.example.test', + ) + ); + + $this->assertSame( 'alex@new.example.test', $this->contact_email( $contact_id ) ); + $this->assertSame( $contact_id, jpcrm_portal_contact_id_for_user( $user_id ) ); + } + + /** + * @testdox WooCommerce confirming a customer's email address confirms it for the portal. + */ + #[TestDox( 'WooCommerce confirming a customer\'s email address confirms it for the portal.' )] + public function test_woocommerce_verification_confirms() { + $user_id = $this->user( 'alex@example.test' ); + $contact_id = $this->contact( 'alex@example.test' ); + + // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound -- WooCommerce's action. + do_action( 'woocommerce_customer_email_verified', $user_id ); + + $this->assertSame( $contact_id, jpcrm_portal_contact_id_for_user( $user_id ) ); + } + + /** + * @testdox A profile update only changes the name of a contact the user is. + */ + #[TestDox( 'A profile update only changes the name of a contact the user is.' )] + public function test_profile_update_only_reaches_the_users_own_contact() { + global $zbs; + + // Somebody who merely registered with a contact's address. + $stranger_id = $this->user( 'alex@example.test' ); + $contact_id = $this->contact( 'alex@example.test' ); + + wp_set_current_user( $stranger_id ); + wp_update_user( + array( + 'ID' => $stranger_id, + 'first_name' => 'Mallory', + ) + ); + + $contact = $zbs->DAL->contacts->getContact( $contact_id ); // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase + $this->assertSame( 'Alex', $contact['fname'], 'An unconfirmed user changed a contact\'s name.' ); + + // The same user, once linked and confirmed. + zeroBS_setCustomerWPID( $contact_id, $stranger_id ); + $this->confirm_user_email( $stranger_id ); + wp_update_user( + array( + 'ID' => $stranger_id, + 'first_name' => 'Alexandra', + ) + ); + + $contact = $zbs->DAL->contacts->getContact( $contact_id ); // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase + $this->assertSame( 'Alexandra', $contact['fname'] ); + } + + /** + * @testdox An account the CRM creates for a contact has nothing to confirm. + */ + #[TestDox( 'An account the CRM creates for a contact has nothing to confirm.' )] + public function test_crm_created_account_is_confirmed() { + $contact_id = $this->contact( 'alex@example.test' ); + + zeroBSCRM_createClientPortalUserFromRecord( $contact_id ); + $user = get_user_by( 'email', 'alex@example.test' ); + + $this->assertInstanceOf( \WP_User::class, $user ); + $this->assertSame( $contact_id, jpcrm_portal_contact_id_for_user( $user->ID ) ); + } + + /** + * @testdox The portal asks customers to confirm, and does not ask staff. + */ + #[TestDox( 'The portal asks customers to confirm, and does not ask staff.' )] + public function test_who_is_asked_to_confirm() { + $customer_id = $this->user( 'alex@example.test' ); + + wp_set_current_user( $customer_id ); + $this->assertTrue( jpcrm_portal_user_needs_email_confirmation() ); + + $this->confirm_user_email( $customer_id ); + $this->assertFalse( jpcrm_portal_user_needs_email_confirmation() ); + + wp_set_current_user( $this->user( 'admin@example.test', 'administrator' ) ); + $this->assertFalse( jpcrm_portal_user_needs_email_confirmation() ); + } + + /** + * Render the portal dashboard as the current user. + * + * @return string + */ + private function render_dashboard(): string { + global $zbs; + + $endpoint = null; + foreach ( $zbs->modules->portal->endpoints as $candidate ) { + if ( 'dashboard' === $candidate->slug ) { + $endpoint = $candidate; + } + } + $this->assertNotNull( $endpoint, 'The portal has no dashboard endpoint.' ); + + ob_start(); + $endpoint->perform_endpoint_action(); + return (string) ob_get_clean(); + } + + /** + * @testdox The portal shows an unconfirmed user the confirmation screen, sends the email, and shows nothing else. + */ + #[TestDox( 'The portal shows an unconfirmed user the confirmation screen, sends the email, and shows nothing else.' )] + public function test_portal_shows_the_confirmation_screen() { + $user_id = $this->user( 'alex@example.test' ); + $this->contact( 'alex@example.test', $user_id ); + wp_set_current_user( $user_id ); + + $html = $this->render_dashboard(); + + $this->assertStringContainsString( 'Confirm your email address', $html ); + $this->assertStringContainsString( 'alex@example.test', $html ); + $this->assertStringNotContainsString( 'zbs-portal-nav', $html, 'The portal navigation was shown to an unconfirmed user.' ); + $this->assertCount( 1, $this->sent, 'Viewing the screen did not send the confirmation email.' ); + + // Viewing it again does not send another. + $this->render_dashboard(); + $this->assertCount( 1, $this->sent ); + + // Once confirmed, the dashboard is shown instead. + jpcrm_portal_confirm_email_with_token( $user_id, $this->last_token() ); + $this->assertStringNotContainsString( 'Confirm your email address', $this->render_dashboard() ); + } +} diff --git a/tests/php/woo-sync/My_Account_Fields_Test.php b/tests/php/woo-sync/My_Account_Fields_Test.php index dbcb83ab..f0cddb51 100644 --- a/tests/php/woo-sync/My_Account_Fields_Test.php +++ b/tests/php/woo-sync/My_Account_Fields_Test.php @@ -112,6 +112,7 @@ public function test_my_account_saves_only_shown_editable_fields() { ) ); zeroBS_setCustomerWPID( $contact_id, $user_id ); + $this->confirm_user_email( $user_id ); $_POST = array( 'account_first_name' => 'Alex',