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