Merge pull request #16474 from sushantpaste/test-for-pr-13809
[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 /**
20 * This class generates form components for custom data
21 *
22 * It delegates the work to lower level subclasses and integrates the changes
23 * back in. It also uses a lot of functionality with the CRM API's, so any change
24 * made here could potentially affect the API etc. Be careful, be aware, use unit tests.
25 *
26 */
27 class CRM_Profile_Form extends CRM_Core_Form {
28 const
29 MODE_REGISTER = 1,
30 MODE_SEARCH = 2,
31 MODE_CREATE = 4,
32 MODE_EDIT = 8;
33
34 protected $_mode;
35
36 protected $_skipPermission = FALSE;
37
38 /**
39 * The contact id that we are editing.
40 *
41 * @var int
42 */
43 protected $_id;
44
45 /**
46 * The group id that we are editing.
47 *
48 * @var int
49 */
50 protected $_gid;
51
52 /**
53 * @var array
54 * Details of the UFGroup used on this page
55 */
56 protected $_ufGroup = ['name' => 'unknown'];
57
58 /**
59 * The group id that we are passing in url.
60 *
61 * @var int
62 */
63 public $_grid;
64
65 /**
66 * Name of button for saving matching contacts.
67 * @var string
68 */
69 protected $_duplicateButtonName;
70 /**
71 * The title of the category we are editing.
72 *
73 * @var string
74 */
75 protected $_title;
76
77 /**
78 * The fields needed to build this form.
79 *
80 * @var array
81 */
82 public $_fields;
83
84 /**
85 * store contact details.
86 *
87 * @var array
88 */
89 protected $_contact;
90
91 /**
92 * Do we allow updates of the contact.
93 *
94 * @var int
95 */
96 public $_isUpdateDupe = 0;
97
98 /**
99 * Dedupe using a specific rule (CRM-6131).
100 * Not currently exposed in profile settings, but can be set in a buildForm hook.
101 * @var int
102 */
103 public $_ruleGroupID = NULL;
104
105 public $_isAddCaptcha = FALSE;
106
107 protected $_isPermissionedChecksum = FALSE;
108
109 /**
110 * THe context from which we came from, allows us to go there if redirect not set.
111 *
112 * @var string
113 */
114 protected $_context;
115
116 /**
117 * THe contact type for registration case.
118 *
119 * @var string
120 */
121 protected $_ctype = NULL;
122
123 /**
124 * Store profile ids if multiple profile ids are passed using comma separated.
125 * Currently lets implement this functionality only for dialog mode.
126 * @var array
127 */
128 protected $_profileIds = [];
129
130 /**
131 * Contact profile having activity fields?
132 *
133 * @var string
134 */
135 protected $_isContactActivityProfile = FALSE;
136
137 /**
138 * Activity Id connected to the profile.
139 *
140 * @var string
141 */
142 protected $_activityId = NULL;
143
144
145 protected $_multiRecordFields = NULL;
146
147 protected $_recordId = NULL;
148
149 /**
150 * Action for multi record profile (create/edit/delete).
151 *
152 * @var string
153 */
154 protected $_multiRecord = NULL;
155
156 protected $_multiRecordProfile = FALSE;
157
158 protected $_recordExists = TRUE;
159
160 protected $_customGroupTitle = NULL;
161
162 protected $_deleteButtonName = NULL;
163
164 protected $_customGroupId = NULL;
165
166 protected $_currentUserID = NULL;
167 protected $_session = NULL;
168
169 /**
170 * Check for any duplicates.
171 *
172 * Depending on form settings & usage scenario we potentially use the found id,
173 * create links to found ids or add an error.
174 *
175 * @param array $errors
176 * @param array $fields
177 * @param CRM_Profile_Form $form
178 *
179 * @return array
180 */
181 protected static function handleDuplicateChecking(&$errors, $fields, $form) {
182 if ($form->_mode == CRM_Profile_Form::MODE_CREATE) {
183 // fix for CRM-2888
184 $exceptions = [];
185 }
186 else {
187 // for edit mode we need to allow our own record to be a dupe match!
188 $exceptions = [CRM_Core_Session::singleton()->get('userID')];
189 }
190 $contactType = CRM_Core_BAO_UFGroup::getContactType($form->_gid);
191 // If all profile fields is of Contact Type then consider
192 // profile is of Individual type(default).
193 if (!$contactType) {
194 $contactType = 'Individual';
195 }
196
197 $ids = CRM_Contact_BAO_Contact::getDuplicateContacts(
198 $fields, $contactType,
199 ($form->_context === 'dialog' ? 'Supervised' : 'Unsupervised'),
200 $exceptions,
201 FALSE,
202 $form->_ruleGroupID
203 );
204 if ($ids) {
205 if ($form->_isUpdateDupe == 2) {
206 CRM_Core_Session::setStatus(ts('Note: this contact may be a duplicate of an existing record.'), ts('Possible Duplicate Detected'), 'alert');
207 }
208 elseif ($form->_isUpdateDupe == 1) {
209 $form->_id = $ids[0];
210 }
211 else {
212 if ($form->_context == 'dialog') {
213 $contactLinks = CRM_Contact_BAO_Contact_Utils::formatContactIDSToLinks($ids, TRUE, TRUE);
214
215 $duplicateContactsLinks = '<div class="matching-contacts-found">';
216 $duplicateContactsLinks .= ts('One matching contact was found. ', [
217 'count' => count($contactLinks['rows']),
218 'plural' => '%count matching contacts were found.<br />',
219 ]);
220 if ($contactLinks['msg'] == 'view') {
221 $duplicateContactsLinks .= ts('You can View the existing contact.', [
222 'count' => count($contactLinks['rows']),
223 'plural' => 'You can View the existing contacts.',
224 ]);
225 }
226 else {
227 $duplicateContactsLinks .= ts('You can View or Edit the existing contact.', [
228 'count' => count($contactLinks['rows']),
229 'plural' => 'You can View or Edit the existing contacts.',
230 ]);
231 }
232 $duplicateContactsLinks .= '</div>';
233 $duplicateContactsLinks .= '<table class="matching-contacts-actions">';
234 $row = '';
235 for ($i = 0; $i < count($contactLinks['rows']); $i++) {
236 $row .= ' <tr> ';
237 $row .= ' <td class="matching-contacts-name"> ';
238 $row .= $contactLinks['rows'][$i]['display_name'];
239 $row .= ' </td>';
240 $row .= ' <td class="matching-contacts-email"> ';
241 $row .= $contactLinks['rows'][$i]['primary_email'];
242 $row .= ' </td>';
243 $row .= ' <td class="action-items"> ';
244 $row .= $contactLinks['rows'][$i]['view'] . ' ';
245 $row .= $contactLinks['rows'][$i]['edit'];
246 $row .= ' </td>';
247 $row .= ' </tr> ';
248 }
249
250 $duplicateContactsLinks .= $row . '</table>';
251 $duplicateContactsLinks .= "If you're sure this record is not a duplicate, click the 'Save Matching Contact' button below.";
252
253 $errors['_qf_default'] = $duplicateContactsLinks;
254
255 // let smarty know that there are duplicates
256 $template = CRM_Core_Smarty::singleton();
257 $template->assign('isDuplicate', 1);
258 }
259 else {
260 $errors['_qf_default'] = ts('A record already exists with the same information.');
261 }
262 }
263 }
264 return $errors;
265 }
266
267 /**
268 * Explicitly declare the entity api name.
269 */
270 public function getDefaultEntity() {
271 return 'Profile';
272 }
273
274 /**
275 * Pre processing work done here.
276 *
277 * gets session variables for table name, id of entity in table, type of entity and stores them.
278 */
279 public function preProcess() {
280 $this->_id = $this->get('id');
281 $this->_profileIds = $this->get('profileIds');
282 $this->_grid = CRM_Utils_Request::retrieve('grid', 'Integer', $this);
283 $this->_context = CRM_Utils_Request::retrieve('context', 'Alphanumeric', $this);
284
285 //unset from session when $_GET doesn't have it
286 //except when the form is submitted
287 if (empty($_POST)) {
288 if (!array_key_exists('multiRecord', $_GET)) {
289 $this->set('multiRecord', NULL);
290 }
291 if (!array_key_exists('recordId', $_GET)) {
292 $this->set('recordId', NULL);
293 }
294 }
295
296 $this->_currentUserID = CRM_Core_Session::singleton()->get('userID');
297
298 if ($this->_mode == self::MODE_EDIT) {
299 //specifies the action being done on a multi record field
300 $multiRecordAction = CRM_Utils_Request::retrieve('multiRecord', 'String', $this);
301 $this->_multiRecord = (!is_numeric($multiRecordAction)) ? CRM_Core_Action::resolve($multiRecordAction) : $multiRecordAction;
302 if ($this->_multiRecord) {
303 $this->set('multiRecord', $this->_multiRecord);
304 }
305
306 if ($this->_multiRecord &&
307 !in_array($this->_multiRecord, [CRM_Core_Action::UPDATE, CRM_Core_Action::ADD, CRM_Core_Action::DELETE])
308 ) {
309 CRM_Core_Error::fatal(ts('Proper action not specified for this custom value record profile'));
310 }
311 }
312 $this->_duplicateButtonName = $this->getButtonName('upload', 'duplicate');
313
314 $gids = explode(',', CRM_Utils_Request::retrieve('gid', 'String', CRM_Core_DAO::$_nullObject, FALSE, 0));
315
316 if ((count($gids) > 1) && !$this->_profileIds && empty($this->_profileIds)) {
317 if (!empty($gids)) {
318 foreach ($gids as $pfId) {
319 $this->_profileIds[] = CRM_Utils_Type::escape($pfId, 'Positive');
320 }
321 }
322
323 // check if we are rendering mixed profiles
324 if (CRM_Core_BAO_UFGroup::checkForMixProfiles($this->_profileIds)) {
325 CRM_Core_Error::fatal(ts('You cannot combine profiles of multiple types.'));
326 }
327
328 // for now consider 1'st profile as primary profile and validate it
329 // i.e check for profile type etc.
330 // FIX ME: validations for other than primary
331 $this->_gid = $this->_profileIds[0];
332 $this->set('gid', $this->_gid);
333 $this->set('profileIds', $this->_profileIds);
334 }
335
336 if (!$this->_gid) {
337 $this->_gid = CRM_Utils_Request::retrieve('gid', 'Positive', $this, FALSE, 0);
338 $this->set('gid', $this->_gid);
339 }
340
341 $this->_activityId = CRM_Utils_Request::retrieve('aid', 'Positive', $this, FALSE, 0, 'GET');
342 if (is_numeric($this->_activityId)) {
343 $latestRevisionId = CRM_Activity_BAO_Activity::getLatestActivityId($this->_activityId);
344 if ($latestRevisionId) {
345 $this->_activityId = $latestRevisionId;
346 }
347 }
348 $this->_isContactActivityProfile = CRM_Core_BAO_UFField::checkContactActivityProfileType($this->_gid);
349
350 //get values for ufGroupName, captcha and dupe update.
351 if ($this->_gid) {
352 $dao = new CRM_Core_DAO_UFGroup();
353 $dao->id = $this->_gid;
354 if ($dao->find(TRUE)) {
355 $this->_isUpdateDupe = $dao->is_update_dupe;
356 $this->_isAddCaptcha = $dao->add_captcha;
357 $this->_ufGroup = (array) $dao;
358 }
359
360 if (empty($this->_ufGroup['is_active'])) {
361 CRM_Core_Error::fatal(ts('The requested profile (gid=%1) is inactive or does not exist.', [
362 1 => $this->_gid,
363 ]));
364 }
365 }
366 $this->assign('ufGroupName', $this->_ufGroup['name']);
367
368 $gids = empty($this->_profileIds) ? $this->_gid : $this->_profileIds;
369
370 // if we don't have a gid use the default, else just use that specific gid
371 if (($this->_mode == self::MODE_REGISTER || $this->_mode == self::MODE_CREATE) && !$this->_gid) {
372 $this->_ctype = CRM_Utils_Request::retrieve('ctype', 'String', $this, FALSE, 'Individual', 'REQUEST');
373 $this->_fields = CRM_Core_BAO_UFGroup::getRegistrationFields($this->_action, $this->_mode, $this->_ctype);
374 }
375 elseif ($this->_mode == self::MODE_SEARCH) {
376 $this->_fields = CRM_Core_BAO_UFGroup::getListingFields($this->_action,
377 CRM_Core_BAO_UFGroup::PUBLIC_VISIBILITY | CRM_Core_BAO_UFGroup::LISTINGS_VISIBILITY,
378 FALSE,
379 $gids,
380 TRUE, NULL,
381 $this->_skipPermission,
382 CRM_Core_Permission::SEARCH
383 );
384 }
385 else {
386 $this->_fields = CRM_Core_BAO_UFGroup::getFields($gids, FALSE, NULL,
387 NULL, NULL,
388 FALSE, NULL,
389 $this->_skipPermission,
390 NULL,
391 ($this->_action == CRM_Core_Action::ADD) ? CRM_Core_Permission::CREATE : CRM_Core_Permission::EDIT
392 );
393 $multiRecordFieldListing = FALSE;
394 //using selector for listing of multi-record fields
395 if ($this->_mode == self::MODE_EDIT && $this->_gid) {
396 CRM_Core_BAO_UFGroup::shiftMultiRecordFields($this->_fields, $this->_multiRecordFields);
397
398 if ($this->_multiRecord) {
399 if ($this->_multiRecord != CRM_Core_Action::ADD) {
400 $this->_recordId = CRM_Utils_Request::retrieve('recordId', 'Positive', $this);
401 }
402 else {
403 $this->_recordId = NULL;
404 $this->set('recordId', NULL);
405 }
406 //record id is necessary for _multiRecord view and update/edit action
407 if (!$this->_recordId
408 && ($this->_multiRecord == CRM_Core_Action::UPDATE || $this->_multiRecord == CRM_Core_Action::DELETE)
409 ) {
410 CRM_Core_Error::fatal(ts('The requested Profile (gid=%1) requires record id while performing this action',
411 [1 => $this->_gid]
412 ));
413 }
414 elseif (empty($this->_multiRecordFields)) {
415 CRM_Core_Error::fatal(ts('No Multi-Record Fields configured for this profile (gid=%1)',
416 [1 => $this->_gid]
417 ));
418 }
419
420 $fieldId = CRM_Core_BAO_CustomField::getKeyID(key($this->_multiRecordFields));
421 $customGroupDetails = CRM_Core_BAO_CustomGroup::getGroupTitles([$fieldId]);
422 $this->_customGroupTitle = $customGroupDetails[$fieldId]['groupTitle'];
423 $this->_customGroupId = $customGroupDetails[$fieldId]['groupID'];
424
425 if ($this->_multiRecord == CRM_Core_Action::UPDATE || $this->_multiRecord == CRM_Core_Action::DELETE) {
426 //record exists check
427 foreach ($this->_multiRecordFields as $key => $field) {
428 $fieldIds[] = CRM_Core_BAO_CustomField::getKeyID($key);
429 }
430 $getValues = CRM_Core_BAO_CustomValueTable::getEntityValues($this->_id, NULL, $fieldIds, TRUE);
431
432 if (array_key_exists($this->_recordId, $getValues)) {
433 $this->_recordExists = TRUE;
434 }
435 else {
436 $this->_recordExists = FALSE;
437 if ($this->_multiRecord & CRM_Core_Action::UPDATE) {
438 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');
439 }
440 }
441 }
442 if ($this->_multiRecord & CRM_Core_Action::ADD) {
443 $this->_maxRecordLimit = CRM_Core_BAO_CustomGroup::hasReachedMaxLimit($customGroupDetails[$fieldId]['groupID'], $this->_id);
444 if ($this->_maxRecordLimit) {
445 CRM_Core_Session::setStatus(ts('You cannot add a new record as maximum allowed limit is reached'), ts('Sorry'), 'error');
446 }
447 }
448
449 }
450 elseif (!empty($this->_multiRecordFields)
451 && (!$this->_multiRecord || !in_array($this->_multiRecord, [
452 CRM_Core_Action::DELETE,
453 CRM_Core_Action::UPDATE,
454 ]))
455 ) {
456 CRM_Core_Resources::singleton()->addScriptFile('civicrm', 'js/crm.livePage.js', 1, 'html-header');
457 //multi-record listing page
458 $multiRecordFieldListing = TRUE;
459 $page = new CRM_Profile_Page_MultipleRecordFieldsListing();
460 $cs = $this->get('cs');
461 $page->set('pageCheckSum', $cs);
462 $page->set('contactId', $this->_id);
463 $page->set('profileId', $this->_gid);
464 $page->set('action', CRM_Core_Action::BROWSE);
465 $page->set('multiRecordFieldListing', $multiRecordFieldListing);
466 $page->run();
467 }
468 }
469 $this->assign('multiRecordFieldListing', $multiRecordFieldListing);
470
471 // is profile double-opt in?
472 if (!empty($this->_fields['group']) &&
473 CRM_Core_BAO_UFGroup::isProfileDoubleOptin()
474 ) {
475 $emailField = FALSE;
476 foreach ($this->_fields as $name => $values) {
477 if (substr($name, 0, 6) == 'email-') {
478 $emailField = TRUE;
479 }
480 }
481
482 if (!$emailField) {
483 $status = ts("Email field should be included in profile if you want to use Group(s) when Profile double-opt in process is enabled.");
484 CRM_Core_Session::singleton()->setStatus($status);
485 }
486 }
487
488 //transferring all the multi-record custom fields in _fields
489 if ($this->_multiRecord && !empty($this->_multiRecordFields)) {
490 $this->_fields = $this->_multiRecordFields;
491 $this->_multiRecordProfile = TRUE;
492 }
493 elseif ($this->_multiRecord && empty($this->_multiRecordFields)) {
494 CRM_Core_Session::setStatus(ts('This feature is not currently available.'), ts('Sorry'), 'error');
495 CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm', 'reset=1'));
496 }
497 }
498
499 if (!is_array($this->_fields)) {
500 CRM_Core_Session::setStatus(ts('This feature is not currently available.'), ts('Sorry'), 'error');
501 CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm', 'reset=1'));
502 }
503 }
504
505 /**
506 * Set default values for the form. Note that in edit/view mode
507 * the default values are retrieved from the database
508 *
509 */
510 public function setDefaultsValues() {
511 $this->_defaults = [];
512 if ($this->_multiRecordProfile && ($this->_multiRecord == CRM_Core_Action::DELETE)) {
513 return;
514 }
515
516 if ($this->_mode != self::MODE_SEARCH) {
517 // set default values for country / state to start with
518 CRM_Core_BAO_UFGroup::setRegisterDefaults($this->_fields, $this->_defaults);
519 }
520
521 if ($this->_id && !$this->_multiRecordProfile) {
522 if ($this->_isContactActivityProfile) {
523 $contactFields = $activityFields = [];
524 foreach ($this->_fields as $fieldName => $field) {
525 if (CRM_Utils_Array::value('field_type', $field) == 'Activity') {
526 $activityFields[$fieldName] = $field;
527 }
528 else {
529 $contactFields[$fieldName] = $field;
530 }
531 }
532
533 CRM_Core_BAO_UFGroup::setProfileDefaults($this->_id, $contactFields, $this->_defaults, TRUE);
534 if ($this->_activityId) {
535 CRM_Core_BAO_UFGroup::setComponentDefaults($activityFields, $this->_activityId, 'Activity', $this->_defaults, TRUE);
536 }
537 }
538 else {
539 CRM_Core_BAO_UFGroup::setProfileDefaults($this->_id, $this->_fields, $this->_defaults, TRUE);
540 }
541 }
542
543 //set custom field defaults
544 if ($this->_multiRecordProfile) {
545 foreach ($this->_multiRecordFields as $key => $field) {
546 $fieldIds[] = CRM_Core_BAO_CustomField::getKeyID($key);
547 }
548
549 $defaultValues = [];
550 if ($this->_multiRecord && $this->_multiRecord == CRM_Core_Action::UPDATE) {
551 $defaultValues = CRM_Core_BAO_CustomValueTable::getEntityValues($this->_id, NULL, $fieldIds, TRUE);
552 if ($this->_recordExists == TRUE) {
553 $defaultValues = $defaultValues[$this->_recordId];
554 }
555 else {
556 $defaultValues = NULL;
557 }
558 }
559
560 if (!empty($defaultValues)) {
561 foreach ($defaultValues as $key => $value) {
562 $name = "custom_{$key}";
563 $htmlType = $this->_multiRecordFields[$name]['html_type'];
564 if ($htmlType != 'File') {
565 if (isset($value)) {
566 CRM_Core_BAO_CustomField::setProfileDefaults($key,
567 $name,
568 $this->_defaults,
569 $this->_id,
570 $this->_mode,
571 $value
572 );
573 }
574 else {
575 $this->_defaults[$name] = "";
576 }
577 }
578
579 if ($htmlType == 'File') {
580 $entityId = $this->_id;
581 if (CRM_Utils_Array::value('field_type', $field) == 'Activity' &&
582 $this->_activityId
583 ) {
584 $entityId = $this->_activityId;
585 }
586
587 $url = '';
588 if (isset($value)) {
589 $url = CRM_Core_BAO_CustomField::getFileURL($entityId, $key, $value);
590 }
591
592 if ($url) {
593 $customFiles[$name]['displayURL'] = ts("Attached File") . ": {$url['file_url']}";
594
595 $deleteExtra = ts("Are you sure you want to delete attached file?");
596 $fileId = $url['file_id'];
597 $fileHash = CRM_Core_BAO_File::generateFileHash($entityId, $fileId);
598 $deleteURL = CRM_Utils_System::url('civicrm/file',
599 "reset=1&id={$fileId}&eid=$entityId&fid={$key}&action=delete&fcs={$fileHash}"
600 );
601 $text = ts("Delete Attached File");
602 $customFiles[$field['name']]['deleteURL'] = "<a href=\"{$deleteURL}\" onclick = \"if (confirm( ' $deleteExtra ' )) this.href+='&amp;confirmed=1'; else return false;\">$text</a>";
603
604 // also delete the required rule that we've set on the form element
605 $this->removeFileRequiredRules($name);
606 }
607 }
608 }
609 }
610 }
611 else {
612 foreach ($this->_fields as $name => $field) {
613 if ($customFieldID = CRM_Core_BAO_CustomField::getKeyID($name)) {
614 $htmlType = $field['html_type'];
615 if ((!isset($this->_defaults[$name]) || $htmlType == 'File') &&
616 (CRM_Utils_Array::value('field_type', $field) != 'Activity')
617 ) {
618 CRM_Core_BAO_CustomField::setProfileDefaults($customFieldID,
619 $name,
620 $this->_defaults,
621 $this->_id,
622 $this->_mode
623 );
624 }
625
626 if ($htmlType == 'File') {
627 $entityId = $this->_id;
628 if (CRM_Utils_Array::value('field_type', $field) == 'Activity' && $this->_activityId) {
629 $entityId = $this->_activityId;
630 }
631 $url = CRM_Core_BAO_CustomField::getFileURL($entityId, $customFieldID);
632
633 if ($url) {
634 $customFiles[$field['name']]['displayURL'] = ts("Attached File") . ": {$url['file_url']}";
635
636 $deleteExtra = ts("Are you sure you want to delete attached file?");
637 $fileId = $url['file_id'];
638 $fileHash = CRM_Core_BAO_File::generateFileHash($entityId, $fileId); /* fieldId=$customFieldID */
639 $deleteURL = CRM_Utils_System::url('civicrm/file',
640 "reset=1&id={$fileId}&eid=$entityId&fid={$customFieldID}&action=delete&fcs={$fileHash}"
641 );
642 $text = ts("Delete Attached File");
643 $customFiles[$field['name']]['deleteURL'] = "<a href=\"{$deleteURL}\" onclick = \"if (confirm( ' $deleteExtra ' )) this.href+='&amp;confirmed=1'; else return false;\">$text</a>";
644
645 // also delete the required rule that we've set on the form element
646 $this->removeFileRequiredRules($field['name']);
647 }
648 }
649 }
650 }
651 }
652 if (isset($customFiles)) {
653 $this->assign('customFiles', $customFiles);
654 }
655
656 if ($this->_multiRecordProfile) {
657 $this->setDefaults($this->_defaults);
658 return;
659 }
660
661 if (!empty($this->_defaults['image_URL'])) {
662 $this->assign("imageURL", CRM_Utils_File::getImageURL($this->_defaults['image_URL']));
663 $this->removeFileRequiredRules('image_URL');
664 }
665
666 $this->setDefaults($this->_defaults);
667 }
668
669 /**
670 * Build the form object.
671 *
672 */
673 public function buildQuickForm() {
674 $this->add('hidden', 'gid', $this->_gid);
675
676 switch ($this->_mode) {
677 case self::MODE_CREATE:
678 case self::MODE_EDIT:
679 case self::MODE_REGISTER:
680 CRM_Utils_Hook::buildProfile($this->_ufGroup['name']);
681 break;
682
683 case self::MODE_SEARCH:
684 CRM_Utils_Hook::searchProfile($this->_ufGroup['name']);
685 break;
686
687 default:
688 }
689
690 //lets have single status message, CRM-4363
691 $return = FALSE;
692 $statusMessage = NULL;
693 if (($this->_multiRecord & CRM_Core_Action::ADD) && $this->_maxRecordLimit) {
694 return;
695 }
696
697 if (($this->_multiRecord & CRM_Core_Action::DELETE)) {
698 if (!$this->_recordExists) {
699 CRM_Core_Session::setStatus(ts('The record %1 doesnot exists', [1 => $this->_recordId]), ts('Record doesnot exists'), 'alert');
700 }
701 else {
702 $this->assign('deleteRecord', TRUE);
703 }
704 return;
705 }
706
707 CRM_Core_BAO_Address::checkContactSharedAddressFields($this->_fields, $this->_id);
708
709 // we should not allow component and mix profiles in search mode
710 if ($this->_mode != self::MODE_REGISTER) {
711 //check for mix profile fields (eg: individual + other contact type)
712 if (CRM_Core_BAO_UFField::checkProfileType($this->_gid)) {
713 if (($this->_mode & self::MODE_EDIT) && $this->_isContactActivityProfile) {
714 $errors = self::validateContactActivityProfile($this->_activityId, $this->_id, $this->_gid);
715 if (!empty($errors)) {
716 $statusMessage = array_pop($errors);
717 $return = TRUE;
718 }
719 }
720 else {
721 $statusMessage = ts('Profile search, view and edit are not supported for Profiles which include fields for more than one record type.');
722 $return = TRUE;
723 }
724 }
725
726 $profileType = CRM_Core_BAO_UFField::getProfileType($this->_gid);
727
728 if ($this->_id) {
729 $contactTypes = CRM_Contact_BAO_Contact::getContactTypes($this->_id);
730 $contactType = $contactTypes[0];
731
732 array_shift($contactTypes);
733 $contactSubtypes = $contactTypes;
734
735 $profileSubType = FALSE;
736 if (CRM_Contact_BAO_ContactType::isaSubType($profileType)) {
737 $profileSubType = $profileType;
738 $profileType = CRM_Contact_BAO_ContactType::getBasicType($profileType);
739 }
740
741 if (
742 ($profileType != 'Contact' && !$this->_isContactActivityProfile) &&
743 (($profileSubType && !empty($contactSubtypes) && (!in_array($profileSubType, $contactSubtypes))) ||
744 ($profileType != $contactType))
745 ) {
746 $return = TRUE;
747 if (!$statusMessage) {
748 $statusMessage = ts("This profile is configured for contact type '%1'. It cannot be used to edit contacts of other types.",
749 [1 => $profileSubType ? $profileSubType : $profileType]);
750 }
751 }
752 }
753
754 if (
755 in_array(
756 $profileType,
757 ["Membership", "Participant", "Contribution"]
758 )
759 ) {
760 $return = TRUE;
761 if (!$statusMessage) {
762 $statusMessage = ts('Profile is not configured for the selected action.');
763 }
764 }
765 }
766
767 //lets have single status message,
768 $this->assign('statusMessage', $statusMessage);
769 if ($return) {
770 return FALSE;
771 }
772
773 $this->assign('id', $this->_id);
774 $this->assign('mode', $this->_mode);
775 $this->assign('action', $this->_action);
776 $this->assign('fields', $this->_fields);
777 $this->assign('fieldset', (isset($this->_fieldset)) ? $this->_fieldset : "");
778
779 // should we restrict what we display
780 $admin = TRUE;
781 if ($this->_mode == self::MODE_EDIT) {
782 $admin = FALSE;
783 // show all fields that are visible:
784 // if we are a admin OR the same user OR acl-user with access to the profile
785 // or we have checksum access to this contact (i.e. the user without a login) - CRM-5909
786 if (
787 CRM_Core_Permission::check('administer users') ||
788 $this->_id == $this->_currentUserID ||
789 $this->_isPermissionedChecksum ||
790 in_array(
791 $this->_gid,
792 CRM_ACL_API::group(
793 CRM_Core_Permission::EDIT,
794 NULL,
795 'civicrm_uf_group',
796 CRM_Core_PseudoConstant::get('CRM_Core_DAO_UFField', 'uf_group_id')
797 )
798 )
799 ) {
800 $admin = TRUE;
801 }
802 }
803
804 // if false, user is not logged-in.
805 $anonUser = FALSE;
806 if (!$this->_currentUserID) {
807 $defaultLocationType = CRM_Core_BAO_LocationType::getDefault();
808 $primaryLocationType = $defaultLocationType->id;
809 $anonUser = TRUE;
810 }
811 $this->assign('anonUser', $anonUser);
812
813 $addCaptcha = [];
814 $emailPresent = FALSE;
815
816 // add the form elements
817 foreach ($this->_fields as $name => $field) {
818 // make sure that there is enough permission to expose this field
819 if (!$admin && $field['visibility'] == 'User and User Admin Only') {
820 unset($this->_fields[$name]);
821 continue;
822 }
823
824 // since the CMS manages the email field, suppress the email display if in
825 // register mode which occur within the CMS form
826 if ($this->_mode == self::MODE_REGISTER && substr($name, 0, 5) == 'email') {
827 unset($this->_fields[$name]);
828 continue;
829 }
830
831 list($prefixName, $index) = CRM_Utils_System::explode('-', $name, 2);
832
833 CRM_Core_BAO_UFGroup::buildProfile($this, $field, $this->_mode);
834
835 if ($field['add_to_group_id']) {
836 $addToGroupId = $field['add_to_group_id'];
837 }
838
839 //build array for captcha
840 if ($field['add_captcha']) {
841 $addCaptcha[$field['group_id']] = $field['add_captcha'];
842 }
843
844 if (($name == 'email-Primary') || ($name == 'email-' . isset($primaryLocationType) ? $primaryLocationType : "")) {
845 $emailPresent = TRUE;
846 $this->_mail = $name;
847 }
848 }
849
850 // add captcha only for create mode.
851 if ($this->_mode == self::MODE_CREATE) {
852 // suppress captcha for logged in users only
853 if ($this->_currentUserID) {
854 $this->_isAddCaptcha = FALSE;
855 }
856 elseif (!$this->_isAddCaptcha && !empty($addCaptcha)) {
857 $this->_isAddCaptcha = TRUE;
858 }
859
860 if ($this->_gid) {
861 $dao = new CRM_Core_DAO_UFGroup();
862 $dao->id = $this->_gid;
863 $dao->addSelect();
864 $dao->addSelect('is_update_dupe');
865 if ($dao->find(TRUE)) {
866 if ($dao->is_update_dupe) {
867 $this->_isUpdateDupe = $dao->is_update_dupe;
868 }
869 }
870 }
871 }
872 else {
873 $this->_isAddCaptcha = FALSE;
874 }
875
876 //finally add captcha to form.
877 if ($this->_isAddCaptcha) {
878 CRM_Utils_ReCAPTCHA::enableCaptchaOnForm($this);
879 }
880
881 if ($this->_mode != self::MODE_SEARCH) {
882 if (isset($addToGroupId)) {
883 $this->_ufGroup['add_to_group_id'] = $addToGroupId;
884 }
885 }
886
887 //let's do set defaults for the profile
888 $this->setDefaultsValues();
889
890 $action = CRM_Utils_Request::retrieve('action', 'String', $this, FALSE, NULL);
891
892 if ($this->_mode == self::MODE_CREATE || $this->_mode == self::MODE_EDIT) {
893 CRM_Core_BAO_CMSUser::buildForm($this, $this->_gid, $emailPresent, $action);
894 }
895 else {
896 $this->assign('showCMS', FALSE);
897 }
898
899 $this->assign('groupId', $this->_gid);
900
901 // if view mode pls freeze it with the done button.
902 if ($this->_action & CRM_Core_Action::VIEW) {
903 $this->freeze();
904 }
905
906 if ($this->_context == 'dialog') {
907 $this->addElement(
908 'submit',
909 $this->_duplicateButtonName,
910 ts('Save Matching Contact')
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 && empty($fields['_qf_Edit_upload_duplicate'])) {
995 // fix for CRM-3240
996 if (!empty($fields['email-Primary'])) {
997 $fields['email'] = CRM_Utils_Array::value('email-Primary', $fields);
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 CRM_Utils_Array::value('postal_greeting_id', $details)
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 = CRM_Utils_Array::value('add_to_group_id', $this->_ufGroup);
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 * @param null $suffix
1326 *
1327 * @return null|string
1328 */
1329 public function checkTemplateFileExists($suffix = NULL) {
1330 if ($this->_gid) {
1331 $templateFile = "CRM/Profile/Form/{$this->_gid}/{$this->_name}.{$suffix}tpl";
1332 $template = CRM_Core_Form::getTemplate();
1333 if ($template->template_exists($templateFile)) {
1334 return $templateFile;
1335 }
1336
1337 // lets see if we have customized by name
1338 $ufGroupName = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_UFGroup', $this->_gid, 'name');
1339 if ($ufGroupName) {
1340 $templateFile = "CRM/Profile/Form/{$ufGroupName}/{$this->_name}.{$suffix}tpl";
1341 if ($template->template_exists($templateFile)) {
1342 return $templateFile;
1343 }
1344 }
1345 }
1346 return NULL;
1347 }
1348
1349 /**
1350 * Use the form name to create the tpl file name.
1351 *
1352 * @return string
1353 */
1354 public function getTemplateFileName() {
1355 $fileName = $this->checkTemplateFileExists();
1356 return $fileName ? $fileName : parent::getTemplateFileName();
1357 }
1358
1359 /**
1360 * Default extra tpl file basically just replaces .tpl with .extra.tpl
1361 * i.e. we dont override
1362 *
1363 * @return string
1364 */
1365 public function overrideExtraTemplateFileName() {
1366 $fileName = $this->checkTemplateFileExists('extra.');
1367 return $fileName ? $fileName : parent::overrideExtraTemplateFileName();
1368 }
1369
1370 }