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