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