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