Merge pull request #15850 from civicrm/5.20
[civicrm-core.git] / api / v3 / MailingAB.php
CommitLineData
4aef704e 1<?php
4aef704e 2/*
3 +--------------------------------------------------------------------+
a30c801b 4 | Copyright CiviCRM LLC. All rights reserved. |
4aef704e 5 | |
a30c801b
TO
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
4aef704e 9 +--------------------------------------------------------------------+
d25dd0ee 10 */
4aef704e 11
12/**
13 *
14 * APIv3 functions for registering/processing mailing ab testing events.
15 *
16 * @package CiviCRM_APIv3
4aef704e 17 */
18
8b06123b
TO
19/**
20 * @param array $spec
21 */
22function _civicrm_api3_mailing_a_b_create_spec(&$spec) {
23 $spec['created_date']['api.default'] = 'now';
24 $spec['created_id']['api.required'] = 1;
25 $spec['created_id']['api.default'] = 'user_contact_id';
26}
27
4aef704e 28/**
1747ab99 29 * Handle a create mailing ab testing.
4aef704e 30 *
31 * @param array $params
4aef704e 32 *
a6c01b45 33 * @return array
72b3a70c 34 * API Success Array
4aef704e 35 */
fd843187 36function civicrm_api3_mailing_a_b_create($params) {
a25b46e9 37 return _civicrm_api3_basic_create(_civicrm_api3_get_BAO(__FUNCTION__), $params, 'MailingAB');
4aef704e 38}
39
40/**
41 * Handle a delete event.
42 *
43 * @param array $params
4aef704e 44 *
a6c01b45 45 * @return array
72b3a70c 46 * API Success Array
4aef704e 47 */
fd843187 48function civicrm_api3_mailing_a_b_delete($params) {
4aef704e 49 return _civicrm_api3_basic_delete(_civicrm_api3_get_BAO(__FUNCTION__), $params);
50}
51
52/**
53 * Handle a get event.
54 *
55 * @param array $params
dc64d047 56 *
4aef704e 57 * @return array
58 */
fd843187 59function civicrm_api3_mailing_a_b_get($params) {
4aef704e 60 return _civicrm_api3_basic_get(_civicrm_api3_get_BAO(__FUNCTION__), $params);
61}
62
7811a84b 63/**
1747ab99 64 * Adjust Metadata for submit action.
7811a84b 65 *
0aa0303c
EM
66 * The metadata is used for setting defaults, documentation & validation.
67 *
481259e3 68 * @param array $spec
b081365f 69 * Array of parameters determined by getfields.
7811a84b 70 */
481259e3 71function _civicrm_api3_mailing_a_b_submit_spec(&$spec) {
768c558c
TO
72 $mailingFields = CRM_Mailing_DAO_Mailing::fields();
73 $mailingAbFields = CRM_Mailing_DAO_MailingAB::fields();
74 $spec['id'] = $mailingAbFields['id'];
75 $spec['status'] = $mailingAbFields['status'];
76 $spec['scheduled_date'] = $mailingFields['scheduled_date'];
77 $spec['approval_date'] = $mailingFields['approval_date'];
78 $spec['approval_status_id'] = $mailingFields['approval_status_id'];
79 $spec['approval_note'] = $mailingFields['approval_note'];
9ee73e80
TO
80 $spec['winner_id'] = [
81 'name' => 'winner_id',
82 'type' => 1,
83 'title' => 'Winner ID',
84 'description' => 'The experimental mailing with the best results. If specified, values are copied to the final mailing.',
85 'localizable' => 0,
86 ];
768c558c
TO
87 // Note: we'll pass through approval_* fields to the underlying mailing, but they may be ignored
88 // if the user doesn't have suitable permission. If separate approvals are required, they must be provided
89 // outside the A/B Test UI.
7811a84b 90}
91
92/**
1747ab99 93 * Send A/B mail to A/B recipients respectively.
7811a84b 94 *
95 * @param array $params
1747ab99 96 *
7811a84b 97 * @return array
768c558c 98 * @throws API_Exception
7811a84b 99 */
768c558c 100function civicrm_api3_mailing_a_b_submit($params) {
cf8f0fff 101 civicrm_api3_verify_mandatory($params, 'CRM_Mailing_DAO_MailingAB', ['id', 'status']);
768c558c
TO
102
103 if (!isset($params['scheduled_date']) && !isset($updateParams['approval_date'])) {
104 throw new API_Exception("Missing parameter scheduled_date and/or approval_date");
105 }
7811a84b 106
768c558c
TO
107 $dao = new CRM_Mailing_DAO_MailingAB();
108 $dao->id = $params['id'];
109 if (!$dao->find(TRUE)) {
110 throw new API_Exception("Failed to locate A/B test by ID");
7811a84b 111 }
768c558c
TO
112 if (empty($dao->mailing_id_a) || empty($dao->mailing_id_b) || empty($dao->mailing_id_c)) {
113 throw new API_Exception("Missing mailing IDs for A/B test");
7811a84b 114 }
115
cf8f0fff 116 $submitParams = CRM_Utils_Array::subset($params, [
768c558c
TO
117 'scheduled_date',
118 'approval_date',
119 'approval_note',
120 'approval_status_id',
cf8f0fff 121 ]);
768c558c
TO
122
123 switch ($params['status']) {
124 case 'Testing':
125 if (!empty($dao->status) && $dao->status != 'Draft') {
126 throw new API_Exception("Cannot transition to state 'Testing'");
127 }
cf8f0fff 128 civicrm_api3('Mailing', 'submit', $submitParams + [
7c31ae57
SL
129 'id' => $dao->mailing_id_a,
130 '_skip_evil_bao_auto_recipients_' => 0,
131 ]);
cf8f0fff 132 civicrm_api3('Mailing', 'submit', $submitParams + [
7c31ae57
SL
133 'id' => $dao->mailing_id_b,
134 '_skip_evil_bao_auto_recipients_' => 1,
135 ]);
768c558c
TO
136 CRM_Mailing_BAO_MailingAB::distributeRecipients($dao);
137 break;
7811a84b 138
768c558c
TO
139 case 'Final':
140 if ($dao->status != 'Testing') {
141 throw new API_Exception("Cannot transition to state 'Final'");
142 }
9ee73e80
TO
143 if (!empty($params['winner_id'])) {
144 _civicrm_api3_mailing_a_b_fill_winner($params['winner_id'], $dao->mailing_id_c);
145 }
cf8f0fff 146 civicrm_api3('Mailing', 'submit', $submitParams + [
7c31ae57
SL
147 'id' => $dao->mailing_id_c,
148 '_skip_evil_bao_auto_recipients_' => 1,
149 ]);
768c558c
TO
150 break;
151
152 default:
153 throw new API_Exception("Unrecognized submission status");
7811a84b 154 }
155
cf8f0fff 156 return civicrm_api3('MailingAB', 'create', [
768c558c
TO
157 'id' => $dao->id,
158 'status' => $params['status'],
cf8f0fff 159 'options' => [
768c558c 160 'reload' => 1,
cf8f0fff
CW
161 ],
162 ]);
467cd00c 163}
164
9ee73e80
TO
165/**
166 * @param int $winner_id
167 * The experimental mailing chosen as the "winner".
168 * @param int $final_id
169 * The final mailing which should imitate the "winner".
170 * @throws \API_Exception
171 */
172function _civicrm_api3_mailing_a_b_fill_winner($winner_id, $final_id) {
173 $copyFields = [
174 // 'id',
175 // 'name',
176 'campaign_id',
177 'from_name',
178 'from_email',
179 'replyto_email',
180 'subject',
181 'dedupe_email',
182 // 'recipients',
183 'body_html',
184 'body_text',
185 'footer_id',
186 'header_id',
187 'visibility',
188 'url_tracking',
189 'dedupe_email',
190 'forward_replies',
191 'auto_responder',
192 'open_tracking',
193 'override_verp',
194 'optout_id',
195 'reply_id',
196 'resubscribe_id',
d683bc99 197 'unsubscribe_id',
9ee73e80
TO
198 ];
199 $f = CRM_Utils_SQL_Select::from('civicrm_mailing')
200 ->where('id = #id', ['id' => $winner_id])
201 ->select($copyFields)
202 ->execute()
203 ->fetchAll();
204 if (count($f) !== 1) {
205 throw new API_Exception('Invalid winner_id');
206 }
207 foreach ($f as $winner) {
208 civicrm_api3('Mailing', 'create', $winner + [
209 'id' => $final_id,
210 '_skip_evil_bao_auto_recipients_' => 1,
211 ]);
212 }
213}
214
467cd00c 215/**
1747ab99 216 * Adjust Metadata for graph_stats action.
467cd00c 217 *
0aa0303c
EM
218 * The metadata is used for setting defaults, documentation & validation.
219 *
cf470720 220 * @param array $params
b081365f 221 * Array of parameters determined by getfields.
467cd00c 222 */
223function _civicrm_api3_mailing_a_b_graph_stats_spec(&$params) {
cf8f0fff 224 $params['criteria'] = [
d142432b
EM
225 'title' => 'Criteria',
226 'default' => 'Open',
227 'type' => CRM_Utils_Type::T_STRING,
cf8f0fff 228 ];
d142432b 229
360aaa75
TO
230 // mailing_ab_winner_criteria
231 $params['target_date']['title'] = 'Target Date';
232 $params['target_date']['type'] = CRM_Utils_Type::T_DATE + CRM_Utils_Type::T_TIME;
cf8f0fff 233 $params['split_count'] = [
d142432b
EM
234 'title' => 'Split Count',
235 'api.default' => 6,
236 'type' => CRM_Utils_Type::T_INT,
cf8f0fff 237 ];
bd6658bd 238 $params['split_count_select']['title'] = 'Split Count Select';
202ebbab 239 $params['split_count_select']['api.required'] = 1;
360aaa75 240 $params['target_url']['title'] = 'Target URL';
202ebbab 241}
467cd00c 242
243/**
1747ab99 244 * Send graph detail for A/B tests mail.
467cd00c 245 *
246 * @param array $params
1747ab99 247 *
467cd00c 248 * @return array
360aaa75 249 * @throws API_Exception
467cd00c 250 */
251function civicrm_api3_mailing_a_b_graph_stats($params) {
202ebbab 252 civicrm_api3_verify_mandatory($params,
253 'CRM_Mailing_DAO_MailingAB',
cf8f0fff 254 ['id'],
202ebbab 255 FALSE
256 );
467cd00c 257
cf8f0fff 258 $defaults = [
360aaa75
TO
259 'criteria' => 'Open',
260 'target_date' => CRM_Utils_Time::getTime('YmdHis'),
261 'split_count' => 6,
262 'split_count_select' => 1,
cf8f0fff 263 ];
360aaa75 264 $params = array_merge($defaults, $params);
202ebbab 265
cf8f0fff
CW
266 $mailingAB = civicrm_api3('MailingAB', 'getsingle', ['id' => $params['id']]);
267 $graphStats = [];
268 $ABFormat = ['A' => 'mailing_id_a', 'B' => 'mailing_id_b'];
467cd00c 269
202ebbab 270 foreach ($ABFormat as $name => $column) {
360aaa75
TO
271 switch (strtolower($params['criteria'])) {
272 case 'open':
768c558c
TO
273 $result = CRM_Mailing_Event_BAO_Opened::getRows($mailingAB['mailing_id_a'], NULL, TRUE, 0, 1, "civicrm_mailing_event_opened.time_stamp ASC");
274 $startDate = CRM_Utils_Date::processDate($result[0]['date']);
360aaa75
TO
275 $targetDate = CRM_Utils_Date::processDate($params['target_date']);
276 $dateDuration = round(round(strtotime($targetDate) - strtotime($startDate)) / $params['split_count']);
202ebbab 277 $toDate = strtotime($startDate) + ($dateDuration * $params['split_count_select']);
278 $toDate = date('YmdHis', $toDate);
cf8f0fff
CW
279 $graphStats[$name] = [
280 $params['split_count_select'] => [
202ebbab 281 'count' => CRM_Mailing_Event_BAO_Opened::getTotalCount($mailingAB[$column], NULL, TRUE, $toDate),
21dfd5f5 282 'time' => CRM_Utils_Date::customFormat($toDate),
cf8f0fff
CW
283 ],
284 ];
202ebbab 285 break;
ea100cb5 286
360aaa75 287 case 'total unique clicks':
202ebbab 288 $result = CRM_Mailing_Event_BAO_TrackableURLOpen::getRows($mailingAB['mailing_id_a'], NULL, TRUE, 0, 1, "civicrm_mailing_event_trackable_url_open.time_stamp ASC");
289 $startDate = CRM_Utils_Date::processDate($result[0]['date']);
360aaa75
TO
290 $targetDate = CRM_Utils_Date::processDate($params['target_date']);
291 $dateDuration = round(abs(strtotime($targetDate) - strtotime($startDate)) / $params['split_count']);
202ebbab 292 $toDate = strtotime($startDate) + ($dateDuration * $params['split_count_select']);
293 $toDate = date('YmdHis', $toDate);
cf8f0fff
CW
294 $graphStats[$name] = [
295 $params['split_count_select'] => [
202ebbab 296 'count' => CRM_Mailing_Event_BAO_TrackableURLOpen::getTotalCount($params['mailing_id'], NULL, FALSE, NULL, $toDate),
21dfd5f5 297 'time' => CRM_Utils_Date::customFormat($toDate),
cf8f0fff
CW
298 ],
299 ];
202ebbab 300 break;
ea100cb5 301
360aaa75
TO
302 case 'total clicks on a particular link':
303 if (empty($params['target_url'])) {
304 throw new API_Exception("Provide url to get stats result for total clicks on a particular link");
202ebbab 305 }
360aaa75
TO
306 // FIXME: doesn't make sense to get url_id mailing_id_(a|b) while getting start date in mailing_id_a
307 $url_id = CRM_Mailing_BAO_TrackableURL::getTrackerURLId($mailingAB[$column], $params['target_url']);
202ebbab 308 $result = CRM_Mailing_Event_BAO_TrackableURLOpen::getRows($mailingAB['mailing_id_a'], NULL, FALSE, $url_id, 0, 1, "civicrm_mailing_event_trackable_url_open.time_stamp ASC");
309 $startDate = CRM_Utils_Date::processDate($result[0]['date']);
360aaa75
TO
310 $targetDate = CRM_Utils_Date::processDate($params['target_date']);
311 $dateDuration = round(abs(strtotime($targetDate) - strtotime($startDate)) / $params['split_count']);
202ebbab 312 $toDate = strtotime($startDate) + ($dateDuration * $params['split_count_select']);
313 $toDate = CRM_Utils_Date::processDate($toDate);
cf8f0fff
CW
314 $graphStats[$name] = [
315 $params['split_count_select'] => [
202ebbab 316 'count' => CRM_Mailing_Event_BAO_TrackableURLOpen::getTotalCount($params['mailing_id'], NULL, FALSE, $url_id, $toDate),
21dfd5f5 317 'time' => CRM_Utils_Date::customFormat($toDate),
cf8f0fff
CW
318 ],
319 ];
202ebbab 320 break;
321 }
322 }
323
324 return civicrm_api3_create_success($graphStats);
b0f9e1df 325}