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