definition. */ public static function questions() { return self::get()['questions']; } /** * @param string $key Question key. * @return array|null */ public static function question( $key ) { $questions = self::questions(); return isset( $questions[ $key ] ) ? $questions[ $key ] : null; } /** * Questions asked in a stage, in schema order. * * @param string|string[] $stages Stage name(s). * @return array Key => definition. */ public static function questions_in( $stages ) { $stages = (array) $stages; $out = array(); foreach ( self::questions() as $key => $def ) { if ( self::is_asked( $def ) && isset( $def['stage'] ) && in_array( $def['stage'], $stages, true ) ) { $out[ $key ] = $def; } } return $out; } /** * Whether a definition is something the borrower answers. * * @param array $def Definition. * @return bool */ public static function is_asked( $def ) { if ( ! empty( $def['legacy'] ) || ! empty( $def['hidden'] ) ) { return false; } return isset( $def['type'] ) && 'derived' !== $def['type']; } /** * Apply 2.6 settings: English label overrides and fields toggled off. * * @param array $schema Schema. * @return array */ private static function apply_site_overrides( $schema ) { global $mortgage_application_required_form_fields; $required = is_array( $mortgage_application_required_form_fields ) ? $mortgage_application_required_form_fields : array(); $enabled = function_exists( 'get_front_mortgage_application_option' ) ? get_front_mortgage_application_option( 'mortgage_application_form_fields' ) : array(); $enabled = is_string( $enabled ) ? maybe_unserialize( $enabled ) : $enabled; // The network settings page stores the switches as JSON. if ( is_string( $enabled ) && '' !== $enabled ) { $decoded = json_decode( $enabled, true ); $enabled = is_array( $decoded ) ? $decoded : $enabled; } foreach ( $schema['questions'] as $key => &$def ) { if ( ! empty( $def['legacy'] ) || ( isset( $def['stage'] ) && 'full' === $def['stage'] ) ) { continue; } if ( function_exists( 'get_front_mortgage_application_option' ) ) { $label = get_front_mortgage_application_option( 'mortgage_application_label_' . $key ); if ( is_string( $label ) && '' !== trim( $label ) ) { $def['label']['en'] = trim( $label ); unset( $def['label_by'] ); } } // 2.6 stores the enabled toggles as an array keyed by field. Only // toggleable 2.6 fields can be hidden; required and new ones stay. if ( is_array( $enabled ) && ! empty( $enabled ) && self::is_toggleable_legacy_key( $key, $required ) && ! array_key_exists( $key, $enabled ) ) { $def['hidden'] = true; } } unset( $def ); return $schema; } /** * @param string $key Key. * @param array $required 2.6 required keys. * @return bool */ private static function is_toggleable_legacy_key( $key, $required ) { $toggleable = array( 'first_time_buyer', 'loan_purpose_purchase', 'mortgage_balance', 'loan_interest_rate', 'second_mortgage', 'reverse_mortgage', 'late_payments', 'foreclosure', 'monthly_income', 'mailing_address', 'military', 'agent_contact' ); return in_array( $key, $toggleable, true ) && ! in_array( $key, $required, true ); } /** * Evaluate a show_if list against answers. All conditions must hold. * * @param array $conditions List of [ key, op, value ]. * @param array $answers Answers (and, for repeat items, item answers merged over app answers). * @return bool */ public static function conditions_hold( $conditions, $answers ) { if ( empty( $conditions ) ) { return true; } foreach ( $conditions as $cond ) { list( $key, $op, $expected ) = array_pad( $cond, 3, '' ); $actual = isset( $answers[ $key ] ) ? $answers[ $key ] : ''; $actual = is_array( $actual ) ? $actual : (string) $actual; switch ( $op ) { case '=': $ok = ( $actual === (string) $expected ); break; case '!=': $ok = ( $actual !== (string) $expected ); break; case 'in': $ok = in_array( $actual, array_map( 'strval', (array) $expected ), true ); break; case 'not_in': $ok = ! in_array( $actual, array_map( 'strval', (array) $expected ), true ); break; case 'lt': $ok = ( '' !== $actual && ! is_array( $actual ) && (float) $actual < (float) $expected ); break; case 'gt': $ok = ( '' !== $actual && ! is_array( $actual ) && (float) $actual > (float) $expected ); break; default: $ok = false; } if ( ! $ok ) { return false; } } return true; } /** * Whether a question is shown for these answers. * * @param string $key Key. * @param array $answers Answers. * @return bool */ public static function is_visible( $key, $answers ) { $def = self::question( $key ); if ( ! $def || ! self::is_asked( $def ) ) { return false; } return self::conditions_hold( isset( $def['show_if'] ) ? $def['show_if'] : array(), $answers ); } /** * Steps whose conditions hold for these answers. * * @param array $answers Answers. * @return array */ public static function visible_steps( $answers ) { $out = array(); foreach ( self::get()['steps'] as $step ) { if ( ! self::conditions_hold( isset( $step['show_if'] ) ? $step['show_if'] : array(), $answers ) ) { continue; } if ( ! empty( $step['questions'] ) ) { $shown = array_filter( $step['questions'], function ( $key ) use ( $answers ) { return self::is_visible( $key, $answers ); } ); if ( empty( $shown ) ) { continue; } } $out[] = $step; } return $out; } /** * Sanitize one answer. Returns the stored value, or WP_Error. * * @param string $key Key. * @param mixed $value Raw value. * @param array $def Definition (defaults to the schema's). * @return mixed|\WP_Error */ public static function sanitize( $key, $value, $def = null ) { $def = $def ? $def : self::question( $key ); if ( ! $def || ! isset( $def['type'] ) || 'derived' === $def['type'] || ! empty( $def['legacy'] ) ) { return new \WP_Error( 'mapp_unknown_field', 'Unknown field.', array( 'field' => $key ) ); } if ( null === $value || '' === $value || array() === $value ) { return ''; } switch ( $def['type'] ) { case 'choice': case 'yesno': $value = is_scalar( $value ) ? (string) $value : ''; $allowed = wp_list_pluck( isset( $def['options'] ) ? $def['options'] : array(), 'value' ); return in_array( $value, $allowed, true ) ? $value : self::invalid( $key ); case 'multi': $allowed = wp_list_pluck( isset( $def['options'] ) ? $def['options'] : array(), 'value' ); $picked = array_values( array_intersect( array_map( 'strval', (array) $value ), $allowed ) ); return ! empty( $picked ) ? $picked : self::invalid( $key ); case 'currency': case 'number': $num = is_numeric( $value ) ? $value : preg_replace( '/[^\d.]/', '', (string) $value ); if ( '' === $num || ! is_numeric( $num ) ) { return self::invalid( $key ); } $num = (int) round( (float) $num ); return self::in_range( $num, $def ) ? (string) $num : self::invalid( $key ); case 'percent': $num = preg_replace( '/[^\d.]/', '', (string) $value ); if ( '' === $num || ! is_numeric( $num ) ) { return self::invalid( $key ); } $num = round( (float) $num, 3 ); return self::in_range( $num, $def ) ? rtrim( rtrim( number_format( $num, 3, '.', '' ), '0' ), '.' ) : self::invalid( $key ); case 'year': $year = (int) preg_replace( '/\D/', '', (string) $value ); $min = isset( $def['min'] ) ? (int) $def['min'] : 1900; return ( $year >= $min && $year <= (int) gmdate( 'Y' ) ) ? (string) $year : self::invalid( $key ); case 'text': $text = sanitize_text_field( (string) $value ); return mb_substr( $text, 0, 200 ); case 'email': $email = sanitize_email( (string) $value ); return is_email( $email ) ? strtolower( $email ) : self::invalid( $key ); case 'tel': $digits = preg_replace( '/\D/', '', (string) $value ); if ( 11 === strlen( $digits ) && '1' === $digits[0] ) { $digits = substr( $digits, 1 ); } if ( ! preg_match( '/^[2-9]\d{2}[2-9]\d{6}$/', $digits ) ) { return self::invalid( $key ); } return sprintf( '(%s) %s-%s', substr( $digits, 0, 3 ), substr( $digits, 3, 3 ), substr( $digits, 6 ) ); case 'date': return self::sanitize_date( $key, $value ); case 'ssn': $digits = preg_replace( '/\D/', '', (string) $value ); if ( ! preg_match( '/^(?!000|666|9\d\d)\d{3}(?!00)\d{2}(?!0000)\d{4}$/', $digits ) ) { return self::invalid( $key ); } return $digits; case 'consent': return ( true === $value || 'yes' === $value || '1' === (string) $value || 'true' === $value ) ? 'yes' : ''; case 'address': return self::sanitize_address( $key, $value ); case 'repeat': return self::sanitize_repeat( $key, $value, $def ); } return self::invalid( $key ); } /** * @param string $key Key. * @return \WP_Error */ private static function invalid( $key ) { return new \WP_Error( 'mapp_invalid', 'Please check this answer.', array( 'field' => $key ) ); } /** * @param float $num Number. * @param array $def Definition. * @return bool */ private static function in_range( $num, $def ) { if ( isset( $def['min'] ) && $num < $def['min'] ) { return false; } if ( isset( $def['max'] ) && $num > $def['max'] ) { return false; } return true; } /** * Dates are stored as YYYY-MM-DD. Accepts that or MM/DD/YYYY, MM-DD-YYYY. * * @param string $key Key. * @param mixed $value Value. * @return string|\WP_Error */ private static function sanitize_date( $key, $value ) { $value = trim( (string) $value ); if ( preg_match( '/^(\d{4})-(\d{2})-(\d{2})$/', $value, $m ) ) { list( , $y, $mo, $d ) = $m; } elseif ( preg_match( '#^(\d{1,2})[/-](\d{1,2})[/-](\d{4})$#', $value, $m ) ) { list( , $mo, $d, $y ) = $m; } else { return self::invalid( $key ); } if ( ! checkdate( (int) $mo, (int) $d, (int) $y ) || (int) $y < 1900 || (int) $y > (int) gmdate( 'Y' ) + 1 ) { return self::invalid( $key ); } return sprintf( '%04d-%02d-%02d', $y, $mo, $d ); } /** * Addresses arrive as { formatted, street, city, state, zip, county } or a * plain string (typed without autocomplete). * * @param string $key Key. * @param mixed $value Value. * @return array|\WP_Error */ private static function sanitize_address( $key, $value ) { if ( is_string( $value ) ) { $value = array( 'formatted' => $value ); } if ( ! is_array( $value ) ) { return self::invalid( $key ); } $out = array(); foreach ( array( 'formatted', 'street', 'city', 'state', 'zip', 'county' ) as $part ) { $out[ $part ] = isset( $value[ $part ] ) ? mb_substr( sanitize_text_field( (string) $value[ $part ] ), 0, 200 ) : ''; } // Typed without autocomplete (no Google key, or the borrower ignored the // list): split "Street, City, ST 12345" ourselves. if ( '' === $out['city'] && '' === $out['state'] && '' === $out['zip'] && '' !== $out['formatted'] ) { $out = array_merge( $out, self::parse_us_address( $out['formatted'] ) ); } $out['state'] = strtoupper( substr( $out['state'], 0, 2 ) ); $out['zip'] = preg_match( '/^\d{5}/', $out['zip'], $zm ) ? $zm[0] : ''; if ( '' === $out['formatted'] ) { $out['formatted'] = trim( implode( ', ', array_filter( array( $out['street'], $out['city'], trim( $out['state'] . ' ' . $out['zip'] ) ) ) ) ); } // A city or ZIP is enough for a purchase search area; anything shorter is not. return strlen( $out['formatted'] ) >= 3 ? $out : self::invalid( $key ); } /** * Best-effort split of a typed US address. Handles "Street, City, ST ZIP", * "City, ST ZIP", "City, ST", "ST ZIP" and a bare ZIP. * * @param string $text Address as typed. * @return array street, city, state, zip (only the parts found). */ public static function parse_us_address( $text ) { $text = trim( preg_replace( '/,?\s*(USA|United States)\.?$/i', '', trim( $text ) ) ); $found = array(); if ( preg_match( '/^\d{5}(-\d{4})?$/', $text ) ) { return array( 'zip' => substr( $text, 0, 5 ) ); } $parts = array_values( array_filter( array_map( 'trim', explode( ',', $text ) ), 'strlen' ) ); if ( ! $parts ) { return $found; } $last = array_pop( $parts ); if ( preg_match( '/^(.*?)\s*\b([A-Za-z]{2})\.?\s*(\d{5})?(?:-\d{4})?$/', $last, $m ) && in_array( strtoupper( $m[2] ), self::us_states(), true ) ) { $found['state'] = strtoupper( $m[2] ); if ( ! empty( $m[3] ) ) { $found['zip'] = $m[3]; } // "Austin TX 78701" with no comma before the state. if ( '' !== trim( $m[1] ) ) { $parts[] = trim( $m[1] ); } } else { $parts[] = $last; } if ( $parts ) { $found['city'] = array_pop( $parts ); } if ( $parts ) { $found['street'] = implode( ', ', $parts ); } // A lone part that starts with a number is a street, not a city. if ( isset( $found['city'] ) && ! isset( $found['street'] ) && preg_match( '/^\d+\s/', $found['city'] ) ) { $found['street'] = $found['city']; unset( $found['city'] ); } return $found; } /** @return string[] USPS state and territory codes. */ private static function us_states() { return array( 'AL', 'AK', 'AZ', 'AR', 'CA', 'CO', 'CT', 'DE', 'DC', 'FL', 'GA', 'HI', 'ID', 'IL', 'IN', 'IA', 'KS', 'KY', 'LA', 'ME', 'MD', 'MA', 'MI', 'MN', 'MS', 'MO', 'MT', 'NE', 'NV', 'NH', 'NJ', 'NM', 'NY', 'NC', 'ND', 'OH', 'OK', 'OR', 'PA', 'RI', 'SC', 'SD', 'TN', 'TX', 'UT', 'VT', 'VA', 'WA', 'WV', 'WI', 'WY', 'PR', 'GU', 'VI', 'AS', 'MP' ); } /** * @param string $key Key. * @param mixed $value List of items. * @param array $def Definition. * @return array|\WP_Error */ private static function sanitize_repeat( $key, $value, $def ) { if ( ! is_array( $value ) ) { return self::invalid( $key ); } $max = isset( $def['max'] ) ? (int) $def['max'] : 20; $items = array(); foreach ( array_slice( array_values( $value ), 0, $max ) as $raw_item ) { if ( ! is_array( $raw_item ) ) { continue; } $item = array(); foreach ( $def['fields'] as $field_key => $field_def ) { if ( ! array_key_exists( $field_key, $raw_item ) ) { continue; } $clean = self::sanitize( $key . '.' . $field_key, $raw_item[ $field_key ], $field_def ); if ( is_wp_error( $clean ) ) { return $clean; } if ( '' !== $clean ) { $item[ $field_key ] = $clean; } } if ( ! empty( $item ) ) { $items[] = $item; } } return $items; } /** * Required questions that are visible and still unanswered for a stage. * Repeat items are checked field by field. * * @param string|string[] $stages Stage(s). * @param array $answers Answers. * @return string[] Missing keys (repeat fields as key.index.field). */ public static function missing( $stages, $answers ) { $missing = array(); foreach ( self::questions_in( $stages ) as $key => $def ) { if ( ! self::is_visible( $key, $answers ) ) { continue; } $required = ! isset( $def['required'] ) || $def['required']; $value = isset( $answers[ $key ] ) ? $answers[ $key ] : ''; if ( 'repeat' === $def['type'] ) { if ( is_array( $value ) ) { foreach ( $value as $i => $item ) { foreach ( $def['fields'] as $field_key => $field_def ) { $field_required = ! isset( $field_def['required'] ) || $field_def['required']; $scope = array_merge( $answers, (array) $item ); $shown = self::conditions_hold( isset( $field_def['show_if'] ) ? $field_def['show_if'] : array(), $scope ); if ( $field_required && $shown && ( ! isset( $item[ $field_key ] ) || '' === $item[ $field_key ] ) ) { $missing[] = $key . '.' . $i . '.' . $field_key; } } } } $min = isset( $def['min'] ) ? (int) $def['min'] : 0; if ( ! empty( $def['min_if'] ) && self::conditions_hold( $def['min_if'], $answers ) ) { $min = max( 1, $min ); } if ( $min > 0 && count( (array) $value ) < $min ) { $missing[] = $key; } continue; } if ( 'consent' === $def['type'] ) { if ( $required && 'yes' !== $value ) { $missing[] = $key; } continue; } if ( $required && ( '' === $value || array() === $value ) ) { $missing[] = $key; } } return $missing; } /** * Label in a language, falling back to English. * * @param array|string $label Label pair or string. * @param string $lang en | es. * @return string */ public static function text( $label, $lang = 'en' ) { if ( is_string( $label ) ) { return $label; } if ( isset( $label[ $lang ] ) && '' !== $label[ $lang ] ) { return $label[ $lang ]; } return isset( $label['en'] ) ? $label['en'] : ''; } /** * Short LO-facing label (emails, GHL notes, admin), falling back to the * borrower's question wording. * * @param string $key Key. * @return string */ public static function admin_label( $key ) { $def = self::question( $key ); if ( ! $def ) { return $key; } if ( ! empty( $def['admin_label'] ) ) { return $def['admin_label']; } $label = self::text( isset( $def['label'] ) ? $def['label'] : $key ); // Co-borrower copies reuse the borrower's wording; say whose answer it is. if ( isset( $def['role'] ) && 'coborrower' === $def['role'] && 0 !== stripos( $label, 'co-borrower' ) ) { return 'Co-borrower: ' . lcfirst( $label ); } return $label; } /** * Human-readable answer for emails, notes and the admin. * * @param string $key Key. * @param mixed $value Stored value. * @param string $lang Language. * @return string */ public static function display_value( $key, $value, $lang = 'en' ) { $def = self::question( $key ); if ( '' === $value || null === $value ) { return ''; } if ( ! $def ) { return is_scalar( $value ) ? (string) $value : wp_json_encode( $value ); } $type = isset( $def['type'] ) ? $def['type'] : 'text'; if ( ! empty( $def['sensitive'] ) ) { return 'ssn' === $type && is_string( $value ) && strlen( $value ) >= 4 ? '•••-••-' . substr( $value, -4 ) : '••••'; } switch ( $type ) { case 'choice': case 'yesno': foreach ( isset( $def['options'] ) ? $def['options'] : array() as $opt ) { if ( $opt['value'] === (string) $value ) { return self::text( $opt['label'], $lang ); } } return (string) $value; case 'multi': $labels = array(); foreach ( (array) $value as $v ) { $labels[] = self::display_value_option( $def, $v, $lang ); } return implode( ', ', $labels ); case 'currency': return '$' . number_format( (float) $value ); case 'percent': return $value . '%'; case 'date': // Displayed dates are MM-DD-YYYY. return preg_match( '/^(\d{4})-(\d{2})-(\d{2})$/', (string) $value, $m ) ? $m[2] . '-' . $m[3] . '-' . $m[1] : (string) $value; case 'address': return is_array( $value ) ? (string) $value['formatted'] : (string) $value; case 'consent': return 'yes' === $value ? ( 'es' === $lang ? 'Aceptado' : 'Agreed' ) : ''; case 'repeat': $lines = array(); foreach ( (array) $value as $i => $item ) { $parts = array(); foreach ( $def['fields'] as $field_key => $field_def ) { if ( isset( $item[ $field_key ] ) && '' !== $item[ $field_key ] ) { $parts[] = self::text( $field_def['label'], $lang ) . ': ' . self::display_field_value( $field_def, $item[ $field_key ], $lang ); } } $lines[] = ( $i + 1 ) . '. ' . implode( '; ', $parts ); } return implode( "\n", $lines ); } return is_scalar( $value ) ? (string) $value : wp_json_encode( $value ); } /** * @param array $def Field definition. * @param mixed $value Value. * @param string $lang Language. * @return string */ private static function display_field_value( $def, $value, $lang ) { switch ( $def['type'] ) { case 'choice': case 'yesno': return self::display_value_option( $def, $value, $lang ); case 'currency': return '$' . number_format( (float) $value ); case 'date': return preg_match( '/^(\d{4})-(\d{2})-(\d{2})$/', (string) $value, $m ) ? $m[2] . '-' . $m[3] . '-' . $m[1] : (string) $value; } return is_scalar( $value ) ? (string) $value : wp_json_encode( $value ); } /** * @param array $def Definition with options. * @param string $value Value. * @param string $lang Language. * @return string */ private static function display_value_option( $def, $value, $lang ) { foreach ( isset( $def['options'] ) ? $def['options'] : array() as $opt ) { if ( $opt['value'] === (string) $value ) { return self::text( $opt['label'], $lang ); } } return (string) $value; } /** * The schema as the browser needs it: asked questions only, no internals. * * @return array */ public static function public_payload() { $schema = self::get(); $questions = array(); foreach ( $schema['questions'] as $key => $def ) { if ( ! self::is_asked( $def ) ) { continue; } unset( $def['terms_option'], $def['admin_label'] ); $questions[ $key ] = $def; } return array( 'version' => $schema['version'], 'questions' => $questions, 'steps' => $schema['steps'], 'sections' => $schema['sections'], ); } }