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