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