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