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