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