Merge pull request #9570 from colemanw/CRM-19773-report
[civicrm-core.git] / CRM / UF / Form / Field.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2017 |
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-2017
32 */
33
34 /**
35 * Form to process actions on the field aspect of Custom.
36 */
37 class CRM_UF_Form_Field extends CRM_Core_Form {
38
39 /**
40 * The uf group id saved to the session for an update.
41 *
42 * @var int
43 */
44 protected $_gid;
45
46 /**
47 * The field id, used when editing the field.
48 *
49 * @var int
50 */
51 protected $_id;
52
53 /**
54 * The set of fields that we can view/edit in the user field framework
55 *
56 * @var array
57 */
58 protected $_fields;
59
60 /**
61 * The title for field.
62 *
63 * @var int
64 */
65 protected $_title;
66
67 /**
68 * The set of fields sent to the select element.
69 *
70 * @var array
71 */
72 protected $_selectFields;
73
74 /**
75 * store fields with if locationtype exits status.
76 *
77 * @var array
78 */
79 protected $_hasLocationTypes;
80
81 /**
82 * Is this profile has searchable field.
83 * or is any field having in selector true.
84 *
85 * @var boolean.
86 */
87 protected $_hasSearchableORInSelector;
88
89 /**
90 * Set variables up before form is built.
91 *
92 * @return void
93 */
94 public function preProcess() {
95 $this->_gid = CRM_Utils_Request::retrieve('gid', 'Positive', $this);
96 $this->_id = CRM_Utils_Request::retrieve('id', 'Positive', $this);
97 if ($this->_gid) {
98 $this->_title = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_UFGroup', $this->_gid, 'title');
99
100 $this->setPageTitle(ts('Profile Field'));
101
102 $url = CRM_Utils_System::url('civicrm/admin/uf/group/field',
103 "reset=1&action=browse&gid={$this->_gid}"
104 );
105
106 $session = CRM_Core_Session::singleton();
107 $session->pushUserContext($url);
108 $breadCrumb = array(
109 array(
110 'title' => ts('CiviCRM Profile Fields'),
111 'url' => $url,
112 ),
113 );
114 CRM_Utils_System::appendBreadCrumb($breadCrumb);
115 }
116
117 $showBestResult = CRM_Utils_Request::retrieve('sbr', 'Positive', CRM_Core_DAO::$_nullArray);
118 if ($showBestResult) {
119 $this->assign('showBestResult', $showBestResult);
120 }
121
122 $this->_fields = CRM_Contact_BAO_Contact::importableFields('All', TRUE, TRUE, TRUE, TRUE, TRUE);
123 $this->_fields = array_merge(CRM_Activity_BAO_Activity::exportableFields('Activity'), $this->_fields);
124
125 //unset campaign related fields.
126 if (isset($this->_fields['activity_campaign_id'])) {
127 $this->_fields['activity_campaign_id']['title'] = ts('Campaign');
128 if (isset($this->_fields['activity_campaign'])) {
129 unset($this->_fields['activity_campaign']);
130 }
131 }
132
133 if (CRM_Core_Permission::access('CiviContribute')) {
134 $this->_fields = array_merge(CRM_Contribute_BAO_Contribution::getContributionFields(FALSE), $this->_fields);
135 $this->_fields = array_merge(CRM_Core_BAO_UFField::getContribBatchEntryFields(), $this->_fields);
136 }
137
138 if (CRM_Core_Permission::access('CiviMember')) {
139 $this->_fields = array_merge(CRM_Member_BAO_Membership::getMembershipFields(), $this->_fields);
140 }
141
142 if (CRM_Core_Permission::access('CiviEvent')) {
143 $this->_fields = array_merge(CRM_Event_BAO_Query::getParticipantFields(), $this->_fields);
144 }
145
146 if (CRM_Core_Permission::access('CiviCase')) {
147 $this->_fields = array_merge(CRM_Case_BAO_Query::getFields(), $this->_fields);
148 }
149
150 $this->_fields = array_merge($this->_fields, CRM_Contact_BAO_Query_Hook::singleton()->getFields());
151
152 $this->_selectFields = array();
153 foreach ($this->_fields as $name => $field) {
154 // lets skip note for now since we dont support it
155 if ($name == 'note') {
156 continue;
157 }
158 $this->_selectFields[$name] = $field['title'];
159 $this->_hasLocationTypes[$name] = CRM_Utils_Array::value('hasLocationType', $field);
160 }
161
162 // lets add group, tag and current_employer to this list
163 $this->_selectFields['group'] = ts('Group(s)');
164 $this->_selectFields['tag'] = ts('Tag(s)');
165 $this->_selectFields['current_employer'] = ts('Current Employer');
166 $this->_selectFields['phone_and_ext'] = ts('Phone and Extension');
167
168 //CRM-4363 check for in selector or searchable fields.
169 $this->_hasSearchableORInSelector = CRM_Core_BAO_UFField::checkSearchableORInSelector($this->_gid);
170
171 $this->assign('fieldId', $this->_id);
172 if ($this->_id) {
173 $fieldTitle = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_UFField', $this->_id, 'label');
174 $this->assign('fieldTitle', $fieldTitle);
175 }
176 }
177
178 /**
179 * Build the form object.
180 *
181 * @return void
182 */
183 public function buildQuickForm() {
184 if ($this->_action & CRM_Core_Action::DELETE) {
185 $this->addButtons(array(
186 array(
187 'type' => 'next',
188 'name' => ts('Delete Profile Field'),
189 'spacing' => '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;',
190 'isDefault' => TRUE,
191 ),
192 array(
193 'type' => 'cancel',
194 'name' => ts('Cancel'),
195 ),
196 ));
197 return;
198 }
199
200 if (isset($this->_id)) {
201 $params = array('id' => $this->_id);
202 CRM_Core_BAO_UFField::retrieve($params, $defaults);
203
204 // set it to null if so (avoids crappy E_NOTICE errors below
205 $defaults['location_type_id'] = CRM_Utils_Array::value('location_type_id', $defaults);
206
207 $specialFields = CRM_Core_BAO_UFGroup::getLocationFields();
208
209 if (!$defaults['location_type_id'] &&
210 $defaults["field_type"] != "Formatting" &&
211 in_array($defaults['field_name'], $specialFields)
212 ) {
213 $defaults['location_type_id'] = 0;
214 }
215
216 $defaults['field_name'] = array(
217 $defaults['field_type'],
218 ($defaults['field_type'] == "Formatting" ? "" : $defaults['field_name']),
219 ($defaults['field_name'] == "url") ? $defaults['website_type_id'] : $defaults['location_type_id'],
220 CRM_Utils_Array::value('phone_type_id', $defaults),
221 );
222 $this->_gid = $defaults['uf_group_id'];
223 }
224 else {
225 $defaults['is_active'] = 1;
226 }
227
228 $otherModules = array_values(CRM_Core_BAO_UFGroup::getUFJoinRecord($this->_gid));
229 $this->assign('otherModules', $otherModules);
230
231 if ($this->_action & CRM_Core_Action::ADD) {
232 $fieldValues = array('uf_group_id' => $this->_gid);
233 $defaults['weight'] = CRM_Utils_Weight::getDefaultWeight('CRM_Core_DAO_UFField', $fieldValues);
234 }
235
236 // lets trim all the whitespace
237 $this->applyFilter('__ALL__', 'trim');
238
239 //hidden field to catch the group id in profile
240 $this->add('hidden', 'group_id', $this->_gid);
241
242 //hidden field to catch the field id in profile
243 $this->add('hidden', 'field_id', $this->_id);
244
245 $fields = CRM_Core_BAO_UFField::getAvailableFields($this->_gid, $defaults);
246
247 $noSearchable = $hasWebsiteTypes = array();
248 $addressCustomFields = array_keys(CRM_Core_BAO_CustomField::getFieldsForImport('Address'));
249
250 foreach ($fields as $key => $value) {
251 foreach ($value as $key1 => $value1) {
252 //CRM-2676, replacing the conflict for same custom field name from different custom group.
253 if ($customFieldId = CRM_Core_BAO_CustomField::getKeyID($key1)) {
254 $customGroupId = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomField', $customFieldId, 'custom_group_id');
255 $customGroupName = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomGroup', $customGroupId, 'title');
256 $this->_mapperFields[$key][$key1] = $value1['title'] . ' :: ' . $customGroupName;
257 if (in_array($key1, $addressCustomFields)) {
258 $noSearchable[] = $value1['title'] . ' :: ' . $customGroupName;
259 }
260 }
261 else {
262 $this->_mapperFields[$key][$key1] = $value1['title'];
263 }
264 $hasLocationTypes[$key][$key1] = CRM_Utils_Array::value('hasLocationType', $value1);
265 $hasWebsiteTypes[$key][$key1] = CRM_Utils_Array::value('hasWebsiteType', $value1);
266 // hide the 'is searchable' field for 'File' custom data
267 if (isset($value1['data_type']) &&
268 isset($value1['html_type']) &&
269 (($value1['data_type'] == 'File' && $value1['html_type'] == 'File')
270 || ($value1['data_type'] == 'Link' && $value1['html_type'] == 'Link')
271 )
272 ) {
273 if (!in_array($value1['title'], $noSearchable)) {
274 $noSearchable[] = $value1['title'];
275 }
276 }
277 }
278 }
279 $this->assign('noSearchable', $noSearchable);
280
281 $this->_location_types = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id');
282 $defaultLocationType = CRM_Core_BAO_LocationType::getDefault();
283 $this->_website_types = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Website', 'website_type_id');
284
285 /**
286 * FIXME: dirty hack to make the default option show up first. This
287 * avoids a mozilla browser bug with defaults on dynamically constructed
288 * selector widgets.
289 */
290 if ($defaultLocationType) {
291 $defaultLocation = $this->_location_types[$defaultLocationType->id];
292 unset($this->_location_types[$defaultLocationType->id]);
293 $this->_location_types = array(
294 $defaultLocationType->id => $defaultLocation,
295 ) + $this->_location_types;
296 }
297
298 $this->_location_types = array('Primary') + $this->_location_types;
299
300 // since we need a hierarchical list to display contact types & subtypes,
301 // this is what we going to display in first selector
302 $contactTypes = CRM_Contact_BAO_ContactType::getSelectElements(FALSE, FALSE);
303 unset($contactTypes['']);
304
305 $contactTypes = !empty($contactTypes) ? array('Contact' => 'Contacts') + $contactTypes : array();
306 $sel1 = array('' => '- select -') + $contactTypes;
307
308 if (!empty($fields['Activity'])) {
309 $sel1['Activity'] = 'Activity';
310 }
311
312 if (CRM_Core_Permission::access('CiviEvent')) {
313 $sel1['Participant'] = 'Participants';
314 }
315
316 if (!empty($fields['Contribution'])) {
317 $sel1['Contribution'] = 'Contributions';
318 }
319
320 if (!empty($fields['Membership'])) {
321 $sel1['Membership'] = 'Membership';
322 }
323
324 if (!empty($fields['Case'])) {
325 $sel1['Case'] = 'Case';
326 }
327
328 if (!empty($fields['Formatting'])) {
329 $sel1['Formatting'] = 'Formatting';
330 }
331
332 foreach ($sel1 as $key => $sel) {
333 if ($key) {
334 $sel2[$key] = $this->_mapperFields[$key];
335 }
336 }
337 $sel3[''] = NULL;
338 $phoneTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Phone', 'phone_type_id');
339 ksort($phoneTypes);
340
341 foreach ($sel1 as $k => $sel) {
342 if ($k) {
343 foreach ($this->_location_types as $key => $value) {
344 $sel4[$k]['phone'][$key] = &$phoneTypes;
345 $sel4[$k]['phone_and_ext'][$key] = &$phoneTypes;
346 }
347 }
348 }
349
350 foreach ($sel1 as $k => $sel) {
351 if ($k) {
352 if (is_array($this->_mapperFields[$k])) {
353 foreach ($this->_mapperFields[$k] as $key => $value) {
354 if ($hasLocationTypes[$k][$key]) {
355 $sel3[$k][$key] = $this->_location_types;
356 }
357 elseif ($hasWebsiteTypes[$k][$key]) {
358 $sel3[$k][$key] = $this->_website_types;
359 }
360 else {
361 $sel3[$key] = NULL;
362 }
363 }
364 }
365 }
366 }
367
368 $this->_defaults = array();
369 $js = "<script type='text/javascript'>\n";
370 $formName = "document.{$this->_name}";
371
372 $alreadyMixProfile = FALSE;
373 if (CRM_Core_BAO_UFField::checkProfileType($this->_gid)) {
374 $alreadyMixProfile = TRUE;
375 }
376 $this->assign('alreadyMixProfile', $alreadyMixProfile);
377
378 $sel = &$this->addElement('hierselect', 'field_name', ts('Field Name'));
379
380 $formValues = $this->exportValues();
381
382 if (empty($formValues)) {
383 for ($k = 1; $k < 4; $k++) {
384 if (!isset($defaults['field_name'][$k])) {
385 $js .= "{$formName}['field_name[$k]'].style.display = 'none';\n";
386 }
387 }
388 }
389 else {
390 if (!empty($formValues['field_name'])) {
391 for ($key = 1; $key < 4; $key++) {
392 if (!isset($formValues['field_name'][$key])) {
393 $js .= "{$formName}['field_name[$key]'].style.display = 'none';\n";
394 }
395 else {
396 $js .= "{$formName}['field_name[$key]'].style.display = '';\n";
397 }
398 }
399 }
400 else {
401 for ($k = 1; $k < 4; $k++) {
402 if (!isset($defaults['field_name'][$k])) {
403 $js .= "{$formName}['field_name[$k]'].style.display = 'none';\n";
404 }
405 }
406 }
407 }
408
409 foreach ($sel2 as $k => $v) {
410 if (is_array($sel2[$k])) {
411 asort($sel2[$k]);
412 }
413 }
414
415 $sel->setOptions(array($sel1, $sel2, $sel3, $sel4));
416
417 // proper interpretation of spec in CRM-8732
418 if (!isset($this->_id) && in_array('Search Profile', $otherModules)) {
419 $defaults['visibility'] = 'Public Pages and Listings';
420 }
421
422 $js .= "</script>\n";
423 $this->assign('initHideBoxes', $js);
424
425 $this->add('select',
426 'visibility',
427 ts('Visibility'),
428 CRM_Core_SelectValues::ufVisibility(),
429 TRUE,
430 array('onChange' => "showHideSeletorSearch(this.value);")
431 );
432
433 //CRM-4363
434 $js = array('onChange' => "mixProfile();");
435 // should the field appear in selectors (as a column)?
436 $this->add('advcheckbox', 'in_selector', ts('Results Column?'), NULL, NULL, $js);
437 $this->add('advcheckbox', 'is_searchable', ts('Searchable?'), NULL, NULL, $js);
438
439 $attributes = CRM_Core_DAO::getAttribute('CRM_Core_DAO_UFField');
440
441 // weight
442 $this->add('text', 'weight', ts('Order'), $attributes['weight'], TRUE);
443 $this->addRule('weight', ts('is a numeric field'), 'numeric');
444
445 $this->add('textarea', 'help_pre', ts('Field Pre Help'), $attributes['help_pre']);
446 $this->add('textarea', 'help_post', ts('Field Post Help'), $attributes['help_post']);
447
448 $this->add('advcheckbox', 'is_required', ts('Required?'));
449
450 $this->add('advcheckbox', 'is_multi_summary', ts('Include in multi-record listing?'));
451 $this->add('advcheckbox', 'is_active', ts('Active?'));
452 $this->add('advcheckbox', 'is_view', ts('View Only?'));
453
454 $this->add('text', 'label', ts('Field Label'), $attributes['label']);
455
456 $js = NULL;
457 if ($this->_hasSearchableORInSelector) {
458 $js = array('onclick' => "return verify( );");
459 }
460
461 // add buttons
462 $this->addButtons(array(
463 array(
464 'type' => 'next',
465 'name' => ts('Save'),
466 'isDefault' => TRUE,
467 'js' => $js,
468 ),
469 array(
470 'type' => 'next',
471 'name' => ts('Save and New'),
472 'subName' => 'new',
473 'js' => $js,
474 ),
475 array(
476 'type' => 'cancel',
477 'name' => ts('Cancel'),
478 ),
479 ));
480
481 $this->addFormRule(array('CRM_UF_Form_Field', 'formRule'), $this);
482
483 // if view mode pls freeze it with the done button.
484 if ($this->_action & CRM_Core_Action::VIEW) {
485 $this->freeze();
486 $this->addElement('button', 'done', ts('Done'),
487 array('onclick' => "location.href='civicrm/admin/uf/group/field?reset=1&action=browse&gid=" . $this->_gid . "'")
488 );
489 }
490
491 $this->setDefaults($defaults);
492 }
493
494 /**
495 * Process the form.
496 *
497 * @return void
498 */
499 public function postProcess() {
500
501 if ($this->_action & CRM_Core_Action::DELETE) {
502 $fieldValues = array('uf_group_id' => $this->_gid);
503 CRM_Utils_Weight::delWeight('CRM_Core_DAO_UFField', $this->_id, $fieldValues);
504 $deleted = CRM_Core_BAO_UFField::del($this->_id);
505
506 //update group_type every time. CRM-3608
507 if ($this->_gid && $deleted) {
508 //get the profile type.
509 $fieldsType = CRM_Core_BAO_UFGroup::calculateGroupType($this->_gid, TRUE);
510 CRM_Core_BAO_UFGroup::updateGroupTypes($this->_gid, $fieldsType);
511 }
512
513 CRM_Core_Session::setStatus(ts('Selected Profile Field has been deleted.'), ts('Profile Field Deleted'), 'success');
514 return;
515 }
516
517 // store the submitted values in an array
518 $params = $this->controller->exportValues('Field');
519 $params['uf_group_id'] = $this->_gid;
520 if ($params['visibility'] == 'User and User Admin Only') {
521 $params['is_searchable'] = $params['in_selector'] = 0;
522 }
523
524 if ($this->_action & CRM_Core_Action::UPDATE) {
525 $params['id'] = $this->_id;
526 }
527
528 $name = NULL;
529 if (isset($params['field_name'][1]) && isset($this->_selectFields[$params['field_name'][1]])) {
530 // we dont get a name for a html formatting element
531 $name = $this->_selectFields[$params['field_name'][1]];
532 }
533
534 //Hack for Formatting Field Name
535 if ($params['field_name'][0] == 'Formatting') {
536 $params['field_name'][1] = 'formatting_' . rand(1000, 9999);
537 }
538
539 //check for duplicate fields
540 if ($params["field_name"][0] != "Formatting" && CRM_Core_BAO_UFField::duplicateField($params, array('uf_group' => $params['uf_group_id'], 'uf_field' => $params['id']))) {
541 CRM_Core_Session::setStatus(ts('The selected field already exists in this profile.'), ts('Field Not Added'), 'error');
542 return;
543 }
544 else {
545 $params['weight'] = CRM_Core_BAO_UFField::autoWeight($params);
546 $ufField = CRM_Core_BAO_UFField::add($params);
547
548 //reset other field is searchable and in selector settings, CRM-4363
549 if ($this->_hasSearchableORInSelector &&
550 in_array($ufField->field_type, array('Participant', 'Contribution', 'Membership', 'Activity', 'Case'))
551 ) {
552 CRM_Core_BAO_UFField::resetInSelectorANDSearchable($this->_gid);
553 }
554
555 $config = CRM_Core_Config::singleton();
556 $showBestResult = FALSE;
557 if (in_array($ufField->field_name, array(
558 'country',
559 'state_province',
560 )) && count($config->countryLimit) > 1
561 ) {
562 // get state or country field weight if exists
563 $field = 'state_province';
564 if ($ufField->field_name == 'state_province') {
565 $field = 'country';
566 }
567 $ufFieldDAO = new CRM_Core_DAO_UFField();
568 $ufFieldDAO->field_name = $field;
569 $ufFieldDAO->location_type_id = $ufField->location_type_id;
570 $ufFieldDAO->uf_group_id = $ufField->uf_group_id;
571
572 if ($ufFieldDAO->find(TRUE)) {
573 if ($field == 'country' && $ufFieldDAO->weight > $ufField->weight) {
574 $showBestResult = TRUE;
575 }
576 elseif ($field == 'state_province' && $ufFieldDAO->weight < $ufField->weight) {
577 $showBestResult = TRUE;
578 }
579 }
580 }
581
582 //update group_type every time. CRM-3608
583 if ($this->_gid && is_a($ufField, 'CRM_Core_DAO_UFField')) {
584 // get the profile type.
585 $fieldsType = CRM_Core_BAO_UFGroup::calculateGroupType($this->_gid, TRUE);
586 CRM_Core_BAO_UFGroup::updateGroupTypes($this->_gid, $fieldsType);
587 }
588 CRM_Core_Session::setStatus(ts('Your CiviCRM Profile Field \'%1\' has been saved to \'%2\'.',
589 array(1 => $name, 2 => $this->_title)
590 ), ts('Profile Field Saved'), 'success');
591 }
592 $buttonName = $this->controller->getButtonName();
593
594 $session = CRM_Core_Session::singleton();
595 if ($buttonName == $this->getButtonName('next', 'new')) {
596 $session->replaceUserContext(CRM_Utils_System::url('civicrm/admin/uf/group/field/add',
597 "reset=1&action=add&gid={$this->_gid}&sbr={$showBestResult}"
598 ));
599 }
600 else {
601 $session->replaceUserContext(CRM_Utils_System::url('civicrm/admin/uf/group/field',
602 "reset=1&action=browse&gid={$this->_gid}"
603 ));
604 $session->set('showBestResult', $showBestResult);
605 }
606 }
607
608 /**
609 * Validation rule for subtype.
610 *
611 * @param string $fieldType
612 * Type of field.
613 * @param array $groupType
614 * Contains all groupTypes.
615 * @param array $errors
616 * List of errors to be posted back to the form.
617 */
618 public static function formRuleSubType($fieldType, $groupType, &$errors) {
619 if (in_array($fieldType, array(
620 'Participant',
621 'Contribution',
622 'Membership',
623 'Activity',
624 ))) {
625 $individualSubTypes = CRM_Contact_BAO_ContactType::subTypes('Individual');
626 foreach ($groupType as $value) {
627 if (!in_array($value, $individualSubTypes) &&
628 !in_array($value, array(
629 'Participant',
630 'Contribution',
631 'Membership',
632 'Individual',
633 'Contact',
634 'Activity',
635 'Formatting',
636 ))
637 ) {
638 $errors['field_name'] = ts('Cannot add or update profile field "%1" with combination of Household or Organization or any subtypes of Household or Organization.', array(1 => $fieldType));
639 break;
640 }
641 }
642 }
643 else {
644 $basicType = CRM_Contact_BAO_ContactType::getBasicType($groupType);
645 if ($basicType) {
646 if (!is_array($basicType)) {
647 $basicType = array($basicType);
648 }
649 if (!in_array($fieldType, $basicType) && $fieldType != 'Contact') {
650 $errors['field_name'] = ts('Cannot add or update profile field type "%1" with combination of subtype other than "%1".',
651 array(1 => $fieldType)
652 );
653 }
654 }
655 }
656 }
657
658 /**
659 * Validation rule for custom data extends entity column values.
660 *
661 * @param Object $customField
662 * Custom field.
663 * @param int $gid
664 * Group Id.
665 * @param string $fieldType
666 * Group type of the field.
667 * @param array $errors
668 * Collect errors.
669 *
670 * @return array
671 * list of errors to be posted back to the form
672 */
673 public static function formRuleCustomDataExtentColumnValue($customField, $gid, $fieldType, &$errors) {
674 // fix me : check object $customField
675 if (in_array($fieldType, array(
676 'Participant',
677 'Contribution',
678 'Membership',
679 'Activity',
680 'Case',
681 ))) {
682 $params = array('id' => $customField->custom_group_id);
683 $customGroup = array();
684 CRM_Core_BAO_CustomGroup::retrieve($params, $customGroup);
685 if (($fieldType != CRM_Utils_Array::value('extends', $customGroup)) || empty($customGroup['extends_entity_column_value'])) {
686 return $errors;
687 }
688
689 $extendsColumnValues = array();
690 foreach (explode(CRM_Core_DAO::VALUE_SEPARATOR, $customGroup['extends_entity_column_value']) as $val) {
691 if ($val) {
692 $extendsColumnValues[] = $val;
693 }
694 }
695
696 if (empty($extendsColumnValues)) {
697 return $errors;
698 }
699
700 $fieldTypeValues = CRM_Core_BAO_UFGroup::groupTypeValues($gid, $fieldType);
701 if (empty($fieldTypeValues[$fieldType])) {
702 return;
703 }
704
705 $disallowedTypes = array_diff($extendsColumnValues, $fieldTypeValues[$fieldType]);
706 if (!empty($disallowedTypes)) {
707 $errors['field_name'] = ts('Profile is already having custom fields extending different group types, you can not add or update this custom field.');
708 }
709 }
710 }
711
712 /**
713 * Validation rule to prevent multiple fields of primary location type within the same communication type.
714 *
715 * @param array $fields
716 * Submitted fields.
717 * @param string $profileFieldName
718 * Group Id.
719 * @param array $groupFields
720 * List of fields already in the group.
721 * @param array $errors
722 * Collect errors.
723 *
724 */
725 public static function formRulePrimaryCheck($fields, $profileFieldName, $groupFields, &$errors) {
726 //FIXME: This may need to also apply to website fields if they are refactored to allow more than one per profile
727 $checkPrimary = array('phone' => 'civicrm_phone.phone', 'phone_and_ext' => 'civicrm_phone.phone');
728 $whereCheck = NULL;
729 $primaryOfSameTypeFound = NULL;
730 $fieldID = empty($fields['field_id']) ? 0 : $fields['field_id'];
731 // Is this a primary location type field of interest
732 if (array_key_exists($profileFieldName, $checkPrimary)) {
733 $whereCheck = $checkPrimary[$profileFieldName];
734 }
735 $potentialLocationType = CRM_Utils_Array::value(2, $fields['field_name']);
736
737 if ($whereCheck && $potentialLocationType == 0) {
738 $primaryOfSameTypeFound = '';
739
740 foreach ($groupFields as $groupField) {
741 // if it is a phone
742 if ($groupField['where'] == $whereCheck && is_null($groupField['location_type_id']) && $groupField['field_id'] != $fieldID) {
743 $primaryOfSameTypeFound = $groupField['title'];
744 break;
745 }
746 }
747 if ($primaryOfSameTypeFound) {
748 $errors['field_name'] = ts('You have already added a primary location field of this type: %1', array(1 => $primaryOfSameTypeFound));
749 }
750 }
751 }
752
753 /**
754 * Global validation rules for the form.
755 *
756 * @param array $fields
757 * Posted values of the form.
758 *
759 * @param $files
760 * @param $self
761 *
762 * @return array
763 * list of errors to be posted back to the form
764 */
765 public static function formRule($fields, $files, $self) {
766 $is_required = CRM_Utils_Array::value('is_required', $fields, FALSE);
767 $is_registration = CRM_Utils_Array::value('is_registration', $fields, FALSE);
768 $is_view = CRM_Utils_Array::value('is_view', $fields, FALSE);
769 $in_selector = CRM_Utils_Array::value('in_selector', $fields, FALSE);
770 $is_active = CRM_Utils_Array::value('is_active', $fields, FALSE);
771
772 $errors = array();
773 if ($is_view && $is_registration) {
774 $errors['is_registration'] = ts('View Only cannot be selected if this field is to be included on the registration form');
775 }
776 if ($is_view && $is_required) {
777 $errors['is_view'] = ts('A View Only field cannot be required');
778 }
779
780 $entityName = $fields['field_name'][0];
781 if (!$entityName) {
782 $errors['field_name'] = ts('Please select a field name');
783 }
784
785 if ($in_selector && in_array($entityName, array(
786 'Contribution',
787 'Participant',
788 'Membership',
789 'Activity',
790 ))
791 ) {
792 $errors['in_selector'] = ts("'In Selector' cannot be checked for %1 fields.", array(1 => $entityName));
793 }
794
795 $isCustomField = FALSE;
796 $profileFieldName = CRM_Utils_Array::value(1, $fields['field_name']);
797 if ($profileFieldName) {
798 //get custom field id
799 $customFieldId = explode('_', $profileFieldName);
800 if ($customFieldId[0] == 'custom') {
801 $customField = new CRM_Core_DAO_CustomField();
802 $customField->id = $customFieldId[1];
803 $customField->find(TRUE);
804 $isCustomField = TRUE;
805 if (!empty($fields['field_id']) && !$customField->is_active && $is_active) {
806 $errors['field_name'] = ts('Cannot set this field "Active" since the selected custom field is disabled.');
807 }
808
809 //check if profile already has a different multi-record custom set field configured
810 $customGroupId = CRM_Core_BAO_CustomField::isMultiRecordField($profileFieldName);
811 if ($customGroupId) {
812 if ($profileMultiRecordCustomGid = CRM_Core_BAO_UFField::checkMultiRecordFieldExists($self->_gid)) {
813 if ($customGroupId != $profileMultiRecordCustomGid) {
814 $errors['field_name'] = ts("You cannot configure multi-record custom fields belonging to different custom sets in one profile");
815 }
816 }
817 }
818 }
819 }
820
821 // Get list of fields already in the group
822 $groupFields = CRM_Core_BAO_UFGroup::getFields($fields['group_id'], FALSE, NULL, NULL, NULL, TRUE, NULL, TRUE);
823 // Check if we already added a primary field of the same communication type
824 self::formRulePrimaryCheck($fields, $profileFieldName, $groupFields, $errors);
825
826 //check profile is configured for double option process
827 //adding group field, email field should be present in the group
828 //fixed for issue CRM-2861 & CRM-4153
829 if (CRM_Core_BAO_UFGroup::isProfileDoubleOptin()) {
830 if (CRM_Utils_Array::value(1, $fields['field_name']) == 'group') {
831 $dao = new CRM_Core_BAO_UFField();
832 $dao->uf_group_id = $fields['group_id'];
833 $dao->find();
834 $emailField = FALSE;
835 while ($dao->fetch()) {
836 //check email field is present in the group
837 if ($dao->field_name == 'email') {
838 $emailField = TRUE;
839 break;
840 }
841 }
842
843 if (!$emailField) {
844 $disableSettingURL = CRM_Utils_System::url(
845 'civicrm/admin/setting/preferences/mailing',
846 'reset=1'
847 );
848
849 $errors['field_name'] = ts('Your site is currently configured to require double-opt in when users join (subscribe) to Group(s) via a Profile form. In this mode, you need to include an Email field in a Profile BEFORE you can add the Group(s) field. This ensures that an opt-in confirmation email can be sent. Your site administrator can disable double opt-in on the civimail admin settings: <em>%1</em>', array(1 => $disableSettingURL));
850 }
851 }
852 }
853
854 //fix for CRM-3037
855 $fieldType = $fields['field_name'][0];
856
857 //get the group type.
858 $groupType = CRM_Core_BAO_UFGroup::calculateGroupType($self->_gid, FALSE, CRM_Utils_Array::value('field_id', $fields));
859
860 switch ($fieldType) {
861 case 'Contact':
862 self::formRuleSubType($fieldType, $groupType, $errors);
863 break;
864
865 case 'Individual':
866 if (in_array('Activity', $groupType) ||
867 in_array('Household', $groupType) ||
868 in_array('Organization', $groupType)
869 ) {
870
871 //CRM-7603 - need to support activity + individual.
872 //$errors['field_name'] =
873 //ts( 'Cannot add or update profile field type Individual with combination of Household or Organization or Activity' );
874 if (in_array('Household', $groupType) ||
875 in_array('Organization', $groupType)
876 ) {
877 $errors['field_name'] = ts('Cannot add or update profile field type Individual with combination of Household or Organization');
878 }
879 }
880 else {
881 self::formRuleSubType($fieldType, $groupType, $errors);
882 }
883 break;
884
885 case 'Household':
886 if (in_array('Activity', $groupType) || in_array('Individual', $groupType) || in_array('Organization', $groupType)) {
887 $errors['field_name'] = ts('Cannot add or update profile field type Household with combination of Individual or Organization or Activity');
888 }
889 else {
890 self::formRuleSubType($fieldType, $groupType, $errors);
891 }
892 break;
893
894 case 'Organization':
895 if (in_array('Activity', $groupType) || in_array('Household', $groupType) || in_array('Individual', $groupType)) {
896 $errors['field_name'] = ts('Cannot add or update profile field type Organization with combination of Household or Individual or Activity');
897 }
898 else {
899 self::formRuleSubType($fieldType, $groupType, $errors);
900 }
901 break;
902
903 case 'Activity':
904 if (in_array('Individual', $groupType) ||
905 in_array('Membership', $groupType) ||
906 in_array('Contribution', $groupType) ||
907 in_array('Organization', $groupType) ||
908 in_array('Household', $groupType) ||
909 in_array('Participant', $groupType)
910 ) {
911
912 //CRM-7603 - need to support activity + contact type.
913 //$errors['field_name'] =
914 //ts( 'Cannot add or update profile field type Activity with combination Participant or Membership or Contribution or Household or Organization or Individual' );
915 if (in_array('Membership', $groupType) ||
916 in_array('Contribution', $groupType) ||
917 in_array('Participant', $groupType)
918 ) {
919 $errors['field_name'] = ts('Cannot add or update profile field type Activity with combination Participant or Membership or Contribution');
920 }
921 }
922 else {
923 self::formRuleSubType($fieldType, $groupType, $errors);
924 }
925
926 if ($isCustomField && !isset($errors['field_name'])) {
927 self::formRuleCustomDataExtentColumnValue($customField, $self->_gid, $fieldType, $errors);
928 }
929 break;
930
931 case 'Participant':
932 if (in_array('Membership', $groupType) || in_array('Contribution', $groupType)
933 || in_array('Organization', $groupType) || in_array('Household', $groupType) || in_array('Activity', $groupType)
934 ) {
935 $errors['field_name'] = ts('Cannot add or update profile field type Participant with combination of Activity or Membership or Contribution or Household or Organization.');
936 }
937 else {
938 self::formRuleSubType($fieldType, $groupType, $errors);
939 }
940 break;
941
942 case 'Contribution':
943 //special case where in we allow contribution + oganization fields, for on behalf feature
944 $profileId = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_UFGroup',
945 'on_behalf_organization', 'id', 'name'
946 );
947
948 if (in_array('Participant', $groupType) || in_array('Membership', $groupType)
949 || ($profileId != $self->_gid && in_array('Organization', $groupType)) || in_array('Household', $groupType) || in_array('Activity', $groupType)
950 ) {
951 $errors['field_name'] = ts('Cannot add or update profile field type Contribution with combination of Activity or Membership or Participant or Household or Organization');
952 }
953 else {
954 self::formRuleSubType($fieldType, $groupType, $errors);
955 }
956 break;
957
958 case 'Membership':
959 //special case where in we allow contribution + oganization fields, for on behalf feature
960 $profileId = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_UFGroup',
961 'on_behalf_organization', 'id', 'name'
962 );
963
964 if (in_array('Participant', $groupType) || in_array('Contribution', $groupType)
965 || ($profileId != $self->_gid && in_array('Organization', $groupType)) || in_array('Household', $groupType) || in_array('Activity', $groupType)
966 ) {
967 $errors['field_name'] = ts('Cannot add or update profile field type Membership with combination of Activity or Participant or Contribution or Household or Organization');
968 }
969 else {
970 self::formRuleSubType($fieldType, $groupType, $errors);
971 }
972 break;
973
974 default:
975 $profileType = CRM_Core_BAO_UFField::getProfileType($fields['group_id'], TRUE, FALSE, TRUE);
976 if (CRM_Contact_BAO_ContactType::isaSubType($fieldType)) {
977 if (CRM_Contact_BAO_ContactType::isaSubType($profileType)) {
978 if ($fieldType != $profileType) {
979 $errors['field_name'] = ts('Cannot add or update profile field type "%1" with combination of "%2".', array(
980 1 => $fieldType,
981 2 => $profileType,
982 ));
983 }
984 }
985 else {
986 $basicType = CRM_Contact_BAO_ContactType::getBasicType($fieldType);
987 if ($profileType &&
988 $profileType != $basicType &&
989 $profileType != 'Contact'
990 ) {
991 $errors['field_name'] = ts('Cannot add or update profile field type "%1" with combination of "%2".', array(
992 1 => $fieldType,
993 2 => $profileType,
994 ));
995 }
996 }
997 }
998 elseif (
999 CRM_Utils_Array::value(1, $fields['field_name']) == 'contact_sub_type' &&
1000 !in_array($profileType, array('Individual', 'Household', 'Organization')) &&
1001 !in_array($profileType, CRM_Contact_BAO_ContactType::subTypes())
1002 ) {
1003 $errors['field_name'] = ts('Cannot add or update profile field Contact Subtype as profile type is not one of Individual, Household or Organization.');
1004 }
1005 }
1006 return empty($errors) ? TRUE : $errors;
1007 }
1008
1009 }