Cleanup uses of CRM_Utils_Array::value related to numbers
[civicrm-core.git] / CRM / Event / Form / SelfSvcTransfer.php
CommitLineData
97d8187a
DG
1<?php
2
3/*
4 +--------------------------------------------------------------------+
bc77d7c0 5 | Copyright CiviCRM LLC. All rights reserved. |
97d8187a 6 | |
bc77d7c0
TO
7 | This work is published under the GNU AGPLv3 license with some |
8 | permitted exceptions and without any warranty. For full license |
9 | and copyright information, see https://civicrm.org/licensing |
97d8187a
DG
10 +--------------------------------------------------------------------+
11 */
12
13/**
14 *
15 * @package CRM
ca5cec67 16 * @copyright CiviCRM LLC https://civicrm.org/licensing
97d8187a
DG
17 */
18
19/**
20 * This class generates form components to transfer an Event to another participant
21 *
22 */
23class CRM_Event_Form_SelfSvcTransfer extends CRM_Core_Form {
24 /**
25 * from particpant id
26 *
27 * @var string
28 *
29 */
30 protected $_from_participant_id;
31 /**
32 * from contact id
33 *
34 * @var string
35 *
36 */
37 protected $_from_contact_id;
38 /**
39 * last name of the particpant to transfer to
40 *
41 * @var string
42 *
43 */
44 protected $_to_contact_last_name;
45 /**
46 * first name of the particpant to transfer to
47 *
48 * @var string
49 *
50 */
51 protected $_to_contact_first_name;
52 /**
53 * email of participant
54 *
55 *
56 * @var string
57 */
58 protected $_to_contact_email;
59 /**
60 * _to_contact_id
61 *
62 * @var string
63 */
64 protected $_to_contact_id;
65 /**
66 * event to be cancelled/transferred
67 *
68 * @var string
69 */
70 protected $_event_id;
71 /**
72 * event title
73 *
74 * @var string
75 */
76 protected $_event_title;
77 /**
78 * event title
79 *
80 * @var string
81 */
82 protected $_event_start_date;
83 /**
84 * action
85 *
86 * @var string
87 */
3a936dab 88 public $_action;
97d8187a
DG
89 /**
90 * participant object
91 *
92 * @var string
93 */
be2fb01f 94 protected $_participant = [];
97d8187a
DG
95 /**
96 * particpant values
97 *
90b461f1 98 * @var string
97d8187a
DG
99 */
100 protected $_part_values;
101 /**
102 * details
103 *
90b461f1 104 * @var array
97d8187a 105 */
be2fb01f 106 protected $_details = [];
97d8187a
DG
107 /**
108 * line items
109 *
90b461f1 110 * @var array
97d8187a 111 */
be2fb01f 112 protected $_line_items = [];
97d8187a
DG
113 /**
114 * contact_id
115 *
90b461f1 116 * @var int
97d8187a
DG
117 */
118 protected $contact_id;
974bdb44 119
e219d53b 120 /**
121 * Is backoffice form?
122 *
90b461f1 123 * @var bool
e219d53b 124 */
125 protected $isBackoffice = FALSE;
126
97d8187a
DG
127 /**
128 * Get source values for transfer based on participant id in URL. Line items will
129 * be transferred to this participant - at this point no transaction changes processed
130 *
131 * return @void
5db18d97 132 *
133 * @throws \CRM_Core_Exception
97d8187a
DG
134 */
135 public function preProcess() {
97d8187a
DG
136 $session = CRM_Core_Session::singleton();
137 $this->_userContext = $session->readUserContext();
138 $this->_from_participant_id = CRM_Utils_Request::retrieve('pid', 'Positive', $this, FALSE, NULL, 'REQUEST');
af29aaac 139 $this->_userChecksum = CRM_Utils_Request::retrieve('cs', 'String', $this, FALSE, NULL, 'REQUEST');
e219d53b 140 $this->isBackoffice = CRM_Utils_Request::retrieve('is_backoffice', 'String', $this, FALSE, NULL, 'REQUEST');
be2fb01f
CW
141 $params = ['id' => $this->_from_participant_id];
142 $participant = $values = [];
97d8187a
DG
143 $this->_participant = CRM_Event_BAO_Participant::getValues($params, $values, $participant);
144 $this->_part_values = $values[$this->_from_participant_id];
145 $this->set('values', $this->_part_values);
146 $this->_event_id = $this->_part_values['event_id'];
af29aaac 147 $url = CRM_Utils_System::url('civicrm/event/info', "reset=1&id={$this->_event_id}");
97d8187a 148 $this->_from_contact_id = $this->_part_values['participant_contact_id'];
af29aaac 149 $validUser = CRM_Contact_BAO_Contact_Utils::validChecksum($this->_from_contact_id, $this->_userChecksum);
150 if (!$validUser && !CRM_Core_Permission::check('edit all events')) {
151 CRM_Core_Error::statusBounce(ts('You do not have sufficient permission to transfer/cancel this participant.'), $url);
152 }
97d8187a
DG
153 $this->assign('action', $this->_action);
154 if ($this->_from_participant_id) {
155 $this->assign('participantId', $this->_from_participant_id);
156 }
5db18d97 157
97d8187a
DG
158 $daoName = 'title';
159 $this->_event_title = CRM_Event_BAO_Event::getFieldValue('CRM_Event_DAO_Event', $this->_event_id, $daoName);
160 $daoName = 'start_date';
161 $this->_event_start_date = CRM_Event_BAO_Event::getFieldValue('CRM_Event_DAO_Event', $this->_event_id, $daoName);
162 list($displayName, $email) = CRM_Contact_BAO_Contact_Location::getEmailDetails($this->_from_contact_id);
163 $this->_contact_name = $displayName;
164 $this->_contact_email = $email;
5db18d97 165
97d8187a 166 $details = CRM_Event_BAO_Participant::participantDetails($this->_from_participant_id);
4a3451de
JG
167 $selfServiceDetails = CRM_Event_BAO_Participant::getSelfServiceEligibility($this->_from_participant_id, $url, $this->isBackoffice);
168 $details = array_merge($details, $selfServiceDetails);
97d8187a
DG
169 $this->assign('details', $details);
170 //This participant row will be cancelled. Get line item(s) to cancel
171 $this->selfsvctransferUrl = CRM_Utils_System::url('civicrm/event/selfsvcupdate',
172 "reset=1&id={$this->_from_participant_id}&id=0");
173 $this->selfsvctransferText = ts('Update');
174 $this->selfsvctransferButtonText = ts('Update');
175 }
974bdb44 176
97d8187a
DG
177 /**
178 * Build form for input of transferree email, name
179 *
180 * return @void
181 */
182 public function buildQuickForm() {
e219d53b 183 // use entityRef select field for contact when this form is used by staff/admin user
184 if ($this->isBackoffice) {
be2fb01f 185 $this->addEntityRef("contact_id", ts('Select Contact'), ['create' => TRUE], TRUE);
e219d53b 186 }
187 // for front-end user show and use the basic three fields used to create a contact
188 else {
6dabf459
ML
189 $this->add('text', 'email', ts('To Email'), $this->_contact_email, TRUE);
190 $this->add('text', 'last_name', ts('To Last Name'), $this->_to_contact_last_name, TRUE);
191 $this->add('text', 'first_name', ts('To First Name'), $this->_to_contact_first_name, TRUE);
e219d53b 192 }
193
be2fb01f
CW
194 $this->addButtons([
195 [
97d8187a 196 'type' => 'submit',
be2fb01f
CW
197 'name' => ts('Transfer Registration'),
198 ],
199 ]);
200 $this->addFormRule(['CRM_Event_Form_SelfSvcTransfer', 'formRule'], $this);
97d8187a
DG
201 parent::buildQuickForm();
202 }
974bdb44 203
97d8187a
DG
204 /**
205 * Set defaults
206 *
207 * return @array _defaults
208 */
209 public function setDefaultValues() {
be2fb01f 210 $this->_defaults = [];
97d8187a
DG
211 return $this->_defaults;
212 }
974bdb44 213
97d8187a
DG
214 /**
215 * Validate email and name input
216 *
217 * return array $errors
218 */
219 public static function formRule($fields, $files, $self) {
be2fb01f 220 $errors = [];
e219d53b 221 if (!empty($fields['contact_id'])) {
222 $to_contact_id = $fields['contact_id'];
223 }
224 else {
225 //check that either an email or firstname+lastname is included in the form(CRM-9587)
226 $to_contact_id = self::checkProfileComplete($fields, $errors, $self);
227 }
97d8187a 228 //To check if the user is already registered for the event(CRM-2426)
e219d53b 229 if (!empty($to_contact_id)) {
e3b510fe 230 self::checkRegistration($fields, $self, $to_contact_id, $errors);
231 }
97d8187a
DG
232 //return parent::formrule($fields, $files, $self);
233 return empty($errors) ? TRUE : $errors;
234 }
974bdb44 235
97d8187a
DG
236 /**
237 * Check whether profile (name, email) is complete
238 *
239 * return $contact_id
240 */
241 public static function checkProfileComplete($fields, &$errors, $self) {
242 $email = '';
243 foreach ($fields as $fieldname => $fieldvalue) {
244 if (substr($fieldname, 0, 5) == 'email' && $fieldvalue) {
245 $email = $fieldvalue;
246 }
247 }
248 if (!$email && !(CRM_Utils_Array::value('first_name', $fields) &&
249 CRM_Utils_Array::value('last_name', $fields))) {
be2fb01f 250 $defaults = $params = ['id' => $eventId];
97d8187a
DG
251 CRM_Event_BAO_Event::retrieve($params, $defaults);
252 $message = ts("Mandatory fields (first name and last name, OR email address) are missing from this form.");
253 $errors['_qf_default'] = $message;
254 }
255 $contact = CRM_Contact_BAO_Contact::matchContactOnEmail($email, "");
256 $contact_id = empty($contact->contact_id) ? NULL : $contact->contact_id;
e3b510fe 257 if (!CRM_Utils_Rule::email($fields['email'])) {
258 $errors['email'] = ts('Enter valid email address.');
259 }
260 if (empty($errors) && empty($contact_id)) {
be2fb01f 261 $params = [
6187cca4
CW
262 'email-Primary' => $fields['email'] ?? NULL,
263 'first_name' => $fields['first_name'] ?? NULL,
264 'last_name' => $fields['last_name'] ?? NULL,
265 'is_deleted' => $fields['is_deleted'] ?? FALSE,
be2fb01f 266 ];
97d8187a
DG
267 //create new contact for this name/email pair
268 //if new contact, no need to check for contact already registered
269 $contact_id = CRM_Contact_BAO_Contact::createProfileContact($params, $fields, $contact_id);
270 }
271 return $contact_id;
272 }
974bdb44 273
97d8187a
DG
274 /**
275 * Check contact details
276 *
277 * return @void
278 */
4abc4ee1 279 public static function checkRegistration($fields, $self, $contact_id, &$errors) {
97d8187a 280 // verify whether this contact already registered for this event
97d8187a
DG
281 $contact_details = CRM_Contact_BAO_Contact::getContactDetails($contact_id);
282 $display_name = $contact_details[0];
5db18d97 283 $query = 'select event_id from civicrm_participant where contact_id = ' . $contact_id;
33621c4f 284 $dao = CRM_Core_DAO::executeQuery($query);
97d8187a 285 while ($dao->fetch()) {
90b461f1 286 $to_event_id[] = $dao->event_id;
97d8187a
DG
287 }
288 if (!empty($to_event_id)) {
289 foreach ($to_event_id as $id) {
290 if ($id == $self->_event_id) {
4abc4ee1 291 $errors['email'] = $display_name . ts(" is already registered for this event");
97d8187a
DG
292 }
293 }
294 }
295 }
974bdb44 296
97d8187a
DG
297 /**
298 * Process transfer - first add the new participant to the event, then cancel
299 * source participant - send confirmation email to transferee
5db18d97 300 *
301 * @throws \CiviCRM_API3_Exception
97d8187a
DG
302 */
303 public function postProcess() {
304 //For transfer, process form to allow selection of transferree
305 $params = $this->controller->exportValues($this->_name);
e219d53b 306 if (!empty($params['contact_id'])) {
307 $contact_id = $params['contact_id'];
308 }
309 else {
310 //cancel 'from' participant row
be2fb01f 311 $contact_id_result = civicrm_api3('Contact', 'get', [
d4a64d9a 312 'sequential' => 1,
5db18d97 313 'return' => ['id'],
d4a64d9a 314 'email' => $params['email'],
be2fb01f
CW
315 'options' => ['limit' => 1],
316 ]);
d4a64d9a
AS
317 $contact_id_result = $contact_id_result['values'][0];
318 $contact_id = $contact_id_result['contact_id'];
319 $contact_is_deleted = $contact_id_result['contact_is_deleted'];
320 if ($contact_is_deleted || !is_numeric($contact_id)) {
2ddf0fcd 321 CRM_Core_Error::statusBounce(ts('Contact does not exist.'));
e219d53b 322 }
97d8187a 323 }
5db18d97 324
325 $query = 'select role_id, source, fee_level, is_test, is_pay_later, fee_amount, discount_id, fee_currency,campaign_id, discount_amount from civicrm_participant where id = ' . $this->_from_participant_id;
33621c4f 326 $dao = CRM_Core_DAO::executeQuery($query);
be2fb01f 327 $value_to = [];
97d8187a
DG
328 while ($dao->fetch()) {
329 $value_to['role_id'] = $dao->role_id;
330 $value_to['source'] = $dao->source;
331 $value_to['fee_level'] = $dao->fee_level;
332 $value_to['is_test'] = $dao->is_test;
333 $value_to['is_pay_later'] = $dao->is_pay_later;
334 $value_to['fee_amount'] = $dao->fee_amount;
335 }
336 $value_to['contact_id'] = $contact_id;
337 $value_to['event_id'] = $this->_event_id;
35538401
PN
338 $value_to['status_id'] = CRM_Core_PseudoConstant::getKey(
339 'CRM_Event_BAO_Participant',
340 'status_id',
341 'Registered'
342 );
97d8187a
DG
343 $value_to['register_date'] = date("Y-m-d");
344 //first create the new participant row -don't set registered_by yet or email won't be sent
345 $participant = CRM_Event_BAO_Participant::create($value_to);
346 //send a confirmation email to the new participant
e3b510fe 347 $this->participantTransfer($participant);
97d8187a
DG
348 //now update registered_by_id
349 $query = "UPDATE civicrm_participant cp SET cp.registered_by_id = %1 WHERE cp.id = ({$participant->id})";
be2fb01f 350 $params = [1 => [$this->_from_participant_id, 'Integer']];
97d8187a
DG
351 $dao = CRM_Core_DAO::executeQuery($query, $params);
352 //copy line items to new participant
353 $line_items = CRM_Price_BAO_LineItem::getLineItems($this->_from_participant_id);
354 foreach ($line_items as $item) {
355 $item['entity_id'] = $participant->id;
356 $item['id'] = NULL;
357 $item['entity_table'] = "civicrm_participant";
358 $new_item = CRM_Price_BAO_LineItem::create($item);
359 }
360 //now cancel the from participant record, leaving the original line-item(s)
be2fb01f 361 $value_from = [];
97d8187a
DG
362 $value_from['id'] = $this->_from_participant_id;
363 $tansferId = array_search('Transferred', CRM_Event_PseudoConstant::participantStatus(NULL, "class = 'Negative'"));
364 $value_from['status_id'] = $tansferId;
365 $value_from['transferred_to_contact_id'] = $contact_id;
366 $contact_details = CRM_Contact_BAO_Contact::getContactDetails($contact_id);
367 $display_name = current($contact_details);
368 $this->assign('to_participant', $display_name);
369 CRM_Event_BAO_Participant::create($value_from);
370 $this->sendCancellation();
371 list($displayName, $email) = CRM_Contact_BAO_Contact_Location::getEmailDetails($contact_id);
be2fb01f
CW
372 $statusMsg = ts('Event registration information for %1 has been updated.', [1 => $displayName]);
373 $statusMsg .= ' ' . ts('A confirmation email has been sent to %1.', [1 => $email]);
974bdb44 374 CRM_Core_Session::setStatus($statusMsg, ts('Registration Transferred'), 'success');
e219d53b 375 if ($this->isBackoffice) {
376 return;
377 }
e3b510fe 378 $url = CRM_Utils_System::url('civicrm/event/info', "reset=1&id={$this->_event_id}");
379 CRM_Utils_System::redirect($url);
97d8187a 380 }
974bdb44 381
97d8187a
DG
382 /**
383 * Based on input, create participant row for transferee and send email
384 *
385 * return @ void
5db18d97 386 *
387 * @throws \CRM_Core_Exception
97d8187a
DG
388 */
389 public function participantTransfer($participant) {
be2fb01f 390 $contactDetails = [];
97d8187a
DG
391 $contactIds[] = $participant->contact_id;
392 list($currentContactDetails) = CRM_Utils_Token::getTokenDetails($contactIds, NULL,
be2fb01f 393 FALSE, FALSE, NULL, [], 'CRM_Event_BAO_Participant');
97d8187a
DG
394 foreach ($currentContactDetails as $contactId => $contactValues) {
395 $contactDetails[$contactId] = $contactValues;
396 }
397 $participantRoles = CRM_Event_PseudoConstant::participantRole();
be2fb01f 398 $participantDetails = [];
97d8187a
DG
399 $query = "SELECT * FROM civicrm_participant WHERE id = " . $participant->id;
400 $dao = CRM_Core_DAO::executeQuery($query);
401 while ($dao->fetch()) {
be2fb01f 402 $participantDetails[$dao->id] = [
97d8187a
DG
403 'id' => $dao->id,
404 'role' => $participantRoles[$dao->role_id],
405 'is_test' => $dao->is_test,
406 'event_id' => $dao->event_id,
407 'status_id' => $dao->status_id,
408 'fee_amount' => $dao->fee_amount,
409 'contact_id' => $dao->contact_id,
410 'register_date' => $dao->register_date,
411 'registered_by_id' => $dao->registered_by_id,
be2fb01f 412 ];
97d8187a 413 }
be2fb01f 414 $domainValues = [];
97d8187a
DG
415 if (empty($domainValues)) {
416 $domain = CRM_Core_BAO_Domain::getDomain();
be2fb01f 417 $tokens = [
97d8187a 418 'domain' =>
be2fb01f 419 [
97d8187a
DG
420 'name',
421 'phone',
422 'address',
423 'email',
be2fb01f 424 ],
97d8187a 425 'contact' => CRM_Core_SelectValues::contactTokens(),
be2fb01f 426 ];
97d8187a
DG
427 foreach ($tokens['domain'] as $token) {
428 $domainValues[$token] = CRM_Utils_Token::getDomainTokenReplacement($token, $domain);
429 }
430 }
be2fb01f
CW
431 $eventDetails = [];
432 $eventParams = ['id' => $participant->event_id];
e3b510fe 433 CRM_Event_BAO_Event::retrieve($eventParams, $eventDetails);
97d8187a 434 //get default participant role.
e3b510fe 435 $eventDetails['participant_role'] = CRM_Utils_Array::value($eventDetails['default_role_id'], $participantRoles);
97d8187a 436 //get the location info
be2fb01f 437 $locParams = [
97d8187a
DG
438 'entity_id' => $participant->event_id,
439 'entity_table' => 'civicrm_event',
be2fb01f 440 ];
e3b510fe 441 $eventDetails['location'] = CRM_Core_BAO_Location::getValues($locParams, TRUE);
442 $toEmail = CRM_Utils_Array::value('email', $contactDetails[$participant->contact_id]);
443 if ($toEmail) {
444 //take a receipt from as event else domain.
445 $receiptFrom = $domainValues['name'] . ' <' . $domainValues['email'] . '>';
446 if (!empty($eventDetails['confirm_from_name']) && !empty($eventDetails['confirm_from_email'])) {
447 $receiptFrom = $eventDetails['confirm_from_name'] . ' <' . $eventDetails['confirm_from_email'] . '>';
448 }
449 $participantName = $contactDetails[$participant->contact_id]['display_name'];
be2fb01f 450 $tplParams = [
e3b510fe 451 'event' => $eventDetails,
452 'participant' => $participantDetails[$participant->id],
453 'participantID' => $participant->id,
454 'participant_status' => 'Registered',
be2fb01f 455 ];
e3b510fe 456
be2fb01f 457 $sendTemplateParams = [
e3b510fe 458 'groupName' => 'msg_tpl_workflow_event',
459 'valueName' => 'event_online_receipt',
460 'contactId' => $participantDetails[$participant->id]['contact_id'],
461 'tplParams' => $tplParams,
462 'from' => $receiptFrom,
463 'toName' => $participantName,
464 'toEmail' => $toEmail,
6b409353
CW
465 'cc' => $eventDetails['cc_confirm'] ?? NULL,
466 'bcc' => $eventDetails['bcc_confirm'] ?? NULL,
be2fb01f 467 ];
e3b510fe 468 CRM_Core_BAO_MessageTemplate::sendTemplate($sendTemplateParams);
469 }
97d8187a 470 }
974bdb44 471
97d8187a
DG
472 /**
473 * Send confirmation of cancellation to source participant
474 *
475 * return @ void
476 */
477 public function sendCancellation() {
be2fb01f 478 $domainValues = [];
97d8187a 479 $domain = CRM_Core_BAO_Domain::getDomain();
be2fb01f 480 $tokens = [
97d8187a 481 'domain' =>
be2fb01f 482 [
97d8187a
DG
483 'name',
484 'phone',
485 'address',
486 'email',
be2fb01f 487 ],
97d8187a 488 'contact' => CRM_Core_SelectValues::contactTokens(),
be2fb01f 489 ];
97d8187a
DG
490 foreach ($tokens['domain'] as $token) {
491 $domainValues[$token] = CRM_Utils_Token::getDomainTokenReplacement($token, $domain);
492 }
5db18d97 493
97d8187a 494 $participantRoles = CRM_Event_PseudoConstant::participantRole();
be2fb01f 495 $participantDetails = [];
97d8187a
DG
496 $query = "SELECT * FROM civicrm_participant WHERE id = {$this->_from_participant_id}";
497 $dao = CRM_Core_DAO::executeQuery($query);
498 while ($dao->fetch()) {
be2fb01f 499 $participantDetails[$dao->id] = [
97d8187a
DG
500 'id' => $dao->id,
501 'role' => $participantRoles[$dao->role_id],
502 'is_test' => $dao->is_test,
503 'event_id' => $dao->event_id,
504 'status_id' => $dao->status_id,
505 'fee_amount' => $dao->fee_amount,
506 'contact_id' => $dao->contact_id,
507 'register_date' => $dao->register_date,
508 'registered_by_id' => $dao->registered_by_id,
be2fb01f 509 ];
97d8187a 510 }
be2fb01f
CW
511 $eventDetails = [];
512 $eventParams = ['id' => $this->_event_id];
97d8187a
DG
513 CRM_Event_BAO_Event::retrieve($eventParams, $eventDetails[$this->_event_id]);
514 //get default participant role.
515 $eventDetails[$this->_event_id]['participant_role'] = CRM_Utils_Array::value($eventDetails[$this->_event_id]['default_role_id'], $participantRoles);
516 //get the location info
be2fb01f 517 $locParams = ['entity_id' => $this->_event_id, 'entity_table' => 'civicrm_event'];
97d8187a
DG
518 $eventDetails[$this->_event_id]['location'] = CRM_Core_BAO_Location::getValues($locParams, TRUE);
519 //get contact details
520 $contactIds[$this->_from_contact_id] = $this->_from_contact_id;
521 list($currentContactDetails) = CRM_Utils_Token::getTokenDetails($contactIds, NULL,
be2fb01f 522 FALSE, FALSE, NULL, [],
97d8187a
DG
523 'CRM_Event_BAO_Participant'
524 );
525 foreach ($currentContactDetails as $contactId => $contactValues) {
526 $contactDetails[$this->_from_contact_id] = $contactValues;
527 }
528 //send a 'cancelled' email to user, and cc the event's cc_confirm email
529 $mail = CRM_Event_BAO_Participant::sendTransitionParticipantMail($this->_from_participant_id,
530 $participantDetails[$this->_from_participant_id],
531 $eventDetails[$this->_event_id],
532 $contactDetails[$this->_from_contact_id],
533 $domainValues,
534 "Transferred",
535 ""
536 );
be2fb01f
CW
537 $statusMsg = ts('Event registration information for %1 has been updated.', [1 => $this->_contact_name]);
538 $statusMsg .= ' ' . ts('A cancellation email has been sent to %1.', [1 => $this->_contact_email]);
8b9023b8 539 CRM_Core_Session::setStatus($statusMsg, ts('Thanks'), 'success');
97d8187a
DG
540 }
541
542}