This commit is contained in:
Rachit Bhargava
2024-01-10 11:53:33 -05:00
parent 83d223b0df
commit 054b4fffc9
16481 changed files with 0 additions and 3473867 deletions

View File

@@ -1,547 +0,0 @@
<?php
namespace WPMailSMTP\Providers\Gmail;
use Exception;
use WPMailSMTP\Admin\Area;
use WPMailSMTP\Admin\ConnectionSettings;
use WPMailSMTP\Admin\DebugEvents\DebugEvents;
use WPMailSMTP\Admin\SetupWizard;
use WPMailSMTP\ConnectionInterface;
use WPMailSMTP\Debug;
use WPMailSMTP\Providers\AuthAbstract;
use WPMailSMTP\Vendor\Google_Client;
use WPMailSMTP\Vendor\Google\Service\Gmail;
/**
* Class Auth to request access and refresh tokens.
*
* @since 1.0.0
*/
class Auth extends AuthAbstract {
/**
* List of all possible "from email" email addresses (aliases).
*
* @since 2.2.0
*
* @var null|array
*/
private $aliases = null;
/**
* Auth constructor.
*
* @since 1.0.0
*
* @param ConnectionInterface $connection The Connection object.
*/
public function __construct( $connection = null ) {
parent::__construct( $connection );
if ( $this->mailer_slug !== Options::SLUG ) {
return;
}
$this->options = $this->connection_options->get_group( $this->mailer_slug );
if ( $this->is_clients_saved() ) {
$this->include_vendor_lib();
$this->client = $this->get_client();
}
}
/**
* Get the url, that users will be redirected back to finish the OAuth process.
*
* @since 1.5.2 Returned to the old, pre-1.5, structure of the link to preserve BC.
*
* @param ConnectionInterface $connection The Connection object.
*
* @return string
*/
public static function get_plugin_auth_url( $connection = null ) {
if ( is_null( $connection ) ) {
$connection = wp_mail_smtp()->get_connections_manager()->get_primary_connection();
}
$auth_url = apply_filters(
'wp_mail_smtp_gmail_get_plugin_auth_url',
add_query_arg(
[
'page' => Area::SLUG,
'tab' => 'auth',
],
admin_url( 'options-general.php' )
)
);
return add_query_arg( 'state', self::get_state_param( $connection ), $auth_url );
}
/**
* Init and get the Google Client object.
*
* @since 1.0.0
* @since 1.5.0 Add ability to apply custom options to the client via a filter.
*
* @param bool $force If the client should be forcefully reinitialized.
*
* @return Google_Client
*/
public function get_client( $force = false ) { // phpcs:ignore Generic.Metrics.CyclomaticComplexity.MaxExceeded
// Doesn't load client twice + gives ability to overwrite.
if ( ! empty( $this->client ) && ! $force ) {
return $this->client;
}
$this->include_vendor_lib();
$client = new Google_Client(
array(
'client_id' => $this->options['client_id'],
'client_secret' => $this->options['client_secret'],
'redirect_uris' => array(
self::get_oauth_redirect_url(),
),
)
);
$client->setApplicationName( 'WP Mail SMTP v' . WPMS_PLUGIN_VER );
$client->setAccessType( 'offline' );
$client->setPrompt( 'consent' );
$client->setIncludeGrantedScopes( false );
// We request only the sending capability, as it's what we only need to do.
$client->setScopes( array( Gmail::MAIL_GOOGLE_COM ) );
$client->setRedirectUri( self::get_oauth_redirect_url() );
if ( self::use_self_oauth_redirect_url() ) {
$client->setState( self::get_state_param( $this->connection ) );
} else {
$client->setState( self::get_plugin_auth_url( $this->connection ) );
}
// Apply custom options to the client.
$client = apply_filters( 'wp_mail_smtp_providers_gmail_auth_get_client_custom_options', $client );
if (
$this->is_auth_required() &&
! empty( $this->options['auth_code'] )
) {
try {
$creds = $client->fetchAccessTokenWithAuthCode( $this->options['auth_code'] );
} catch ( Exception $e ) {
$creds['error'] = $e->getMessage();
}
// Bail if we have an error.
if ( ! empty( $creds['error'] ) ) {
if ( $creds['error'] === 'invalid_client' ) {
$creds['error'] .= PHP_EOL . esc_html__( 'Please make sure your Google Client ID and Secret in the plugin settings are valid. Save the settings and try the Authorization again.' , 'wp-mail-smtp' );
}
Debug::set(
'Mailer: Gmail' . "\r\n" .
$creds['error']
);
return $client;
} else {
Debug::clear();
}
$this->update_access_token( $client->getAccessToken() );
$this->update_refresh_token( $client->getRefreshToken() );
$this->update_user_details( $client );
// Update the "from email" to the connected user's email.
if ( ! empty( $this->options['user_details']['email'] ) ) {
$this->connection_options->set(
[
'mail' => [
'from_email' => $this->options['user_details']['email'],
],
],
false,
false
);
}
}
if ( ! empty( $this->options['access_token'] ) ) {
$client->setAccessToken( $this->options['access_token'] );
}
// Refresh the token if it's expired.
if ( $client->isAccessTokenExpired() ) {
$refresh = $client->getRefreshToken();
if ( empty( $refresh ) && isset( $this->options['refresh_token'] ) ) {
$refresh = $this->options['refresh_token'];
}
if ( ! empty( $refresh ) ) {
try {
$creds = $client->fetchAccessTokenWithRefreshToken( $refresh );
} catch ( Exception $e ) {
$creds['error'] = $e->getMessage();
Debug::set(
'Mailer: Gmail' . "\r\n" .
$e->getMessage()
);
}
// Bail if we have an error.
if ( ! empty( $creds['error'] ) ) {
return $client;
}
$this->update_access_token( $client->getAccessToken() );
$this->update_refresh_token( $client->getRefreshToken() );
}
}
return $client;
}
/**
* Get the auth code from the $_GET and save it.
* Redirect user back to settings with an error message, if failed.
*
* @since 1.0.0
*/
public function process() { // phpcs:ignore Generic.Metrics.CyclomaticComplexity.MaxExceeded
$redirect_url = ( new ConnectionSettings( $this->connection ) )->get_admin_page_url();
$is_setup_wizard_auth = ! empty( $this->options['is_setup_wizard_auth'] );
if ( $is_setup_wizard_auth ) {
$this->update_is_setup_wizard_auth( false );
$redirect_url = SetupWizard::get_site_url() . '#/step/configure_mailer/gmail';
}
if ( ! ( isset( $_GET['tab'] ) && $_GET['tab'] === 'auth' ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended
wp_safe_redirect( $redirect_url );
exit;
}
$state = isset( $_GET['state'] ) ? sanitize_key( $_GET['state'] ) : false;
if ( empty( $state ) ) {
wp_safe_redirect(
add_query_arg( 'error', 'oauth_invalid_state', $redirect_url )
);
}
list( $nonce ) = array_pad( explode( '-', $state ), 1, false );
// Verify the nonce that should be returned in the state parameter.
if ( ! wp_verify_nonce( $nonce, $this->state_key ) ) {
wp_safe_redirect(
add_query_arg(
'error',
'google_invalid_nonce',
$redirect_url
)
);
exit;
}
// We can't process without saved client_id/secret.
if ( ! $this->is_clients_saved() ) {
Debug::set(
esc_html__( 'There was an error while processing the Google authentication request. Please make sure that you have Client ID and Client Secret both valid and saved.', 'wp-mail-smtp' )
);
wp_safe_redirect(
add_query_arg(
'error',
'google_no_clients',
$redirect_url
)
);
exit;
}
$this->include_vendor_lib();
$code = '';
$scope = '';
$error = '';
if ( isset( $_GET['error'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended
$error = sanitize_key( $_GET['error'] ); // phpcs:ignore WordPress.Security.NonceVerification.Recommended
}
// In case of any error: display a message to a user.
if ( ! empty( $error ) ) {
DebugEvents::add_debug(
sprintf( /* Translators: %s the error code passed from Google. */
esc_html__( 'There was an error while processing Google authorization: %s' ),
esc_html( $error )
)
);
wp_safe_redirect(
add_query_arg(
'error',
'google_' . $error,
$redirect_url
)
);
exit;
}
if ( isset( $_GET['code'] ) ) {
// phpcs:ignore WordPress.Security.NonceVerification.Recommended, WordPress.Security.ValidatedSanitizedInput.MissingUnslash, WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
$code = urldecode( $_GET['code'] );
}
if ( isset( $_GET['scope'] ) ) {
// phpcs:ignore WordPress.Security.NonceVerification.Recommended, WordPress.Security.ValidatedSanitizedInput.MissingUnslash, WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
$scope = $_GET['scope'];
if ( self::use_self_oauth_redirect_url() ) {
$scope = urldecode( $scope );
} else {
// phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_decode
$scope = urldecode( base64_decode( $scope ) );
}
}
// Let's try to get the access token.
if (
! empty( $code ) &&
(
$scope === Gmail::MAIL_GOOGLE_COM . ' ' . Gmail::GMAIL_SEND ||
$scope === Gmail::GMAIL_SEND . ' ' . Gmail::MAIL_GOOGLE_COM ||
$scope === Gmail::GMAIL_SEND ||
$scope === Gmail::MAIL_GOOGLE_COM
)
) {
// Save the auth code. So Google_Client can reuse it to retrieve the access token.
$this->update_auth_code( $code );
} else {
DebugEvents::add_debug(
esc_html__( 'There was an error while processing Google authorization: missing code or scope parameter.' )
);
wp_safe_redirect(
add_query_arg(
'error',
'google_no_code_scope',
$redirect_url
)
);
exit;
}
Debug::clear();
$this->get_client( true );
$error = Debug::get_last();
if ( ! empty( $error ) ) {
wp_safe_redirect(
add_query_arg(
'error',
'google_unsuccessful_oauth',
$redirect_url
)
);
exit;
}
wp_safe_redirect(
add_query_arg(
'success',
'google_site_linked',
$redirect_url
)
);
exit;
}
/**
* Get the auth URL used to proceed to Provider to request access to send emails.
*
* @since 1.0.0
*
* @return string
*/
public function get_auth_url() {
if (
! empty( $this->client ) &&
class_exists( 'WPMailSMTP\Vendor\Google_Client', false ) &&
$this->client instanceof Google_Client
) {
return filter_var( $this->client->createAuthUrl(), FILTER_SANITIZE_URL );
}
return '#';
}
/**
* Get and update user-related details (currently only email).
*
* @since 3.11.0
*
* @param Google_Client $client The Google Client object (optional).
*/
private function update_user_details( $client = false ) {
if ( $client === false ) {
$client = $this->get_client();
}
$gmail = new Gmail( $client );
try {
$email = $gmail->users->getProfile( 'me' )->getEmailAddress();
$user_details = [
'email' => $email,
];
// To save in DB.
$updated_settings = [
$this->mailer_slug => [
'user_details' => $user_details,
],
];
// To save in currently retrieved options array.
$this->options['user_details'] = $user_details;
$this->connection_options->set( $updated_settings, false, false );
} catch ( Exception $e ) { // phpcs:ignore Generic.CodeAnalysis.EmptyStatement.DetectedCatch
// Do nothing.
}
}
/**
* Get user information (currently only email) that is associated with the current OAuth connection.
*
* @since 1.5.0
* @since 3.11.0 Switched to DB stored value instead of API call.
*
* @return array
*/
public function get_user_info() {
/*
* We need to populate user data on the fly for old users who already performed
* authorization before we switched to DB stored value.
*/
if ( ! isset( $this->options['user_details'] ) && ! $this->is_auth_required() ) {
$this->update_user_details();
}
return $this->connection_options->get( $this->mailer_slug, 'user_details' );
}
/**
* Get the registered email addresses that the user can use as the "from email".
*
* @since 2.2.0
*
* @return array The list of possible from email addresses.
*/
public function get_user_possible_send_from_addresses() {
if ( isset( $this->aliases ) ) {
return $this->aliases;
}
$gmail = new Gmail( $this->get_client() );
try {
// phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase
$response = $gmail->users_settings_sendAs->listUsersSettingsSendAs( 'me' );
// phpcs:disable
$this->aliases = array_map(
function( $sendAsObject ) {
return $sendAsObject['sendAsEmail'];
},
(array) $response->getSendAs()
);
// phpcs:enable
} catch ( Exception $exception ) {
DebugEvents::add_debug(
sprintf( /* Translators: %s the error message. */
esc_html__( 'An error occurred when trying to get Gmail aliases: %s' ),
esc_html( $exception->getMessage() )
)
);
$this->aliases = [];
}
return $this->aliases;
}
/**
* Get the Google oAuth 2.0 redirect URL.
*
* This is the URL that Google will redirect after the access to the Gmail account is granted or rejected.
* The below endpoint will then redirect back to the user's WP site (to self::get_plugin_auth_url() URL).
*
* @since 2.5.0
*
* @return string
*/
public static function get_oauth_redirect_url() {
if ( self::use_self_oauth_redirect_url() ) {
return remove_query_arg( 'state', self::get_plugin_auth_url() );
} else {
return 'https://connect.wpmailsmtp.com/google/';
}
}
/**
* Get the state parameter for the Google oAuth redirect URL.
*
* @since 3.10.0
*
* @param ConnectionInterface $connection The Connection object.
*
* @return string
*/
private static function get_state_param( $connection ) {
$state = [
wp_create_nonce( 'wp_mail_smtp_provider_client_state' ),
$connection->get_id(),
];
return implode( '-', $state );
}
/**
* Whether to use self website redirect URL for the Google oAuth.
*
* @since 3.10.0
*
* @return bool
*/
private static function use_self_oauth_redirect_url() {
/**
* Filter whether to use self website redirect URL for the Google oAuth.
*
* @since 3.10.0
*
* @param bool $use Whether to use self website redirect URL for the Google oAuth.
*/
return apply_filters( 'wp_mail_smtp_providers_gmail_auth_use_self_oauth_redirect_url', false );
}
}

View File

@@ -1,294 +0,0 @@
<?php
namespace WPMailSMTP\Providers\Gmail;
use WPMailSMTP\Admin\DebugEvents\DebugEvents;
use WPMailSMTP\Helpers\Helpers;
use WPMailSMTP\MailCatcherInterface;
use WPMailSMTP\Providers\MailerAbstract;
use WPMailSMTP\Vendor\Google\Service\Gmail;
use WPMailSMTP\Vendor\Google\Service\Gmail\Message;
use WPMailSMTP\WP;
/**
* Class Mailer.
*
* @since 1.0.0
*/
class Mailer extends MailerAbstract {
/**
* URL to make an API request to.
* Not used for Gmail, as we are using its API.
*
* @since 1.0.0
*
* @var string
*/
protected $url = 'https://www.googleapis.com/upload/gmail/v1/users/{userId}/messages/send';
/**
* Gmail message.
*
* @since 1.0.0
*
* @var Message
*/
protected $message;
/**
* Re-use the MailCatcher class methods and properties.
*
* @since 1.2.0
*
* @param MailCatcherInterface $phpmailer The MailCatcher object.
*/
public function process_phpmailer( $phpmailer ) {
// Make sure that we have access to PHPMailer class methods.
if ( ! wp_mail_smtp()->is_valid_phpmailer( $phpmailer ) ) {
return;
}
$this->phpmailer = $phpmailer;
}
/**
* Use Google API Services to send emails.
*
* @since 1.0.0
*/
public function send() {
// Include the Google library.
require_once wp_mail_smtp()->plugin_path . '/vendor/autoload.php';
$auth = new Auth( $this->connection );
$message = new Message();
// Set the authorized Gmail email address as the "from email" if the set email is not on the list of aliases.
$possible_from_emails = $auth->get_user_possible_send_from_addresses();
if ( ! in_array( $this->phpmailer->From, $possible_from_emails, true ) ) {
$user_info = $auth->get_user_info();
if ( ! empty( $user_info['email'] ) ) {
$this->phpmailer->From = $user_info['email'];
$this->phpmailer->Sender = $user_info['email'];
}
}
try {
// Prepare a message for sending if any changes happened above.
$this->phpmailer->preSend();
// Get the raw MIME email using MailCatcher data. We need to make base64URL-safe string.
$base64 = str_replace(
[ '+', '/', '=' ],
[ '-', '_', '' ],
base64_encode( $this->phpmailer->getSentMIMEMessage() ) //phpcs:ignore
);
$message->setRaw( $base64 );
$service = new Gmail( $auth->get_client() );
$response = $service->users_messages->send( 'me', $message );
DebugEvents::add_debug(
esc_html__( 'An email request was sent to the Gmail API.', 'wp-mail-smtp' )
);
$this->process_response( $response );
} catch ( \Exception $e ) {
$this->error_message = $this->process_exception_message( $e->getMessage() );
}
}
/**
* Save response from the API to use it later.
*
* @since 1.0.0
* @since 1.5.0 Added action "wp_mail_smtp_providers_gmail_mailer_process_response" with $response.
*
* @param Message $response Instance of Gmail response.
*/
protected function process_response( $response ) {
$this->response = $response;
if ( empty( $this->response ) || ! method_exists( $this->response, 'getId' ) ) {
$this->error_message = esc_html__( 'The response object is invalid (missing getId method).', 'wp-mail-smtp' );
} else {
$message_id = $this->response->getId();
if ( empty( $message_id ) ) {
$this->error_message = esc_html__( 'The email message ID is missing.', 'wp-mail-smtp' );
}
}
do_action( 'wp_mail_smtp_providers_gmail_mailer_process_response', $this->response, $this->phpmailer );
}
/**
* Check whether the email was sent.
*
* @since 1.0.0
*
* @return bool
*/
public function is_email_sent() {
$is_sent = false;
if (
! empty( $this->response ) &&
method_exists( $this->response, 'getId' ) &&
! empty( $this->response->getId() )
) {
$is_sent = true;
}
/** This filter is documented in src/Providers/MailerAbstract.php. */
return apply_filters( 'wp_mail_smtp_providers_mailer_is_email_sent', $is_sent, $this->mailer );
}
/**
* This method is relevant to SMTP and Pepipost.
* All other custom mailers should override it with own information.
*
* @since 1.2.0
*
* @return string
*/
public function get_debug_info() { // phpcs:ignore Generic.Metrics.CyclomaticComplexity.MaxExceeded
$gmail_text = array();
$gmail = $this->connection_options->get_group( 'gmail' );
$curl_ver = 'No';
if ( function_exists( 'curl_version' ) ) {
$curl = curl_version();
$curl_ver = $curl['version'];
}
$gmail_text[] = '<strong>Client ID/Secret:</strong> ' . ( ! empty( $gmail['client_id'] ) && ! empty( $gmail['client_secret'] ) ? 'Yes' : 'No' );
$gmail_text[] = '<strong>Auth Code:</strong> ' . ( ! empty( $gmail['auth_code'] ) ? 'Yes' : 'No' );
$gmail_text[] = '<strong>Access Token:</strong> ' . ( ! empty( $gmail['access_token'] ) ? 'Yes' : 'No' );
$gmail_text[] = '<br><strong>Server:</strong>';
$gmail_text[] = '<strong>OpenSSL:</strong> ' . ( extension_loaded( 'openssl' ) && defined( 'OPENSSL_VERSION_TEXT' ) ? OPENSSL_VERSION_TEXT : 'No' );
$gmail_text[] = '<strong>PHP.allow_url_fopen:</strong> ' . ( ini_get( 'allow_url_fopen' ) ? 'Yes' : 'No' );
$gmail_text[] = '<strong>PHP.stream_socket_client():</strong> ' . ( function_exists( 'stream_socket_client' ) ? 'Yes' : 'No' );
$gmail_text[] = '<strong>PHP.fsockopen():</strong> ' . ( function_exists( 'fsockopen' ) ? 'Yes' : 'No' );
$gmail_text[] = '<strong>PHP.curl_version():</strong> ' . $curl_ver;
if ( function_exists( 'apache_get_modules' ) ) {
$modules = apache_get_modules();
$gmail_text[] = '<strong>Apache.mod_security:</strong> ' . ( in_array( 'mod_security', $modules, true ) || in_array( 'mod_security2', $modules, true ) ? 'Yes' : 'No' );
}
if ( function_exists( 'selinux_is_enabled' ) ) {
$gmail_text[] = '<strong>OS.SELinux:</strong> ' . ( selinux_is_enabled() ? 'Yes' : 'No' );
}
if ( function_exists( 'grsecurity_is_enabled' ) ) {
$gmail_text[] = '<strong>OS.grsecurity:</strong> ' . ( grsecurity_is_enabled() ? 'Yes' : 'No' );
}
return implode( '<br>', $gmail_text );
}
/**
* Whether the mailer has all its settings correctly set up and saved.
*
* @since 1.4.0
*
* @return bool
*/
public function is_mailer_complete() {
if ( ! $this->is_php_compatible() ) {
return false;
}
$auth = new Auth( $this->connection );
if (
$auth->is_clients_saved() &&
! $auth->is_auth_required()
) {
return true;
}
return false;
}
/**
* Process the exception message and append additional explanation to it.
*
* @since 2.1.0
*
* @param mixed $message A string or an object with strings.
*
* @return string
*/
protected function process_exception_message( $message ) {
// Transform the passed message to a string.
if ( ! is_string( $message ) ) {
$message = wp_json_encode( $message );
} else {
$message = wp_strip_all_tags( $message, false );
}
// Define known errors, that we will scan the message with.
$known_errors = [
[
'errors' => [
'invalid_grant',
],
'explanation' => esc_html__( 'Please re-grant Google app permissions!', 'wp-mail-smtp' ) . ' ' . WP::EOL .
esc_html__( 'Go to WP Mail SMTP plugin settings page. Click the “Remove OAuth Connection” button.', 'wp-mail-smtp' ) . ' ' . WP::EOL .
esc_html__( 'Then click the “Allow plugin to send emails using your Google account” button and re-enable access.', 'wp-mail-smtp' ),
],
];
// Check if we get a match and append the explanation to the original message.
foreach ( $known_errors as $error ) {
foreach ( $error['errors'] as $error_fragment ) {
if ( false !== strpos( $message, $error_fragment ) ) {
return Helpers::format_error_message( $message, '', $error['explanation'] );
}
}
}
// If we get no match we return the original message (as a string).
return $message;
}
/**
* Get the default email addresses for the reply to email parameter.
*
* @deprecated 2.1.1
*
* @since 2.1.0
* @since 2.1.1 Not used anymore.
*
* @return array
*/
public function default_reply_to_addresses() {
_deprecated_function( __CLASS__ . '::' . __METHOD__, '2.1.1 of WP Mail SMTP plugin' );
$gmail_creds = ( new Auth( $this->connection ) )->get_user_info();
if ( empty( $gmail_creds['email'] ) ) {
return [];
}
return [
$gmail_creds['email'] => [
$gmail_creds['email'],
'',
],
];
}
}

View File

@@ -1,291 +0,0 @@
<?php
namespace WPMailSMTP\Providers\Gmail;
use WPMailSMTP\Admin\ConnectionSettings;
use WPMailSMTP\ConnectionInterface;
use WPMailSMTP\Helpers\UI;
use WPMailSMTP\Providers\OptionsAbstract;
/**
* Class Option.
*
* @since 1.0.0
*/
class Options extends OptionsAbstract {
/**
* Mailer slug.
*
* @since 1.5.0
*/
const SLUG = 'gmail';
/**
* Gmail Options constructor.
*
* @since 1.0.0
* @since 2.3.0 Added supports parameter.
*
* @param ConnectionInterface $connection The Connection object.
*/
public function __construct( $connection = null ) {
parent::__construct(
[
'logo_url' => wp_mail_smtp()->assets_url . '/images/providers/google.svg',
'slug' => self::SLUG,
'title' => esc_html__( 'Google / Gmail', 'wp-mail-smtp' ),
'description' => sprintf(
wp_kses( /* translators: %s - URL to our Gmail doc. */
__( 'Our Gmail mailer works with any Gmail or Google Workspace account via the Google API. You can send WordPress emails from your main email address or a Gmail alias, and it\'s more secure than connecting to Gmail using SMTP credentials. We now have a One-Click Setup, which simply asks you to authorize your Google account to use our app and takes care of everything for you. Alternatively, you can connect manually, which involves several steps that are more technical than other mailer options, so we created a detailed guide to walk you through the process.<br><br>To get started, read our <a href="%s" target="_blank" rel="noopener noreferrer">Gmail documentation</a>.', 'wp-mail-smtp' ),
[
'br' => [],
'a' => [
'href' => [],
'rel' => [],
'target' => [],
],
]
),
esc_url( wp_mail_smtp()->get_utm_url( 'https://wpmailsmtp.com/docs/how-to-set-up-the-gmail-mailer-in-wp-mail-smtp/', 'Gmail documentation' ) )
),
'notices' => [
'educational' => wp_kses(
__( 'The Gmail mailer works well for sites that send low numbers of emails. However, Gmail\'s API has rate limitations and a number of additional restrictions that can lead to challenges during setup.<br><br>If you expect to send a high volume of emails, or if you find that your web host is not compatible with the Gmail API restrictions, then we recommend considering a different mailer option.', 'wp-mail-smtp' ),
[
'br' => [],
]
),
],
'php' => '5.6',
'supports' => [
'from_email' => true,
'from_name' => true,
'return_path' => false,
'from_email_force' => true,
'from_name_force' => true,
],
],
$connection
);
}
/**
* @inheritdoc
*/
public function display_options() {
// Do not display options if PHP version is not correct.
if ( ! $this->is_php_correct() ) {
$this->display_php_warning();
return;
}
?>
<?php if ( ! wp_mail_smtp()->is_pro() ) : ?>
<div id="wp-mail-smtp-setting-row-<?php echo esc_attr( $this->get_slug() ); ?>-one_click_setup_enabled-lite" class="wp-mail-smtp-setting-row">
<div class="wp-mail-smtp-setting-label">
<label for="wp-mail-smtp-setting-<?php echo esc_attr( $this->get_slug() ); ?>-one_click_setup_enabled-lite">
<?php esc_html_e( 'One-Click Setup', 'wp-mail-smtp' ); ?>
</label>
</div>
<div class="wp-mail-smtp-setting-field">
<?php
UI::toggle(
[
'id' => 'wp-mail-smtp-setting-' . esc_attr( $this->get_slug() ) . '-one_click_setup_enabled-lite',
]
);
?>
<p class="desc">
<?php esc_html_e( 'Provides a quick and easy way to connect to Google that doesn\'t require creating your own app.', 'wp-mail-smtp' ); ?>
</p>
</div>
</div>
<?php endif; ?>
<!-- Client ID -->
<div id="wp-mail-smtp-setting-row-<?php echo esc_attr( $this->get_slug() ); ?>-client_id"
class="wp-mail-smtp-setting-row wp-mail-smtp-setting-row-text wp-mail-smtp-clear">
<div class="wp-mail-smtp-setting-label">
<label for="wp-mail-smtp-setting-<?php echo esc_attr( $this->get_slug() ); ?>-client_id"><?php esc_html_e( 'Client ID', 'wp-mail-smtp' ); ?></label>
</div>
<div class="wp-mail-smtp-setting-field">
<input name="wp-mail-smtp[<?php echo esc_attr( $this->get_slug() ); ?>][client_id]" type="text"
value="<?php echo esc_attr( $this->connection_options->get( $this->get_slug(), 'client_id' ) ); ?>"
<?php echo $this->connection_options->is_const_defined( $this->get_slug(), 'client_id' ) ? 'disabled' : ''; ?>
id="wp-mail-smtp-setting-<?php echo esc_attr( $this->get_slug() ); ?>-client_id" spellcheck="false"
/>
</div>
</div>
<!-- Client Secret -->
<div id="wp-mail-smtp-setting-row-<?php echo esc_attr( $this->get_slug() ); ?>-client_secret"
class="wp-mail-smtp-setting-row wp-mail-smtp-setting-row-text wp-mail-smtp-clear">
<div class="wp-mail-smtp-setting-label">
<label for="wp-mail-smtp-setting-<?php echo esc_attr( $this->get_slug() ); ?>-client_secret"><?php esc_html_e( 'Client Secret', 'wp-mail-smtp' ); ?></label>
</div>
<div class="wp-mail-smtp-setting-field">
<?php if ( $this->connection_options->is_const_defined( $this->get_slug(), 'client_secret' ) ) : ?>
<input type="text" disabled value="****************************************"
id="wp-mail-smtp-setting-<?php echo esc_attr( $this->get_slug() ); ?>-client_secret"
/>
<?php $this->display_const_set_message( 'WPMS_GMAIL_CLIENT_SECRET' ); ?>
<?php else : ?>
<input type="password" spellcheck="false"
name="wp-mail-smtp[<?php echo esc_attr( $this->get_slug() ); ?>][client_secret]"
value="<?php echo esc_attr( $this->connection_options->get( $this->get_slug(), 'client_secret' ) ); ?>"
id="wp-mail-smtp-setting-<?php echo esc_attr( $this->get_slug() ); ?>-client_secret"
/>
<?php endif; ?>
</div>
</div>
<!-- Authorized redirect URI -->
<div id="wp-mail-smtp-setting-row-<?php echo esc_attr( $this->get_slug() ); ?>-client_redirect"
class="wp-mail-smtp-setting-row wp-mail-smtp-setting-row-text wp-mail-smtp-clear">
<div class="wp-mail-smtp-setting-label">
<label for="wp-mail-smtp-setting-<?php echo esc_attr( $this->get_slug() ); ?>-client_redirect"><?php esc_html_e( 'Authorized redirect URI', 'wp-mail-smtp' ); ?></label>
</div>
<div class="wp-mail-smtp-setting-field">
<input type="text" readonly="readonly" onfocus="this.select();"
value="<?php echo esc_attr( Auth::get_oauth_redirect_url() ); ?>"
id="wp-mail-smtp-setting-<?php echo esc_attr( $this->get_slug() ); ?>-client_redirect"
/>
<button type="button" class="wp-mail-smtp-btn wp-mail-smtp-btn-md wp-mail-smtp-btn-grey wp-mail-smtp-setting-copy"
title="<?php esc_attr_e( 'Copy URL to clipboard', 'wp-mail-smtp' ); ?>"
data-source_id="wp-mail-smtp-setting-<?php echo esc_attr( $this->get_slug() ); ?>-client_redirect">
<span class="dashicons dashicons-admin-page"></span>
</button>
<p class="desc">
<?php esc_html_e( 'Please copy this URL into the "Authorized redirect URIs" field of your Google web application.', 'wp-mail-smtp' ); ?>
</p>
</div>
</div>
<!-- Auth users button -->
<div id="wp-mail-smtp-setting-row-<?php echo esc_attr( $this->get_slug() ); ?>-authorize"
class="wp-mail-smtp-setting-row wp-mail-smtp-setting-row-text wp-mail-smtp-clear">
<div class="wp-mail-smtp-setting-label">
<label><?php esc_html_e( 'Authorization', 'wp-mail-smtp' ); ?></label>
</div>
<div class="wp-mail-smtp-setting-field">
<?php $this->display_auth_setting_action(); ?>
</div>
</div>
<?php
}
/**
* Display either an "Allow..." or "Remove..." button.
*
* @since 1.3.0
*/
protected function display_auth_setting_action() {
// Do the processing on the fly, as having ajax here is too complicated.
$this->process_provider_remove();
$auth = new Auth( $this->connection );
?>
<?php if ( $auth->is_clients_saved() ) : ?>
<?php if ( $auth->is_auth_required() ) : ?>
<a href="<?php echo esc_url( $auth->get_auth_url() ); ?>" class="wp-mail-smtp-btn wp-mail-smtp-btn-md wp-mail-smtp-btn-orange">
<?php esc_html_e( 'Allow plugin to send emails using your Google account', 'wp-mail-smtp' ); ?>
</a>
<p class="desc">
<?php esc_html_e( 'Click the button above to confirm authorization.', 'wp-mail-smtp' ); ?>
</p>
<?php else : ?>
<a href="<?php echo esc_url( wp_nonce_url( ( new ConnectionSettings( $this->connection ) )->get_admin_page_url(), 'gmail_remove', 'gmail_remove_nonce' ) ); ?>#wp-mail-smtp-setting-row-<?php echo esc_attr( $this->get_slug() ); ?>-authorize" class="wp-mail-smtp-btn wp-mail-smtp-btn-md wp-mail-smtp-btn-red js-wp-mail-smtp-provider-remove">
<?php esc_html_e( 'Remove OAuth Connection', 'wp-mail-smtp' ); ?>
</a>
<span class="connected-as">
<?php
$user = $auth->get_user_info();
if ( ! empty( $user['email'] ) ) {
printf(
/* translators: %s - email address, as received from Google API. */
esc_html__( 'Connected as %s', 'wp-mail-smtp' ),
'<code>' . esc_html( $user['email'] ) . '</code>'
);
}
?>
</span>
<p class="desc">
<?php
printf(
wp_kses( /* translators: %s - URL to Google Gmail alias documentation page. */
__( 'If you want to use a different From Email address you can set up a Google email alias. <a href="%s" target="_blank" rel="noopener noreferrer">Follow these instructions</a> and then select the From Email at the top of this page.', 'wp-mail-smtp' ),
[
'a' => [
'href' => [],
'rel' => [],
'target' => [],
],
]
),
esc_url( wp_mail_smtp()->get_utm_url( 'https://wpmailsmtp.com/gmail-send-from-alias-wp-mail-smtp/', 'Gmail aliases description - Follow these instructions' ) )
);
?>
</p>
<p class="desc">
<?php esc_html_e( 'You can also send emails with different From Email addresses, by disabling the Force From Email setting and using registered aliases throughout your WordPress site as the From Email addresses.', 'wp-mail-smtp' ); ?>
</p>
<p class="desc">
<?php esc_html_e( 'Removing the OAuth connection will give you an ability to redo the OAuth connection or link to another Google account.', 'wp-mail-smtp' ); ?>
</p>
<?php endif; ?>
<?php else : ?>
<p class="inline-notice inline-error">
<?php esc_html_e( 'You need to save settings with Client ID and Client Secret before you can proceed.', 'wp-mail-smtp' ); ?>
</p>
<?php
endif;
}
/**
* Remove Provider OAuth connection.
*
* @since 1.3.0
*/
public function process_provider_remove() {
if ( ! current_user_can( wp_mail_smtp()->get_capability_manage_options() ) ) {
return;
}
if (
! isset( $_GET['gmail_remove_nonce'] ) ||
! wp_verify_nonce( sanitize_key( $_GET['gmail_remove_nonce'] ), 'gmail_remove' )
) {
return;
}
if ( $this->connection->get_mailer_slug() !== $this->get_slug() ) {
return;
}
$old_opt = $this->connection_options->get_all_raw();
unset( $old_opt[ $this->get_slug() ]['access_token'] );
unset( $old_opt[ $this->get_slug() ]['refresh_token'] );
unset( $old_opt[ $this->get_slug() ]['user_details'] );
unset( $old_opt[ $this->get_slug() ]['auth_code'] );
$this->connection_options->set( $old_opt );
}
}