Merge pull request #18950 from MegaphoneJon/event-44
[civicrm-core.git] / api / v3 / MailingAB.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
5 | |
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 |
9 +--------------------------------------------------------------------+
10 */
11
12 /**
13 *
14 * APIv3 functions for registering/processing mailing ab testing events.
15 *
16 * @package CiviCRM_APIv3
17 */
18
19 /**
20 * @param array $spec
21 */
22 function _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 $spec['domain_id']['api.default'] = CRM_Core_Config::domainID();
27 }
28
29 /**
30 * Handle a create mailing ab testing.
31 *
32 * @param array $params
33 *
34 * @return array
35 * API Success Array
36 */
37 function civicrm_api3_mailing_a_b_create($params) {
38 return _civicrm_api3_basic_create(_civicrm_api3_get_BAO(__FUNCTION__), $params, 'MailingAB');
39 }
40
41 /**
42 * Handle a delete event.
43 *
44 * @param array $params
45 *
46 * @return array
47 * API Success Array
48 */
49 function civicrm_api3_mailing_a_b_delete($params) {
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
57 *
58 * @return array
59 */
60 function civicrm_api3_mailing_a_b_get($params) {
61 return _civicrm_api3_basic_get(_civicrm_api3_get_BAO(__FUNCTION__), $params);
62 }
63
64 /**
65 * Adjust Metadata for submit action.
66 *
67 * The metadata is used for setting defaults, documentation & validation.
68 *
69 * @param array $spec
70 * Array of parameters determined by getfields.
71 */
72 function _civicrm_api3_mailing_a_b_submit_spec(&$spec) {
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'];
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 ];
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.
91 }
92
93 /**
94 * Send A/B mail to A/B recipients respectively.
95 *
96 * @param array $params
97 *
98 * @return array
99 * @throws API_Exception
100 */
101 function civicrm_api3_mailing_a_b_submit($params) {
102 civicrm_api3_verify_mandatory($params, 'CRM_Mailing_DAO_MailingAB', ['id', 'status']);
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 }
107
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");
112 }
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");
115 }
116
117 $submitParams = CRM_Utils_Array::subset($params, [
118 'scheduled_date',
119 'approval_date',
120 'approval_note',
121 'approval_status_id',
122 ]);
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 }
129 civicrm_api3('Mailing', 'submit', $submitParams + [
130 'id' => $dao->mailing_id_a,
131 '_skip_evil_bao_auto_recipients_' => 0,
132 ]);
133 civicrm_api3('Mailing', 'submit', $submitParams + [
134 'id' => $dao->mailing_id_b,
135 '_skip_evil_bao_auto_recipients_' => 1,
136 ]);
137 CRM_Mailing_BAO_MailingAB::distributeRecipients($dao);
138 break;
139
140 case 'Final':
141 if ($dao->status != 'Testing') {
142 throw new API_Exception("Cannot transition to state 'Final'");
143 }
144 if (!empty($params['winner_id'])) {
145 _civicrm_api3_mailing_a_b_fill_winner($params['winner_id'], $dao->mailing_id_c);
146 }
147 civicrm_api3('Mailing', 'submit', $submitParams + [
148 'id' => $dao->mailing_id_c,
149 '_skip_evil_bao_auto_recipients_' => 1,
150 ]);
151 break;
152
153 default:
154 throw new API_Exception("Unrecognized submission status");
155 }
156
157 return civicrm_api3('MailingAB', 'create', [
158 'id' => $dao->id,
159 'status' => $params['status'],
160 'options' => [
161 'reload' => 1,
162 ],
163 ]);
164 }
165
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 */
173 function _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',
198 'unsubscribe_id',
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
216 /**
217 * Adjust Metadata for graph_stats action.
218 *
219 * The metadata is used for setting defaults, documentation & validation.
220 *
221 * @param array $params
222 * Array of parameters determined by getfields.
223 */
224 function _civicrm_api3_mailing_a_b_graph_stats_spec(&$params) {
225 $params['criteria'] = [
226 'title' => 'Criteria',
227 'default' => 'Open',
228 'type' => CRM_Utils_Type::T_STRING,
229 ];
230
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;
234 $params['split_count'] = [
235 'title' => 'Split Count',
236 'api.default' => 6,
237 'type' => CRM_Utils_Type::T_INT,
238 ];
239 $params['split_count_select']['title'] = 'Split Count Select';
240 $params['split_count_select']['api.required'] = 1;
241 $params['target_url']['title'] = 'Target URL';
242 }
243
244 /**
245 * Send graph detail for A/B tests mail.
246 *
247 * @param array $params
248 *
249 * @return array
250 * @throws API_Exception
251 */
252 function civicrm_api3_mailing_a_b_graph_stats($params) {
253 civicrm_api3_verify_mandatory($params,
254 'CRM_Mailing_DAO_MailingAB',
255 ['id'],
256 FALSE
257 );
258
259 $defaults = [
260 'criteria' => 'Open',
261 'target_date' => CRM_Utils_Time::getTime('YmdHis'),
262 'split_count' => 6,
263 'split_count_select' => 1,
264 ];
265 $params = array_merge($defaults, $params);
266
267 $mailingAB = civicrm_api3('MailingAB', 'getsingle', ['id' => $params['id']]);
268 $graphStats = [];
269 $ABFormat = ['A' => 'mailing_id_a', 'B' => 'mailing_id_b'];
270
271 foreach ($ABFormat as $name => $column) {
272 switch (strtolower($params['criteria'])) {
273 case 'open':
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']);
276 $targetDate = CRM_Utils_Date::processDate($params['target_date']);
277 $dateDuration = round(round(strtotime($targetDate) - strtotime($startDate)) / $params['split_count']);
278 $toDate = strtotime($startDate) + ($dateDuration * $params['split_count_select']);
279 $toDate = date('YmdHis', $toDate);
280 $graphStats[$name] = [
281 $params['split_count_select'] => [
282 'count' => CRM_Mailing_Event_BAO_Opened::getTotalCount($mailingAB[$column], NULL, TRUE, $toDate),
283 'time' => CRM_Utils_Date::customFormat($toDate),
284 ],
285 ];
286 break;
287
288 case 'total unique clicks':
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']);
291 $targetDate = CRM_Utils_Date::processDate($params['target_date']);
292 $dateDuration = round(abs(strtotime($targetDate) - strtotime($startDate)) / $params['split_count']);
293 $toDate = strtotime($startDate) + ($dateDuration * $params['split_count_select']);
294 $toDate = date('YmdHis', $toDate);
295 $graphStats[$name] = [
296 $params['split_count_select'] => [
297 'count' => CRM_Mailing_Event_BAO_TrackableURLOpen::getTotalCount($params['mailing_id'], NULL, FALSE, NULL, $toDate),
298 'time' => CRM_Utils_Date::customFormat($toDate),
299 ],
300 ];
301 break;
302
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");
306 }
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']);
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']);
311 $targetDate = CRM_Utils_Date::processDate($params['target_date']);
312 $dateDuration = round(abs(strtotime($targetDate) - strtotime($startDate)) / $params['split_count']);
313 $toDate = strtotime($startDate) + ($dateDuration * $params['split_count_select']);
314 $toDate = CRM_Utils_Date::processDate($toDate);
315 $graphStats[$name] = [
316 $params['split_count_select'] => [
317 'count' => CRM_Mailing_Event_BAO_TrackableURLOpen::getTotalCount($params['mailing_id'], NULL, FALSE, $url_id, $toDate),
318 'time' => CRM_Utils_Date::customFormat($toDate),
319 ],
320 ];
321 break;
322 }
323 }
324
325 return civicrm_api3_create_success($graphStats);
326 }