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