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