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