Convert variable names to camel case
[MAILPOET-1796]
This commit is contained in:
@ -44,18 +44,18 @@ class API {
|
||||
|
||||
public function __construct(
|
||||
ContainerInterface $container,
|
||||
AccessControl $access_control,
|
||||
AccessControl $accessControl,
|
||||
SettingsController $settings,
|
||||
WPFunctions $wp
|
||||
) {
|
||||
$this->container = $container;
|
||||
$this->access_control = $access_control;
|
||||
$this->accessControl = $accessControl;
|
||||
$this->settings = $settings;
|
||||
$this->wp = $wp;
|
||||
foreach ($this->_available_api_versions as $available_api_version) {
|
||||
foreach ($this->availableApiVersions as $availableApiVersion) {
|
||||
$this->addEndpointNamespace(
|
||||
sprintf('%s\%s', __NAMESPACE__, $available_api_version),
|
||||
$available_api_version
|
||||
sprintf('%s\%s', __NAMESPACE__, $availableApiVersion),
|
||||
$availableApiVersion
|
||||
);
|
||||
}
|
||||
}
|
||||
@ -91,62 +91,62 @@ class API {
|
||||
|
||||
$ignoreToken = (
|
||||
$this->settings->get('captcha.type') != Captcha::TYPE_DISABLED &&
|
||||
$this->_request_endpoint === 'subscribers' &&
|
||||
$this->_request_method === 'subscribe'
|
||||
$this->requestEndpoint === 'subscribers' &&
|
||||
$this->requestMethod === 'subscribe'
|
||||
);
|
||||
|
||||
if (!$ignoreToken && $this->checkToken() === false) {
|
||||
$error_message = WPFunctions::get()->__("Sorry, but we couldn't connect to the MailPoet server. Please refresh the web page and try again.", 'mailpoet');
|
||||
$error_response = $this->createErrorResponse(Error::UNAUTHORIZED, $error_message, Response::STATUS_UNAUTHORIZED);
|
||||
return $error_response->send();
|
||||
$errorMessage = WPFunctions::get()->__("Sorry, but we couldn't connect to the MailPoet server. Please refresh the web page and try again.", 'mailpoet');
|
||||
$errorResponse = $this->createErrorResponse(Error::UNAUTHORIZED, $errorMessage, Response::STATUS_UNAUTHORIZED);
|
||||
return $errorResponse->send();
|
||||
}
|
||||
|
||||
$response = $this->processRoute();
|
||||
$response->send();
|
||||
}
|
||||
|
||||
public function setRequestData($data, $request_type) {
|
||||
$this->_request_api_version = !empty($data['api_version']) ? $data['api_version'] : false;
|
||||
public function setRequestData($data, $requestType) {
|
||||
$this->requestApiVersion = !empty($data['api_version']) ? $data['api_version'] : false;
|
||||
|
||||
$this->_request_endpoint = isset($data['endpoint'])
|
||||
$this->requestEndpoint = isset($data['endpoint'])
|
||||
? Helpers::underscoreToCamelCase(trim($data['endpoint']))
|
||||
: null;
|
||||
|
||||
// JS part of /wp-admin/customize.php does not like a 'method' field in a form widget
|
||||
$method_param_name = isset($data['mailpoet_method']) ? 'mailpoet_method' : 'method';
|
||||
$this->_request_method = isset($data[$method_param_name])
|
||||
? Helpers::underscoreToCamelCase(trim($data[$method_param_name]))
|
||||
$methodParamName = isset($data['mailpoet_method']) ? 'mailpoet_method' : 'method';
|
||||
$this->requestMethod = isset($data[$methodParamName])
|
||||
? Helpers::underscoreToCamelCase(trim($data[$methodParamName]))
|
||||
: null;
|
||||
$this->_request_type = $request_type;
|
||||
$this->requestType = $requestType;
|
||||
|
||||
$this->_request_token = isset($data['token'])
|
||||
$this->requestToken = isset($data['token'])
|
||||
? trim($data['token'])
|
||||
: null;
|
||||
|
||||
if (!$this->_request_endpoint || !$this->_request_method || !$this->_request_api_version) {
|
||||
$error_message = WPFunctions::get()->__('Invalid API request.', 'mailpoet');
|
||||
$error_response = $this->createErrorResponse(Error::BAD_REQUEST, $error_message, Response::STATUS_BAD_REQUEST);
|
||||
return $error_response;
|
||||
} else if (!empty($this->_endpoint_namespaces[$this->_request_api_version])) {
|
||||
foreach ($this->_endpoint_namespaces[$this->_request_api_version] as $namespace) {
|
||||
$endpoint_class = sprintf(
|
||||
if (!$this->requestEndpoint || !$this->requestMethod || !$this->requestApiVersion) {
|
||||
$errorMessage = WPFunctions::get()->__('Invalid API request.', 'mailpoet');
|
||||
$errorResponse = $this->createErrorResponse(Error::BAD_REQUEST, $errorMessage, Response::STATUS_BAD_REQUEST);
|
||||
return $errorResponse;
|
||||
} else if (!empty($this->endpointNamespaces[$this->requestApiVersion])) {
|
||||
foreach ($this->endpointNamespaces[$this->requestApiVersion] as $namespace) {
|
||||
$endpointClass = sprintf(
|
||||
'%s\%s',
|
||||
$namespace,
|
||||
ucfirst($this->_request_endpoint)
|
||||
ucfirst($this->requestEndpoint)
|
||||
);
|
||||
if ($this->container->has($endpoint_class)) {
|
||||
$this->_request_endpoint_class = $endpoint_class;
|
||||
if ($this->container->has($endpointClass)) {
|
||||
$this->requestEndpointClass = $endpointClass;
|
||||
break;
|
||||
}
|
||||
}
|
||||
$this->_request_data = isset($data['data'])
|
||||
$this->requestData = isset($data['data'])
|
||||
? WPFunctions::get()->stripslashesDeep($data['data'])
|
||||
: [];
|
||||
|
||||
// remove reserved keywords from data
|
||||
if (is_array($this->_request_data) && !empty($this->_request_data)) {
|
||||
if (is_array($this->requestData) && !empty($this->requestData)) {
|
||||
// filter out reserved keywords from data
|
||||
$reserved_keywords = [
|
||||
$reservedKeywords = [
|
||||
'token',
|
||||
'endpoint',
|
||||
'method',
|
||||
@ -154,9 +154,9 @@ class API {
|
||||
'mailpoet_method', // alias of 'method'
|
||||
'mailpoet_redirect',
|
||||
];
|
||||
$this->_request_data = array_diff_key(
|
||||
$this->_request_data,
|
||||
array_flip($reserved_keywords)
|
||||
$this->requestData = array_diff_key(
|
||||
$this->requestData,
|
||||
array_flip($reservedKeywords)
|
||||
);
|
||||
}
|
||||
}
|
||||
@ -164,54 +164,54 @@ class API {
|
||||
|
||||
public function processRoute() {
|
||||
try {
|
||||
if (empty($this->_request_endpoint_class) ||
|
||||
!$this->container->has($this->_request_endpoint_class)
|
||||
if (empty($this->requestEndpointClass) ||
|
||||
!$this->container->has($this->requestEndpointClass)
|
||||
) {
|
||||
throw new \Exception(__('Invalid API endpoint.', 'mailpoet'));
|
||||
}
|
||||
|
||||
$endpoint = $this->container->get($this->_request_endpoint_class);
|
||||
if (!method_exists($endpoint, $this->_request_method)) {
|
||||
$endpoint = $this->container->get($this->requestEndpointClass);
|
||||
if (!method_exists($endpoint, $this->requestMethod)) {
|
||||
throw new \Exception(__('Invalid API endpoint method.', 'mailpoet'));
|
||||
}
|
||||
|
||||
if (!$endpoint->isMethodAllowed($this->_request_method, $this->_request_type)) {
|
||||
if (!$endpoint->isMethodAllowed($this->requestMethod, $this->requestType)) {
|
||||
throw new \Exception(__('HTTP request method not allowed.', 'mailpoet'));
|
||||
}
|
||||
|
||||
if (class_exists(Debugger::class)) {
|
||||
ApiPanel::init($endpoint, $this->_request_method, $this->_request_data);
|
||||
ApiPanel::init($endpoint, $this->requestMethod, $this->requestData);
|
||||
DIPanel::init();
|
||||
}
|
||||
|
||||
// check the accessibility of the requested endpoint's action
|
||||
// by default, an endpoint's action is considered "private"
|
||||
if (!$this->validatePermissions($this->_request_method, $endpoint->permissions)) {
|
||||
$error_message = WPFunctions::get()->__('You do not have the required permissions.', 'mailpoet');
|
||||
$error_response = $this->createErrorResponse(Error::FORBIDDEN, $error_message, Response::STATUS_FORBIDDEN);
|
||||
return $error_response;
|
||||
if (!$this->validatePermissions($this->requestMethod, $endpoint->permissions)) {
|
||||
$errorMessage = WPFunctions::get()->__('You do not have the required permissions.', 'mailpoet');
|
||||
$errorResponse = $this->createErrorResponse(Error::FORBIDDEN, $errorMessage, Response::STATUS_FORBIDDEN);
|
||||
return $errorResponse;
|
||||
}
|
||||
$response = $endpoint->{$this->_request_method}($this->_request_data);
|
||||
$response = $endpoint->{$this->requestMethod}($this->requestData);
|
||||
return $response;
|
||||
} catch (\Exception $e) {
|
||||
if (class_exists(Debugger::class) && Debugger::$logDirectory) {
|
||||
Debugger::log($e, ILogger::EXCEPTION);
|
||||
}
|
||||
$error_message = $e->getMessage();
|
||||
$error_response = $this->createErrorResponse(Error::BAD_REQUEST, $error_message, Response::STATUS_BAD_REQUEST);
|
||||
return $error_response;
|
||||
$errorMessage = $e->getMessage();
|
||||
$errorResponse = $this->createErrorResponse(Error::BAD_REQUEST, $errorMessage, Response::STATUS_BAD_REQUEST);
|
||||
return $errorResponse;
|
||||
}
|
||||
}
|
||||
|
||||
public function validatePermissions($request_method, $permissions) {
|
||||
public function validatePermissions($requestMethod, $permissions) {
|
||||
// validate method permission if defined, otherwise validate global permission
|
||||
return(!empty($permissions['methods'][$request_method])) ?
|
||||
$this->access_control->validatePermission($permissions['methods'][$request_method]) :
|
||||
$this->access_control->validatePermission($permissions['global']);
|
||||
return(!empty($permissions['methods'][$requestMethod])) ?
|
||||
$this->accessControl->validatePermission($permissions['methods'][$requestMethod]) :
|
||||
$this->accessControl->validatePermission($permissions['global']);
|
||||
}
|
||||
|
||||
public function checkToken() {
|
||||
return WPFunctions::get()->wpVerifyNonce($this->_request_token, 'mailpoet_token');
|
||||
return WPFunctions::get()->wpVerifyNonce($this->requestToken, 'mailpoet_token');
|
||||
}
|
||||
|
||||
public function setTokenAndAPIVersion() {
|
||||
@ -227,30 +227,30 @@ class API {
|
||||
}
|
||||
|
||||
public function addEndpointNamespace($namespace, $version) {
|
||||
if (!empty($this->_endpoint_namespaces[$version][$namespace])) return;
|
||||
$this->_endpoint_namespaces[$version][] = $namespace;
|
||||
if (!empty($this->endpointNamespaces[$version][$namespace])) return;
|
||||
$this->endpointNamespaces[$version][] = $namespace;
|
||||
}
|
||||
|
||||
public function getEndpointNamespaces() {
|
||||
return $this->_endpoint_namespaces;
|
||||
return $this->endpointNamespaces;
|
||||
}
|
||||
|
||||
public function getRequestedEndpointClass() {
|
||||
return $this->_request_endpoint_class;
|
||||
return $this->requestEndpointClass;
|
||||
}
|
||||
|
||||
public function getRequestedAPIVersion() {
|
||||
return $this->_request_api_version;
|
||||
return $this->requestApiVersion;
|
||||
}
|
||||
|
||||
public function createErrorResponse($error_type, $error_message, $response_status) {
|
||||
$error_response = new ErrorResponse(
|
||||
public function createErrorResponse($errorType, $errorMessage, $responseStatus) {
|
||||
$errorResponse = new ErrorResponse(
|
||||
[
|
||||
$error_type => $error_message,
|
||||
$errorType => $errorMessage,
|
||||
],
|
||||
[],
|
||||
$response_status
|
||||
$responseStatus
|
||||
);
|
||||
return $error_response;
|
||||
return $errorResponse;
|
||||
}
|
||||
}
|
||||
|
@ -45,7 +45,7 @@ abstract class Endpoint {
|
||||
public function isMethodAllowed($name, $type) {
|
||||
// Block GET requests on POST endpoints, but allow POST requests on GET endpoints (some plugins
|
||||
// change REQUEST_METHOD to POST on GET requests, which caused them to be blocked)
|
||||
if ($type === self::TYPE_GET && !in_array($name, static::$get_methods)) {
|
||||
if ($type === self::TYPE_GET && !in_array($name, static::$getMethods)) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
|
@ -10,22 +10,22 @@ class CustomFieldsResponseBuilder {
|
||||
* @param CustomFieldEntity[] $custom_fields
|
||||
* @return array
|
||||
*/
|
||||
public function buildBatch(array $custom_fields) {
|
||||
return array_map([$this, 'build'], $custom_fields);
|
||||
public function buildBatch(array $customFields) {
|
||||
return array_map([$this, 'build'], $customFields);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param CustomFieldEntity $custom_field
|
||||
* @return array
|
||||
*/
|
||||
public function build(CustomFieldEntity $custom_field) {
|
||||
public function build(CustomFieldEntity $customField) {
|
||||
return [
|
||||
'id' => $custom_field->getId(),
|
||||
'name' => $custom_field->getName(),
|
||||
'type' => $custom_field->getType(),
|
||||
'params' => $custom_field->getParams(),
|
||||
'created_at' => $custom_field->getCreatedAt()->format('Y-m-d H:i:s'),
|
||||
'updated_at' => $custom_field->getUpdatedAt()->format('Y-m-d H:i:s'),
|
||||
'id' => $customField->getId(),
|
||||
'name' => $customField->getName(),
|
||||
'type' => $customField->getType(),
|
||||
'params' => $customField->getParams(),
|
||||
'created_at' => $customField->getCreatedAt()->format('Y-m-d H:i:s'),
|
||||
'updated_at' => $customField->getUpdatedAt()->format('Y-m-d H:i:s'),
|
||||
];
|
||||
}
|
||||
}
|
||||
|
@ -22,10 +22,10 @@ class NewslettersResponseBuilder {
|
||||
'reply_to_name' => $newsletter->getReplyToName(),
|
||||
'preheader' => $newsletter->getPreheader(),
|
||||
'body' => $newsletter->getBody(),
|
||||
'sent_at' => ($sent_at = $newsletter->getSentAt()) ? $sent_at->format(self::DATE_FORMAT) : null,
|
||||
'sent_at' => ($sentAt = $newsletter->getSentAt()) ? $sentAt->format(self::DATE_FORMAT) : null,
|
||||
'created_at' => $newsletter->getCreatedAt()->format(self::DATE_FORMAT),
|
||||
'updated_at' => $newsletter->getUpdatedAt()->format(self::DATE_FORMAT),
|
||||
'deleted_at' => ($deleted_at = $newsletter->getDeletedAt()) ? $deleted_at->format(self::DATE_FORMAT) : null,
|
||||
'deleted_at' => ($deletedAt = $newsletter->getDeletedAt()) ? $deletedAt->format(self::DATE_FORMAT) : null,
|
||||
'parent_id' => ($parent = $newsletter->getParent()) ? $parent->getId() : null,
|
||||
'segments' => $this->buildSegments($newsletter),
|
||||
'options' => $this->buildOptions($newsletter),
|
||||
@ -37,8 +37,8 @@ class NewslettersResponseBuilder {
|
||||
|
||||
private function buildSegments(NewsletterEntity $newsletter) {
|
||||
$output = [];
|
||||
foreach ($newsletter->getNewsletterSegments() as $newsletter_segment) {
|
||||
$segment = $newsletter_segment->getSegment();
|
||||
foreach ($newsletter->getNewsletterSegments() as $newsletterSegment) {
|
||||
$segment = $newsletterSegment->getSegment();
|
||||
if ($segment->getDeletedAt()) {
|
||||
continue;
|
||||
}
|
||||
@ -69,7 +69,7 @@ class NewslettersResponseBuilder {
|
||||
'description' => $segment->getDescription(),
|
||||
'created_at' => $segment->getCreatedAt()->format(self::DATE_FORMAT),
|
||||
'updated_at' => $segment->getUpdatedAt()->format(self::DATE_FORMAT),
|
||||
'deleted_at' => ($deleted_at = $segment->getDeletedAt()) ? $deleted_at->format(self::DATE_FORMAT) : null,
|
||||
'deleted_at' => ($deletedAt = $segment->getDeletedAt()) ? $deletedAt->format(self::DATE_FORMAT) : null,
|
||||
];
|
||||
}
|
||||
|
||||
@ -83,11 +83,11 @@ class NewslettersResponseBuilder {
|
||||
'type' => $task->getType(),
|
||||
'status' => $task->getStatus(),
|
||||
'priority' => (string)$task->getPriority(), // (string) for BC
|
||||
'scheduled_at' => ($scheduled_at = $task->getScheduledAt()) ? $scheduled_at->format(self::DATE_FORMAT) : null,
|
||||
'processed_at' => ($processed_at = $task->getProcessedAt()) ? $processed_at->format(self::DATE_FORMAT) : null,
|
||||
'scheduled_at' => ($scheduledAt = $task->getScheduledAt()) ? $scheduledAt->format(self::DATE_FORMAT) : null,
|
||||
'processed_at' => ($processedAt = $task->getProcessedAt()) ? $processedAt->format(self::DATE_FORMAT) : null,
|
||||
'created_at' => $queue->getCreatedAt()->format(self::DATE_FORMAT),
|
||||
'updated_at' => $queue->getUpdatedAt()->format(self::DATE_FORMAT),
|
||||
'deleted_at' => ($deleted_at = $queue->getDeletedAt()) ? $deleted_at->format(self::DATE_FORMAT) : null,
|
||||
'deleted_at' => ($deletedAt = $queue->getDeletedAt()) ? $deletedAt->format(self::DATE_FORMAT) : null,
|
||||
'meta' => $queue->getMeta(),
|
||||
'task_id' => (string)$queue->getTask()->getId(), // (string) for BC
|
||||
'newsletter_id' => (string)$queue->getNewsletter()->getId(), // (string) for BC
|
||||
|
@ -21,24 +21,24 @@ class AutomatedLatestContent extends APIEndpoint {
|
||||
}
|
||||
|
||||
public function getPostTypes() {
|
||||
$post_types = array_map(function($post_type) {
|
||||
$postTypes = array_map(function($postType) {
|
||||
return [
|
||||
'name' => $post_type->name,
|
||||
'label' => $post_type->label,
|
||||
'name' => $postType->name,
|
||||
'label' => $postType->label,
|
||||
];
|
||||
}, WPPosts::getTypes([], 'objects'));
|
||||
return $this->successResponse(
|
||||
array_filter($post_types)
|
||||
array_filter($postTypes)
|
||||
);
|
||||
}
|
||||
|
||||
public function getTaxonomies($data = []) {
|
||||
$post_type = (isset($data['postType'])) ? $data['postType'] : 'post';
|
||||
$all_taxonomies = WPFunctions::get()->getObjectTaxonomies($post_type, 'objects');
|
||||
$taxonomies_with_label = array_filter($all_taxonomies, function($taxonomy) {
|
||||
$postType = (isset($data['postType'])) ? $data['postType'] : 'post';
|
||||
$allTaxonomies = WPFunctions::get()->getObjectTaxonomies($postType, 'objects');
|
||||
$taxonomiesWithLabel = array_filter($allTaxonomies, function($taxonomy) {
|
||||
return $taxonomy->label;
|
||||
});
|
||||
return $this->successResponse($taxonomies_with_label);
|
||||
return $this->successResponse($taxonomiesWithLabel);
|
||||
}
|
||||
|
||||
public function getTerms($data = []) {
|
||||
@ -76,18 +76,18 @@ class AutomatedLatestContent extends APIEndpoint {
|
||||
}
|
||||
|
||||
public function getBulkTransformedPosts($data = []) {
|
||||
$used_posts = [];
|
||||
$rendered_posts = [];
|
||||
$usedPosts = [];
|
||||
$renderedPosts = [];
|
||||
|
||||
foreach ($data['blocks'] as $block) {
|
||||
$posts = $this->ALC->getPosts($block, $used_posts);
|
||||
$rendered_posts[] = $this->ALC->transformPosts($block, $posts);
|
||||
$posts = $this->ALC->getPosts($block, $usedPosts);
|
||||
$renderedPosts[] = $this->ALC->transformPosts($block, $posts);
|
||||
|
||||
foreach ($posts as $post) {
|
||||
$used_posts[] = $post->ID;
|
||||
$usedPosts[] = $post->ID;
|
||||
}
|
||||
}
|
||||
|
||||
return $this->successResponse($rendered_posts);
|
||||
return $this->successResponse($renderedPosts);
|
||||
}
|
||||
}
|
||||
|
@ -21,10 +21,10 @@ class AutomaticEmails extends APIEndpoint {
|
||||
public function getEventOptions($data) {
|
||||
$query = (!empty($data['query'])) ? $data['query'] : null;
|
||||
$filter = (!empty($data['filter'])) ? $data['filter'] : null;
|
||||
$email_slug = (!empty($data['email_slug'])) ? $data['email_slug'] : null;
|
||||
$event_slug = (!empty($data['event_slug'])) ? $data['event_slug'] : null;
|
||||
$emailSlug = (!empty($data['email_slug'])) ? $data['email_slug'] : null;
|
||||
$eventSlug = (!empty($data['event_slug'])) ? $data['event_slug'] : null;
|
||||
|
||||
if (!$query || !$filter || !$email_slug || !$event_slug) {
|
||||
if (!$query || !$filter || !$emailSlug || !$eventSlug) {
|
||||
return $this->errorResponse(
|
||||
[
|
||||
APIError::BAD_REQUEST => WPFunctions::get()->__('Improperly formatted request.', 'mailpoet'),
|
||||
@ -32,12 +32,12 @@ class AutomaticEmails extends APIEndpoint {
|
||||
);
|
||||
}
|
||||
|
||||
$automatic_emails = new \MailPoet\AutomaticEmails\AutomaticEmails();
|
||||
$event = $automatic_emails->getAutomaticEmailEventBySlug($email_slug, $event_slug);
|
||||
$event_filter = (!empty($event['options']['remoteQueryFilter'])) ? $event['options']['remoteQueryFilter'] : null;
|
||||
$automaticEmails = new \MailPoet\AutomaticEmails\AutomaticEmails();
|
||||
$event = $automaticEmails->getAutomaticEmailEventBySlug($emailSlug, $eventSlug);
|
||||
$eventFilter = (!empty($event['options']['remoteQueryFilter'])) ? $event['options']['remoteQueryFilter'] : null;
|
||||
|
||||
return ($event_filter === $filter && WPFunctions::get()->hasFilter($event_filter)) ?
|
||||
$this->successResponse($this->wp->applyFilters($event_filter, $query)) :
|
||||
return ($eventFilter === $filter && WPFunctions::get()->hasFilter($eventFilter)) ?
|
||||
$this->successResponse($this->wp->applyFilters($eventFilter, $query)) :
|
||||
$this->errorResponse(
|
||||
[
|
||||
APIError::BAD_REQUEST => WPFunctions::get()->__('Automatic email event filter does not exist.', 'mailpoet'),
|
||||
@ -46,10 +46,10 @@ class AutomaticEmails extends APIEndpoint {
|
||||
}
|
||||
|
||||
public function getEventShortcodes($data) {
|
||||
$email_slug = (!empty($data['email_slug'])) ? $data['email_slug'] : null;
|
||||
$event_slug = (!empty($data['event_slug'])) ? $data['event_slug'] : null;
|
||||
$emailSlug = (!empty($data['email_slug'])) ? $data['email_slug'] : null;
|
||||
$eventSlug = (!empty($data['event_slug'])) ? $data['event_slug'] : null;
|
||||
|
||||
if (!$email_slug || !$event_slug) {
|
||||
if (!$emailSlug || !$eventSlug) {
|
||||
return $this->errorResponse(
|
||||
[
|
||||
APIError::BAD_REQUEST => WPFunctions::get()->__('Improperly formatted request.', 'mailpoet'),
|
||||
@ -57,9 +57,9 @@ class AutomaticEmails extends APIEndpoint {
|
||||
);
|
||||
}
|
||||
|
||||
$automatic_emails = new \MailPoet\AutomaticEmails\AutomaticEmails();
|
||||
$automatic_email = $automatic_emails->getAutomaticEmailBySlug($email_slug);
|
||||
$event = $automatic_emails->getAutomaticEmailEventBySlug($email_slug, $event_slug);
|
||||
$automaticEmails = new \MailPoet\AutomaticEmails\AutomaticEmails();
|
||||
$automaticEmail = $automaticEmails->getAutomaticEmailBySlug($emailSlug);
|
||||
$event = $automaticEmails->getAutomaticEmailEventBySlug($emailSlug, $eventSlug);
|
||||
|
||||
if (!$event) {
|
||||
return $this->errorResponse(
|
||||
@ -69,12 +69,12 @@ class AutomaticEmails extends APIEndpoint {
|
||||
);
|
||||
}
|
||||
|
||||
$event_shortcodes = (!empty($event['shortcodes']) && is_array($event['shortcodes'])) ?
|
||||
$eventShortcodes = (!empty($event['shortcodes']) && is_array($event['shortcodes'])) ?
|
||||
[
|
||||
$automatic_email['title'] => $event['shortcodes'],
|
||||
$automaticEmail['title'] => $event['shortcodes'],
|
||||
] :
|
||||
null;
|
||||
|
||||
return $this->successResponse($event_shortcodes);
|
||||
return $this->successResponse($eventShortcodes);
|
||||
}
|
||||
}
|
||||
|
@ -24,26 +24,26 @@ class CustomFields extends APIEndpoint {
|
||||
private $custom_fields_response_builder;
|
||||
|
||||
public function __construct(
|
||||
CustomFieldsRepository $custom_fields_repository,
|
||||
CustomFieldsResponseBuilder $custom_fields_response_builder
|
||||
CustomFieldsRepository $customFieldsRepository,
|
||||
CustomFieldsResponseBuilder $customFieldsResponseBuilder
|
||||
) {
|
||||
$this->custom_fields_repository = $custom_fields_repository;
|
||||
$this->custom_fields_response_builder = $custom_fields_response_builder;
|
||||
$this->customFieldsRepository = $customFieldsRepository;
|
||||
$this->customFieldsResponseBuilder = $customFieldsResponseBuilder;
|
||||
}
|
||||
|
||||
public function getAll() {
|
||||
$collection = $this->custom_fields_repository->findBy([], ['created_at' => 'asc']);
|
||||
return $this->successResponse($this->custom_fields_response_builder->buildBatch($collection));
|
||||
$collection = $this->customFieldsRepository->findBy([], ['created_at' => 'asc']);
|
||||
return $this->successResponse($this->customFieldsResponseBuilder->buildBatch($collection));
|
||||
}
|
||||
|
||||
public function delete($data = []) {
|
||||
$id = (isset($data['id']) ? (int)$data['id'] : null);
|
||||
$custom_field = $this->custom_fields_repository->findOneById($id);
|
||||
if ($custom_field instanceof CustomFieldEntity) {
|
||||
$this->custom_fields_repository->remove($custom_field);
|
||||
$this->custom_fields_repository->flush();
|
||||
$customField = $this->customFieldsRepository->findOneById($id);
|
||||
if ($customField instanceof CustomFieldEntity) {
|
||||
$this->customFieldsRepository->remove($customField);
|
||||
$this->customFieldsRepository->flush();
|
||||
|
||||
return $this->successResponse($this->custom_fields_response_builder->build($custom_field));
|
||||
return $this->successResponse($this->customFieldsResponseBuilder->build($customField));
|
||||
} else {
|
||||
return $this->errorResponse([
|
||||
APIError::NOT_FOUND => WPFunctions::get()->__('This custom field does not exist.', 'mailpoet'),
|
||||
@ -53,10 +53,10 @@ class CustomFields extends APIEndpoint {
|
||||
|
||||
public function save($data = []) {
|
||||
try {
|
||||
$custom_field = $this->custom_fields_repository->createOrUpdate($data);
|
||||
$custom_field = $this->custom_fields_repository->findOneById($custom_field->getId());
|
||||
if(!$custom_field instanceof CustomFieldEntity) return $this->errorResponse();
|
||||
return $this->successResponse($this->custom_fields_response_builder->build($custom_field));
|
||||
$customField = $this->customFieldsRepository->createOrUpdate($data);
|
||||
$customField = $this->customFieldsRepository->findOneById($customField->getId());
|
||||
if(!$customField instanceof CustomFieldEntity) return $this->errorResponse();
|
||||
return $this->successResponse($this->customFieldsResponseBuilder->build($customField));
|
||||
} catch (\Exception $e) {
|
||||
return $this->errorResponse($errors = [], $meta = [], $status = Response::STATUS_BAD_REQUEST);
|
||||
}
|
||||
@ -64,9 +64,9 @@ class CustomFields extends APIEndpoint {
|
||||
|
||||
public function get($data = []) {
|
||||
$id = (isset($data['id']) ? (int)$data['id'] : null);
|
||||
$custom_field = $this->custom_fields_repository->findOneById($id);
|
||||
if ($custom_field instanceof CustomFieldEntity) {
|
||||
return $this->successResponse($this->custom_fields_response_builder->build($custom_field));
|
||||
$customField = $this->customFieldsRepository->findOneById($id);
|
||||
if ($customField instanceof CustomFieldEntity) {
|
||||
return $this->successResponse($this->customFieldsResponseBuilder->build($customField));
|
||||
}
|
||||
return $this->errorResponse([
|
||||
APIError::NOT_FOUND => WPFunctions::get()->__('This custom field does not exist.', 'mailpoet'),
|
||||
|
@ -42,13 +42,13 @@ class DynamicSegments extends APIEndpoint {
|
||||
/** @var Handler */
|
||||
private $listing_handler;
|
||||
|
||||
public function __construct(BulkActionController $bulk_action, Handler $handler, $mapper = null, $saver = null, $dynamic_segments_loader = null, $subscribers_counts_loader = null) {
|
||||
$this->bulk_action = $bulk_action;
|
||||
$this->listing_handler = $handler;
|
||||
public function __construct(BulkActionController $bulkAction, Handler $handler, $mapper = null, $saver = null, $dynamicSegmentsLoader = null, $subscribersCountsLoader = null) {
|
||||
$this->bulkAction = $bulkAction;
|
||||
$this->listingHandler = $handler;
|
||||
$this->mapper = $mapper ?: new FormDataMapper();
|
||||
$this->saver = $saver ?: new Saver();
|
||||
$this->dynamic_segments_loader = $dynamic_segments_loader ?: new SingleSegmentLoader(new DBMapper());
|
||||
$this->subscribers_counts_loader = $subscribers_counts_loader ?: new SubscribersCount();
|
||||
$this->dynamicSegmentsLoader = $dynamicSegmentsLoader ?: new SingleSegmentLoader(new DBMapper());
|
||||
$this->subscribersCountsLoader = $subscribersCountsLoader ?: new SubscribersCount();
|
||||
}
|
||||
|
||||
public function get($data = []) {
|
||||
@ -61,7 +61,7 @@ class DynamicSegments extends APIEndpoint {
|
||||
}
|
||||
|
||||
try {
|
||||
$segment = $this->dynamic_segments_loader->load($id);
|
||||
$segment = $this->dynamicSegmentsLoader->load($id);
|
||||
|
||||
$filters = $segment->getFilters();
|
||||
|
||||
@ -79,8 +79,8 @@ class DynamicSegments extends APIEndpoint {
|
||||
|
||||
public function save($data) {
|
||||
try {
|
||||
$dynamic_segment = $this->mapper->mapDataToDB($data);
|
||||
$this->saver->save($dynamic_segment);
|
||||
$dynamicSegment = $this->mapper->mapDataToDB($data);
|
||||
$this->saver->save($dynamicSegment);
|
||||
|
||||
return $this->successResponse($data);
|
||||
} catch (InvalidSegmentTypeException $e) {
|
||||
@ -127,7 +127,7 @@ class DynamicSegments extends APIEndpoint {
|
||||
}
|
||||
|
||||
try {
|
||||
$segment = $this->dynamic_segments_loader->load($id);
|
||||
$segment = $this->dynamicSegmentsLoader->load($id);
|
||||
$segment->trash();
|
||||
return $this->successResponse(
|
||||
$segment->asArray(),
|
||||
@ -150,7 +150,7 @@ class DynamicSegments extends APIEndpoint {
|
||||
}
|
||||
|
||||
try {
|
||||
$segment = $this->dynamic_segments_loader->load($id);
|
||||
$segment = $this->dynamicSegmentsLoader->load($id);
|
||||
$segment->restore();
|
||||
return $this->successResponse(
|
||||
$segment->asArray(),
|
||||
@ -173,7 +173,7 @@ class DynamicSegments extends APIEndpoint {
|
||||
}
|
||||
|
||||
try {
|
||||
$segment = $this->dynamic_segments_loader->load($id);
|
||||
$segment = $this->dynamicSegmentsLoader->load($id);
|
||||
$segment->delete();
|
||||
return $this->successResponse(null, ['count' => 1]);
|
||||
} catch (\InvalidArgumentException $e) {
|
||||
@ -184,31 +184,31 @@ class DynamicSegments extends APIEndpoint {
|
||||
}
|
||||
|
||||
public function listing($data = []) {
|
||||
$listing_data = $this->listing_handler->get('\MailPoet\Models\DynamicSegment', $data);
|
||||
$listingData = $this->listingHandler->get('\MailPoet\Models\DynamicSegment', $data);
|
||||
|
||||
$data = [];
|
||||
foreach ($listing_data['items'] as $segment) {
|
||||
$segment->subscribers_url = WPFunctions::get()->adminUrl(
|
||||
foreach ($listingData['items'] as $segment) {
|
||||
$segment->subscribersUrl = WPFunctions::get()->adminUrl(
|
||||
'admin.php?page=mailpoet-subscribers#/filter[segment=' . $segment->id . ']'
|
||||
);
|
||||
|
||||
$row = $segment->asArray();
|
||||
$segment_with_filters = $this->dynamic_segments_loader->load($segment->id);
|
||||
$row['count'] = $this->subscribers_counts_loader->getSubscribersCount($segment_with_filters);
|
||||
$segmentWithFilters = $this->dynamicSegmentsLoader->load($segment->id);
|
||||
$row['count'] = $this->subscribersCountsLoader->getSubscribersCount($segmentWithFilters);
|
||||
$data[] = $row;
|
||||
}
|
||||
|
||||
return $this->successResponse($data, [
|
||||
'count' => $listing_data['count'],
|
||||
'filters' => $listing_data['filters'],
|
||||
'groups' => $listing_data['groups'],
|
||||
'count' => $listingData['count'],
|
||||
'filters' => $listingData['filters'],
|
||||
'groups' => $listingData['groups'],
|
||||
]);
|
||||
|
||||
}
|
||||
|
||||
public function bulkAction($data = []) {
|
||||
try {
|
||||
$meta = $this->bulk_action->apply('\MailPoet\Models\DynamicSegment', $data);
|
||||
$meta = $this->bulkAction->apply('\MailPoet\Models\DynamicSegment', $data);
|
||||
return $this->successResponse(null, $meta);
|
||||
} catch (\Exception $e) {
|
||||
return $this->errorResponse([
|
||||
|
@ -20,19 +20,19 @@ class FeatureFlags extends APIEndpoint {
|
||||
/** @var FeatureFlagsController */
|
||||
private $feature_flags_controller;
|
||||
|
||||
public function __construct(FeaturesController $features_controller, FeatureFlagsController $feature_flags) {
|
||||
$this->features_controller = $features_controller;
|
||||
$this->feature_flags_controller = $feature_flags;
|
||||
public function __construct(FeaturesController $featuresController, FeatureFlagsController $featureFlags) {
|
||||
$this->featuresController = $featuresController;
|
||||
$this->featureFlagsController = $featureFlags;
|
||||
}
|
||||
|
||||
public function getAll() {
|
||||
$feature_flags = $this->feature_flags_controller->getAll();
|
||||
return $this->successResponse($feature_flags);
|
||||
$featureFlags = $this->featureFlagsController->getAll();
|
||||
return $this->successResponse($featureFlags);
|
||||
}
|
||||
|
||||
public function set(array $flags) {
|
||||
foreach ($flags as $name => $value) {
|
||||
if (!$this->features_controller->exists($name)) {
|
||||
if (!$this->featuresController->exists($name)) {
|
||||
return $this->badRequest([
|
||||
APIError::BAD_REQUEST => "Feature '$name' does not exist'",
|
||||
]);
|
||||
@ -40,7 +40,7 @@ class FeatureFlags extends APIEndpoint {
|
||||
}
|
||||
|
||||
foreach ($flags as $name => $value) {
|
||||
$this->feature_flags_controller->set($name, (bool)$value);
|
||||
$this->featureFlagsController->set($name, (bool)$value);
|
||||
}
|
||||
return $this->successResponse([]);
|
||||
}
|
||||
|
@ -32,15 +32,15 @@ class Forms extends APIEndpoint {
|
||||
];
|
||||
|
||||
public function __construct(
|
||||
Listing\BulkActionController $bulk_action,
|
||||
Listing\Handler $listing_handler,
|
||||
FeaturesController $features_controller,
|
||||
Util\Styles $form_styles_utils
|
||||
Listing\BulkActionController $bulkAction,
|
||||
Listing\Handler $listingHandler,
|
||||
FeaturesController $featuresController,
|
||||
Util\Styles $formStylesUtils
|
||||
) {
|
||||
$this->bulk_action = $bulk_action;
|
||||
$this->listing_handler = $listing_handler;
|
||||
$this->features_controller = $features_controller;
|
||||
$this->form_styles_utils = $form_styles_utils;
|
||||
$this->bulkAction = $bulkAction;
|
||||
$this->listingHandler = $listingHandler;
|
||||
$this->featuresController = $featuresController;
|
||||
$this->formStylesUtils = $formStylesUtils;
|
||||
}
|
||||
|
||||
public function get($data = []) {
|
||||
@ -55,10 +55,10 @@ class Forms extends APIEndpoint {
|
||||
}
|
||||
|
||||
public function listing($data = []) {
|
||||
$listing_data = $this->listing_handler->get('\MailPoet\Models\Form', $data);
|
||||
$listingData = $this->listingHandler->get('\MailPoet\Models\Form', $data);
|
||||
|
||||
$data = [];
|
||||
foreach ($listing_data['items'] as $form) {
|
||||
foreach ($listingData['items'] as $form) {
|
||||
$form = $form->asArray();
|
||||
|
||||
$form['signups'] = StatisticsForms::getTotalSignups($form['id']);
|
||||
@ -73,20 +73,20 @@ class Forms extends APIEndpoint {
|
||||
}
|
||||
|
||||
return $this->successResponse($data, [
|
||||
'count' => $listing_data['count'],
|
||||
'filters' => $listing_data['filters'],
|
||||
'groups' => $listing_data['groups'],
|
||||
'count' => $listingData['count'],
|
||||
'filters' => $listingData['filters'],
|
||||
'groups' => $listingData['groups'],
|
||||
]);
|
||||
}
|
||||
|
||||
public function create() {
|
||||
$form_name = WPFunctions::get()->__('New form', 'mailpoet');
|
||||
if ($this->features_controller->isSupported(FeaturesController::NEW_FORM_EDITOR)) {
|
||||
$form_name = '';
|
||||
$formName = WPFunctions::get()->__('New form', 'mailpoet');
|
||||
if ($this->featuresController->isSupported(FeaturesController::NEW_FORM_EDITOR)) {
|
||||
$formName = '';
|
||||
}
|
||||
// create new form
|
||||
$form_data = [
|
||||
'name' => $form_name,
|
||||
$formData = [
|
||||
'name' => $formName,
|
||||
'body' => [
|
||||
[
|
||||
'id' => 'email',
|
||||
@ -116,11 +116,11 @@ class Forms extends APIEndpoint {
|
||||
],
|
||||
];
|
||||
|
||||
if ($this->features_controller->isSupported(FeaturesController::NEW_FORM_EDITOR)) {
|
||||
$form_data['body'][0]['params']['label_within'] = true;
|
||||
if ($this->featuresController->isSupported(FeaturesController::NEW_FORM_EDITOR)) {
|
||||
$formData['body'][0]['params']['label_within'] = true;
|
||||
}
|
||||
|
||||
return $this->save($form_data);
|
||||
return $this->save($formData);
|
||||
}
|
||||
|
||||
public function save($data = []) {
|
||||
@ -143,7 +143,7 @@ class Forms extends APIEndpoint {
|
||||
$html = WPFunctions::get()->doShortcode($html);
|
||||
|
||||
// styles
|
||||
$css = $this->form_styles_utils->render(FormRenderer::getStyles($data));
|
||||
$css = $this->formStylesUtils->render(FormRenderer::getStyles($data));
|
||||
|
||||
return $this->successResponse([
|
||||
'html' => $html,
|
||||
@ -164,19 +164,19 @@ class Forms extends APIEndpoint {
|
||||
}
|
||||
|
||||
public function saveEditor($data = []) {
|
||||
$form_id = (isset($data['id']) ? (int)$data['id'] : 0);
|
||||
$formId = (isset($data['id']) ? (int)$data['id'] : 0);
|
||||
$name = (isset($data['name']) ? $data['name'] : WPFunctions::get()->__('New form', 'mailpoet'));
|
||||
$body = (isset($data['body']) ? $data['body'] : []);
|
||||
$settings = (isset($data['settings']) ? $data['settings'] : []);
|
||||
$styles = (isset($data['styles']) ? $data['styles'] : '');
|
||||
|
||||
// check if the form is used as a widget
|
||||
$is_widget = false;
|
||||
$isWidget = false;
|
||||
$widgets = WPFunctions::get()->getOption('widget_mailpoet_form');
|
||||
if (!empty($widgets)) {
|
||||
foreach ($widgets as $widget) {
|
||||
if (isset($widget['form']) && (int)$widget['form'] === $form_id) {
|
||||
$is_widget = true;
|
||||
if (isset($widget['form']) && (int)$widget['form'] === $formId) {
|
||||
$isWidget = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
@ -184,13 +184,13 @@ class Forms extends APIEndpoint {
|
||||
|
||||
// check if the user gets to pick his own lists
|
||||
// or if it's selected by the admin
|
||||
$has_segment_selection = false;
|
||||
$list_selection = [];
|
||||
$hasSegmentSelection = false;
|
||||
$listSelection = [];
|
||||
foreach ($body as $i => $block) {
|
||||
if ($block['type'] === 'segment') {
|
||||
$has_segment_selection = true;
|
||||
$hasSegmentSelection = true;
|
||||
if (!empty($block['params']['values'])) {
|
||||
$list_selection = array_filter(
|
||||
$listSelection = array_filter(
|
||||
array_map(function($segment) {
|
||||
return (isset($segment['id'])
|
||||
? $segment['id']
|
||||
@ -204,15 +204,15 @@ class Forms extends APIEndpoint {
|
||||
}
|
||||
|
||||
// check list selection
|
||||
if ($has_segment_selection === true) {
|
||||
if ($hasSegmentSelection === true) {
|
||||
$settings['segments_selected_by'] = 'user';
|
||||
$settings['segments'] = $list_selection;
|
||||
$settings['segments'] = $listSelection;
|
||||
} else {
|
||||
$settings['segments_selected_by'] = 'admin';
|
||||
}
|
||||
|
||||
$form = Form::createOrUpdate([
|
||||
'id' => $form_id,
|
||||
'id' => $formId,
|
||||
'name' => $name,
|
||||
'body' => $body,
|
||||
'settings' => $settings,
|
||||
@ -228,7 +228,7 @@ class Forms extends APIEndpoint {
|
||||
if(!$form instanceof Form) return $this->errorResponse();
|
||||
return $this->successResponse(
|
||||
$form->asArray(),
|
||||
['is_widget' => $is_widget]
|
||||
['is_widget' => $isWidget]
|
||||
);
|
||||
}
|
||||
|
||||
@ -287,9 +287,9 @@ class Forms extends APIEndpoint {
|
||||
$form = Form::findOne($id);
|
||||
|
||||
if ($form instanceof Form) {
|
||||
$form_name = $form->name ? sprintf(__('Copy of %s', 'mailpoet'), $form->name) : '';
|
||||
$formName = $form->name ? sprintf(__('Copy of %s', 'mailpoet'), $form->name) : '';
|
||||
$data = [
|
||||
'name' => $form_name,
|
||||
'name' => $formName,
|
||||
];
|
||||
$duplicate = $form->duplicate($data);
|
||||
$errors = $duplicate->getErrors();
|
||||
@ -313,7 +313,7 @@ class Forms extends APIEndpoint {
|
||||
|
||||
public function bulkAction($data = []) {
|
||||
try {
|
||||
$meta = $this->bulk_action->apply('\MailPoet\Models\Form', $data);
|
||||
$meta = $this->bulkAction->apply('\MailPoet\Models\Form', $data);
|
||||
return $this->successResponse(null, $meta);
|
||||
} catch (\Exception $e) {
|
||||
return $this->errorResponse([
|
||||
|
@ -93,7 +93,7 @@ class ImportExport extends APIEndpoint {
|
||||
$task->type = WooCommerceSync::TASK_TYPE;
|
||||
$task->status = ScheduledTask::STATUS_SCHEDULED;
|
||||
}
|
||||
$task->scheduled_at = Carbon::createFromTimestamp((int)current_time('timestamp'));
|
||||
$task->scheduledAt = Carbon::createFromTimestamp((int)current_time('timestamp'));
|
||||
$task->save();
|
||||
return $this->successResponse();
|
||||
} catch (\Exception $e) {
|
||||
|
@ -30,8 +30,8 @@ class Mailer extends APIEndpoint {
|
||||
'global' => AccessControl::PERMISSION_MANAGE_EMAILS,
|
||||
];
|
||||
|
||||
public function __construct(AuthorizedEmailsController $authorized_emails_controller, SettingsController $settings, Bridge $bridge, MetaInfo $mailerMetaInfo) {
|
||||
$this->authorized_emails_controller = $authorized_emails_controller;
|
||||
public function __construct(AuthorizedEmailsController $authorizedEmailsController, SettingsController $settings, Bridge $bridge, MetaInfo $mailerMetaInfo) {
|
||||
$this->authorizedEmailsController = $authorizedEmailsController;
|
||||
$this->settings = $settings;
|
||||
$this->bridge = $bridge;
|
||||
$this->mailerMetaInfo = $mailerMetaInfo;
|
||||
@ -46,10 +46,10 @@ class Mailer extends APIEndpoint {
|
||||
(isset($data['reply_to'])) ? $data['reply_to'] : false
|
||||
);
|
||||
// report this as 'sending_test' in metadata since this endpoint is only used to test sending methods for now
|
||||
$extra_params = [
|
||||
$extraParams = [
|
||||
'meta' => $this->mailerMetaInfo->getSendingTestMetaInfo(),
|
||||
];
|
||||
$result = $mailer->send($data['newsletter'], $data['subscriber'], $extra_params);
|
||||
$result = $mailer->send($data['newsletter'], $data['subscriber'], $extraParams);
|
||||
} catch (\Exception $e) {
|
||||
return $this->errorResponse([
|
||||
$e->getCode() => $e->getMessage(),
|
||||
@ -69,14 +69,14 @@ class Mailer extends APIEndpoint {
|
||||
|
||||
public function resumeSending() {
|
||||
if ($this->settings->get(AuthorizedEmailsController::AUTHORIZED_EMAIL_ADDRESSES_ERROR_SETTING)) {
|
||||
$this->authorized_emails_controller->checkAuthorizedEmailAddresses();
|
||||
$this->authorizedEmailsController->checkAuthorizedEmailAddresses();
|
||||
}
|
||||
MailerLog::resumeSending();
|
||||
return $this->successResponse(null);
|
||||
}
|
||||
|
||||
public function getAuthorizedEmailAddresses() {
|
||||
$authorized_emails = $this->bridge->getAuthorizedEmailAddresses();
|
||||
return $this->successResponse($authorized_emails);
|
||||
$authorizedEmails = $this->bridge->getAuthorizedEmailAddresses();
|
||||
return $this->successResponse($authorizedEmails);
|
||||
}
|
||||
}
|
||||
|
@ -81,45 +81,45 @@ class Newsletters extends APIEndpoint {
|
||||
private $subscribers_feature;
|
||||
|
||||
public function __construct(
|
||||
Listing\BulkActionController $bulk_action,
|
||||
Listing\Handler $listing_handler,
|
||||
Listing\BulkActionController $bulkAction,
|
||||
Listing\Handler $listingHandler,
|
||||
WPFunctions $wp,
|
||||
WCHelper $woocommerce_helper,
|
||||
WCHelper $woocommerceHelper,
|
||||
SettingsController $settings,
|
||||
CronHelper $cron_helper,
|
||||
AuthorizedEmailsController $authorized_emails_controller,
|
||||
NewslettersRepository $newsletters_repository,
|
||||
NewslettersResponseBuilder $newsletters_response_builder,
|
||||
PostNotificationScheduler $post_notification_scheduler,
|
||||
CronHelper $cronHelper,
|
||||
AuthorizedEmailsController $authorizedEmailsController,
|
||||
NewslettersRepository $newslettersRepository,
|
||||
NewslettersResponseBuilder $newslettersResponseBuilder,
|
||||
PostNotificationScheduler $postNotificationScheduler,
|
||||
MailerFactory $mailer,
|
||||
MetaInfo $mailerMetaInfo,
|
||||
Emoji $emoji,
|
||||
SubscribersFeature $subscribers_feature
|
||||
SubscribersFeature $subscribersFeature
|
||||
) {
|
||||
$this->bulk_action = $bulk_action;
|
||||
$this->listing_handler = $listing_handler;
|
||||
$this->bulkAction = $bulkAction;
|
||||
$this->listingHandler = $listingHandler;
|
||||
$this->wp = $wp;
|
||||
$this->woocommerce_helper = $woocommerce_helper;
|
||||
$this->woocommerceHelper = $woocommerceHelper;
|
||||
$this->settings = $settings;
|
||||
$this->cron_helper = $cron_helper;
|
||||
$this->authorized_emails_controller = $authorized_emails_controller;
|
||||
$this->newsletters_repository = $newsletters_repository;
|
||||
$this->newsletters_response_builder = $newsletters_response_builder;
|
||||
$this->post_notification_scheduler = $post_notification_scheduler;
|
||||
$this->cronHelper = $cronHelper;
|
||||
$this->authorizedEmailsController = $authorizedEmailsController;
|
||||
$this->newslettersRepository = $newslettersRepository;
|
||||
$this->newslettersResponseBuilder = $newslettersResponseBuilder;
|
||||
$this->postNotificationScheduler = $postNotificationScheduler;
|
||||
$this->mailer = $mailer;
|
||||
$this->mailerMetaInfo = $mailerMetaInfo;
|
||||
$this->emoji = $emoji;
|
||||
$this->subscribers_feature = $subscribers_feature;
|
||||
$this->subscribersFeature = $subscribersFeature;
|
||||
}
|
||||
|
||||
public function get($data = []) {
|
||||
$newsletter = isset($data['id'])
|
||||
? $this->newsletters_repository->findOneById((int)$data['id'])
|
||||
? $this->newslettersRepository->findOneById((int)$data['id'])
|
||||
: null;
|
||||
|
||||
if ($newsletter) {
|
||||
$response = $this->newsletters_response_builder->build($newsletter);
|
||||
$preview_url = NewsletterUrl::getViewInBrowserUrl(
|
||||
$response = $this->newslettersResponseBuilder->build($newsletter);
|
||||
$previewUrl = NewsletterUrl::getViewInBrowserUrl(
|
||||
NewsletterUrl::TYPE_LISTING_EDITOR,
|
||||
(object)[
|
||||
'id' => $newsletter->getId(),
|
||||
@ -129,7 +129,7 @@ class Newsletters extends APIEndpoint {
|
||||
);
|
||||
|
||||
$response = $this->wp->applyFilters('mailpoet_api_newsletters_get_after', $response);
|
||||
return $this->successResponse($response, ['preview_url' => $preview_url]);
|
||||
return $this->successResponse($response, ['preview_url' => $previewUrl]);
|
||||
} else {
|
||||
return $this->errorResponse([
|
||||
APIError::NOT_FOUND => __('This email does not exist.', 'mailpoet'),
|
||||
@ -146,16 +146,16 @@ class Newsletters extends APIEndpoint {
|
||||
->withOptions()
|
||||
->withSendingQueue()
|
||||
->withTotalSent()
|
||||
->withStatistics($this->woocommerce_helper);
|
||||
->withStatistics($this->woocommerceHelper);
|
||||
|
||||
$preview_url = NewsletterUrl::getViewInBrowserUrl(
|
||||
$previewUrl = NewsletterUrl::getViewInBrowserUrl(
|
||||
NewsletterUrl::TYPE_LISTING_EDITOR,
|
||||
$newsletter,
|
||||
Subscriber::getCurrentWPUser()
|
||||
);
|
||||
|
||||
$newsletter = $this->wp->applyFilters('mailpoet_api_newsletters_get_after', $newsletter->asArray());
|
||||
$newsletter['preview_url'] = $preview_url;
|
||||
$newsletter['preview_url'] = $previewUrl;
|
||||
return $this->successResponse($newsletter);
|
||||
} else {
|
||||
return $this->errorResponse([
|
||||
@ -187,10 +187,10 @@ class Newsletters extends APIEndpoint {
|
||||
unset($data['template_id']);
|
||||
}
|
||||
|
||||
$old_newsletter = null;
|
||||
$oldNewsletter = null;
|
||||
if (isset($data['id'])) {
|
||||
$fetched = Newsletter::findOne(intval($data['id']));
|
||||
$old_newsletter = $fetched instanceof Newsletter ? $fetched : null;
|
||||
$oldNewsletter = $fetched instanceof Newsletter ? $fetched : null;
|
||||
}
|
||||
|
||||
if (!empty($data['body'])) {
|
||||
@ -211,8 +211,8 @@ class Newsletters extends APIEndpoint {
|
||||
foreach ($segments as $segment) {
|
||||
if (!is_array($segment)) continue;
|
||||
$relation = NewsletterSegment::create();
|
||||
$relation->segment_id = (int)$segment['id'];
|
||||
$relation->newsletter_id = $newsletter->id;
|
||||
$relation->segmentId = (int)$segment['id'];
|
||||
$relation->newsletterId = $newsletter->id;
|
||||
$relation->save();
|
||||
}
|
||||
}
|
||||
@ -226,18 +226,18 @@ class Newsletters extends APIEndpoint {
|
||||
}
|
||||
|
||||
if (!empty($options)) {
|
||||
$option_fields = NewsletterOptionField::where(
|
||||
$optionFields = NewsletterOptionField::where(
|
||||
'newsletter_type',
|
||||
$newsletter->type
|
||||
)->findMany();
|
||||
// update newsletter options
|
||||
foreach ($option_fields as $option_field) {
|
||||
if (isset($options[$option_field->name])) {
|
||||
$newsletter_option = NewsletterOption::createOrUpdate(
|
||||
foreach ($optionFields as $optionField) {
|
||||
if (isset($options[$optionField->name])) {
|
||||
$newsletterOption = NewsletterOption::createOrUpdate(
|
||||
[
|
||||
'newsletter_id' => $newsletter->id,
|
||||
'option_field_id' => $option_field->id,
|
||||
'value' => $options[$option_field->name],
|
||||
'option_field_id' => $optionField->id,
|
||||
'value' => $options[$optionField->name],
|
||||
]
|
||||
);
|
||||
}
|
||||
@ -248,13 +248,13 @@ class Newsletters extends APIEndpoint {
|
||||
// if this is a post notification, process newsletter options and update its schedule
|
||||
if ($newsletter->type === Newsletter::TYPE_NOTIFICATION) {
|
||||
// generate the new schedule from options and get the new "next run" date
|
||||
$newsletter->schedule = $this->post_notification_scheduler->processPostNotificationSchedule($newsletter);
|
||||
$next_run_date = Scheduler::getNextRunDate($newsletter->schedule);
|
||||
$newsletter->schedule = $this->postNotificationScheduler->processPostNotificationSchedule($newsletter);
|
||||
$nextRunDate = Scheduler::getNextRunDate($newsletter->schedule);
|
||||
// find previously scheduled jobs and reschedule them using the new "next run" date
|
||||
SendingQueue::findTaskByNewsletterId($newsletter->id)
|
||||
->where('tasks.status', SendingQueue::STATUS_SCHEDULED)
|
||||
->findResultSet()
|
||||
->set('scheduled_at', $next_run_date)
|
||||
->set('scheduled_at', $nextRunDate)
|
||||
->save();
|
||||
}
|
||||
}
|
||||
@ -267,23 +267,23 @@ class Newsletters extends APIEndpoint {
|
||||
$newsletter->status = Newsletter::STATUS_DRAFT;
|
||||
$newsletter->save();
|
||||
} else {
|
||||
$queue->newsletter_rendered_body = null;
|
||||
$queue->newsletter_rendered_subject = null;
|
||||
$queue->newsletterRenderedBody = null;
|
||||
$queue->newsletterRenderedSubject = null;
|
||||
$newsletterQueueTask = new NewsletterQueueTask();
|
||||
$newsletterQueueTask->preProcessNewsletter($newsletter, $queue);
|
||||
}
|
||||
}
|
||||
|
||||
$this->wp->doAction('mailpoet_api_newsletters_save_after', $newsletter);
|
||||
$this->authorized_emails_controller->onNewsletterUpdate($newsletter, $old_newsletter);
|
||||
$this->authorizedEmailsController->onNewsletterUpdate($newsletter, $oldNewsletter);
|
||||
|
||||
$preview_url = NewsletterUrl::getViewInBrowserUrl(
|
||||
$previewUrl = NewsletterUrl::getViewInBrowserUrl(
|
||||
NewsletterUrl::TYPE_LISTING_EDITOR,
|
||||
$newsletter,
|
||||
Subscriber::getCurrentWPUser()
|
||||
);
|
||||
|
||||
return $this->successResponse($newsletter->asArray(), ['preview_url' => $preview_url]);
|
||||
return $this->successResponse($newsletter->asArray(), ['preview_url' => $previewUrl]);
|
||||
}
|
||||
|
||||
public function setStatus($data = []) {
|
||||
@ -295,7 +295,7 @@ class Newsletters extends APIEndpoint {
|
||||
]);
|
||||
}
|
||||
|
||||
if ($status === Newsletter::STATUS_ACTIVE && $this->subscribers_feature->check()) {
|
||||
if ($status === Newsletter::STATUS_ACTIVE && $this->subscribersFeature->check()) {
|
||||
return $this->errorResponse([
|
||||
APIError::FORBIDDEN => __('Subscribers limit reached.', 'mailpoet'),
|
||||
], [], Response::STATUS_FORBIDDEN);
|
||||
@ -319,17 +319,17 @@ class Newsletters extends APIEndpoint {
|
||||
|
||||
// if there are past due notifications, reschedule them for the next send date
|
||||
if ($newsletter->type === Newsletter::TYPE_NOTIFICATION && $status === Newsletter::STATUS_ACTIVE) {
|
||||
$next_run_date = Scheduler::getNextRunDate($newsletter->schedule);
|
||||
$nextRunDate = Scheduler::getNextRunDate($newsletter->schedule);
|
||||
$queue = $newsletter->queue()->findOne();
|
||||
if ($queue) {
|
||||
$queue->task()
|
||||
->whereLte('scheduled_at', Carbon::createFromTimestamp($this->wp->currentTime('timestamp')))
|
||||
->where('status', SendingQueue::STATUS_SCHEDULED)
|
||||
->findResultSet()
|
||||
->set('scheduled_at', $next_run_date)
|
||||
->set('scheduled_at', $nextRunDate)
|
||||
->save();
|
||||
}
|
||||
$this->post_notification_scheduler->createPostNotificationSendingTask($newsletter);
|
||||
$this->postNotificationScheduler->createPostNotificationSendingTask($newsletter);
|
||||
}
|
||||
|
||||
$newsletter = Newsletter::findOne($newsletter->id);
|
||||
@ -435,19 +435,19 @@ class Newsletters extends APIEndpoint {
|
||||
$newsletter->body = $this->emoji->encodeForUTF8Column(MP_NEWSLETTERS_TABLE, 'body', $newsletter->body);
|
||||
$newsletter->save();
|
||||
$subscriber = Subscriber::getCurrentWPUser();
|
||||
$preview_url = NewsletterUrl::getViewInBrowserUrl(
|
||||
$previewUrl = NewsletterUrl::getViewInBrowserUrl(
|
||||
NewsletterUrl::TYPE_LISTING_EDITOR,
|
||||
$newsletter,
|
||||
$subscriber
|
||||
);
|
||||
// strip protocol to avoid mix content error
|
||||
$preview_url = preg_replace('{^https?:}i', '', $preview_url);
|
||||
$previewUrl = preg_replace('{^https?:}i', '', $previewUrl);
|
||||
|
||||
$newsletter = Newsletter::findOne($newsletter->id);
|
||||
if(!$newsletter instanceof Newsletter) return $this->errorResponse();
|
||||
return $this->successResponse(
|
||||
$newsletter->asArray(),
|
||||
['preview_url' => $preview_url]
|
||||
['preview_url' => $previewUrl]
|
||||
);
|
||||
} else {
|
||||
return $this->errorResponse([
|
||||
@ -468,14 +468,14 @@ class Newsletters extends APIEndpoint {
|
||||
|
||||
if ($newsletter instanceof Newsletter) {
|
||||
$renderer = new Renderer($newsletter, $preview = true);
|
||||
$rendered_newsletter = $renderer->render();
|
||||
$renderedNewsletter = $renderer->render();
|
||||
$divider = '***MailPoet***';
|
||||
$data_for_shortcodes = array_merge(
|
||||
$dataForShortcodes = array_merge(
|
||||
[$newsletter->subject],
|
||||
$rendered_newsletter
|
||||
$renderedNewsletter
|
||||
);
|
||||
|
||||
$body = implode($divider, $data_for_shortcodes);
|
||||
$body = implode($divider, $dataForShortcodes);
|
||||
|
||||
$subscriber = Subscriber::getCurrentWPUser();
|
||||
$subscriber = ($subscriber) ? $subscriber : false;
|
||||
@ -484,22 +484,22 @@ class Newsletters extends APIEndpoint {
|
||||
$newsletter,
|
||||
$subscriber,
|
||||
$queue = false,
|
||||
$wp_user_preview = true
|
||||
$wpUserPreview = true
|
||||
);
|
||||
|
||||
list(
|
||||
$rendered_newsletter['subject'],
|
||||
$rendered_newsletter['body']['html'],
|
||||
$rendered_newsletter['body']['text']
|
||||
$renderedNewsletter['subject'],
|
||||
$renderedNewsletter['body']['html'],
|
||||
$renderedNewsletter['body']['text']
|
||||
) = explode($divider, $shortcodes->replace($body));
|
||||
$rendered_newsletter['id'] = $newsletter->id;
|
||||
$renderedNewsletter['id'] = $newsletter->id;
|
||||
|
||||
try {
|
||||
$extra_params = [
|
||||
$extraParams = [
|
||||
'unsubscribe_url' => WPFunctions::get()->homeUrl(),
|
||||
'meta' => $this->mailerMetaInfo->getPreviewMetaInfo(),
|
||||
];
|
||||
$result = $this->mailer->send($rendered_newsletter, $data['subscriber'], $extra_params);
|
||||
$result = $this->mailer->send($renderedNewsletter, $data['subscriber'], $extraParams);
|
||||
|
||||
if ($result['response'] === false) {
|
||||
$error = sprintf(
|
||||
@ -528,23 +528,23 @@ class Newsletters extends APIEndpoint {
|
||||
}
|
||||
|
||||
public function listing($data = []) {
|
||||
$listing_data = $this->listing_handler->get('\MailPoet\Models\Newsletter', $data);
|
||||
$listingData = $this->listingHandler->get('\MailPoet\Models\Newsletter', $data);
|
||||
|
||||
$data = [];
|
||||
foreach ($listing_data['items'] as $newsletter) {
|
||||
foreach ($listingData['items'] as $newsletter) {
|
||||
$queue = false;
|
||||
|
||||
if ($newsletter->type === Newsletter::TYPE_STANDARD) {
|
||||
$newsletter
|
||||
->withSegments(true)
|
||||
->withSendingQueue()
|
||||
->withStatistics($this->woocommerce_helper);
|
||||
->withStatistics($this->woocommerceHelper);
|
||||
} else if ($newsletter->type === Newsletter::TYPE_WELCOME || $newsletter->type === Newsletter::TYPE_AUTOMATIC) {
|
||||
$newsletter
|
||||
->withOptions()
|
||||
->withTotalSent()
|
||||
->withScheduledToBeSent()
|
||||
->withStatistics($this->woocommerce_helper);
|
||||
->withStatistics($this->woocommerceHelper);
|
||||
} else if ($newsletter->type === Newsletter::TYPE_NOTIFICATION) {
|
||||
$newsletter
|
||||
->withOptions()
|
||||
@ -554,7 +554,7 @@ class Newsletters extends APIEndpoint {
|
||||
$newsletter
|
||||
->withSegments(true)
|
||||
->withSendingQueue()
|
||||
->withStatistics($this->woocommerce_helper);
|
||||
->withStatistics($this->woocommerceHelper);
|
||||
}
|
||||
|
||||
if ($newsletter->status === Newsletter::STATUS_SENT ||
|
||||
@ -564,7 +564,7 @@ class Newsletters extends APIEndpoint {
|
||||
}
|
||||
|
||||
// get preview url
|
||||
$newsletter->preview_url = NewsletterUrl::getViewInBrowserUrl(
|
||||
$newsletter->previewUrl = NewsletterUrl::getViewInBrowserUrl(
|
||||
NewsletterUrl::TYPE_LISTING_EDITOR,
|
||||
$newsletter,
|
||||
$subscriber = null,
|
||||
@ -575,19 +575,19 @@ class Newsletters extends APIEndpoint {
|
||||
}
|
||||
|
||||
return $this->successResponse($data, [
|
||||
'count' => $listing_data['count'],
|
||||
'filters' => $listing_data['filters'],
|
||||
'groups' => $listing_data['groups'],
|
||||
'count' => $listingData['count'],
|
||||
'filters' => $listingData['filters'],
|
||||
'groups' => $listingData['groups'],
|
||||
'mta_log' => $this->settings->get('mta_log'),
|
||||
'mta_method' => $this->settings->get('mta.method'),
|
||||
'cron_accessible' => $this->cron_helper->isDaemonAccessible(),
|
||||
'cron_accessible' => $this->cronHelper->isDaemonAccessible(),
|
||||
'current_time' => $this->wp->currentTime('mysql'),
|
||||
]);
|
||||
}
|
||||
|
||||
public function bulkAction($data = []) {
|
||||
try {
|
||||
$meta = $this->bulk_action->apply('\MailPoet\Models\Newsletter', $data);
|
||||
$meta = $this->bulkAction->apply('\MailPoet\Models\Newsletter', $data);
|
||||
return $this->successResponse(null, $meta);
|
||||
} catch (\Exception $e) {
|
||||
return $this->errorResponse([
|
||||
@ -610,8 +610,8 @@ class Newsletters extends APIEndpoint {
|
||||
return $this->badRequest($errors);
|
||||
} else {
|
||||
// try to load template data
|
||||
$template_id = (isset($data['template']) ? (int)$data['template'] : false);
|
||||
$template = NewsletterTemplate::findOne($template_id);
|
||||
$templateId = (isset($data['template']) ? (int)$data['template'] : false);
|
||||
$template = NewsletterTemplate::findOne($templateId);
|
||||
if ($template instanceof NewsletterTemplate) {
|
||||
$newsletter->body = $template->body;
|
||||
} else {
|
||||
@ -625,16 +625,16 @@ class Newsletters extends APIEndpoint {
|
||||
return $this->badRequest($errors);
|
||||
} else {
|
||||
if (!empty($options)) {
|
||||
$option_fields = NewsletterOptionField::where(
|
||||
$optionFields = NewsletterOptionField::where(
|
||||
'newsletter_type', $newsletter->type
|
||||
)->findArray();
|
||||
|
||||
foreach ($option_fields as $option_field) {
|
||||
if (isset($options[$option_field['name']])) {
|
||||
foreach ($optionFields as $optionField) {
|
||||
if (isset($options[$optionField['name']])) {
|
||||
$relation = NewsletterOption::create();
|
||||
$relation->newsletter_id = $newsletter->id;
|
||||
$relation->option_field_id = $option_field['id'];
|
||||
$relation->value = $options[$option_field['name']];
|
||||
$relation->newsletterId = $newsletter->id;
|
||||
$relation->optionFieldId = $optionField['id'];
|
||||
$relation->value = $options[$optionField['name']];
|
||||
$relation->save();
|
||||
}
|
||||
}
|
||||
@ -648,7 +648,7 @@ class Newsletters extends APIEndpoint {
|
||||
$data['type'] === Newsletter::TYPE_NOTIFICATION
|
||||
) {
|
||||
$newsletter = Newsletter::filter('filterWithOptions', $data['type'])->findOne($newsletter->id);
|
||||
$this->post_notification_scheduler->processPostNotificationSchedule($newsletter);
|
||||
$this->postNotificationScheduler->processPostNotificationSchedule($newsletter);
|
||||
}
|
||||
|
||||
$newsletter = Newsletter::findOne($newsletter->id);
|
||||
|
@ -26,13 +26,13 @@ class Segments extends APIEndpoint {
|
||||
private $woo_commerce_sync;
|
||||
|
||||
public function __construct(
|
||||
Listing\BulkActionController $bulk_action,
|
||||
Listing\Handler $listing_handler,
|
||||
WooCommerce $woo_commerce
|
||||
Listing\BulkActionController $bulkAction,
|
||||
Listing\Handler $listingHandler,
|
||||
WooCommerce $wooCommerce
|
||||
) {
|
||||
$this->bulk_action = $bulk_action;
|
||||
$this->listing_handler = $listing_handler;
|
||||
$this->woo_commerce_sync = $woo_commerce;
|
||||
$this->bulkAction = $bulkAction;
|
||||
$this->listingHandler = $listingHandler;
|
||||
$this->wooCommerceSync = $wooCommerce;
|
||||
}
|
||||
|
||||
public function get($data = []) {
|
||||
@ -48,11 +48,11 @@ class Segments extends APIEndpoint {
|
||||
}
|
||||
|
||||
public function listing($data = []) {
|
||||
$listing_data = $this->listing_handler->get('\MailPoet\Models\Segment', $data);
|
||||
$listingData = $this->listingHandler->get('\MailPoet\Models\Segment', $data);
|
||||
|
||||
$data = [];
|
||||
foreach ($listing_data['items'] as $segment) {
|
||||
$segment->subscribers_url = WPFunctions::get()->adminUrl(
|
||||
foreach ($listingData['items'] as $segment) {
|
||||
$segment->subscribersUrl = WPFunctions::get()->adminUrl(
|
||||
'admin.php?page=mailpoet-subscribers#/filter[segment=' . $segment->id . ']'
|
||||
);
|
||||
|
||||
@ -63,9 +63,9 @@ class Segments extends APIEndpoint {
|
||||
}
|
||||
|
||||
return $this->successResponse($data, [
|
||||
'count' => $listing_data['count'],
|
||||
'filters' => $listing_data['filters'],
|
||||
'groups' => $listing_data['groups'],
|
||||
'count' => $listingData['count'],
|
||||
'filters' => $listingData['filters'],
|
||||
'groups' => $listingData['groups'],
|
||||
]);
|
||||
}
|
||||
|
||||
@ -164,7 +164,7 @@ class Segments extends APIEndpoint {
|
||||
public function synchronize($data) {
|
||||
try {
|
||||
if ($data['type'] === Segment::TYPE_WC_USERS) {
|
||||
$this->woo_commerce_sync->synchronizeCustomers();
|
||||
$this->wooCommerceSync->synchronizeCustomers();
|
||||
} else {
|
||||
WP::synchronizeUsers();
|
||||
}
|
||||
@ -179,7 +179,7 @@ class Segments extends APIEndpoint {
|
||||
|
||||
public function bulkAction($data = []) {
|
||||
try {
|
||||
$meta = $this->bulk_action->apply('\MailPoet\Models\Segment', $data);
|
||||
$meta = $this->bulkAction->apply('\MailPoet\Models\Segment', $data);
|
||||
return $this->successResponse(null, $meta);
|
||||
} catch (\Exception $e) {
|
||||
return $this->errorResponse([
|
||||
|
@ -23,23 +23,23 @@ class SendingQueue extends APIEndpoint {
|
||||
/** @var SubscribersFeature */
|
||||
private $subscribers_feature;
|
||||
|
||||
public function __construct(SubscribersFeature $subscribers_feature) {
|
||||
$this->subscribers_feature = $subscribers_feature;
|
||||
public function __construct(SubscribersFeature $subscribersFeature) {
|
||||
$this->subscribersFeature = $subscribersFeature;
|
||||
}
|
||||
|
||||
public function add($data = []) {
|
||||
if ($this->subscribers_feature->check()) {
|
||||
if ($this->subscribersFeature->check()) {
|
||||
return $this->errorResponse([
|
||||
APIError::FORBIDDEN => __('Subscribers limit reached.', 'mailpoet'),
|
||||
], [], Response::STATUS_FORBIDDEN);
|
||||
}
|
||||
$newsletter_id = (isset($data['newsletter_id'])
|
||||
$newsletterId = (isset($data['newsletter_id'])
|
||||
? (int)$data['newsletter_id']
|
||||
: false
|
||||
);
|
||||
|
||||
// check that the newsletter exists
|
||||
$newsletter = Newsletter::findOneWithOptions($newsletter_id);
|
||||
$newsletter = Newsletter::findOneWithOptions($newsletterId);
|
||||
|
||||
if (!$newsletter instanceof Newsletter) {
|
||||
return $this->errorResponse([
|
||||
@ -69,15 +69,15 @@ class SendingQueue extends APIEndpoint {
|
||||
]);
|
||||
}
|
||||
|
||||
$scheduled_queue = SendingQueueModel::joinWithTasks()
|
||||
$scheduledQueue = SendingQueueModel::joinWithTasks()
|
||||
->where('queues.newsletter_id', $newsletter->id)
|
||||
->where('tasks.status', SendingQueueModel::STATUS_SCHEDULED)
|
||||
->findOne();
|
||||
if ($scheduled_queue instanceof SendingQueueModel) {
|
||||
$queue = SendingTask::createFromQueue($scheduled_queue);
|
||||
if ($scheduledQueue instanceof SendingQueueModel) {
|
||||
$queue = SendingTask::createFromQueue($scheduledQueue);
|
||||
} else {
|
||||
$queue = SendingTask::create();
|
||||
$queue->newsletter_id = $newsletter->id;
|
||||
$queue->newsletterId = $newsletter->id;
|
||||
}
|
||||
|
||||
WordPress::resetRunInterval();
|
||||
@ -88,19 +88,19 @@ class SendingQueue extends APIEndpoint {
|
||||
|
||||
// set queue status
|
||||
$queue->status = SendingQueueModel::STATUS_SCHEDULED;
|
||||
$queue->scheduled_at = Scheduler::formatDatetimeString($newsletter->scheduledAt);
|
||||
$queue->scheduledAt = Scheduler::formatDatetimeString($newsletter->scheduledAt);
|
||||
} else {
|
||||
$segments = $newsletter->segments()->findMany();
|
||||
$finder = new SubscribersFinder();
|
||||
$subscribers_count = $finder->addSubscribersToTaskFromSegments($queue->task(), $segments);
|
||||
if (!$subscribers_count) {
|
||||
$subscribersCount = $finder->addSubscribersToTaskFromSegments($queue->task(), $segments);
|
||||
if (!$subscribersCount) {
|
||||
return $this->errorResponse([
|
||||
APIError::UNKNOWN => __('There are no subscribers in that list!', 'mailpoet'),
|
||||
]);
|
||||
}
|
||||
$queue->updateCount();
|
||||
$queue->status = null;
|
||||
$queue->scheduled_at = null;
|
||||
$queue->scheduledAt = null;
|
||||
|
||||
// set newsletter status
|
||||
$newsletter->setStatus(Newsletter::STATUS_SENDING);
|
||||
@ -118,11 +118,11 @@ class SendingQueue extends APIEndpoint {
|
||||
}
|
||||
|
||||
public function pause($data = []) {
|
||||
$newsletter_id = (isset($data['newsletter_id'])
|
||||
$newsletterId = (isset($data['newsletter_id'])
|
||||
? (int)$data['newsletter_id']
|
||||
: false
|
||||
);
|
||||
$newsletter = Newsletter::findOne($newsletter_id);
|
||||
$newsletter = Newsletter::findOne($newsletterId);
|
||||
|
||||
if ($newsletter instanceof Newsletter) {
|
||||
$queue = $newsletter->getQueue();
|
||||
@ -145,16 +145,16 @@ class SendingQueue extends APIEndpoint {
|
||||
}
|
||||
|
||||
public function resume($data = []) {
|
||||
if ($this->subscribers_feature->check()) {
|
||||
if ($this->subscribersFeature->check()) {
|
||||
return $this->errorResponse([
|
||||
APIError::FORBIDDEN => __('Subscribers limit reached.', 'mailpoet'),
|
||||
], [], Response::STATUS_FORBIDDEN);
|
||||
}
|
||||
$newsletter_id = (isset($data['newsletter_id'])
|
||||
$newsletterId = (isset($data['newsletter_id'])
|
||||
? (int)$data['newsletter_id']
|
||||
: false
|
||||
);
|
||||
$newsletter = Newsletter::findOne($newsletter_id);
|
||||
$newsletter = Newsletter::findOne($newsletterId);
|
||||
if ($newsletter instanceof Newsletter) {
|
||||
$queue = $newsletter->getQueue();
|
||||
|
||||
|
@ -32,75 +32,75 @@ class SendingTaskSubscribers extends APIEndpoint {
|
||||
private $wp;
|
||||
|
||||
public function __construct(
|
||||
Listing\Handler $listing_handler,
|
||||
Listing\Handler $listingHandler,
|
||||
SettingsController $settings,
|
||||
CronHelper $cron_helper,
|
||||
CronHelper $cronHelper,
|
||||
WPFunctions $wp
|
||||
) {
|
||||
$this->listing_handler = $listing_handler;
|
||||
$this->listingHandler = $listingHandler;
|
||||
$this->settings = $settings;
|
||||
$this->cron_helper = $cron_helper;
|
||||
$this->cronHelper = $cronHelper;
|
||||
$this->wp = $wp;
|
||||
}
|
||||
|
||||
public function listing($data = []) {
|
||||
$newsletter_id = !empty($data['params']['id']) ? (int)$data['params']['id'] : false;
|
||||
$tasks_ids = SendingQueueModel::select('task_id')
|
||||
->where('newsletter_id', $newsletter_id)
|
||||
$newsletterId = !empty($data['params']['id']) ? (int)$data['params']['id'] : false;
|
||||
$tasksIds = SendingQueueModel::select('task_id')
|
||||
->where('newsletter_id', $newsletterId)
|
||||
->findArray();
|
||||
if (empty($tasks_ids)) {
|
||||
if (empty($tasksIds)) {
|
||||
return $this->errorResponse([
|
||||
APIError::NOT_FOUND => __('This email has not been sent yet.', 'mailpoet'),
|
||||
]);
|
||||
}
|
||||
$data['params']['task_ids'] = array_column($tasks_ids, 'task_id');
|
||||
$listing_data = $this->listing_handler->get('\MailPoet\Models\ScheduledTaskSubscriber', $data);
|
||||
$data['params']['task_ids'] = array_column($tasksIds, 'task_id');
|
||||
$listingData = $this->listingHandler->get('\MailPoet\Models\ScheduledTaskSubscriber', $data);
|
||||
|
||||
$items = [];
|
||||
foreach ($listing_data['items'] as $item) {
|
||||
foreach ($listingData['items'] as $item) {
|
||||
$items[] = $item->asArray();
|
||||
}
|
||||
|
||||
return $this->successResponse($items, [
|
||||
'count' => $listing_data['count'],
|
||||
'filters' => $listing_data['filters'],
|
||||
'groups' => $listing_data['groups'],
|
||||
'count' => $listingData['count'],
|
||||
'filters' => $listingData['filters'],
|
||||
'groups' => $listingData['groups'],
|
||||
'mta_log' => $this->settings->get('mta_log'),
|
||||
'mta_method' => $this->settings->get('mta.method'),
|
||||
'cron_accessible' => $this->cron_helper->isDaemonAccessible(),
|
||||
'cron_accessible' => $this->cronHelper->isDaemonAccessible(),
|
||||
'current_time' => $this->wp->currentTime('mysql'),
|
||||
]);
|
||||
}
|
||||
|
||||
public function resend($data = []) {
|
||||
$task_id = !empty($data['taskId']) ? (int)$data['taskId'] : false;
|
||||
$subscriber_id = !empty($data['subscriberId']) ? (int)$data['subscriberId'] : false;
|
||||
$task_subscriber = ScheduledTaskSubscriber::where('task_id', $task_id)
|
||||
->where('subscriber_id', $subscriber_id)
|
||||
$taskId = !empty($data['taskId']) ? (int)$data['taskId'] : false;
|
||||
$subscriberId = !empty($data['subscriberId']) ? (int)$data['subscriberId'] : false;
|
||||
$taskSubscriber = ScheduledTaskSubscriber::where('task_id', $taskId)
|
||||
->where('subscriber_id', $subscriberId)
|
||||
->findOne();
|
||||
$task = ScheduledTask::findOne($task_id);
|
||||
$sending_queue = SendingQueueModel::where('task_id', $task_id)->findOne();
|
||||
$task = ScheduledTask::findOne($taskId);
|
||||
$sendingQueue = SendingQueueModel::where('task_id', $taskId)->findOne();
|
||||
if (
|
||||
!($task instanceof ScheduledTask)
|
||||
|| !($task_subscriber instanceof ScheduledTaskSubscriber)
|
||||
|| !($sending_queue instanceof SendingQueueModel)
|
||||
|| $task_subscriber->failed != 1
|
||||
|| !($taskSubscriber instanceof ScheduledTaskSubscriber)
|
||||
|| !($sendingQueue instanceof SendingQueueModel)
|
||||
|| $taskSubscriber->failed != 1
|
||||
) {
|
||||
return $this->errorResponse([
|
||||
APIError::NOT_FOUND => __('Failed sending task not found!', 'mailpoet'),
|
||||
]);
|
||||
}
|
||||
$newsletter = Newsletter::findOne($sending_queue->newsletter_id);
|
||||
$newsletter = Newsletter::findOne($sendingQueue->newsletterId);
|
||||
if (!($newsletter instanceof Newsletter)) {
|
||||
return $this->errorResponse([
|
||||
APIError::NOT_FOUND => __('Newsletter not found!', 'mailpoet'),
|
||||
]);
|
||||
}
|
||||
|
||||
$task_subscriber->error = '';
|
||||
$task_subscriber->failed = 0;
|
||||
$task_subscriber->processed = 0;
|
||||
$task_subscriber->save();
|
||||
$taskSubscriber->error = '';
|
||||
$taskSubscriber->failed = 0;
|
||||
$taskSubscriber->processed = 0;
|
||||
$taskSubscriber->save();
|
||||
|
||||
$task->status = null;
|
||||
$task->save();
|
||||
|
@ -41,26 +41,26 @@ class Services extends APIEndpoint {
|
||||
'global' => AccessControl::PERMISSION_MANAGE_SETTINGS,
|
||||
];
|
||||
|
||||
public function __construct(Bridge $bridge, SettingsController $settings, AnalyticsHelper $analytics, SPFCheck $spf_check, SendingServiceKeyCheck $mss_worker, PremiumKeyCheck $premium_worker) {
|
||||
public function __construct(Bridge $bridge, SettingsController $settings, AnalyticsHelper $analytics, SPFCheck $spfCheck, SendingServiceKeyCheck $mssWorker, PremiumKeyCheck $premiumWorker) {
|
||||
$this->bridge = $bridge;
|
||||
$this->settings = $settings;
|
||||
$this->analytics = $analytics;
|
||||
$this->spf_check = $spf_check;
|
||||
$this->mss_worker = $mss_worker;
|
||||
$this->premium_worker = $premium_worker;
|
||||
$this->date_time = new DateTime();
|
||||
$this->spfCheck = $spfCheck;
|
||||
$this->mssWorker = $mssWorker;
|
||||
$this->premiumWorker = $premiumWorker;
|
||||
$this->dateTime = new DateTime();
|
||||
}
|
||||
|
||||
public function checkSPFRecord($data = []) {
|
||||
$sender_address = $this->settings->get('sender.address');
|
||||
$domain_name = mb_substr($sender_address, mb_strpos($sender_address, '@') + 1);
|
||||
$senderAddress = $this->settings->get('sender.address');
|
||||
$domainName = mb_substr($senderAddress, mb_strpos($senderAddress, '@') + 1);
|
||||
|
||||
$result = $this->spf_check->checkSPFRecord($domain_name);
|
||||
$result = $this->spfCheck->checkSPFRecord($domainName);
|
||||
|
||||
if (!$result) {
|
||||
return $this->errorResponse(
|
||||
[APIError::BAD_REQUEST => WPFunctions::get()->__('SPF check has failed.', 'mailpoet')],
|
||||
['sender_address' => $sender_address]
|
||||
['sender_address' => $senderAddress]
|
||||
);
|
||||
}
|
||||
|
||||
@ -87,13 +87,13 @@ class Services extends APIEndpoint {
|
||||
|
||||
$state = !empty($result['state']) ? $result['state'] : null;
|
||||
|
||||
$success_message = null;
|
||||
$successMessage = null;
|
||||
if ($state == Bridge::KEY_VALID) {
|
||||
$success_message = WPFunctions::get()->__('Your MailPoet Sending Service key has been successfully validated.', 'mailpoet');
|
||||
$successMessage = WPFunctions::get()->__('Your MailPoet Sending Service key has been successfully validated.', 'mailpoet');
|
||||
} elseif ($state == Bridge::KEY_EXPIRING) {
|
||||
$success_message = sprintf(
|
||||
$successMessage = sprintf(
|
||||
WPFunctions::get()->__('Your MailPoet Sending Service key expires on %s!', 'mailpoet'),
|
||||
$this->date_time->formatDate(strtotime($result['data']['expire_at']))
|
||||
$this->dateTime->formatDate(strtotime($result['data']['expire_at']))
|
||||
);
|
||||
}
|
||||
|
||||
@ -101,8 +101,8 @@ class Services extends APIEndpoint {
|
||||
$this->analytics->setPublicId($result['data']['public_id']);
|
||||
}
|
||||
|
||||
if ($success_message) {
|
||||
return $this->successResponse(['message' => $success_message]);
|
||||
if ($successMessage) {
|
||||
return $this->successResponse(['message' => $successMessage]);
|
||||
}
|
||||
|
||||
switch ($state) {
|
||||
@ -149,13 +149,13 @@ class Services extends APIEndpoint {
|
||||
|
||||
$state = !empty($result['state']) ? $result['state'] : null;
|
||||
|
||||
$success_message = null;
|
||||
$successMessage = null;
|
||||
if ($state == Bridge::KEY_VALID) {
|
||||
$success_message = WPFunctions::get()->__('Your Premium key has been successfully validated.', 'mailpoet');
|
||||
$successMessage = WPFunctions::get()->__('Your Premium key has been successfully validated.', 'mailpoet');
|
||||
} elseif ($state == Bridge::KEY_EXPIRING) {
|
||||
$success_message = sprintf(
|
||||
$successMessage = sprintf(
|
||||
WPFunctions::get()->__('Your Premium key expires on %s.', 'mailpoet'),
|
||||
$this->date_time->formatDate(strtotime($result['data']['expire_at']))
|
||||
$this->dateTime->formatDate(strtotime($result['data']['expire_at']))
|
||||
);
|
||||
}
|
||||
|
||||
@ -163,9 +163,9 @@ class Services extends APIEndpoint {
|
||||
$this->analytics->setPublicId($result['data']['public_id']);
|
||||
}
|
||||
|
||||
if ($success_message) {
|
||||
if ($successMessage) {
|
||||
return $this->successResponse(
|
||||
['message' => $success_message],
|
||||
['message' => $successMessage],
|
||||
Installer::getPremiumStatus()
|
||||
);
|
||||
}
|
||||
@ -190,10 +190,10 @@ class Services extends APIEndpoint {
|
||||
}
|
||||
|
||||
public function recheckKeys() {
|
||||
$this->mss_worker->init();
|
||||
$this->mss_worker->checkKey();
|
||||
$this->premium_worker->init();
|
||||
$this->premium_worker->checkKey();
|
||||
$this->mssWorker->init();
|
||||
$this->mssWorker->checkKey();
|
||||
$this->premiumWorker->init();
|
||||
$this->premiumWorker->checkKey();
|
||||
return $this->successResponse();
|
||||
}
|
||||
|
||||
|
@ -38,13 +38,13 @@ class Settings extends APIEndpoint {
|
||||
public function __construct(
|
||||
SettingsController $settings,
|
||||
Bridge $bridge,
|
||||
AuthorizedEmailsController $authorized_emails_controller,
|
||||
TransactionalEmails $wc_transactional_emails
|
||||
AuthorizedEmailsController $authorizedEmailsController,
|
||||
TransactionalEmails $wcTransactionalEmails
|
||||
) {
|
||||
$this->settings = $settings;
|
||||
$this->bridge = $bridge;
|
||||
$this->authorized_emails_controller = $authorized_emails_controller;
|
||||
$this->wc_transactional_emails = $wc_transactional_emails;
|
||||
$this->authorizedEmailsController = $authorizedEmailsController;
|
||||
$this->wcTransactionalEmails = $wcTransactionalEmails;
|
||||
}
|
||||
|
||||
public function get() {
|
||||
@ -59,44 +59,44 @@ class Settings extends APIEndpoint {
|
||||
WPFunctions::get()->__('You have not specified any settings to be saved.', 'mailpoet'),
|
||||
]);
|
||||
} else {
|
||||
$old_settings = $this->settings->getAll();
|
||||
$signup_confirmation = $this->settings->get('signup_confirmation.enabled');
|
||||
$oldSettings = $this->settings->getAll();
|
||||
$signupConfirmation = $this->settings->get('signup_confirmation.enabled');
|
||||
foreach ($settings as $name => $value) {
|
||||
$this->settings->set($name, $value);
|
||||
}
|
||||
|
||||
$this->onSettingsChange($old_settings, $this->settings->getAll());
|
||||
$this->onSettingsChange($oldSettings, $this->settings->getAll());
|
||||
|
||||
$this->bridge->onSettingsSave($settings);
|
||||
$this->authorized_emails_controller->onSettingsSave($settings);
|
||||
if ($signup_confirmation !== $this->settings->get('signup_confirmation.enabled')) {
|
||||
$this->authorizedEmailsController->onSettingsSave($settings);
|
||||
if ($signupConfirmation !== $this->settings->get('signup_confirmation.enabled')) {
|
||||
Form::updateSuccessMessages();
|
||||
}
|
||||
return $this->successResponse($this->settings->getAll());
|
||||
}
|
||||
}
|
||||
|
||||
private function onSettingsChange($old_settings, $new_settings) {
|
||||
private function onSettingsChange($oldSettings, $newSettings) {
|
||||
// Recalculate inactive subscribers
|
||||
$old_inactivation_interval = $old_settings['deactivate_subscriber_after_inactive_days'];
|
||||
$new_inactivation_interval = $new_settings['deactivate_subscriber_after_inactive_days'];
|
||||
if ($old_inactivation_interval !== $new_inactivation_interval) {
|
||||
$oldInactivationInterval = $oldSettings['deactivate_subscriber_after_inactive_days'];
|
||||
$newInactivationInterval = $newSettings['deactivate_subscriber_after_inactive_days'];
|
||||
if ($oldInactivationInterval !== $newInactivationInterval) {
|
||||
$this->onInactiveSubscribersIntervalChange();
|
||||
}
|
||||
|
||||
// Sync WooCommerce Customers list
|
||||
$old_subscribe_old_woocommerce_customers = isset($old_settings['mailpoet_subscribe_old_woocommerce_customers']['enabled'])
|
||||
? $old_settings['mailpoet_subscribe_old_woocommerce_customers']['enabled']
|
||||
$oldSubscribeOldWoocommerceCustomers = isset($oldSettings['mailpoet_subscribe_old_woocommerce_customers']['enabled'])
|
||||
? $oldSettings['mailpoet_subscribe_old_woocommerce_customers']['enabled']
|
||||
: '0';
|
||||
$new_subscribe_old_woocommerce_customers = isset($new_settings['mailpoet_subscribe_old_woocommerce_customers']['enabled'])
|
||||
? $new_settings['mailpoet_subscribe_old_woocommerce_customers']['enabled']
|
||||
$newSubscribeOldWoocommerceCustomers = isset($newSettings['mailpoet_subscribe_old_woocommerce_customers']['enabled'])
|
||||
? $newSettings['mailpoet_subscribe_old_woocommerce_customers']['enabled']
|
||||
: '0';
|
||||
if ($old_subscribe_old_woocommerce_customers !== $new_subscribe_old_woocommerce_customers) {
|
||||
if ($oldSubscribeOldWoocommerceCustomers !== $newSubscribeOldWoocommerceCustomers) {
|
||||
$this->onSubscribeOldWoocommerceCustomersChange();
|
||||
}
|
||||
|
||||
if (!empty($new_settings['woocommerce']['use_mailpoet_editor'])) {
|
||||
$this->wc_transactional_emails->init();
|
||||
if (!empty($newSettings['woocommerce']['use_mailpoet_editor'])) {
|
||||
$this->wcTransactionalEmails->init();
|
||||
}
|
||||
}
|
||||
|
||||
@ -110,7 +110,7 @@ class Settings extends APIEndpoint {
|
||||
$task->status = ScheduledTask::STATUS_SCHEDULED;
|
||||
}
|
||||
$datetime = Carbon::createFromTimestamp(WPFunctions::get()->currentTime('timestamp'));
|
||||
$task->scheduled_at = $datetime->subMinute();
|
||||
$task->scheduledAt = $datetime->subMinute();
|
||||
$task->save();
|
||||
}
|
||||
|
||||
@ -124,7 +124,7 @@ class Settings extends APIEndpoint {
|
||||
$task->status = ScheduledTask::STATUS_SCHEDULED;
|
||||
}
|
||||
$datetime = Carbon::createFromTimestamp((int)WPFunctions::get()->currentTime('timestamp'));
|
||||
$task->scheduled_at = $datetime->subMinute();
|
||||
$task->scheduledAt = $datetime->subMinute();
|
||||
$task->save();
|
||||
}
|
||||
}
|
||||
|
@ -69,29 +69,29 @@ class Subscribers extends APIEndpoint {
|
||||
private $subscription_url_factory;
|
||||
|
||||
public function __construct(
|
||||
Listing\BulkActionController $bulk_action_controller,
|
||||
SubscribersListings $subscribers_listings,
|
||||
SubscriberActions $subscriber_actions,
|
||||
RequiredCustomFieldValidator $required_custom_field_validator,
|
||||
Listing\Handler $listing_handler,
|
||||
Captcha $subscription_captcha,
|
||||
Listing\BulkActionController $bulkActionController,
|
||||
SubscribersListings $subscribersListings,
|
||||
SubscriberActions $subscriberActions,
|
||||
RequiredCustomFieldValidator $requiredCustomFieldValidator,
|
||||
Listing\Handler $listingHandler,
|
||||
Captcha $subscriptionCaptcha,
|
||||
WPFunctions $wp,
|
||||
SettingsController $settings,
|
||||
CaptchaSession $captcha_session,
|
||||
ConfirmationEmailMailer $confirmation_email_mailer,
|
||||
SubscriptionUrlFactory $subscription_url_factory
|
||||
CaptchaSession $captchaSession,
|
||||
ConfirmationEmailMailer $confirmationEmailMailer,
|
||||
SubscriptionUrlFactory $subscriptionUrlFactory
|
||||
) {
|
||||
$this->bulk_action_controller = $bulk_action_controller;
|
||||
$this->subscribers_listings = $subscribers_listings;
|
||||
$this->subscriber_actions = $subscriber_actions;
|
||||
$this->required_custom_field_validator = $required_custom_field_validator;
|
||||
$this->listing_handler = $listing_handler;
|
||||
$this->subscription_captcha = $subscription_captcha;
|
||||
$this->bulkActionController = $bulkActionController;
|
||||
$this->subscribersListings = $subscribersListings;
|
||||
$this->subscriberActions = $subscriberActions;
|
||||
$this->requiredCustomFieldValidator = $requiredCustomFieldValidator;
|
||||
$this->listingHandler = $listingHandler;
|
||||
$this->subscriptionCaptcha = $subscriptionCaptcha;
|
||||
$this->wp = $wp;
|
||||
$this->settings = $settings;
|
||||
$this->captcha_session = $captcha_session;
|
||||
$this->confirmation_email_mailer = $confirmation_email_mailer;
|
||||
$this->subscription_url_factory = $subscription_url_factory;
|
||||
$this->captchaSession = $captchaSession;
|
||||
$this->confirmationEmailMailer = $confirmationEmailMailer;
|
||||
$this->subscriptionUrlFactory = $subscriptionUrlFactory;
|
||||
}
|
||||
|
||||
public function get($data = []) {
|
||||
@ -114,54 +114,54 @@ class Subscribers extends APIEndpoint {
|
||||
public function listing($data = []) {
|
||||
|
||||
if (!isset($data['filter']['segment'])) {
|
||||
$listing_data = $this->listing_handler->get('\MailPoet\Models\Subscriber', $data);
|
||||
$listingData = $this->listingHandler->get('\MailPoet\Models\Subscriber', $data);
|
||||
} else {
|
||||
$listing_data = $this->subscribers_listings->getListingsInSegment($data);
|
||||
$listingData = $this->subscribersListings->getListingsInSegment($data);
|
||||
}
|
||||
|
||||
$result = [];
|
||||
foreach ($listing_data['items'] as $subscriber) {
|
||||
$subscriber_result = $subscriber
|
||||
foreach ($listingData['items'] as $subscriber) {
|
||||
$subscriberResult = $subscriber
|
||||
->withSubscriptions()
|
||||
->asArray();
|
||||
if (isset($data['filter']['segment'])) {
|
||||
$subscriber_result = $this->preferUnsubscribedStatusFromSegment($subscriber_result, $data['filter']['segment']);
|
||||
$subscriberResult = $this->preferUnsubscribedStatusFromSegment($subscriberResult, $data['filter']['segment']);
|
||||
}
|
||||
$result[] = $subscriber_result;
|
||||
$result[] = $subscriberResult;
|
||||
}
|
||||
|
||||
$listing_data['filters']['segment'] = $this->wp->applyFilters(
|
||||
$listingData['filters']['segment'] = $this->wp->applyFilters(
|
||||
'mailpoet_subscribers_listings_filters_segments',
|
||||
$listing_data['filters']['segment']
|
||||
$listingData['filters']['segment']
|
||||
);
|
||||
|
||||
return $this->successResponse($result, [
|
||||
'count' => $listing_data['count'],
|
||||
'filters' => $listing_data['filters'],
|
||||
'groups' => $listing_data['groups'],
|
||||
'count' => $listingData['count'],
|
||||
'filters' => $listingData['filters'],
|
||||
'groups' => $listingData['groups'],
|
||||
]);
|
||||
}
|
||||
|
||||
private function preferUnsubscribedStatusFromSegment(array $subscriber, $segment_id) {
|
||||
$segment_status = $this->findSegmentStatus($subscriber, $segment_id);
|
||||
private function preferUnsubscribedStatusFromSegment(array $subscriber, $segmentId) {
|
||||
$segmentStatus = $this->findSegmentStatus($subscriber, $segmentId);
|
||||
|
||||
if ($segment_status === Subscriber::STATUS_UNSUBSCRIBED) {
|
||||
$subscriber['status'] = $segment_status;
|
||||
if ($segmentStatus === Subscriber::STATUS_UNSUBSCRIBED) {
|
||||
$subscriber['status'] = $segmentStatus;
|
||||
}
|
||||
return $subscriber;
|
||||
}
|
||||
|
||||
private function findSegmentStatus(array $subscriber, $segment_id) {
|
||||
private function findSegmentStatus(array $subscriber, $segmentId) {
|
||||
foreach ($subscriber['subscriptions'] as $segment) {
|
||||
if ($segment['segment_id'] === $segment_id) {
|
||||
if ($segment['segment_id'] === $segmentId) {
|
||||
return $segment['status'];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public function subscribe($data = []) {
|
||||
$form_id = (isset($data['form_id']) ? (int)$data['form_id'] : false);
|
||||
$form = Form::findOne($form_id);
|
||||
$formId = (isset($data['form_id']) ? (int)$data['form_id'] : false);
|
||||
$form = Form::findOne($formId);
|
||||
unset($data['form_id']);
|
||||
|
||||
if (!$form instanceof Form) {
|
||||
@ -175,19 +175,19 @@ class Subscribers extends APIEndpoint {
|
||||
]);
|
||||
}
|
||||
|
||||
$captcha_settings = $this->settings->get('captcha');
|
||||
$captchaSettings = $this->settings->get('captcha');
|
||||
|
||||
if (!empty($captcha_settings['type'])
|
||||
&& $captcha_settings['type'] === Captcha::TYPE_BUILTIN
|
||||
if (!empty($captchaSettings['type'])
|
||||
&& $captchaSettings['type'] === Captcha::TYPE_BUILTIN
|
||||
) {
|
||||
$captcha_session_id = isset($data['captcha_session_id']) ? $data['captcha_session_id'] : null;
|
||||
$this->captcha_session->init($captcha_session_id);
|
||||
$captchaSessionId = isset($data['captcha_session_id']) ? $data['captcha_session_id'] : null;
|
||||
$this->captchaSession->init($captchaSessionId);
|
||||
if (!isset($data['captcha'])) {
|
||||
// Save form data to session
|
||||
$this->captcha_session->setFormData(array_merge($data, ['form_id' => $form_id]));
|
||||
} elseif ($this->captcha_session->getFormData()) {
|
||||
$this->captchaSession->setFormData(array_merge($data, ['form_id' => $formId]));
|
||||
} elseif ($this->captchaSession->getFormData()) {
|
||||
// Restore form data from session
|
||||
$data = array_merge($this->captcha_session->getFormData(), ['captcha' => $data['captcha']]);
|
||||
$data = array_merge($this->captchaSession->getFormData(), ['captcha' => $data['captcha']]);
|
||||
}
|
||||
// Otherwise use the post data
|
||||
}
|
||||
@ -195,54 +195,54 @@ class Subscribers extends APIEndpoint {
|
||||
$data = $this->deobfuscateFormPayload($data);
|
||||
|
||||
try {
|
||||
$this->required_custom_field_validator->validate($data, $form);
|
||||
$this->requiredCustomFieldValidator->validate($data, $form);
|
||||
} catch (\Exception $e) {
|
||||
return $this->badRequest([APIError::BAD_REQUEST => $e->getMessage()]);
|
||||
}
|
||||
|
||||
$segment_ids = (!empty($data['segments'])
|
||||
$segmentIds = (!empty($data['segments'])
|
||||
? (array)$data['segments']
|
||||
: []
|
||||
);
|
||||
$segment_ids = $form->filterSegments($segment_ids);
|
||||
$segmentIds = $form->filterSegments($segmentIds);
|
||||
unset($data['segments']);
|
||||
|
||||
if (empty($segment_ids)) {
|
||||
if (empty($segmentIds)) {
|
||||
return $this->badRequest([
|
||||
APIError::BAD_REQUEST => WPFunctions::get()->__('Please select a list.', 'mailpoet'),
|
||||
]);
|
||||
}
|
||||
|
||||
$captcha_validation_result = $this->validateCaptcha($captcha_settings, $data);
|
||||
if ($captcha_validation_result instanceof APIResponse) {
|
||||
return $captcha_validation_result;
|
||||
$captchaValidationResult = $this->validateCaptcha($captchaSettings, $data);
|
||||
if ($captchaValidationResult instanceof APIResponse) {
|
||||
return $captchaValidationResult;
|
||||
}
|
||||
|
||||
// only accept fields defined in the form
|
||||
$form_fields = $form->getFieldList();
|
||||
$data = array_intersect_key($data, array_flip($form_fields));
|
||||
$formFields = $form->getFieldList();
|
||||
$data = array_intersect_key($data, array_flip($formFields));
|
||||
|
||||
// make sure we don't allow too many subscriptions with the same ip address
|
||||
$timeout = SubscriptionThrottling::throttle();
|
||||
|
||||
if ($timeout > 0) {
|
||||
$time_to_wait = SubscriptionThrottling::secondsToTimeString($timeout);
|
||||
$timeToWait = SubscriptionThrottling::secondsToTimeString($timeout);
|
||||
$meta = [];
|
||||
$meta['refresh_captcha'] = true;
|
||||
return $this->badRequest([
|
||||
APIError::BAD_REQUEST => sprintf(WPFunctions::get()->__('You need to wait %s before subscribing again.', 'mailpoet'), $time_to_wait),
|
||||
APIError::BAD_REQUEST => sprintf(WPFunctions::get()->__('You need to wait %s before subscribing again.', 'mailpoet'), $timeToWait),
|
||||
], $meta);
|
||||
}
|
||||
|
||||
$subscriber = $this->subscriber_actions->subscribe($data, $segment_ids);
|
||||
$subscriber = $this->subscriberActions->subscribe($data, $segmentIds);
|
||||
$errors = $subscriber->getErrors();
|
||||
|
||||
if ($errors !== false) {
|
||||
return $this->badRequest($errors);
|
||||
} else {
|
||||
if (!empty($captcha_settings['type']) && $captcha_settings['type'] === Captcha::TYPE_BUILTIN) {
|
||||
if (!empty($captchaSettings['type']) && $captchaSettings['type'] === Captcha::TYPE_BUILTIN) {
|
||||
// Captcha has been verified, invalidate the session vars
|
||||
$this->captcha_session->reset();
|
||||
$this->captchaSession->reset();
|
||||
}
|
||||
|
||||
$meta = [];
|
||||
@ -275,34 +275,34 @@ class Subscribers extends APIEndpoint {
|
||||
return $obfuscator->deobfuscateFormPayload($data);
|
||||
}
|
||||
|
||||
private function validateCaptcha($captcha_settings, $data) {
|
||||
if (empty($captcha_settings['type'])) {
|
||||
private function validateCaptcha($captchaSettings, $data) {
|
||||
if (empty($captchaSettings['type'])) {
|
||||
return true;
|
||||
}
|
||||
|
||||
$is_builtin_captcha_required = false;
|
||||
if ($captcha_settings['type'] === Captcha::TYPE_BUILTIN) {
|
||||
$is_builtin_captcha_required = $this->subscription_captcha->isRequired(isset($data['email']) ? $data['email'] : '');
|
||||
if ($is_builtin_captcha_required && empty($data['captcha'])) {
|
||||
$isBuiltinCaptchaRequired = false;
|
||||
if ($captchaSettings['type'] === Captcha::TYPE_BUILTIN) {
|
||||
$isBuiltinCaptchaRequired = $this->subscriptionCaptcha->isRequired(isset($data['email']) ? $data['email'] : '');
|
||||
if ($isBuiltinCaptchaRequired && empty($data['captcha'])) {
|
||||
$meta = [];
|
||||
$meta['redirect_url'] = $this->subscription_url_factory->getCaptchaUrl($this->captcha_session->getId());
|
||||
$meta['redirect_url'] = $this->subscriptionUrlFactory->getCaptchaUrl($this->captchaSession->getId());
|
||||
return $this->badRequest([
|
||||
APIError::BAD_REQUEST => WPFunctions::get()->__('Please fill in the CAPTCHA.', 'mailpoet'),
|
||||
], $meta);
|
||||
}
|
||||
}
|
||||
|
||||
if ($captcha_settings['type'] === Captcha::TYPE_RECAPTCHA && empty($data['recaptcha'])) {
|
||||
if ($captchaSettings['type'] === Captcha::TYPE_RECAPTCHA && empty($data['recaptcha'])) {
|
||||
return $this->badRequest([
|
||||
APIError::BAD_REQUEST => WPFunctions::get()->__('Please check the CAPTCHA.', 'mailpoet'),
|
||||
]);
|
||||
}
|
||||
|
||||
if ($captcha_settings['type'] === Captcha::TYPE_RECAPTCHA) {
|
||||
if ($captchaSettings['type'] === Captcha::TYPE_RECAPTCHA) {
|
||||
$res = empty($data['recaptcha']) ? $data['recaptcha-no-js'] : $data['recaptcha'];
|
||||
$res = WPFunctions::get()->wpRemotePost('https://www.google.com/recaptcha/api/siteverify', [
|
||||
'body' => [
|
||||
'secret' => $captcha_settings['recaptcha_secret_token'],
|
||||
'secret' => $captchaSettings['recaptcha_secret_token'],
|
||||
'response' => $res,
|
||||
],
|
||||
]);
|
||||
@ -317,14 +317,14 @@ class Subscribers extends APIEndpoint {
|
||||
APIError::BAD_REQUEST => WPFunctions::get()->__('Error while validating the CAPTCHA.', 'mailpoet'),
|
||||
]);
|
||||
}
|
||||
} elseif ($captcha_settings['type'] === Captcha::TYPE_BUILTIN && $is_builtin_captcha_required) {
|
||||
$captcha_hash = $this->captcha_session->getCaptchaHash();
|
||||
if (empty($captcha_hash)) {
|
||||
} elseif ($captchaSettings['type'] === Captcha::TYPE_BUILTIN && $isBuiltinCaptchaRequired) {
|
||||
$captchaHash = $this->captchaSession->getCaptchaHash();
|
||||
if (empty($captchaHash)) {
|
||||
return $this->badRequest([
|
||||
APIError::BAD_REQUEST => WPFunctions::get()->__('Please regenerate the CAPTCHA.', 'mailpoet'),
|
||||
]);
|
||||
} elseif (!hash_equals(strtolower($data['captcha']), $captcha_hash)) {
|
||||
$this->captcha_session->setCaptchaHash(null);
|
||||
} elseif (!hash_equals(strtolower($data['captcha']), $captchaHash)) {
|
||||
$this->captchaSession->setCaptchaHash(null);
|
||||
$meta = [];
|
||||
$meta['refresh_captcha'] = true;
|
||||
return $this->badRequest([
|
||||
@ -341,7 +341,7 @@ class Subscribers extends APIEndpoint {
|
||||
$data['segments'] = [];
|
||||
}
|
||||
$data['segments'] = array_merge($data['segments'], $this->getNonDefaultSubscribedSegments($data));
|
||||
$new_segments = $this->findNewSegments($data);
|
||||
$newSegments = $this->findNewSegments($data);
|
||||
$subscriber = Subscriber::createOrUpdate($data);
|
||||
$errors = $subscriber->getErrors();
|
||||
|
||||
@ -354,9 +354,9 @@ class Subscribers extends APIEndpoint {
|
||||
$subscriber->save();
|
||||
}
|
||||
|
||||
if (!empty($new_segments)) {
|
||||
if (!empty($newSegments)) {
|
||||
$scheduler = new WelcomeScheduler();
|
||||
$scheduler->scheduleSubscriberWelcomeNotification($subscriber->id, $new_segments);
|
||||
$scheduler->scheduleSubscriberWelcomeNotification($subscriber->id, $newSegments);
|
||||
}
|
||||
|
||||
return $this->successResponse(
|
||||
@ -369,35 +369,35 @@ class Subscribers extends APIEndpoint {
|
||||
return [];
|
||||
}
|
||||
|
||||
$subscribed_segment_ids = [];
|
||||
$non_default_segment = Segment::select('id')
|
||||
$subscribedSegmentIds = [];
|
||||
$nonDefaultSegment = Segment::select('id')
|
||||
->whereNotEqual('type', Segment::TYPE_DEFAULT)
|
||||
->findArray();
|
||||
$non_default_segment_ids = array_map(function($segment) {
|
||||
$nonDefaultSegmentIds = array_map(function($segment) {
|
||||
return $segment['id'];
|
||||
}, $non_default_segment);
|
||||
}, $nonDefaultSegment);
|
||||
|
||||
$subscribed_segments = SubscriberSegment::select('segment_id')
|
||||
$subscribedSegments = SubscriberSegment::select('segment_id')
|
||||
->where('subscriber_id', $data['id'])
|
||||
->where('status', Subscriber::STATUS_SUBSCRIBED)
|
||||
->whereIn('segment_id', $non_default_segment_ids)
|
||||
->whereIn('segment_id', $nonDefaultSegmentIds)
|
||||
->findArray();
|
||||
$subscribed_segment_ids = array_map(function($segment) {
|
||||
$subscribedSegmentIds = array_map(function($segment) {
|
||||
return $segment['segment_id'];
|
||||
}, $subscribed_segments);
|
||||
}, $subscribedSegments);
|
||||
|
||||
return $subscribed_segment_ids;
|
||||
return $subscribedSegmentIds;
|
||||
}
|
||||
|
||||
private function findNewSegments(array $data) {
|
||||
$old_segment_ids = [];
|
||||
$oldSegmentIds = [];
|
||||
if (isset($data['id']) && (int)$data['id'] > 0) {
|
||||
$old_segments = SubscriberSegment::where('subscriber_id', $data['id'])->findMany();
|
||||
foreach ($old_segments as $old_segment) {
|
||||
$old_segment_ids[] = $old_segment->segment_id;
|
||||
$oldSegments = SubscriberSegment::where('subscriber_id', $data['id'])->findMany();
|
||||
foreach ($oldSegments as $oldSegment) {
|
||||
$oldSegmentIds[] = $oldSegment->segmentId;
|
||||
}
|
||||
}
|
||||
return array_diff($data['segments'], $old_segment_ids);
|
||||
return array_diff($data['segments'], $oldSegmentIds);
|
||||
}
|
||||
|
||||
public function restore($data = []) {
|
||||
@ -453,7 +453,7 @@ class Subscribers extends APIEndpoint {
|
||||
$id = (isset($data['id']) ? (int)$data['id'] : false);
|
||||
$subscriber = Subscriber::findOne($id);
|
||||
if ($subscriber instanceof Subscriber) {
|
||||
if ($this->confirmation_email_mailer->sendConfirmationEmail($subscriber)) {
|
||||
if ($this->confirmationEmailMailer->sendConfirmationEmail($subscriber)) {
|
||||
return $this->successResponse();
|
||||
}
|
||||
return $this->errorResponse();
|
||||
@ -469,11 +469,11 @@ class Subscribers extends APIEndpoint {
|
||||
if (!isset($data['listing']['filter']['segment'])) {
|
||||
return $this->successResponse(
|
||||
null,
|
||||
$this->bulk_action_controller->apply('\MailPoet\Models\Subscriber', $data)
|
||||
$this->bulkActionController->apply('\MailPoet\Models\Subscriber', $data)
|
||||
);
|
||||
} else {
|
||||
$bulk_action = new BulkAction($data);
|
||||
return $this->successResponse(null, $bulk_action->apply());
|
||||
$bulkAction = new BulkAction($data);
|
||||
return $this->successResponse(null, $bulkAction->apply());
|
||||
}
|
||||
} catch (\Exception $e) {
|
||||
return $this->errorResponse([
|
||||
|
@ -17,8 +17,8 @@ class UserFlags extends APIEndpoint {
|
||||
'global' => AccessControl::ALL_ROLES_ACCESS,
|
||||
];
|
||||
|
||||
public function __construct(UserFlagsController $user_flags) {
|
||||
$this->user_flags = $user_flags;
|
||||
public function __construct(UserFlagsController $userFlags) {
|
||||
$this->userFlags = $userFlags;
|
||||
}
|
||||
|
||||
public function set(array $flags = []) {
|
||||
@ -30,7 +30,7 @@ class UserFlags extends APIEndpoint {
|
||||
]);
|
||||
} else {
|
||||
foreach ($flags as $name => $value) {
|
||||
$this->user_flags->set($name, $value);
|
||||
$this->userFlags->set($name, $value);
|
||||
}
|
||||
return $this->successResponse([]);
|
||||
}
|
||||
|
@ -24,7 +24,7 @@ class WoocommerceSettings extends APIEndpoint {
|
||||
|
||||
public function set($data = []) {
|
||||
foreach ($data as $option => $value) {
|
||||
if (in_array($option, $this->allowed_settings)) {
|
||||
if (in_array($option, $this->allowedSettings)) {
|
||||
$this->wp->updateOption($option, $value);
|
||||
}
|
||||
}
|
||||
|
Reference in New Issue
Block a user