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