Use new code style

This commit is contained in:
David Stone
2025-02-07 19:02:33 -07:00
parent 0181024ae1
commit 8433379d90
672 changed files with 37107 additions and 45249 deletions

View File

@ -27,6 +27,5 @@ class Base_Manager {
* @since 2.0.11
* @return void
*/
public function init() {} // end init;
} // end class Base_Manager;
public function init() {}
}

View File

@ -38,8 +38,7 @@ class Block_Manager extends Base_Manager {
$hook = version_compare($wp_version, '5.8', '<') ? 'block_categories' : 'block_categories_all';
add_filter($hook, array($this, 'add_wp_ultimo_block_category'), 1, 2);
} // end init;
}
/**
* Adds wp-ultimo as a Block category on Gutenberg.
@ -52,13 +51,14 @@ class Block_Manager extends Base_Manager {
*/
public function add_wp_ultimo_block_category($categories, $post) {
return array_merge($categories, array(
return array_merge(
$categories,
array(
'slug' => 'wp-ultimo',
'title' => __('Multisite WaaS', 'wp-ultimo'),
),
));
} // end add_wp_ultimo_block_category;
} // end class Block_Manager;
array(
'slug' => 'wp-ultimo',
'title' => __('Multisite WaaS', 'wp-ultimo'),
),
)
);
}
}

View File

@ -25,7 +25,9 @@ defined('ABSPATH') || exit;
*/
class Broadcast_Manager extends Base_Manager {
use \WP_Ultimo\Apis\Rest_Api, \WP_Ultimo\Apis\WP_CLI, \WP_Ultimo\Traits\Singleton;
use \WP_Ultimo\Apis\Rest_Api;
use \WP_Ultimo\Apis\WP_CLI;
use \WP_Ultimo\Traits\Singleton;
/**
* The manager slug.
@ -58,13 +60,10 @@ class Broadcast_Manager extends Base_Manager {
/**
* Add unseen broadcast notices to the panel.
*/
if (!is_network_admin() && !is_main_site()) {
if ( ! is_network_admin() && ! is_main_site()) {
add_action('init', array($this, 'add_unseen_broadcast_notices'));
} // end if;
} // end init;
}
}
/**
* Add unseen broadcast messages.
@ -76,52 +75,41 @@ class Broadcast_Manager extends Base_Manager {
$current_customer = wu_get_current_customer();
if (!$current_customer) {
if ( ! $current_customer) {
return;
}
} // end if;
$all_broadcasts = Broadcast::query(array(
'number' => 10,
'order' => 'DESC',
'order_by' => 'id',
'type__in' => array('broadcast_notice'),
));
$all_broadcasts = Broadcast::query(
array(
'number' => 10,
'order' => 'DESC',
'order_by' => 'id',
'type__in' => array('broadcast_notice'),
)
);
if (isset($all_broadcasts)) {
foreach ($all_broadcasts as $key => $broadcast) {
if (isset($broadcast) && 'broadcast_notice' === $broadcast->get_type()) {
$targets = $this->get_all_notice_customer_targets($broadcast->get_id());
if (!is_array($targets)) {
if ( ! is_array($targets)) {
$targets = array($targets);
} // end if;
}
$dismissed = get_user_meta(get_current_user_id(), 'wu_dismissed_admin_notices');
if (in_array($current_customer->get_id(), $targets, true) && !in_array($broadcast->get_id(), $dismissed, true)) {
if (in_array($current_customer->get_id(), $targets, true) && ! in_array($broadcast->get_id(), $dismissed, true)) {
$notice = '<span><strong>' . $broadcast->get_title() . '</strong> ' . $broadcast->get_content() . '</span>';
WP_Ultimo()->notices->add($notice, $broadcast->get_notice_type(), 'admin', strval($broadcast->get_id()));
WP_Ultimo()->notices->add($notice, $broadcast->get_notice_type(), 'user', strval($broadcast->get_id()));
} // end if;
} // end if;
} // end foreach;
} // end if;
} // end add_unseen_broadcast_notices;
}
}
}
}
}
/**
* Handles the broadcast message send via modal.
@ -138,21 +126,18 @@ class Broadcast_Manager extends Base_Manager {
$target_products = wu_request('target_products', '');
if (!$target_customers && !$target_products) {
if ( ! $target_customers && ! $target_products) {
wp_send_json_error(new \WP_Error('error', __('No product or customer target was selected.', 'wp-ultimo')));
} // end if;
}
$broadcast_type = wu_request('type', 'broadcast_notice');
$args['type'] = $broadcast_type;
if ($broadcast_type === 'broadcast_notice') {
$targets = array(
'customers' => $target_customers,
'products' => $target_products
'products' => $target_products,
);
$args['targets'] = $targets;
@ -161,21 +146,19 @@ class Broadcast_Manager extends Base_Manager {
$saved = $this->save_broadcast($args);
if (is_wp_error($saved)) {
wp_send_json_error($saved);
} // end if;
}
$redirect = current_user_can('wu_edit_broadcasts') ? 'wp-ultimo-edit-broadcast' : 'wp-ultimo-broadcasts';
wp_send_json_success(array(
'redirect_url' => add_query_arg('id', $saved->get_id(), wu_network_admin_url($redirect))
));
} // end if;
wp_send_json_success(
array(
'redirect_url' => add_query_arg('id', $saved->get_id(), wu_network_admin_url($redirect)),
)
);
}
if ($args['type'] === 'broadcast_email') {
$to = array();
$bcc = array();
@ -183,28 +166,22 @@ class Broadcast_Manager extends Base_Manager {
$targets = array();
if ($args['target_customers']) {
$customers = explode(',', (string) $args['target_customers']);
$targets = array_merge($targets, $customers);
} // end if;
}
if ($args['target_products']) {
$product_targets = explode(',', (string) $args['target_products']);
$customers = array();
foreach ($product_targets as $product_id) {
$customers = array_merge($customers, wu_get_membership_customers($product_id));
} // end foreach;
}
$targets = array_merge($targets, $customers);
} // end if;
}
$targets = array_unique($targets);
@ -212,35 +189,27 @@ class Broadcast_Manager extends Base_Manager {
* Get name and email based on user id
*/
foreach ($targets as $target) {
$customer = wu_get_customer($target);
if ($customer) {
$to[] = array(
'name' => $customer->get_display_name(),
'email' => $customer->get_email_address(),
);
}
}
} // end if;
} // end foreach;
if (!isset($args['custom_sender'])) {
if ( ! isset($args['custom_sender'])) {
$from = array(
'name' => wu_get_setting('from_name', get_network_option(null, 'site_name')),
'email' => wu_get_setting('from_email', get_network_option(null, 'admin_email')),
);
} else {
$from = array(
'name' => $args['custom_sender']['from_name'],
'email' => $args['custom_sender']['from_email'],
);
} // end if;
}
$template_type = wu_get_setting('email_template_type', 'html');
@ -255,19 +224,14 @@ class Broadcast_Manager extends Base_Manager {
);
try {
$status = Sender::send_mail($from, $to, $send_args);
} catch (\Throwable $e) {
$error = new \WP_Error($e->getCode(), $e->getMessage());
wp_send_json_error($error);
} // end try;
}
if ($status) {
$args['targets'] = array(
'customers' => $args['target_customers'],
'products' => $args['target_products'],
@ -276,19 +240,18 @@ class Broadcast_Manager extends Base_Manager {
// then we save with the message status (success, fail)
$this->save_broadcast($args);
wp_send_json_success(array(
'redirect_url' => wu_network_admin_url('wp-ultimo-broadcasts')
));
} // end if;
} // end if;
wp_send_json_success(
array(
'redirect_url' => wu_network_admin_url('wp-ultimo-broadcasts'),
)
);
}
}
$error = new \WP_Error('mail-error', __('Something wrong happened.', 'wp-ultimo'));
wp_send_json_error($error);
} // end handle_broadcast;
}
/**
* Saves the broadcast message in the database
@ -310,18 +273,15 @@ class Broadcast_Manager extends Base_Manager {
$broadcast = new Broadcast($broadcast_data);
if ($args['type'] === 'broadcast_notice') {
$broadcast->set_notice_type($args['notice_type']);
} // end if;
}
$broadcast->set_message_targets($args['targets']);
$saved = $broadcast->save();
return is_wp_error($saved) ? $saved : $broadcast;
} // end save_broadcast;
}
/**
* Returns targets for a specific broadcast.
@ -338,21 +298,16 @@ class Broadcast_Manager extends Base_Manager {
$targets = $broadcast->get_message_targets();
if (isset($targets[$type])) {
if (isset($targets[ $type ])) {
if (is_string($targets[ $type ])) {
return explode(',', $targets[ $type ]);
}
if (is_string($targets[$type])) {
return explode(',', $targets[$type]);
} // end if;
return (array) $targets[$type];
} // end if;
return (array) $targets[ $type ];
}
return array();
} // end get_broadcast_targets;
}
/**
* Returns all customer from targets.
@ -371,41 +326,25 @@ class Broadcast_Manager extends Base_Manager {
$product_customers = array();
if (is_array($products) && $products[0]) {
foreach ($products as $product_key => $product) {
$membership_customers = wu_get_membership_customers($product);
if ($membership_customers) {
if (is_array($membership_customers)) {
$product_customers = array_merge($membership_customers, $product_customers);
} else {
array_push($product_customers, $membership_customers);
} // end if;
} // end if;
} // end foreach;
} // end if;
}
}
}
}
if (isset($product_customers) ) {
$targets = array_merge($product_customers, $customers_targets);
} else {
$targets = $customers_targets;
} // end if;
}
return array_map('absint', array_filter(array_unique($targets)));
} // end get_all_notice_customer_targets;
} // end class Broadcast_Manager;
}
}

View File

@ -38,21 +38,16 @@ class Cache_Manager {
* To support more caching plugins, just add a method to this class suffixed with '_cache_flush'
*/
foreach (get_class_methods($this) as $method) {
if (substr_compare($method, '_cache_flush', -strlen('_cache_flush')) === 0) {
$this->$method();
} // end if;
} // end foreach;
}
}
/**
* Hook to additional cleaning
*/
do_action('wu_flush_known_caches');
} // end flush_known_caches;
}
/**
* Flush WPEngine Cache
@ -63,14 +58,12 @@ class Cache_Manager {
protected function wp_engine_cache_flush() {
if (class_exists('\WpeCommon') && method_exists('\WpeCommon', 'purge_varnish_cache')) {
\WpeCommon::purge_memcached(); // WPEngine Cache Flushing
\WpeCommon::clear_maxcdn_cache(); // WPEngine Cache Flushing
\WpeCommon::purge_varnish_cache(); // WPEngine Cache Flushing
} // end if;
} // end wp_engine_cache_flush;
}
}
/**
* Flush WP Rocket Cache
@ -81,12 +74,9 @@ class Cache_Manager {
protected function wp_rocket_cache_flush() {
if (function_exists('rocket_clean_domain')) {
\rocket_clean_domain();
} // end if;
} // end wp_rocket_cache_flush;
}
}
/**
* Flush WP Super Cache
@ -97,12 +87,10 @@ class Cache_Manager {
protected function wp_super_cache_flush() {
if (function_exists('wp_cache_clear_cache')) {
\wp_cache_clear_cache(); // WP Super Cache Flush
} // end if;
} // end wp_super_cache_flush;
}
}
/**
* Flush WP Fastest Cache
@ -113,12 +101,10 @@ class Cache_Manager {
protected function wp_fastest_cache_flush() {
if (function_exists('wpfc_clear_all_cache')) {
\wpfc_clear_all_cache(); // WP Fastest Cache Flushing
} // end if;
} // end wp_fastest_cache_flush;
}
}
/**
* Flush W3 Total Cache
@ -129,12 +115,10 @@ class Cache_Manager {
protected function w3_total_cache_flush() {
if (function_exists('w3tc_pgcache_flush')) {
\w3tc_pgcache_flush(); // W3TC Cache Flushing
} // end if;
} // end w3_total_cache_flush;
}
}
/**
* Flush Hummingbird Cache
@ -145,12 +129,10 @@ class Cache_Manager {
protected function hummingbird_cache_flush() {
if (class_exists('\Hummingbird\WP_Hummingbird') && method_exists('\Hummingbird\WP_Hummingbird', 'flush_cache')) {
\Hummingbird\WP_Hummingbird::flush_cache(); // Hummingbird Cache Flushing
} // end if;
} // end hummingbird_cache_flush;
}
}
/**
* Flush WP Optimize Cache
@ -161,18 +143,14 @@ class Cache_Manager {
protected function wp_optimize_cache_flush() {
if (class_exists('\WP_Optimize') && method_exists('\WP_Optimize', 'get_page_cache')) {
$wp_optimize = \WP_Optimize()->get_page_cache();
if (method_exists($wp_optimize, 'purge')) {
$wp_optimize->purge(); // WP Optimize Cache Flushing
} // end if;
} // end if;
} // end wp_optimize_cache_flush;
}
}
}
/**
* Flush Comet Cache
@ -183,12 +161,10 @@ class Cache_Manager {
protected function comet_cache_flush() {
if (class_exists('\Comet_Cache') && method_exists('\Comet_Cache', 'clear')) {
\Comet_Cache::clear(); // Comet Cache Flushing
} // end if;
} // end comet_cache_flush;
}
}
/**
* Flush LiteSpeed Cache
@ -199,11 +175,8 @@ class Cache_Manager {
protected function litespeed_cache_flush() {
if (class_exists('\LiteSpeed_Cache_API') && method_exists('\LiteSpeed_Cache_API', 'purge_all')) {
\LiteSpeed_Cache_API::purge_all(); // LiteSpeed Cache Flushing
} // end if;
} // end litespeed_cache_flush;
} // end class Cache_Manager;
}
}
}

View File

@ -23,7 +23,9 @@ defined('ABSPATH') || exit;
*/
class Checkout_Form_Manager extends Base_Manager {
use \WP_Ultimo\Apis\Rest_Api, \WP_Ultimo\Apis\WP_CLI, \WP_Ultimo\Traits\Singleton;
use \WP_Ultimo\Apis\Rest_Api;
use \WP_Ultimo\Apis\WP_CLI;
use \WP_Ultimo\Traits\Singleton;
/**
* The manager slug.
@ -52,7 +54,5 @@ class Checkout_Form_Manager extends Base_Manager {
$this->enable_rest_api();
$this->enable_wp_cli();
} // end init;
} // end class Checkout_Form_Manager;
}
}

View File

@ -11,9 +11,9 @@
namespace WP_Ultimo\Managers;
use \WP_Ultimo\Managers\Base_Manager;
use \WP_Ultimo\Models\Customer;
use \WP_Ultimo\Database\Memberships\Membership_Status;
use WP_Ultimo\Managers\Base_Manager;
use WP_Ultimo\Models\Customer;
use WP_Ultimo\Database\Memberships\Membership_Status;
// Exit if accessed directly
defined('ABSPATH') || exit;
@ -25,7 +25,9 @@ defined('ABSPATH') || exit;
*/
class Customer_Manager extends Base_Manager {
use \WP_Ultimo\Apis\Rest_Api, \WP_Ultimo\Apis\WP_CLI, \WP_Ultimo\Traits\Singleton;
use \WP_Ultimo\Apis\Rest_Api;
use \WP_Ultimo\Apis\WP_CLI;
use \WP_Ultimo\Traits\Singleton;
/**
* The manager slug.
@ -55,11 +57,16 @@ class Customer_Manager extends Base_Manager {
$this->enable_wp_cli();
add_action('init', function () {
Event_Manager::register_model_events( 'customer',
__( 'Customer', 'wp-ultimo' ),
array( 'created', 'updated' ) );
});
add_action(
'init',
function () {
Event_Manager::register_model_events(
'customer',
__('Customer', 'wp-ultimo'),
array('created', 'updated')
);
}
);
add_action('wp_login', array($this, 'log_ip_and_last_login'), 10, 2);
add_filter('heartbeat_send', array($this, 'on_heartbeat_send'));
@ -71,8 +78,7 @@ class Customer_Manager extends Base_Manager {
add_action('wu_maybe_create_customer', array($this, 'maybe_add_to_main_site'), 10, 2);
add_action('wp_ajax_wu_resend_verification_email', array($this, 'handle_resend_verification_email'));
} // end init;
}
/**
* Handle the resend verification email ajax action.
@ -82,31 +88,26 @@ class Customer_Manager extends Base_Manager {
*/
public function handle_resend_verification_email() {
if (!check_ajax_referer('wu_resend_verification_email_nonce', false, false)) {
if ( ! check_ajax_referer('wu_resend_verification_email_nonce', false, false)) {
wp_send_json_error(new \WP_Error('not-allowed', __('Error: you are not allowed to perform this action.', 'wp-ultimo')));
exit;
} // end if;
}
$customer = wu_get_current_customer();
if (!$customer) {
if ( ! $customer) {
wp_send_json_error(new \WP_Error('customer-not-found', __('Error: customer not found.', 'wp-ultimo')));
exit;
} // end if;
}
$customer->send_verification_email();
wp_send_json_success();
exit;
} // end handle_resend_verification_email;
}
/**
* Handle heartbeat response sent.
@ -121,8 +122,7 @@ class Customer_Manager extends Base_Manager {
$this->log_ip_and_last_login(wp_get_current_user());
return $response;
} // end on_heartbeat_send;
}
/**
* Saves the IP address and last_login date onto the user.
@ -134,29 +134,22 @@ class Customer_Manager extends Base_Manager {
*/
public function log_ip_and_last_login($user) {
if (!is_a($user, '\WP_User')) {
if ( ! is_a($user, '\WP_User')) {
$user = get_user_by('login', $user);
}
} // end if;
if (!$user) {
if ( ! $user) {
return;
} // end if;
}
$customer = wu_get_customer_by_user_id($user->ID);
if (!$customer) {
if ( ! $customer) {
return;
} // end if;
}
$customer->update_last_login();
} // end log_ip_and_last_login;
}
/**
* Watches the change in customer verification status to take action when needed.
@ -171,20 +164,15 @@ class Customer_Manager extends Base_Manager {
public function transition_customer_email_verification($old_status, $new_status, $customer_id) {
if ($new_status !== 'pending') {
return;
} // end if;
}
$customer = wu_get_customer($customer_id);
if ($customer) {
$customer->send_verification_email();
} // end if;
} // end transition_customer_email_verification;
}
}
/**
* Verifies a customer by checking the email key.
@ -200,72 +188,58 @@ class Customer_Manager extends Base_Manager {
$email_verify_key = wu_request('email-verification-key');
if (!$email_verify_key) {
if ( ! $email_verify_key) {
return;
} // end if;
}
$customer_hash = wu_request('customer');
$customer_to_verify = wu_get_customer_by_hash($customer_hash);
if (!is_user_logged_in()) {
if ( ! is_user_logged_in()) {
wp_die(
sprintf(
/* translators: the placeholder is the login URL */
__('You must be authenticated in order to verify your email address. <a href=%s>Click here</a> to access your account.', 'wp-ultimo'),
wp_login_url(add_query_arg(
array(
'email-verification-key' => $email_verify_key,
'customer' => $customer_hash,
wp_login_url(
add_query_arg(
array(
'email-verification-key' => $email_verify_key,
'customer' => $customer_hash,
)
)
))
)
)
);
}
} // end if;
if (!$customer_to_verify) {
if ( ! $customer_to_verify) {
wp_die(__('Invalid verification key.', 'wp-ultimo'));
} // end if;
}
$current_customer = wu_get_current_customer();
if (!$current_customer) {
if ( ! $current_customer) {
wp_die(__('Invalid verification key.', 'wp-ultimo'));
} // end if;
}
if ($current_customer->get_id() !== $customer_to_verify->get_id()) {
wp_die(__('Invalid verification key.', 'wp-ultimo'));
} // end if;
}
if ($customer_to_verify->get_email_verification() !== 'pending') {
wp_die(__('Invalid verification key.', 'wp-ultimo'));
} // end if;
}
$key = $customer_to_verify->get_verification_key();
if (!$key) {
if ( ! $key) {
wp_die(__('Invalid verification key.', 'wp-ultimo'));
} // end if;
}
if ($key !== $email_verify_key) {
wp_die(__('Invalid verification key.', 'wp-ultimo'));
} // end if;
}
/*
* Uff! If we got here, we can verify the customer.
@ -285,52 +259,44 @@ class Customer_Manager extends Base_Manager {
* which one to manage.
*/
if (count($memberships) === 1) {
$membership = current($memberships);
/*
* Only publish pending memberships
*/
if ($membership->get_status() === Membership_Status::PENDING) {
$membership->publish_pending_site_async();
if ($membership->get_date_trial_end() <= gmdate('Y-m-d 23:59:59')) {
$membership->set_status(Membership_Status::ACTIVE);
} // end if;
}
$membership->save();
} elseif ($membership->get_status() === Membership_Status::TRIALING) {
$membership->publish_pending_site_async();
} // end if;
}
$payments = $membership->get_payments();
if ($payments) {
$redirect_url = add_query_arg(array(
'payment' => $payments[0]->get_hash(),
'status' => 'done',
), wu_get_registration_url());
$redirect_url = add_query_arg(
array(
'payment' => $payments[0]->get_hash(),
'status' => 'done',
),
wu_get_registration_url()
);
wp_redirect($redirect_url);
exit;
} // end if;
} // end if;
}
}
wp_redirect(get_admin_url($customer_to_verify->get_primary_site_id()));
exit;
} // end maybe_verify_email_address;
}
/**
* Maybe adds the customer to the main site.
@ -343,24 +309,18 @@ class Customer_Manager extends Base_Manager {
*/
public function maybe_add_to_main_site($customer, $checkout) {
if (!wu_get_setting('add_users_to_main_site')) {
if ( ! wu_get_setting('add_users_to_main_site')) {
return;
} // end if;
}
$user_id = $customer->get_user_id();
$is_already_user = is_user_member_of_blog($user_id, wu_get_main_site_id());
if ($is_already_user === false) {
$role = wu_get_setting('main_site_default_role', 'subscriber');
add_user_to_blog(wu_get_main_site_id(), $user_id, $role);
} // end if;
} // end maybe_add_to_main_site;
} // end class Customer_Manager;
}
}
}

View File

@ -24,7 +24,9 @@ defined('ABSPATH') || exit;
*/
class Discount_Code_Manager extends Base_Manager {
use \WP_Ultimo\Apis\Rest_Api, \WP_Ultimo\Apis\WP_CLI, \WP_Ultimo\Traits\Singleton;
use \WP_Ultimo\Apis\Rest_Api;
use \WP_Ultimo\Apis\WP_CLI;
use \WP_Ultimo\Traits\Singleton;
/**
* The manager slug.
@ -55,8 +57,7 @@ class Discount_Code_Manager extends Base_Manager {
$this->enable_wp_cli();
add_action('wu_gateway_payment_processed', array($this, 'maybe_add_use_on_payment_received'));
} // end init;
}
/**
* Listens for payments received in order to increase the discount code uses.
@ -68,11 +69,9 @@ class Discount_Code_Manager extends Base_Manager {
*/
public function maybe_add_use_on_payment_received($payment) {
if (!$payment) {
if ( ! $payment) {
return;
} // end if;
}
/*
* Try to fetch the original cart of the payment.
@ -82,18 +81,14 @@ class Discount_Code_Manager extends Base_Manager {
$original_cart = $payment->get_meta('wu_original_cart');
if (is_a($original_cart, \WP_Ultimo\Checkout\Cart::class) === false) {
return;
} // end if;
}
$discount_code = $original_cart->get_discount_code();
if (!$discount_code) {
if ( ! $discount_code) {
return;
} // end if;
}
/*
* Refetch the object, as the original version
@ -102,13 +97,9 @@ class Discount_Code_Manager extends Base_Manager {
$discount_code = wu_get_discount_code($discount_code->get_id());
if ($discount_code) {
$discount_code->add_use();
$discount_code->save();
} // end if;
} // end maybe_add_use_on_payment_received;
} // end class Discount_Code_Manager;
}
}
}

View File

@ -25,7 +25,9 @@ defined('ABSPATH') || exit;
*/
class Domain_Manager extends Base_Manager {
use \WP_Ultimo\Apis\Rest_Api, \WP_Ultimo\Apis\WP_CLI, \WP_Ultimo\Traits\Singleton;
use \WP_Ultimo\Apis\Rest_Api;
use \WP_Ultimo\Apis\WP_CLI;
use \WP_Ultimo\Traits\Singleton;
/**
* The manager slug.
@ -62,8 +64,7 @@ class Domain_Manager extends Base_Manager {
public function get_integrations() {
return apply_filters('wu_domain_manager_get_integrations', $this->integrations, $this);
} // end get_integrations;
}
/**
* Get the instance of one of the integrations classes.
@ -77,17 +78,14 @@ class Domain_Manager extends Base_Manager {
$integrations = $this->get_integrations();
if (isset($integrations[$id])) {
$class_name = $integrations[$id];
if (isset($integrations[ $id ])) {
$class_name = $integrations[ $id ];
return $class_name::get_instance();
} // end if;
}
return false;
} // end get_integration_instance;
}
/**
* Instantiate the necessary hooks.
@ -134,8 +132,7 @@ class Domain_Manager extends Base_Manager {
add_action('wp_insert_site', array($this, 'handle_site_created'));
add_action('wp_delete_site', array($this, 'handle_site_deleted'));
} // end init;
}
/**
* Set COOKIE_DOMAIN if not defined in sites with mapped domains.
@ -146,13 +143,10 @@ class Domain_Manager extends Base_Manager {
*/
protected function set_cookie_domain() {
if (defined('DOMAIN_CURRENT_SITE') && !defined('COOKIE_DOMAIN') && !preg_match('/' . DOMAIN_CURRENT_SITE . '$/', '.' . $_SERVER['HTTP_HOST'])) {
define( 'COOKIE_DOMAIN', '.' . $_SERVER['HTTP_HOST'] );
} // end if;
} // end set_cookie_domain;
if (defined('DOMAIN_CURRENT_SITE') && ! defined('COOKIE_DOMAIN') && ! preg_match('/' . DOMAIN_CURRENT_SITE . '$/', '.' . $_SERVER['HTTP_HOST'])) {
define('COOKIE_DOMAIN', '.' . $_SERVER['HTTP_HOST']);
}
}
/**
* Triggers subdomain mapping events on site creation.
@ -168,11 +162,9 @@ class Domain_Manager extends Base_Manager {
$has_subdomain = str_replace($current_site->domain, '', $site->domain);
if (!$has_subdomain) {
if ( ! $has_subdomain) {
return;
} // end if;
}
$args = array(
'subdomain' => $site->domain,
@ -180,8 +172,7 @@ class Domain_Manager extends Base_Manager {
);
wu_enqueue_async_action('wu_add_subdomain', $args, 'domain');
} // end handle_site_created;
}
/**
* Triggers subdomain mapping events on site deletion.
@ -197,11 +188,9 @@ class Domain_Manager extends Base_Manager {
$has_subdomain = str_replace($current_site->domain, '', $site->domain);
if (!$has_subdomain) {
if ( ! $has_subdomain) {
return;
} // end if;
}
$args = array(
'subdomain' => $site->domain,
@ -209,8 +198,7 @@ class Domain_Manager extends Base_Manager {
);
wu_enqueue_async_action('wu_remove_subdomain', $args, 'domain');
} // end handle_site_deleted;
}
/**
* Triggers the do_event of the payment successful.
@ -232,8 +220,7 @@ class Domain_Manager extends Base_Manager {
);
wu_do_event('domain_created', $payload);
} // end handle_domain_created;
}
/**
* Remove send domain removal event.
@ -247,17 +234,14 @@ class Domain_Manager extends Base_Manager {
public function handle_domain_deleted($result, $domain) {
if ($result) {
$args = array(
'domain' => $domain->get_domain(),
'site_id' => $domain->get_site_id(),
);
wu_enqueue_async_action('wu_remove_domain', $args, 'domain');
} // end if;
} // end handle_domain_deleted;
}
}
/**
* Add all domain mapping settings.
@ -267,59 +251,78 @@ class Domain_Manager extends Base_Manager {
*/
public function add_domain_mapping_settings() {
wu_register_settings_field('domain-mapping', 'domain_mapping_header', array(
'title' => __('Domain Mapping Settings', 'wp-ultimo'),
'desc' => __('Define the domain mapping settings for your network.', 'wp-ultimo'),
'type' => 'header',
));
wu_register_settings_field(
'domain-mapping',
'domain_mapping_header',
array(
'title' => __('Domain Mapping Settings', 'wp-ultimo'),
'desc' => __('Define the domain mapping settings for your network.', 'wp-ultimo'),
'type' => 'header',
)
);
wu_register_settings_field('domain-mapping', 'enable_domain_mapping', array(
'title' => __('Enable Domain Mapping?', 'wp-ultimo'),
'desc' => __('Do you want to enable domain mapping?', 'wp-ultimo'),
'type' => 'toggle',
'default' => 1,
));
wu_register_settings_field(
'domain-mapping',
'enable_domain_mapping',
array(
'title' => __('Enable Domain Mapping?', 'wp-ultimo'),
'desc' => __('Do you want to enable domain mapping?', 'wp-ultimo'),
'type' => 'toggle',
'default' => 1,
)
);
wu_register_settings_field('domain-mapping', 'force_admin_redirect', array(
'title' => __('Force Admin Redirect', 'wp-ultimo'),
'desc' => __('Select how you want your users to access the admin panel if they have mapped domains.', 'wp-ultimo') . '<br><br>' . __('Force Redirect to Mapped Domain: your users with mapped domains will be redirected to theirdomain.com/wp-admin, even if they access using yournetworkdomain.com/wp-admin.', 'wp-ultimo') . '<br><br>' . __('Force Redirect to Network Domain: your users with mapped domains will be redirect to yournetworkdomain.com/wp-admin, even if they access using theirdomain.com/wp-admin.', 'wp-ultimo'),
'tooltip' => '',
'type' => 'select',
'default' => 'both',
'require' => array('enable_domain_mapping' => 1),
'options' => array(
'both' => __('Allow access to the admin by both mapped domain and network domain', 'wp-ultimo'),
'force_map' => __('Force Redirect to Mapped Domain', 'wp-ultimo'),
'force_network' => __('Force Redirect to Network Domain', 'wp-ultimo'),
),
));
wu_register_settings_field(
'domain-mapping',
'force_admin_redirect',
array(
'title' => __('Force Admin Redirect', 'wp-ultimo'),
'desc' => __('Select how you want your users to access the admin panel if they have mapped domains.', 'wp-ultimo') . '<br><br>' . __('Force Redirect to Mapped Domain: your users with mapped domains will be redirected to theirdomain.com/wp-admin, even if they access using yournetworkdomain.com/wp-admin.', 'wp-ultimo') . '<br><br>' . __('Force Redirect to Network Domain: your users with mapped domains will be redirect to yournetworkdomain.com/wp-admin, even if they access using theirdomain.com/wp-admin.', 'wp-ultimo'),
'tooltip' => '',
'type' => 'select',
'default' => 'both',
'require' => array('enable_domain_mapping' => 1),
'options' => array(
'both' => __('Allow access to the admin by both mapped domain and network domain', 'wp-ultimo'),
'force_map' => __('Force Redirect to Mapped Domain', 'wp-ultimo'),
'force_network' => __('Force Redirect to Network Domain', 'wp-ultimo'),
),
)
);
wu_register_settings_field('domain-mapping', 'custom_domains', array(
'title' => __('Enable Custom Domains?', 'wp-ultimo'),
'desc' => __('Toggle this option if you wish to allow end-customers to add their own domains. This can be controlled on a plan per plan basis.', 'wp-ultimo'),
'type' => 'toggle',
'default' => 1,
'require' => array(
'enable_domain_mapping' => true,
),
));
wu_register_settings_field(
'domain-mapping',
'custom_domains',
array(
'title' => __('Enable Custom Domains?', 'wp-ultimo'),
'desc' => __('Toggle this option if you wish to allow end-customers to add their own domains. This can be controlled on a plan per plan basis.', 'wp-ultimo'),
'type' => 'toggle',
'default' => 1,
'require' => array(
'enable_domain_mapping' => true,
),
)
);
wu_register_settings_field('domain-mapping', 'domain_mapping_instructions', array(
'title' => __('Add New Domain Instructions', 'wp-ultimo'),
'tooltip' => __('Display a customized message with instructions for the mapping and alerting the end-user of the risks of mapping a misconfigured domain.', 'wp-ultimo'),
'desc' => __('You can use the placeholder <code>%NETWORK_DOMAIN%</code> and <code>%NETWORK_IP%</code>.', 'wp-ultimo'),
'type' => 'textarea',
'default' => array($this, 'default_domain_mapping_instructions'),
'html_attr' => array(
'rows' => 8,
),
'require' => array(
'enable_domain_mapping' => true,
'custom_domains' => true,
),
));
} // end add_domain_mapping_settings;
wu_register_settings_field(
'domain-mapping',
'domain_mapping_instructions',
array(
'title' => __('Add New Domain Instructions', 'wp-ultimo'),
'tooltip' => __('Display a customized message with instructions for the mapping and alerting the end-user of the risks of mapping a misconfigured domain.', 'wp-ultimo'),
'desc' => __('You can use the placeholder <code>%NETWORK_DOMAIN%</code> and <code>%NETWORK_IP%</code>.', 'wp-ultimo'),
'type' => 'textarea',
'default' => array($this, 'default_domain_mapping_instructions'),
'html_attr' => array(
'rows' => 8,
),
'require' => array(
'enable_domain_mapping' => true,
'custom_domains' => true,
),
)
);
}
/**
* Add all SSO settings.
@ -329,40 +332,55 @@ class Domain_Manager extends Base_Manager {
*/
public function add_sso_settings() {
wu_register_settings_field('sso', 'sso_header', array(
'title' => __('Single Sign-On Settings', 'wp-ultimo'),
'desc' => __('Settings to configure the Single Sign-On functionality of WP Multisite WaaS, responsible for keeping customers and admins logged in across all network domains.', 'wp-ultimo'),
'type' => 'header',
));
wu_register_settings_field(
'sso',
'sso_header',
array(
'title' => __('Single Sign-On Settings', 'wp-ultimo'),
'desc' => __('Settings to configure the Single Sign-On functionality of WP Multisite WaaS, responsible for keeping customers and admins logged in across all network domains.', 'wp-ultimo'),
'type' => 'header',
)
);
wu_register_settings_field('sso', 'enable_sso', array(
'title' => __('Enable Single Sign-On', 'wp-ultimo'),
'desc' => __('Enables the Single Sign-on functionality.', 'wp-ultimo'),
'type' => 'toggle',
'default' => 1,
));
wu_register_settings_field(
'sso',
'enable_sso',
array(
'title' => __('Enable Single Sign-On', 'wp-ultimo'),
'desc' => __('Enables the Single Sign-on functionality.', 'wp-ultimo'),
'type' => 'toggle',
'default' => 1,
)
);
wu_register_settings_field('sso', 'restrict_sso_to_login_pages', array(
'title' => __('Restrict SSO Checks to Login Pages', 'wp-ultimo'),
'desc' => __('The Single Sign-on feature adds one extra ajax calls to every page load on sites with custom domains active to check if it should perform an auth loopback. You can restrict these extra calls to the login pages of sub-sites using this option. If enabled, SSO will only work on login pages.', 'wp-ultimo'),
'type' => 'toggle',
'default' => 0,
'require' => array(
'enable_sso' => true,
),
));
wu_register_settings_field(
'sso',
'restrict_sso_to_login_pages',
array(
'title' => __('Restrict SSO Checks to Login Pages', 'wp-ultimo'),
'desc' => __('The Single Sign-on feature adds one extra ajax calls to every page load on sites with custom domains active to check if it should perform an auth loopback. You can restrict these extra calls to the login pages of sub-sites using this option. If enabled, SSO will only work on login pages.', 'wp-ultimo'),
'type' => 'toggle',
'default' => 0,
'require' => array(
'enable_sso' => true,
),
)
);
wu_register_settings_field('sso', 'enable_sso_loading_overlay', array(
'title' => __('Enable SSO Loading Overlay', 'wp-ultimo'),
'desc' => __('When active, a loading overlay will be added on-top of the site currently being viewed while the SSO auth loopback is performed on the background.', 'wp-ultimo'),
'type' => 'toggle',
'default' => 1,
'require' => array(
'enable_sso' => true,
),
));
} // end add_sso_settings;
wu_register_settings_field(
'sso',
'enable_sso_loading_overlay',
array(
'title' => __('Enable SSO Loading Overlay', 'wp-ultimo'),
'desc' => __('When active, a loading overlay will be added on-top of the site currently being viewed while the SSO auth loopback is performed on the background.', 'wp-ultimo'),
'type' => 'toggle',
'default' => 1,
'require' => array(
'enable_sso' => true,
),
)
);
}
/**
* Returns the default instructions for domain mapping.
*
@ -379,8 +397,7 @@ class Domain_Manager extends Base_Manager {
$instructions[] = __('After you finish that step, come back to this screen and click the button below.', 'wp-ultimo');
return implode(PHP_EOL . PHP_EOL, $instructions);
} // end default_domain_mapping_instructions;
}
/**
* Gets the instructions, filtered and without the shortcodes.
@ -394,11 +411,9 @@ class Domain_Manager extends Base_Manager {
$instructions = wu_get_setting('domain_mapping_instructions');
if (!$instructions) {
if ( ! $instructions) {
$instructions = $this->default_domain_mapping_instructions();
} // end if;
}
$domain = $current_site->domain;
$ip = Helper::get_network_public_ip();
@ -410,8 +425,7 @@ class Domain_Manager extends Base_Manager {
$instructions = str_replace('%NETWORK_IP%', $ip, $instructions);
return apply_filters('wu_get_domain_mapping_instructions', $instructions, $domain, $ip);
} // end get_domain_mapping_instructions;
}
/**
* Creates the event to save the transition.
@ -426,7 +440,6 @@ class Domain_Manager extends Base_Manager {
public function send_domain_to_host($old_value, $new_value, $item_id) {
if ($old_value !== $new_value) {
$domain = wu_get_domain($item_id);
$args = array(
@ -435,10 +448,8 @@ class Domain_Manager extends Base_Manager {
);
wu_enqueue_async_action('wu_add_domain', $args, 'domain');
} // end if;
} // end send_domain_to_host;
}
}
/**
* Checks the DNS and SSL status of a domain.
@ -453,17 +464,15 @@ class Domain_Manager extends Base_Manager {
$domain = wu_get_domain($domain_id);
if (!$domain) {
if ( ! $domain) {
return;
} // end if;
}
$max_tries = apply_filters('wu_async_process_domain_stage_max_tries', 5, $domain);
$try_again_time = apply_filters('wu_async_process_domains_try_again_time', 5, $domain); // minutes
$tries++;
++$tries;
$stage = $domain->get_stage();
@ -473,9 +482,7 @@ class Domain_Manager extends Base_Manager {
wu_log_add("domain-{$domain_url}", sprintf(__('Starting Check for %s', 'wp-ultimo'), $domain_url));
if ($stage === 'checking-dns') {
if ($domain->has_correct_dns()) {
$domain->set_stage('checking-ssl-cert');
$domain->save();
@ -485,18 +492,23 @@ class Domain_Manager extends Base_Manager {
__('- DNS propagation finished, advancing domain to next step...', 'wp-ultimo')
);
wu_enqueue_async_action('wu_async_process_domain_stage', array('domain_id' => $domain_id, 'tries' => 0), 'domain');
wu_enqueue_async_action(
'wu_async_process_domain_stage',
array(
'domain_id' => $domain_id,
'tries' => 0,
),
'domain'
);
do_action('wu_domain_manager_dns_propagation_finished', $domain);
return;
} else {
/*
* Max attempts
*/
if ($tries > $max_tries) {
$domain->set_stage('failed');
$domain->save();
@ -508,8 +520,7 @@ class Domain_Manager extends Base_Manager {
);
return;
} // end if;
}
wu_log_add(
"domain-{$domain_url}",
@ -528,13 +539,9 @@ class Domain_Manager extends Base_Manager {
);
return;
} // end if;
}
} elseif ($stage === 'checking-ssl-cert') {
if ($domain->has_valid_ssl_certificate()) {
$domain->set_stage('done');
$domain->set_secure(true);
@ -547,13 +554,11 @@ class Domain_Manager extends Base_Manager {
);
return;
} else {
/*
* Max attempts
*/
if ($tries > $max_tries) {
$domain->set_stage('done-without-ssl');
$domain->save();
@ -565,8 +570,7 @@ class Domain_Manager extends Base_Manager {
);
return;
} // end if;
}
wu_log_add(
"domain-{$domain_url}",
@ -574,15 +578,20 @@ class Domain_Manager extends Base_Manager {
sprintf(__('- SSL Cert not found, retrying in %d minute(s)...', 'wp-ultimo'), $try_again_time)
);
wu_schedule_single_action(strtotime("+{$try_again_time} minutes"), 'wu_async_process_domain_stage', array('domain_id' => $domain_id, 'tries' => $tries), 'domain');
wu_schedule_single_action(
strtotime("+{$try_again_time} minutes"),
'wu_async_process_domain_stage',
array(
'domain_id' => $domain_id,
'tries' => $tries,
),
'domain'
);
return;
} // end if;
} // end if;
} // end async_process_domain_stage;
}
}
}
/**
* Alternative implementation for PHP's native dns_get_record.
@ -606,7 +615,6 @@ class Domain_Manager extends Base_Manager {
);
foreach ($record_types as $record_type) {
$chain = new \RemotelyLiving\PHPDNS\Resolvers\Chain(
new \RemotelyLiving\PHPDNS\Resolvers\CloudFlare(),
new \RemotelyLiving\PHPDNS\Resolvers\GoogleDNS(),
@ -617,7 +625,6 @@ class Domain_Manager extends Base_Manager {
$records = $chain->getRecords($domain, $record_type);
foreach ($records as $record_data) {
$record = array();
$record['type'] = $record_type;
@ -625,10 +632,8 @@ class Domain_Manager extends Base_Manager {
$record['data'] = (string) $record_data->getData();
if (empty($record['data'])) {
$record['data'] = (string) $record_data->getIPAddress();
} // end if;
}
// Some DNS providers return a trailing dot.
$record['data'] = rtrim($record['data'], '.');
@ -642,14 +647,11 @@ class Domain_Manager extends Base_Manager {
$record['tag'] = ''; // Used by integrations.
$results[] = $record;
} // end foreach;
} // end foreach;
}
}
return apply_filters('wu_domain_dns_get_record', $results, $domain);
} // end dns_get_record;
}
/**
* Get the DNS records for a given domain.
@ -661,42 +663,41 @@ class Domain_Manager extends Base_Manager {
$domain = wu_request('domain');
if (!$domain) {
if ( ! $domain) {
wp_send_json_error(new \WP_Error('domain-missing', __('A valid domain was not passed.', 'wp-ultimo')));
} // end if;
}
$auth_ns = array();
$additional = array();
try {
$result = self::dns_get_record($domain);
} catch (\Throwable $e) {
wp_send_json_error(new \WP_Error('error', __('Not able to fetch DNS entries.', 'wp-ultimo'), array(
'exception' => $e->getMessage(),
)));
} // end try;
wp_send_json_error(
new \WP_Error(
'error',
__('Not able to fetch DNS entries.', 'wp-ultimo'),
array(
'exception' => $e->getMessage(),
)
)
);
}
if ($result === false) {
wp_send_json_error(new \WP_Error('error', __('Not able to fetch DNS entries.', 'wp-ultimo')));
}
} // end if;
wp_send_json_success(array(
'entries' => $result,
'auth' => $auth_ns,
'additional' => $additional,
'network_ip' => Helper::get_network_public_ip(),
));
} // end get_dns_records;
wp_send_json_success(
array(
'entries' => $result,
'auth' => $auth_ns,
'additional' => $additional,
'network_ip' => Helper::get_network_public_ip(),
)
);
}
/**
* Takes the list of domains and set them to non-primary when a new primary is added.
@ -711,20 +712,15 @@ class Domain_Manager extends Base_Manager {
public function async_remove_old_primary_domains($domains) {
foreach ($domains as $domain_id) {
$domain = wu_get_domain($domain_id);
if ($domain) {
$domain->set_primary_domain(false);
$domain->save();
} // end if;
} // end foreach;
} // end async_remove_old_primary_domains;
}
}
}
/**
* Tests the integration in the Wizard context.
@ -738,31 +734,30 @@ class Domain_Manager extends Base_Manager {
$integration = $this->get_integration_instance($integration_id);
if (!$integration) {
wp_send_json_error(array(
'message' => __('Invalid Integration ID', 'wp-ultimo'),
));
} // end if;
if ( ! $integration) {
wp_send_json_error(
array(
'message' => __('Invalid Integration ID', 'wp-ultimo'),
)
);
}
/*
* Checks for the constants...
*/
if (!$integration->is_setup()) {
wp_send_json_error(array(
'message' => sprintf(
__('The necessary constants were not found on your wp-config.php file: %s', 'wp-ultimo'),
implode(', ', $integration->get_missing_constants())
),
));
} // end if;
if ( ! $integration->is_setup()) {
wp_send_json_error(
array(
'message' => sprintf(
__('The necessary constants were not found on your wp-config.php file: %s', 'wp-ultimo'),
implode(', ', $integration->get_missing_constants())
),
)
);
}
return $integration->test_connection();
} // end test_integration;
}
/**
* Loads all the host provider integrations we have available.
@ -818,11 +813,9 @@ class Domain_Manager extends Base_Manager {
/**
* Allow developers to add their own host provider integrations via wp plugins.
*
*
* @since 2.0.0
*/
do_action('wp_ultimo_host_providers_load');
} // end load_integrations;
} // end class Domain_Manager;
}
}

View File

@ -12,10 +12,10 @@
namespace WP_Ultimo\Managers;
use Psr\Log\LogLevel;
use \WP_Ultimo\Managers\Base_Manager;
use \WP_Ultimo\Models\Email;
use \WP_Ultimo\Helpers\Sender;
use \WP_Ultimo\Models\Base_Model;
use WP_Ultimo\Managers\Base_Manager;
use WP_Ultimo\Models\Email;
use WP_Ultimo\Helpers\Sender;
use WP_Ultimo\Models\Base_Model;
// Exit if accessed directly
defined('ABSPATH') || exit;
@ -27,7 +27,9 @@ defined('ABSPATH') || exit;
*/
class Email_Manager extends Base_Manager {
use \WP_Ultimo\Apis\Rest_Api, \WP_Ultimo\Apis\WP_CLI, \WP_Ultimo\Traits\Singleton;
use \WP_Ultimo\Apis\Rest_Api;
use \WP_Ultimo\Apis\WP_CLI;
use \WP_Ultimo\Traits\Singleton;
/**
* The manager slug.
@ -65,9 +67,12 @@ class Email_Manager extends Base_Manager {
$this->enable_wp_cli();
add_action('init', function () {
$this->register_all_default_system_emails();
});
add_action(
'init',
function () {
$this->register_all_default_system_emails();
}
);
/*
* Adds the Email fields
@ -87,8 +92,7 @@ class Email_Manager extends Base_Manager {
add_action('wp_mail_failed', array($this, 'log_mailer_failure'));
add_action('wp_ajax_wu_get_event_payload_placeholders', array($this, 'get_event_placeholders'));
} // end init;
}
/**
* Send the email related to the current event.
@ -99,9 +103,11 @@ class Email_Manager extends Base_Manager {
*/
public function send_system_email($slug, $payload) {
$all_emails = wu_get_emails(array(
'event' => $slug,
));
$all_emails = wu_get_emails(
array(
'event' => $slug,
)
);
$original_from = array(
'name' => wu_get_setting('from_name'),
@ -112,19 +118,14 @@ class Email_Manager extends Base_Manager {
* Loop through all the emails registered.
*/
foreach ($all_emails as $email) {
if ($email->get_custom_sender()) {
$from = array(
'name' => $email->get_custom_sender_name(),
'email' => $email->get_custom_sender_email(),
);
} else {
$from = $original_from;
} // end if;
}
/*
* Compiles the target list.
@ -132,12 +133,10 @@ class Email_Manager extends Base_Manager {
$to = $email->get_target_list($payload);
if (empty($to)) {
wu_log_add('mailer', __('No targets found.', 'wp-ultimo'));
return;
} // end if;
}
$args = array(
'style' => $email->get_style(),
@ -150,26 +149,20 @@ class Email_Manager extends Base_Manager {
* Add the invoice attachment, if need be.
*/
if (wu_get_isset($payload, 'payment_invoice_url') && wu_get_setting('attach_invoice_pdf', true)) {
$file_name = 'invoice-' . $payload['payment_reference_code'] . '.pdf';
$this->attach_file_by_url($payload['payment_invoice_url'], $file_name, $args['subject']);
} // end if;
}
$when_to_send = $email->get_when_to_send();
if ($when_to_send) {
$args['schedule'] = $when_to_send;
} // end if;
}
Sender::send_mail($from, $to, $args);
} // end foreach;
} // end send_system_email;
}
}
/**
* Attach a file by a URL
@ -183,34 +176,35 @@ class Email_Manager extends Base_Manager {
*/
public function attach_file_by_url($file_url, $file_name, $email_subject = '') {
add_action('phpmailer_init', function($mail) use ($file_url, $file_name, $email_subject) {
add_action(
'phpmailer_init',
function ($mail) use ($file_url, $file_name, $email_subject) {
if ($email_subject && $mail->Subject !== $email_subject) { // phpcs:ignore
return;
return;
}
} // end if;
$response = wp_remote_get(
$file_url,
array(
'timeout' => 50,
)
);
$response = wp_remote_get($file_url, array(
'timeout' => 50,
));
if (is_wp_error($response)) {
return;
}
if (is_wp_error($response)) {
$file = wp_remote_retrieve_body($response);
return;
} // end if;
$file = wp_remote_retrieve_body($response);
/*
* Use the default PHPMailer APIs to attach the file.
*/
$mail->addStringAttachment($file, $file_name);
});
} // end attach_file_by_url;
/*
* Use the default PHPMailer APIs to attach the file.
*/
$mail->addStringAttachment($file, $file_name);
}
);
}
/**
* Add all email fields.
@ -220,71 +214,98 @@ class Email_Manager extends Base_Manager {
*/
public function add_email_fields() {
wu_register_settings_field('emails', 'sender_header', array(
'title' => __('Sender Settings', 'wp-ultimo'),
'desc' => __('Change the settings of the email headers, like from and name.', 'wp-ultimo'),
'type' => 'header',
));
wu_register_settings_field(
'emails',
'sender_header',
array(
'title' => __('Sender Settings', 'wp-ultimo'),
'desc' => __('Change the settings of the email headers, like from and name.', 'wp-ultimo'),
'type' => 'header',
)
);
wu_register_settings_field('emails', 'from_name', array(
'title' => __('"From" Name', 'wp-ultimo'),
'desc' => __('How the sender name will appear in emails sent by WP Multisite WaaS.', 'wp-ultimo'),
'type' => 'text',
'placeholder' => get_network_option(null, 'site_name'),
'default' => get_network_option(null, 'site_name'),
'html_attr' => array(
'v-model' => 'from_name',
),
));
wu_register_settings_field(
'emails',
'from_name',
array(
'title' => __('"From" Name', 'wp-ultimo'),
'desc' => __('How the sender name will appear in emails sent by WP Multisite WaaS.', 'wp-ultimo'),
'type' => 'text',
'placeholder' => get_network_option(null, 'site_name'),
'default' => get_network_option(null, 'site_name'),
'html_attr' => array(
'v-model' => 'from_name',
),
)
);
wu_register_settings_field('emails', 'from_email', array(
'title' => __('"From" E-mail', 'wp-ultimo'),
'desc' => __('How the sender email will appear in emails sent by WP Multisite WaaS.', 'wp-ultimo'),
'type' => 'email',
'placeholder' => get_network_option(null, 'admin_email'),
'default' => get_network_option(null, 'admin_email'),
'html_attr' => array(
'v-model' => 'from_email',
),
));
wu_register_settings_field(
'emails',
'from_email',
array(
'title' => __('"From" E-mail', 'wp-ultimo'),
'desc' => __('How the sender email will appear in emails sent by WP Multisite WaaS.', 'wp-ultimo'),
'type' => 'email',
'placeholder' => get_network_option(null, 'admin_email'),
'default' => get_network_option(null, 'admin_email'),
'html_attr' => array(
'v-model' => 'from_email',
),
)
);
wu_register_settings_field('emails', 'template_header', array(
'title' => __('Template Settings', 'wp-ultimo'),
'desc' => __('Change the settings of the email templates.', 'wp-ultimo'),
'type' => 'header',
));
wu_register_settings_field(
'emails',
'template_header',
array(
'title' => __('Template Settings', 'wp-ultimo'),
'desc' => __('Change the settings of the email templates.', 'wp-ultimo'),
'type' => 'header',
)
);
wu_register_settings_field('emails', 'email_template_type', array(
'title' => __('Email Templates Style', 'wp-ultimo'),
'desc' => __('Choose if email body will be sent using the HTML template or in plain text.', 'wp-ultimo'),
'type' => 'select',
'default' => 'html',
'options' => array(
'html' => __('HTML Emails', 'wp-ultimo'),
'plain' => __('Plain Emails', 'wp-ultimo'),
),
'html_attr' => array(
'v-model' => 'emails_template',
),
));
wu_register_settings_field(
'emails',
'email_template_type',
array(
'title' => __('Email Templates Style', 'wp-ultimo'),
'desc' => __('Choose if email body will be sent using the HTML template or in plain text.', 'wp-ultimo'),
'type' => 'select',
'default' => 'html',
'options' => array(
'html' => __('HTML Emails', 'wp-ultimo'),
'plain' => __('Plain Emails', 'wp-ultimo'),
),
'html_attr' => array(
'v-model' => 'emails_template',
),
)
);
wu_register_settings_field('emails', 'expiring_header', array(
'title' => __('Expiring Notification Settings', 'wp-ultimo'),
'desc' => __('Change the settings for the expiring notification (trials and subscriptions) emails.', 'wp-ultimo'),
'type' => 'header',
));
wu_register_settings_field(
'emails',
'expiring_header',
array(
'title' => __('Expiring Notification Settings', 'wp-ultimo'),
'desc' => __('Change the settings for the expiring notification (trials and subscriptions) emails.', 'wp-ultimo'),
'type' => 'header',
)
);
wu_register_settings_field('emails', 'expiring_days', array(
'title' => __('Days to Expire', 'wp-ultimo'),
'desc' => __('Select when we should send the notification email. If you select 3 days, for example, a notification email will be sent to every membership (or trial period) expiring in the next 3 days. Memberships are checked hourly.', 'wp-ultimo'),
'type' => 'number',
'placeholder' => __('e.g. 3', 'wp-ultimo'),
'html_attr' => array(
'v-model' => 'expiring_days',
),
));
} // end add_email_fields;
wu_register_settings_field(
'emails',
'expiring_days',
array(
'title' => __('Days to Expire', 'wp-ultimo'),
'desc' => __('Select when we should send the notification email. If you select 3 days, for example, a notification email will be sent to every membership (or trial period) expiring in the next 3 days. Memberships are checked hourly.', 'wp-ultimo'),
'type' => 'number',
'placeholder' => __('e.g. 3', 'wp-ultimo'),
'html_attr' => array(
'v-model' => 'expiring_days',
),
)
);
}
/**
* Register in the global variable all the default system emails.
@ -296,9 +317,8 @@ class Email_Manager extends Base_Manager {
*/
public function register_default_system_email($args) {
$this->registered_default_system_emails[$args['slug']] = $args;
} // end register_default_system_email;
$this->registered_default_system_emails[ $args['slug'] ] = $args;
}
/**
* Create a system email.
@ -311,33 +331,33 @@ class Email_Manager extends Base_Manager {
public function create_system_email($args) {
if ($this->is_created($args['slug'])) {
return;
}
} // end if;
$email_args = wp_parse_args($args, array(
'event' => '',
'title' => '',
'content' => '',
'slug' => '',
'target' => 'admin',
'style' => 'use_default',
'send_copy_to_admin' => true,
'active' => true,
'legacy' => false,
'date_registered' => wu_get_current_time('mysql', true),
'date_modified' => wu_get_current_time('mysql', true),
'status' => 'publish'
));
$email_args = wp_parse_args(
$args,
array(
'event' => '',
'title' => '',
'content' => '',
'slug' => '',
'target' => 'admin',
'style' => 'use_default',
'send_copy_to_admin' => true,
'active' => true,
'legacy' => false,
'date_registered' => wu_get_current_time('mysql', true),
'date_modified' => wu_get_current_time('mysql', true),
'status' => 'publish',
)
);
$email = new Email($email_args);
$saved = $email->save();
return is_wp_error($saved) ? $saved : $email;
} // end create_system_email;
}
/**
* Register all default system emails.
@ -351,12 +371,9 @@ class Email_Manager extends Base_Manager {
$system_emails = wu_get_default_system_emails();
foreach ($system_emails as $email_key => $email_value) {
$this->create_system_email($email_value);
} // end foreach;
} // end create_all_system_emails;
}
}
/**
* Register all default system emails.
@ -369,83 +386,96 @@ class Email_Manager extends Base_Manager {
/*
* Payment Successful - Admin
*/
$this->register_default_system_email(array(
'event' => 'payment_received',
'slug' => 'payment_received_admin',
'target' => 'admin',
'title' => __('You got a new payment!', 'wp-ultimo'),
'content' => wu_get_template_contents('emails/admin/payment-received'),
));
$this->register_default_system_email(
array(
'event' => 'payment_received',
'slug' => 'payment_received_admin',
'target' => 'admin',
'title' => __('You got a new payment!', 'wp-ultimo'),
'content' => wu_get_template_contents('emails/admin/payment-received'),
)
);
/*
* Payment Successful - Customer
*/
$this->register_default_system_email(array(
'event' => 'payment_received',
'slug' => 'payment_received_customer',
'target' => 'customer',
'title' => __('We got your payment!', 'wp-ultimo'),
'content' => wu_get_template_contents('emails/customer/payment-received'),
));
$this->register_default_system_email(
array(
'event' => 'payment_received',
'slug' => 'payment_received_customer',
'target' => 'customer',
'title' => __('We got your payment!', 'wp-ultimo'),
'content' => wu_get_template_contents('emails/customer/payment-received'),
)
);
/*
* Site Published - Admin
*/
$this->register_default_system_email(array(
'event' => 'site_published',
'target' => 'admin',
'slug' => 'site_published_admin',
'title' => __('A new site was created on your Network!', 'wp-ultimo'),
'content' => wu_get_template_contents('emails/admin/site-published'),
));
$this->register_default_system_email(
array(
'event' => 'site_published',
'target' => 'admin',
'slug' => 'site_published_admin',
'title' => __('A new site was created on your Network!', 'wp-ultimo'),
'content' => wu_get_template_contents('emails/admin/site-published'),
)
);
/*
* Site Published - Customer
*/
$this->register_default_system_email(array(
'event' => 'site_published',
'target' => 'customer',
'slug' => 'site_published_customer',
'title' => __('Your site is ready!', 'wp-ultimo'),
'content' => wu_get_template_contents('emails/customer/site-published'),
));
$this->register_default_system_email(
array(
'event' => 'site_published',
'target' => 'customer',
'slug' => 'site_published_customer',
'title' => __('Your site is ready!', 'wp-ultimo'),
'content' => wu_get_template_contents('emails/customer/site-published'),
)
);
/*
* Site Published - Customer
*/
$this->register_default_system_email(array(
'event' => 'confirm_email_address',
'target' => 'customer',
'slug' => 'confirm_email_address',
'title' => __('Confirm your email address!', 'wp-ultimo'),
'content' => wu_get_template_contents('emails/customer/confirm-email-address'),
));
$this->register_default_system_email(
array(
'event' => 'confirm_email_address',
'target' => 'customer',
'slug' => 'confirm_email_address',
'title' => __('Confirm your email address!', 'wp-ultimo'),
'content' => wu_get_template_contents('emails/customer/confirm-email-address'),
)
);
/*
* Domain Created - Admin
*/
$this->register_default_system_email(array(
'event' => 'domain_created',
'target' => 'admin',
'slug' => 'domain_created_admin',
'title' => __('A new domain was added to your Network!', 'wp-ultimo'),
'content' => wu_get_template_contents('emails/admin/domain-created'),
));
$this->register_default_system_email(
array(
'event' => 'domain_created',
'target' => 'admin',
'slug' => 'domain_created_admin',
'title' => __('A new domain was added to your Network!', 'wp-ultimo'),
'content' => wu_get_template_contents('emails/admin/domain-created'),
)
);
/*
* Pending Renewal Payment Created - Customer
*/
$this->register_default_system_email(array(
'event' => 'renewal_payment_created',
'target' => 'customer',
'slug' => 'renewal_payment_created',
'title' => __('You have a new pending payment!', 'wp-ultimo'),
'content' => wu_get_template_contents('emails/customer/renewal-payment-created'),
));
$this->register_default_system_email(
array(
'event' => 'renewal_payment_created',
'target' => 'customer',
'slug' => 'renewal_payment_created',
'title' => __('You have a new pending payment!', 'wp-ultimo'),
'content' => wu_get_template_contents('emails/customer/renewal-payment-created'),
)
);
do_action('wu_system_emails_after_register');
} // end register_all_default_system_emails;
}
/**
* Get a single or all default registered system emails.
@ -457,15 +487,12 @@ class Email_Manager extends Base_Manager {
*/
public function get_default_system_emails($slug = '') {
if ($slug && isset($this->registered_default_system_emails[$slug])) {
return $this->registered_default_system_emails[$slug];
} // end if;
if ($slug && isset($this->registered_default_system_emails[ $slug ])) {
return $this->registered_default_system_emails[ $slug ];
}
return $this->registered_default_system_emails;
} // end get_default_system_emails;
}
/**
* Check if the system email already exists.
@ -476,8 +503,7 @@ class Email_Manager extends Base_Manager {
public function is_created($slug): bool {
return (bool) wu_get_email_by('slug', $slug);
} // end is_created;
}
/**
* Get the default template email.
@ -492,43 +518,30 @@ class Email_Manager extends Base_Manager {
$placeholders = array();
if (wu_request('email_event')) {
$slug = wu_request('email_event');
} // end if;
}
if ($slug) {
$event = wu_get_event_type($slug);
if ($event) {
foreach (wu_maybe_lazy_load_payload($event['payload']) as $placeholder => $value) {
$name = ucwords(str_replace('_', ' ', $placeholder));
$placeholders[] = array(
'name' => $name,
'placeholder' => $placeholder
'placeholder' => $placeholder,
);
} // end foreach;
} // end if;
} // end if;
}
}
}
if (wu_request('email_event')) {
wp_send_json($placeholders);
} else {
return $placeholders;
} // end if;
} // end get_event_placeholders;
}
}
/**
* Sends a schedule email.
@ -545,8 +558,7 @@ class Email_Manager extends Base_Manager {
public function send_schedule_system_email($to, $subject, $template, $headers, $attachments) {
return Sender::send_mail($to, $subject, $template, $headers, $attachments);
} // end send_schedule_system_email;
}
/**
* Log failures on the WordPress mailer, just so we have a copy of the issues for debugging.
@ -559,11 +571,7 @@ class Email_Manager extends Base_Manager {
public function log_mailer_failure($error) {
if (is_wp_error($error)) {
wu_log_add('mailer-errors', $error->get_error_message(), LogLevel::ERROR);
} // end if;
} // end log_mailer_failure;
} // end class Email_Manager;
}
}
}

View File

@ -11,9 +11,9 @@
namespace WP_Ultimo\Managers;
use \WP_Ultimo\Managers\Base_Manager;
use WP_Ultimo\Managers\Base_Manager;
use WP_Ultimo\Models\Base_Model;
use \WP_Ultimo\Models\Event;
use WP_Ultimo\Models\Event;
// Exit if accessed directly
defined('ABSPATH') || exit;
@ -25,7 +25,9 @@ defined('ABSPATH') || exit;
*/
class Event_Manager extends Base_Manager {
use \WP_Ultimo\Apis\Rest_Api, \WP_Ultimo\Apis\WP_CLI, \WP_Ultimo\Traits\Singleton;
use \WP_Ultimo\Apis\Rest_Api;
use \WP_Ultimo\Apis\WP_CLI;
use \WP_Ultimo\Traits\Singleton;
/**
* The manager slug.
@ -80,8 +82,7 @@ class Event_Manager extends Base_Manager {
add_action('wu_model_post_save', array($this, 'log_transitions'), 10, 4);
add_action('wu_daily', array($this, 'clean_old_events'));
} // end init;
}
/**
* Returns the payload to be displayed in the payload preview field.
@ -98,45 +99,41 @@ class Event_Manager extends Base_Manager {
public function log_transitions($model, $data, $data_unserialized, $object) {
if ($model === 'event') {
return;
} // end if;
}
/*
* Editing Model
*/
if (wu_get_isset($data_unserialized, 'id')) {
$original = $object->_get_original();
$diff = wu_array_recursive_diff($data_unserialized, $original);
$keys_to_remove = apply_filters('wu_exclude_transitions_keys', array(
'meta',
'last_login',
'ips',
'query_class',
'settings',
'_compiled_product_list',
'_gateway_info',
'_limitations',
));
$keys_to_remove = apply_filters(
'wu_exclude_transitions_keys',
array(
'meta',
'last_login',
'ips',
'query_class',
'settings',
'_compiled_product_list',
'_gateway_info',
'_limitations',
)
);
foreach ($keys_to_remove as $key_to_remove) {
unset($diff[$key_to_remove]);
} // end foreach;
unset($diff[ $key_to_remove ]);
}
/**
* If empty, go home.
*/
if (empty($diff)) {
return;
} // end if;
}
$changed = array();
@ -144,27 +141,21 @@ class Event_Manager extends Base_Manager {
* Loop changed data.
*/
foreach ($diff as $key => $new_value) {
$old_value = wu_get_isset($original, $key, '');
if ($key === 'id' && intval($old_value) === 0) {
return;
} // end if;
}
if (empty(json_encode($old_value)) && empty(json_encode($new_value))) {
return;
}
} // end if;
$changed[$key] = array(
$changed[ $key ] = array(
'old_value' => $old_value,
'new_value' => $new_value,
);
} // end foreach;
}
$event_data = array(
'severity' => Event::SEVERITY_INFO,
@ -173,9 +164,7 @@ class Event_Manager extends Base_Manager {
'object_id' => $object->get_id(),
'payload' => $changed,
);
} else {
$event_data = array(
'severity' => Event::SEVERITY_INFO,
'slug' => 'created',
@ -183,19 +172,15 @@ class Event_Manager extends Base_Manager {
'object_id' => $object->get_id(),
'payload' => array(),
);
}
} // end if;
if (!empty($_POST) && is_user_logged_in()) {
if ( ! empty($_POST) && is_user_logged_in()) {
$event_data['initiator'] = 'manual';
$event_data['author_id'] = get_current_user_id();
} // end if;
}
return wu_create_event($event_data);
} // end log_transitions;
}
/**
* Returns the payload to be displayed in the payload preview field.
@ -205,37 +190,28 @@ class Event_Manager extends Base_Manager {
*/
public function event_payload_preview() {
if (!wu_request('event')) {
if ( ! wu_request('event')) {
wp_send_json_error(new \WP_Error('error', __('No event was selected.', 'wp-ultimo')));
} // end if;
}
$slug = wu_request('event');
if (!$slug) {
if ( ! $slug) {
wp_send_json_error(new \WP_Error('not-found', __('Event was not found.', 'wp-ultimo')));
} // end if;
}
$event = wu_get_event_type($slug);
if (!$event) {
if ( ! $event) {
wp_send_json_error(new \WP_Error('not-found', __('Data not found.', 'wp-ultimo')));
} else {
$payload = isset($event['payload']) ? wu_maybe_lazy_load_payload($event['payload']) : '{}';
$payload = array_map('htmlentities2', $payload);
wp_send_json_success($payload);
} // end if;
} // end event_payload_preview;
}
}
/**
* Returns the list of event types to register.
@ -263,8 +239,7 @@ class Event_Manager extends Base_Manager {
$types = array_filter($types, fn($item) => $item['hidden'] === false);
return $types;
} // end get_event_type_as_options;
}
/**
* Add a new event.
@ -280,23 +255,17 @@ class Event_Manager extends Base_Manager {
$registered_event = $this->get_event($slug);
if (!$registered_event) {
if ( ! $registered_event) {
return array('error' => 'Event not found');
} // end if;
}
$payload_diff = array_diff_key(wu_maybe_lazy_load_payload($registered_event['payload']), $payload);
if (isset($payload_diff[0])) {
foreach ($payload_diff[0] as $diff_key => $diff_value) {
return array('error' => 'Param required:' . $diff_key);
} // end foreach;
} // end if;
}
}
$payload['wu_version'] = wu_get_version();
@ -308,8 +277,7 @@ class Event_Manager extends Base_Manager {
* Saves in the database
*/
$this->save_event($slug, $payload);
} // end do_event;
}
/**
* Register a new event to be used as param.
@ -323,11 +291,10 @@ class Event_Manager extends Base_Manager {
*/
public function register_event($slug, $args): bool {
$this->events[$slug] = $args;
$this->events[ $slug ] = $args;
return true;
} // end register_event;
}
/**
* Returns the list of available webhook events.
@ -338,8 +305,7 @@ class Event_Manager extends Base_Manager {
public function get_events() {
return $this->events;
} // end get_events;
}
/**
* Returns the list of available webhook events.
@ -354,22 +320,15 @@ class Event_Manager extends Base_Manager {
$events = $this->get_events();
if ($events) {
foreach ($events as $key => $event) {
if ($key === $slug) {
return $event;
} // end if;
} // end foreach;
} // end if;
}
}
}
return false;
} // end get_event;
}
/**
* Saves event in the database.
@ -380,18 +339,19 @@ class Event_Manager extends Base_Manager {
*/
public function save_event($slug, $payload) {
$event = new Event(array(
'object_id' => wu_get_isset($payload, 'object_id', ''),
'object_type' => wu_get_isset($payload, 'object_type', ''),
'severity' => wu_get_isset($payload, 'type', Event::SEVERITY_INFO),
'date_created' => wu_get_current_time('mysql', true),
'slug' => strtolower($slug),
'payload' => $payload,
));
$event = new Event(
array(
'object_id' => wu_get_isset($payload, 'object_id', ''),
'object_type' => wu_get_isset($payload, 'object_type', ''),
'severity' => wu_get_isset($payload, 'type', Event::SEVERITY_INFO),
'date_created' => wu_get_current_time('mysql', true),
'slug' => strtolower($slug),
'payload' => $payload,
)
);
$event->save();
} // end save_event;
}
/**
* Registers the list of default events.
@ -404,80 +364,94 @@ class Event_Manager extends Base_Manager {
/**
* Payment Received.
*/
wu_register_event_type('payment_received', array(
'name' => __('Payment Received', 'wp-ultimo'),
'desc' => __('This event is fired every time a new payment is received, regardless of the payment status.', 'wp-ultimo'),
'payload' => fn() => array_merge(
wu_register_event_type(
'payment_received',
array(
'name' => __('Payment Received', 'wp-ultimo'),
'desc' => __('This event is fired every time a new payment is received, regardless of the payment status.', 'wp-ultimo'),
'payload' => fn() => array_merge(
wu_generate_event_payload('payment'),
wu_generate_event_payload('membership'),
wu_generate_event_payload('customer')
),
'deprecated_args' => array(
'user_id' => 'customer_user_id',
'amount' => 'payment_total',
'gateway' => 'payment_gateway',
'status' => 'payment_status',
'date' => 'payment_date_created',
),
));
'deprecated_args' => array(
'user_id' => 'customer_user_id',
'amount' => 'payment_total',
'gateway' => 'payment_gateway',
'status' => 'payment_status',
'date' => 'payment_date_created',
),
)
);
/**
* Site Published.
*/
wu_register_event_type('site_published', array(
'name' => __('Site Published', 'wp-ultimo'),
'desc' => __('This event is fired every time a new site is created tied to a membership, or transitions from a pending state to a published state.', 'wp-ultimo'),
'payload' => fn() => array_merge(
wu_register_event_type(
'site_published',
array(
'name' => __('Site Published', 'wp-ultimo'),
'desc' => __('This event is fired every time a new site is created tied to a membership, or transitions from a pending state to a published state.', 'wp-ultimo'),
'payload' => fn() => array_merge(
wu_generate_event_payload('site'),
wu_generate_event_payload('customer'),
wu_generate_event_payload('membership')
),
'deprecated_args' => array(),
));
'deprecated_args' => array(),
)
);
/**
* Confirm Email Address
*/
wu_register_event_type('confirm_email_address', array(
'name' => __('Email Verification Needed', 'wp-ultimo'),
'desc' => __('This event is fired every time a new customer is added with an email verification status of pending.', 'wp-ultimo'),
'payload' => fn() => array_merge(
wu_register_event_type(
'confirm_email_address',
array(
'name' => __('Email Verification Needed', 'wp-ultimo'),
'desc' => __('This event is fired every time a new customer is added with an email verification status of pending.', 'wp-ultimo'),
'payload' => fn() => array_merge(
array(
'verification_link' => 'https://linktoverifyemail.com',
),
wu_generate_event_payload('customer')
),
'deprecated_args' => array(),
));
'deprecated_args' => array(),
)
);
/**
* Domain Mapping Added
*/
wu_register_event_type('domain_created', array(
'name' => __('New Domain Mapping Added', 'wp-ultimo'),
'desc' => __('This event is fired every time a new domain mapping is added by a customer.', 'wp-ultimo'),
'payload' => fn() => array_merge(
wu_register_event_type(
'domain_created',
array(
'name' => __('New Domain Mapping Added', 'wp-ultimo'),
'desc' => __('This event is fired every time a new domain mapping is added by a customer.', 'wp-ultimo'),
'payload' => fn() => array_merge(
wu_generate_event_payload('domain'),
wu_generate_event_payload('site'),
wu_generate_event_payload('membership'),
wu_generate_event_payload('customer')
),
'deprecated_args' => array(
'user_id' => 1,
'user_site_id' => 1,
'mapped_domain' => 'mydomain.com',
'user_site_url' => 'http://test.mynetwork.com/',
'network_ip' => '125.399.3.23',
),
));
'deprecated_args' => array(
'user_id' => 1,
'user_site_id' => 1,
'mapped_domain' => 'mydomain.com',
'user_site_url' => 'http://test.mynetwork.com/',
'network_ip' => '125.399.3.23',
),
)
);
/**
* Renewal payment created
*/
wu_register_event_type('renewal_payment_created', array(
'name' => __('New Renewal Payment Created', 'wp-ultimo'),
'desc' => __('This event is fired every time a new renewal payment is created by WP Multisite WaaS.', 'wp-ultimo'),
'payload' => fn() => array_merge(
wu_register_event_type(
'renewal_payment_created',
array(
'name' => __('New Renewal Payment Created', 'wp-ultimo'),
'desc' => __('This event is fired every time a new renewal payment is created by WP Multisite WaaS.', 'wp-ultimo'),
'payload' => fn() => array_merge(
array(
'default_payment_url' => 'https://linktopayment.com',
),
@ -485,31 +459,30 @@ class Event_Manager extends Base_Manager {
wu_generate_event_payload('membership'),
wu_generate_event_payload('customer')
),
'deprecated_args' => array(),
));
'deprecated_args' => array(),
)
);
$models = $this->models_events;
foreach ($models as $model => $params) {
foreach ($params['types'] as $type) {
wu_register_event_type($model . '_' . $type, array(
'name' => sprintf(__('%1$s %2$s', 'wp-ultimo'), $params['label'], ucfirst($type)),
'desc' => sprintf(__('This event is fired every time a %1$s is %2$s by WP Multisite WaaS.', 'wp-ultimo'), $params['label'], $type),
'deprecated_args' => array(),
'payload' => fn() => $this->get_model_payload($model),
));
} // end foreach;
wu_register_event_type(
$model . '_' . $type,
array(
'name' => sprintf(__('%1$s %2$s', 'wp-ultimo'), $params['label'], ucfirst($type)),
'desc' => sprintf(__('This event is fired every time a %1$s is %2$s by WP Multisite WaaS.', 'wp-ultimo'), $params['label'], $type),
'deprecated_args' => array(),
'payload' => fn() => $this->get_model_payload($model),
)
);
}
add_action("wu_{$model}_post_save", array($this, 'dispatch_base_model_event'), 10, 3);
} // end foreach;
}
do_action('wu_register_all_events');
} // end register_all_events;
}
/**
* Register models events
@ -523,12 +496,11 @@ class Event_Manager extends Base_Manager {
$instance = self::get_instance();
$instance->models_events[$slug] = array(
$instance->models_events[ $slug ] = array(
'label' => $label,
'types' => $event_types,
);
} // end register_model_events;
}
/**
* Dispatch registered model events
@ -547,17 +519,14 @@ class Event_Manager extends Base_Manager {
$registered_model = wu_get_isset($this->models_events, $model);
if (!$registered_model || !in_array($type, $registered_model['types'], true)) {
if ( ! $registered_model || ! in_array($type, $registered_model['types'], true)) {
return;
} // end if;
}
$payload = $this->get_model_payload($model, $obj);
wu_do_event($model . '_' . $type, $payload);
} // end dispatch_base_model_event;
}
/**
* Returns the full payload for a given model.
@ -574,31 +543,25 @@ class Event_Manager extends Base_Manager {
$payload = wu_generate_event_payload($model, $obj);
if (method_exists($obj, 'get_membership')) {
$membership = $model_object ? $obj->get_membership() : false;
$payload = array_merge(
$payload,
wu_generate_event_payload('membership', $membership)
);
} // end if;
}
if (method_exists($obj, 'get_customer')) {
$customer = $model_object ? $obj->get_customer() : false;
$payload = array_merge(
$payload,
wu_generate_event_payload('customer', $customer)
);
} // end if;
}
if (method_exists($obj, 'get_billing_address') || method_exists($obj, 'get_membership')) {
if ($model_object) {
$payload = method_exists($obj, 'get_billing_address')
? array_merge(
$payload,
@ -607,23 +570,21 @@ class Event_Manager extends Base_Manager {
$payload,
$obj->get_membership()->get_billing_address()->to_array()
);
} else {
$payload = array_merge(
$payload,
array_map(function () {
return '';
}, \WP_Ultimo\Objects\Billing_Address::fields())
array_map(
function () {
return '';
},
\WP_Ultimo\Objects\Billing_Address::fields()
)
);
} // end if;
} // end if;
}
}
return $payload;
} // end get_model_payload;
}
/**
* Every day, deletes old events that we don't want to keep.
@ -638,39 +599,34 @@ class Event_Manager extends Base_Manager {
$threshold_days = apply_filters('wu_events_threshold_days', 1);
if (empty($threshold_days)) {
return false;
}
} // end if;
$events_to_remove = wu_get_events(array(
'number' => 100,
'date_query' => array(
'column' => 'date_created',
'before' => "-{$threshold_days} days",
'inclusive' => true,
),
));
$events_to_remove = wu_get_events(
array(
'number' => 100,
'date_query' => array(
'column' => 'date_created',
'before' => "-{$threshold_days} days",
'inclusive' => true,
),
)
);
$success_count = 0;
foreach ($events_to_remove as $event) {
$status = $event->delete();
if (!is_wp_error($status) && $status) {
$success_count++;
} // end if;
} // end foreach;
if ( ! is_wp_error($status) && $status) {
++$success_count;
}
}
wu_log_add('wu-cron', sprintf(__('Removed %1$d events successfully. Failed to remove %2$d events.', 'wp-ultimo'), $success_count, count($events_to_remove) - $success_count));
return true;
} // end clean_old_events;
}
/**
* Create a endpoint to retrieve all available event hooks.
@ -681,21 +637,22 @@ class Event_Manager extends Base_Manager {
*/
public function hooks_endpoint() {
if (!wu_get_setting('enable_api', true)) {
if ( ! wu_get_setting('enable_api', true)) {
return;
} // end if;
}
$api = \WP_Ultimo\API::get_instance();
register_rest_route($api->get_namespace(), '/hooks', array(
'methods' => 'GET',
'callback' => array($this, 'get_hooks_rest'),
'permission_callback' => array($api, 'check_authorization'),
));
} // end hooks_endpoint;
register_rest_route(
$api->get_namespace(),
'/hooks',
array(
'methods' => 'GET',
'callback' => array($this, 'get_hooks_rest'),
'permission_callback' => array($api, 'check_authorization'),
)
);
}
/**
* Return all event types for the REST API request.
@ -710,19 +667,13 @@ class Event_Manager extends Base_Manager {
$response = wu_get_event_types();
foreach ($response as $key => $value) {
$payload = wu_get_isset($value, 'payload');
if (is_callable($payload)) {
$response[$key]['payload'] = $payload();
} // end if;
} // end foreach;
$response[ $key ]['payload'] = $payload();
}
}
return rest_ensure_response($response);
} // end get_hooks_rest;
} // end class Event_Manager;
}
}

View File

@ -11,7 +11,7 @@
namespace WP_Ultimo\Managers;
use \WP_Ultimo\Managers\Base_Manager;
use WP_Ultimo\Managers\Base_Manager;
// Exit if accessed directly
defined('ABSPATH') || exit;
@ -44,8 +44,7 @@ class Field_Templates_Manager extends Base_Manager {
add_action('wu_ajax_nopriv_wu_render_field_template', array($this, 'serve_field_template'));
add_action('wu_ajax_wu_render_field_template', array($this, 'serve_field_template'));
} // end init;
}
/**
* Serve the HTML markup for the templates.
@ -61,21 +60,20 @@ class Field_Templates_Manager extends Base_Manager {
$template_class = $this->get_template_class($template_parts[0], $template_parts[1]);
if (!$template_class) {
if ( ! $template_class) {
wp_send_json_error(new \WP_Error('template', __('Template not found.', 'wp-ultimo')));
} // end if;
}
$key = $template_parts[0];
$attributes = apply_filters("wu_{$key}_render_attributes", wu_request('attributes'));
wp_send_json_success(array(
'html' => $template_class->render($attributes),
));
} // end serve_field_template;
wp_send_json_success(
array(
'html' => $template_class->render($attributes),
)
);
}
/**
* Returns the list of registered signup field types.
@ -157,8 +155,7 @@ class Field_Templates_Manager extends Base_Manager {
* @return array
*/
return apply_filters('wu_checkout_field_templates', $field_templates);
} // end get_field_templates;
}
/**
* Get the field templates for a field type. Returns only the class names.
@ -171,8 +168,7 @@ class Field_Templates_Manager extends Base_Manager {
public function get_templates($field_type) {
return wu_get_isset($this->get_field_templates(), $field_type, array());
} // end get_templates;
}
/**
* Get the instance of the template class.
@ -188,8 +184,7 @@ class Field_Templates_Manager extends Base_Manager {
$templates = $this->get_instantiated_field_types($field_type);
return wu_get_isset($templates, $field_template_id);
} // end get_template_class;
}
/**
* Returns the field templates as a key => title array of options.
@ -206,14 +201,11 @@ class Field_Templates_Manager extends Base_Manager {
$options = array();
foreach ($templates as $template_id => $template) {
$options[$template_id] = $template->get_title();
} // end foreach;
$options[ $template_id ] = $template->get_title();
}
return $options;
} // end get_templates_as_options;
}
/**
* Returns the field templates as a key => info_array array of fields.
@ -230,19 +222,16 @@ class Field_Templates_Manager extends Base_Manager {
$options = array();
foreach ($templates as $template_id => $template) {
$options[$template_id] = array(
$options[ $template_id ] = array(
'id' => $template_id,
'title' => $template->get_title(),
'description' => $template->get_description(),
'preview' => $template->get_preview(),
);
} // end foreach;
}
return $options;
} // end get_templates_info;
}
/**
* Instantiate a field template.
@ -255,8 +244,7 @@ class Field_Templates_Manager extends Base_Manager {
public function instantiate_field_template($class_name) {
return new $class_name();
} // end instantiate_field_template;
}
/**
* Returns an array with all fields, instantiated.
@ -269,15 +257,12 @@ class Field_Templates_Manager extends Base_Manager {
$holder_name = "instantiated_{$field_type}_templates";
if (!isset($this->holders[$holder_name]) || $this->holders[$holder_name] === null) {
if ( ! isset($this->holders[ $holder_name ]) || $this->holders[ $holder_name ] === null) {
$this->holders[ $holder_name ] = array_map(array($this, 'instantiate_field_template'), $this->get_templates($field_type));
}
$this->holders[$holder_name] = array_map(array($this, 'instantiate_field_template'), $this->get_templates($field_type));
} // end if;
return $this->holders[$holder_name];
} // end get_instantiated_field_types;
return $this->holders[ $holder_name ];
}
/**
* Render preview block.
@ -291,22 +276,24 @@ class Field_Templates_Manager extends Base_Manager {
$preview_block = '<div class="wu-w-full">';
foreach (Field_Templates_Manager::get_instance()->get_templates_info($field_type) as $template_slug => $template_info) {
foreach (self::get_instance()->get_templates_info($field_type) as $template_slug => $template_info) {
$image_tag = $template_info['preview'] ? sprintf('<img class="wu-object-cover wu-image-preview wu-w-7 wu-h-7 wu-rounded wu-mr-3" src="%1$s" data-image="%1$s">', $template_info['preview']) : '<div class="wu-w-7 wu-h-7 wu-bg-gray-200 wu-rounded wu-text-gray-600 wu-flex wu-items-center wu-justify-center wu-mr-2">
<span class="dashicons-wu-image"></span>
</div>';
$preview_block .= sprintf("<div v-show='%4\$s_template === \"%1\$s\"' class='wu-w-full wu-flex wu-items-center'>
$preview_block .= sprintf(
"<div v-show='%4\$s_template === \"%1\$s\"' class='wu-w-full wu-flex wu-items-center'>
<div class='wu-flex wu-items-center'>%2\$s</div><div class='wu-flex-wrap wu-overflow-hidden'>%3\$s</div>
</div>", $template_info['id'], $image_tag, $template_info['description'], $field_type);
} // end foreach;
</div>",
$template_info['id'],
$image_tag,
$template_info['description'],
$field_type
);
}
$preview_block .= '</div>';
return $preview_block;
} // end render_preview_block;
} // end class Field_Templates_Manager;
}
}

View File

@ -50,8 +50,7 @@ class Form_Manager extends Base_Manager {
add_action('wu_page_load', 'add_wubox');
do_action('wu_register_forms');
} // end init;
}
/**
* Displays the form unavailable message.
@ -68,25 +67,25 @@ class Form_Manager extends Base_Manager {
$message = __('Form not available', 'wp-ultimo');
if (is_wp_error($error)) {
$message = $error->get_error_message();
}
} // end if;
echo sprintf('
printf(
'
<div class="wu-modal-form wu-h-full wu-flex wu-items-center wu-justify-center wu-bg-gray-200 wu-m-0 wu-mt-0 wu--mb-3">
<div>
<span class="dashicons dashicons-warning wu-h-8 wu-w-8 wu-mx-auto wu-text-center wu-text-4xl wu-block"></span>
<span class="wu-block wu-text-sm">%s</span>
</div>
</div>
', $message);
',
$message
);
do_action('wu_form_scripts', false);
die;
} // end display_form_unavailable;
}
/**
* Renders a registered form, when requested.
@ -100,18 +99,27 @@ class Form_Manager extends Base_Manager {
$form = $this->get_form(wu_request('form'));
echo sprintf("<form class='wu_form wu-styling' id='%s' action='%s' method='post'>",
$form['id'],
$this->get_form_url($form['id'], array(
'action' => 'wu_form_handler',
)));
printf(
"<form class='wu_form wu-styling' id='%s' action='%s' method='post'>",
$form['id'],
$this->get_form_url(
$form['id'],
array(
'action' => 'wu_form_handler',
)
)
);
echo sprintf('
printf(
'
<div v-cloak data-wu-app="%s" data-state="%s">
<ul class="wu-p-4 wu-bg-red-200 wu-m-0 wu-list-none" v-if="errors.length">
<li class="wu-m-0 wu-p-0" v-for="error in errors">{{ error.message }}</li>
</ul>
</div>', $form['id'] . '_errors', htmlspecialchars(json_encode(array('errors' => array()))));
</div>',
$form['id'] . '_errors',
htmlspecialchars(json_encode(array('errors' => array())))
);
call_user_func($form['render']);
@ -124,8 +132,7 @@ class Form_Manager extends Base_Manager {
do_action('wu_form_scripts', $form);
exit;
} // end display_form;
}
/**
* Handles the submission of a registered form.
@ -139,11 +146,9 @@ class Form_Manager extends Base_Manager {
$form = $this->get_form(wu_request('form'));
if (!wp_verify_nonce(wu_request('_wpnonce'), 'wu_form_' . $form['id'])) {
if ( ! wp_verify_nonce(wu_request('_wpnonce'), 'wu_form_' . $form['id'])) {
wp_send_json_error();
} // end if;
}
/**
* The handler is supposed to send a wp_json message back.
@ -153,14 +158,11 @@ class Form_Manager extends Base_Manager {
$check = call_user_func($form['handler']);
if (is_wp_error($check)) {
$this->display_form_unavailable($check);
} // end if;
}
exit;
} // end handle_form;
}
/**
* Checks that the form exists and that the user has permission to see it.
@ -173,26 +175,19 @@ class Form_Manager extends Base_Manager {
* We only want ajax requests.
*/
if ((empty($_SERVER['HTTP_X_REQUESTED_WITH']) || strtolower((string) $_SERVER['HTTP_X_REQUESTED_WITH']) !== 'xmlhttprequest')) {
wp_die(0);
} // end if;
}
$form = $this->get_form(wu_request('form'));
if (!$form) {
if ( ! $form) {
return $this->display_form_unavailable();
}
} // end if;
if (!current_user_can($form['capability'])) {
if ( ! current_user_can($form['capability'])) {
return $this->display_form_unavailable();
} // end if;
} // end security_checks;
}
}
/**
* Returns a list of all the registered gateways.
@ -203,8 +198,7 @@ class Form_Manager extends Base_Manager {
public function get_registered_forms() {
return $this->registered_forms;
} // end get_registered_forms;
}
/**
* Checks if a form is already registered.
@ -216,9 +210,8 @@ class Form_Manager extends Base_Manager {
*/
public function is_form_registered($id) {
return is_array($this->registered_forms) && isset($this->registered_forms[$id]);
} // end is_form_registered;
return is_array($this->registered_forms) && isset($this->registered_forms[ $id ]);
}
/**
* Returns a registered form.
@ -230,9 +223,8 @@ class Form_Manager extends Base_Manager {
*/
public function get_form($id) {
return $this->is_form_registered($id) ? $this->registered_forms[$id] : false;
} // end get_form;
return $this->is_form_registered($id) ? $this->registered_forms[ $id ] : false;
}
/**
* Registers a new Ajax Form.
@ -249,26 +241,26 @@ class Form_Manager extends Base_Manager {
*/
public function register_form($id, $atts = array()) {
$atts = wp_parse_args($atts, array(
'id' => $id,
'form' => '',
'capability' => 'manage_network',
'handler' => '__return_false',
'render' => '__return_empty_string',
));
$atts = wp_parse_args(
$atts,
array(
'id' => $id,
'form' => '',
'capability' => 'manage_network',
'handler' => '__return_false',
'render' => '__return_empty_string',
)
);
// Checks if gateway was already added
if ($this->is_form_registered($id)) {
return;
}
} // end if;
$this->registered_forms[$id] = $atts;
$this->registered_forms[ $id ] = $atts;
return true;
} // end register_form;
}
/**
* Returns the ajax URL for a given form.
@ -281,16 +273,18 @@ class Form_Manager extends Base_Manager {
*/
public function get_form_url($form_id, $atts = array()) {
$atts = wp_parse_args($atts, array(
'form' => $form_id,
'action' => 'wu_form_display',
'width' => '400',
'height' => '360',
));
$atts = wp_parse_args(
$atts,
array(
'form' => $form_id,
'action' => 'wu_form_display',
'width' => '400',
'height' => '360',
)
);
return add_query_arg($atts, wu_ajax_url('init'));
} // end get_form_url;
}
/**
* Register the confirmation modal form to delete a customer.
@ -301,20 +295,25 @@ class Form_Manager extends Base_Manager {
$model = wu_request('model');
wu_register_form('delete_modal', array(
'render' => array($this, 'render_model_delete_form'),
'handler' => array($this, 'handle_model_delete_form'),
'capability' => "wu_delete_{$model}s",
));
wu_register_form(
'delete_modal',
array(
'render' => array($this, 'render_model_delete_form'),
'handler' => array($this, 'handle_model_delete_form'),
'capability' => "wu_delete_{$model}s",
)
);
wu_register_form('bulk_actions', array(
'render' => array($this, 'render_bulk_action_form'),
'handler' => array($this, 'handle_bulk_action_form'),
));
wu_register_form(
'bulk_actions',
array(
'render' => array($this, 'render_bulk_action_form'),
'handler' => array($this, 'handle_bulk_action_form'),
)
);
add_action('wu_handle_bulk_action_form', array($this, 'default_bulk_action_handler'), 100, 3);
} // end register_action_forms;
}
/**
* Renders the deletion confirmation form.
@ -335,34 +334,27 @@ class Form_Manager extends Base_Manager {
* Handle metadata elements passed as model
*/
if (strpos((string) $model, '_meta_') !== false) {
$elements = explode('_meta_', (string) $model);
$model = $elements[0];
$meta_key = $elements[1];
} // end if;
}
try {
$object = call_user_func("wu_get_{$model}", $id);
} catch (\Throwable $exception) {
// No need to do anything, but cool to stop fatal errors.
} // end try;
}
$object = apply_filters("wu_delete_form_get_object_{$model}", $object, $id, $model);
if (!$object) {
if ( ! $object) {
$this->display_form_unavailable(new \WP_Error('not-found', __('Object not found.', 'wp-ultimo')));
return;
} // end if;
}
$fields = apply_filters(
"wu_form_fields_delete_{$model}_modal",
@ -406,28 +398,31 @@ class Form_Manager extends Base_Manager {
$object
);
$form_attributes = apply_filters("wu_form_attributes_delete_{$model}_modal", array(
'title' => 'Delete',
'views' => 'admin-pages/fields',
'classes' => 'wu-modal-form wu-widget-list wu-striped wu-m-0 wu-mt-0',
'field_wrapper_classes' => 'wu-w-full wu-box-border wu-items-center wu-flex wu-justify-between wu-p-4 wu-m-0 wu-border-t wu-border-l-0 wu-border-r-0 wu-border-b-0 wu-border-gray-300 wu-border-solid',
'html_attr' => array(
'data-wu-app' => 'true',
'data-state' => json_encode(array(
'confirmed' => false,
)),
),
));
$form_attributes = apply_filters(
"wu_form_attributes_delete_{$model}_modal",
array(
'title' => 'Delete',
'views' => 'admin-pages/fields',
'classes' => 'wu-modal-form wu-widget-list wu-striped wu-m-0 wu-mt-0',
'field_wrapper_classes' => 'wu-w-full wu-box-border wu-items-center wu-flex wu-justify-between wu-p-4 wu-m-0 wu-border-t wu-border-l-0 wu-border-r-0 wu-border-b-0 wu-border-gray-300 wu-border-solid',
'html_attr' => array(
'data-wu-app' => 'true',
'data-state' => json_encode(
array(
'confirmed' => false,
)
),
),
)
);
$form = new \WP_Ultimo\UI\Form('total-actions', $fields, $form_attributes);
do_action("wu_before_render_delete_{$model}_modal", $form);
$form->render();
} // end if;
} // end render_model_delete_form;
}
}
/**
* Handles the deletion of customer.
@ -454,7 +449,6 @@ class Form_Manager extends Base_Manager {
* Handle meta key deletion
*/
if ($meta_key) {
$status = delete_metadata('wu_membership', wu_request('id'), 'pending_site');
$data_json_success = array(
@ -464,26 +458,20 @@ class Form_Manager extends Base_Manager {
wp_send_json_success($data_json_success);
exit;
} // end if;
}
try {
$object = call_user_func("wu_get_{$model}", $id);
} catch (\Throwable $exception) {
// No need to do anything, but cool to stop fatal errors.
} // end try;
}
$object = apply_filters("wu_delete_form_get_object_{$model}", $object, $id, $model);
if (!$object) {
if ( ! $object) {
wp_send_json_error(new \WP_Error('not-found', __('Object not found.', 'wp-ultimo')));
} // end if;
}
/*
* Handle objects (default state)
@ -493,26 +481,23 @@ class Form_Manager extends Base_Manager {
$saved = $object->delete();
if (is_wp_error($saved)) {
wp_send_json_error($saved);
} // end if;
}
do_action("wu_after_delete_{$model}_modal", $object);
$data_json_success = apply_filters("wu_data_json_success_delete_{$model}_modal", array(
'redirect_url' => wu_network_admin_url("wp-ultimo-{$plural_name}", array('deleted' => 1))
));
$data_json_success = apply_filters(
"wu_data_json_success_delete_{$model}_modal",
array(
'redirect_url' => wu_network_admin_url("wp-ultimo-{$plural_name}", array('deleted' => 1)),
)
);
wp_send_json_success($data_json_success);
} else {
wp_send_json_error(new \WP_Error('model-not-found', __('Something went wrong.', 'wp-ultimo')));
} // end if;
} // end handle_model_delete_form;
}
}
/**
* Renders the deletion confirmation form.
@ -526,57 +511,64 @@ class Form_Manager extends Base_Manager {
$model = wu_request('model');
$fields = apply_filters("wu_bulk_actions_{$model}_{$action}", array(
'confirm' => array(
'type' => 'toggle',
'title' => __('Confirm Action', 'wp-ultimo'),
'desc' => __('Review this action carefully.', 'wp-ultimo'),
'html_attr' => array(
'v-model' => 'confirmed',
$fields = apply_filters(
"wu_bulk_actions_{$model}_{$action}",
array(
'confirm' => array(
'type' => 'toggle',
'title' => __('Confirm Action', 'wp-ultimo'),
'desc' => __('Review this action carefully.', 'wp-ultimo'),
'html_attr' => array(
'v-model' => 'confirmed',
),
),
),
'submit_button' => array(
'type' => 'submit',
'title' => wu_slug_to_name($action),
'placeholder' => wu_slug_to_name($action),
'value' => 'save',
'classes' => 'button button-primary wu-w-full',
'wrapper_classes' => 'wu-items-end',
'html_attr' => array(
'v-bind:disabled' => '!confirmed',
'submit_button' => array(
'type' => 'submit',
'title' => wu_slug_to_name($action),
'placeholder' => wu_slug_to_name($action),
'value' => 'save',
'classes' => 'button button-primary wu-w-full',
'wrapper_classes' => 'wu-items-end',
'html_attr' => array(
'v-bind:disabled' => '!confirmed',
),
),
),
'model' => array(
'type' => 'hidden',
'value' => $model,
),
'bulk_action' => array(
'type' => 'hidden',
'value' => wu_request('bulk_action'),
),
'ids' => array(
'type' => 'hidden',
'value' => implode(',', wu_request('bulk-delete', '')),
),
));
'model' => array(
'type' => 'hidden',
'value' => $model,
),
'bulk_action' => array(
'type' => 'hidden',
'value' => wu_request('bulk_action'),
),
'ids' => array(
'type' => 'hidden',
'value' => implode(',', wu_request('bulk-delete', '')),
),
)
);
$form_attributes = apply_filters("wu_bulk_actions_{$action}_form", array(
'views' => 'admin-pages/fields',
'classes' => 'wu-modal-form wu-widget-list wu-striped wu-m-0 wu-mt-0',
'field_wrapper_classes' => 'wu-w-full wu-box-border wu-items-center wu-flex wu-justify-between wu-p-4 wu-m-0 wu-border-t wu-border-l-0 wu-border-r-0 wu-border-b-0 wu-border-gray-300 wu-border-solid',
'html_attr' => array(
'data-wu-app' => 'true',
'data-state' => json_encode(array(
'confirmed' => false,
)),
),
));
$form_attributes = apply_filters(
"wu_bulk_actions_{$action}_form",
array(
'views' => 'admin-pages/fields',
'classes' => 'wu-modal-form wu-widget-list wu-striped wu-m-0 wu-mt-0',
'field_wrapper_classes' => 'wu-w-full wu-box-border wu-items-center wu-flex wu-justify-between wu-p-4 wu-m-0 wu-border-t wu-border-l-0 wu-border-r-0 wu-border-b-0 wu-border-gray-300 wu-border-solid',
'html_attr' => array(
'data-wu-app' => 'true',
'data-state' => json_encode(
array(
'confirmed' => false,
)
),
),
)
);
$form = new \WP_Ultimo\UI\Form('total-actions', $fields, $form_attributes);
$form->render();
} // end render_bulk_action_form;
}
/**
* Handles the deletion of customer.
@ -597,8 +589,7 @@ class Form_Manager extends Base_Manager {
do_action("wu_handle_bulk_action_form_{$model}_{$action}", $action, $model, $ids);
do_action('wu_handle_bulk_action_form', $action, $model, $ids);
} // end handle_bulk_action_form;
}
/**
* Default handler for bulk actions.
@ -615,15 +606,13 @@ class Form_Manager extends Base_Manager {
$status = \WP_Ultimo\List_Tables\Base_List_Table::process_bulk_action();
if (is_wp_error($status)) {
wp_send_json_error($status);
}
} // end if;
wp_send_json_success(array(
'redirect_url' => add_query_arg($action, count($ids), wu_get_current_url()),
));
} // end default_bulk_action_handler;
} // end class Form_Manager;
wp_send_json_success(
array(
'redirect_url' => add_query_arg($action, count($ids), wu_get_current_url()),
)
);
}
}

View File

@ -12,14 +12,14 @@
namespace WP_Ultimo\Managers;
use Psr\Log\LogLevel;
use \WP_Ultimo\Managers\Base_Manager;
use \WP_Ultimo\Gateways\Ignorable_Exception;
use WP_Ultimo\Managers\Base_Manager;
use WP_Ultimo\Gateways\Ignorable_Exception;
use \WP_Ultimo\Gateways\Free_Gateway;
use \WP_Ultimo\Gateways\Stripe_Gateway;
use \WP_Ultimo\Gateways\Stripe_Checkout_Gateway;
use \WP_Ultimo\Gateways\PayPal_Gateway;
use \WP_Ultimo\Gateways\Manual_Gateway;
use WP_Ultimo\Gateways\Free_Gateway;
use WP_Ultimo\Gateways\Stripe_Gateway;
use WP_Ultimo\Gateways\Stripe_Checkout_Gateway;
use WP_Ultimo\Gateways\PayPal_Gateway;
use WP_Ultimo\Gateways\Manual_Gateway;
// Exit if accessed directly
defined('ABSPATH') || exit;
@ -66,8 +66,7 @@ class Gateway_Manager extends Base_Manager {
public function init() {
add_action('plugins_loaded', array($this, 'on_load'));
} // end init;
}
/**
* Runs after all plugins have been loaded to allow for add-ons to hook into it correctly.
@ -83,9 +82,13 @@ class Gateway_Manager extends Base_Manager {
/*
* Allow developers to add new gateways.
*/
add_action('init', function () {
do_action('wu_register_gateways');
}, 19);
add_action(
'init',
function () {
do_action('wu_register_gateways');
},
19
);
/*
* Adds the Gateway selection fields
@ -108,8 +111,7 @@ class Gateway_Manager extends Base_Manager {
* Waits for webhook signals and deal with them.
*/
add_action('admin_init', array($this, 'maybe_process_v1_webhooks'), 1);
} // end on_load;
}
/**
* Checks if we need to process webhooks received by gateways.
@ -121,7 +123,7 @@ class Gateway_Manager extends Base_Manager {
$gateway = wu_request('wu-gateway');
if ($gateway && !is_admin() && is_main_site()) {
if ($gateway && ! is_admin() && is_main_site()) {
/*
* Do not cache this!
*/
@ -146,9 +148,7 @@ class Gateway_Manager extends Base_Manager {
http_response_code(200);
die('Thanks!');
} catch (Ignorable_Exception $e) {
$message = sprintf('We failed to handle a webhook call, but in this case, no further action is necessary. Message: %s', $e->getMessage());
wu_log_add("wu-{$gateway}-webhook-errors", $message);
@ -157,9 +157,7 @@ class Gateway_Manager extends Base_Manager {
* Send the error back, but with a 200.
*/
wp_send_json_error(new \WP_Error('webhook-error', $message), 200);
} catch (\Throwable $e) {
$file = $e->getFile();
$line = $e->getLine();
@ -177,12 +175,9 @@ class Gateway_Manager extends Base_Manager {
* a non-200 code is returned.
*/
wp_send_json_error(new \WP_Error('webhook-error', $message), 500);
} // end try;
} // end if;
} // end maybe_process_webhooks;
}
}
}
/**
* Checks if we need to process webhooks received by legacy gateways.
@ -203,7 +198,6 @@ class Gateway_Manager extends Base_Manager {
$gateway = wu_get_gateway($gateway_id);
if ($gateway) {
$gateway->before_backwards_compatible_webhook();
/*
@ -230,9 +224,7 @@ class Gateway_Manager extends Base_Manager {
http_response_code(200);
die('Thanks!');
} catch (Ignorable_Exception $e) {
$message = sprintf('We failed to handle a webhook call, but in this case, no further action is necessary. Message: %s', $e->getMessage());
wu_log_add("wu-{$gateway_id}-webhook-errors", $message);
@ -241,9 +233,7 @@ class Gateway_Manager extends Base_Manager {
* Send the error back, but with a 200.
*/
wp_send_json_error(new \WP_Error('webhook-error', $message), 200);
} catch (\Throwable $e) {
$message = sprintf('We failed to handle a webhook call. Error: %s', $e->getMessage());
wu_log_add("wu-{$gateway_id}-webhook-errors", $message, LogLevel::ERROR);
@ -257,14 +247,10 @@ class Gateway_Manager extends Base_Manager {
http_response_code(500);
wp_send_json_error(new \WP_Error('webhook-error', $message));
} // end try;
} // end if;
} // end if;
} // end maybe_process_v1_webhooks;
}
}
}
}
/**
* Let gateways deal with their confirmation steps.
@ -278,11 +264,9 @@ class Gateway_Manager extends Base_Manager {
/*
* First we check for the confirmation parameter.
*/
if (!wu_request('wu-confirm') || (wu_request('status') && wu_request('status') === 'done')) {
if ( ! wu_request('wu-confirm') || (wu_request('status') && wu_request('status') === 'done')) {
return;
} // end if;
}
ob_start();
@ -292,25 +276,27 @@ class Gateway_Manager extends Base_Manager {
$gateway = wu_get_gateway($gateway_id);
if (!$gateway) {
if ( ! $gateway) {
$error = new \WP_Error('missing_gateway', __('Missing gateway parameter.', 'wp-ultimo'));
wp_die($error, __('Error', 'wp-ultimo'), array('back_link' => true, 'response' => '200'));
} // end if;
wp_die(
$error,
__('Error', 'wp-ultimo'),
array(
'back_link' => true,
'response' => '200',
)
);
}
try {
$payment_hash = wu_request('payment');
$payment = wu_get_payment_by_hash($payment_hash);
if ($payment) {
$gateway->set_payment($payment);
} // end if;
}
/*
* Pass it down to the gateway.
@ -322,31 +308,38 @@ class Gateway_Manager extends Base_Manager {
$results = $gateway->process_confirmation();
if (is_wp_error($results)) {
wp_die($results, __('Error', 'wp-ultimo'), array('back_link' => true, 'response' => '200'));
} // end if;
wp_die(
$results,
__('Error', 'wp-ultimo'),
array(
'back_link' => true,
'response' => '200',
)
);
}
} catch (\Throwable $e) {
$error = new \WP_Error('confirm-error-' . $e->getCode(), $e->getMessage());
wp_die($error, __('Error', 'wp-ultimo'), array('back_link' => true, 'response' => '200'));
} // end try;
wp_die(
$error,
__('Error', 'wp-ultimo'),
array(
'back_link' => true,
'response' => '200',
)
);
}
$output = ob_get_clean();
if (!empty($output)) {
if ( ! empty($output)) {
/*
* Add a filter to bypass the checkout form.
* This is used for PayPal confirmation page.
*/
add_action('wu_bypass_checkout_form', fn($bypass, $atts) => $output, 10, 2);
} // end if;
} // end process_gateway_confirmations;
}
}
/**
* Adds the field that enabled and disables Payment Gateways on the settings.
@ -356,16 +349,19 @@ class Gateway_Manager extends Base_Manager {
*/
public function add_gateway_selector_field() {
wu_register_settings_field('payment-gateways', 'active_gateways', array(
'title' => __('Active Payment Gateways', 'wp-ultimo'),
'desc' => __('Payment gateways are what your customers will use to pay.', 'wp-ultimo'),
'type' => 'multiselect',
'columns' => 2,
'options' => array($this, 'get_gateways_as_options'),
'default' => array(),
));
} // end add_gateway_selector_field;
wu_register_settings_field(
'payment-gateways',
'active_gateways',
array(
'title' => __('Active Payment Gateways', 'wp-ultimo'),
'desc' => __('Payment gateways are what your customers will use to pay.', 'wp-ultimo'),
'type' => 'multiselect',
'columns' => 2,
'options' => array($this, 'get_gateways_as_options'),
'default' => array(),
)
);
}
/**
* Returns the list of registered gateways as options for the gateway selector setting.
@ -384,8 +380,7 @@ class Gateway_Manager extends Base_Manager {
$gateways = array_filter($gateways, fn($item) => $item['hidden'] === false);
return $gateways;
} // end get_gateways_as_options;
}
/**
* Loads the default gateways.
@ -422,8 +417,7 @@ class Gateway_Manager extends Base_Manager {
*/
$manual_desc = __('Use the Manual Gateway to allow users to pay you directly via bank transfers, checks, or other channels.', 'wp-ultimo');
wu_register_gateway('manual', __('Manual', 'wp-ultimo'), $manual_desc, Manual_Gateway::class);
} // end add_default_gateways;
}
/**
* Checks if a gateway was already registered.
@ -434,9 +428,8 @@ class Gateway_Manager extends Base_Manager {
*/
public function is_gateway_registered($id) {
return is_array($this->registered_gateways) && isset($this->registered_gateways[$id]);
} // end is_gateway_registered;
return is_array($this->registered_gateways) && isset($this->registered_gateways[ $id ]);
}
/**
* Returns a list of all the registered gateways
@ -447,8 +440,7 @@ class Gateway_Manager extends Base_Manager {
public function get_registered_gateways() {
return $this->registered_gateways;
} // end get_registered_gateways;
}
/**
* Returns a particular Gateway registered
@ -459,9 +451,8 @@ class Gateway_Manager extends Base_Manager {
*/
public function get_gateway($id) {
return $this->is_gateway_registered($id) ? $this->registered_gateways[$id] : false;
} // end get_gateway;
return $this->is_gateway_registered($id) ? $this->registered_gateways[ $id ] : false;
}
/**
* Adds a new Gateway to the System. Used by gateways to make themselves visible.
@ -479,15 +470,13 @@ class Gateway_Manager extends Base_Manager {
// Checks if gateway was already added
if ($this->is_gateway_registered($id)) {
return;
} // end if;
}
$active_gateways = (array) wu_get_setting('active_gateways', array());
// Adds to the global
$this->registered_gateways[$id] = array(
$this->registered_gateways[ $id ] = array(
'id' => $id,
'title' => $title,
'desc' => $desc,
@ -502,8 +491,7 @@ class Gateway_Manager extends Base_Manager {
// Return the value
return true;
} // end register_gateway;
}
/**
* Adds additional hooks for each of the gateway registered.
@ -524,17 +512,14 @@ class Gateway_Manager extends Base_Manager {
* payments, add it to the list.
*/
if ($gateway->supports_recurring()) {
$this->auto_renewable_gateways[] = $gateway_id;
} // end if;
}
add_action('wu_checkout_scripts', array($gateway, 'register_scripts'));
$gateway->hooks();
$gateway->hooks();
add_action('wu_settings_payment_gateways', array($gateway, 'settings'));
add_action("wu_{$gateway_id}_process_webhooks", array($gateway, 'process_webhooks'));
add_action("wu_{$gateway_id}_remote_payment_url", array($gateway, 'get_payment_url_on_gateway'));
@ -546,13 +531,15 @@ class Gateway_Manager extends Base_Manager {
/*
* Renders the gateway fields.
*/
add_action('wu_checkout_gateway_fields', function($checkout) use ($gateway) {
add_action(
'wu_checkout_gateway_fields',
function ($checkout) use ($gateway) {
$field_content = call_user_func(array($gateway, 'fields'));
$field_content = call_user_func(array($gateway, 'fields'));
ob_start();
ob_start();
?>
?>
<div v-cloak v-show="gateway == '<?php echo esc_attr($gateway->get_id()); ?>' && order && order.should_collect_payment" class="wu-overflow">
@ -560,13 +547,12 @@ class Gateway_Manager extends Base_Manager {
</div>
<?php
<?php
echo ob_get_clean();
});
} // end install_hooks;
echo ob_get_clean();
}
);
}
/**
* Returns an array with the list of gateways that support auto-renew.
@ -577,7 +563,5 @@ class Gateway_Manager extends Base_Manager {
public function get_auto_renewable_gateways() {
return (array) $this->auto_renewable_gateways;
} // end get_auto_renewable_gateways;
} // end class Gateway_Manager;
}
}

View File

@ -32,7 +32,5 @@ class Job_Manager {
* @return void
*/
public function init() {
} // end init;
} // end class Job_Manager;
}
}

View File

@ -14,9 +14,9 @@ namespace WP_Ultimo\Managers;
// Exit if accessed directly
defined('ABSPATH') || exit;
use \Psr\Log\LogLevel;
use \WP_Ultimo\Objects\Limitations;
use \WP_Ultimo\Database\Sites\Site_Type;
use Psr\Log\LogLevel;
use WP_Ultimo\Objects\Limitations;
use WP_Ultimo\Database\Sites\Site_Type;
/**
* Handles processes related to limitations.
@ -36,10 +36,8 @@ class Limitation_Manager {
public function init() {
if (WP_Ultimo()->is_loaded() === false) {
return;
} // end if;
}
add_filter('wu_product_options_sections', array($this, 'add_limitation_sections'), 10, 2);
@ -52,8 +50,7 @@ class Limitation_Manager {
add_action('wu_async_handle_plugins', array($this, 'async_handle_plugins'), 10, 5);
add_action('wu_async_switch_theme', array($this, 'async_switch_theme'), 10, 2);
} // end init;
}
/**
* Handles async plugin activation and deactivation.
@ -73,34 +70,25 @@ class Limitation_Manager {
// Avoid doing anything on the main site.
if (wu_get_main_site_id() === $site_id) {
return $results;
} // end if;
}
switch_to_blog($site_id);
if ($action === 'activate') {
$results = activate_plugins($plugins, '', $network_wide, $silent);
} elseif ($action === 'deactivate') {
$results = deactivate_plugins($plugins, $silent, $network_wide);
} // end if;
}
if (is_wp_error($results)) {
wu_log_add('plugins', $results, LogLevel::ERROR);
} // end if;
}
restore_current_blog();
return $results;
} // end async_handle_plugins;
}
/**
* Switch themes via Job Queue.
@ -120,8 +108,7 @@ class Limitation_Manager {
restore_current_blog();
return true;
} // end async_switch_theme;
}
/**
* Register the modal windows to confirm resetting the limitations.
@ -131,12 +118,14 @@ class Limitation_Manager {
*/
public function register_forms() {
wu_register_form('confirm_limitations_reset', array(
'render' => array($this, 'render_confirm_limitations_reset'),
'handler' => array($this, 'handle_confirm_limitations_reset'),
));
} // end register_forms;
wu_register_form(
'confirm_limitations_reset',
array(
'render' => array($this, 'render_confirm_limitations_reset'),
'handler' => array($this, 'handle_confirm_limitations_reset'),
)
);
}
/**
* Renders the conformation modal to reset limitations.
@ -182,17 +171,18 @@ class Limitation_Manager {
'field_wrapper_classes' => 'wu-w-full wu-box-border wu-items-center wu-flex wu-justify-between wu-p-4 wu-m-0 wu-border-t wu-border-l-0 wu-border-r-0 wu-border-b-0 wu-border-gray-300 wu-border-solid',
'html_attr' => array(
'data-wu-app' => 'reset_limitations',
'data-state' => json_encode(array(
'confirmed' => false,
)),
'data-state' => json_encode(
array(
'confirmed' => false,
)
),
),
);
$form = new \WP_Ultimo\UI\Form('reset_limitations', $fields, $form_attributes);
$form->render();
} // end render_confirm_limitations_reset;
}
/**
* Handles the reset of permissions.
@ -206,28 +196,32 @@ class Limitation_Manager {
$model = wu_request('model');
if (!$id || !$model) {
wp_send_json_error(new \WP_Error(
'parameters-not-found',
__('Required parameters are missing.', 'wp-ultimo')
));
} // end if;
if ( ! $id || ! $model) {
wp_send_json_error(
new \WP_Error(
'parameters-not-found',
__('Required parameters are missing.', 'wp-ultimo')
)
);
}
/*
* Remove limitations object
*/
Limitations::remove_limitations($model, $id);
wp_send_json_success(array(
'redirect_url' => wu_network_admin_url("wp-ultimo-edit-{$model}", array(
'id' => $id,
'updated' => 1,
))
));
} // end handle_confirm_limitations_reset;
wp_send_json_success(
array(
'redirect_url' => wu_network_admin_url(
"wp-ultimo-edit-{$model}",
array(
'id' => $id,
'updated' => 1,
)
),
)
);
}
/**
* Returns the type of the object that has limitations.
@ -242,22 +236,15 @@ class Limitation_Manager {
$model = false;
if (is_a($object, \WP_Ultimo\Models\Site::class)) {
$model = 'site';
} elseif (is_a($object, WP_Ultimo\Models\Membership::class)) {
$model = 'membership';
} elseif (is_a($object, \WP_Ultimo\Models\Product::class)) {
$model = 'product';
} // end if;
}
return apply_filters('wu_limitations_get_object_type', $model);
} // end get_object_type;
}
/**
* Injects the limitations panels when necessary.
@ -271,7 +258,6 @@ class Limitation_Manager {
public function add_limitation_sections($sections, $object) {
if ($this->get_object_type($object) === 'site' && $object->get_type() !== Site_Type::CUSTOMER_OWNED) {
$html = sprintf('<span class="wu--mt-4 wu-p-2 wu-bg-blue-100 wu-text-blue-600 wu-rounded wu-block">%s</span>', __('Limitations are only available for customer-owned sites. You need to change the type to Customer-owned and save this site before the options are shown.', 'wp-ultimo'));
$sections['sites'] = array(
@ -282,16 +268,14 @@ class Limitation_Manager {
'note' => array(
'type' => 'html',
'content' => $html,
)
)
),
),
);
return $sections;
} // end if;
}
if ($this->get_object_type($object) !== 'site') {
$sections['sites'] = array(
'title' => __('Sites', 'wp-ultimo'),
'desc' => __('Control limitations imposed to the number of sites allowed for memberships attached to this product.', 'wp-ultimo'),
@ -302,14 +286,12 @@ class Limitation_Manager {
'limit_sites' => $object->get_limitations()->sites->is_enabled(),
),
);
} // end if;
}
/*
* Add Visits limitation control
*/
if ((bool) wu_get_setting('enable_visits_limiting', true)) {
$sections['visits'] = array(
'title' => __('Visits', 'wp-ultimo'),
'desc' => __('Control limitations imposed to the number of unique visitors allowed for memberships attached to this product.', 'wp-ultimo'),
@ -325,17 +307,15 @@ class Limitation_Manager {
'desc' => __('Toggle this option to enable unique visits limitation.', 'wp-ultimo'),
'value' => 10,
'html_attr' => array(
'v-model' => 'limit_visits'
'v-model' => 'limit_visits',
),
),
),
);
if ($object->model !== 'product') {
$sections['visits']['fields']['modules_visits_overwrite'] = $this->override_notice($object->get_limitations(false)->visits->has_own_enabled());
} // end if;
}
$sections['visits']['fields']['modules[visits][limit]'] = array(
'type' => 'number',
@ -353,17 +333,14 @@ class Limitation_Manager {
);
if ($object->model !== 'product') {
$sections['visits']['fields']['allowed_visits_overwrite'] = $this->override_notice($object->get_limitations(false)->visits->has_own_limit(), array('limit_visits'));
} // end if;
}
/*
* If this is a site edit screen, show the current values
* for visits and the reset date
*/
if ($this->get_object_type($object) === 'site') {
$sections['visits']['fields']['visits_count'] = array(
'type' => 'text-display',
'title' => __('Current Unique Visits Count this Month', 'wp-ultimo'),
@ -374,10 +351,8 @@ class Limitation_Manager {
'v-cloak' => '1',
),
);
} // end if;
} // end if;
}
}
$sections['users'] = array(
'title' => __('Users', 'wp-ultimo'),
@ -393,17 +368,15 @@ class Limitation_Manager {
'title' => __('Limit User', 'wp-ultimo'),
'desc' => __('Enable user limitations for this product.', 'wp-ultimo'),
'html_attr' => array(
'v-model' => 'limit_users'
'v-model' => 'limit_users',
),
),
),
);
if ($object->model !== 'product') {
$sections['users']['fields']['modules_user_overwrite'] = $this->override_notice($object->get_limitations(false)->users->has_own_enabled());
} // end if;
}
$this->register_user_fields($sections, $object);
@ -429,10 +402,8 @@ class Limitation_Manager {
);
if ($object->model !== 'product') {
$sections['post_types']['fields']['post_quota_overwrite'] = $this->override_notice($object->get_limitations(false)->post_types->has_own_enabled());
} // end if;
}
$sections['post_types']['post_quota_note'] = array(
'type' => 'note',
@ -467,10 +438,8 @@ class Limitation_Manager {
);
if ($object->model !== 'product') {
$sections['limit_disk_space']['fields']['disk_space_modules_overwrite'] = $this->override_notice($object->get_limitations(false)->disk_space->has_own_enabled());
} // end if;
}
$sections['limit_disk_space']['fields']['modules[disk_space][limit]'] = array(
'type' => 'number',
@ -486,10 +455,8 @@ class Limitation_Manager {
);
if ($object->model !== 'product') {
$sections['limit_disk_space']['fields']['disk_space_override'] = $this->override_notice($object->get_limitations(false)->disk_space->has_own_limit(), array('limit_disk_space'));
} // end if;
}
$sections['custom_domain'] = array(
'title' => __('Custom Domains', 'wp-ultimo'),
@ -516,10 +483,8 @@ class Limitation_Manager {
);
if ($object->model !== 'product') {
$sections['custom_domain']['fields']['custom_domain_override'] = $this->override_notice($object->get_limitations(false)->domain_mapping->has_own_enabled(), array('allow_domain_mapping'));
} // end if;
}
$sections['allowed_themes'] = array(
'title' => __('Themes', 'wp-ultimo'),
@ -554,10 +519,13 @@ class Limitation_Manager {
),
);
$reset_url = wu_get_form_url('confirm_limitations_reset', array(
'id' => $object->get_id(),
'model' => $object->model,
));
$reset_url = wu_get_form_url(
'confirm_limitations_reset',
array(
'id' => $object->get_id(),
'model' => $object->model,
)
);
$sections['reset_limitations'] = array(
'title' => __('Reset Limitations', 'wp-ultimo'),
@ -573,8 +541,7 @@ class Limitation_Manager {
);
return $sections;
} // end add_limitation_sections;
}
/**
* Generates the override notice.
@ -599,8 +566,7 @@ class Limitation_Manager {
'style' => 'border-top-width: 0 !important',
),
);
} // end override_notice;
}
/**
* Register the user roles fields
@ -618,10 +584,9 @@ class Limitation_Manager {
$sections['users']['state']['roles'] = array();
foreach ($user_roles as $user_role_slug => $user_role) {
$sections['users']['state']['roles'][ $user_role_slug ] = $object->get_limitations()->users->{$user_role_slug};
$sections['users']['state']['roles'][$user_role_slug] = $object->get_limitations()->users->{$user_role_slug};
$sections['users']['fields']["control_{$user_role_slug}"] = array(
$sections['users']['fields'][ "control_{$user_role_slug}" ] = array(
'type' => 'group',
'title' => sprintf(__('Limit %s Role', 'wp-ultimo'), $user_role['name']),
'desc' => sprintf(__('The customer will be able to create %s users(s) of this user role.', 'wp-ultimo'), "{{ roles['{$user_role_slug}'].enabled ? ( parseInt(roles['{$user_role_slug}'].number, 10) ? roles['{$user_role_slug}'].number : '" . __('unlimited', 'wp-ultimo') . "' ) : '" . __('no', 'wp-ultimo') . "' }}"),
@ -656,14 +621,10 @@ class Limitation_Manager {
* Add override notice.
*/
if ($object->model !== 'product') {
$sections['users']['fields']["override_{$user_role_slug}"] = $this->override_notice($object->get_limitations(false)->users->exists($user_role_slug), array('limit_users'));
} // end if;
} // end foreach;
} // end register_user_fields;
$sections['users']['fields'][ "override_{$user_role_slug}" ] = $this->override_notice($object->get_limitations(false)->users->exists($user_role_slug), array('limit_users'));
}
}
}
/**
* Register the post type fields
@ -681,10 +642,9 @@ class Limitation_Manager {
$sections['post_types']['state']['types'] = array();
foreach ($post_types as $post_type_slug => $post_type) {
$sections['post_types']['state']['types'][ $post_type_slug ] = $object->get_limitations()->post_types->{$post_type_slug};
$sections['post_types']['state']['types'][$post_type_slug] = $object->get_limitations()->post_types->{$post_type_slug};
$sections['post_types']['fields']["control_{$post_type_slug}"] = array(
$sections['post_types']['fields'][ "control_{$post_type_slug}" ] = array(
'type' => 'group',
'title' => sprintf(__('Limit %s', 'wp-ultimo'), $post_type->label),
'desc' => sprintf(__('The customer will be able to create %s post(s) of this post type.', 'wp-ultimo'), "{{ types['{$post_type_slug}'].enabled ? ( parseInt(types['{$post_type_slug}'].number, 10) ? types['{$post_type_slug}'].number : '" . __('unlimited', 'wp-ultimo') . "' ) : '" . __('no', 'wp-ultimo') . "' }}"),
@ -719,16 +679,15 @@ class Limitation_Manager {
* Add override notice.
*/
if ($object->model !== 'product') {
$sections['post_types']['fields']["override_{$post_type_slug}"] = $this->override_notice($object->get_limitations(false)->post_types->exists($post_type_slug), array(
'limit_post_types'
));
} // end if;
} // end foreach;
} // end register_post_type_fields;
$sections['post_types']['fields'][ "override_{$post_type_slug}" ] = $this->override_notice(
$object->get_limitations(false)->post_types->exists($post_type_slug),
array(
'limit_post_types',
)
);
}
}
}
/**
* Returns the list of fields for the site tab.
@ -747,16 +706,14 @@ class Limitation_Manager {
'desc' => __('Enable site limitations for this product.', 'wp-ultimo'),
'value' => $object->get_limitations()->sites->is_enabled(),
'html_attr' => array(
'v-model' => 'limit_sites'
'v-model' => 'limit_sites',
),
),
);
if ($object->model !== 'product') {
$fields['sites_overwrite'] = $this->override_notice($object->get_limitations(false)->sites->has_own_enabled());
} // end if;
}
/*
* Sites not supported on this type
@ -785,14 +742,11 @@ class Limitation_Manager {
);
if ($object->model !== 'product') {
$fields['sites_overwrite_2'] = $this->override_notice($object->get_limitations(false)->sites->has_own_limit(), array("get_state_value('product_type', 'none') !== 'service' && limit_sites"));
} // end if;
}
return apply_filters('wu_limitations_get_sites_fields', $fields, $object, $this);
} // end get_sites_fields;
}
/**
* Returns the HTML markup for the plugin selector list.
@ -806,12 +760,14 @@ class Limitation_Manager {
$all_plugins = $this->get_all_plugins();
return wu_get_template_contents('limitations/plugin-selector', array(
'plugins' => $all_plugins,
'object' => $object,
));
} // end get_plugin_selection_list;
return wu_get_template_contents(
'limitations/plugin-selector',
array(
'plugins' => $all_plugins,
'object' => $object,
)
);
}
/**
* Returns the HTML markup for the plugin selector list.
@ -826,13 +782,15 @@ class Limitation_Manager {
$all_themes = $this->get_all_themes();
return wu_get_template_contents('limitations/theme-selector', array(
'section' => $section,
'themes' => $all_themes,
'object' => $object,
));
} // end get_theme_selection_list;
return wu_get_template_contents(
'limitations/theme-selector',
array(
'section' => $section,
'themes' => $all_themes,
'object' => $object,
)
);
}
/**
* Returns a list of all plugins available as options, excluding WP Multisite WaaS.
@ -849,26 +807,19 @@ class Limitation_Manager {
$listed_plugins = array();
foreach ($all_plugins as $plugin_path => $plugin_info) {
if (wu_get_isset($plugin_info, 'Network') === true) {
continue;
} // end if;
}
if (in_array($plugin_path, $this->plugin_exclusion_list(), true)) {
continue;
}
} // end if;
$listed_plugins[$plugin_path] = $plugin_info;
} // end foreach;
$listed_plugins[ $plugin_path ] = $plugin_info;
}
return $listed_plugins;
} // end get_all_plugins;
}
/**
* Returns a list of all themes available as options, after filtering.
*
@ -878,9 +829,8 @@ class Limitation_Manager {
$all_plugins = wp_get_themes();
return array_filter($all_plugins, fn($path) => !in_array($path, $this->theme_exclusion_list(), true), ARRAY_FILTER_USE_KEY);
} // end get_all_themes;
return array_filter($all_plugins, fn($path) => ! in_array($path, $this->theme_exclusion_list(), true), ARRAY_FILTER_USE_KEY);
}
/**
* Returns the exclusion list for plugins.
@ -898,8 +848,7 @@ class Limitation_Manager {
);
return apply_filters('wu_limitations_plugin_exclusion_list', $exclusion_list);
} // end plugin_exclusion_list;
}
/**
* Returns the exclusion list for themes.
@ -912,7 +861,5 @@ class Limitation_Manager {
$exclusion_list = array();
return apply_filters('wu_limitations_theme_exclusion_list', $exclusion_list);
} // end theme_exclusion_list;
} // end class Limitation_Manager;
}
}

View File

@ -11,9 +11,9 @@
namespace WP_Ultimo\Managers;
use \Psr\Log\LogLevel;
use \WP_Ultimo\Managers\Base_Manager;
use \WP_Ultimo\Database\Memberships\Membership_Status;
use Psr\Log\LogLevel;
use WP_Ultimo\Managers\Base_Manager;
use WP_Ultimo\Database\Memberships\Membership_Status;
// Exit if accessed directly
defined('ABSPATH') || exit;
@ -25,7 +25,9 @@ defined('ABSPATH') || exit;
*/
class Membership_Manager extends Base_Manager {
use \WP_Ultimo\Apis\Rest_Api, \WP_Ultimo\Apis\WP_CLI, \WP_Ultimo\Traits\Singleton;
use \WP_Ultimo\Apis\Rest_Api;
use \WP_Ultimo\Apis\WP_CLI;
use \WP_Ultimo\Traits\Singleton;
/**
* The manager slug.
@ -55,9 +57,12 @@ class Membership_Manager extends Base_Manager {
$this->enable_wp_cli();
add_action('init', function (){
Event_Manager::register_model_events('membership', __('Membership', 'wp-ultimo'), array('created', 'updated'));
});
add_action(
'init',
function () {
Event_Manager::register_model_events('membership', __('Membership', 'wp-ultimo'), array('created', 'updated'));
}
);
add_action('wu_async_transfer_membership', array($this, 'async_transfer_membership'), 10, 2);
@ -83,8 +88,7 @@ class Membership_Manager extends Base_Manager {
add_action('wp_ajax_wu_check_pending_site_created', array($this, 'check_pending_site_created'));
add_action('wu_async_publish_pending_site', array($this, 'async_publish_pending_site'), 10);
} // end init;
}
/**
* Processes a delayed site publish action.
@ -98,50 +102,42 @@ class Membership_Manager extends Base_Manager {
ignore_user_abort(true);
// Don't make the request block till we finish, if possible.
if ( function_exists( 'fastcgi_finish_request' ) && version_compare( phpversion(), '7.0.16', '>=' ) ) {
wp_send_json(array( 'status' => 'creating-site'));
if ( function_exists('fastcgi_finish_request') && version_compare(phpversion(), '7.0.16', '>=') ) {
wp_send_json(array('status' => 'creating-site'));
fastcgi_finish_request();
} // end if;
}
$membership_id = wu_request('membership_id');
$this->async_publish_pending_site($membership_id);
exit; // Just exit the request
} // end publish_pending_site;
/**
* Processes a delayed site publish action.
*
* @since 2.0.0
*
* @param int $membership_id The membership id.
* @return bool|\WP_Error
*/
public function async_publish_pending_site($membership_id) {
}
/**
* Processes a delayed site publish action.
*
* @since 2.0.0
*
* @param int $membership_id The membership id.
* @return bool|\WP_Error
*/
public function async_publish_pending_site($membership_id) {
$membership = wu_get_membership($membership_id);
if (!$membership) {
if ( ! $membership) {
return new \WP_Error('error', __('An unexpected error happened.', 'wp-ultimo'));
} // end if;
}
$status = $membership->publish_pending_site();
if (is_wp_error($status)) {
wu_log_add('site-errors', $status, LogLevel::ERROR);
} // end if;
}
return $status;
} // end async_publish_pending_site;
}
/**
* Processes a delayed site publish action.
@ -154,82 +150,68 @@ class Membership_Manager extends Base_Manager {
$membership = wu_get_membership_by_hash($membership_id);
if (!$membership) {
if ( ! $membership) {
return new \WP_Error('error', __('An unexpected error happened.', 'wp-ultimo'));
} // end if;
}
$pending_site = $membership->get_pending_site();
if (!$pending_site) {
if ( ! $pending_site) {
/**
* We do not have a pending site, so we can assume the site was created.
*/
wp_send_json(array('publish_status' => 'completed'));
exit;
} // end if;
}
wp_send_json(array('publish_status' => $pending_site->is_publishing() ? 'running' : 'stopped'));
exit;
} // end check_pending_site_created;
/**
* Processes a membership swap.
*
* @since 2.0.0
*
* @param int $membership_id The membership id.
* @return bool|\WP_Error
*/
public function async_membership_swap($membership_id) {
}
/**
* Processes a membership swap.
*
* @since 2.0.0
*
* @param int $membership_id The membership id.
* @return bool|\WP_Error
*/
public function async_membership_swap($membership_id) {
global $wpdb;
$membership = wu_get_membership($membership_id);
if (!$membership) {
if ( ! $membership) {
return new \WP_Error('error', __('An unexpected error happened.', 'wp-ultimo'));
} // end if;
}
$scheduled_swap = $membership->get_scheduled_swap();
if (empty($scheduled_swap)) {
return new \WP_Error('error', __('An unexpected error happened.', 'wp-ultimo'));
} // end if;
}
$order = $scheduled_swap->order;
$wpdb->query('START TRANSACTION');
try {
$membership->swap($order);
$status = $membership->save();
if (is_wp_error($status)) {
$wpdb->query('ROLLBACK');
return new \WP_Error('error', __('An unexpected error happened.', 'wp-ultimo'));
} // end if;
}
} catch (\Throwable $exception) {
$wpdb->query('ROLLBACK');
return new \WP_Error('error', __('An unexpected error happened.', 'wp-ultimo'));
} // end try;
}
/*
* Clean up the membership swap order.
@ -239,8 +221,7 @@ class Membership_Manager extends Base_Manager {
$wpdb->query('COMMIT');
return true;
} // end async_membership_swap;
}
/**
* Watches the change in payment status to take action when needed.
@ -261,22 +242,18 @@ class Membership_Manager extends Base_Manager {
Membership_Status::ON_HOLD,
);
if (!in_array($old_status, $allowed_previous_status, true)) {
if ( ! in_array($old_status, $allowed_previous_status, true)) {
return;
} // end if;
}
$allowed_status = array(
Membership_Status::ACTIVE,
Membership_Status::TRIALING,
);
if (!in_array($new_status, $allowed_status, true)) {
if ( ! in_array($new_status, $allowed_status, true)) {
return;
} // end if;
}
/*
* Create pending sites.
@ -286,12 +263,9 @@ class Membership_Manager extends Base_Manager {
$status = $membership->publish_pending_site_async();
if (is_wp_error($status)) {
wu_log_add('site-errors', $status, LogLevel::ERROR);
} // end if;
} // end transition_membership_status;
}
}
/**
* Mark the membership date of cancellation.
@ -306,16 +280,13 @@ class Membership_Manager extends Base_Manager {
public function mark_cancelled_date($old_value, $new_value, $item_id) {
if ($new_value === 'cancelled' && $new_value !== $old_value) {
$membership = wu_get_membership($item_id);
$membership->set_date_cancellation(wu_get_current_time('mysql', true));
$membership->save();
} // end if;
} // end mark_cancelled_date;
}
}
/**
* Transfer a membership from a user to another.
@ -334,11 +305,9 @@ class Membership_Manager extends Base_Manager {
$target_customer = wu_get_customer($target_customer_id);
if (!$membership || !$target_customer || absint($membership->get_customer_id()) === absint($target_customer->get_id())) {
if ( ! $membership || ! $target_customer || absint($membership->get_customer_id()) === absint($target_customer->get_id())) {
return new \WP_Error('error', __('An unexpected error happened.', 'wp-ultimo'));
} // end if;
}
$wpdb->query('START TRANSACTION');
@ -346,30 +315,28 @@ class Membership_Manager extends Base_Manager {
/*
* Get Sites and move them over.
*/
$sites = wu_get_sites(array(
'meta_query' => array(
'membership_id' => array(
'key' => 'wu_membership_id',
'value' => $membership->get_id(),
$sites = wu_get_sites(
array(
'meta_query' => array(
'membership_id' => array(
'key' => 'wu_membership_id',
'value' => $membership->get_id(),
),
),
),
));
)
);
foreach ($sites as $site) {
$site->set_customer_id($target_customer_id);
$saved = $site->save();
if (is_wp_error($saved)) {
$wpdb->query('ROLLBACK');
return $saved;
} // end if;
} // end foreach;
}
}
/*
* Change the membership
@ -379,28 +346,22 @@ class Membership_Manager extends Base_Manager {
$saved = $membership->save();
if (is_wp_error($saved)) {
$wpdb->query('ROLLBACK');
return $saved;
} // end if;
}
} catch (\Throwable $e) {
$wpdb->query('ROLLBACK');
return new \WP_Error('exception', $e->getMessage());
} // end try;
}
$wpdb->query('COMMIT');
$membership->unlock();
return true;
} // end async_transfer_membership;
}
/**
* Delete a membership.
@ -416,11 +377,9 @@ class Membership_Manager extends Base_Manager {
$membership = wu_get_membership($membership_id);
if (!$membership) {
if ( ! $membership) {
return new \WP_Error('error', __('An unexpected error happened.', 'wp-ultimo'));
} // end if;
}
$wpdb->query('START TRANSACTION');
@ -428,28 +387,26 @@ class Membership_Manager extends Base_Manager {
/*
* Get Sites and delete them.
*/
$sites = wu_get_sites(array(
'meta_query' => array(
'membership_id' => array(
'key' => 'wu_membership_id',
'value' => $membership->get_id(),
$sites = wu_get_sites(
array(
'meta_query' => array(
'membership_id' => array(
'key' => 'wu_membership_id',
'value' => $membership->get_id(),
),
),
),
));
)
);
foreach ($sites as $site) {
$saved = $site->delete();
if (is_wp_error($saved)) {
$wpdb->query('ROLLBACK');
return $saved;
} // end if;
} // end foreach;
}
}
/*
* Delete the membership
@ -457,25 +414,18 @@ class Membership_Manager extends Base_Manager {
$saved = $membership->delete();
if (is_wp_error($saved)) {
$wpdb->query('ROLLBACK');
return $saved;
} // end if;
}
} catch (\Throwable $e) {
$wpdb->query('ROLLBACK');
return new \WP_Error('exception', $e->getMessage());
} // end try;
}
$wpdb->query('COMMIT');
return true;
} // end async_delete_membership;
} // end class Membership_Manager;
}
}

View File

@ -11,7 +11,7 @@
namespace WP_Ultimo\Managers;
use \WP_Ultimo\Managers\Base_Manager;
use WP_Ultimo\Managers\Base_Manager;
// Exit if accessed directly
defined('ABSPATH') || exit;
@ -58,10 +58,9 @@ class Notes_Manager extends Base_Manager {
add_filter('wu_customer_options_sections', array($this, 'add_notes_options_section'), 10, 2);
add_filter('wu_site_options_sections', array($this, 'add_notes_options_section'), 10, 2);
}
} // end init;
/**
/**
* Register ajax forms that we use for object.
*
* @since 2.0.0
@ -71,33 +70,41 @@ class Notes_Manager extends Base_Manager {
/*
* Add note
*/
wu_register_form('add_note', array(
'render' => array($this, 'render_add_note_modal'),
'handler' => array($this, 'handle_add_note_modal'),
'capability' => 'edit_notes',
));
wu_register_form(
'add_note',
array(
'render' => array($this, 'render_add_note_modal'),
'handler' => array($this, 'handle_add_note_modal'),
'capability' => 'edit_notes',
)
);
/*
* Clear notes
*/
wu_register_form('clear_notes', array(
'render' => array($this, 'render_clear_notes_modal'),
'handler' => array($this, 'handle_clear_notes_modal'),
'capability' => 'delete_notes',
));
wu_register_form(
'clear_notes',
array(
'render' => array($this, 'render_clear_notes_modal'),
'handler' => array($this, 'handle_clear_notes_modal'),
'capability' => 'delete_notes',
)
);
/*
* Clear notes
*/
wu_register_form('delete_note', array(
'render' => array($this, 'render_delete_note_modal'),
'handler' => array($this, 'handle_delete_note_modal'),
'capability' => 'delete_notes',
));
wu_register_form(
'delete_note',
array(
'render' => array($this, 'render_delete_note_modal'),
'handler' => array($this, 'handle_delete_note_modal'),
'capability' => 'delete_notes',
)
);
}
} // end register_forms;
/**
/**
* Add all domain mapping settings.
*
* @since 2.0.0
@ -109,11 +116,9 @@ class Notes_Manager extends Base_Manager {
*/
public function add_notes_options_section($sections, $object) {
if (!current_user_can('read_notes') && !current_user_can('edit_notes')) {
if ( ! current_user_can('read_notes') && ! current_user_can('edit_notes')) {
return $sections;
} // end if;
}
$fields = array();
@ -123,50 +128,55 @@ class Notes_Manager extends Base_Manager {
'wrapper_html_attr' => array(
'style' => sprintf('min-height: 500px; background: url("%s");', wu_get_asset('pattern-wp-ultimo.png')),
),
'content' => wu_get_template_contents('base/edit/display-notes', array(
'notes' => $object->get_notes(),
'model' => $object->model,
)),
'content' => wu_get_template_contents(
'base/edit/display-notes',
array(
'notes' => $object->get_notes(),
'model' => $object->model,
)
),
);
$fields_buttons = array();
if (current_user_can('delete_notes')) {
$fields_buttons['button_clear_notes'] = array(
'type' => 'link',
'display_value' => __('Clear Notes', 'wp-ultimo'),
'wrapper_classes' => 'wu-mb-0',
'classes' => 'button wubox',
'html_attr' => array(
'href' => wu_get_form_url('clear_notes', array(
'object_id' => $object->get_id(),
'model' => $object->model,
)),
'href' => wu_get_form_url(
'clear_notes',
array(
'object_id' => $object->get_id(),
'model' => $object->model,
)
),
'title' => __('Clear Notes', 'wp-ultimo'),
),
);
} // end if;
}
if (current_user_can('edit_notes')) {
$fields_buttons['button_add_note'] = array(
'type' => 'link',
'display_value' => __('Add new Note', 'wp-ultimo'),
'wrapper_classes' => 'wu-mb-0',
'classes' => 'button button-primary wubox wu-absolute wu-right-5',
'html_attr' => array(
'href' => wu_get_form_url('add_note', array(
'object_id' => $object->get_id(),
'model' => $object->model,
'height' => 306,
)),
'href' => wu_get_form_url(
'add_note',
array(
'object_id' => $object->get_id(),
'model' => $object->model,
'height' => 306,
)
),
'title' => __('Add new Note', 'wp-ultimo'),
),
);
} // end if;
}
$fields['buttons'] = array(
'type' => 'group',
@ -183,8 +193,7 @@ class Notes_Manager extends Base_Manager {
);
return $sections;
} // end add_notes_options_section;
}
/**
* Renders the notes form.
@ -229,21 +238,26 @@ class Notes_Manager extends Base_Manager {
$fields = apply_filters('wu_notes_options_section_fields', $fields);
$form = new \WP_Ultimo\UI\Form('add_note', $fields, array(
'views' => 'admin-pages/fields',
'classes' => 'wu-modal-form wu-widget-list wu-striped wu-m-0 wu-mt-0',
'field_wrapper_classes' => 'wu-w-full wu-box-border wu-items-center wu-flex wu-justify-between wu-p-4 wu-m-0 wu-border-t wu-border-l-0 wu-border-r-0 wu-border-b-0 wu-border-gray-300 wu-border-solid',
'html_attr' => array(
'data-wu-app' => 'add_note',
'data-state' => wu_convert_to_state(array(
'content' => '',
)),
),
));
$form = new \WP_Ultimo\UI\Form(
'add_note',
$fields,
array(
'views' => 'admin-pages/fields',
'classes' => 'wu-modal-form wu-widget-list wu-striped wu-m-0 wu-mt-0',
'field_wrapper_classes' => 'wu-w-full wu-box-border wu-items-center wu-flex wu-justify-between wu-p-4 wu-m-0 wu-border-t wu-border-l-0 wu-border-r-0 wu-border-b-0 wu-border-gray-300 wu-border-solid',
'html_attr' => array(
'data-wu-app' => 'add_note',
'data-state' => wu_convert_to_state(
array(
'content' => '',
)
),
),
)
);
$form->render();
} // end render_add_note_modal;
}
/**
* Handles the notes form.
@ -257,27 +271,31 @@ class Notes_Manager extends Base_Manager {
$function_name = "wu_get_{$model}";
$object = $function_name(wu_request('object_id'));
$status = $object->add_note(array(
'text' => wu_remove_empty_p(wu_request('content')),
'author_id' => get_current_user_id(),
'note_id' => uniqid(),
));
$status = $object->add_note(
array(
'text' => wu_remove_empty_p(wu_request('content')),
'author_id' => get_current_user_id(),
'note_id' => uniqid(),
)
);
if (is_wp_error($status)) {
wp_send_json_error($status);
}
} // end if;
wp_send_json_success(array(
'redirect_url' => wu_network_admin_url("wp-ultimo-edit-{$model}", array(
'id' => $object->get_id(),
'updated' => 1,
'options' => 'notes',
)),
));
} // end handle_add_note_modal;
wp_send_json_success(
array(
'redirect_url' => wu_network_admin_url(
"wp-ultimo-edit-{$model}",
array(
'id' => $object->get_id(),
'updated' => 1,
'options' => 'notes',
)
),
)
);
}
/**
* Renders the clear notes confirmation form.
@ -317,21 +335,26 @@ class Notes_Manager extends Base_Manager {
),
);
$form = new \WP_Ultimo\UI\Form('clear_notes', $fields, array(
'views' => 'admin-pages/fields',
'classes' => 'wu-modal-form wu-widget-list wu-striped wu-m-0 wu-mt-0',
'field_wrapper_classes' => 'wu-w-full wu-box-border wu-items-center wu-flex wu-justify-between wu-p-4 wu-m-0 wu-border-t wu-border-l-0 wu-border-r-0 wu-border-b-0 wu-border-gray-300 wu-border-solid',
'html_attr' => array(
'data-wu-app' => 'clear_notes',
'data-state' => wu_convert_to_state(array(
'confirmed' => false,
)),
),
));
$form = new \WP_Ultimo\UI\Form(
'clear_notes',
$fields,
array(
'views' => 'admin-pages/fields',
'classes' => 'wu-modal-form wu-widget-list wu-striped wu-m-0 wu-mt-0',
'field_wrapper_classes' => 'wu-w-full wu-box-border wu-items-center wu-flex wu-justify-between wu-p-4 wu-m-0 wu-border-t wu-border-l-0 wu-border-r-0 wu-border-b-0 wu-border-gray-300 wu-border-solid',
'html_attr' => array(
'data-wu-app' => 'clear_notes',
'data-state' => wu_convert_to_state(
array(
'confirmed' => false,
)
),
),
)
);
$form->render();
} // end render_clear_notes_modal;
}
/**
* Handles the clear notes modal.
@ -345,29 +368,29 @@ class Notes_Manager extends Base_Manager {
$function_name = "wu_get_{$model}";
$object = $function_name(wu_request('object_id'));
if (!$object) {
if ( ! $object) {
return;
} // end if;
}
$status = $object->clear_notes();
if (is_wp_error($status)) {
wp_send_json_error($status);
}
} // end if;
wp_send_json_success(array(
'redirect_url' => wu_network_admin_url("wp-ultimo-edit-{$model}", array(
'id' => $object->get_id(),
'deleted' => 1,
'options' => 'notes',
)),
));
} // end handle_clear_notes_modal;
wp_send_json_success(
array(
'redirect_url' => wu_network_admin_url(
"wp-ultimo-edit-{$model}",
array(
'id' => $object->get_id(),
'deleted' => 1,
'options' => 'notes',
)
),
)
);
}
/**
* Renders the delete note confirmation form.
@ -411,21 +434,26 @@ class Notes_Manager extends Base_Manager {
),
);
$form = new \WP_Ultimo\UI\Form('delete_note', $fields, array(
'views' => 'admin-pages/fields',
'classes' => 'wu-modal-form wu-widget-list wu-striped wu-m-0 wu-mt-0',
'field_wrapper_classes' => 'wu-w-full wu-box-border wu-items-center wu-flex wu-justify-between wu-p-4 wu-m-0 wu-border-t wu-border-l-0 wu-border-r-0 wu-border-b-0 wu-border-gray-300 wu-border-solid',
'html_attr' => array(
'data-wu-app' => 'delete_note',
'data-state' => wu_convert_to_state(array(
'confirmed' => false,
)),
),
));
$form = new \WP_Ultimo\UI\Form(
'delete_note',
$fields,
array(
'views' => 'admin-pages/fields',
'classes' => 'wu-modal-form wu-widget-list wu-striped wu-m-0 wu-mt-0',
'field_wrapper_classes' => 'wu-w-full wu-box-border wu-items-center wu-flex wu-justify-between wu-p-4 wu-m-0 wu-border-t wu-border-l-0 wu-border-r-0 wu-border-b-0 wu-border-gray-300 wu-border-solid',
'html_attr' => array(
'data-wu-app' => 'delete_note',
'data-state' => wu_convert_to_state(
array(
'confirmed' => false,
)
),
),
)
);
$form->render();
} // end render_delete_note_modal;
}
/**
* Handles the delete note modal.
@ -440,28 +468,27 @@ class Notes_Manager extends Base_Manager {
$object = $function_name(wu_request('object_id'));
$note_id = wu_request('note_id');
if (!$object) {
if ( ! $object) {
return;
} // end if;
}
$status = $object->delete_note($note_id);
if (is_wp_error($status) || $status === false) {
wp_send_json_error(new \WP_Error('not-found', __('Note not found', 'wp-ultimo')));
}
} // end if;
wp_send_json_success(array(
'redirect_url' => wu_network_admin_url("wp-ultimo-edit-{$model}", array(
'id' => $object->get_id(),
'deleted' => 1,
'options' => 'notes',
)),
));
} // end handle_delete_note_modal;
} // end class Notes_Manager;
wp_send_json_success(
array(
'redirect_url' => wu_network_admin_url(
"wp-ultimo-edit-{$model}",
array(
'id' => $object->get_id(),
'deleted' => 1,
'options' => 'notes',
)
),
)
);
}
}

View File

@ -41,13 +41,10 @@ class Notification_Manager {
add_action('wp_ultimo_load', array($this, 'add_settings'));
if (is_admin() && !is_network_admin()) {
if (is_admin() && ! is_network_admin()) {
add_action('admin_init', array($this, 'hide_notifications_subsites'));
} // end if;
} // end init;
}
}
/**
* Hide notifications on subsites if settings was enabled.
@ -57,36 +54,32 @@ class Notification_Manager {
*/
public function hide_notifications_subsites() {
if (!wu_get_setting('hide_notifications_subsites')) {
if ( ! wu_get_setting('hide_notifications_subsites')) {
return;
} // end if;
}
global $wp_filter;
/*
* List of callbacks to keep, for backwards compatibility purposes.
*/
$this->backwards_compatibility_list = apply_filters('wu_hide_notifications_exclude_list', array(
'inject_admin_head_ads',
));
$this->backwards_compatibility_list = apply_filters(
'wu_hide_notifications_exclude_list',
array(
'inject_admin_head_ads',
)
);
$cleaner = array($this, 'clear_callback_list');
if (wu_get_isset($wp_filter, 'admin_notices')) {
$wp_filter['admin_notices']->callbacks = array_filter($wp_filter['admin_notices']->callbacks, $cleaner === null ? fn($v, $k): bool => !empty($v) : $cleaner, $cleaner === null ? ARRAY_FILTER_USE_BOTH : 0);
} // end if;
$wp_filter['admin_notices']->callbacks = array_filter($wp_filter['admin_notices']->callbacks, $cleaner === null ? fn($v, $k): bool => ! empty($v) : $cleaner, $cleaner === null ? ARRAY_FILTER_USE_BOTH : 0);
}
if (wu_get_isset($wp_filter, 'all_admin_notices')) {
$wp_filter['all_admin_notices']->callbacks = array_filter($wp_filter['all_admin_notices']->callbacks, $cleaner === null ? fn($v, $k): bool => !empty($v) : $cleaner, $cleaner === null ? ARRAY_FILTER_USE_BOTH : 0);
} // end if;
} // end hide_notifications_subsites;
$wp_filter['all_admin_notices']->callbacks = array_filter($wp_filter['all_admin_notices']->callbacks, $cleaner === null ? fn($v, $k): bool => ! empty($v) : $cleaner, $cleaner === null ? ARRAY_FILTER_USE_BOTH : 0);
}
}
/**
* Keeps the allowed callbacks.
@ -99,30 +92,21 @@ class Notification_Manager {
public function clear_callback_list($callbacks): bool {
if (empty($this->backwards_compatibility_list)) {
return false;
} // end if;
}
$keys = array_keys($callbacks);
foreach ($keys as $key) {
foreach ($this->backwards_compatibility_list as $key_to_keep) {
if (strpos($key, (string) $key_to_keep) !== false) {
return true;
} // end if;
} // end foreach;
} // end foreach;
}
}
}
return false;
} // end clear_callback_list;
}
/**
* Filter the WP Multisite WaaS settings to add Notifications Options
@ -133,14 +117,16 @@ class Notification_Manager {
*/
public function add_settings() {
wu_register_settings_field('sites', 'hide_notifications_subsites', array(
'title' => __('Hide Admin Notices on Sites', 'wp-ultimo'),
'desc' => __('Hide all admin notices on network sites, except for WP Multisite WaaS broadcasts.', 'wp-ultimo'),
'type' => 'toggle',
'default' => 0,
'order' => 25,
));
} // end add_settings;
} // end class Notification_Manager;
wu_register_settings_field(
'sites',
'hide_notifications_subsites',
array(
'title' => __('Hide Admin Notices on Sites', 'wp-ultimo'),
'desc' => __('Hide all admin notices on network sites, except for WP Multisite WaaS broadcasts.', 'wp-ultimo'),
'type' => 'toggle',
'default' => 0,
'order' => 25,
)
);
}
}

View File

@ -11,11 +11,11 @@
namespace WP_Ultimo\Managers;
use \WP_Ultimo\Managers\Base_Manager;
use \WP_Ultimo\Models\Payment;
use \WP_Ultimo\Logger;
use \WP_Ultimo\Invoices\Invoice;
use \WP_Ultimo\Checkout\Cart;
use WP_Ultimo\Managers\Base_Manager;
use WP_Ultimo\Models\Payment;
use WP_Ultimo\Logger;
use WP_Ultimo\Invoices\Invoice;
use WP_Ultimo\Checkout\Cart;
// Exit if accessed directly
defined('ABSPATH') || exit;
@ -27,7 +27,9 @@ defined('ABSPATH') || exit;
*/
class Payment_Manager extends Base_Manager {
use \WP_Ultimo\Apis\Rest_Api, \WP_Ultimo\Apis\WP_CLI, \WP_Ultimo\Traits\Singleton;
use \WP_Ultimo\Apis\Rest_Api;
use \WP_Ultimo\Apis\WP_CLI;
use \WP_Ultimo\Traits\Singleton;
/**
* The manager slug.
@ -59,11 +61,16 @@ class Payment_Manager extends Base_Manager {
$this->register_forms();
add_action('init', function () {
Event_Manager::register_model_events( 'payment',
__( 'Payment', 'wp-ultimo' ),
array( 'created', 'updated' ) );
});
add_action(
'init',
function () {
Event_Manager::register_model_events(
'payment',
__('Payment', 'wp-ultimo'),
array('created', 'updated')
);
}
);
add_action('wp_login', array($this, 'check_pending_payments'), 10);
add_action('wp_enqueue_scripts', array($this, 'show_pending_payments'), 10);
@ -79,8 +86,7 @@ class Payment_Manager extends Base_Manager {
add_action('wu_gateway_payment_processed', array($this, 'handle_payment_success'), 10, 3);
add_action('wu_transition_payment_status', array($this, 'transition_payment_status'), 10, 3);
} // end init;
}
/**
* Triggers the do_event of the payment successful.
@ -101,8 +107,7 @@ class Payment_Manager extends Base_Manager {
);
wu_do_event('payment_received', $payload);
} // end handle_payment_success;
}
/**
* Check if current customer haves pending payments
@ -112,47 +117,34 @@ class Payment_Manager extends Base_Manager {
*/
public function check_pending_payments($user) {
if (!is_main_site()) {
if ( ! is_main_site()) {
return;
}
} // end if;
if (!is_a($user, '\WP_User')) {
if ( ! is_a($user, '\WP_User')) {
$user = get_user_by('login', $user);
}
} // end if;
if (!$user) {
if ( ! $user) {
return;
} // end if;
}
$customer = wu_get_customer_by_user_id($user->ID);
if (!$customer) {
if ( ! $customer) {
return;
} // end if;
}
foreach ($customer->get_memberships() as $membership) {
$pending_payment = $membership->get_last_pending_payment();
if ($pending_payment) {
add_user_meta($user->ID, 'wu_show_pending_payment_popup', true, true);
break;
} // end if;
} // end foreach;
} // end check_pending_payments;
}
}
}
/**
* Add and trigger a popup in screen with the pending payments
@ -161,21 +153,17 @@ class Payment_Manager extends Base_Manager {
*/
public function show_pending_payments() {
if (!is_user_logged_in()) {
if ( ! is_user_logged_in()) {
return;
} // end if;
}
$user_id = get_current_user_id();
$show_pending_payment = get_user_meta($user_id, 'wu_show_pending_payment_popup', true);
if (!$show_pending_payment) {
if ( ! $show_pending_payment) {
return;
} // end if;
}
wp_enqueue_style('dashicons');
wp_enqueue_style('wu-admin');
@ -184,12 +172,11 @@ class Payment_Manager extends Base_Manager {
$form_title = __('Pending Payments', 'wp-ultimo');
$form_url = wu_get_form_url('pending_payments');
wp_add_inline_script( 'wubox', "document.addEventListener('DOMContentLoaded', function(){wubox.show('$form_title', '$form_url');});" );
wp_add_inline_script('wubox', "document.addEventListener('DOMContentLoaded', function(){wubox.show('$form_title', '$form_url');});");
// Show only after user login
delete_user_meta($user_id, 'wu_show_pending_payment_popup');
} // end show_pending_payments;
}
/**
* Register the form showing the pending payments of current customer
@ -199,15 +186,15 @@ class Payment_Manager extends Base_Manager {
public function register_forms() {
if (function_exists('wu_register_form')) {
wu_register_form('pending_payments', array(
'render' => array($this, 'render_pending_payments'),
'capability' => 'exist',
));
} // end if;
} // end register_forms;
wu_register_form(
'pending_payments',
array(
'render' => array($this, 'render_pending_payments'),
'capability' => 'exist',
)
);
}
}
/**
* Add customerr pending payments
@ -216,37 +203,29 @@ class Payment_Manager extends Base_Manager {
*/
public function render_pending_payments() {
if (!is_user_logged_in()) {
if ( ! is_user_logged_in()) {
return;
} // end if;
}
$user_id = get_current_user_id();
$customer = wu_get_customer_by_user_id($user_id);
if (!$customer) {
if ( ! $customer) {
return;
} // end if;
}
$pending_payments = array();
foreach ($customer->get_memberships() as $membership) {
$pending_payment = $membership->get_last_pending_payment();
if ($pending_payment) {
$pending_payments[] = $pending_payment;
}
}
} // end if;
} // end foreach;
$message = !empty($pending_payments) ? __('You have pending payments on your account!', 'wp-ultimo') : __('You do not have pending payments on your account!', 'wp-ultimo');
$message = ! empty($pending_payments) ? __('You have pending payments on your account!', 'wp-ultimo') : __('You do not have pending payments on your account!', 'wp-ultimo');
/**
* Allow user to change the message about the pending payments.
@ -269,7 +248,6 @@ class Payment_Manager extends Base_Manager {
);
foreach ($pending_payments as $payment) {
$slug = $payment->get_hash();
$url = $payment->get_payment_url();
@ -283,18 +261,20 @@ class Payment_Manager extends Base_Manager {
'title' => $title,
'desc' => $html,
);
}
} // end foreach;
$form = new \WP_Ultimo\UI\Form('pending-payments', $fields, array(
'views' => 'admin-pages/fields',
'classes' => 'wu-modal-form wu-widget-list wu-striped wu-m-0 wu-mt-0',
'field_wrapper_classes' => 'wu-w-full wu-box-border wu-items-center wu-flex wu-justify-between wu-p-4 wu-m-0 wu-border-t wu-border-l-0 wu-border-r-0 wu-border-b-0 wu-border-gray-300 wu-border-solid',
));
$form = new \WP_Ultimo\UI\Form(
'pending-payments',
$fields,
array(
'views' => 'admin-pages/fields',
'classes' => 'wu-modal-form wu-widget-list wu-striped wu-m-0 wu-mt-0',
'field_wrapper_classes' => 'wu-w-full wu-box-border wu-items-center wu-flex wu-justify-between wu-p-4 wu-m-0 wu-border-t wu-border-l-0 wu-border-r-0 wu-border-b-0 wu-border-gray-300 wu-border-solid',
)
);
$form->render();
} // end render_pending_payments;
}
/**
* Adds an init endpoint to render the invoices.
@ -309,19 +289,16 @@ class Payment_Manager extends Base_Manager {
/*
* Validates nonce.
*/
if (!wp_verify_nonce(wu_request('key'), 'see_invoice')) {
if ( ! wp_verify_nonce(wu_request('key'), 'see_invoice')) {
// wp_die(__('You do not have permissions to access this file.', 'wp-ultimo'));
} // end if;
}
$payment = wu_get_payment_by_hash(wu_request('reference'));
if (!$payment) {
if ( ! $payment) {
wp_die(__('This invoice does not exist.', 'wp-ultimo'));
} // end if;
}
$invoice = new Invoice($payment);
@ -331,10 +308,8 @@ class Payment_Manager extends Base_Manager {
$invoice->print_file();
exit;
} // end if;
} // end invoice_viewer;
}
}
/**
* Transfer a payment from a user to another.
@ -353,11 +328,9 @@ class Payment_Manager extends Base_Manager {
$target_customer = wu_get_customer($target_customer_id);
if (!$payment || !$target_customer || $payment->get_customer_id() === $target_customer->get_id()) {
if ( ! $payment || ! $target_customer || $payment->get_customer_id() === $target_customer->get_id()) {
return new \WP_Error('error', __('An unexpected error happened.', 'wp-ultimo'));
} // end if;
}
$wpdb->query('START TRANSACTION');
@ -371,26 +344,20 @@ class Payment_Manager extends Base_Manager {
$saved = $payment->save();
if (is_wp_error($saved)) {
$wpdb->query('ROLLBACK');
return $saved;
} // end if;
}
} catch (\Throwable $e) {
$wpdb->query('ROLLBACK');
return new \WP_Error('exception', $e->getMessage());
} // end try;
}
$wpdb->query('COMMIT');
return true;
} // end async_transfer_payment;
}
/**
* Delete a payment.
@ -406,11 +373,9 @@ class Payment_Manager extends Base_Manager {
$payment = wu_get_payment($payment_id);
if (!$payment) {
if ( ! $payment) {
return new \WP_Error('error', __('An unexpected error happened.', 'wp-ultimo'));
} // end if;
}
$wpdb->query('START TRANSACTION');
@ -422,26 +387,20 @@ class Payment_Manager extends Base_Manager {
$saved = $payment->delete();
if (is_wp_error($saved)) {
$wpdb->query('ROLLBACK');
return $saved;
} // end if;
}
} catch (\Throwable $e) {
$wpdb->query('ROLLBACK');
return new \WP_Error('exception', $e->getMessage());
} // end try;
}
$wpdb->query('COMMIT');
return true;
} // end async_delete_payment;
}
/**
* Watches the change in payment status to take action when needed.
@ -459,19 +418,15 @@ class Payment_Manager extends Base_Manager {
'completed',
);
if (!in_array($new_status, $completable_statuses, true)) {
if ( ! in_array($new_status, $completable_statuses, true)) {
return;
} // end if;
}
$payment = wu_get_payment($payment_id);
if (!$payment || $payment->get_saved_invoice_number()) {
if ( ! $payment || $payment->get_saved_invoice_number()) {
return;
} // end if;
}
$current_invoice_number = absint(wu_get_setting('next_invoice_number', 1));
@ -480,7 +435,5 @@ class Payment_Manager extends Base_Manager {
$payment->save();
return wu_save_setting('next_invoice_number', $current_invoice_number + 1);
} // end transition_payment_status;
} // end class Payment_Manager;
}
}

View File

@ -24,7 +24,9 @@ defined('ABSPATH') || exit;
*/
class Product_Manager extends Base_Manager {
use \WP_Ultimo\Apis\Rest_Api, \WP_Ultimo\Apis\WP_CLI, \WP_Ultimo\Traits\Singleton;
use \WP_Ultimo\Apis\Rest_Api;
use \WP_Ultimo\Apis\WP_CLI;
use \WP_Ultimo\Traits\Singleton;
/**
* The manager slug.
@ -53,7 +55,5 @@ class Product_Manager extends Base_Manager {
$this->enable_rest_api();
$this->enable_wp_cli();
} // end init;
} // end class Product_Manager;
}
}

View File

@ -90,8 +90,7 @@ class Signup_Fields_Manager extends Base_Manager {
* @return array
*/
return apply_filters('wu_checkout_field_types', $field_types);
} // end get_field_types;
}
/**
* Instantiate a field type.
@ -104,8 +103,7 @@ class Signup_Fields_Manager extends Base_Manager {
public function instantiate_field_type($class_name) {
return new $class_name();
} // end instantiate_field_type;
}
/**
* Returns an array with all fields, instantiated.
@ -116,14 +114,11 @@ class Signup_Fields_Manager extends Base_Manager {
public function get_instantiated_field_types() {
if ($this->instantiated_field_types === null) {
$this->instantiated_field_types = array_map(array($this, 'instantiate_field_type'), $this->get_field_types());
} // end if;
}
return $this->instantiated_field_types;
} // end get_instantiated_field_types;
}
/**
* Returns a list of all the required fields that must be present on a CF.
@ -138,8 +133,7 @@ class Signup_Fields_Manager extends Base_Manager {
$fields = array_filter($fields, fn($item) => $item->is_required());
return $fields;
} // end get_required_fields;
}
/**
* Returns a list of all the user fields.
@ -154,8 +148,7 @@ class Signup_Fields_Manager extends Base_Manager {
$fields = array_filter($fields, fn($item) => $item->is_user_field());
return $fields;
} // end get_user_fields;
}
/**
* Returns a list of all the site fields.
@ -170,8 +163,7 @@ class Signup_Fields_Manager extends Base_Manager {
$fields = array_filter($fields, fn($item) => $item->is_site_field());
return $fields;
} // end get_site_fields;
}
/**
* Returns a list of all editor fields registered.
@ -186,13 +178,9 @@ class Signup_Fields_Manager extends Base_Manager {
$field_types = $this->get_instantiated_field_types();
foreach ($field_types as $field_type) {
$all_editor_fields = array_merge($all_editor_fields, $field_class->get_fields());
} // end foreach;
}
return $all_editor_fields;
} // end get_all_editor_fields;
} // end class Signup_Fields_Manager;
}
}

View File

@ -11,10 +11,10 @@
namespace WP_Ultimo\Managers;
use \WP_Ultimo\Managers\Base_Manager;
use \WP_Ultimo\Helpers\Screenshot;
use \WP_Ultimo\Database\Sites\Site_Type;
use \WP_Ultimo\Database\Memberships\Membership_Status;
use WP_Ultimo\Managers\Base_Manager;
use WP_Ultimo\Helpers\Screenshot;
use WP_Ultimo\Database\Sites\Site_Type;
use WP_Ultimo\Database\Memberships\Membership_Status;
// Exit if accessed directly
defined('ABSPATH') || exit;
@ -26,7 +26,9 @@ defined('ABSPATH') || exit;
*/
class Site_Manager extends Base_Manager {
use \WP_Ultimo\Apis\Rest_Api, \WP_Ultimo\Apis\WP_CLI, \WP_Ultimo\Traits\Singleton;
use \WP_Ultimo\Apis\Rest_Api;
use \WP_Ultimo\Apis\WP_CLI;
use \WP_Ultimo\Traits\Singleton;
/**
* The manager slug.
@ -97,8 +99,7 @@ class Site_Manager extends Base_Manager {
add_filter('wpmu_validate_blog_signup', array($this, 'allow_hyphens_in_site_name'), 10, 1);
add_action('wu_daily', array($this, 'delete_pending_sites'));
} // end init;
}
/**
* Allows for hyphens to be used, since WordPress supports it.
@ -123,27 +124,20 @@ class Site_Manager extends Base_Manager {
* if so, we remove it and re-validate with our custom rule
* which is the same, but also allows for hyphens.
*/
if (!empty($blogname_errors) && $error_key !== false) {
unset($result['errors']->errors['blogname'][$error_key]);
if ( ! empty($blogname_errors) && $error_key !== false) {
unset($result['errors']->errors['blogname'][ $error_key ]);
if (empty($result['errors']->errors['blogname'])) {
unset($result['errors']->errors['blogname']);
} // end if;
}
if (preg_match('/[^a-z0-9-]+/', (string) $result['blogname'])) {
$result['errors']->add('blogname', __('Site names can only contain lowercase letters (a-z), numbers, and hyphens.', 'wp-ultimo'));
} // end if;
} // end if;
}
}
return $result;
} // end allow_hyphens_in_site_name;
}
/**
* Handles the request to add a new site, if that's the case.
@ -158,8 +152,7 @@ class Site_Manager extends Base_Manager {
global $wpdb;
if (wu_request('create-new-site') && wp_verify_nonce(wu_request('create-new-site'), 'create-new-site')) {
$errors = new \WP_Error;
$errors = new \WP_Error();
$rules = array(
'site_title' => 'min:4',
@ -167,73 +160,57 @@ class Site_Manager extends Base_Manager {
);
if ($checkout->is_last_step()) {
$membership = WP_Ultimo()->currents->get_membership();
$customer = wu_get_current_customer();
if (!$customer || !$membership || $customer->get_id() !== $membership->get_customer_id()) {
if ( ! $customer || ! $membership || $customer->get_id() !== $membership->get_customer_id()) {
$errors->add('not-owner', __('You do not have the necessary permissions to create a site to this membership', 'wp-ultimo'));
} // end if;
}
if ($errors->has_errors() === false) {
$d = wu_get_site_domain_and_path(wu_request('site_url', ''), $checkout->request_or_session('site_domain'));
$pending_site = $membership->create_pending_site(array(
'domain' => $d->domain,
'path' => $d->path,
'template_id' => $checkout->request_or_session('template_id'),
'title' => $checkout->request_or_session('site_title'),
'customer_id' => $customer->get_id(),
'membership_id' => $membership->get_id(),
));
$pending_site = $membership->create_pending_site(
array(
'domain' => $d->domain,
'path' => $d->path,
'template_id' => $checkout->request_or_session('template_id'),
'title' => $checkout->request_or_session('site_title'),
'customer_id' => $customer->get_id(),
'membership_id' => $membership->get_id(),
)
);
if (is_wp_error($pending_site)) {
wp_send_json_error($pending_site);
exit;
} // end if;
}
$results = $membership->publish_pending_site();
if (is_wp_error($results)) {
wp_send_json_error($errors);
} // end if;
}
} else {
wp_send_json_error($errors);
} // end if;
}
wp_send_json_success(array());
} else {
$validation = $checkout->validate($rules);
if (is_wp_error($validation)) {
wp_send_json_error($validation);
} // end if;
}
$wpdb->query('COMMIT');
wp_send_json_success(array());
} // end if;
} // end if;
} // end maybe_validate_add_new_site;
}
}
}
/**
* Checks if the current request is a add new site request.
@ -244,20 +221,20 @@ class Site_Manager extends Base_Manager {
public function maybe_add_new_site() {
if (wu_request('create-new-site') && wp_verify_nonce(wu_request('create-new-site'), 'create-new-site')) {
$redirect_url = wu_request('redirect_url', admin_url('admin.php?page=sites'));
$redirect_url = add_query_arg(array(
'new_site_created' => true,
), $redirect_url);
$redirect_url = add_query_arg(
array(
'new_site_created' => true,
),
$redirect_url
);
wp_redirect($redirect_url);
exit;
} // end if;
} // end maybe_add_new_site;
}
}
/**
* Triggers the do_event of the site publish successful.
@ -277,8 +254,7 @@ class Site_Manager extends Base_Manager {
);
wu_do_event('site_published', $payload);
} // end handle_site_published;
}
/**
* Locks the site front-end if the site is not public.
@ -291,10 +267,8 @@ class Site_Manager extends Base_Manager {
public function lock_site() {
if (is_main_site() || is_admin() || wu_is_login_page() || wp_doing_ajax() || wu_request('wu-ajax')) {
return;
} // end if;
}
$can_access = true;
@ -302,11 +276,9 @@ class Site_Manager extends Base_Manager {
$site = wu_get_current_site();
if (!$site->is_active()) {
if ( ! $site->is_active()) {
$can_access = false;
} // end if;
}
$membership = $site->get_membership();
@ -314,7 +286,7 @@ class Site_Manager extends Base_Manager {
$is_cancelled = $status === Membership_Status::CANCELLED;
$is_inactive = $status && !$membership->is_active() && $status !== Membership_Status::TRIALING;
$is_inactive = $status && ! $membership->is_active() && $status !== Membership_Status::TRIALING;
if ($is_cancelled || ($is_inactive && wu_get_setting('block_frontend', false))) {
@ -324,40 +296,36 @@ class Site_Manager extends Base_Manager {
$expiration_time = wu_date($membership->get_date_expiration())->getTimestamp() + $grace_period * DAY_IN_SECONDS;
if ($expiration_time < wu_date()->getTimestamp()) {
$checkout_pages = \WP_Ultimo\Checkout\Checkout_Pages::get_instance();
// We only show the url field when block_frontend is true
$redirect_url = wu_get_setting('block_frontend', false) ? $checkout_pages->get_page_url('block_frontend') : false;
$can_access = false;
} // end if;
} // end if;
}
}
if ($can_access === false) {
if ($redirect_url) {
wp_redirect($redirect_url);
exit;
}
} // end if;
wp_die(new \WP_Error(
'not-available',
wp_die(
new \WP_Error(
'not-available',
// phpcs:ignore
sprintf( __('This site is not available at the moment.<br><small>If you are the site admin, click <a href="%s">here</a> to login.</small>', 'wp-ultimo'), wp_login_url()),
array(
'title' => __('Site not available', 'wp-ultimo'),
)
), '', array('code' => 200));
} // end if;
} // end lock_site;
array(
'title' => __('Site not available', 'wp-ultimo'),
)
),
'',
array('code' => 200)
);
}
}
/**
* Takes screenshots asynchronously.
@ -371,27 +339,22 @@ class Site_Manager extends Base_Manager {
$site = wu_get_site($site_id);
if (!$site) {
if ( ! $site) {
return false;
} // end if;
}
$domain = $site->get_active_site_url();
$attachment_id = Screenshot::take_screenshot($domain);
if (!$attachment_id) {
if ( ! $attachment_id) {
return false;
} // end if;
}
$site->set_featured_image_id($attachment_id);
return $site->save();
} // end async_get_site_screenshot;
}
/**
* Listens for the ajax endpoint and generate the screenshot.
@ -405,34 +368,31 @@ class Site_Manager extends Base_Manager {
$site = wu_get_site($site_id);
if (!$site) {
if ( ! $site) {
wp_send_json_error(
new \WP_Error('missing-site', __('Site not found.', 'wp-ultimo'))
);
} // end if;
}
$domain = $site->get_active_site_url();
$attachment_id = Screenshot::take_screenshot($domain);
if (!$attachment_id) {
if ( ! $attachment_id) {
wp_send_json_error(
new \WP_Error('error', __('We were not able to fetch the screenshot.', 'wp-ultimo'))
);
} // end if;
}
$attachment_url = wp_get_attachment_image_src($attachment_id, 'wu-thumb-medium');
wp_send_json_success(array(
'attachment_id' => $attachment_id,
'attachment_url' => $attachment_url[0],
));
} // end get_site_screenshot;
wp_send_json_success(
array(
'attachment_id' => $attachment_id,
'attachment_url' => $attachment_url[0],
)
);
}
/**
* Add the additional sizes required by WP Multisite WaaS.
@ -445,14 +405,12 @@ class Site_Manager extends Base_Manager {
public function additional_thumbnail_sizes() {
if (is_main_site()) {
add_image_size('wu-thumb-large', 900, 675, array('center', 'top')); // (cropped)
add_image_size('wu-thumb-medium', 400, 300, array('center', 'top')); // (cropped)
} // end if;
} // end additional_thumbnail_sizes;
}
}
/**
* Adds a notification if the no-index setting is active.
@ -463,12 +421,9 @@ class Site_Manager extends Base_Manager {
public function add_no_index_warning() {
if (wu_get_setting('stop_template_indexing', false)) {
add_meta_box('wu-warnings', __('WP Multisite WaaS - Search Engines', 'wp-ultimo'), array($this, 'render_no_index_warning'), 'dashboard-network', 'normal', 'high');
} // end if;
} // end add_no_index_warning;
}
}
/**
* Renders the no indexing warning.
@ -491,8 +446,7 @@ class Site_Manager extends Base_Manager {
</div>
<?php // phpcs:enable
} // end render_no_index_warning;
}
/**
* Prevents Search Engines from indexing Site Templates.
@ -502,29 +456,21 @@ class Site_Manager extends Base_Manager {
*/
public function prevent_site_template_indexing() {
if (!wu_get_setting('stop_template_indexing', false)) {
if ( ! wu_get_setting('stop_template_indexing', false)) {
return;
} // end if;
}
$site = wu_get_current_site();
if ($site && $site->get_type() === Site_Type::SITE_TEMPLATE) {
if (function_exists('wp_robots_no_robots')) {
add_filter('wp_robots', 'wp_robots_no_robots'); // WordPress 5.7+
} else {
wp_no_robots();
} // end if;
} // end if;
} // end prevent_site_template_indexing;
}
}
}
/**
* Check if sub-site has a custom logo and change login logo.
@ -535,23 +481,17 @@ class Site_Manager extends Base_Manager {
*/
public function custom_login_logo() {
if (!wu_get_setting('subsite_custom_login_logo', false) || !has_custom_logo()) {
if ( ! wu_get_setting('subsite_custom_login_logo', false) || ! has_custom_logo()) {
$logo = wu_get_network_logo();
} else {
$logo = wp_get_attachment_image_src(get_theme_mod('custom_logo'), 'full');
$logo = wu_get_isset($logo, 0, false);
} // end if;
}
if (empty($logo)) {
return;
} // end if;
}
// phpcs:disable
@ -568,8 +508,7 @@ class Site_Manager extends Base_Manager {
</style>
<?php // phpcs:enable
} // end custom_login_logo;
}
/**
* Replaces the WordPress url with the site url.
@ -580,8 +519,7 @@ class Site_Manager extends Base_Manager {
public function login_header_url() {
return get_site_url();
} // end login_header_url;
}
/**
* Replaces the WordPress text with the site name.
@ -592,8 +530,7 @@ class Site_Manager extends Base_Manager {
public function login_header_text() {
return get_bloginfo('name');
} // end login_header_text;
}
/**
* Add notices to default site page, recommending the WP Multisite WaaS option.
@ -605,20 +542,28 @@ class Site_Manager extends Base_Manager {
$notice = __('Hey there! We highly recommend managing your network sites using the WP Multisite WaaS &rarr; Sites page. <br>If you want to avoid confusion, you can also hide this page from the admin panel completely on the WP Multisite WaaS &rarr; Settings &rarr; Whitelabel options.', 'wp-ultimo');
WP_Ultimo()->notices->add($notice, 'info', 'network-admin', 'wu-sites-use-wp-ultimo', array(
WP_Ultimo()->notices->add(
$notice,
'info',
'network-admin',
'wu-sites-use-wp-ultimo',
array(
'title' => __('Go to the WP Multisite WaaS Sites page &rarr;', 'wp-ultimo'),
'url' => wu_network_admin_url('wp-ultimo-sites'),
),
array(
'title' => __('Go to the Whitelabel Settings &rarr;', 'wp-ultimo'),
'url' => wu_network_admin_url('wp-ultimo-settings', array(
'tab' => 'whitelabel',
)),
),
));
} // end add_notices_to_default_site_page;
array(
'title' => __('Go to the WP Multisite WaaS Sites page &rarr;', 'wp-ultimo'),
'url' => wu_network_admin_url('wp-ultimo-sites'),
),
array(
'title' => __('Go to the Whitelabel Settings &rarr;', 'wp-ultimo'),
'url' => wu_network_admin_url(
'wp-ultimo-settings',
array(
'tab' => 'whitelabel',
)
),
),
)
);
}
/**
* Add search and replace filter to be used on site duplication.
@ -638,8 +583,7 @@ class Site_Manager extends Base_Manager {
$final_list = array_merge($search_and_replace, $additional_duplication);
return $this->filter_illegal_search_keys($final_list);
} // end search_and_replace_on_duplication;
}
/**
* Get search and replace settings
@ -654,18 +598,13 @@ class Site_Manager extends Base_Manager {
$pairs = array();
foreach ($search_and_replace as $item) {
if ((isset($item['search']) && !empty($item['search'])) && isset($item['replace'])) {
$pairs[$item['search']] = $item['replace'];
} // end if;
} // end foreach;
if ((isset($item['search']) && ! empty($item['search'])) && isset($item['replace'])) {
$pairs[ $item['search'] ] = $item['replace'];
}
}
return $pairs;
} // end get_search_and_replace_settings;
}
/**
* Handles search and replace for new blogs from WordPress.
@ -679,11 +618,9 @@ class Site_Manager extends Base_Manager {
$to_site_id = $site->get_id();
if (!$to_site_id) {
if ( ! $to_site_id) {
return;
} // end if;
}
/**
* In order to be backwards compatible here, we'll have to do some crazy stuff,
@ -706,46 +643,33 @@ class Site_Manager extends Base_Manager {
$results = \MUCD_Data::do_sql_query('SHOW TABLES LIKE \'' . $to_blog_prefix_like . '%\'', 'col', false);
foreach ($results as $k => $v) {
$tables[str_replace($to_blog_prefix, '', (string) $v)] = array();
} // end foreach;
$tables[ str_replace($to_blog_prefix, '', (string) $v) ] = array();
}
foreach ( $tables as $table => $col) {
$results = \MUCD_Data::do_sql_query('SHOW COLUMNS FROM `' . $to_blog_prefix . $table . '`', 'col', false);
$columns = array();
foreach ($results as $k => $v) {
$columns[] = $v;
}
} // end foreach;
$tables[$table] = $columns;
} // end foreach;
$tables[ $table ] = $columns;
}
$default_tables = \MUCD_Option::get_fields_to_update();
foreach ($default_tables as $table => $field) {
$tables[$table] = $field;
} // end foreach;
$tables[ $table ] = $field;
}
foreach ($tables as $table => $field) {
foreach ($string_to_replace as $from_string => $to_string) {
\MUCD_Data::update($to_blog_prefix . $table, $field, $from_string, $to_string);
} // end foreach;
} // end foreach;
} // end search_and_replace_for_new_site;
}
}
}
/**
* Makes sure the search and replace array have no illegal values, such as null, false, etc
*
@ -754,9 +678,8 @@ class Site_Manager extends Base_Manager {
*/
public function filter_illegal_search_keys($search_and_replace): array {
return array_filter($search_and_replace, fn($k) => !is_null($k) && $k !== false && !empty($k), ARRAY_FILTER_USE_KEY);
} // end filter_illegal_search_keys;
return array_filter($search_and_replace, fn($k) => ! is_null($k) && $k !== false && ! empty($k), ARRAY_FILTER_USE_KEY);
}
/**
* Handle the deletion of pending sites.
@ -771,7 +694,6 @@ class Site_Manager extends Base_Manager {
public function handle_delete_pending_sites($action, $model, $ids) {
foreach ($ids as $membership_id) {
$membership = wu_get_membership($membership_id);
if (empty($membership)) {
@ -782,18 +704,17 @@ class Site_Manager extends Base_Manager {
delete_metadata('wu_membership', $membership_id, 'pending_site');
continue;
} // end if;
}
$membership->delete_pending_site();
}
} // end foreach;
wp_send_json_success(array(
'redirect_url' => add_query_arg('deleted', count($ids), wu_get_current_url()),
));
} // end handle_delete_pending_sites;
wp_send_json_success(
array(
'redirect_url' => add_query_arg('deleted', count($ids), wu_get_current_url()),
)
);
}
/**
* Hide the super admin user from the sub-site table list.
@ -805,15 +726,12 @@ class Site_Manager extends Base_Manager {
*/
public function hide_super_admin_from_list($args) {
if (!is_super_admin()) {
if ( ! is_super_admin()) {
$args['login__not_in'] = get_super_admins();
} // end if;
}
return $args;
} // end hide_super_admin_from_list;
}
/**
* Hides customer sites from the super admin user on listing.
@ -829,60 +747,46 @@ class Site_Manager extends Base_Manager {
global $wpdb;
if (!is_super_admin()) {
if ( ! is_super_admin()) {
return $sites;
} // end if;
}
$keys = get_user_meta($user_id);
if (empty($keys)) {
return $sites;
} // end if;
}
// List the main site at beginning of array.
if (isset($keys[$wpdb->base_prefix . 'capabilities']) && defined('MULTISITE')) {
if (isset($keys[ $wpdb->base_prefix . 'capabilities' ]) && defined('MULTISITE')) {
$site_ids[] = 1;
unset($keys[$wpdb->base_prefix . 'capabilities']);
} // end if;
unset($keys[ $wpdb->base_prefix . 'capabilities' ]);
}
$keys = array_keys($keys);
foreach ($keys as $key) {
if (substr_compare($key, 'capabilities', -strlen('capabilities')) !== 0) {
continue;
} // end if;
}
if ($wpdb->base_prefix && strncmp($key, (string) $wpdb->base_prefix, strlen((string) $wpdb->base_prefix)) !== 0) {
continue;
} // end if;
}
$site_id = str_replace(array($wpdb->base_prefix, '_capabilities'), '', $key);
if (!is_numeric($site_id)) {
if ( ! is_numeric($site_id)) {
continue;
} // end if;
}
$site_ids[] = (int) $site_id;
} // end foreach;
}
$sites = array();
if (!empty($site_ids)) {
if ( ! empty($site_ids)) {
/**
* Here we change the default WP behavior to filter
@ -908,13 +812,11 @@ class Site_Manager extends Base_Manager {
),
);
if (!$all) {
if ( ! $all) {
$args['archived'] = 0;
$args['spam'] = 0;
$args['deleted'] = 0;
} // end if;
}
$_sites = array_merge(
array(
@ -924,14 +826,11 @@ class Site_Manager extends Base_Manager {
);
foreach ($_sites as $site) {
if (!$site) {
if ( ! $site) {
continue;
}
} // end if;
$sites[$site->id] = (object) array(
$sites[ $site->id ] = (object) array(
'userblog_id' => $site->id,
'blogname' => $site->blogname,
'domain' => $site->domain,
@ -943,10 +842,8 @@ class Site_Manager extends Base_Manager {
'spam' => $site->spam,
'deleted' => $site->deleted,
);
} // end foreach;
} // end if;
}
}
/**
* Replicates the original WP Filter here, for good measure.
@ -961,8 +858,7 @@ class Site_Manager extends Base_Manager {
* those marked 'deleted', 'archived', or 'spam'. Default false.
*/
return apply_filters('get_blogs_of_user', $sites, $user_id, $all); // phpcs:ignore
} // end hide_customer_sites_from_super_admin_list;
}
/**
* Delete pending sites from non-pending memberships
@ -974,12 +870,9 @@ class Site_Manager extends Base_Manager {
$pending_sites = \WP_Ultimo\Models\Site::get_all_by_type('pending');
foreach ($pending_sites as $site) {
if ($site->is_publishing()) {
continue;
} // end if;
}
$membership = $site->get_membership();
@ -987,15 +880,9 @@ class Site_Manager extends Base_Manager {
// Check if the last modify has more than some time, to avoid the deletion of sites on creation process
if ($membership->get_date_modified() < gmdate('Y-m-d H:i:s', strtotime('-1 days'))) {
$membership->delete_pending_site();
} // end if;
} // end if;
} // end foreach;
} // end delete_pending_sites;
} // end class Site_Manager;
}
}
}
}
}

View File

@ -32,10 +32,9 @@ class Visits_Manager {
public function init() {
if ((bool) wu_get_setting('enable_visits_limiting', true) === false || is_main_site()) {
return; // Feature not active, bail.
} // end if;
}
/*
* Due to how caching plugins work, we need to count visits via ajax.
@ -46,8 +45,7 @@ class Visits_Manager {
add_action('wp_enqueue_scripts', array($this, 'enqueue_visit_counter_script'));
add_action('template_redirect', array($this, 'maybe_lock_site'));
} // end init;
}
/**
* Check if the limits for visits was set. If that's the case, lock the site.
@ -59,28 +57,21 @@ class Visits_Manager {
$site = wu_get_current_site();
if (!$site) {
if ( ! $site) {
return;
} // end if;
}
/*
* Case unlimited visits
*/
if (empty($site->get_limitations()->visits->get_limit())) {
return;
} // end if;
}
if ($site->has_limitations() && $site->get_visits_count() > $site->get_limitations()->visits->get_limit()) {
wp_die(__('This site is not available at this time.', 'wp-ultimo'), __('Not available', 'wp-ultimo'), 404);
} // end if;
} // end maybe_lock_site;
}
}
/**
* Counts visits to network sites.
@ -98,18 +89,15 @@ class Visits_Manager {
public function count_visits() {
if (is_main_site() && is_admin()) {
return; // bail on main site.
} // end if;
}
$site = wu_get_current_site();
if ($site->get_type() !== 'customer_owned') {
return;
} // end if;
}
$visits_manager = new \WP_Ultimo\Objects\Visits($site->get_id());
@ -122,18 +110,15 @@ class Visits_Manager {
* Checks against the limitations.
*/
if (false) {
Cache_Manager::get_instance()->flush_known_caches();
echo 'flushing caches';
die('2');
} // end if;
}
die('1');
} // end count_visits;
}
/**
* Enqueues the visits count script when necessary.
@ -144,20 +129,21 @@ class Visits_Manager {
public function enqueue_visit_counter_script() {
if (is_user_logged_in()) {
return; // bail if user is logged in.
} // end if;
}
wp_register_script('wu-visits-counter', wu_get_asset('visits-counter.js', 'js'), array(), wu_get_version());
wp_localize_script('wu-visits-counter', 'wu_visits_counter', array(
'ajaxurl' => admin_url('admin-ajax.php'),
'code' => wp_create_nonce('wu-visit-counter'),
));
wp_localize_script(
'wu-visits-counter',
'wu_visits_counter',
array(
'ajaxurl' => admin_url('admin-ajax.php'),
'code' => wp_create_nonce('wu-visit-counter'),
)
);
wp_enqueue_script('wu-visits-counter');
} // end enqueue_visit_counter_script;
} // end class Visits_Manager;
}
}

View File

@ -25,7 +25,9 @@ defined('ABSPATH') || exit;
*/
class Webhook_Manager extends Base_Manager {
use \WP_Ultimo\Apis\Rest_Api, \WP_Ultimo\Apis\WP_CLI, \WP_Ultimo\Traits\Singleton;
use \WP_Ultimo\Apis\Rest_Api;
use \WP_Ultimo\Apis\WP_CLI;
use \WP_Ultimo\Traits\Singleton;
/**
* The manager slug.
@ -74,8 +76,7 @@ class Webhook_Manager extends Base_Manager {
add_action('init', array($this, 'register_webhook_listeners'));
add_action('wp_ajax_wu_send_test_event', array($this, 'send_test_event'));
} // end init;
}
/**
* Adds the listeners to the webhook callers, extend this by adding actions to wu_register_webhook_listeners
@ -86,12 +87,9 @@ class Webhook_Manager extends Base_Manager {
public function register_webhook_listeners() {
foreach (wu_get_event_types() as $key => $event) {
add_action('wu_event_' . $key, array($this, 'send_webhooks'));
} // end foreach;
} // end register_webhook_listeners;
}
}
/**
* Sends all the webhooks that are triggered by a specific event.
@ -106,18 +104,13 @@ class Webhook_Manager extends Base_Manager {
$webhooks = Webhook::get_all();
foreach ($webhooks as $webhook) {
if ('wu_event_' . $webhook->get_event() === current_filter()) {
$blocking = wu_get_setting('webhook_calls_blocking', false);
$this->send_webhook($webhook, $args, $blocking);
} // end if;
} // end foreach;
} // end send_webhooks;
}
}
}
/**
* Sends a specific webhook.
@ -132,30 +125,31 @@ class Webhook_Manager extends Base_Manager {
*/
public function send_webhook($webhook, $data, $blocking = true, $count = true) {
if (!$data) {
if ( ! $data) {
return;
}
} // end if;
$request = wp_remote_post($webhook->get_webhook_url(), array(
'method' => 'POST',
'timeout' => 45,
'redirection' => 5,
'headers' => array(
'Content-Type' => 'application/json',
$request = wp_remote_post(
$webhook->get_webhook_url(),
array(
'method' => 'POST',
'timeout' => 45,
'redirection' => 5,
'headers' => array(
'Content-Type' => 'application/json',
),
'cookies' => array(),
'body' => wp_json_encode($data),
'blocking' => $blocking,
),
'cookies' => array(),
'body' => wp_json_encode($data),
'blocking' => $blocking,
), current_filter(), $webhook);
current_filter(),
$webhook
);
if (is_wp_error($request)) {
$error_message = $request->get_error_message();
if ($count) {
$this->create_event(
$webhook->get_event(),
$webhook->get_id(),
@ -164,24 +158,19 @@ class Webhook_Manager extends Base_Manager {
$error_message,
true
);
} // end if;
}
return $error_message;
} // end if;
}
$response = '';
// if blocking, we have a response
if ($blocking) {
$response = wp_remote_retrieve_body($request);
} // end if;
}
if ($count) {
$this->create_event(
$webhook->get_event(),
$webhook->get_id(),
@ -194,12 +183,10 @@ class Webhook_Manager extends Base_Manager {
$webhook->set_event_count($new_count);
$webhook->save();
} // end if;
}
return $response;
} // end send_webhook;
}
/**
* Send a test event of the webhook
@ -208,14 +195,14 @@ class Webhook_Manager extends Base_Manager {
*/
public function send_test_event() {
if (!current_user_can('manage_network')) {
wp_send_json(array(
'response' => __('You do not have enough permissions to send a test event.', 'wp-ultimo'),
'webhooks' => Webhook::get_items_as_array(),
));
} // end if;
if ( ! current_user_can('manage_network')) {
wp_send_json(
array(
'response' => __('You do not have enough permissions to send a test event.', 'wp-ultimo'),
'webhooks' => Webhook::get_items_as_array(),
)
);
}
$event = wu_get_event_type($_POST['webhook_event']);
@ -229,12 +216,13 @@ class Webhook_Manager extends Base_Manager {
$response = $this->send_webhook($webhook, wu_maybe_lazy_load_payload($event['payload']), true, false);
wp_send_json(array(
'response' => htmlentities2($response),
'id' => wu_request('webhook_id')
));
} // end send_test_event;
wp_send_json(
array(
'response' => htmlentities2($response),
'id' => wu_request('webhook_id'),
)
);
}
/**
* Reads the log file and displays the content.
@ -262,34 +250,33 @@ class Webhook_Manager extends Base_Manager {
</style>
';
if (!current_user_can('manage_network')) {
if ( ! current_user_can('manage_network')) {
echo __('You do not have enough permissions to read the logs of this webhook.', 'wp-ultimo');
exit;
} // end if;
}
$id = absint($_REQUEST['id']);
$logs = array_map(function($line): string {
$logs = array_map(
function ($line): string {
$line = str_replace(' - ', ' </strong> - ', $line);
$line = str_replace(' - ', ' </strong> - ', $line);
$matches = array();
$matches = array();
$line = str_replace('\'', '\\\'', $line);
$line = preg_replace('~(\{(?:[^{}]|(?R))*\})~', '<pre><script>document.write(JSON.stringify(JSON.parse(\'${1}\'), null, 2));</script></pre>', $line);
$line = str_replace('\'', '\\\'', $line);
$line = preg_replace('~(\{(?:[^{}]|(?R))*\})~', '<pre><script>document.write(JSON.stringify(JSON.parse(\'${1}\'), null, 2));</script></pre>', $line);
return '<strong>' . $line . '<hr>';
}, Logger::read_lines("webhook-$id", 5));
return '<strong>' . $line . '<hr>';
},
Logger::read_lines("webhook-$id", 5)
);
echo implode('', $logs);
exit;
} // end serve_logs;
}
/**
* Log a webhook sent for later reference.
@ -308,15 +295,11 @@ class Webhook_Manager extends Base_Manager {
$message = sprintf('Sent a %s event to the URL %s with data: %s ', $event_name, $url, json_encode($data));
if (!$is_error) {
if ( ! $is_error) {
$message .= empty($response) ? sprintf('Got response: %s', $response) : 'To debug the remote server response, turn the "Wait for Response" option on the WP Multisite WaaS Settings > API & Webhooks Tab';
} else {
$message .= sprintf('Got error: %s', $response);
} // end if;
}
$event_data = array(
'object_id' => $id,
@ -328,7 +311,5 @@ class Webhook_Manager extends Base_Manager {
);
wu_create_event($event_data);
} // end create_event;
} // end class Webhook_Manager;
}
}