Merge pull request #4628 from priyankakaran26/recurring-entity-improvements-phase-2
[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 * 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
110 $this->setPageTitle(ts('Profile Field'));
111
112 $url = CRM_Utils_System::url('civicrm/admin/uf/group/field',
113 "reset=1&action=browse&gid={$this->_gid}"
114 );
115
116 $session = CRM_Core_Session::singleton();
117 $session->pushUserContext($url);
118 $breadCrumb = array(array('title' => ts('CiviCRM Profile Fields'),
119 'url' => $url,
120 ));
121 CRM_Utils_System::appendBreadCrumb($breadCrumb);
122 }
123
124 $showBestResult = CRM_Utils_Request::retrieve('sbr', 'Positive', CRM_Core_DAO::$_nullArray);
125 if ($showBestResult) {
126 $this->assign('showBestResult', $showBestResult);
127 }
128
129 $this->_fields = CRM_Contact_BAO_Contact::importableFields('All', TRUE, TRUE, TRUE, TRUE, TRUE);
130 $this->_fields = array_merge(CRM_Activity_BAO_Activity::exportableFields('Activity'), $this->_fields);
131
132 //unset campaign related fields.
133 if (isset($this->_fields['activity_campaign_id'])) {
134 $this->_fields['activity_campaign_id']['title'] = ts('Campaign');
135 if (isset($this->_fields['activity_campaign'])) {
136 unset($this->_fields['activity_campaign']);
137 }
138 }
139
140 if (CRM_Core_Permission::access('CiviContribute')) {
141 $this->_fields = array_merge(CRM_Contribute_BAO_Contribution::getContributionFields(FALSE), $this->_fields);
142 $this->_fields = array_merge(CRM_Core_BAO_UFField::getContribBatchEntryFields(), $this->_fields);
143 }
144
145 if (CRM_Core_Permission::access('CiviMember')) {
146 $this->_fields = array_merge(CRM_Member_BAO_Membership::getMembershipFields(), $this->_fields);
147 }
148
149 if (CRM_Core_Permission::access('CiviEvent')) {
150 $this->_fields = array_merge(CRM_Event_BAO_Query::getParticipantFields(), $this->_fields);
151 }
152
153 if (CRM_Core_Permission::access('CiviCase')) {
154 $this->_fields = array_merge(CRM_Case_BAO_Query::getFields(), $this->_fields);
155 }
156
157 $this->_fields = array_merge($this->_fields, CRM_Contact_BAO_Query_Hook::singleton()->getFields());
158
159 $this->_selectFields = array();
160 foreach ($this->_fields as $name => $field) {
161 // lets skip note for now since we dont support it
162 if ($name == 'note') {
163 continue;
164 }
165 $this->_selectFields[$name] = $field['title'];
166 $this->_hasLocationTypes[$name] = CRM_Utils_Array::value('hasLocationType', $field);
167 }
168
169 // lets add group, tag and current_employer to this list
170 $this->_selectFields['group'] = ts('Group(s)');
171 $this->_selectFields['tag'] = ts('Tag(s)');
172 $this->_selectFields['current_employer'] = ts('Current Employer');
173 $this->_selectFields['phone_and_ext'] = ts('Phone and Extension');
174
175 //CRM-4363 check for in selector or searchable fields.
176 $this->_hasSearchableORInSelector = CRM_Core_BAO_UFField::checkSearchableORInSelector($this->_gid);
177
178 $this->assign('fieldId', $this->_id);
179 if ($this->_id) {
180 $fieldTitle = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_UFField', $this->_id, 'label');
181 $this->assign('fieldTitle', $fieldTitle);
182 }
183 }
184
185 /**
186 * Build the form object
187 *
188 * @return void
189 * @access public
190 */
191 public function buildQuickForm() {
192 if ($this->_action & CRM_Core_Action::DELETE) {
193 $this->addButtons(array(
194 array(
195 'type' => 'next',
196 'name' => ts('Delete Profile Field'),
197 'spacing' => '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;',
198 'isDefault' => TRUE,
199 ),
200 array(
201 'type' => 'cancel',
202 'name' => ts('Cancel'),
203 ),
204 )
205 );
206 return;
207 }
208
209 if (isset($this->_id)) {
210 $params = array('id' => $this->_id);
211 CRM_Core_BAO_UFField::retrieve($params, $defaults);
212
213 // set it to null if so (avoids crappy E_NOTICE errors below
214 $defaults['location_type_id'] = CRM_Utils_Array::value('location_type_id', $defaults);
215
216 $specialFields = CRM_Core_BAO_UFGroup::getLocationFields();
217
218 if (!$defaults['location_type_id'] &&
219 $defaults["field_type"] != "Formatting" &&
220 in_array($defaults['field_name'], $specialFields)
221 ) {
222 $defaults['location_type_id'] = 0;
223 }
224
225 $defaults['field_name'] = array(
226 $defaults['field_type'],
227 ($defaults['field_type'] == "Formatting" ? "" : $defaults['field_name']),
228 ($defaults['field_name'] == "url") ? $defaults['website_type_id'] : $defaults['location_type_id'],
229 CRM_Utils_Array::value('phone_type_id', $defaults),
230 );
231 $this->_gid = $defaults['uf_group_id'];
232 }
233 else {
234 $defaults['is_active'] = 1;
235 }
236
237 $otherModules = array_values(CRM_Core_BAO_UFGroup::getUFJoinRecord($this->_gid));
238 $this->assign('otherModules', $otherModules);
239
240 if ($this->_action & CRM_Core_Action::ADD) {
241 $fieldValues = array('uf_group_id' => $this->_gid);
242 $defaults['weight'] = CRM_Utils_Weight::getDefaultWeight('CRM_Core_DAO_UFField', $fieldValues);
243 }
244
245 // lets trim all the whitespace
246 $this->applyFilter('__ALL__', 'trim');
247
248 //hidden field to catch the group id in profile
249 $this->add('hidden', 'group_id', $this->_gid);
250
251 //hidden field to catch the field id in profile
252 $this->add('hidden', 'field_id', $this->_id);
253
254 $fields = CRM_Core_BAO_UFField::getAvailableFields($this->_gid, $defaults);
255
256 $noSearchable = $hasWebsiteTypes = array();
257 $addressCustomFields = array_keys(CRM_Core_BAO_CustomField::getFieldsForImport('Address'));
258
259 foreach ($fields as $key => $value) {
260 foreach ($value as $key1 => $value1) {
261 //CRM-2676, replacing the conflict for same custom field name from different custom group.
262 if ($customFieldId = CRM_Core_BAO_CustomField::getKeyID($key1)) {
263 $customGroupId = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomField', $customFieldId, 'custom_group_id');
264 $customGroupName = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomGroup', $customGroupId, 'title');
265 $this->_mapperFields[$key][$key1] = $value1['title'] . ' :: ' . $customGroupName;
266 if (in_array($key1, $addressCustomFields)) {
267 $noSearchable[] = $value1['title'] . ' :: ' . $customGroupName;
268 }
269 }
270 else {
271 $this->_mapperFields[$key][$key1] = $value1['title'];
272 }
273 $hasLocationTypes[$key][$key1] = CRM_Utils_Array::value('hasLocationType', $value1);
274 $hasWebsiteTypes[$key][$key1] = CRM_Utils_Array::value('hasWebsiteType', $value1);
275 // hide the 'is searchable' field for 'File' custom data
276 if (isset($value1['data_type']) &&
277 isset($value1['html_type']) &&
278 (($value1['data_type'] == 'File' && $value1['html_type'] == 'File')
279 || ($value1['data_type'] == 'Link' && $value1['html_type'] == 'Link')
280 )
281 ) {
282 if (!in_array($value1['title'], $noSearchable)) {
283 $noSearchable[] = $value1['title'];
284 }
285 }
286 }
287 }
288 $this->assign('noSearchable', $noSearchable);
289
290 $this->_location_types = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id');
291 $defaultLocationType = CRM_Core_BAO_LocationType::getDefault();
292 $this->_website_types = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Website', 'website_type_id');
293
294 /**
295 * FIXME: dirty hack to make the default option show up first. This
296 * avoids a mozilla browser bug with defaults on dynamically constructed
297 * selector widgets.
298 */
299 if ($defaultLocationType) {
300 $defaultLocation = $this->_location_types[$defaultLocationType->id];
301 unset($this->_location_types[$defaultLocationType->id]);
302 $this->_location_types = array(
303 $defaultLocationType->id => $defaultLocation) + $this->_location_types;
304 }
305
306 $this->_location_types = array('Primary') + $this->_location_types;
307
308 // since we need a hierarchical list to display contact types & subtypes,
309 // this is what we going to display in first selector
310 $contactTypes = CRM_Contact_BAO_ContactType::getSelectElements(FALSE, FALSE);
311 unset($contactTypes['']);
312
313 $contactTypes = !empty($contactTypes) ? array('Contact' => 'Contacts') + $contactTypes : array();
314 $sel1 = array('' => '- select -') + $contactTypes;
315
316 if (!empty($fields['Activity'])) {
317 $sel1['Activity'] = 'Activity';
318 }
319
320 if (CRM_Core_Permission::access('CiviEvent')) {
321 $sel1['Participant'] = 'Participants';
322 }
323
324 if (!empty($fields['Contribution'])) {
325 $sel1['Contribution'] = 'Contributions';
326 }
327
328 if (!empty($fields['Membership'])) {
329 $sel1['Membership'] = 'Membership';
330 }
331
332 if (!empty($fields['Case'])) {
333 $sel1['Case'] = 'Case';
334 }
335
336 if (!empty($fields['Formatting'])) {
337 $sel1['Formatting'] = 'Formatting';
338 }
339
340 foreach ($sel1 as $key => $sel) {
341 if ($key) {
342 $sel2[$key] = $this->_mapperFields[$key];
343 }
344 }
345 $sel3[''] = NULL;
346 $phoneTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Phone', 'phone_type_id');
347 ksort($phoneTypes);
348
349 foreach ($sel1 as $k => $sel) {
350 if ($k) {
351 foreach ($this->_location_types as $key => $value) {
352 $sel4[$k]['phone'][$key] = &$phoneTypes;
353 $sel4[$k]['phone_and_ext'][$key] = &$phoneTypes;
354 }
355 }
356 }
357
358 foreach ($sel1 as $k => $sel) {
359 if ($k) {
360 if (is_array($this->_mapperFields[$k])) {
361 foreach ($this->_mapperFields[$k] as $key => $value) {
362 if ($hasLocationTypes[$k][$key]) {
363 $sel3[$k][$key] = $this->_location_types;
364 }
365 elseif ($hasWebsiteTypes[$k][$key]) {
366 $sel3[$k][$key] = $this->_website_types;
367 }
368 else {
369 $sel3[$key] = NULL;
370 }
371 }
372 }
373 }
374 }
375
376 $this->_defaults = array();
377 $js = "<script type='text/javascript'>\n";
378 $formName = "document.{$this->_name}";
379
380 $alreadyMixProfile = FALSE;
381 if (CRM_Core_BAO_UFField::checkProfileType($this->_gid)) {
382 $alreadyMixProfile = TRUE;
383 }
384 $this->assign('alreadyMixProfile', $alreadyMixProfile);
385
386 $sel = &$this->addElement('hierselect', 'field_name', ts('Field Name'));
387
388 $formValues = $this->exportValues();
389
390 if (empty($formValues)) {
391 for ($k = 1; $k < 4; $k++) {
392 if (!isset($defaults['field_name'][$k])) {
393 $js .= "{$formName}['field_name[$k]'].style.display = 'none';\n";
394 }
395 }
396 }
397 else {
398 if (!empty($formValues['field_name'])) {
399 for ($key = 1; $key < 4; $key++) {
400 if (!isset($formValues['field_name'][$key])) {
401 $js .= "{$formName}['field_name[$key]'].style.display = 'none';\n";
402 }
403 else {
404 $js .= "{$formName}['field_name[$key]'].style.display = '';\n";
405 }
406 }
407 }
408 else {
409 for ($k = 1; $k < 4; $k++) {
410 if (!isset($defaults['field_name'][$k])) {
411 $js .= "{$formName}['field_name[$k]'].style.display = 'none';\n";
412 }
413 }
414 }
415 }
416
417 foreach ($sel2 as $k => $v) {
418 if (is_array($sel2[$k])) {
419 asort($sel2[$k]);
420 }
421 }
422
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 }