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