74ed2ca620c674b3c07c955d56003d8a9cb53592
[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() {
693 $this->add('hidden', 'gid', $this->_gid);
694
695 switch ($this->_mode) {
696 case self::MODE_CREATE:
697 case self::MODE_EDIT:
698 case self::MODE_REGISTER:
699 CRM_Utils_Hook::buildProfile($this->_ufGroup['name']);
700 break;
701
702 case self::MODE_SEARCH:
703 CRM_Utils_Hook::searchProfile($this->_ufGroup['name']);
704 break;
705
706 default:
707 }
708
709 //lets have single status message, CRM-4363
710 $return = FALSE;
711 $statusMessage = NULL;
712 if (($this->_multiRecord & CRM_Core_Action::ADD) && $this->_maxRecordLimit) {
713 return;
714 }
715
716 if (($this->_multiRecord & CRM_Core_Action::DELETE)) {
717 if (!$this->_recordExists) {
718 CRM_Core_Session::setStatus(ts('The record %1 doesnot exists', [1 => $this->_recordId]), ts('Record doesnot exists'), 'alert');
719 }
720 else {
721 $this->assign('deleteRecord', TRUE);
722 }
723 return;
724 }
725
726 CRM_Core_BAO_Address::checkContactSharedAddressFields($this->_fields, $this->_id);
727
728 // we should not allow component and mix profiles in search mode
729 if ($this->_mode != self::MODE_REGISTER) {
730 //check for mix profile fields (eg: individual + other contact type)
731 if (CRM_Core_BAO_UFField::checkProfileType($this->_gid)) {
732 if (($this->_mode & self::MODE_EDIT) && $this->_isContactActivityProfile) {
733 $errors = self::validateContactActivityProfile($this->_activityId, $this->_id, $this->_gid);
734 if (!empty($errors)) {
735 $statusMessage = array_pop($errors);
736 $return = TRUE;
737 }
738 }
739 else {
740 $statusMessage = ts('Profile search, view and edit are not supported for Profiles which include fields for more than one record type.');
741 $return = TRUE;
742 }
743 }
744
745 $profileType = CRM_Core_BAO_UFField::getProfileType($this->_gid);
746
747 if ($this->_id) {
748 $contactTypes = CRM_Contact_BAO_Contact::getContactTypes($this->_id);
749 $contactType = $contactTypes[0];
750
751 array_shift($contactTypes);
752 $contactSubtypes = $contactTypes;
753
754 $profileSubType = FALSE;
755 if (CRM_Contact_BAO_ContactType::isaSubType($profileType)) {
756 $profileSubType = $profileType;
757 $profileType = CRM_Contact_BAO_ContactType::getBasicType($profileType);
758 }
759
760 if (
761 ($profileType != 'Contact' && !$this->_isContactActivityProfile) &&
762 (($profileSubType && !empty($contactSubtypes) && (!in_array($profileSubType, $contactSubtypes))) ||
763 ($profileType != $contactType))
764 ) {
765 $return = TRUE;
766 if (!$statusMessage) {
767 $statusMessage = ts("This profile is configured for contact type '%1'. It cannot be used to edit contacts of other types.",
768 [1 => $profileSubType ? $profileSubType : $profileType]);
769 }
770 }
771 }
772
773 if (
774 in_array(
775 $profileType,
776 ["Membership", "Participant", "Contribution"]
777 )
778 ) {
779 $return = TRUE;
780 if (!$statusMessage) {
781 $statusMessage = ts('Profile is not configured for the selected action.');
782 }
783 }
784 }
785
786 //lets have single status message,
787 $this->assign('statusMessage', $statusMessage);
788 if ($return) {
789 return FALSE;
790 }
791
792 $this->assign('id', $this->_id);
793 $this->assign('mode', $this->_mode);
794 $this->assign('action', $this->_action);
795 $this->assign('fields', $this->_fields);
796 $this->assign('fieldset', (isset($this->_fieldset)) ? $this->_fieldset : "");
797
798 // should we restrict what we display
799 $admin = TRUE;
800 if ($this->_mode == self::MODE_EDIT) {
801 $admin = FALSE;
802 // show all fields that are visible:
803 // if we are a admin OR the same user OR acl-user with access to the profile
804 // or we have checksum access to this contact (i.e. the user without a login) - CRM-5909
805 if (
806 CRM_Core_Permission::check('administer users') ||
807 $this->_id == $this->_currentUserID ||
808 $this->_isPermissionedChecksum ||
809 in_array(
810 $this->_gid,
811 CRM_ACL_API::group(
812 CRM_Core_Permission::EDIT,
813 NULL,
814 'civicrm_uf_group',
815 CRM_Core_PseudoConstant::get('CRM_Core_DAO_UFField', 'uf_group_id')
816 )
817 )
818 ) {
819 $admin = TRUE;
820 }
821 }
822
823 // if false, user is not logged-in.
824 $anonUser = FALSE;
825 if (!$this->_currentUserID) {
826 $defaultLocationType = CRM_Core_BAO_LocationType::getDefault();
827 $primaryLocationType = $defaultLocationType->id;
828 $anonUser = TRUE;
829 }
830 $this->assign('anonUser', $anonUser);
831
832 $emailPresent = FALSE;
833
834 // add the form elements
835 foreach ($this->_fields as $name => $field) {
836 // make sure that there is enough permission to expose this field
837 if (!$admin && $field['visibility'] == 'User and User Admin Only') {
838 unset($this->_fields[$name]);
839 continue;
840 }
841
842 // since the CMS manages the email field, suppress the email display if in
843 // register mode which occur within the CMS form
844 if ($this->_mode == self::MODE_REGISTER && substr($name, 0, 5) == 'email') {
845 unset($this->_fields[$name]);
846 continue;
847 }
848
849 list($prefixName, $index) = CRM_Utils_System::explode('-', $name, 2);
850
851 CRM_Core_BAO_UFGroup::buildProfile($this, $field, $this->_mode);
852
853 if ($field['add_to_group_id']) {
854 $addToGroupId = $field['add_to_group_id'];
855 }
856
857 if (($name == 'email-Primary') || ($name == 'email-' . ($primaryLocationType ?? ""))) {
858 $emailPresent = TRUE;
859 $this->_mail = $name;
860 }
861 }
862
863 if ($this->_mode == self::MODE_CREATE) {
864 if ($this->_gid) {
865 $dao = new CRM_Core_DAO_UFGroup();
866 $dao->id = $this->_gid;
867 $dao->addSelect();
868 $dao->addSelect('is_update_dupe');
869 if ($dao->find(TRUE)) {
870 if ($dao->is_update_dupe) {
871 $this->_isUpdateDupe = $dao->is_update_dupe;
872 }
873 }
874 }
875 }
876
877 if ($this->_mode != self::MODE_SEARCH) {
878 if (isset($addToGroupId)) {
879 $this->_ufGroup['add_to_group_id'] = $addToGroupId;
880 }
881 }
882
883 //let's do set defaults for the profile
884 $this->setDefaultsValues();
885
886 $action = CRM_Utils_Request::retrieve('action', 'String', $this, FALSE, NULL);
887
888 if ($this->_mode == self::MODE_CREATE || $this->_mode == self::MODE_EDIT) {
889 CRM_Core_BAO_CMSUser::buildForm($this, $this->_gid, $emailPresent, $action);
890 }
891 else {
892 $this->assign('showCMS', FALSE);
893 }
894
895 $this->assign('groupId', $this->_gid);
896
897 // if view mode pls freeze it with the done button.
898 if ($this->_action & CRM_Core_Action::VIEW) {
899 $this->freeze();
900 }
901
902 if ($this->_context == 'dialog') {
903 $this->addElement(
904 'xbutton',
905 $this->_duplicateButtonName,
906 ts('Save Matching Contact'),
907 [
908 'type' => 'submit',
909 'class' => 'crm-button',
910 ]
911 );
912 }
913 }
914
915 /**
916 * Validate profile and provided activity Id.
917 *
918 * @param int $activityId
919 * @param int $contactId
920 * @param int $gid
921 *
922 * @return array
923 */
924 public static function validateContactActivityProfile($activityId, $contactId, $gid) {
925 $errors = [];
926 if (!$activityId) {
927 $errors[] = ts('Profile is using one or more activity fields, and is missing the activity Id (aid) in the URL.');
928 return $errors;
929 }
930
931 $activityDetails = [];
932 $activityParams = ['id' => $activityId];
933 CRM_Activity_BAO_Activity::retrieve($activityParams, $activityDetails);
934
935 if (empty($activityDetails)) {
936 $errors[] = ts('Invalid Activity Id (aid).');
937 return $errors;
938 }
939
940 $profileActivityTypes = CRM_Core_BAO_UFGroup::groupTypeValues($gid, 'Activity');
941
942 if ((!empty($profileActivityTypes['Activity']) &&
943 !in_array($activityDetails['activity_type_id'], $profileActivityTypes['Activity'])
944 ) ||
945 (!in_array($contactId, $activityDetails['assignee_contact']) &&
946 !in_array($contactId, $activityDetails['target_contact'])
947 )
948 ) {
949 $errors[] = ts('This activity cannot be edited or viewed via this profile.');
950 }
951
952 return $errors;
953 }
954
955 /**
956 * Global form rule.
957 *
958 * @param array $fields
959 * The input form values.
960 * @param array $files
961 * The uploaded files if any.
962 * @param CRM_Core_Form $form
963 * The form object.
964 *
965 * @return bool|array
966 * true if no errors, else array of errors
967 */
968 public static function formRule($fields, $files, $form) {
969 CRM_Utils_Hook::validateProfile($form->_ufGroup['name']);
970
971 // if no values, return
972 if (empty($fields)) {
973 return TRUE;
974 }
975
976 $errors = [];
977 $register = NULL;
978
979 // hack we use a -1 in options to indicate that its registration
980 // ... and I can't remove that comment because even though it's clear as mud
981 // perhaps someone will find it helpful in the absence of ANY OTHER EXPLANATION
982 // as to what it means....
983 if ($form->_id) {
984 // @todo - wonder if it ever occurred to someone that if they didn't document this param
985 // it might not be crystal clear why we have it....
986 $form->_isUpdateDupe = 1;
987 }
988
989 if ($form->_mode == CRM_Profile_Form::MODE_REGISTER) {
990 $register = TRUE;
991 }
992
993 // don't check for duplicates during registration validation: CRM-375
994 if (!$register && !array_key_exists('_qf_Edit_upload_duplicate', $fields)) {
995 // fix for CRM-3240
996 if (!empty($fields['email-Primary'])) {
997 $fields['email'] = $fields['email-Primary'] ?? NULL;
998 }
999
1000 // fix for CRM-6141
1001 if (!empty($fields['phone-Primary-1']) && empty($fields['phone-Primary'])) {
1002 $fields['phone-Primary'] = $fields['phone-Primary-1'];
1003 }
1004
1005 if (!$form->_id) {
1006 self::handleDuplicateChecking($errors, $fields, $form);
1007 }
1008 }
1009
1010 foreach ($fields as $key => $value) {
1011 list($fieldName, $locTypeId, $phoneTypeId) = CRM_Utils_System::explode('-', $key, 3);
1012 if ($fieldName == 'state_province' && !empty($fields["country-{$locTypeId}"])) {
1013 // Validate Country - State list
1014 $countryId = $fields["country-{$locTypeId}"];
1015 $stateProvinceId = $value;
1016
1017 if ($stateProvinceId && $countryId) {
1018 $stateProvinceDAO = new CRM_Core_DAO_StateProvince();
1019 $stateProvinceDAO->id = $stateProvinceId;
1020 $stateProvinceDAO->find(TRUE);
1021
1022 if ($stateProvinceDAO->country_id != $countryId) {
1023 // country mismatch hence display error
1024 $stateProvinces = CRM_Core_PseudoConstant::stateProvince();
1025 $countries = CRM_Core_PseudoConstant::country();
1026 $errors[$key] = "State/Province " . $stateProvinces[$stateProvinceId] . " is not part of " . $countries[$countryId] . ". It belongs to " . $countries[$stateProvinceDAO->country_id] . ".";
1027 }
1028 }
1029 }
1030
1031 if ($fieldName == 'county' && $fields["state_province-{$locTypeId}"]) {
1032 // Validate County - State list
1033 $stateProvinceId = $fields["state_province-{$locTypeId}"];
1034 $countyId = $value;
1035
1036 if ($countyId && $stateProvinceId) {
1037 $countyDAO = new CRM_Core_DAO_County();
1038 $countyDAO->id = $countyId;
1039 $countyDAO->find(TRUE);
1040
1041 if ($countyDAO->state_province_id != $stateProvinceId) {
1042 // state province mismatch hence display error
1043 $stateProvinces = CRM_Core_PseudoConstant::stateProvince();
1044 $counties = CRM_Core_PseudoConstant::county();
1045 $errors[$key] = "County " . $counties[$countyId] . " is not part of " . $stateProvinces[$stateProvinceId] . ". It belongs to " . $stateProvinces[$countyDAO->state_province_id] . ".";
1046 }
1047 }
1048 }
1049 }
1050 foreach (CRM_Contact_BAO_Contact::$_greetingTypes as $greeting) {
1051 if ($greetingType = CRM_Utils_Array::value($greeting, $fields)) {
1052 $customizedValue = CRM_Core_PseudoConstant::getKey('CRM_Contact_BAO_Contact', $greeting . '_id', 'Customized');
1053 if ($customizedValue == $greetingType && empty($fields[$greeting . '_custom'])) {
1054 $errors[$greeting . '_custom'] = ts('Custom %1 is a required field if %1 is of type Customized.',
1055 [1 => ucwords(str_replace('_', ' ', $greeting))]
1056 );
1057 }
1058 }
1059 }
1060
1061 return empty($errors) ? TRUE : $errors;
1062 }
1063
1064 /**
1065 * Process the user submitted custom data values.
1066 *
1067 */
1068 public function postProcess() {
1069 $params = $this->controller->exportValues($this->_name);
1070
1071 //if the delete record button is clicked
1072 if ($this->_deleteButtonName) {
1073 if (!empty($_POST[$this->_deleteButtonName]) && $this->_recordId) {
1074 $filterParams['id'] = $this->_customGroupId;
1075 $returnProperties = ['is_multiple', 'table_name'];
1076 CRM_Core_DAO::commonRetrieve("CRM_Core_DAO_CustomGroup", $filterParams, $returnValues, $returnProperties);
1077 if (!empty($returnValues['is_multiple'])) {
1078 if ($tableName = CRM_Utils_Array::value('table_name', $returnValues)) {
1079 $sql = "DELETE FROM {$tableName} WHERE id = %1 AND entity_id = %2";
1080 $sqlParams = [
1081 1 => [$this->_recordId, 'Integer'],
1082 2 => [$this->_id, 'Integer'],
1083 ];
1084 CRM_Core_DAO::executeQuery($sql, $sqlParams);
1085 CRM_Core_Session::setStatus(ts('Your record has been deleted.'), ts('Deleted'), 'success');
1086 }
1087 }
1088 return;
1089 }
1090 }
1091 CRM_Utils_Hook::processProfile($this->_ufGroup['name']);
1092 if (!empty($params['image_URL'])) {
1093 CRM_Contact_BAO_Contact::processImageParams($params);
1094 }
1095
1096 $greetingTypes = [
1097 'addressee' => 'addressee_id',
1098 'email_greeting' => 'email_greeting_id',
1099 'postal_greeting' => 'postal_greeting_id',
1100 ];
1101
1102 $details = [];
1103 if ($this->_id) {
1104 $contactDetails = CRM_Contact_BAO_Contact::getHierContactDetails($this->_id,
1105 $greetingTypes
1106 );
1107 $details = $contactDetails[$this->_id];
1108 }
1109 if (!(!empty($details['addressee_id']) || !empty($details['email_greeting_id']) ||
1110 !empty($details['postal_greeting_id'])
1111 )
1112 ) {
1113
1114 $profileType = CRM_Core_BAO_UFField::getProfileType($this->_gid);
1115 //Though Profile type is contact we need
1116 //Individual/Household/Organization for setting Greetings.
1117 if ($profileType == 'Contact') {
1118 $profileType = 'Individual';
1119 //if we editing Household/Organization.
1120 if ($this->_id) {
1121 $profileType = CRM_Contact_BAO_Contact::getContactType($this->_id);
1122 }
1123 }
1124 if (CRM_Contact_BAO_ContactType::isaSubType($profileType)) {
1125 $profileType = CRM_Contact_BAO_ContactType::getBasicType($profileType);
1126 }
1127
1128 foreach ($greetingTypes as $key => $value) {
1129 if (!array_key_exists($key, $params)) {
1130 $params[$key] = CRM_Contact_BAO_Contact_Utils::defaultGreeting($profileType, $key);
1131 }
1132 }
1133 }
1134
1135 $transaction = new CRM_Core_Transaction();
1136
1137 //used to send subscribe mail to the group which user want.
1138 //if the profile double option in is enabled
1139 $mailingType = [];
1140
1141 $result = NULL;
1142 foreach ($params as $name => $values) {
1143 if (substr($name, 0, 6) == 'email-') {
1144 $result['email'] = $values;
1145 }
1146 }
1147
1148 //array of group id, subscribed by contact
1149 $contactGroup = [];
1150 if (!empty($params['group']) &&
1151 CRM_Core_BAO_UFGroup::isProfileDoubleOptin()
1152 ) {
1153 $groupSubscribed = [];
1154 if (!empty($result['email'])) {
1155 if ($this->_id) {
1156 $contactGroups = new CRM_Contact_DAO_GroupContact();
1157 $contactGroups->contact_id = $this->_id;
1158 $contactGroups->status = 'Added';
1159 $contactGroups->find();
1160 $contactGroup = [];
1161 while ($contactGroups->fetch()) {
1162 $contactGroup[] = $contactGroups->group_id;
1163 $groupSubscribed[$contactGroups->group_id] = 1;
1164 }
1165 }
1166 foreach ($params['group'] as $key => $val) {
1167 if (!$val) {
1168 unset($params['group'][$key]);
1169 continue;
1170 }
1171 $groupTypes = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Group',
1172 $key, 'group_type', 'id'
1173 );
1174 $groupType = explode(CRM_Core_DAO::VALUE_SEPARATOR,
1175 substr($groupTypes, 1, -1)
1176 );
1177 //filter group of mailing type and unset it from params
1178 if (in_array(2, $groupType)) {
1179 //if group is already subscribed , ignore it
1180 $groupExist = CRM_Utils_Array::key($key, $contactGroup);
1181 if (!isset($groupExist)) {
1182 $mailingType[] = $key;
1183 unset($params['group'][$key]);
1184 }
1185 }
1186 }
1187 }
1188 }
1189
1190 $addToGroupId = $this->_ufGroup['add_to_group_id'] ?? NULL;
1191 if (!empty($addToGroupId)) {
1192 //run same check whether group is a mailing list
1193 $groupTypes = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Group',
1194 $addToGroupId, 'group_type', 'id'
1195 );
1196 $groupType = explode(CRM_Core_DAO::VALUE_SEPARATOR,
1197 substr($groupTypes, 1, -1)
1198 );
1199 //filter group of mailing type and unset it from params
1200 if (in_array(2, $groupType) && !empty($result['email']) &&
1201 CRM_Core_BAO_UFGroup::isProfileAddToGroupDoubleOptin()
1202 ) {
1203 if (!count($contactGroup)) {
1204 //array of group id, subscribed by contact
1205 $contactGroup = [];
1206 if ($this->_id) {
1207 $contactGroups = new CRM_Contact_DAO_GroupContact();
1208 $contactGroups->contact_id = $this->_id;
1209 $contactGroups->status = 'Added';
1210 $contactGroups->find();
1211 $contactGroup = [];
1212 while ($contactGroups->fetch()) {
1213 $contactGroup[] = $contactGroups->group_id;
1214 $groupSubscribed[$contactGroups->group_id] = 1;
1215 }
1216 }
1217 }
1218 //if group is already subscribed , ignore it
1219 $groupExist = CRM_Utils_Array::key($addToGroupId, $contactGroup);
1220 if (!isset($groupExist)) {
1221 $mailingType[] = $addToGroupId;
1222 $addToGroupId = NULL;
1223 }
1224 }
1225 else {
1226 // since we are directly adding contact to group lets unset it from mailing
1227 if ($key = array_search($addToGroupId, $mailingType)) {
1228 unset($mailingType[$key]);
1229 }
1230 }
1231 }
1232
1233 if ($this->_grid) {
1234 $params['group'] = $groupSubscribed;
1235 }
1236
1237 // commenting below code, since we potentially
1238 // triggered maximum name field formatting cases during CRM-4430.
1239 // CRM-4343
1240 // $params['preserveDBName'] = true;
1241
1242 $profileFields = $this->_fields;
1243 if (($this->_mode & self::MODE_EDIT) && $this->_activityId && $this->_isContactActivityProfile) {
1244 $profileFields = $activityParams = [];
1245 foreach ($this->_fields as $fieldName => $field) {
1246 if (CRM_Utils_Array::value('field_type', $field) == 'Activity') {
1247 if (isset($params[$fieldName])) {
1248 $activityParams[$fieldName] = $params[$fieldName];
1249 }
1250 if (isset($params['activity_date_time'])) {
1251 $activityParams['activity_date_time'] = CRM_Utils_Date::processDate($params['activity_date_time'], $params['activity_date_time_time']);
1252 }
1253 if (!empty($params[$fieldName]) && isset($params["{$fieldName}_id"])) {
1254 $activityParams[$fieldName] = $params["{$fieldName}_id"];
1255 }
1256 }
1257 else {
1258 $profileFields[$fieldName] = $field;
1259 }
1260 }
1261
1262 if (!empty($activityParams)) {
1263 $activityParams['version'] = 3;
1264 $activityParams['id'] = $this->_activityId;
1265 $activityParams['skipRecentView'] = TRUE;
1266 civicrm_api('Activity', 'create', $activityParams);
1267 }
1268 }
1269
1270 if ($this->_multiRecord && $this->_recordId && $this->_multiRecordFields && $this->_recordExists) {
1271 $params['customRecordValues'][$this->_recordId] = array_keys($this->_multiRecordFields);
1272 }
1273
1274 $this->_id = CRM_Contact_BAO_Contact::createProfileContact(
1275 $params,
1276 $profileFields,
1277 $this->_id,
1278 $addToGroupId,
1279 $this->_gid,
1280 $this->_ctype,
1281 TRUE
1282 );
1283
1284 //mailing type group
1285 if (!empty($mailingType)) {
1286 // we send in the contactID so we match the same groups and are exact, rather than relying on email
1287 // CRM-8710
1288 CRM_Mailing_Event_BAO_Subscribe::commonSubscribe($mailingType, $result, $this->_id, 'profile');
1289 }
1290
1291 $ufGroups = [];
1292 if ($this->_gid) {
1293 $ufGroups[$this->_gid] = 1;
1294 }
1295 elseif ($this->_mode == self::MODE_REGISTER) {
1296 $ufGroups = CRM_Core_BAO_UFGroup::getModuleUFGroup('User Registration');
1297 }
1298
1299 foreach ($ufGroups as $gId => $val) {
1300 if ($notify = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_UFGroup', $gId, 'notify')) {
1301 $values = CRM_Core_BAO_UFGroup::checkFieldsEmptyValues($gId, $this->_id, NULL);
1302 CRM_Core_BAO_UFGroup::commonSendMail($this->_id, $values);
1303 }
1304 }
1305
1306 //create CMS user (if CMS user option is selected in profile)
1307 if (!empty($params['cms_create_account']) &&
1308 ($this->_mode == self::MODE_CREATE || $this->_mode == self::MODE_EDIT)
1309 ) {
1310 $params['contactID'] = $this->_id;
1311 if (!CRM_Core_BAO_CMSUser::create($params, $this->_mail)) {
1312 CRM_Core_Session::setStatus(ts('Your profile is not saved and Account is not created.'), ts('Profile Error'), 'error');
1313 CRM_Core_Error::debug_log_message("Rolling back transaction as CMSUser Create failed in Profile_Form for contact " . $params['contactID']);
1314 $transaction->rollback();
1315 return CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/profile/create',
1316 'reset=1&gid=' . $this->_gid
1317 ));
1318 }
1319 }
1320
1321 $transaction->commit();
1322 }
1323
1324 /**
1325 * Check template file exists.
1326 *
1327 * @param string|null $suffix
1328 *
1329 * @return string|null
1330 * Template file path, else null
1331 */
1332 public function checkTemplateFileExists($suffix = NULL) {
1333 if ($this->_gid) {
1334 $templateFile = "CRM/Profile/Form/{$this->_gid}/{$this->_name}.{$suffix}tpl";
1335 $template = CRM_Core_Form::getTemplate();
1336 if ($template->template_exists($templateFile)) {
1337 return $templateFile;
1338 }
1339
1340 // lets see if we have customized by name
1341 $ufGroupName = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_UFGroup', $this->_gid, 'name');
1342 if ($ufGroupName) {
1343 $templateFile = "CRM/Profile/Form/{$ufGroupName}/{$this->_name}.{$suffix}tpl";
1344 if ($template->template_exists($templateFile)) {
1345 return $templateFile;
1346 }
1347 }
1348 }
1349 return NULL;
1350 }
1351
1352 /**
1353 * Use the form name to create the tpl file name.
1354 *
1355 * @return string
1356 */
1357 public function getTemplateFileName() {
1358 $fileName = $this->checkTemplateFileExists();
1359 return $fileName ? $fileName : parent::getTemplateFileName();
1360 }
1361
1362 /**
1363 * Default extra tpl file basically just replaces .tpl with .extra.tpl
1364 * i.e. we dont override
1365 *
1366 * @return string
1367 */
1368 public function overrideExtraTemplateFileName() {
1369 $fileName = $this->checkTemplateFileExists('extra.');
1370 return $fileName ? $fileName : parent::overrideExtraTemplateFileName();
1371 }
1372
1373 }