settings = $settings;
$this->leads = $leads;
}
/**
* Hooked to thinroof_lead_created.
*
* @param int $lead_id Lead ID.
* @param array|null $lead Lead row.
*/
public function on_lead_created( int $lead_id, $lead ): void {
if ( ! is_array( $lead ) ) {
return;
}
$email = $this->settings->get( 'email' );
if ( ! empty( $email['admin_enabled'] ) ) {
$this->record( $lead_id, 'admin', $this->send_admin( $lead ) );
}
if ( ! empty( $email['visitor_enabled'] ) && is_email( $lead['email'] ) ) {
$this->record( $lead_id, 'visitor', $this->send_visitor( $lead ) );
}
}
/**
* Send the admin notification.
*
* @param array $lead Lead.
* @return true|WP_Error
*/
public function send_admin( array $lead ) {
$email = $this->settings->get( 'email' );
$recipients = array_filter( array_map( 'trim', explode( ',', (string) $email['admin_recipients'] ) ), 'is_email' );
if ( ! $recipients ) {
$recipients = array( (string) get_option( 'admin_email' ) );
}
$tags = $this->tags( $lead );
$subject = $this->render( $email['admin_subject'] ? $email['admin_subject'] : $this->settings->defaults( 'email' )['admin_subject'], $tags, false );
$body = $this->render( $email['admin_template'] ? $email['admin_template'] : Settings::default_admin_template(), $tags, true );
// Replies go straight to the homeowner.
$headers = array( 'Reply-To: ' . $this->address( $lead['full_name'], $lead['email'] ) );
return $this->send( $recipients, $subject, $body, $headers );
}
/**
* Send the visitor confirmation.
*
* @param array $lead Lead.
* @return true|WP_Error
*/
public function send_visitor( array $lead ) {
$email = $this->settings->get( 'email' );
$tags = $this->tags( $lead );
$subject = $this->render( $email['visitor_subject'] ? $email['visitor_subject'] : $this->settings->defaults( 'email' )['visitor_subject'], $tags, false );
$body = $this->render( $email['visitor_template'] ? $email['visitor_template'] : Settings::default_visitor_template(), $tags, true );
$reply = $email['reply_to'] ? $email['reply_to'] : (string) get_option( 'admin_email' );
$headers = array( 'Reply-To: ' . $this->address( $this->business_name(), $reply ) );
return $this->send( array( $lead['email'] ), $subject, $body, $headers );
}
/**
* Send a test message.
*
* @param string $to Address.
* @return true|WP_Error
*/
public function send_test( string $to ) {
if ( ! is_email( $to ) ) {
return new WP_Error( 'thinroof_bad_address', __( 'Enter a valid email address for the test.', 'thinroof' ) );
}
$result = $this->send(
array( $to ),
/* translators: %s: business name. */
sprintf( __( 'ThinRoof test email from %s', 'thinroof' ), $this->business_name() ),
'
' . esc_html__( 'This is a test email from ThinRoof. If you received it, WordPress can send email from this site.', 'thinroof' ) . '
',
array()
);
$this->append_log( 0, 'test', $result );
return $result;
}
/**
* Capture wp_mail() failures (only while we are sending).
*
* @param WP_Error $error Error.
*/
public function capture_mail_error( $error ): void {
if ( $this->sending && $error instanceof WP_Error ) {
$this->last_error = $error;
}
}
/**
* Template tags for a lead.
*
* @param array $lead Lead.
* @return array
*/
public function tags( array $lead ): array {
$labels = Labels::instance();
$name = (string) $lead['full_name'];
$first = trim( (string) strtok( $name, ' ' ) );
$general = $this->settings->get( 'general' );
$tags = array(
'business_name' => $this->business_name(),
'site_name' => wp_specialchars_decode( (string) get_bloginfo( 'name' ), ENT_QUOTES ),
'full_name' => $name,
'first_name' => $first,
'email' => (string) $lead['email'],
'phone' => '' !== (string) $lead['phone'] ? (string) $lead['phone'] : '—',
'zip' => (string) $lead['zip'],
'property_type' => $labels->display( 'property_type', $lead['property_type'] ),
'project_type' => $labels->display( 'project_type', $lead['project_type'] ),
'material' => '' !== (string) $lead['material'] ? $labels->display( 'material', $lead['material'] ) : '—',
'pitch' => $labels->display( 'pitch', $lead['pitch'] ),
'stories' => $labels->display( 'stories', $lead['stories'] ),
'tear_off' => $labels->display( 'tear_off', $lead['tear_off'] ),
'roof_area' => number_format_i18n( (int) $lead['roof_area'] ),
'roof_squares' => number_format_i18n( (int) $lead['roof_area'] / Pricing_Engine::SQ_FT_PER_SQUARE, 1 ),
'estimate_total' => Pricing_Engine::money( (float) $lead['estimate_total'] ),
'estimate_range' => Pricing_Engine::range_text( $lead ),
'budget' => '' !== (string) $lead['budget'] ? $labels->display( 'budget', $lead['budget'] ) : '—',
'timeline' => '' !== (string) $lead['timeline'] ? $labels->display( 'timeline', $lead['timeline'] ) : '—',
'notes' => '' !== (string) $lead['notes'] ? (string) $lead['notes'] : '—',
'marketing_consent' => $labels->display( 'marketing_consent', $lead['marketing_consent'] ),
'lead_id' => (string) (int) $lead['id'],
'lead_url' => admin_url( 'admin.php?page=thinroof-leads&lead=' . (int) $lead['id'] ),
'disclaimer' => (string) $general['default_disclaimer'],
'date' => $labels->display( 'created_at', $lead['created_at'] ),
);
/**
* Filter email template tags.
*
* @param array $tags Tags (raw values; escaped on render).
* @param array $lead Lead.
*/
return (array) apply_filters( 'thinroof_email_tags', $tags, $lead );
}
/**
* Replace {tags}. Values are escaped for HTML bodies; subjects are plain text.
*
* @param string $template Template.
* @param array $tags Tags.
* @param bool $html HTML body.
*/
public function render( string $template, array $tags, bool $html ): string {
$replace = array();
foreach ( $tags as $key => $value ) {
$value = (string) $value;
if ( $html ) {
$value = 'lead_url' === $key ? esc_url( $value ) : nl2br( esc_html( $value ) );
} else {
$value = Settings::header_text( $value );
}
$replace[ '{' . $key . '}' ] = $value;
}
$out = strtr( $template, $replace );
return $html ? $out : Settings::header_text( $out );
}
/**
* Recent delivery log.
*
* @return array
*/
public function log_entries(): array {
$log = get_option( self::OPTION_LOG, array() );
return is_array( $log ) ? $log : array();
}
/**
* The most recent failure, if the most recent send failed.
*/
public function last_failure(): ?array {
$log = $this->log_entries();
return ( $log && empty( $log[0]['ok'] ) ) ? $log[0] : null;
}
/**
* Business name used in emails.
*/
public function business_name(): string {
$email = (string) $this->settings->value( 'email', 'business_name', '' );
if ( '' !== $email ) {
return $email;
}
$general = (string) $this->settings->value( 'general', 'business_name', '' );
return '' !== $general ? $general : wp_specialchars_decode( (string) get_bloginfo( 'name' ), ENT_QUOTES );
}
/**
* Wrap wp_mail() and report the real error.
*
* @param string[] $to Recipients.
* @param string $subject Subject.
* @param string $body HTML body fragment.
* @param string[] $headers Headers.
* @return true|WP_Error
*/
private function send( array $to, string $subject, string $body, array $headers ) {
$headers[] = 'Content-Type: text/html; charset=UTF-8';
$from_name = (string) $this->settings->value( 'email', 'from_name', '' );
$name_filter = static fn() => $from_name;
if ( '' !== $from_name ) {
add_filter( 'wp_mail_from_name', $name_filter, 20 );
}
$this->sending = true;
$this->last_error = null;
$sent = wp_mail( $to, $subject, $this->wrap( $body ), $headers );
$this->sending = false;
if ( '' !== $from_name ) {
remove_filter( 'wp_mail_from_name', $name_filter, 20 );
}
if ( $sent ) {
return true;
}
$reason = $this->last_error ? $this->last_error->get_error_message() : __( 'wp_mail() returned false without an error message. Your server may not be able to send email; an SMTP plugin usually fixes this.', 'thinroof' );
return new WP_Error( 'thinroof_mail_failed', $reason );
}
/**
* Minimal, client-safe HTML wrapper.
*
* @param string $body Body fragment.
*/
private function wrap( string $body ): string {
$color = esc_attr( (string) $this->settings->value( 'general', 'primary_color', '#0b2545' ) );
return ''
. ''
. $body
. '
';
}
/**
* "Name " with header-safe name.
*
* @param string $name Name.
* @param string $email Email.
*/
private function address( string $name, string $email ): string {
$name = str_replace( array( '"', '<', '>' ), '', Settings::header_text( $name ) );
return '' !== $name ? sprintf( '"%s" <%s>', $name, sanitize_email( $email ) ) : sanitize_email( $email );
}
/**
* Record outcome in activity + log.
*
* @param int $lead_id Lead.
* @param string $type admin|visitor.
* @param true|WP_Error $result Result.
*/
private function record( int $lead_id, string $type, $result ): void {
$label = 'admin' === $type ? __( 'Admin notification', 'thinroof' ) : __( 'Visitor confirmation', 'thinroof' );
if ( true === $result ) {
/* translators: %s: email type. */
$this->leads->log( $lead_id, 'email_sent', sprintf( __( '%s sent.', 'thinroof' ), $label ) );
} else {
/* translators: 1: email type, 2: error. */
$this->leads->log( $lead_id, 'email_failed', sprintf( __( '%1$s failed: %2$s', 'thinroof' ), $label, $result->get_error_message() ) );
}
$this->append_log( $lead_id, $type, $result );
}
/**
* Append to the rolling log (no message bodies or addresses).
*
* @param int $lead_id Lead.
* @param string $type Type.
* @param true|WP_Error $result Result.
*/
private function append_log( int $lead_id, string $type, $result ): void {
$log = $this->log_entries();
array_unshift(
$log,
array(
'time' => time(),
'type' => $type,
'lead_id' => $lead_id,
'ok' => true === $result,
'error' => true === $result ? '' : sanitize_text_field( $result->get_error_message() ),
)
);
update_option( self::OPTION_LOG, array_slice( $log, 0, self::LOG_SIZE ), false );
}
}