Vigiar
1
0
Derivar
Você já tinha feito uma derivação do repositório wordpress-email-center-plugin, anteriormente
0
wordpress-email-center-plugin/mozout-email-center/includes/class-admin.php
2026-12-01 13:25:59 +02:00

607 linhas
37 KiB
PHP

<?php
if (!defined('ABSPATH')) {
exit;
}
/**
* Settings page: Settings > MozOut E-mail Center, with tabs.
* The API key is saved encrypted and is never printed back into the page.
*/
class MOZOUT_EMAIL_CENTER_Admin
{
const PAGE = 'mozout-email-center';
public static function init()
{
add_action('admin_menu', array(__CLASS__, 'menu'));
add_action('admin_post_mozout_email_center_save', array(__CLASS__, 'save'));
add_action('admin_post_mozout_email_center_test', array(__CLASS__, 'test_connection'));
add_action('admin_post_mozout_email_center_test_mail', array(__CLASS__, 'test_mail'));
add_action('admin_enqueue_scripts', array(__CLASS__, 'assets'));
add_filter('plugin_action_links_' . plugin_basename(MOZOUT_EMAIL_CENTER_FILE), array(__CLASS__, 'action_links'));
}
public static function menu()
{
add_options_page(
__('MozOut E-mail Center', 'mozout-email-center'),
__('MozOut E-mail Center', 'mozout-email-center'),
'manage_options',
self::PAGE,
array(__CLASS__, 'page')
);
}
public static function action_links($links)
{
array_unshift($links, '<a href="' . esc_url(self::url()) . '">' . esc_html__('Settings', 'mozout-email-center') . '</a>');
return $links;
}
public static function assets($hook)
{
if ($hook !== 'settings_page_' . self::PAGE) {
return;
}
wp_enqueue_style('mozout-email-center-admin', MOZOUT_EMAIL_CENTER_URL . 'assets/admin.css', array(), MOZOUT_EMAIL_CENTER_VERSION);
wp_enqueue_script('mozout-email-center-select', MOZOUT_EMAIL_CENTER_URL . 'assets/select.js', array(), MOZOUT_EMAIL_CENTER_VERSION, true);
}
public static function url($tab = 'connection', $args = array())
{
return add_query_arg(array_merge(array('page' => self::PAGE, 'tab' => $tab), $args), admin_url('options-general.php'));
}
private static function tabs()
{
return array(
'connection' => __('Connection', 'mozout-email-center'),
'email' => __('Site emails', 'mozout-email-center'),
'subscribe' => __('Sign-up forms', 'mozout-email-center'),
'woo' => __('WooCommerce', 'mozout-email-center'),
'activity' => __('Activity', 'mozout-email-center'),
);
}
private static function notice_from_query()
{
if (empty($_GET['mozout_email_center_msg'])) {
return;
}
$key = sanitize_key(wp_unslash($_GET['mozout_email_center_msg']));
$notice = get_transient('mozout_email_center_notice_' . get_current_user_id());
delete_transient('mozout_email_center_notice_' . get_current_user_id());
if (!is_array($notice) || $notice['key'] !== $key) {
return;
}
$class = $notice['ok'] ? 'notice-success' : 'notice-error';
echo '<div class="notice ' . esc_attr($class) . ' is-dismissible"><p>' . esc_html($notice['text']) . '</p></div>';
}
private static function redirect($tab, $ok, $text)
{
$key = strtolower(wp_generate_password(8, false, false));
set_transient('mozout_email_center_notice_' . get_current_user_id(), array('key' => $key, 'ok' => $ok, 'text' => $text), 120);
wp_safe_redirect(self::url($tab, array('mozout_email_center_msg' => $key)));
exit;
}
private static function check($action)
{
if (!current_user_can('manage_options')) {
wp_die(esc_html__('You do not have permission to change these settings.', 'mozout-email-center'), 403);
}
check_admin_referer($action);
}
/* ------------------------------------------------------------------ */
/* Page */
/* ------------------------------------------------------------------ */
public static function page()
{
if (!current_user_can('manage_options')) {
return;
}
$tabs = self::tabs();
$tab = isset($_GET['tab']) ? sanitize_key(wp_unslash($_GET['tab'])) : 'connection';
if (!isset($tabs[$tab])) {
$tab = 'connection';
}
echo '<div class="wrap mozout-email-center-wrap">';
echo '<h1>' . esc_html__('MozOut E-mail Center', 'mozout-email-center') . ' <span class="mozout-email-center-brand">' . esc_html(MOZOUT_EMAIL_CENTER_Brands::name()) . '</span></h1>';
self::notice_from_query();
echo '<nav class="nav-tab-wrapper">';
foreach ($tabs as $id => $label) {
printf('<a href="%s" class="nav-tab %s">%s</a>', esc_url(self::url($id)), $id === $tab ? 'nav-tab-active' : '', esc_html($label));
}
echo '</nav>';
call_user_func(array(__CLASS__, 'tab_' . $tab));
echo '</div>';
}
private static function form_open($tab)
{
echo '<form method="post" action="' . esc_url(admin_url('admin-post.php')) . '" class="mozout-email-center-form" autocomplete="off">';
echo '<input type="hidden" name="action" value="mozout_email_center_save"><input type="hidden" name="tab" value="' . esc_attr($tab) . '">';
wp_nonce_field('mozout_email_center_save_' . $tab);
echo '<table class="form-table" role="presentation">';
}
private static function form_close()
{
echo '</table>';
submit_button(__('Save changes', 'mozout-email-center'));
echo '</form>';
}
private static function row($label, $html, $help = '', $for = '')
{
echo '<tr><th scope="row">' . ($for ? '<label for="' . esc_attr($for) . '">' . esc_html($label) . '</label>' : esc_html($label)) . '</th><td>' . $html;
if ($help !== '') {
echo '<p class="description">' . wp_kses($help, array('a' => array('href' => array(), 'target' => array(), 'rel' => array()), 'code' => array(), 'strong' => array())) . '</p>';
}
echo '</td></tr>';
}
private static function checkbox($name, $label)
{
return '<label><input type="checkbox" name="' . esc_attr($name) . '" value="1" ' . checked((int) MOZOUT_EMAIL_CENTER_Settings::get($name), 1, false) . '> ' . esc_html($label) . '</label>';
}
private static function input($name, $type = 'text', $attrs = '')
{
return '<input type="' . esc_attr($type) . '" id="mozout-email-center-' . esc_attr($name) . '" name="' . esc_attr($name) . '" value="' . esc_attr((string) MOZOUT_EMAIL_CENTER_Settings::get($name)) . '" class="regular-text" ' . $attrs . '>';
}
private static function textarea($name, $rows = 3, $value = null, $placeholder = '')
{
$v = $value === null ? (string) MOZOUT_EMAIL_CENTER_Settings::get($name) : $value;
return '<textarea id="mozout-email-center-' . esc_attr(str_replace(array('[', ']'), '-', $name)) . '" name="' . esc_attr($name) . '" rows="' . (int) $rows . '" class="large-text" placeholder="' . esc_attr($placeholder) . '">' . esc_textarea($v) . '</textarea>';
}
/** A select box with the plugin style (select.js turns it into a button with a list). */
private static function select($name, array $options, $current, $id = '')
{
$id = $id !== '' ? $id : 'mozout-email-center-' . $name;
$html = '<select name="' . esc_attr($name) . '" id="' . esc_attr($id) . '" data-mozout-email-center-select>';
foreach ($options as $k => $v) {
$html .= '<option value="' . esc_attr($k) . '" ' . selected((string) $current, (string) $k, false) . '>' . esc_html($v) . '</option>';
}
return $html . '</select>';
}
private static function need_key_notice()
{
if (MOZOUT_EMAIL_CENTER_Settings::api_key() === '') {
echo '<div class="notice notice-warning inline"><p>' . esc_html__('Save the API key in the Connection tab first.', 'mozout-email-center') . '</p></div>';
}
}
/* ---- Connection ---- */
private static function tab_connection()
{
$hint = MOZOUT_EMAIL_CENTER_Settings::key_hint();
self::form_open('connection');
if (!MOZOUT_EMAIL_CENTER_Brands::is_fixed()) {
$opts = array();
foreach (MOZOUT_EMAIL_CENTER_Brands::all() as $id => $b) {
$opts[$id] = MOZOUT_EMAIL_CENTER_Brands::label($b);
}
self::row(__('Brand', 'mozout-email-center'), self::select('brand', $opts, MOZOUT_EMAIL_CENTER_Brands::current_id()), __('The company where you have your account. The API address and links follow this choice.', 'mozout-email-center'), 'mozout-email-center-brand');
}
if (MOZOUT_EMAIL_CENTER_Settings::key_from_constant()) {
$key_html = '<p><strong>' . esc_html__('The key is defined in wp-config.php (MOZOUT_EMAIL_CENTER_API_KEY) and cannot be changed here.', 'mozout-email-center') . '</strong></p>';
} else {
$key_html = '<input type="password" name="api_key" id="mozout-email-center-api_key" class="regular-text" value="" autocomplete="new-password" spellcheck="false" placeholder="'
. esc_attr(!empty($hint['suffix']) ? __('Saved. Write a new key only to replace it.', 'mozout-email-center') : 'prod_... / sandbox_...') . '">';
if (!empty($hint['suffix'])) {
$key_html .= '<p class="mozout-email-center-keyhint">' . esc_html(sprintf(
/* translators: 1: Sandbox or Production, 2: last 4 characters */
__('Saved key: %1$s, ending in %2$s.', 'mozout-email-center'),
$hint['mode'] === 'sandbox' ? 'Sandbox' : __('Production', 'mozout-email-center'),
$hint['suffix']
)) . '</p>';
$key_html .= '<label><input type="checkbox" name="delete_key" value="1"> ' . esc_html__('Delete the saved key', 'mozout-email-center') . '</label>';
}
if (MOZOUT_EMAIL_CENTER_Settings::key_unreadable()) {
$key_html .= '<p class="mozout-email-center-error">' . esc_html__('The saved API key can no longer be read (the WordPress security keys changed). Save the key again.', 'mozout-email-center') . '</p>';
}
}
$help = sprintf(
/* translators: 1: link to the API page, 2: name of the customer area */
__('Create the key in %2$s, on the <a href="%1$s" target="_blank" rel="noopener">API page</a>, with the email_center:read and email_center:write permissions. It is saved encrypted and is never shown again. A sandbox_ key simulates every send and spends nothing.', 'mozout-email-center'),
esc_url(MOZOUT_EMAIL_CENTER_Brands::portal_link('api-center.php')),
esc_html(MOZOUT_EMAIL_CENTER_Brands::portal_name())
);
self::row(__('API key', 'mozout-email-center'), $key_html, $help, 'mozout-email-center-api_key');
$lang_opts = array('auto' => __('Same as WordPress', 'mozout-email-center'), 'pt' => 'Português', 'en' => 'English');
self::row(__('Language', 'mozout-email-center'), self::select('ui_lang', $lang_opts, MOZOUT_EMAIL_CENTER_Settings::get('ui_lang')), __('Language of this page and of the texts shown to visitors.', 'mozout-email-center'), 'mozout-email-center-ui_lang');
self::form_close();
echo '<h2>' . esc_html__('Connection test', 'mozout-email-center') . '</h2>';
echo '<form method="post" action="' . esc_url(admin_url('admin-post.php')) . '">';
echo '<input type="hidden" name="action" value="mozout_email_center_test">';
wp_nonce_field('mozout_email_center_test');
submit_button(__('Test the connection', 'mozout-email-center'), 'secondary', 'submit', false);
echo '</form>';
$info = get_transient('mozout_email_center_token_info');
if (is_array($info)) {
echo '<table class="widefat striped mozout-email-center-info"><tbody>';
echo '<tr><th>' . esc_html__('Mode', 'mozout-email-center') . '</th><td>' . esc_html($info['mode'] === 'sandbox' ? __('Sandbox (sends are simulated)', 'mozout-email-center') : __('Production', 'mozout-email-center')) . '</td></tr>';
echo '<tr><th>' . esc_html__('Key name', 'mozout-email-center') . '</th><td>' . esc_html($info['name']) . '</td></tr>';
echo '<tr><th>' . esc_html__('Expires', 'mozout-email-center') . '</th><td>' . esc_html($info['expires_at'] ? $info['expires_at'] : __('Never', 'mozout-email-center')) . '</td></tr>';
if (isset($info['balance'])) {
echo '<tr><th>' . esc_html__('Email balance', 'mozout-email-center') . '</th><td>' . esc_html(sprintf(
/* translators: %s: number of credits */
__('%s credits', 'mozout-email-center'),
number_format_i18n((float) $info['balance'])
)) . (!empty($info['test_mode']) ? ' · ' . esc_html__('E-mail Center is in test mode: emails are not delivered.', 'mozout-email-center') : '') . '</td></tr>';
}
echo '<tr><th>' . esc_html__('Permissions', 'mozout-email-center') . '</th><td>';
foreach (array('email_center:write' => __('site emails and sign-ups', 'mozout-email-center'), 'email_center:read' => __('sender domains, groups and balance', 'mozout-email-center')) as $scope => $what) {
$has = in_array($scope, $info['permissions'], true) || in_array('*', $info['permissions'], true);
echo '<span class="mozout-email-center-scope ' . ($has ? 'is-ok' : 'is-missing') . '">' . esc_html(($has ? '✓ ' : '✗ ') . $scope) . '</span> <span class="description">' . esc_html($what) . '</span><br>';
}
echo '</td></tr></tbody></table>';
}
}
/* ---- Emails ---- */
private static function tab_email()
{
self::need_key_notice();
echo '<p>' . esc_html__('All emails of WordPress and of other plugins (wp_mail) go out through E-mail Center. Each recipient spends one email credit.', 'mozout-email-center') . '</p>';
self::form_open('email');
self::row(__('Send through E-mail Center', 'mozout-email-center'), self::checkbox('mail_enabled', __('Active', 'mozout-email-center')));
$domains = self::cached_list('/v1/email/domains', 'mozout_email_center_domains');
$help = __('Must be at a sender domain verified in E-mail Center.', 'mozout-email-center');
if (is_array($domains)) {
$names = array();
foreach ($domains as $d) {
if (isset($d['domain'])) {
$names[] = $d['domain'] . (isset($d['status']) && $d['status'] !== 'verified' ? ' (' . $d['status'] . ')' : '');
}
}
$help .= ' ' . ($names ? sprintf(
/* translators: %s: list of domains */
__('Your domains: %s.', 'mozout-email-center'),
implode(', ', $names)
) : __('Your account has no sender domain yet.', 'mozout-email-center'));
}
self::row(__('Sender address', 'mozout-email-center'), self::input('mail_from_email', 'email', 'placeholder="noreply@example.com"'), $help, 'mozout-email-center-mail_from_email');
self::row(__('Sender name', 'mozout-email-center'), self::input('mail_from_name', 'text', 'placeholder="' . esc_attr(get_bloginfo('name')) . '"'), '', 'mozout-email-center-mail_from_name');
self::row(__('Sender of other plugins', 'mozout-email-center'), self::checkbox('mail_force_from', __('Always use the address above (the original sender goes to Reply-To)', 'mozout-email-center')), __('Recommended: forms often use the visitor address as sender, and the API only sends from verified domains.', 'mozout-email-center'));
self::row(__('If the API fails', 'mozout-email-center'), self::checkbox('mail_fallback', __('Send the normal WordPress way', 'mozout-email-center')), __('No email is lost when the key expires, the credits end or the API does not answer.', 'mozout-email-center'));
self::form_close();
echo '<h2>' . esc_html__('Send a test', 'mozout-email-center') . '</h2>';
echo '<form method="post" action="' . esc_url(admin_url('admin-post.php')) . '" class="mozout-email-center-inline">';
echo '<input type="hidden" name="action" value="mozout_email_center_test_mail">';
wp_nonce_field('mozout_email_center_test_mail');
echo '<label for="mozout-email-center-test-to" class="screen-reader-text">' . esc_html__('Send the test to', 'mozout-email-center') . '</label>';
echo '<input type="email" id="mozout-email-center-test-to" name="to" class="regular-text" required value="' . esc_attr(wp_get_current_user()->user_email) . '"> ';
submit_button(__('Send test', 'mozout-email-center'), 'secondary', 'submit', false);
echo '</form><p class="description">' . esc_html__('The test goes straight to the API, without the fallback, so you see the real answer. With a sandbox_ key the email is simulated and does not arrive.', 'mozout-email-center') . '</p>';
self::log_table('mail');
}
/* ---- Sign-up forms ---- */
private static function tab_subscribe()
{
self::need_key_notice();
echo '<p>' . wp_kses(__('Put the form on any page with the <strong>Newsletter sign-up</strong> block or the shortcode <code>[mozout_email_subscribe]</code> (optional: groups="3,4" title="..." button="..." name="0").', 'mozout-email-center'), array('strong' => array(), 'code' => array())) . '</p>';
self::form_open('subscribe');
self::row(__('Double confirmation', 'mozout-email-center'), self::checkbox('sub_double_optin', __('The contact only enters the list after opening the link sent by email', 'mozout-email-center')), __('Recommended. Unconfirmed sign-ups are deleted after 7 days.', 'mozout-email-center'));
self::row(__('E-mail Center groups', 'mozout-email-center'), self::groups_field('sub_email_groups', '/v1/email/groups', 'mozout_email_center_email_groups'), __('Default groups for new contacts. A form can choose others.', 'mozout-email-center'));
self::row(__('Consent text (Portuguese)', 'mozout-email-center'), self::textarea('sub_consent_pt', 2, null, MOZOUT_EMAIL_CENTER_Subscribe::consent_text('pt')), __('Shown next to the box the person ticks. The exact text accepted is kept as proof.', 'mozout-email-center'));
self::row(__('Consent text (English)', 'mozout-email-center'), self::textarea('sub_consent_en', 2, null, MOZOUT_EMAIL_CENTER_Subscribe::consent_text('en')));
self::row(__('Page after confirming', 'mozout-email-center'), self::input('sub_thanks_url', 'url', 'placeholder="' . esc_attr(home_url('/')) . '"'), __('Optional. Without it, a short confirmation message is shown.', 'mozout-email-center'), 'mozout-email-center-sub_thanks_url');
self::row(__('Sign-ups per hour, per IP', 'mozout-email-center'), self::input('sub_per_hour', 'number', 'min="1" max="100" style="width:6em"'), '', 'mozout-email-center-sub_per_hour');
self::form_close();
$rows = MOZOUT_EMAIL_CENTER_Subscribe::recent(15);
if ($rows) {
echo '<h2>' . esc_html__('Latest sign-ups', 'mozout-email-center') . '</h2><table class="widefat striped"><thead><tr><th>' . esc_html__('Date', 'mozout-email-center') . '</th><th>' . esc_html__('Contact', 'mozout-email-center') . '</th><th>' . esc_html__('Status', 'mozout-email-center') . '</th></tr></thead><tbody>';
$status = array('pending' => __('Waiting for confirmation', 'mozout-email-center'), 'confirmed' => __('Confirmed', 'mozout-email-center'), 'failed' => __('Confirmed, not sent to the API', 'mozout-email-center'));
foreach ($rows as $r) {
echo '<tr><td>' . esc_html(get_date_from_gmt($r->created_at, 'd/m/Y H:i')) . '</td><td>' . esc_html(MOZOUT_EMAIL_CENTER_Log::mask_email($r->email)) . '</td><td>' . esc_html(isset($status[$r->status]) ? $status[$r->status] : $r->status) . '</td></tr>';
}
echo '</tbody></table>';
}
self::log_table('subscribe');
}
private static function groups_field($name, $path, $cache)
{
$selected = array_map('intval', (array) MOZOUT_EMAIL_CENTER_Settings::get($name));
$groups = self::cached_list($path, $cache);
if (!is_array($groups)) {
return '<input type="text" name="' . esc_attr($name) . '" class="regular-text" value="' . esc_attr(implode(',', $selected)) . '" placeholder="3,4"><p class="description">'
. esc_html(is_wp_error($groups) ? $groups->get_error_message() : __('Group ids, comma separated.', 'mozout-email-center')) . '</p>';
}
if (!$groups) {
return '<p>' . esc_html__('No groups yet. Contacts enter without a group.', 'mozout-email-center') . '</p>';
}
$html = '<fieldset>';
foreach ($groups as $g) {
$html .= '<label class="mozout-email-center-group"><input type="checkbox" name="' . esc_attr($name) . '[]" value="' . (int) $g['id'] . '" ' . checked(in_array((int) $g['id'], $selected, true), true, false) . '> '
. esc_html($g['name']) . ' <span class="description">(id ' . (int) $g['id'] . ')</span></label><br>';
}
return $html . '</fieldset>';
}
/** Reads a list from the API and keeps it for 10 minutes. Returns array, WP_Error or null (no key). */
private static function cached_list($path, $cache)
{
if (MOZOUT_EMAIL_CENTER_Settings::api_key() === '') {
return null;
}
$hit = get_transient($cache);
if (is_array($hit)) {
return $hit;
}
$res = MOZOUT_EMAIL_CENTER_Api::request('GET', $path, null, array('query' => array('per_page' => 100), 'timeout' => 10));
if (is_wp_error($res)) {
return $res;
}
$list = is_array($res['data']) ? $res['data'] : array();
set_transient($cache, $list, 10 * MINUTE_IN_SECONDS);
return $list;
}
/* ---- WooCommerce ---- */
private static function tab_woo()
{
if (!class_exists('WooCommerce')) {
echo '<div class="notice notice-info inline"><p>' . esc_html__('WooCommerce is not active on this site.', 'mozout-email-center') . '</p></div>';
return;
}
self::need_key_notice();
echo '<p>' . esc_html__('Emails go out in the background when the order changes status, once per order and event, through wp_mail (and E-mail Center, when "Site emails" is on). WooCommerce keeps sending its own emails: turn on here only what you want on top of them.', 'mozout-email-center') . '</p>';
self::form_open('woo');
self::row(__('Order emails', 'mozout-email-center'), self::checkbox('woo_enabled', __('Active', 'mozout-email-center')));
self::row(__('Site owner email', 'mozout-email-center'), self::input('woo_owner_email', 'email', 'placeholder="' . esc_attr(get_option('admin_email')) . '"'), __('Receives the new order alert. Empty uses the site admin address.', 'mozout-email-center'), 'mozout-email-center-woo_owner_email');
self::row(__('"Shipped" status', 'mozout-email-center'), self::checkbox('woo_shipped_status', __('Add the "Shipped" order status', 'mozout-email-center')), __('A tracking number saved in the order (_tracking_number) goes into the text.', 'mozout-email-center'));
$statuses = array('' => __('The "Shipped" status of this plugin', 'mozout-email-center'));
foreach (wc_get_order_statuses() as $k => $v) {
if ($k !== 'wc-' . MOZOUT_EMAIL_CENTER_Woo::SHIPPED) {
$statuses[$k] = $v;
}
}
self::row(__('Status that means shipped', 'mozout-email-center'), self::select('woo_shipped_key', $statuses, MOZOUT_EMAIL_CENTER_Settings::get('woo_shipped_key')), __('Choose another status if a shipping plugin already adds one.', 'mozout-email-center'), 'mozout-email-center-woo_shipped_key');
$lang_opts = array('auto' => __('Language of the site (or of the order, with WPML or Polylang)', 'mozout-email-center'), 'pt' => 'Português', 'en' => 'English');
self::row(__('Language of the emails', 'mozout-email-center'), self::select('woo_lang', $lang_opts, MOZOUT_EMAIL_CENTER_Settings::get('woo_lang')), '', 'mozout-email-center-woo_lang');
echo '</table>';
echo '<p class="description">' . esc_html__('Placeholders:', 'mozout-email-center') . ' <code>{first_name}</code> <code>{customer_name}</code> <code>{order_number}</code> <code>{order_total}</code> <code>{order_date}</code> <code>{payment_method}</code> <code>{order_url}</code> <code>{tracking_number}</code> <code>{site_name}</code> <code>{admin_order_url}</code>.</p>';
$ev = (array) MOZOUT_EMAIL_CENTER_Settings::get('woo_events');
$tpl = (array) MOZOUT_EMAIL_CENTER_Settings::get('woo_templates');
foreach (MOZOUT_EMAIL_CENTER_Woo::events() as $event => $label) {
$on = !empty($ev[$event]['email']);
echo '<details class="mozout-email-center-event"><summary><strong>' . esc_html($label) . '</strong> <span class="mozout-email-center-pill ' . ($on ? 'is-on' : '') . '">' . esc_html($on ? __('On', 'mozout-email-center') : __('Off', 'mozout-email-center')) . '</span></summary><table class="form-table" role="presentation">';
self::row(__('Send', 'mozout-email-center'), '<label><input type="checkbox" name="woo_events[' . esc_attr($event) . '][email]" value="1" ' . checked($on, true, false) . '> ' . esc_html__('Send this email', 'mozout-email-center') . '</label>');
foreach (array('pt' => __('Portuguese', 'mozout-email-center'), 'en' => __('English', 'mozout-email-center')) as $lang => $lang_label) {
$cur = function ($field) use ($tpl, $event, $lang) {
return isset($tpl[$event][$field][$lang]) ? (string) $tpl[$event][$field][$lang] : '';
};
/* translators: %s: language name */
self::row(sprintf(__('Email subject (%s)', 'mozout-email-center'), $lang_label), '<input type="text" class="large-text" name="' . esc_attr("woo_templates[$event][subject][$lang]") . '" value="' . esc_attr($cur('subject')) . '" placeholder="' . esc_attr(MOZOUT_EMAIL_CENTER_I18n::in($lang, MOZOUT_EMAIL_CENTER_Woo::default_template($event, 'subject'))) . '">');
/* translators: %s: language name */
self::row(sprintf(__('Email text (%s)', 'mozout-email-center'), $lang_label), self::textarea("woo_templates[$event][body][$lang]", 6, $cur('body'), MOZOUT_EMAIL_CENTER_I18n::in($lang, MOZOUT_EMAIL_CENTER_Woo::default_template($event, 'body'))));
}
echo '</table></details>';
}
echo '<p class="description">' . esc_html__('Empty fields use the text shown in grey.', 'mozout-email-center') . '</p>';
echo '<table class="form-table">';
self::form_close();
self::log_table('woo');
}
/* ---- Activity ---- */
private static function tab_activity()
{
self::log_table(null, 50);
}
private static function log_table($area, $n = 10)
{
$log = array_slice(MOZOUT_EMAIL_CENTER_Log::all($area), 0, $n);
if (!$log) {
if ($area === null) {
echo '<p>' . esc_html__('No activity yet.', 'mozout-email-center') . '</p>';
}
return;
}
$areas = array(
'mail' => __('Site emails', 'mozout-email-center'),
'subscribe' => __('Sign-up forms', 'mozout-email-center'),
'woo' => __('Order email', 'mozout-email-center'),
);
echo '<h2>' . esc_html__('Recent activity', 'mozout-email-center') . '</h2><table class="widefat striped mozout-email-center-log"><thead><tr><th>' . esc_html__('Date', 'mozout-email-center') . '</th><th>' . esc_html__('Area', 'mozout-email-center') . '</th><th>' . esc_html__('Result', 'mozout-email-center') . '</th><th>' . esc_html__('Details', 'mozout-email-center') . '</th></tr></thead><tbody>';
foreach ($log as $e) {
$extra = array();
foreach ((array) $e['extra'] as $k => $v) {
if ($k === 'fallback') {
$extra[] = $v ? __('sent the normal way', 'mozout-email-center') : __('not sent', 'mozout-email-center');
continue;
}
$extra[] = $k . ': ' . (is_scalar($v) ? $v : wp_json_encode($v));
}
$area_name = isset($areas[$e['area']]) ? $areas[$e['area']] : $e['area'];
echo '<tr><td>' . esc_html(wp_date('d/m/Y H:i', $e['t'])) . '</td><td>' . esc_html($area_name) . '</td><td class="' . ($e['ok'] ? 'mozout-email-center-ok' : 'mozout-email-center-error') . '">' . esc_html($e['text']) . '</td><td>' . esc_html(implode(' · ', $extra)) . '</td></tr>';
}
echo '</tbody></table>';
}
/* ------------------------------------------------------------------ */
/* Saving */
/* ------------------------------------------------------------------ */
public static function save()
{
$tab = isset($_POST['tab']) ? sanitize_key(wp_unslash($_POST['tab'])) : '';
self::check('mozout_email_center_save_' . $tab);
$p = wp_unslash($_POST);
$v = array();
$msg = __('Settings saved.', 'mozout-email-center');
$ok = true;
switch ($tab) {
case 'connection':
$brands = MOZOUT_EMAIL_CENTER_Brands::all();
$old_brand = MOZOUT_EMAIL_CENTER_Brands::current_id();
if (!MOZOUT_EMAIL_CENTER_Brands::is_fixed() && isset($p['brand'], $brands[$p['brand']])) {
$v['brand'] = $p['brand'];
}
$v['ui_lang'] = in_array(isset($p['ui_lang']) ? $p['ui_lang'] : '', array('auto', 'pt', 'en'), true) ? $p['ui_lang'] : 'auto';
MOZOUT_EMAIL_CENTER_Settings::update($v);
if (!MOZOUT_EMAIL_CENTER_Settings::key_from_constant()) {
if (!empty($p['delete_key'])) {
MOZOUT_EMAIL_CENTER_Settings::delete_api_key();
$msg = __('Settings saved. The key was deleted.', 'mozout-email-center');
} elseif (!empty($p['api_key'])) {
$r = MOZOUT_EMAIL_CENTER_Settings::save_api_key($p['api_key']);
if (is_wp_error($r)) {
$ok = false;
$msg = $r->get_error_message();
} else {
$msg = __('Settings saved. The key is stored encrypted and will not be shown again.', 'mozout-email-center');
}
}
}
if (isset($v['brand']) && $v['brand'] !== $old_brand) {
delete_transient('mozout_email_center_token_info');
}
self::forget_lists();
break;
case 'email':
$v['mail_enabled'] = empty($p['mail_enabled']) ? 0 : 1;
$v['mail_from_email'] = sanitize_email(isset($p['mail_from_email']) ? $p['mail_from_email'] : '');
$v['mail_from_name'] = sanitize_text_field(isset($p['mail_from_name']) ? $p['mail_from_name'] : '');
$v['mail_force_from'] = empty($p['mail_force_from']) ? 0 : 1;
$v['mail_fallback'] = empty($p['mail_fallback']) ? 0 : 1;
if ($v['mail_enabled'] && !$v['mail_from_email']) {
$ok = false;
$msg = __('Saved, but emails will keep going the normal way until you fill in the sender address.', 'mozout-email-center');
}
MOZOUT_EMAIL_CENTER_Settings::update($v);
break;
case 'subscribe':
$v['sub_double_optin'] = empty($p['sub_double_optin']) ? 0 : 1;
$v['sub_email_groups'] = self::int_list(isset($p['sub_email_groups']) ? $p['sub_email_groups'] : array());
$v['sub_consent_pt'] = sanitize_textarea_field(isset($p['sub_consent_pt']) ? $p['sub_consent_pt'] : '');
$v['sub_consent_en'] = sanitize_textarea_field(isset($p['sub_consent_en']) ? $p['sub_consent_en'] : '');
$v['sub_thanks_url'] = esc_url_raw(isset($p['sub_thanks_url']) ? $p['sub_thanks_url'] : '');
$v['sub_per_hour'] = min(100, max(1, (int) (isset($p['sub_per_hour']) ? $p['sub_per_hour'] : 5)));
MOZOUT_EMAIL_CENTER_Settings::update($v);
break;
case 'woo':
$v['woo_enabled'] = empty($p['woo_enabled']) ? 0 : 1;
$v['woo_shipped_status'] = empty($p['woo_shipped_status']) ? 0 : 1;
$v['woo_owner_email'] = sanitize_email(isset($p['woo_owner_email']) ? $p['woo_owner_email'] : '');
$v['woo_lang'] = in_array(isset($p['woo_lang']) ? $p['woo_lang'] : '', array('auto', 'pt', 'en'), true) ? $p['woo_lang'] : 'auto';
$key = isset($p['woo_shipped_key']) ? sanitize_key($p['woo_shipped_key']) : '';
$v['woo_shipped_key'] = ($key !== '' && function_exists('wc_get_order_statuses') && isset(wc_get_order_statuses()[$key])) ? $key : '';
$events = array();
$templates = array();
foreach (array_keys(MOZOUT_EMAIL_CENTER_Woo::events()) as $event) {
$events[$event]['email'] = empty($p['woo_events'][$event]['email']) ? 0 : 1;
foreach (array('subject', 'body') as $field) {
foreach (array('pt', 'en') as $lang) {
$val = isset($p['woo_templates'][$event][$field][$lang]) ? (string) $p['woo_templates'][$event][$field][$lang] : '';
$templates[$event][$field][$lang] = $field === 'body' ? sanitize_textarea_field($val) : sanitize_text_field($val);
}
}
}
$v['woo_events'] = $events;
$v['woo_templates'] = $templates;
MOZOUT_EMAIL_CENTER_Settings::update($v);
break;
default:
wp_die('bad tab', 400);
}
self::redirect($tab, $ok, $msg);
}
private static function int_list($value)
{
if (!is_array($value)) {
$value = preg_split('/[\s,]+/', (string) $value);
}
$out = array();
foreach ($value as $x) {
$x = (int) $x;
if ($x > 0) {
$out[] = $x;
}
}
return array_values(array_unique($out));
}
private static function forget_lists()
{
foreach (array('mozout_email_center_domains', 'mozout_email_center_email_groups') as $t) {
delete_transient($t);
}
}
public static function test_connection()
{
self::check('mozout_email_center_test');
delete_transient('mozout_email_center_token_info');
self::forget_lists();
$res = MOZOUT_EMAIL_CENTER_Api::request('GET', '/v1/token', null, array('timeout' => 10));
if (is_wp_error($res)) {
self::redirect('connection', false, $res->get_error_message());
}
$d = is_array($res['data']) ? $res['data'] : array();
$info = array(
'mode' => isset($d['mode']) ? $d['mode'] : (isset($d['type']) ? $d['type'] : ''),
'name' => isset($d['name']) ? (string) $d['name'] : '',
'expires_at' => isset($d['expires_at']) ? (string) $d['expires_at'] : '',
'permissions' => isset($d['permissions']) && is_array($d['permissions']) ? $d['permissions'] : array(),
);
$bal = MOZOUT_EMAIL_CENTER_Api::request('GET', '/v1/email/balance', null, array('timeout' => 10));
if (!is_wp_error($bal) && is_array($bal['data']) && isset($bal['data']['balance'])) {
$info['balance'] = $bal['data']['balance'];
$info['test_mode'] = !empty($bal['data']['test_mode']);
}
set_transient('mozout_email_center_token_info', $info, HOUR_IN_SECONDS);
self::redirect('connection', true, sprintf(
/* translators: %s: brand name */
__('Connection to %s working.', 'mozout-email-center'),
MOZOUT_EMAIL_CENTER_Brands::name()
));
}
public static function test_mail()
{
self::check('mozout_email_center_test_mail');
$to = sanitize_email(isset($_POST['to']) ? wp_unslash($_POST['to']) : '');
if (!is_email($to)) {
self::redirect('email', false, __('Write a valid address for the test.', 'mozout-email-center'));
}
$r = MOZOUT_EMAIL_CENTER_Mailer::test($to);
if (is_wp_error($r)) {
MOZOUT_EMAIL_CENTER_Log::add('mail', false, $r->get_error_message(), array('to' => MOZOUT_EMAIL_CENTER_Log::mask_email($to)));
self::redirect('email', false, $r->get_error_message());
}
$sim = MOZOUT_EMAIL_CENTER_Mailer::$last_simulated;
self::redirect('email', true, $sim ? __('Test accepted by the API, simulated (sandbox key or test mode): nothing was delivered.', 'mozout-email-center') : __('Test sent. Check the inbox (and the spam folder).', 'mozout-email-center'));
}
}