Merge pull request #22463 from eileenmcnaughton/label
[civicrm-core.git] / CRM / Profile / Form.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 * @package CRM
15 * @copyright CiviCRM LLC https://civicrm.org/licensing
16 */
17
18 /**
19 * This class generates form components for custom data
20 *
21 * It delegates the work to lower level subclasses and integrates the changes
22 * back in. It also uses a lot of functionality with the CRM API's, so any change
23 * made here could potentially affect the API etc. Be careful, be aware, use unit tests.
24 *
25 */
26 class CRM_Profile_Form extends CRM_Core_Form {
27 const
28 MODE_REGISTER = 1,
29 MODE_SEARCH = 2,
30 MODE_CREATE = 4,
31 MODE_EDIT = 8;
32
33 protected $_mode;
34
35 protected $_skipPermission = FALSE;
36
37 /**
38 * The contact id that we are editing.
39 *
40 * @var int
41 */
42 protected $_id;
43
44 /**
45 * The group id that we are editing.
46 *
47 * @var int
48 */
49 protected $_gid;
50
51 /**
52 * @var array
53 * Details of the UFGroup used on this page
54 */
55 protected $_ufGroup = ['name' => 'unknown'];
56
57 /**
58 * The group id that we are passing in url.
59 *
60 * @var int
61 */
62 public $_grid;
63
64 /**
65 * Name of button for saving matching contacts.
66 * @var string
67 */
68 protected $_duplicateButtonName;
69 /**
70 * The title of the category we are editing.
71 *
72 * @var string
73 */
74 protected $_title;
75
76 /**
77 * The fields needed to build this form.
78 *
79 * @var array
80 */
81 public $_fields;
82
83 /**
84 * store contact details.
85 *
86 * @var array
87 */
88 protected $_contact;
89
90 /**
91 * Do we allow updates of the contact.
92 *
93 * @var int
94 */
95 public $_isUpdateDupe = 0;
96
97 /**
98 * Dedupe using a specific rule (CRM-6131).
99 * Not currently exposed in profile settings, but can be set in a buildForm hook.
100 * @var int
101 */
102 public $_ruleGroupID = NULL;
103
104 public $_isAddCaptcha = FALSE;
105
106 protected $_isPermissionedChecksum = FALSE;
107
108 /**
109 * THe context from which we came from, allows us to go there if redirect not set.
110 *
111 * @var string
112 */
113 protected $_context;
114
115 /**
116 * THe contact type for registration case.
117 *
118 * @var string
119 */
120 protected $_ctype = NULL;
121
122 /**
123 * Store profile ids if multiple profile ids are passed using comma separated.
124 * Currently lets implement this functionality only for dialog mode.
125 * @var array
126 */
127 protected $_profileIds = [];
128
129 /**
130 * Contact profile having activity fields?
131 *
132 * @var string
133 */
134 protected $_isContactActivityProfile = FALSE;
135
136 /**
137 * Activity Id connected to the profile.
138 *
139 * @var string
140 */
141 protected $_activityId = NULL;
142
143
144 protected $_multiRecordFields = NULL;
145
146 protected $_recordId = NULL;
147
148 /**
149 * Action for multi record profile (create/edit/delete).
150 *
151 * @var string
152 */
153 protected $_multiRecord = NULL;
154
155 protected $_multiRecordProfile = FALSE;
156
157 protected $_recordExists = TRUE;
158
159 protected $_customGroupTitle = NULL;
160
161 protected $_deleteButtonName = NULL;
162
163 protected $_customGroupId = NULL;
164
165 protected $_currentUserID = NULL;
166 protected $_session = NULL;
167
168 /**
169 * Check for any duplicates.
170 *
171 * Depending on form settings & usage scenario we potentially use the found id,
172 * create links to found ids or add an error.
173 *
174 * @param array $errors
175 * @param array $fields
176 * @param CRM_Profile_Form $form
177 *
178 * @return array
179 */
180 protected static function handleDuplicateChecking(&$errors, $fields, $form) {
181 if ($form->_mode == CRM_Profile_Form::MODE_CREATE) {
182 // fix for CRM-2888
183 $exceptions = [];
184 }
185 else {
186 // for edit mode we need to allow our own record to be a dupe match!
187 $exceptions = [CRM_Core_Session::singleton()->get('userID')];
188 }
189 $contactType = CRM_Core_BAO_UFGroup::getContactType($form->_gid);
190 // If all profile fields is of Contact Type then consider
191 // profile is of Individual type(default).
192 if (!$contactType) {
193 $contactType = 'Individual';
194 }
195
196 $ids = CRM_Contact_BAO_Contact::getDuplicateContacts(
197 $fields, $contactType,
198 ($form->_context === 'dialog' ? 'Supervised' : 'Unsupervised'),
199 $exceptions,
200 FALSE,
201 $form->_ruleGroupID
202 );
203 if ($ids) {
204 if ($form->_isUpdateDupe == 2) {
205 CRM_Core_Session::setStatus(ts('Note: this contact may be a duplicate of an existing record.'), ts('Possible Duplicate Detected'), 'alert');
206 }
207 elseif ($form->_isUpdateDupe == 1) {
208 $form->_id = $ids[0];
209 }
210 else {
211 if ($form->_context == 'dialog') {
212 $contactLinks = CRM_Contact_BAO_Contact_Utils::formatContactIDSToLinks($ids, TRUE, TRUE);
213
214 $duplicateContactsLinks = '<div class="matching-contacts-found">';
215 $duplicateContactsLinks .= ts('One matching contact was found. ', [
216 'count' => count($contactLinks['rows']),
217 'plural' => '%count matching contacts were found.<br />',
218 ]);
219 if ($contactLinks['msg'] == 'view') {
220 $duplicateContactsLinks .= ts('You can View the existing contact.', [
221 'count' => count($contactLinks['rows']),
222 'plural' => 'You can View the existing contacts.',
223 ]);
224 }
225 else {
226 $duplicateContactsLinks .= ts('You can View or Edit the existing contact.', [
227 'count' => count($contactLinks['rows']),
228 'plural' => 'You can View or Edit the existing contacts.',
229 ]);
230 }
231 $duplicateContactsLinks .= '</div>';
232 $duplicateContactsLinks .= '<table class="matching-contacts-actions">';
233 $row = '';
234 for ($i = 0; $i < count($contactLinks['rows']); $i++) {
235 $row .= ' <tr> ';
236 $row .= ' <td class="matching-contacts-name"> ';
237 $row .= $contactLinks['rows'][$i]['display_name'];
238 $row .= ' </td>';
239 $row .= ' <td class="matching-contacts-email"> ';
240 $row .= $contactLinks['rows'][$i]['primary_email'];
241 $row .= ' </td>';
242 $row .= ' <td class="action-items"> ';
243 $row .= $contactLinks['rows'][$i]['view'] . ' ';
244 $row .= $contactLinks['rows'][$i]['edit'];
245 $row .= ' </td>';
246 $row .= ' </tr> ';
247 }
248
249 $duplicateContactsLinks .= $row . '</table>';
250 $duplicateContactsLinks .= "If you're sure this record is not a duplicate, click the 'Save Matching Contact' button below.";
251
252 $errors['_qf_default'] = $duplicateContactsLinks;
253
254 // let smarty know that there are duplicates
255 $template = CRM_Core_Smarty::singleton();
256 $template->assign('isDuplicate', 1);
257 }
258 else {
259 $errors['_qf_default'] = ts('A record already exists with the same information.');
260 }
261 }
262 }
263 return $errors;
264 }
265
266 /**
267 * Explicitly declare the entity api name.
268 */
269 public function getDefaultEntity() {
270 return 'Profile';
271 }
272
273 /**
274 * Get the active UFGroups (profiles) on this form
275 * Many forms load one or more UFGroups (profiles).
276 * This provides a standard function to retrieve the IDs of those profiles from the form
277 * so that you can implement things such as "is is_captcha field set on any of the active profiles on this form?"
278 *
279 * NOT SUPPORTED FOR USE OUTSIDE CORE EXTENSIONS - Added for reCAPTCHA core extension.
280 *
281 * @return array
282 */
283 public function getUFGroupIDs() {
284 if (empty($this->_profileIds)) {
285 $dao = new CRM_Core_DAO_UFGroup();
286 $dao->id = $this->_gid;
287 $this->_profileIds = (array) $dao;
288 }
289 return $this->_profileIds;
290 }
291
292 /**
293 * Are we using the profile in create mode?
294 *
295 * @return bool
296 */
297 public function getIsCreateMode() {
298 return ($this->_mode == self::MODE_CREATE);
299 }
300
301 /**
302 * Pre processing work done here.
303 *
304 * gets session variables for table name, id of entity in table, type of entity and stores them.
305 */
306 public function preProcess() {
307 $this->_id = $this->get('id');
308 $this->_profileIds = $this->get('profileIds');
309 $this->_grid = CRM_Utils_Request::retrieve('grid', 'Integer', $this);
310 $this->_context = CRM_Utils_Request::retrieve('context', 'Alphanumeric', $this);
311
312 //unset from session when $_GET doesn't have it
313 //except when the form is submitted
314 if (empty($_POST)) {
315 if (!array_key_exists('multiRecord', $_GET)) {
316 $this->set('multiRecord', NULL);
317 }
318 if (!array_key_exists('recordId', $_GET)) {
319 $this->set('recordId', NULL);
320 }
321 }
322
323 $this->_currentUserID = CRM_Core_Session::singleton()->get('userID');
324
325 if ($this->_mode == self::MODE_EDIT) {
326 //specifies the action being done on a multi record field
327 $multiRecordAction = CRM_Utils_Request::retrieve('multiRecord', 'String', $this);
328 $this->_multiRecord = (!is_numeric($multiRecordAction)) ? CRM_Core_Action::resolve($multiRecordAction) : $multiRecordAction;
329 if ($this->_multiRecord) {
330 $this->set('multiRecord', $this->_multiRecord);
331 }
332
333 if ($this->_multiRecord &&
334 !in_array($this->_multiRecord, [CRM_Core_Action::UPDATE, CRM_Core_Action::ADD, CRM_Core_Action::DELETE])
335 ) {
336 CRM_Core_Error::statusBounce(ts('Proper action not specified for this custom value record profile'));
337 }
338 }
339 $this->_duplicateButtonName = $this->getButtonName('upload', 'duplicate');
340
341 $gids = explode(',', CRM_Utils_Request::retrieve('gid', 'String', CRM_Core_DAO::$_nullObject, FALSE, 0));
342
343 if ((count($gids) > 1) && !$this->_profileIds && empty($this->_profileIds)) {
344 if (!empty($gids)) {
345 foreach ($gids as $pfId) {
346 $this->_profileIds[] = CRM_Utils_Type::escape($pfId, 'Positive');
347 }
348 }
349
350 // check if we are rendering mixed profiles
351 if (CRM_Core_BAO_UFGroup::checkForMixProfiles($this->_profileIds)) {
352 CRM_Core_Error::statusBounce(ts('You cannot combine profiles of multiple types.'));
353 }
354
355 // for now consider 1'st profile as primary profile and validate it
356 // i.e check for profile type etc.
357 // FIX ME: validations for other than primary
358 $this->_gid = $this->_profileIds[0];
359 $this->set('gid', $this->_gid);
360 $this->set('profileIds', $this->_profileIds);
361 }
362
363 if (!$this->_gid) {
364 $this->_gid = CRM_Utils_Request::retrieve('gid', 'Positive', $this, FALSE, 0);
365 $this->set('gid', $this->_gid);
366 }
367
368 $this->_activityId = CRM_Utils_Request::retrieve('aid', 'Positive', $this, FALSE, 0, 'GET');
369 if (is_numeric($this->_activityId)) {
370 $latestRevisionId = CRM_Activity_BAO_Activity::getLatestActivityId($this->_activityId);
371 if ($latestRevisionId) {
372 $this->_activityId = $latestRevisionId;
373 }
374 }
375 $this->_isContactActivityProfile = CRM_Core_BAO_UFField::checkContactActivityProfileType($this->_gid);
376
377 //get values for ufGroupName, captcha and dupe update.
378 if ($this->_gid) {
379 $dao = new CRM_Core_DAO_UFGroup();
380 $dao->id = $this->_gid;
381 if ($dao->find(TRUE)) {
382 $this->_isUpdateDupe = $dao->is_update_dupe;
383 $this->_isAddCaptcha = $dao->add_captcha;
384 $this->_ufGroup = (array) $dao;
385 }
386
387 if (empty($this->_ufGroup['is_active'])) {
388 CRM_Core_Error::statusBounce(ts('The requested profile (gid=%1) is inactive or does not exist.', [
389 1 => $this->_gid,
390 ]));
391 }
392 }
393 $this->assign('ufGroupName', $this->_ufGroup['name']);
394
395 $gids = empty($this->_profileIds) ? $this->_gid : $this->_profileIds;
396
397 // if we don't have a gid use the default, else just use that specific gid
398 if (($this->_mode == self::MODE_REGISTER || $this->_mode == self::MODE_CREATE) && !$this->_gid) {
399 $this->_ctype = CRM_Utils_Request::retrieve('ctype', 'String', $this, FALSE, 'Individual', 'REQUEST');
400 $this->_fields = CRM_Core_BAO_UFGroup::getRegistrationFields($this->_action, $this->_mode, $this->_ctype);
401 }
402 elseif ($this->_mode == self::MODE_SEARCH) {
403 $this->_fields = CRM_Core_BAO_UFGroup::getListingFields($this->_action,
404 CRM_Core_BAO_UFGroup::PUBLIC_VISIBILITY | CRM_Core_BAO_UFGroup::LISTINGS_VISIBILITY,
405 FALSE,
406 $gids,
407 TRUE, NULL,
408 $this->_skipPermission,
409 CRM_Core_Permission::SEARCH
410 );
411 }
412 else {
413 $this->_fields = CRM_Core_BAO_UFGroup::getFields($gids, FALSE, NULL,
414 NULL, NULL,
415 FALSE, NULL,
416 $this->_skipPermission,
417 NULL,
418 ($this->_action == CRM_Core_Action::ADD) ? CRM_Core_Permission::CREATE : CRM_Core_Permission::EDIT
419 );
420 $multiRecordFieldListing = FALSE;
421 //using selector for listing of multi-record fields
422 if ($this->_mode == self::MODE_EDIT && $this->_gid) {
423 CRM_Core_BAO_UFGroup::shiftMultiRecordFields($this->_fields, $this->_multiRecordFields);
424
425 if ($this->_multiRecord) {
426 if ($this->_multiRecord != CRM_Core_Action::ADD) {
427 $this->_recordId = CRM_Utils_Request::retrieve('recordId', 'Positive', $this);
428 }
429 else {
430 $this->_recordId = NULL;
431 $this->set('recordId', NULL);
432 }
433 //record id is necessary for _multiRecord view and update/edit action
434 if (!$this->_recordId
435 && ($this->_multiRecord == CRM_Core_Action::UPDATE || $this->_multiRecord == CRM_Core_Action::DELETE)
436 ) {
437 CRM_Core_Error::statusBounce(ts('The requested Profile (gid=%1) requires record id while performing this action',
438 [1 => $this->_gid]
439 ));
440 }
441 elseif (empty($this->_multiRecordFields)) {
442 CRM_Core_Error::statusBounce(ts('No Multi-Record Fields configured for this profile (gid=%1)',
443 [1 => $this->_gid]
444 ));
445 }
446
447 $fieldId = CRM_Core_BAO_CustomField::getKeyID(key($this->_multiRecordFields));
448 $customGroupDetails = CRM_Core_BAO_CustomGroup::getGroupTitles([$fieldId]);
449 $this->_customGroupTitle = $customGroupDetails[$fieldId]['groupTitle'];
450 $this->_customGroupId = $customGroupDetails[$fieldId]['groupID'];
451
452 if ($this->_multiRecord == CRM_Core_Action::UPDATE || $this->_multiRecord == CRM_Core_Action::DELETE) {
453 //record exists check
454 foreach ($this->_multiRecordFields as $key => $field) {
455 $fieldIds[] = CRM_Core_BAO_CustomField::getKeyID($key);
456 }
457 $getValues = CRM_Core_BAO_CustomValueTable::getEntityValues($this->_id, NULL, $fieldIds, TRUE);
458
459 if (array_key_exists($this->_recordId, $getValues)) {
460 $this->_recordExists = TRUE;
461 }
462 else {
463 $this->_recordExists = FALSE;
464 if ($this->_multiRecord & CRM_Core_Action::UPDATE) {
465 CRM_Core_Session::setStatus(ts('Note: The record %1 doesnot exists. Upon save a new record will be create', [1 => $this->_recordId]), ts('Record doesnot exist'), 'alert');
466 }
467 }
468 }
469 if ($this->_multiRecord & CRM_Core_Action::ADD) {
470 $this->_maxRecordLimit = CRM_Core_BAO_CustomGroup::hasReachedMaxLimit($customGroupDetails[$fieldId]['groupID'], $this->_id);
471 if ($this->_maxRecordLimit) {
472 CRM_Core_Session::setStatus(ts('You cannot add a new record as maximum allowed limit is reached'), ts('Sorry'), 'error');
473 }
474 }
475
476 }
477 elseif (!empty($this->_multiRecordFields)
478 && (!$this->_multiRecord || !in_array($this->_multiRecord, [
479 CRM_Core_Action::DELETE,
480 CRM_Core_Action::UPDATE,
481 ]))
482 ) {
483 CRM_Core_Resources::singleton()->addScriptFile('civicrm', 'js/crm.livePage.js', 1, 'html-header');
484 //multi-record listing page
485 $multiRecordFieldListing = TRUE;
486 $page = new CRM_Profile_Page_MultipleRecordFieldsListing();
487 $cs = $this->get('cs');
488 $page->set('pageCheckSum', $cs);
489 $page->set('contactId', $this->_id);
490 $page->set('profileId', $this->_gid);
491 $page->set('action', CRM_Core_Action::BROWSE);
492 $page->set('multiRecordFieldListing', $multiRecordFieldListing);
493 $page->run();
494 }
495 }
496 $this->assign('multiRecordFieldListing', $multiRecordFieldListing);
497
498 // is profile double-opt in?
499 if (!empty($this->_fields['group']) &&
500 CRM_Core_BAO_UFGroup::isProfileDoubleOptin()
501 ) {
502 $emailField = FALSE;
503 foreach ($this->_fields as $name => $values) {
504 if (substr($name, 0, 6) == 'email-') {
505 $emailField = TRUE;
506 }
507 }
508
509 if (!$emailField) {
510 $status = ts("Email field should be included in profile if you want to use Group(s) when Profile double-opt in process is enabled.");
511 CRM_Core_Session::singleton()->setStatus($status);
512 }
513 }
514
515 //transferring all the multi-record custom fields in _fields
516 if ($this->_multiRecord && !empty($this->_multiRecordFields)) {
517 $this->_fields = $this->_multiRecordFields;
518 $this->_multiRecordProfile = TRUE;
519 }
520 elseif ($this->_multiRecord && empty($this->_multiRecordFields)) {
521 CRM_Core_Session::setStatus(ts('This feature is not currently available.'), ts('Sorry'), 'error');
522 CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm', 'reset=1'));
523 }
524 }
525
526 if (!is_array($this->_fields)) {
527 CRM_Core_Session::setStatus(ts('This feature is not currently available.'), ts('Sorry'), 'error');
528 CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm', 'reset=1'));
529 }
530 }
531
532 /**
533 * Set default values for the form. Note that in edit/view mode
534 * the default values are retrieved from the database
535 *
536 */
537 public function setDefaultsValues() {
538 $this->_defaults = [];
539 if ($this->_multiRecordProfile && ($this->_multiRecord == CRM_Core_Action::DELETE)) {
540 return;
541 }
542
543 if ($this->_mode != self::MODE_SEARCH) {
544 // set default values for country / state to start with
545 CRM_Core_BAO_UFGroup::setRegisterDefaults($this->_fields, $this->_defaults);
546 }
547
548 if ($this->_id && !$this->_multiRecordProfile) {
549 if ($this->_isContactActivityProfile) {
550 $contactFields = $activityFields = [];
551 foreach ($this->_fields as $fieldName => $field) {
552 if (CRM_Utils_Array::value('field_type', $field) == 'Activity') {
553 $activityFields[$fieldName] = $field;
554 }
555 else {
556 $contactFields[$fieldName] = $field;
557 }
558 }
559
560 CRM_Core_BAO_UFGroup::setProfileDefaults($this->_id, $contactFields, $this->_defaults, TRUE);
561 if ($this->_activityId) {
562 CRM_Core_BAO_UFGroup::setComponentDefaults($activityFields, $this->_activityId, 'Activity', $this->_defaults, TRUE);
563 }
564 }
565 else {
566 CRM_Core_BAO_UFGroup::setProfileDefaults($this->_id, $this->_fields, $this->_defaults, TRUE);
567 }
568 }
569
570 //set custom field defaults
571 if ($this->_multiRecordProfile) {
572 foreach ($this->_multiRecordFields as $key => $field) {
573 $fieldIds[] = CRM_Core_BAO_CustomField::getKeyID($key);
574 }
575
576 $defaultValues = [];
577 if ($this->_multiRecord && $this->_multiRecord == CRM_Core_Action::UPDATE) {
578 $defaultValues = CRM_Core_BAO_CustomValueTable::getEntityValues($this->_id, NULL, $fieldIds, TRUE);
579 if ($this->_recordExists == TRUE) {
580 $defaultValues = $defaultValues[$this->_recordId];
581 }
582 else {
583 $defaultValues = NULL;
584 }
585 }
586
587 if (!empty($defaultValues)) {
588 foreach ($defaultValues as $key => $value) {
589 $name = "custom_{$key}";
590 $htmlType = $this->_multiRecordFields[$name]['html_type'];
591 if ($htmlType != 'File') {
592 if (isset($value)) {
593 CRM_Core_BAO_CustomField::setProfileDefaults($key,
594 $name,
595 $this->_defaults,
596 $this->_id,
597 $this->_mode,
598 $value
599 );
600 }
601 else {
602 $this->_defaults[$name] = "";
603 }
604 }
605
606 if ($htmlType == 'File') {
607 $entityId = $this->_id;
608 if (CRM_Utils_Array::value('field_type', $field) == 'Activity' &&
609 $this->_activityId
610 ) {
611 $entityId = $this->_activityId;
612 }
613
614 $url = '';
615 if (isset($value)) {
616 $url = CRM_Core_BAO_CustomField::getFileURL($entityId, $key, $value);
617 }
618
619 if ($url) {
620 $customFiles[$name]['displayURL'] = ts("Attached File") . ": {$url['file_url']}";
621
622 $deleteExtra = ts("Are you sure you want to delete attached file?");
623 $fileId = $url['file_id'];
624 $fileHash = CRM_Core_BAO_File::generateFileHash($entityId, $fileId);
625 $deleteURL = CRM_Utils_System::url('civicrm/file',
626 "reset=1&id={$fileId}&eid=$entityId&fid={$key}&action=delete&fcs={$fileHash}"
627 );
628 $text = ts("Delete Attached File");
629 $customFiles[$field['name']]['deleteURL'] = "<a href=\"{$deleteURL}\" onclick = \"if (confirm( ' $deleteExtra ' )) this.href+='&amp;confirmed=1'; else return false;\">$text</a>";
630
631 // also delete the required rule that we've set on the form element
632 $this->removeFileRequiredRules($name);
633 }
634 }
635 }
636 }
637 }
638 else {
639 foreach ($this->_fields as $name => $field) {
640 if ($customFieldID = CRM_Core_BAO_CustomField::getKeyID($name)) {
641 $htmlType = $field['html_type'];
642 if ((!isset($this->_defaults[$name]) || $htmlType == 'File') &&
643 (CRM_Utils_Array::value('field_type', $field) != 'Activity')
644 ) {
645 CRM_Core_BAO_CustomField::setProfileDefaults($customFieldID,
646 $name,
647 $this->_defaults,
648 $this->_id,
649 $this->_mode
650 );
651 }
652
653 if ($htmlType == 'File') {
654 $entityId = $this->_id;
655 if (CRM_Utils_Array::value('field_type', $field) == 'Activity' && $this->_activityId) {
656 $entityId = $this->_activityId;
657 }
658 $url = CRM_Core_BAO_CustomField::getFileURL($entityId, $customFieldID);
659
660 if ($url) {
661 $customFiles[$field['name']]['displayURL'] = ts("Attached File") . ": {$url['file_url']}";
662
663 $deleteExtra = ts("Are you sure you want to delete attached file?");
664 $fileId = $url['file_id'];
665 $fileHash = CRM_Core_BAO_File::generateFileHash($entityId, $fileId); /* fieldId=$customFieldID */
666 $deleteURL = CRM_Utils_System::url('civicrm/file',
667 "reset=1&id={$fileId}&eid=$entityId&fid={$customFieldID}&action=delete&fcs={$fileHash}"
668 );
669 $text = ts("Delete Attached File");
670 $customFiles[$field['name']]['deleteURL'] = "<a href=\"{$deleteURL}\" onclick = \"if (confirm( ' $deleteExtra ' )) this.href+='&amp;confirmed=1'; else return false;\">$text</a>";
671
672 // also delete the required rule that we've set on the form element
673 $this->removeFileRequiredRules($field['name']);
674 }
675 }
676 }
677 }
678 }
679 if (isset($customFiles)) {
680 $this->assign('customFiles', $customFiles);
681 }
682
683 if ($this->_multiRecordProfile) {
684 $this->setDefaults($this->_defaults);
685 return;
686 }
687
688 if (!empty($this->_defaults['image_URL'])) {
689 $this->assign("imageURL", CRM_Utils_File::getImageURL($this->_defaults['image_URL']));
690 $this->removeFileRequiredRules('image_URL');
691 }
692
693 $this->setDefaults($this->_defaults);
694 }
695
696 /**
697 * Build the form object.
698 *
699 */
700 public function buildQuickForm() {
701 $this->add('hidden', 'gid', $this->_gid);
702
703 switch ($this->_mode) {
704 case self::MODE_CREATE:
705 case self::MODE_EDIT:
706 case self::MODE_REGISTER:
707 CRM_Utils_Hook::buildProfile($this->_ufGroup['name']);
708 break;
709
710 case self::MODE_SEARCH:
711 CRM_Utils_Hook::searchProfile($this->_ufGroup['name']);
712 break;
713
714 default:
715 }
716
717 //lets have single status message, CRM-4363
718 $return = FALSE;
719 $statusMessage = NULL;
720 if (($this->_multiRecord & CRM_Core_Action::ADD) && $this->_maxRecordLimit) {
721 return;
722 }
723
724 if (($this->_multiRecord & CRM_Core_Action::DELETE)) {
725 if (!$this->_recordExists) {
726 CRM_Core_Session::setStatus(ts('The record %1 doesnot exists', [1 => $this->_recordId]), ts('Record doesnot exists'), 'alert');
727 }
728 else {
729 $this->assign('deleteRecord', TRUE);
730 }
731 return;
732 }
733
734 CRM_Core_BAO_Address::checkContactSharedAddressFields($this->_fields, $this->_id);
735
736 // we should not allow component and mix profiles in search mode
737 if ($this->_mode != self::MODE_REGISTER) {
738 //check for mix profile fields (eg: individual + other contact type)
739 if (CRM_Core_BAO_UFField::checkProfileType($this->_gid)) {
740 if (($this->_mode & self::MODE_EDIT) && $this->_isContactActivityProfile) {
741 $errors = self::validateContactActivityProfile($this->_activityId, $this->_id, $this->_gid);
742 if (!empty($errors)) {
743 $statusMessage = array_pop($errors);
744 $return = TRUE;
745 }
746 }
747 else {
748 $statusMessage = ts('Profile search, view and edit are not supported for Profiles which include fields for more than one record type.');
749 $return = TRUE;
750 }
751 }
752
753 $profileType = CRM_Core_BAO_UFField::getProfileType($this->_gid);
754
755 if ($this->_id) {
756 $contactTypes = CRM_Contact_BAO_Contact::getContactTypes($this->_id);
757 $contactType = $contactTypes[0];
758
759 array_shift($contactTypes);
760 $contactSubtypes = $contactTypes;
761
762 $profileSubType = FALSE;
763 if (CRM_Contact_BAO_ContactType::isaSubType($profileType)) {
764 $profileSubType = $profileType;
765 $profileType = CRM_Contact_BAO_ContactType::getBasicType($profileType);
766 }
767
768 if (
769 ($profileType != 'Contact' && !$this->_isContactActivityProfile) &&
770 (($profileSubType && !empty($contactSubtypes) && (!in_array($profileSubType, $contactSubtypes))) ||
771 ($profileType != $contactType))
772 ) {
773 $return = TRUE;
774 if (!$statusMessage) {
775 $statusMessage = ts("This profile is configured for contact type '%1'. It cannot be used to edit contacts of other types.",
776 [1 => $profileSubType ? $profileSubType : $profileType]);
777 }
778 }
779 }
780
781 if (
782 in_array(
783 $profileType,
784 ["Membership", "Participant", "Contribution"]
785 )
786 ) {
787 $return = TRUE;
788 if (!$statusMessage) {
789 $statusMessage = ts('Profile is not configured for the selected action.');
790 }
791 }
792 }
793
794 //lets have single status message,
795 $this->assign('statusMessage', $statusMessage);
796 if ($return) {
797 return FALSE;
798 }
799
800 $this->assign('id', $this->_id);
801 $this->assign('mode', $this->_mode);
802 $this->assign('action', $this->_action);
803 $this->assign('fields', $this->_fields);
804 $this->assign('fieldset', (isset($this->_fieldset)) ? $this->_fieldset : "");
805
806 // should we restrict what we display
807 $admin = TRUE;
808 if ($this->_mode == self::MODE_EDIT) {
809 $admin = FALSE;
810 // show all fields that are visible:
811 // if we are a admin OR the same user OR acl-user with access to the profile
812 // or we have checksum access to this contact (i.e. the user without a login) - CRM-5909
813 if (
814 CRM_Core_Permission::check('administer users') ||
815 $this->_id == $this->_currentUserID ||
816 $this->_isPermissionedChecksum ||
817 in_array(
818 $this->_gid,
819 CRM_ACL_API::group(
820 CRM_Core_Permission::EDIT,
821 NULL,
822 'civicrm_uf_group',
823 CRM_Core_PseudoConstant::get('CRM_Core_DAO_UFField', 'uf_group_id')
824 )
825 )
826 ) {
827 $admin = TRUE;
828 }
829 }
830
831 // if false, user is not logged-in.
832 $anonUser = FALSE;
833 if (!$this->_currentUserID) {
834 $defaultLocationType = CRM_Core_BAO_LocationType::getDefault();
835 $primaryLocationType = $defaultLocationType->id;
836 $anonUser = TRUE;
837 }
838 $this->assign('anonUser', $anonUser);
839
840 $addCaptcha = [];
841 $emailPresent = FALSE;
842
843 // add the form elements
844 foreach ($this->_fields as $name => $field) {
845 // make sure that there is enough permission to expose this field
846 if (!$admin && $field['visibility'] == 'User and User Admin Only') {
847 unset($this->_fields[$name]);
848 continue;
849 }
850
851 // since the CMS manages the email field, suppress the email display if in
852 // register mode which occur within the CMS form
853 if ($this->_mode == self::MODE_REGISTER && substr($name, 0, 5) == 'email') {
854 unset($this->_fields[$name]);
855 continue;
856 }
857
858 list($prefixName, $index) = CRM_Utils_System::explode('-', $name, 2);
859
860 CRM_Core_BAO_UFGroup::buildProfile($this, $field, $this->_mode);
861
862 if ($field['add_to_group_id']) {
863 $addToGroupId = $field['add_to_group_id'];
864 }
865
866 //build array for captcha
867 if ($field['add_captcha']) {
868 $addCaptcha[$field['group_id']] = $field['add_captcha'];
869 }
870
871 if (($name == 'email-Primary') || ($name == 'email-' . ($primaryLocationType ?? ""))) {
872 $emailPresent = TRUE;
873 $this->_mail = $name;
874 }
875 }
876
877 // add captcha only for create mode.
878 if ($this->_mode == self::MODE_CREATE) {
879 // suppress captcha for logged in users only
880 if ($this->_currentUserID) {
881 $this->_isAddCaptcha = FALSE;
882 }
883 elseif (!$this->_isAddCaptcha && !empty($addCaptcha)) {
884 $this->_isAddCaptcha = TRUE;
885 }
886
887 if ($this->_gid) {
888 $dao = new CRM_Core_DAO_UFGroup();
889 $dao->id = $this->_gid;
890 $dao->addSelect();
891 $dao->addSelect('is_update_dupe');
892 if ($dao->find(TRUE)) {
893 if ($dao->is_update_dupe) {
894 $this->_isUpdateDupe = $dao->is_update_dupe;
895 }
896 }
897 }
898 }
899 else {
900 $this->_isAddCaptcha = FALSE;
901 }
902
903 //finally add captcha to form.
904 if ($this->_isAddCaptcha) {
905 CRM_Utils_ReCAPTCHA::enableCaptchaOnForm($this);
906 }
907
908 if ($this->_mode != self::MODE_SEARCH) {
909 if (isset($addToGroupId)) {
910 $this->_ufGroup['add_to_group_id'] = $addToGroupId;
911 }
912 }
913
914 //let's do set defaults for the profile
915 $this->setDefaultsValues();
916
917 $action = CRM_Utils_Request::retrieve('action', 'String', $this, FALSE, NULL);
918
919 if ($this->_mode == self::MODE_CREATE || $this->_mode == self::MODE_EDIT) {
920 CRM_Core_BAO_CMSUser::buildForm($this, $this->_gid, $emailPresent, $action);
921 }
922 else {
923 $this->assign('showCMS', FALSE);
924 }
925
926 $this->assign('groupId', $this->_gid);
927
928 // if view mode pls freeze it with the done button.
929 if ($this->_action & CRM_Core_Action::VIEW) {
930 $this->freeze();
931 }
932
933 if ($this->_context == 'dialog') {
934 $this->addElement(
935 'xbutton',
936 $this->_duplicateButtonName,
937 ts('Save Matching Contact'),
938 [
939 'type' => 'submit',
940 'class' => 'crm-button',
941 ]
942 );
943 }
944 }
945
946 /**
947 * Validate profile and provided activity Id.
948 *
949 * @param int $activityId
950 * @param int $contactId
951 * @param int $gid
952 *
953 * @return array
954 */
955 public static function validateContactActivityProfile($activityId, $contactId, $gid) {
956 $errors = [];
957 if (!$activityId) {
958 $errors[] = ts('Profile is using one or more activity fields, and is missing the activity Id (aid) in the URL.');
959 return $errors;
960 }
961
962 $activityDetails = [];
963 $activityParams = ['id' => $activityId];
964 CRM_Activity_BAO_Activity::retrieve($activityParams, $activityDetails);
965
966 if (empty($activityDetails)) {
967 $errors[] = ts('Invalid Activity Id (aid).');
968 return $errors;
969 }
970
971 $profileActivityTypes = CRM_Core_BAO_UFGroup::groupTypeValues($gid, 'Activity');
972
973 if ((!empty($profileActivityTypes['Activity']) &&
974 !in_array($activityDetails['activity_type_id'], $profileActivityTypes['Activity'])
975 ) ||
976 (!in_array($contactId, $activityDetails['assignee_contact']) &&
977 !in_array($contactId, $activityDetails['target_contact'])
978 )
979 ) {
980 $errors[] = ts('This activity cannot be edited or viewed via this profile.');
981 }
982
983 return $errors;
984 }
985
986 /**
987 * Global form rule.
988 *
989 * @param array $fields
990 * The input form values.
991 * @param array $files
992 * The uploaded files if any.
993 * @param CRM_Core_Form $form
994 * The form object.
995 *
996 * @return bool|array
997 * true if no errors, else array of errors
998 */
999 public static function formRule($fields, $files, $form) {
1000 CRM_Utils_Hook::validateProfile($form->_ufGroup['name']);
1001
1002 // if no values, return
1003 if (empty($fields)) {
1004 return TRUE;
1005 }
1006
1007 $errors = [];
1008 $register = NULL;
1009
1010 // hack we use a -1 in options to indicate that its registration
1011 // ... and I can't remove that comment because even though it's clear as mud
1012 // perhaps someone will find it helpful in the absence of ANY OTHER EXPLANATION
1013 // as to what it means....
1014 if ($form->_id) {
1015 // @todo - wonder if it ever occurred to someone that if they didn't document this param
1016 // it might not be crystal clear why we have it....
1017 $form->_isUpdateDupe = 1;
1018 }
1019
1020 if ($form->_mode == CRM_Profile_Form::MODE_REGISTER) {
1021 $register = TRUE;
1022 }
1023
1024 // don't check for duplicates during registration validation: CRM-375
1025 if (!$register && !array_key_exists('_qf_Edit_upload_duplicate', $fields)) {
1026 // fix for CRM-3240
1027 if (!empty($fields['email-Primary'])) {
1028 $fields['email'] = $fields['email-Primary'] ?? NULL;
1029 }
1030
1031 // fix for CRM-6141
1032 if (!empty($fields['phone-Primary-1']) && empty($fields['phone-Primary'])) {
1033 $fields['phone-Primary'] = $fields['phone-Primary-1'];
1034 }
1035
1036 if (!$form->_id) {
1037 self::handleDuplicateChecking($errors, $fields, $form);
1038 }
1039 }
1040
1041 foreach ($fields as $key => $value) {
1042 list($fieldName, $locTypeId, $phoneTypeId) = CRM_Utils_System::explode('-', $key, 3);
1043 if ($fieldName == 'state_province' && !empty($fields["country-{$locTypeId}"])) {
1044 // Validate Country - State list
1045 $countryId = $fields["country-{$locTypeId}"];
1046 $stateProvinceId = $value;
1047
1048 if ($stateProvinceId && $countryId) {
1049 $stateProvinceDAO = new CRM_Core_DAO_StateProvince();
1050 $stateProvinceDAO->id = $stateProvinceId;
1051 $stateProvinceDAO->find(TRUE);
1052
1053 if ($stateProvinceDAO->country_id != $countryId) {
1054 // country mismatch hence display error
1055 $stateProvinces = CRM_Core_PseudoConstant::stateProvince();
1056 $countries = CRM_Core_PseudoConstant::country();
1057 $errors[$key] = "State/Province " . $stateProvinces[$stateProvinceId] . " is not part of " . $countries[$countryId] . ". It belongs to " . $countries[$stateProvinceDAO->country_id] . ".";
1058 }
1059 }
1060 }
1061
1062 if ($fieldName == 'county' && $fields["state_province-{$locTypeId}"]) {
1063 // Validate County - State list
1064 $stateProvinceId = $fields["state_province-{$locTypeId}"];
1065 $countyId = $value;
1066
1067 if ($countyId && $stateProvinceId) {
1068 $countyDAO = new CRM_Core_DAO_County();
1069 $countyDAO->id = $countyId;
1070 $countyDAO->find(TRUE);
1071
1072 if ($countyDAO->state_province_id != $stateProvinceId) {
1073 // state province mismatch hence display error
1074 $stateProvinces = CRM_Core_PseudoConstant::stateProvince();
1075 $counties = CRM_Core_PseudoConstant::county();
1076 $errors[$key] = "County " . $counties[$countyId] . " is not part of " . $stateProvinces[$stateProvinceId] . ". It belongs to " . $stateProvinces[$countyDAO->state_province_id] . ".";
1077 }
1078 }
1079 }
1080 }
1081 foreach (CRM_Contact_BAO_Contact::$_greetingTypes as $greeting) {
1082 if ($greetingType = CRM_Utils_Array::value($greeting, $fields)) {
1083 $customizedValue = CRM_Core_PseudoConstant::getKey('CRM_Contact_BAO_Contact', $greeting . '_id', 'Customized');
1084 if ($customizedValue == $greetingType && empty($fields[$greeting . '_custom'])) {
1085 $errors[$greeting . '_custom'] = ts('Custom %1 is a required field if %1 is of type Customized.',
1086 [1 => ucwords(str_replace('_', ' ', $greeting))]
1087 );
1088 }
1089 }
1090 }
1091
1092 return empty($errors) ? TRUE : $errors;
1093 }
1094
1095 /**
1096 * Process the user submitted custom data values.
1097 *
1098 */
1099 public function postProcess() {
1100 $params = $this->controller->exportValues($this->_name);
1101
1102 //if the delete record button is clicked
1103 if ($this->_deleteButtonName) {
1104 if (!empty($_POST[$this->_deleteButtonName]) && $this->_recordId) {
1105 $filterParams['id'] = $this->_customGroupId;
1106 $returnProperties = ['is_multiple', 'table_name'];
1107 CRM_Core_DAO::commonRetrieve("CRM_Core_DAO_CustomGroup", $filterParams, $returnValues, $returnProperties);
1108 if (!empty($returnValues['is_multiple'])) {
1109 if ($tableName = CRM_Utils_Array::value('table_name', $returnValues)) {
1110 $sql = "DELETE FROM {$tableName} WHERE id = %1 AND entity_id = %2";
1111 $sqlParams = [
1112 1 => [$this->_recordId, 'Integer'],
1113 2 => [$this->_id, 'Integer'],
1114 ];
1115 CRM_Core_DAO::executeQuery($sql, $sqlParams);
1116 CRM_Core_Session::setStatus(ts('Your record has been deleted.'), ts('Deleted'), 'success');
1117 }
1118 }
1119 return;
1120 }
1121 }
1122 CRM_Utils_Hook::processProfile($this->_ufGroup['name']);
1123 if (!empty($params['image_URL'])) {
1124 CRM_Contact_BAO_Contact::processImageParams($params);
1125 }
1126
1127 $greetingTypes = [
1128 'addressee' => 'addressee_id',
1129 'email_greeting' => 'email_greeting_id',
1130 'postal_greeting' => 'postal_greeting_id',
1131 ];
1132
1133 $details = [];
1134 if ($this->_id) {
1135 $contactDetails = CRM_Contact_BAO_Contact::getHierContactDetails($this->_id,
1136 $greetingTypes
1137 );
1138 $details = $contactDetails[$this->_id];
1139 }
1140 if (!(!empty($details['addressee_id']) || !empty($details['email_greeting_id']) ||
1141 !empty($details['postal_greeting_id'])
1142 )
1143 ) {
1144
1145 $profileType = CRM_Core_BAO_UFField::getProfileType($this->_gid);
1146 //Though Profile type is contact we need
1147 //Individual/Household/Organization for setting Greetings.
1148 if ($profileType == 'Contact') {
1149 $profileType = 'Individual';
1150 //if we editing Household/Organization.
1151 if ($this->_id) {
1152 $profileType = CRM_Contact_BAO_Contact::getContactType($this->_id);
1153 }
1154 }
1155 if (CRM_Contact_BAO_ContactType::isaSubType($profileType)) {
1156 $profileType = CRM_Contact_BAO_ContactType::getBasicType($profileType);
1157 }
1158
1159 foreach ($greetingTypes as $key => $value) {
1160 if (!array_key_exists($key, $params)) {
1161 $params[$key] = CRM_Contact_BAO_Contact_Utils::defaultGreeting($profileType, $key);
1162 }
1163 }
1164 }
1165
1166 $transaction = new CRM_Core_Transaction();
1167
1168 //used to send subscribe mail to the group which user want.
1169 //if the profile double option in is enabled
1170 $mailingType = [];
1171
1172 $result = NULL;
1173 foreach ($params as $name => $values) {
1174 if (substr($name, 0, 6) == 'email-') {
1175 $result['email'] = $values;
1176 }
1177 }
1178
1179 //array of group id, subscribed by contact
1180 $contactGroup = [];
1181 if (!empty($params['group']) &&
1182 CRM_Core_BAO_UFGroup::isProfileDoubleOptin()
1183 ) {
1184 $groupSubscribed = [];
1185 if (!empty($result['email'])) {
1186 if ($this->_id) {
1187 $contactGroups = new CRM_Contact_DAO_GroupContact();
1188 $contactGroups->contact_id = $this->_id;
1189 $contactGroups->status = 'Added';
1190 $contactGroups->find();
1191 $contactGroup = [];
1192 while ($contactGroups->fetch()) {
1193 $contactGroup[] = $contactGroups->group_id;
1194 $groupSubscribed[$contactGroups->group_id] = 1;
1195 }
1196 }
1197 foreach ($params['group'] as $key => $val) {
1198 if (!$val) {
1199 unset($params['group'][$key]);
1200 continue;
1201 }
1202 $groupTypes = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Group',
1203 $key, 'group_type', 'id'
1204 );
1205 $groupType = explode(CRM_Core_DAO::VALUE_SEPARATOR,
1206 substr($groupTypes, 1, -1)
1207 );
1208 //filter group of mailing type and unset it from params
1209 if (in_array(2, $groupType)) {
1210 //if group is already subscribed , ignore it
1211 $groupExist = CRM_Utils_Array::key($key, $contactGroup);
1212 if (!isset($groupExist)) {
1213 $mailingType[] = $key;
1214 unset($params['group'][$key]);
1215 }
1216 }
1217 }
1218 }
1219 }
1220
1221 $addToGroupId = $this->_ufGroup['add_to_group_id'] ?? NULL;
1222 if (!empty($addToGroupId)) {
1223 //run same check whether group is a mailing list
1224 $groupTypes = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Group',
1225 $addToGroupId, 'group_type', 'id'
1226 );
1227 $groupType = explode(CRM_Core_DAO::VALUE_SEPARATOR,
1228 substr($groupTypes, 1, -1)
1229 );
1230 //filter group of mailing type and unset it from params
1231 if (in_array(2, $groupType) && !empty($result['email']) &&
1232 CRM_Core_BAO_UFGroup::isProfileAddToGroupDoubleOptin()
1233 ) {
1234 if (!count($contactGroup)) {
1235 //array of group id, subscribed by contact
1236 $contactGroup = [];
1237 if ($this->_id) {
1238 $contactGroups = new CRM_Contact_DAO_GroupContact();
1239 $contactGroups->contact_id = $this->_id;
1240 $contactGroups->status = 'Added';
1241 $contactGroups->find();
1242 $contactGroup = [];
1243 while ($contactGroups->fetch()) {
1244 $contactGroup[] = $contactGroups->group_id;
1245 $groupSubscribed[$contactGroups->group_id] = 1;
1246 }
1247 }
1248 }
1249 //if group is already subscribed , ignore it
1250 $groupExist = CRM_Utils_Array::key($addToGroupId, $contactGroup);
1251 if (!isset($groupExist)) {
1252 $mailingType[] = $addToGroupId;
1253 $addToGroupId = NULL;
1254 }
1255 }
1256 else {
1257 // since we are directly adding contact to group lets unset it from mailing
1258 if ($key = array_search($addToGroupId, $mailingType)) {
1259 unset($mailingType[$key]);
1260 }
1261 }
1262 }
1263
1264 if ($this->_grid) {
1265 $params['group'] = $groupSubscribed;
1266 }
1267
1268 // commenting below code, since we potentially
1269 // triggered maximum name field formatting cases during CRM-4430.
1270 // CRM-4343
1271 // $params['preserveDBName'] = true;
1272
1273 $profileFields = $this->_fields;
1274 if (($this->_mode & self::MODE_EDIT) && $this->_activityId && $this->_isContactActivityProfile) {
1275 $profileFields = $activityParams = [];
1276 foreach ($this->_fields as $fieldName => $field) {
1277 if (CRM_Utils_Array::value('field_type', $field) == 'Activity') {
1278 if (isset($params[$fieldName])) {
1279 $activityParams[$fieldName] = $params[$fieldName];
1280 }
1281 if (isset($params['activity_date_time'])) {
1282 $activityParams['activity_date_time'] = CRM_Utils_Date::processDate($params['activity_date_time'], $params['activity_date_time_time']);
1283 }
1284 if (!empty($params[$fieldName]) && isset($params["{$fieldName}_id"])) {
1285 $activityParams[$fieldName] = $params["{$fieldName}_id"];
1286 }
1287 }
1288 else {
1289 $profileFields[$fieldName] = $field;
1290 }
1291 }
1292
1293 if (!empty($activityParams)) {
1294 $activityParams['version'] = 3;
1295 $activityParams['id'] = $this->_activityId;
1296 $activityParams['skipRecentView'] = TRUE;
1297 civicrm_api('Activity', 'create', $activityParams);
1298 }
1299 }
1300
1301 if ($this->_multiRecord && $this->_recordId && $this->_multiRecordFields && $this->_recordExists) {
1302 $params['customRecordValues'][$this->_recordId] = array_keys($this->_multiRecordFields);
1303 }
1304
1305 $this->_id = CRM_Contact_BAO_Contact::createProfileContact(
1306 $params,
1307 $profileFields,
1308 $this->_id,
1309 $addToGroupId,
1310 $this->_gid,
1311 $this->_ctype,
1312 TRUE
1313 );
1314
1315 //mailing type group
1316 if (!empty($mailingType)) {
1317 // we send in the contactID so we match the same groups and are exact, rather than relying on email
1318 // CRM-8710
1319 CRM_Mailing_Event_BAO_Subscribe::commonSubscribe($mailingType, $result, $this->_id, 'profile');
1320 }
1321
1322 $ufGroups = [];
1323 if ($this->_gid) {
1324 $ufGroups[$this->_gid] = 1;
1325 }
1326 elseif ($this->_mode == self::MODE_REGISTER) {
1327 $ufGroups = CRM_Core_BAO_UFGroup::getModuleUFGroup('User Registration');
1328 }
1329
1330 foreach ($ufGroups as $gId => $val) {
1331 if ($notify = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_UFGroup', $gId, 'notify')) {
1332 $values = CRM_Core_BAO_UFGroup::checkFieldsEmptyValues($gId, $this->_id, NULL);
1333 CRM_Core_BAO_UFGroup::commonSendMail($this->_id, $values);
1334 }
1335 }
1336
1337 //create CMS user (if CMS user option is selected in profile)
1338 if (!empty($params['cms_create_account']) &&
1339 ($this->_mode == self::MODE_CREATE || $this->_mode == self::MODE_EDIT)
1340 ) {
1341 $params['contactID'] = $this->_id;
1342 if (!CRM_Core_BAO_CMSUser::create($params, $this->_mail)) {
1343 CRM_Core_Session::setStatus(ts('Your profile is not saved and Account is not created.'), ts('Profile Error'), 'error');
1344 CRM_Core_Error::debug_log_message("Rolling back transaction as CMSUser Create failed in Profile_Form for contact " . $params['contactID']);
1345 $transaction->rollback();
1346 return CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/profile/create',
1347 'reset=1&gid=' . $this->_gid
1348 ));
1349 }
1350 }
1351
1352 $transaction->commit();
1353 }
1354
1355 /**
1356 * Check template file exists.
1357 *
1358 * @param string|null $suffix
1359 *
1360 * @return string|null
1361 * Template file path, else null
1362 */
1363 public function checkTemplateFileExists($suffix = NULL) {
1364 if ($this->_gid) {
1365 $templateFile = "CRM/Profile/Form/{$this->_gid}/{$this->_name}.{$suffix}tpl";
1366 $template = CRM_Core_Form::getTemplate();
1367 if ($template->template_exists($templateFile)) {
1368 return $templateFile;
1369 }
1370
1371 // lets see if we have customized by name
1372 $ufGroupName = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_UFGroup', $this->_gid, 'name');
1373 if ($ufGroupName) {
1374 $templateFile = "CRM/Profile/Form/{$ufGroupName}/{$this->_name}.{$suffix}tpl";
1375 if ($template->template_exists($templateFile)) {
1376 return $templateFile;
1377 }
1378 }
1379 }
1380 return NULL;
1381 }
1382
1383 /**
1384 * Use the form name to create the tpl file name.
1385 *
1386 * @return string
1387 */
1388 public function getTemplateFileName() {
1389 $fileName = $this->checkTemplateFileExists();
1390 return $fileName ? $fileName : parent::getTemplateFileName();
1391 }
1392
1393 /**
1394 * Default extra tpl file basically just replaces .tpl with .extra.tpl
1395 * i.e. we dont override
1396 *
1397 * @return string
1398 */
1399 public function overrideExtraTemplateFileName() {
1400 $fileName = $this->checkTemplateFileExists('extra.');
1401 return $fileName ? $fileName : parent::overrideExtraTemplateFileName();
1402 }
1403
1404 }