Merge pull request #13923 from seamuslee001/update_phpword_patches
[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 $fileHash = CRM_Core_BAO_File::generateFileHash($entityId, $fileId);
613 $deleteURL = CRM_Utils_System::url('civicrm/file',
614 "reset=1&id={$fileId}&eid=$entityId&fid={$key}&action=delete&fcs={$fileHash}"
615 );
616 $text = ts("Delete Attached File");
617 $customFiles[$field['name']]['deleteURL'] = "<a href=\"{$deleteURL}\" onclick = \"if (confirm( ' $deleteExtra ' )) this.href+='&amp;confirmed=1'; else return false;\">$text</a>";
618
619 // also delete the required rule that we've set on the form element
620 $this->removeFileRequiredRules($name);
621 }
622 }
623 }
624 }
625 }
626 else {
627 foreach ($this->_fields as $name => $field) {
628 if ($customFieldID = CRM_Core_BAO_CustomField::getKeyID($name)) {
629 $htmlType = $field['html_type'];
630 if ((!isset($this->_defaults[$name]) || $htmlType == 'File') &&
631 (CRM_Utils_Array::value('field_type', $field) != 'Activity')
632 ) {
633 CRM_Core_BAO_CustomField::setProfileDefaults($customFieldID,
634 $name,
635 $this->_defaults,
636 $this->_id,
637 $this->_mode
638 );
639 }
640
641 if ($htmlType == 'File') {
642 $entityId = $this->_id;
643 if (CRM_Utils_Array::value('field_type', $field) == 'Activity' && $this->_activityId) {
644 $entityId = $this->_activityId;
645 }
646 $url = CRM_Core_BAO_CustomField::getFileURL($entityId, $customFieldID);
647
648 if ($url) {
649 $customFiles[$field['name']]['displayURL'] = ts("Attached File") . ": {$url['file_url']}";
650
651 $deleteExtra = ts("Are you sure you want to delete attached file?");
652 $fileId = $url['file_id'];
653 $fileHash = CRM_Core_BAO_File::generateFileHash($entityId, $fileId); /* fieldId=$customFieldID */
654 $deleteURL = CRM_Utils_System::url('civicrm/file',
655 "reset=1&id={$fileId}&eid=$entityId&fid={$customFieldID}&action=delete&fcs={$fileHash}"
656 );
657 $text = ts("Delete Attached File");
658 $customFiles[$field['name']]['deleteURL'] = "<a href=\"{$deleteURL}\" onclick = \"if (confirm( ' $deleteExtra ' )) this.href+='&amp;confirmed=1'; else return false;\">$text</a>";
659
660 // also delete the required rule that we've set on the form element
661 $this->removeFileRequiredRules($field['name']);
662 }
663 }
664 }
665 }
666 }
667 if (isset($customFiles)) {
668 $this->assign('customFiles', $customFiles);
669 }
670
671 if ($this->_multiRecordProfile) {
672 $this->setDefaults($this->_defaults);
673 return;
674 }
675
676 if (!empty($this->_defaults['image_URL'])) {
677 $this->assign("imageURL", CRM_Utils_File::getImageURL($this->_defaults['image_URL']));
678 $this->removeFileRequiredRules('image_URL');
679 }
680
681 $this->setDefaults($this->_defaults);
682 }
683
684 /**
685 * Build the form object.
686 *
687 */
688 public function buildQuickForm() {
689 $this->add('hidden', 'gid', $this->_gid);
690
691 switch ($this->_mode) {
692 case self::MODE_CREATE:
693 case self::MODE_EDIT:
694 case self::MODE_REGISTER:
695 CRM_Utils_Hook::buildProfile($this->_ufGroup['name']);
696 break;
697
698 case self::MODE_SEARCH:
699 CRM_Utils_Hook::searchProfile($this->_ufGroup['name']);
700 break;
701
702 default:
703 }
704
705 //lets have single status message, CRM-4363
706 $return = FALSE;
707 $statusMessage = NULL;
708 if (($this->_multiRecord & CRM_Core_Action::ADD) && $this->_maxRecordLimit) {
709 return;
710 }
711
712 if (($this->_multiRecord & CRM_Core_Action::DELETE)) {
713 if (!$this->_recordExists) {
714 CRM_Core_Session::setStatus(ts('The record %1 doesnot exists', array(1 => $this->_recordId)), ts('Record doesnot exists'), 'alert');
715 }
716 else {
717 $this->assign('deleteRecord', TRUE);
718 }
719 return;
720 }
721
722 CRM_Core_BAO_Address::checkContactSharedAddressFields($this->_fields, $this->_id);
723
724 // we should not allow component and mix profiles in search mode
725 if ($this->_mode != self::MODE_REGISTER) {
726 //check for mix profile fields (eg: individual + other contact type)
727 if (CRM_Core_BAO_UFField::checkProfileType($this->_gid)) {
728 if (($this->_mode & self::MODE_EDIT) && $this->_isContactActivityProfile) {
729 $errors = self::validateContactActivityProfile($this->_activityId, $this->_id, $this->_gid);
730 if (!empty($errors)) {
731 $statusMessage = array_pop($errors);
732 $return = TRUE;
733 }
734 }
735 else {
736 $statusMessage = ts('Profile search, view and edit are not supported for Profiles which include fields for more than one record type.');
737 $return = TRUE;
738 }
739 }
740
741 $profileType = CRM_Core_BAO_UFField::getProfileType($this->_gid);
742
743 if ($this->_id) {
744 $contactTypes = CRM_Contact_BAO_Contact::getContactTypes($this->_id);
745 $contactType = $contactTypes[0];
746
747 array_shift($contactTypes);
748 $contactSubtypes = $contactTypes;
749
750 $profileSubType = FALSE;
751 if (CRM_Contact_BAO_ContactType::isaSubType($profileType)) {
752 $profileSubType = $profileType;
753 $profileType = CRM_Contact_BAO_ContactType::getBasicType($profileType);
754 }
755
756 if (
757 ($profileType != 'Contact' && !$this->_isContactActivityProfile) &&
758 (($profileSubType && !empty($contactSubtypes) && (!in_array($profileSubType, $contactSubtypes))) ||
759 ($profileType != $contactType))
760 ) {
761 $return = TRUE;
762 if (!$statusMessage) {
763 $statusMessage = ts("This profile is configured for contact type '%1'. It cannot be used to edit contacts of other types.",
764 array(1 => $profileSubType ? $profileSubType : $profileType));
765 }
766 }
767 }
768
769 if (
770 in_array(
771 $profileType,
772 array("Membership", "Participant", "Contribution")
773 )
774 ) {
775 $return = TRUE;
776 if (!$statusMessage) {
777 $statusMessage = ts('Profile is not configured for the selected action.');
778 }
779 }
780 }
781
782 //lets have single status message,
783 $this->assign('statusMessage', $statusMessage);
784 if ($return) {
785 return FALSE;
786 }
787
788 $this->assign('id', $this->_id);
789 $this->assign('mode', $this->_mode);
790 $this->assign('action', $this->_action);
791 $this->assign('fields', $this->_fields);
792 $this->assign('fieldset', (isset($this->_fieldset)) ? $this->_fieldset : "");
793
794 // should we restrict what we display
795 $admin = TRUE;
796 if ($this->_mode == self::MODE_EDIT) {
797 $admin = FALSE;
798 // show all fields that are visible:
799 // if we are a admin OR the same user OR acl-user with access to the profile
800 // or we have checksum access to this contact (i.e. the user without a login) - CRM-5909
801 if (
802 CRM_Core_Permission::check('administer users') ||
803 $this->_id == $this->_currentUserID ||
804 $this->_isPermissionedChecksum ||
805 in_array(
806 $this->_gid,
807 CRM_ACL_API::group(
808 CRM_Core_Permission::EDIT,
809 NULL,
810 'civicrm_uf_group',
811 CRM_Core_PseudoConstant::get('CRM_Core_DAO_UFField', 'uf_group_id')
812 )
813 )
814 ) {
815 $admin = TRUE;
816 }
817 }
818
819 // if false, user is not logged-in.
820 $anonUser = FALSE;
821 if (!$this->_currentUserID) {
822 $defaultLocationType = CRM_Core_BAO_LocationType::getDefault();
823 $primaryLocationType = $defaultLocationType->id;
824 $anonUser = TRUE;
825 }
826 $this->assign('anonUser', $anonUser);
827
828 $addCaptcha = array();
829 $emailPresent = FALSE;
830
831 // add the form elements
832 foreach ($this->_fields as $name => $field) {
833 // make sure that there is enough permission to expose this field
834 if (!$admin && $field['visibility'] == 'User and User Admin Only') {
835 unset($this->_fields[$name]);
836 continue;
837 }
838
839 // since the CMS manages the email field, suppress the email display if in
840 // register mode which occur within the CMS form
841 if ($this->_mode == self::MODE_REGISTER && substr($name, 0, 5) == 'email') {
842 unset($this->_fields[$name]);
843 continue;
844 }
845
846 list($prefixName, $index) = CRM_Utils_System::explode('-', $name, 2);
847
848 CRM_Core_BAO_UFGroup::buildProfile($this, $field, $this->_mode);
849
850 if ($field['add_to_group_id']) {
851 $addToGroupId = $field['add_to_group_id'];
852 }
853
854 //build array for captcha
855 if ($field['add_captcha']) {
856 $addCaptcha[$field['group_id']] = $field['add_captcha'];
857 }
858
859 if (($name == 'email-Primary') || ($name == 'email-' . isset($primaryLocationType) ? $primaryLocationType : "")) {
860 $emailPresent = TRUE;
861 $this->_mail = $name;
862 }
863 }
864
865 // add captcha only for create mode.
866 if ($this->_mode == self::MODE_CREATE) {
867 // suppress captcha for logged in users only
868 if ($this->_currentUserID) {
869 $this->_isAddCaptcha = FALSE;
870 }
871 elseif (!$this->_isAddCaptcha && !empty($addCaptcha)) {
872 $this->_isAddCaptcha = TRUE;
873 }
874
875 if ($this->_gid) {
876 $dao = new CRM_Core_DAO_UFGroup();
877 $dao->id = $this->_gid;
878 $dao->addSelect();
879 $dao->addSelect('is_update_dupe');
880 if ($dao->find(TRUE)) {
881 if ($dao->is_update_dupe) {
882 $this->_isUpdateDupe = $dao->is_update_dupe;
883 }
884 }
885 }
886 }
887 else {
888 $this->_isAddCaptcha = FALSE;
889 }
890
891 //finally add captcha to form.
892 if ($this->_isAddCaptcha) {
893 $captcha = CRM_Utils_ReCAPTCHA::singleton();
894 $captcha->add($this);
895 }
896 $this->assign("isCaptcha", $this->_isAddCaptcha);
897
898 if ($this->_mode != self::MODE_SEARCH) {
899 if (isset($addToGroupId)) {
900 $this->_ufGroup['add_to_group_id'] = $addToGroupId;
901 }
902 }
903
904 //let's do set defaults for the profile
905 $this->setDefaultsValues();
906
907 $action = CRM_Utils_Request::retrieve('action', 'String', $this, FALSE, NULL);
908
909 if ($this->_mode == self::MODE_CREATE || $this->_mode == self::MODE_EDIT) {
910 CRM_Core_BAO_CMSUser::buildForm($this, $this->_gid, $emailPresent, $action);
911 }
912 else {
913 $this->assign('showCMS', FALSE);
914 }
915
916 $this->assign('groupId', $this->_gid);
917
918 // if view mode pls freeze it with the done button.
919 if ($this->_action & CRM_Core_Action::VIEW) {
920 $this->freeze();
921 }
922
923 if ($this->_context == 'dialog') {
924 $this->addElement(
925 'submit',
926 $this->_duplicateButtonName,
927 ts('Save Matching Contact')
928 );
929 }
930 }
931
932 /**
933 * Validate profile and provided activity Id.
934 *
935 * @param int $activityId
936 * @param int $contactId
937 * @param int $gid
938 *
939 * @return array
940 */
941 public static function validateContactActivityProfile($activityId, $contactId, $gid) {
942 $errors = array();
943 if (!$activityId) {
944 $errors[] = ts('Profile is using one or more activity fields, and is missing the activity Id (aid) in the URL.');
945 return $errors;
946 }
947
948 $activityDetails = array();
949 $activityParams = array('id' => $activityId);
950 CRM_Activity_BAO_Activity::retrieve($activityParams, $activityDetails);
951
952 if (empty($activityDetails)) {
953 $errors[] = ts('Invalid Activity Id (aid).');
954 return $errors;
955 }
956
957 $profileActivityTypes = CRM_Core_BAO_UFGroup::groupTypeValues($gid, 'Activity');
958
959 if ((!empty($profileActivityTypes['Activity']) &&
960 !in_array($activityDetails['activity_type_id'], $profileActivityTypes['Activity'])
961 ) ||
962 (!in_array($contactId, $activityDetails['assignee_contact']) &&
963 !in_array($contactId, $activityDetails['target_contact'])
964 )
965 ) {
966 $errors[] = ts('This activity cannot be edited or viewed via this profile.');
967 }
968
969 return $errors;
970 }
971
972 /**
973 * Global form rule.
974 *
975 * @param array $fields
976 * The input form values.
977 * @param array $files
978 * The uploaded files if any.
979 * @param CRM_Core_Form $form
980 * The form object.
981 *
982 * @return bool|array
983 * true if no errors, else array of errors
984 */
985 public static function formRule($fields, $files, $form) {
986 CRM_Utils_Hook::validateProfile($form->_ufGroup['name']);
987
988 // if no values, return
989 if (empty($fields)) {
990 return TRUE;
991 }
992
993 $errors = [];
994 $register = NULL;
995
996 // hack we use a -1 in options to indicate that its registration
997 // ... and I can't remove that comment because even though it's clear as mud
998 // perhaps someone will find it helpful in the absence of ANY OTHER EXPLANATION
999 // as to what it means....
1000 if ($form->_id) {
1001 // @todo - wonder if it ever occurred to someone that if they didn't document this param
1002 // it might not be crystal clear why we have it....
1003 $form->_isUpdateDupe = 1;
1004 }
1005
1006 if ($form->_mode == CRM_Profile_Form::MODE_REGISTER) {
1007 $register = TRUE;
1008 }
1009
1010 // don't check for duplicates during registration validation: CRM-375
1011 if (!$register && empty($fields['_qf_Edit_upload_duplicate'])) {
1012 // fix for CRM-3240
1013 if (!empty($fields['email-Primary'])) {
1014 $fields['email'] = CRM_Utils_Array::value('email-Primary', $fields);
1015 }
1016
1017 // fix for CRM-6141
1018 if (!empty($fields['phone-Primary-1']) && empty($fields['phone-Primary'])) {
1019 $fields['phone-Primary'] = $fields['phone-Primary-1'];
1020 }
1021
1022 if (!$form->_id) {
1023 self::handleDuplicateChecking($errors, $fields, $form);
1024 }
1025 }
1026
1027 foreach ($fields as $key => $value) {
1028 list($fieldName, $locTypeId, $phoneTypeId) = CRM_Utils_System::explode('-', $key, 3);
1029 if ($fieldName == 'state_province' && !empty($fields["country-{$locTypeId}"])) {
1030 // Validate Country - State list
1031 $countryId = $fields["country-{$locTypeId}"];
1032 $stateProvinceId = $value;
1033
1034 if ($stateProvinceId && $countryId) {
1035 $stateProvinceDAO = new CRM_Core_DAO_StateProvince();
1036 $stateProvinceDAO->id = $stateProvinceId;
1037 $stateProvinceDAO->find(TRUE);
1038
1039 if ($stateProvinceDAO->country_id != $countryId) {
1040 // country mismatch hence display error
1041 $stateProvinces = CRM_Core_PseudoConstant::stateProvince();
1042 $countries = CRM_Core_PseudoConstant::country();
1043 $errors[$key] = "State/Province " . $stateProvinces[$stateProvinceId] . " is not part of " . $countries[$countryId] . ". It belongs to " . $countries[$stateProvinceDAO->country_id] . ".";
1044 }
1045 }
1046 }
1047
1048 if ($fieldName == 'county' && $fields["state_province-{$locTypeId}"]) {
1049 // Validate County - State list
1050 $stateProvinceId = $fields["state_province-{$locTypeId}"];
1051 $countyId = $value;
1052
1053 if ($countyId && $stateProvinceId) {
1054 $countyDAO = new CRM_Core_DAO_County();
1055 $countyDAO->id = $countyId;
1056 $countyDAO->find(TRUE);
1057
1058 if ($countyDAO->state_province_id != $stateProvinceId) {
1059 // state province mismatch hence display error
1060 $stateProvinces = CRM_Core_PseudoConstant::stateProvince();
1061 $counties = CRM_Core_PseudoConstant::county();
1062 $errors[$key] = "County " . $counties[$countyId] . " is not part of " . $stateProvinces[$stateProvinceId] . ". It belongs to " . $stateProvinces[$countyDAO->state_province_id] . ".";
1063 }
1064 }
1065 }
1066 }
1067 foreach (CRM_Contact_BAO_Contact::$_greetingTypes as $greeting) {
1068 if ($greetingType = CRM_Utils_Array::value($greeting, $fields)) {
1069 $customizedValue = CRM_Core_PseudoConstant::getKey('CRM_Contact_BAO_Contact', $greeting . '_id', 'Customized');
1070 if ($customizedValue == $greetingType && empty($fields[$greeting . '_custom'])) {
1071 $errors[$greeting . '_custom'] = ts('Custom %1 is a required field if %1 is of type Customized.',
1072 array(1 => ucwords(str_replace('_', ' ', $greeting)))
1073 );
1074 }
1075 }
1076 }
1077
1078 return empty($errors) ? TRUE : $errors;
1079 }
1080
1081 /**
1082 * Process the user submitted custom data values.
1083 *
1084 */
1085 public function postProcess() {
1086 $params = $this->controller->exportValues($this->_name);
1087
1088 //if the delete record button is clicked
1089 if ($this->_deleteButtonName) {
1090 if (!empty($_POST[$this->_deleteButtonName]) && $this->_recordId) {
1091 $filterParams['id'] = $this->_customGroupId;
1092 $returnProperties = array('is_multiple', 'table_name');
1093 CRM_Core_DAO::commonRetrieve("CRM_Core_DAO_CustomGroup", $filterParams, $returnValues, $returnProperties);
1094 if (!empty($returnValues['is_multiple'])) {
1095 if ($tableName = CRM_Utils_Array::value('table_name', $returnValues)) {
1096 $sql = "DELETE FROM {$tableName} WHERE id = %1 AND entity_id = %2";
1097 $sqlParams = array(
1098 1 => array($this->_recordId, 'Integer'),
1099 2 => array($this->_id, 'Integer'),
1100 );
1101 CRM_Core_DAO::executeQuery($sql, $sqlParams);
1102 CRM_Core_Session::setStatus(ts('Your record has been deleted.'), ts('Deleted'), 'success');
1103 }
1104 }
1105 return;
1106 }
1107 }
1108 CRM_Utils_Hook::processProfile($this->_ufGroup['name']);
1109 if (!empty($params['image_URL'])) {
1110 CRM_Contact_BAO_Contact::processImageParams($params);
1111 }
1112
1113 $greetingTypes = array(
1114 'addressee' => 'addressee_id',
1115 'email_greeting' => 'email_greeting_id',
1116 'postal_greeting' => 'postal_greeting_id',
1117 );
1118
1119 $details = array();
1120 if ($this->_id) {
1121 $contactDetails = CRM_Contact_BAO_Contact::getHierContactDetails($this->_id,
1122 $greetingTypes
1123 );
1124 $details = $contactDetails[0][$this->_id];
1125 }
1126 if (!(!empty($details['addressee_id']) || !empty($details['email_greeting_id']) ||
1127 CRM_Utils_Array::value('postal_greeting_id', $details)
1128 )
1129 ) {
1130
1131 $profileType = CRM_Core_BAO_UFField::getProfileType($this->_gid);
1132 //Though Profile type is contact we need
1133 //Individual/Household/Organization for setting Greetings.
1134 if ($profileType == 'Contact') {
1135 $profileType = 'Individual';
1136 //if we editing Household/Organization.
1137 if ($this->_id) {
1138 $profileType = CRM_Contact_BAO_Contact::getContactType($this->_id);
1139 }
1140 }
1141 if (CRM_Contact_BAO_ContactType::isaSubType($profileType)) {
1142 $profileType = CRM_Contact_BAO_ContactType::getBasicType($profileType);
1143 }
1144
1145 foreach ($greetingTypes as $key => $value) {
1146 if (!array_key_exists($key, $params)) {
1147 $params[$key] = CRM_Contact_BAO_Contact_Utils::defaultGreeting($profileType, $key);
1148 }
1149 }
1150 }
1151
1152 $transaction = new CRM_Core_Transaction();
1153
1154 //used to send subscribe mail to the group which user want.
1155 //if the profile double option in is enabled
1156 $mailingType = array();
1157
1158 $result = NULL;
1159 foreach ($params as $name => $values) {
1160 if (substr($name, 0, 6) == 'email-') {
1161 $result['email'] = $values;
1162 }
1163 }
1164
1165 //array of group id, subscribed by contact
1166 $contactGroup = array();
1167 if (!empty($params['group']) &&
1168 CRM_Core_BAO_UFGroup::isProfileDoubleOptin()
1169 ) {
1170 $groupSubscribed = array();
1171 if (!empty($result['email'])) {
1172 if ($this->_id) {
1173 $contactGroups = new CRM_Contact_DAO_GroupContact();
1174 $contactGroups->contact_id = $this->_id;
1175 $contactGroups->status = 'Added';
1176 $contactGroups->find();
1177 $contactGroup = array();
1178 while ($contactGroups->fetch()) {
1179 $contactGroup[] = $contactGroups->group_id;
1180 $groupSubscribed[$contactGroups->group_id] = 1;
1181 }
1182 }
1183 foreach ($params['group'] as $key => $val) {
1184 if (!$val) {
1185 unset($params['group'][$key]);
1186 continue;
1187 }
1188 $groupTypes = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Group',
1189 $key, 'group_type', 'id'
1190 );
1191 $groupType = explode(CRM_Core_DAO::VALUE_SEPARATOR,
1192 substr($groupTypes, 1, -1)
1193 );
1194 //filter group of mailing type and unset it from params
1195 if (in_array(2, $groupType)) {
1196 //if group is already subscribed , ignore it
1197 $groupExist = CRM_Utils_Array::key($key, $contactGroup);
1198 if (!isset($groupExist)) {
1199 $mailingType[] = $key;
1200 unset($params['group'][$key]);
1201 }
1202 }
1203 }
1204 }
1205 }
1206
1207 $addToGroupId = CRM_Utils_Array::value('add_to_group_id', $this->_ufGroup);
1208 if (!empty($addToGroupId)) {
1209 //run same check whether group is a mailing list
1210 $groupTypes = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Group',
1211 $addToGroupId, 'group_type', 'id'
1212 );
1213 $groupType = explode(CRM_Core_DAO::VALUE_SEPARATOR,
1214 substr($groupTypes, 1, -1)
1215 );
1216 //filter group of mailing type and unset it from params
1217 if (in_array(2, $groupType) && !empty($result['email']) &&
1218 CRM_Core_BAO_UFGroup::isProfileAddToGroupDoubleOptin()
1219 ) {
1220 if (!count($contactGroup)) {
1221 //array of group id, subscribed by contact
1222 $contactGroup = array();
1223 if ($this->_id) {
1224 $contactGroups = new CRM_Contact_DAO_GroupContact();
1225 $contactGroups->contact_id = $this->_id;
1226 $contactGroups->status = 'Added';
1227 $contactGroups->find();
1228 $contactGroup = array();
1229 while ($contactGroups->fetch()) {
1230 $contactGroup[] = $contactGroups->group_id;
1231 $groupSubscribed[$contactGroups->group_id] = 1;
1232 }
1233 }
1234 }
1235 //if group is already subscribed , ignore it
1236 $groupExist = CRM_Utils_Array::key($addToGroupId, $contactGroup);
1237 if (!isset($groupExist)) {
1238 $mailingType[] = $addToGroupId;
1239 $addToGroupId = NULL;
1240 }
1241 }
1242 else {
1243 // since we are directly adding contact to group lets unset it from mailing
1244 if ($key = array_search($addToGroupId, $mailingType)) {
1245 unset($mailingType[$key]);
1246 }
1247 }
1248 }
1249
1250 if ($this->_grid) {
1251 $params['group'] = $groupSubscribed;
1252 }
1253
1254 // commenting below code, since we potentially
1255 // triggered maximum name field formatting cases during CRM-4430.
1256 // CRM-4343
1257 // $params['preserveDBName'] = true;
1258
1259 $profileFields = $this->_fields;
1260 if (($this->_mode & self::MODE_EDIT) && $this->_activityId && $this->_isContactActivityProfile) {
1261 $profileFields = $activityParams = array();
1262 foreach ($this->_fields as $fieldName => $field) {
1263 if (CRM_Utils_Array::value('field_type', $field) == 'Activity') {
1264 if (isset($params[$fieldName])) {
1265 $activityParams[$fieldName] = $params[$fieldName];
1266 }
1267 if (isset($params['activity_date_time'])) {
1268 $activityParams['activity_date_time'] = CRM_Utils_Date::processDate($params['activity_date_time'], $params['activity_date_time_time']);
1269 }
1270 if (!empty($params[$fieldName]) && isset($params["{$fieldName}_id"])) {
1271 $activityParams[$fieldName] = $params["{$fieldName}_id"];
1272 }
1273 }
1274 else {
1275 $profileFields[$fieldName] = $field;
1276 }
1277 }
1278
1279 if (!empty($activityParams)) {
1280 $activityParams['version'] = 3;
1281 $activityParams['id'] = $this->_activityId;
1282 $activityParams['skipRecentView'] = TRUE;
1283 civicrm_api('Activity', 'create', $activityParams);
1284 }
1285 }
1286
1287 if ($this->_multiRecord && $this->_recordId && $this->_multiRecordFields && $this->_recordExists) {
1288 $params['customRecordValues'][$this->_recordId] = array_keys($this->_multiRecordFields);
1289 }
1290
1291 $this->_id = CRM_Contact_BAO_Contact::createProfileContact(
1292 $params,
1293 $profileFields,
1294 $this->_id,
1295 $addToGroupId,
1296 $this->_gid,
1297 $this->_ctype,
1298 TRUE
1299 );
1300
1301 //mailing type group
1302 if (!empty($mailingType)) {
1303 // we send in the contactID so we match the same groups and are exact, rather than relying on email
1304 // CRM-8710
1305 CRM_Mailing_Event_BAO_Subscribe::commonSubscribe($mailingType, $result, $this->_id, 'profile');
1306 }
1307
1308 $ufGroups = array();
1309 if ($this->_gid) {
1310 $ufGroups[$this->_gid] = 1;
1311 }
1312 elseif ($this->_mode == self::MODE_REGISTER) {
1313 $ufGroups = CRM_Core_BAO_UFGroup::getModuleUFGroup('User Registration');
1314 }
1315
1316 foreach ($ufGroups as $gId => $val) {
1317 if ($notify = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_UFGroup', $gId, 'notify')) {
1318 $values = CRM_Core_BAO_UFGroup::checkFieldsEmptyValues($gId, $this->_id, NULL);
1319 CRM_Core_BAO_UFGroup::commonSendMail($this->_id, $values);
1320 }
1321 }
1322
1323 //create CMS user (if CMS user option is selected in profile)
1324 if (!empty($params['cms_create_account']) &&
1325 ($this->_mode == self::MODE_CREATE || $this->_mode == self::MODE_EDIT)
1326 ) {
1327 $params['contactID'] = $this->_id;
1328 if (!CRM_Core_BAO_CMSUser::create($params, $this->_mail)) {
1329 CRM_Core_Session::setStatus(ts('Your profile is not saved and Account is not created.'), ts('Profile Error'), 'error');
1330 CRM_Core_Error::debug_log_message("Rolling back transaction as CMSUser Create failed in Profile_Form for contact " . $params['contactID']);
1331 $transaction->rollback();
1332 return CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/profile/create',
1333 'reset=1&gid=' . $this->_gid
1334 ));
1335 }
1336 }
1337
1338 $transaction->commit();
1339 }
1340
1341 /**
1342 * @param null $suffix
1343 *
1344 * @return null|string
1345 */
1346 public function checkTemplateFileExists($suffix = NULL) {
1347 if ($this->_gid) {
1348 $templateFile = "CRM/Profile/Form/{$this->_gid}/{$this->_name}.{$suffix}tpl";
1349 $template = CRM_Core_Form::getTemplate();
1350 if ($template->template_exists($templateFile)) {
1351 return $templateFile;
1352 }
1353
1354 // lets see if we have customized by name
1355 $ufGroupName = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_UFGroup', $this->_gid, 'name');
1356 if ($ufGroupName) {
1357 $templateFile = "CRM/Profile/Form/{$ufGroupName}/{$this->_name}.{$suffix}tpl";
1358 if ($template->template_exists($templateFile)) {
1359 return $templateFile;
1360 }
1361 }
1362 }
1363 return NULL;
1364 }
1365
1366 /**
1367 * Use the form name to create the tpl file name.
1368 *
1369 * @return string
1370 */
1371 public function getTemplateFileName() {
1372 $fileName = $this->checkTemplateFileExists();
1373 return $fileName ? $fileName : parent::getTemplateFileName();
1374 }
1375
1376 /**
1377 * Default extra tpl file basically just replaces .tpl with .extra.tpl
1378 * i.e. we dont override
1379 *
1380 * @return string
1381 */
1382 public function overrideExtraTemplateFileName() {
1383 $fileName = $this->checkTemplateFileExists('extra.');
1384 return $fileName ? $fileName : parent::overrideExtraTemplateFileName();
1385 }
1386
1387 }