Analytics.php
3 years ago
AutomatedLatestContent.php
2 months ago
AutomaticEmails.php
3 years ago
Captcha.php
1 year ago
Coupons.php
2 years ago
CustomFields.php
2 months ago
DynamicProducts.php
1 year ago
DynamicSegments.php
2 months ago
FeatureFlags.php
3 years ago
Forms.php
2 months ago
Help.php
1 year ago
ImportExport.php
2 months ago
Mailer.php
1 year ago
NewsletterLinks.php
2 months ago
NewsletterTemplates.php
2 months ago
Newsletters.php
2 months ago
Premium.php
10 months ago
RedirectResponse.php
1 year ago
Segments.php
2 months ago
SendingQueue.php
2 months ago
Services.php
6 months ago
Settings.php
2 months ago
Setup.php
1 year ago
StatisticsExport.php
3 months ago
SubscriberStats.php
1 month ago
Subscribers.php
2 months ago
Tags.php
3 years ago
UserFlags.php
2 years ago
WoocommerceProductVariations.php
2 months ago
WoocommerceSettings.php
3 years ago
index.php
3 years ago
Segments.php
289 lines
| 1 | <?php // phpcs:ignore SlevomatCodingStandard.TypeHints.DeclareStrictTypes.DeclareStrictTypesMissing |
| 2 | |
| 3 | namespace MailPoet\API\JSON\v1; |
| 4 | |
| 5 | if (!defined('ABSPATH')) exit; |
| 6 | |
| 7 | |
| 8 | use Exception; |
| 9 | use MailPoet\API\JSON\Endpoint as APIEndpoint; |
| 10 | use MailPoet\API\JSON\Error as APIError; |
| 11 | use MailPoet\API\JSON\Response; |
| 12 | use MailPoet\API\JSON\ResponseBuilders\SegmentsResponseBuilder; |
| 13 | use MailPoet\Config\AccessControl; |
| 14 | use MailPoet\ConflictException; |
| 15 | use MailPoet\Cron\CronWorkerScheduler; |
| 16 | use MailPoet\Cron\Workers\WooCommerceSync; |
| 17 | use MailPoet\Doctrine\Validator\ValidationException; |
| 18 | use MailPoet\Entities\SegmentEntity; |
| 19 | use MailPoet\Entities\SubscriberEntity; |
| 20 | use MailPoet\Form\FormsRepository; |
| 21 | use MailPoet\Newsletter\Segment\NewsletterSegmentRepository; |
| 22 | use MailPoet\Segments\SegmentSaveController; |
| 23 | use MailPoet\Segments\SegmentsRepository; |
| 24 | use MailPoet\Segments\SegmentSubscribersRepository; |
| 25 | use MailPoet\Segments\WP; |
| 26 | use MailPoet\Subscribers\SubscribersRepository; |
| 27 | |
| 28 | class Segments extends APIEndpoint { |
| 29 | public $permissions = [ |
| 30 | 'global' => AccessControl::PERMISSION_MANAGE_SEGMENTS, |
| 31 | ]; |
| 32 | |
| 33 | /** @var SegmentsRepository */ |
| 34 | private $segmentsRepository; |
| 35 | |
| 36 | /** @var SegmentsResponseBuilder */ |
| 37 | private $segmentsResponseBuilder; |
| 38 | |
| 39 | /** @var SegmentSaveController */ |
| 40 | private $segmentSavecontroller; |
| 41 | |
| 42 | /** @var SubscribersRepository */ |
| 43 | private $subscribersRepository; |
| 44 | |
| 45 | /** @var WP */ |
| 46 | private $wpSegment; |
| 47 | |
| 48 | /** @var NewsletterSegmentRepository */ |
| 49 | private $newsletterSegmentRepository; |
| 50 | |
| 51 | /** @var CronWorkerScheduler */ |
| 52 | private $cronWorkerScheduler; |
| 53 | |
| 54 | /** @var FormsRepository */ |
| 55 | private $formsRepository; |
| 56 | |
| 57 | /** @var SegmentSubscribersRepository */ |
| 58 | private $segmentSubscribersRepository; |
| 59 | |
| 60 | public function __construct( |
| 61 | SegmentsRepository $segmentsRepository, |
| 62 | SegmentsResponseBuilder $segmentsResponseBuilder, |
| 63 | SegmentSaveController $segmentSavecontroller, |
| 64 | SegmentSubscribersRepository $segmentSubscribersRepository, |
| 65 | SubscribersRepository $subscribersRepository, |
| 66 | WP $wpSegment, |
| 67 | NewsletterSegmentRepository $newsletterSegmentRepository, |
| 68 | CronWorkerScheduler $cronWorkerScheduler, |
| 69 | FormsRepository $formsRepository |
| 70 | ) { |
| 71 | $this->segmentsRepository = $segmentsRepository; |
| 72 | $this->segmentsResponseBuilder = $segmentsResponseBuilder; |
| 73 | $this->segmentSavecontroller = $segmentSavecontroller; |
| 74 | $this->subscribersRepository = $subscribersRepository; |
| 75 | $this->wpSegment = $wpSegment; |
| 76 | $this->newsletterSegmentRepository = $newsletterSegmentRepository; |
| 77 | $this->cronWorkerScheduler = $cronWorkerScheduler; |
| 78 | $this->formsRepository = $formsRepository; |
| 79 | $this->segmentSubscribersRepository = $segmentSubscribersRepository; |
| 80 | } |
| 81 | |
| 82 | public function get($data = []) { |
| 83 | $id = (isset($data['id']) ? (int)$data['id'] : false); |
| 84 | $segment = $this->segmentsRepository->findOneById($id); |
| 85 | if ($segment instanceof SegmentEntity) { |
| 86 | return $this->successResponse($this->segmentsResponseBuilder->build($segment)); |
| 87 | } else { |
| 88 | return $this->errorResponse([ |
| 89 | APIError::NOT_FOUND => __('This list does not exist.', 'mailpoet'), |
| 90 | ]); |
| 91 | } |
| 92 | } |
| 93 | |
| 94 | public function save($data = []) { |
| 95 | try { |
| 96 | $data['name'] = isset($data['name']) ? sanitize_text_field($data['name']) : ''; |
| 97 | $data['description'] = isset($data['description']) ? sanitize_textarea_field($data['description']) : ''; |
| 98 | if (array_key_exists('public_description', $data)) { |
| 99 | $data['public_description'] = sanitize_textarea_field((string)$data['public_description']); |
| 100 | } |
| 101 | $segment = $this->segmentSavecontroller->save($data); |
| 102 | } catch (ValidationException $exception) { |
| 103 | return $this->badRequest([ |
| 104 | APIError::BAD_REQUEST => __('Please specify a name.', 'mailpoet'), |
| 105 | ]); |
| 106 | } catch (ConflictException $exception) { |
| 107 | return $this->badRequest([ |
| 108 | APIError::BAD_REQUEST => __('Another record already exists. Please specify a different "name".', 'mailpoet'), |
| 109 | ]); |
| 110 | } |
| 111 | $response = $this->segmentsResponseBuilder->build($segment); |
| 112 | return $this->successResponse($response); |
| 113 | } |
| 114 | |
| 115 | public function restore($data = []) { |
| 116 | $segment = $this->getSegment($data); |
| 117 | if ($segment instanceof SegmentEntity) { |
| 118 | if (!$this->isTrashOrRestoreAllowed($segment)) { |
| 119 | return $this->errorResponse([ |
| 120 | APIError::FORBIDDEN => __('This list cannot be moved to trash.', 'mailpoet'), |
| 121 | ]); |
| 122 | } |
| 123 | // When the segment is of type WP_USERS we want to restore all its subscribers |
| 124 | if ($segment->getType() === SegmentEntity::TYPE_WP_USERS) { |
| 125 | $subscribers = $this->subscribersRepository->findBySegment((int)$segment->getId()); |
| 126 | $subscriberIds = array_map(function (SubscriberEntity $subscriberEntity): int { |
| 127 | return (int)$subscriberEntity->getId(); |
| 128 | }, $subscribers); |
| 129 | $this->subscribersRepository->bulkRestore($subscriberIds); |
| 130 | } |
| 131 | |
| 132 | $this->segmentsRepository->bulkRestore([$segment->getId()], $segment->getType()); |
| 133 | $this->segmentsRepository->refresh($segment); |
| 134 | return $this->successResponse( |
| 135 | $this->segmentsResponseBuilder->build($segment), |
| 136 | ['count' => 1] |
| 137 | ); |
| 138 | } else { |
| 139 | return $this->errorResponse([ |
| 140 | APIError::NOT_FOUND => __('This list does not exist.', 'mailpoet'), |
| 141 | ]); |
| 142 | } |
| 143 | } |
| 144 | |
| 145 | public function trash($data = []) { |
| 146 | $segment = $this->getSegment($data); |
| 147 | if (!$segment instanceof SegmentEntity) { |
| 148 | |
| 149 | return $this->errorResponse([ |
| 150 | APIError::NOT_FOUND => __('This list does not exist.', 'mailpoet'), |
| 151 | ]); |
| 152 | } |
| 153 | |
| 154 | if (!$this->isTrashOrRestoreAllowed($segment)) { |
| 155 | return $this->errorResponse([ |
| 156 | APIError::FORBIDDEN => __('This list cannot be moved to trash.', 'mailpoet'), |
| 157 | ]); |
| 158 | } |
| 159 | |
| 160 | $activelyUsedNewslettersSubjects = $this->newsletterSegmentRepository->getSubjectsOfActivelyUsedEmailsForSegments([$segment->getId()]); |
| 161 | if (isset($activelyUsedNewslettersSubjects[$segment->getId()])) { |
| 162 | return $this->badRequest([ |
| 163 | APIError::BAD_REQUEST => str_replace( |
| 164 | '%1$s', |
| 165 | "'" . join("', '", $activelyUsedNewslettersSubjects[$segment->getId()]) . "'", |
| 166 | // translators: %1$s is a comma-separated list of emails for which the segment is used. |
| 167 | _x('List cannot be deleted because it’s used for %1$s email', 'Alert shown when trying to delete segment, which is assigned to any automatic emails.', 'mailpoet') |
| 168 | ), |
| 169 | ]); |
| 170 | } |
| 171 | |
| 172 | $activelyUsedFormNames = $this->formsRepository->getNamesOfFormsForSegments(); |
| 173 | if (isset($activelyUsedFormNames[$segment->getId()])) { |
| 174 | return $this->badRequest([ |
| 175 | APIError::BAD_REQUEST => str_replace( |
| 176 | '%1$s', |
| 177 | "'" . join("', '", $activelyUsedFormNames[$segment->getId()]) . "'", |
| 178 | // translators: %1$s is a comma-separated list of forms for which the segment is used. |
| 179 | _nx( |
| 180 | 'List cannot be deleted because it’s used for %1$s form', |
| 181 | 'List cannot be deleted because it’s used for %1$s forms', |
| 182 | count($activelyUsedFormNames[$segment->getId()]), |
| 183 | 'Alert shown when trying to delete segment, when it is assigned to a form.', |
| 184 | 'mailpoet' |
| 185 | ) |
| 186 | ), |
| 187 | ]); |
| 188 | } |
| 189 | |
| 190 | // When the segment is of type WP_USERS we want to trash all subscribers who aren't subscribed in another list |
| 191 | if ($segment->getType() === SegmentEntity::TYPE_WP_USERS) { |
| 192 | $subscribers = $this->subscribersRepository->findExclusiveSubscribersBySegment((int)$segment->getId()); |
| 193 | $subscriberIds = array_map(function (SubscriberEntity $subscriberEntity): int { |
| 194 | return (int)$subscriberEntity->getId(); |
| 195 | }, $subscribers); |
| 196 | $this->subscribersRepository->bulkTrash($subscriberIds); |
| 197 | } |
| 198 | |
| 199 | $this->segmentsRepository->doTrash([$segment->getId()], $segment->getType()); |
| 200 | $this->segmentsRepository->refresh($segment); |
| 201 | return $this->successResponse( |
| 202 | $this->segmentsResponseBuilder->build($segment), |
| 203 | ['count' => 1] |
| 204 | ); |
| 205 | } |
| 206 | |
| 207 | public function delete($data = []) { |
| 208 | $segment = $this->getSegment($data); |
| 209 | if ($segment instanceof SegmentEntity) { |
| 210 | $this->segmentsRepository->bulkDelete([$segment->getId()]); |
| 211 | return $this->successResponse(null, ['count' => 1]); |
| 212 | } else { |
| 213 | return $this->errorResponse([ |
| 214 | APIError::NOT_FOUND => __('This list does not exist.', 'mailpoet'), |
| 215 | ]); |
| 216 | } |
| 217 | } |
| 218 | |
| 219 | public function duplicate($data = []) { |
| 220 | $segment = $this->getSegment($data); |
| 221 | |
| 222 | if ($segment instanceof SegmentEntity) { |
| 223 | try { |
| 224 | $duplicate = $this->segmentSavecontroller->duplicate($segment); |
| 225 | } catch (Exception $e) { |
| 226 | return $this->errorResponse([ |
| 227 | APIError::UNKNOWN => __('Duplicating of segment failed.', 'mailpoet'), |
| 228 | ], [], Response::STATUS_UNKNOWN); |
| 229 | } |
| 230 | return $this->successResponse( |
| 231 | $this->segmentsResponseBuilder->build($duplicate), |
| 232 | ['count' => 1] |
| 233 | ); |
| 234 | } else { |
| 235 | return $this->errorResponse([ |
| 236 | APIError::NOT_FOUND => __('This list does not exist.', 'mailpoet'), |
| 237 | ]); |
| 238 | } |
| 239 | } |
| 240 | |
| 241 | public function synchronize($data) { |
| 242 | try { |
| 243 | if ($data['type'] === SegmentEntity::TYPE_WC_USERS) { |
| 244 | $this->cronWorkerScheduler->scheduleImmediatelyIfNotRunning(WooCommerceSync::TASK_TYPE); |
| 245 | } else { |
| 246 | $this->wpSegment->synchronizeUsers(); |
| 247 | } |
| 248 | } catch (\Exception $e) { |
| 249 | return $this->errorResponse([ |
| 250 | $e->getCode() => $e->getMessage(), |
| 251 | ]); |
| 252 | } |
| 253 | |
| 254 | return $this->successResponse(null); |
| 255 | } |
| 256 | |
| 257 | public function subscriberCount($data = []) { |
| 258 | $segmentIds = $data['segmentIds'] ?? []; |
| 259 | if (empty($segmentIds)) { |
| 260 | return $this->errorResponse([ |
| 261 | APIError::BAD_REQUEST => __('No segment IDs provided.', 'mailpoet'), |
| 262 | ]); |
| 263 | } |
| 264 | $filterSegmentId = $data['filterSegmentId'] ?? null; |
| 265 | $status = $data['status'] ?? SubscriberEntity::STATUS_SUBSCRIBED; |
| 266 | $response['count'] = $this->segmentSubscribersRepository->getSubscribersCountBySegmentIds($segmentIds, $status, $filterSegmentId); |
| 267 | |
| 268 | return $this->successResponse($response); |
| 269 | } |
| 270 | |
| 271 | private function isTrashOrRestoreAllowed(SegmentEntity $segment): bool { |
| 272 | $allowedSegmentTypes = [ |
| 273 | SegmentEntity::TYPE_DEFAULT, |
| 274 | SegmentEntity::TYPE_WP_USERS, |
| 275 | ]; |
| 276 | if (in_array($segment->getType(), $allowedSegmentTypes, true)) { |
| 277 | return true; |
| 278 | } |
| 279 | |
| 280 | return false; |
| 281 | } |
| 282 | |
| 283 | private function getSegment(array $data): ?SegmentEntity { |
| 284 | return isset($data['id']) |
| 285 | ? $this->segmentsRepository->findOneById((int)$data['id']) |
| 286 | : null; |
| 287 | } |
| 288 | } |
| 289 |