Merge pull request #2033 from JoeMurray/master
[civicrm-core.git] / CRM / Profile / Form.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.4 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2013 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
9 | |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
13 | |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
18 | |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
26 */
27
28 /**
29 *
30 * @package CRM
31 * @copyright CiviCRM LLC (c) 2004-2013
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 */
44 class 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
69 /**
70 * The group id that we are editing
71 *
72 * @var string
73 */
74 protected $_ufGroupName = 'unknown';
75
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
183 public $_stateCountryMap = array();
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
267 //get values for ufGroupName, captch and dupe update.
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;
274 if (!empty($dao->name)) {
275 $this->_ufGroupName = $dao->name;
276 }
277 }
278 $dao->free();
279 }
280 $this->assign('ufGroupName', $this->_ufGroupName);
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)) )) {
361 //multirecord listing page
362 $multiRecordFieldListing = TRUE;
363 $page = new CRM_Profile_Page_MultipleRecordFieldsListing();
364 $cs = $this->get('cs');
365 $page->set('pageCheckSum', $cs);
366 $page->set('contactId', $this->_id);
367 $page->set('profileId', $this->_gid);
368 $page->set('action', CRM_Core_Action::BROWSE);
369 $page->set('multiRecordFieldListing', $multiRecordFieldListing);
370 $page->run();
371 }
372 }
373 $this->assign('multiRecordFieldListing', $multiRecordFieldListing);
374
375 // is profile double-opt in?
376 if (CRM_Utils_Array::value('group', $this->_fields) &&
377 CRM_Core_BAO_UFGroup::isProfileDoubleOptin()
378 ) {
379 $emailField = FALSE;
380 foreach ($this->_fields as $name => $values) {
381 if (substr($name, 0, 6) == 'email-') {
382 $emailField = TRUE;
383 }
384 }
385
386 if (!$emailField) {
387 $status = ts("Email field should be included in profile if you want to use Group(s) when Profile double-opt in process is enabled.");
388 $this->_session->setStatus($status);
389 }
390 }
391
392 //transfering all the multirecord custom fields in _fields
393 if ($this->_multiRecord && !empty($this->_multiRecordFields)) {
394 $this->_fields = $this->_multiRecordFields;
395 $this->_multiRecordProfile = TRUE;
396 } elseif ($this->_multiRecord && empty($this->_multiRecordFields)) {
397 CRM_Core_Session::setStatus(ts('This feature is not currently available.'), ts('Sorry'), 'error');
398 return CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm', 'reset=1'));
399 }
400 }
401
402 if (!is_array($this->_fields)) {
403 CRM_Core_Session::setStatus(ts('This feature is not currently available.'), ts('Sorry'), 'error');
404 return CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm', 'reset=1'));
405 }
406 }
407
408 /**
409 * This function sets the default values for the form. Note that in edit/view mode
410 * the default values are retrieved from the database
411 *
412 * @access public
413 *
414 * @return void
415 */
416 function setDefaultsValues() {
417 $this->_defaults = array();
418 if ($this->_multiRecordProfile && ($this->_multiRecord == CRM_Core_Action::DELETE)) {
419 return;
420 }
421
422 if ($this->_mode != self::MODE_SEARCH) {
423 // set default values for country / state to start with
424 CRM_Core_BAO_UFGroup::setRegisterDefaults($this->_fields, $this->_defaults);
425 }
426
427 if ($this->_id && !$this->_multiRecordProfile) {
428 if ($this->_isContactActivityProfile) {
429 $contactFields = $activityFields = array();
430 foreach ($this->_fields as $fieldName => $field) {
431 if (CRM_Utils_Array::value('field_type', $field) == 'Activity') {
432 $activityFields[$fieldName] = $field;
433 }
434 else {
435 $contactFields[$fieldName] = $field;
436 }
437 }
438
439 CRM_Core_BAO_UFGroup::setProfileDefaults($this->_id, $contactFields, $this->_defaults, TRUE);
440 if ($this->_activityId) {
441 CRM_Core_BAO_UFGroup::setComponentDefaults($activityFields, $this->_activityId, 'Activity', $this->_defaults, TRUE);
442 }
443 }
444 else {
445 CRM_Core_BAO_UFGroup::setProfileDefaults($this->_id, $this->_fields, $this->_defaults, TRUE);
446 }
447 }
448
449 //set custom field defaults
450 if ($this->_multiRecordProfile) {
451 foreach ($this->_multiRecordFields as $key => $field) {
452 $fieldIds[] = CRM_Core_BAO_CustomField::getKeyID($key);
453 }
454
455 $defaultValues = array( );
456 if ($this->_multiRecord && $this->_multiRecord == CRM_Core_Action::UPDATE) {
457 $defaultValues = CRM_Core_BAO_CustomValueTable::getEntityValues($this->_id, NULL, $fieldIds, TRUE);
458 if ($this->_recordExists == TRUE) {
459 $defaultValues = $defaultValues[$this->_recordId];
460 } else {
461 $defaultValues = NULL;
462 }
463 }
464
465 if (!empty($defaultValues)) {
466 foreach ($defaultValues as $key => $value) {
467 $name = "custom_{$key}";
468 $htmlType = $this->_multiRecordFields[$name]['html_type'];
469 if ($htmlType != 'File') {
470 if (isset($value)) {
471 CRM_Core_BAO_CustomField::setProfileDefaults($key,
472 $name,
473 $this->_defaults,
474 $this->_id,
475 $this->_mode,
476 $value
477 );
478 } else {
479 $this->_defaults[$name] = "";
480 }
481 }
482
483 if ($htmlType == 'File') {
484 $entityId = $this->_id;
485 if (CRM_Utils_Array::value('field_type', $field) == 'Activity' &&
486 $this->_activityId
487 ) {
488 $entityId = $this->_activityId;
489 }
490 $url = CRM_Core_BAO_CustomField::getFileURL($entityId, $key);
491
492 if ($url) {
493 $customFiles[$name]['displayURL'] = ts("Attached File") . ": {$url['file_url']}";
494
495 $deleteExtra = ts("Are you sure you want to delete attached file?");
496 $fileId = $url['file_id'];
497 $deleteURL = CRM_Utils_System::url('civicrm/file',
498 "reset=1&id={$fileId}&eid=$entityId&fid={$key}&action=delete"
499 );
500 $text = ts("Delete Attached File");
501 $customFiles[$field['name']]['deleteURL'] = "<a href=\"{$deleteURL}\" onclick = \"if (confirm( ' $deleteExtra ' )) this.href+='&amp;confirmed=1'; else return false;\">$text</a>";
502
503 // also delete the required rule that we've set on the form element
504 $this->removeFileRequiredRules($name);
505 }
506 }
507 }
508 }
509 }
510 else {
511 foreach ($this->_fields as $name => $field) {
512 if ($customFieldID = CRM_Core_BAO_CustomField::getKeyID($name)) {
513 $htmlType = $field['html_type'];
514 if ((!isset($this->_defaults[$name]) || $htmlType == 'File') &&
515 (CRM_Utils_Array::value('field_type', $field) != 'Activity')
516 ) {
517 CRM_Core_BAO_CustomField::setProfileDefaults($customFieldID,
518 $name,
519 $this->_defaults,
520 $this->_id,
521 $this->_mode
522 );
523 }
524
525 if ($htmlType == 'File') {
526 $entityId = $this->_id;
527 if (CRM_Utils_Array::value('field_type', $field) == 'Activity' && $this->_activityId) {
528 $entityId = $this->_activityId;
529 }
530 $url = CRM_Core_BAO_CustomField::getFileURL($entityId, $customFieldID);
531
532 if ($url) {
533 $customFiles[$field['name']]['displayURL'] = ts("Attached File") . ": {$url['file_url']}";
534
535 $deleteExtra = ts("Are you sure you want to delete attached file?");
536 $fileId = $url['file_id'];
537 $deleteURL = CRM_Utils_System::url('civicrm/file',
538 "reset=1&id={$fileId}&eid=$entityId&fid={$customFieldID}&action=delete"
539 );
540 $text = ts("Delete Attached File");
541 $customFiles[$field['name']]['deleteURL'] = "<a href=\"{$deleteURL}\" onclick = \"if (confirm( ' $deleteExtra ' )) this.href+='&amp;confirmed=1'; else return false;\">$text</a>";
542
543 // also delete the required rule that we've set on the form element
544 $this->removeFileRequiredRules($field['name']);
545 }
546 }
547 }
548 }
549 }
550 if (isset($customFiles)) {
551 $this->assign('customFiles', $customFiles);
552 }
553
554 if ($this->_multiRecordProfile) {
555 $this->setDefaults($this->_defaults);
556 return;
557 }
558
559 if (CRM_Utils_Array::value('image_URL', $this->_defaults)) {
560 list($imageWidth, $imageHeight) = getimagesize($this->_defaults['image_URL']);
561 list($imageThumbWidth, $imageThumbHeight) = CRM_Contact_BAO_Contact::getThumbSize($imageWidth, $imageHeight);
562 $this->assign("imageWidth", $imageWidth);
563 $this->assign("imageHeight", $imageHeight);
564 $this->assign("imageThumbWidth", $imageThumbWidth);
565 $this->assign("imageThumbHeight", $imageThumbHeight);
566 $this->assign("imageURL", $this->_defaults['image_URL']);
567 $this->removeFileRequiredRules('image_URL');
568 }
569
570 if (array_key_exists('contact_sub_type', $this->_defaults) &&
571 !empty($this->_defaults['contact_sub_type'])
572 ) {
573 $this->_defaults['contact_sub_type'] = explode(CRM_Core_DAO::VALUE_SEPARATOR,
574 trim($this->_defaults['contact_sub_type'], CRM_Core_DAO::VALUE_SEPARATOR)
575 );
576 }
577
578 $this->setDefaults($this->_defaults);
579 }
580
581 /**
582 * Function to actually build the form
583 *
584 * @return void
585 * @access public
586 */
587 public function buildQuickForm() {
588 switch ($this->_mode) {
589 case self::MODE_CREATE:
590 case self::MODE_EDIT:
591 case self::MODE_REGISTER:
592 CRM_Utils_Hook::buildProfile($this->_ufGroupName);
593 break;
594 case self::MODE_SEARCH:
595 CRM_Utils_Hook::searchProfile($this->_ufGroupName);
596 break;
597 default:
598 }
599
600 //lets have single status message, CRM-4363
601 $return = FALSE;
602 $statusMessage = NULL;
603 if (($this->_multiRecord & CRM_Core_Action::ADD) && $this->_maxRecordLimit) {
604 return;
605 }
606
607 if (($this->_multiRecord & CRM_Core_Action::DELETE)) {
608 if (!$this->_recordExists) {
609 CRM_Core_Session::setStatus(ts('The record %1 doesnot exists', array(1 => $this->_recordId)), ts('Record doesnot exists'), 'alert');
610 }
611 else {
612 $this->assign('deleteRecord', TRUE);
613 }
614 return;
615 }
616
617 CRM_Core_BAO_Address::checkContactSharedAddressFields($this->_fields, $this->_id);
618
619 // we should not allow component and mix profiles in search mode
620 if ($this->_mode != self::MODE_REGISTER) {
621 //check for mix profile fields (eg: individual + other contact type)
622 if (CRM_Core_BAO_UFField::checkProfileType($this->_gid)) {
623 if (($this->_mode & self::MODE_EDIT) && $this->_isContactActivityProfile) {
624 $errors = self::validateContactActivityProfile($this->_activityId, $this->_id, $this->_gid);
625 if (!empty($errors)) {
626 $statusMessage = array_pop($errors);
627 $return = TRUE;
628 }
629 }
630 else {
631 $statusMessage = ts('Profile search, view and edit are not supported for Profiles which include fields for more than one record type.');
632 $return = TRUE;
633 }
634 }
635
636 $profileType = CRM_Core_BAO_UFField::getProfileType($this->_gid);
637
638 if ($this->_id) {
639 $contactTypes = CRM_Contact_BAO_Contact::getContactTypes($this->_id);
640 $contactType = $contactTypes[0];
641
642 array_shift($contactTypes);
643 $contactSubtypes = $contactTypes;
644
645 $profileSubType = FALSE;
646 if (CRM_Contact_BAO_ContactType::isaSubType($profileType)) {
647 $profileSubType = $profileType;
648 $profileType = CRM_Contact_BAO_ContactType::getBasicType($profileType);
649 }
650
651 if (
652 ($profileType != 'Contact' && !$this->_isContactActivityProfile) &&
653 (($profileSubType && !empty($contactSubtypes) && (!in_array($profileSubType,$contactSubtypes))) ||
654 ($profileType != $contactType))
655 ) {
656 $return = TRUE;
657 if (!$statusMessage) {
658 $statusMessage =
659 ts("This profile is configured for contact type '%1'. It cannot be used to edit contacts of other types.",
660 array(1 => $profileSubType ? $profileSubType : $profileType));
661 }
662 }
663 }
664
665 if (
666 in_array(
667 $profileType,
668 array("Membership", "Participant", "Contribution")
669 )
670 ) {
671 $return = TRUE;
672 if (!$statusMessage) {
673 $statusMessage = ts('Profile is not configured for the selected action.');
674 }
675 }
676 }
677
678 //lets have sigle status message,
679 $this->assign('statusMessage', $statusMessage);
680 if ($return) {
681 return FALSE;
682 }
683
684 if (count($this->_submitValues)) {
685 $locationTypeId = null;
686 foreach ($this->_fields as $field) {
687 if (!empty($field['location_type_id'])) {
688 $locationTypeId = $field['location_type_id'];
689 }
690 if (array_key_exists("country-{$locationTypeId}", $this->_fields) &&
691 array_key_exists("state_province-{$locationTypeId}", $this->_fields) &&
692 !empty($this->_submitValues["country-{$locationTypeId}"])) {
693 $this->_fields["state_province-{$locationTypeId}"]['is_required'] =
694 CRM_Core_Payment_Form::checkRequiredStateProvince($this, "country-{$locationTypeId}");
695 }
696 }
697 }
698
699 $this->assign('id', $this->_id);
700 $this->assign('mode', $this->_mode);
701 $this->assign('action', $this->_action);
702 $this->assign('fields', $this->_fields);
703 $this->assign('fieldset', (isset($this->_fieldset)) ? $this->_fieldset : "");
704
705 // should we restrict what we display
706 $admin = TRUE;
707 if ($this->_mode == self::MODE_EDIT) {
708 $admin = FALSE;
709 // show all fields that are visibile:
710 // if we are a admin OR the same user OR acl-user with access to the profile
711 // or we have checksum access to this contact (i.e. the user without a login) - CRM-5909
712 if (
713 CRM_Core_Permission::check('administer users') ||
714 $this->_id == $this->_currentUserID ||
715 $this->_isPermissionedChecksum ||
716 in_array(
717 $this->_gid,
718 CRM_ACL_API::group(
719 CRM_Core_Permission::EDIT,
720 NULL,
721 'civicrm_uf_group',
722 CRM_Core_PseudoConstant::get('CRM_Core_DAO_UFField', 'uf_group_id')
723 )
724 )
725 ) {
726 $admin = TRUE;
727 }
728 }
729
730 // if false, user is not logged-in.
731 $anonUser = FALSE;
732 if (!$this->_currentUserID) {
733 $defaultLocationType = CRM_Core_BAO_LocationType::getDefault();
734 $primaryLocationType = $defaultLocationType->id;
735 $anonUser = TRUE;
736 }
737 $this->assign('anonUser', $anonUser);
738
739 $addCaptcha = array();
740 $emailPresent = FALSE;
741
742 // cache the state country fields. based on the results, we could use our javascript solution
743 // in create or register mode
744 $stateCountryMap = array();
745
746 // add the form elements
747 foreach ($this->_fields as $name => $field) {
748 // make sure that there is enough permission to expose this field
749 if (!$admin && $field['visibility'] == 'User and User Admin Only') {
750 unset($this->_fields[$name]);
751 continue;
752 }
753
754 // since the CMS manages the email field, suppress the email display if in
755 // register mode which occur within the CMS form
756 if ($this->_mode == self::MODE_REGISTER && substr($name, 0, 5) == 'email') {
757 unset($this->_fields[$name]);
758 continue;
759 }
760
761 list($prefixName, $index) = CRM_Utils_System::explode('-', $name, 2);
762 if ($prefixName == 'state_province' || $prefixName == 'country' || $prefixName == 'county') {
763 if (!array_key_exists($index, $stateCountryMap)) {
764 $stateCountryMap[$index] = array();
765 }
766 $stateCountryMap[$index][$prefixName] = $name;
767 }
768
769 CRM_Core_BAO_UFGroup::buildProfile($this, $field, $this->_mode);
770
771 if ($field['add_to_group_id']) {
772 $addToGroupId = $field['add_to_group_id'];
773 }
774
775 //build array for captcha
776 if ($field['add_captcha']) {
777 $addCaptcha[$field['group_id']] = $field['add_captcha'];
778 }
779
780 if (($name == 'email-Primary') || ($name == 'email-' . isset($primaryLocationType) ? $primaryLocationType : "")) {
781 $emailPresent = TRUE;
782 $this->_mail = $name;
783 }
784 }
785
786 // add captcha only for create mode.
787 if ($this->_mode == self::MODE_CREATE) {
788 // suppress captcha for logged in users only
789 if ($this->_currentUserID) {
790 $this->_isAddCaptcha = FALSE;
791 }
792 else if (!$this->_isAddCaptcha && !empty($addCaptcha)) {
793 $this->_isAddCaptcha = TRUE;
794 }
795
796 if ($this->_gid) {
797 $dao = new CRM_Core_DAO_UFGroup();
798 $dao->id = $this->_gid;
799 $dao->addSelect();
800 $dao->addSelect('is_update_dupe');
801 if ($dao->find(TRUE)) {
802 if ($dao->is_update_dupe) {
803 $this->_isUpdateDupe = $dao->is_update_dupe;
804 }
805 }
806 }
807 }
808 else {
809 $this->_isAddCaptcha = FALSE;
810 }
811
812 //finally add captcha to form.
813 if ($this->_isAddCaptcha) {
814 $captcha = CRM_Utils_ReCAPTCHA::singleton();
815 $captcha->add($this);
816 }
817 $this->assign("isCaptcha", $this->_isAddCaptcha);
818
819 if ($this->_mode != self::MODE_SEARCH) {
820 if (isset($addToGroupId)) {
821 $this->add('hidden', "add_to_group", $addToGroupId);
822 $this->_addToGroupID = $addToGroupId;
823 }
824 }
825
826 // lets do the defaults, so we can use it for the below state country routines
827 $this->setDefaultsValues();
828
829 // also do state country js
830 CRM_Core_BAO_Address::addStateCountryMap($stateCountryMap, $this->_defaults);
831
832 $action = CRM_Utils_Request::retrieve('action', 'String', $this, FALSE, NULL);
833 if ($this->_mode == self::MODE_CREATE) {
834 CRM_Core_BAO_CMSUser::buildForm($this, $this->_gid, $emailPresent, $action);
835 }
836 else {
837 $this->assign('showCMS', FALSE);
838 }
839
840 $this->assign('groupId', $this->_gid);
841
842 // now fix all state country selectors
843 CRM_Core_BAO_Address::fixAllStateSelects($this, $this->_defaults);
844
845 // if view mode pls freeze it with the done button.
846 if ($this->_action & CRM_Core_Action::VIEW) {
847 $this->freeze();
848 }
849
850 if ($this->_context == 'dialog') {
851 $this->addElement(
852 'submit',
853 $this->_duplicateButtonName,
854 ts('Save Matching Contact')
855 );
856 }
857 }
858
859 /*
860 * Function to validate profile and provided activity Id
861 *
862 * @params Integer $activityId Activity Id
863 * @params Integer $gid Profile Id
864 *
865 * @return Array $errors Errors ( if any ).
866 */
867 static function validateContactActivityProfile($activityId, $contactId, $gid) {
868 $errors = array();
869 if (!$activityId) {
870 $errors[] = 'Profile is using one or more activity fields, and is missing the activity Id (aid) in the URL.';
871 return $errors;
872 }
873
874 $activityDetails = array();
875 $activityParams = array('id' => $activityId);
876 CRM_Activity_BAO_Activity::retrieve($activityParams, $activityDetails);
877
878 if (empty($activityDetails)) {
879 $errors[] = 'Invalid Activity Id (aid).';
880 return $errors;
881 }
882
883 $profileActivityTypes = CRM_Core_BAO_UFGroup::groupTypeValues($gid, 'Activity');
884
885 if ((CRM_Utils_Array::value('Activity', $profileActivityTypes) &&
886 !in_array($activityDetails['activity_type_id'], $profileActivityTypes['Activity'])
887 ) ||
888 (!in_array($contactId, $activityDetails['assignee_contact']) &&
889 !in_array($contactId, $activityDetails['target_contact'])
890 )
891 ) {
892 $errors[] = 'This activity cannot be edited or viewed via this profile.';
893 }
894
895 return $errors;
896 }
897
898 /**
899 * global form rule
900 *
901 * @param array $fields the input form values
902 * @param array $files the uploaded files if any
903 * @param object $form the form object
904 *
905 * @return true if no errors, else array of errors
906 * @access public
907 * @static
908 */
909 static function formRule($fields, $files, $form) {
910 CRM_Utils_Hook::validateProfile($form->_ufGroupName);
911
912 $errors = array();
913 // if no values, return
914 if (empty($fields)) {
915 return TRUE;
916 }
917
918 $register = NULL;
919
920 // hack we use a -1 in options to indicate that its registration
921 if ($form->_id) {
922 $form->_isUpdateDupe = 1;
923 }
924
925 if ($form->_mode == CRM_Profile_Form::MODE_REGISTER) {
926 $register = TRUE;
927 }
928
929 // dont check for duplicates during registration validation: CRM-375
930 if (!$register && !CRM_Utils_Array::value('_qf_Edit_upload_duplicate', $fields)) {
931 // fix for CRM-3240
932 if (CRM_Utils_Array::value('email-Primary', $fields)) {
933 $fields['email'] = CRM_Utils_Array::value('email-Primary', $fields);
934 }
935
936 // fix for CRM-6141
937 if (CRM_Utils_Array::value('phone-Primary-1', $fields) &&
938 !CRM_Utils_Array::value('phone-Primary', $fields)
939 ) {
940 $fields['phone-Primary'] = $fields['phone-Primary-1'];
941 }
942
943 $ctype = CRM_Core_BAO_UFGroup::getContactType($form->_gid);
944 // If all profile fields is of Contact Type then consider
945 // profile is of Individual type(default).
946 if (!$ctype) {
947 $ctype = 'Individual';
948 }
949 $dedupeParams = CRM_Dedupe_Finder::formatParams($fields, $ctype);
950 if ($form->_mode == CRM_Profile_Form::MODE_CREATE) {
951 // fix for CRM-2888
952 $exceptions = array();
953 }
954 else {
955 // for edit mode we need to allow our own record to be a dupe match!
956 $exceptions = array($form->_session->get('userID'));
957 }
958
959 // for dialog mode we should always use fuzzy rule.
960 $ruleType = 'Unsupervised';
961 if ($form->_context == 'dialog') {
962 $ruleType = 'Supervised';
963 }
964
965 $dedupeParams['check_permission'] = FALSE;
966 $ids = CRM_Dedupe_Finder::dupesByParams($dedupeParams,
967 $ctype,
968 $ruleType,
969 $exceptions
970 );
971 if ($ids) {
972 if ($form->_isUpdateDupe == 2) {
973 CRM_Core_Session::setStatus(ts('Note: this contact may be a duplicate of an existing record.'), ts('Possible Duplicate Detected'), 'alert');
974 }
975 elseif ($form->_isUpdateDupe == 1) {
976 if (!$form->_id) {
977 $form->_id = $ids[0];
978 }
979 }
980 else {
981 if ($form->_context == 'dialog') {
982 $contactLinks = CRM_Contact_BAO_Contact_Utils::formatContactIDSToLinks($ids, TRUE, TRUE);
983
984 $duplicateContactsLinks = '<div class="matching-contacts-found">';
985 $duplicateContactsLinks .= ts('One matching contact was found. ', array('count' => count($contactLinks['rows']), 'plural' => '%count matching contacts were found.<br />'));
986 if ($contactLinks['msg'] == 'view') {
987 $duplicateContactsLinks .= ts('You can View the existing contact.', array('count' => count($contactLinks['rows']), 'plural' => 'You can View the existing contacts.'));
988 }
989 else {
990 $duplicateContactsLinks .= ts('You can View or Edit the existing contact.', array('count' => count($contactLinks['rows']), 'plural' => 'You can View or Edit the existing contacts.'));
991 }
992 $duplicateContactsLinks .= '</div>';
993 $duplicateContactsLinks .= '<table class="matching-contacts-actions">';
994 $row = '';
995 for ($i = 0; $i < sizeof($contactLinks['rows']); $i++) {
996 $row .= ' <tr> ';
997 $row .= ' <td class="matching-contacts-name"> ';
998 $row .= $contactLinks['rows'][$i]['display_name'];
999 $row .= ' </td>';
1000 $row .= ' <td class="matching-contacts-email"> ';
1001 $row .= $contactLinks['rows'][$i]['primary_email'];
1002 $row .= ' </td>';
1003 $row .= ' <td class="action-items"> ';
1004 $row .= $contactLinks['rows'][$i]['view'] . ' ';
1005 $row .= $contactLinks['rows'][$i]['edit'];
1006 $row .= ' </td>';
1007 $row .= ' </tr> ';
1008 }
1009
1010 $duplicateContactsLinks .= $row . '</table>';
1011 $duplicateContactsLinks .= "If you're sure this record is not a duplicate, click the 'Save Matching Contact' button below.";
1012
1013 $errors['_qf_default'] = $duplicateContactsLinks;
1014
1015 // let smarty know that there are duplicates
1016 $template = CRM_Core_Smarty::singleton();
1017 $template->assign('isDuplicate', 1);
1018 }
1019 else {
1020 $errors['_qf_default'] = ts('A record already exists with the same information.');
1021 }
1022 }
1023 }
1024 }
1025
1026 foreach ($fields as $key => $value) {
1027 list($fieldName, $locTypeId, $phoneTypeId) = CRM_Utils_System::explode('-', $key, 3);
1028 if ($fieldName == 'state_province' && !empty($fields["country-{$locTypeId}"])) {
1029 // Validate Country - State list
1030 $countryId = $fields["country-{$locTypeId}"];
1031 $stateProvinceId = $value;
1032
1033 if ($stateProvinceId && $countryId) {
1034 $stateProvinceDAO = new CRM_Core_DAO_StateProvince();
1035 $stateProvinceDAO->id = $stateProvinceId;
1036 $stateProvinceDAO->find(TRUE);
1037
1038 if ($stateProvinceDAO->country_id != $countryId) {
1039 // country mismatch hence display error
1040 $stateProvinces = CRM_Core_PseudoConstant::stateProvince();
1041 $countries = CRM_Core_PseudoConstant::country();
1042 $errors[$key] = "State/Province " . $stateProvinces[$stateProvinceId] . " is not part of " . $countries[$countryId] . ". It belongs to " . $countries[$stateProvinceDAO->country_id] . ".";
1043 }
1044 }
1045 }
1046
1047 if ($fieldName == 'county' && $fields["state_province-{$locTypeId}"]) {
1048 // Validate County - State list
1049 $stateProvinceId = $fields["state_province-{$locTypeId}"];
1050 $countyId = $value;
1051
1052 if ($countyId && $stateProvinceId) {
1053 $countyDAO = new CRM_Core_DAO_County();
1054 $countyDAO->id = $countyId;
1055 $countyDAO->find(TRUE);
1056
1057 if ($countyDAO->state_province_id != $stateProvinceId) {
1058 // state province mismatch hence display error
1059 $stateProvinces = CRM_Core_PseudoConstant::stateProvince();
1060 $counties = CRM_Core_PseudoConstant::county();
1061 $errors[$key] = "County " . $counties[$countyId] . " is not part of " . $stateProvinces[$stateProvinceId] . ". It belongs to " . $stateProvinces[$countyDAO->state_province_id] . ".";
1062 }
1063 }
1064 }
1065 }
1066 foreach (CRM_Contact_BAO_Contact::$_greetingTypes as $greeting) {
1067 if ($greetingType = CRM_Utils_Array::value($greeting, $fields)) {
1068 $customizedValue = CRM_Core_OptionGroup::getValue($greeting, 'Customized', 'name');
1069 if ($customizedValue == $greetingType && empty($fields[$greeting . '_custom'])) {
1070 $errors[$greeting . '_custom'] = ts('Custom %1 is a required field if %1 is of type Customized.',
1071 array(1 => ucwords(str_replace('_', ' ', $greeting)))
1072 );
1073 }
1074 }
1075 }
1076
1077 return empty($errors) ? TRUE : $errors;
1078 }
1079
1080 /**
1081 * Process the user submitted custom data values.
1082 *
1083 * @access public
1084 *
1085 * @return void
1086 */
1087 public function postProcess() {
1088 $params = $this->controller->exportValues($this->_name);
1089
1090 //if the delete record button is clicked
1091 if ($this->_deleteButtonName) {
1092 if (CRM_Utils_Array::value($this->_deleteButtonName, $_POST) && $this->_recordId) {
1093 $filterParams['id'] = $this->_customGroupId;
1094 $returnProperities = array('is_multiple', 'table_name');
1095 CRM_Core_DAO::commonRetrieve("CRM_Core_DAO_CustomGroup", $filterParams, $returnValues, $returnProperities);
1096 if (CRM_Utils_Array::value('is_multiple', $returnValues)) {
1097 if ($tableName = CRM_Utils_Array::value('table_name', $returnValues)) {
1098 $sql = "DELETE FROM {$tableName} WHERE id = %1 AND entity_id = %2";
1099 $sqlParams = array(
1100 1 => array($this->_recordId, 'Integer'),
1101 2 => array($this->_id, 'Integer')
1102 );
1103 CRM_Core_DAO::executeQuery($sql, $sqlParams);
1104 CRM_Core_Session::setStatus(ts('Your record has been deleted.'), ts('Deleted'), 'success');
1105 }
1106 }
1107 return;
1108 }
1109 }
1110 CRM_Utils_Hook::processProfile($this->_ufGroupName);
1111 if (CRM_Utils_Array::value('image_URL', $params)) {
1112 CRM_Contact_BAO_Contact::processImageParams($params);
1113 }
1114
1115 $greetingTypes = array(
1116 'addressee' => 'addressee_id',
1117 'email_greeting' => 'email_greeting_id',
1118 'postal_greeting' => 'postal_greeting_id',
1119 );
1120
1121 $details = array();
1122 if ($this->_id) {
1123 $contactDetails = CRM_Contact_BAO_Contact::getHierContactDetails($this->_id,
1124 $greetingTypes
1125 );
1126 $details = $contactDetails[0][$this->_id];
1127 }
1128 if (!(CRM_Utils_Array::value('addressee_id', $details) ||
1129 CRM_Utils_Array::value('email_greeting_id', $details) ||
1130 CRM_Utils_Array::value('postal_greeting_id', $details)
1131 )) {
1132
1133 $profileType = CRM_Core_BAO_UFField::getProfileType($this->_gid);
1134 //Though Profile type is contact we need
1135 //Individual/Household/Organization for setting Greetings.
1136 if ($profileType == 'Contact') {
1137 $profileType = 'Individual';
1138 //if we editing Household/Organization.
1139 if ($this->_id) {
1140 $profileType = CRM_Contact_BAO_Contact::getContactType($this->_id);
1141 }
1142 }
1143 if (CRM_Contact_BAO_ContactType::isaSubType($profileType)) {
1144 $profileType = CRM_Contact_BAO_ContactType::getBasicType($profileType);
1145 }
1146
1147 foreach ($greetingTypes as $key => $value) {
1148 if (!array_key_exists($key, $params)) {
1149 $params[$key] = CRM_Contact_BAO_Contact_Utils::defaultGreeting($profileType, $key);
1150 }
1151 }
1152 }
1153
1154 $transaction = new CRM_Core_Transaction();
1155
1156 //used to send subcribe mail to the group which user want.
1157 //if the profile double option in is enabled
1158 $mailingType = array();
1159 $config = CRM_Core_Config::singleton();
1160
1161 $result = NULL;
1162 foreach ($params as $name => $values) {
1163 if (substr($name, 0, 6) == 'email-') {
1164 $result['email'] = $values;
1165 }
1166 }
1167
1168 //array of group id, subscribed by contact
1169 $contactGroup = array();
1170 if (CRM_Utils_Array::value('group', $params) &&
1171 CRM_Core_BAO_UFGroup::isProfileDoubleOptin()
1172 ) {
1173 $groupSubscribed = array();
1174 if (CRM_Utils_Array::value('email', $result)) {
1175 if ($this->_id) {
1176 $contactGroups = new CRM_Contact_DAO_GroupContact();
1177 $contactGroups->contact_id = $this->_id;
1178 $contactGroups->status = 'Added';
1179 $contactGroups->find();
1180 $contactGroup = array();
1181 while ($contactGroups->fetch()) {
1182 $contactGroup[] = $contactGroups->group_id;
1183 $groupSubscribed[$contactGroups->group_id] = 1;
1184 }
1185 }
1186 foreach ($params['group'] as $key => $val) {
1187 if (!$val) {
1188 unset($params['group'][$key]);
1189 continue;
1190 }
1191 $groupTypes = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Group',
1192 $key, 'group_type', 'id'
1193 );
1194 $groupType = explode(CRM_Core_DAO::VALUE_SEPARATOR,
1195 substr($groupTypes, 1, -1)
1196 );
1197 //filter group of mailing type and unset it from params
1198 if (in_array(2, $groupType)) {
1199 //if group is already subscribed , ignore it
1200 $groupExist = CRM_Utils_Array::key($key, $contactGroup);
1201 if (!isset($groupExist)) {
1202 $mailingType[] = $key;
1203 unset($params['group'][$key]);
1204 }
1205 }
1206 }
1207 }
1208 }
1209
1210 $addToGroupId = NULL;
1211 if (CRM_Utils_Array::value('add_to_group', $params)) {
1212 $addToGroupId = $params['add_to_group'];
1213
1214 //run same check whether group is a mailing list
1215 $groupTypes = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Group',
1216 $addToGroupId, 'group_type', 'id'
1217 );
1218 $groupType = explode(CRM_Core_DAO::VALUE_SEPARATOR,
1219 substr($groupTypes, 1, -1)
1220 );
1221 //filter group of mailing type and unset it from params
1222 if (in_array(2, $groupType) &&
1223 CRM_Utils_Array::value('email', $result) &&
1224 CRM_Core_BAO_UFGroup::isProfileAddToGroupDoubleOptin()
1225 ) {
1226 if (!count($contactGroup)) {
1227 //array of group id, subscribed by contact
1228 $contactGroup = array();
1229 if ($this->_id) {
1230 $contactGroups = new CRM_Contact_DAO_GroupContact();
1231 $contactGroups->contact_id = $this->_id;
1232 $contactGroups->status = 'Added';
1233 $contactGroups->find();
1234 $contactGroup = array();
1235 while ($contactGroups->fetch()) {
1236 $contactGroup[] = $contactGroups->group_id;
1237 $groupSubscribed[$contactGroups->group_id] = 1;
1238 }
1239 }
1240 }
1241 //if group is already subscribed , ignore it
1242 $groupExist = CRM_Utils_Array::key($addToGroupId, $contactGroup);
1243 if (!isset($groupExist)) {
1244 $mailingType[] = $addToGroupId;
1245 $addToGroupId = NULL;
1246 }
1247 }
1248 else {
1249 // since we are directly adding contact to group lets unset it from mailing
1250 if ($key = array_search($addToGroupId, $mailingType)) {
1251 unset($mailingType[$key]);
1252 }
1253 }
1254 }
1255
1256 if ($this->_grid) {
1257 $params['group'] = $groupSubscribed;
1258 }
1259
1260 // commenting below code, since we potentially
1261 // triggered maximum name field formatting cases during CRM-4430.
1262 // CRM-4343
1263 // $params['preserveDBName'] = true;
1264
1265 $profileFields = $this->_fields;
1266 if (($this->_mode & self::MODE_EDIT) && $this->_activityId && $this->_isContactActivityProfile) {
1267 $profileFields = $activityParams = array();
1268 foreach ($this->_fields as $fieldName => $field) {
1269 if (CRM_Utils_Array::value('field_type', $field) == 'Activity') {
1270 if (isset($params[$fieldName])) {
1271 $activityParams[$fieldName] = $params[$fieldName];
1272 }
1273 if (isset($params['activity_date_time'])) {
1274 $activityParams['activity_date_time'] = CRM_Utils_Date::processDate($params['activity_date_time'], $params['activity_date_time_time']);
1275 }
1276 if (CRM_Utils_Array::value($fieldName, $params) && isset($params["{$fieldName}_id"])) {
1277 $activityParams[$fieldName] = $params["{$fieldName}_id"];
1278 }
1279 }
1280 else {
1281 $profileFields[$fieldName] = $field;
1282 }
1283 }
1284
1285 if (!empty($activityParams)) {
1286 $activityParams['version'] = 3;
1287 $activityParams['id'] = $this->_activityId;
1288 $activityParams['skipRecentView'] = TRUE;
1289 civicrm_api('Activity', 'create', $activityParams);
1290 }
1291 }
1292
1293 if ($this->_multiRecord && $this->_recordId && $this->_multiRecordFields && $this->_recordExists) {
1294 $params['customRecordValues'][$this->_recordId] = array_keys($this->_multiRecordFields);
1295 }
1296
1297 $this->_id = CRM_Contact_BAO_Contact::createProfileContact(
1298 $params,
1299 $profileFields,
1300 $this->_id,
1301 $addToGroupId,
1302 $this->_gid,
1303 $this->_ctype,
1304 TRUE
1305 );
1306
1307 //mailing type group
1308 if (!empty($mailingType)) {
1309 // we send in the contactID so we match the same groups and are exact, rather than relying on email
1310 // CRM-8710
1311 CRM_Mailing_Event_BAO_Subscribe::commonSubscribe($mailingType, $result, $this->_id, 'profile');
1312 }
1313
1314 $ufGroups = array();
1315 if ($this->_gid) {
1316 $ufGroups[$this->_gid] = 1;
1317 }
1318 elseif ($this->_mode == self::MODE_REGISTER) {
1319 $ufGroups = CRM_Core_BAO_UFGroup::getModuleUFGroup('User Registration');
1320 }
1321
1322 foreach ($ufGroups as $gId => $val) {
1323 if ($notify = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_UFGroup', $gId, 'notify')) {
1324 $values = CRM_Core_BAO_UFGroup::checkFieldsEmptyValues($gId, $this->_id, NULL);
1325 CRM_Core_BAO_UFGroup::commonSendMail($this->_id, $values);
1326 }
1327 }
1328
1329 //create CMS user (if CMS user option is selected in profile)
1330 if (CRM_Utils_Array::value('cms_create_account', $params) &&
1331 $this->_mode == self::MODE_CREATE
1332 ) {
1333 $params['contactID'] = $this->_id;
1334 if (!CRM_Core_BAO_CMSUser::create($params, $this->_mail)) {
1335 CRM_Core_Session::setStatus(ts('Your profile is not saved and Account is not created.'), ts('Profile Error'), 'error');
1336 CRM_Core_Error::debug_log_message("Rolling back transaction as CMSUser Create failed in Profile_Form for contact " . $params['contactID']);
1337 $transaction->rollback();
1338 return CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/profile/create',
1339 'reset=1&gid=' . $this->_gid
1340 ));
1341 }
1342 }
1343
1344 $transaction->commit();
1345 }
1346
1347 function checkTemplateFileExists($suffix = NULL) {
1348 if ($this->_gid) {
1349 $templateFile = "CRM/Profile/Form/{$this->_gid}/{$this->_name}.{$suffix}tpl";
1350 $template = CRM_Core_Form::getTemplate();
1351 if ($template->template_exists($templateFile)) {
1352 return $templateFile;
1353 }
1354
1355 // lets see if we have customized by name
1356 $ufGroupName = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_UFGroup', $this->_gid, 'name');
1357 if ($ufGroupName) {
1358 $templateFile = "CRM/Profile/Form/{$ufGroupName}/{$this->_name}.{$suffix}tpl";
1359 if ($template->template_exists($templateFile)) {
1360 return $templateFile;
1361 }
1362 }
1363 }
1364 return NULL;
1365 }
1366
1367 function getTemplateFileName() {
1368 $fileName = $this->checkTemplateFileExists();
1369 return $fileName ? $fileName : parent::getTemplateFileName();
1370 }
1371
1372 function overrideExtraTemplateFileName() {
1373 $fileName = $this->checkTemplateFileExists('extra.');
1374 return $fileName ? $fileName : parent::overrideExtraTemplateFileName();
1375 }
1376 }
1377