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