Merge pull request #4863 from totten/master-phpcbf4
[civicrm-core.git] / CRM / Core / BAO / UFField.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
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 * This class contains function for UFField
38 *
39 */
40 class CRM_Core_BAO_UFField extends CRM_Core_DAO_UFField {
41
42 /**
43 * Batch entry fields
44 */
45 private static $_contriBatchEntryFields = NULL;
46 private static $_memberBatchEntryFields = NULL;
47
48
49 /**
50 * Fetch object based on array of properties
51 *
52 * @param array $params
53 * (reference ) an assoc array of name/value pairs.
54 * @param array $defaults
55 * (reference ) an assoc array to hold the flattened values.
56 *
57 * @return CRM_Core_BAO_UFField object
58 * @static
59 */
60 public static function retrieve(&$params, &$defaults) {
61 return CRM_Core_DAO::commonRetrieve('CRM_Core_DAO_UFField', $params, $defaults);
62 }
63
64 /**
65 * Get the form title.
66 *
67 * @param int $id
68 * Id of uf_form.
69 *
70 * @return string title
71 *
72 * @static
73 *
74 */
75 public static function getTitle($id) {
76 return CRM_Core_DAO::getFieldValue('CRM_Core_DAO_UFField', $groupId, 'title');
77 }
78
79 /**
80 * Update the is_active flag in the db
81 *
82 * @param int $id
83 * Id of the database record.
84 * @param bool $is_active
85 * Value we want to set the is_active field.
86 *
87 * @return Object DAO object on sucess, null otherwise
88 * @static
89 */
90 public static function setIsActive($id, $is_active) {
91 //check if custom data profile field is disabled
92 if ($is_active) {
93 if (CRM_Core_BAO_UFField::checkUFStatus($id)) {
94 return CRM_Core_DAO::setFieldValue('CRM_Core_DAO_UFField', $id, 'is_active', $is_active);
95 }
96 else {
97 CRM_Core_Session::setStatus(ts('Cannot enable this UF field since the used custom field is disabled.'), ts('Check Custom Field'), 'error');
98 }
99 }
100 else {
101 return CRM_Core_DAO::setFieldValue('CRM_Core_DAO_UFField', $id, 'is_active', $is_active);
102 }
103 }
104
105 /**
106 * Delete the profile Field.
107 *
108 * @param int $id
109 * Field Id.
110 *
111 * @return boolean
112 *
113 * @static
114 *
115 */
116 public static function del($id) {
117 //delete field field
118 $field = new CRM_Core_DAO_UFField();
119 $field->id = $id;
120 $field->delete();
121 return TRUE;
122 }
123
124 /**
125 * Check duplicate for duplicate field in a group
126 *
127 * @param array $params
128 * An associative array with field and values.
129 * @param $ids
130 *
131 * @return mixed
132 * @ids array $ids array that containd ids
133 *
134 * @static
135 */
136 public static function duplicateField($params, $ids) {
137 $ufField = new CRM_Core_DAO_UFField();
138 $ufField->uf_group_id = CRM_Utils_Array::value('uf_group', $ids);
139 $ufField->field_type = $params['field_name'][0];
140 $ufField->field_name = $params['field_name'][1];
141 if ($params['field_name'][1] == 'url') {
142 $ufField->website_type_id = CRM_Utils_Array::value(2, $params['field_name'], NULL);
143 }
144 else {
145 $ufField->location_type_id = (CRM_Utils_Array::value(2, $params['field_name'])) ? $params['field_name'][2] : 'NULL';
146 }
147 $ufField->phone_type_id = CRM_Utils_Array::value(3, $params['field_name']);
148
149 if (!empty($ids['uf_field'])) {
150 $ufField->whereAdd("id <> " . CRM_Utils_Array::value('uf_field', $ids));
151 }
152
153 return $ufField->find(TRUE);
154 }
155
156 /**
157 * Does profile consists of a multi-record custom field
158 */
159 public static function checkMultiRecordFieldExists($gId) {
160 $queryString = "SELECT f.field_name
161 FROM civicrm_uf_field f, civicrm_uf_group g
162 WHERE f.uf_group_id = g.id
163 AND g.id = %1 AND f.field_name LIKE 'custom%'";
164 $p = array(1 => array($gId, 'Integer'));
165 $dao = CRM_Core_DAO::executeQuery($queryString, $p);
166 $customFieldIds = array();
167 $isMultiRecordFieldPresent = FALSE;
168 while ($dao->fetch()) {
169 if ($customId = CRM_Core_BAO_CustomField::getKeyID($dao->field_name)) {
170 if (is_numeric($customId)) {
171 $customFieldIds[] = $customId;
172 }
173 }
174 }
175
176 if (!empty($customFieldIds) && count($customFieldIds) == 1) {
177 $customFieldId = array_pop($customFieldIds);
178 $isMultiRecordFieldPresent = CRM_Core_BAO_CustomField::isMultiRecordField($customFieldId);
179 }
180 elseif (count($customFieldIds) > 1) {
181 $customFieldIds = implode(", ", $customFieldIds);
182 $queryString = "
183 SELECT cg.id as cgId
184 FROM civicrm_custom_group cg
185 INNER JOIN civicrm_custom_field cf
186 ON cg.id = cf.custom_group_id
187 WHERE cf.id IN (" . $customFieldIds . ") AND is_multiple = 1 LIMIT 0,1";
188
189 $dao = CRM_Core_DAO::executeQuery($queryString);
190 if ($dao->fetch()) {
191 $isMultiRecordFieldPresent = ($dao->cgId) ? $dao->cgId : FALSE;
192 }
193 }
194
195 return $isMultiRecordFieldPresent;
196 }
197
198 /**
199 * Add the UF Field
200 *
201 * @param array $params
202 * (reference) array containing the values submitted by the form.
203 * @param array $ids
204 * Array containing the id.
205 *
206 * @return CRM_Core_BAO_UFField object
207 *
208 * @static
209 *
210 */
211 public static function add(&$params, $ids = array()) {
212 // set values for uf field properties and save
213 $ufField = new CRM_Core_DAO_UFField();
214 $ufField->field_type = $params['field_name'][0];
215 $ufField->field_name = $params['field_name'][1];
216
217 //should not set location type id for Primary
218 $locationTypeId = NULL;
219 if ($params['field_name'][1] == 'url') {
220 $ufField->website_type_id = CRM_Utils_Array::value(2, $params['field_name']);
221 }
222 else {
223 $locationTypeId = CRM_Utils_Array::value(2, $params['field_name']);
224 $ufField->website_type_id = NULL;
225 }
226 if ($locationTypeId) {
227 $ufField->location_type_id = $locationTypeId;
228 }
229 else {
230 $ufField->location_type_id = 'null';
231 }
232
233 $ufField->phone_type_id = CRM_Utils_Array::value(3, $params['field_name'], 'NULL');
234 $ufField->listings_title = CRM_Utils_Array::value('listings_title', $params);
235 $ufField->visibility = CRM_Utils_Array::value('visibility', $params);
236 $ufField->help_pre = CRM_Utils_Array::value('help_pre', $params);
237 $ufField->help_post = CRM_Utils_Array::value('help_post', $params);
238 $ufField->label = CRM_Utils_Array::value('label', $params);
239 $ufField->is_required = CRM_Utils_Array::value('is_required', $params, FALSE);
240 $ufField->is_active = CRM_Utils_Array::value('is_active', $params, FALSE);
241 $ufField->in_selector = CRM_Utils_Array::value('in_selector', $params, FALSE);
242 $ufField->is_view = CRM_Utils_Array::value('is_view', $params, FALSE);
243 $ufField->is_registration = CRM_Utils_Array::value('is_registration', $params, FALSE);
244 $ufField->is_match = CRM_Utils_Array::value('is_match', $params, FALSE);
245 $ufField->is_searchable = CRM_Utils_Array::value('is_searchable', $params, FALSE);
246 $ufField->is_multi_summary = CRM_Utils_Array::value('is_multi_summary', $params, FALSE);
247 $ufField->weight = CRM_Utils_Array::value('weight', $params, 0);
248
249 // need the FKEY - uf group id
250 $ufField->uf_group_id = CRM_Utils_Array::value('uf_group', $ids, FALSE);
251 $ufField->id = CRM_Utils_Array::value('uf_field', $ids, FALSE);
252
253 return $ufField->save();
254 }
255
256 /**
257 * Automatically determine one weight and modify others
258 *
259 * @param array $params
260 * UFField record, e.g. with 'weight', 'uf_group_id', and 'field_id'.
261 * @return int
262 */
263 public static function autoWeight($params) {
264 // fix for CRM-316
265 $oldWeight = NULL;
266
267 if (!empty($params['field_id'])) {
268 $oldWeight = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_UFField', $params['field_id'], 'weight', 'id');
269 }
270 $fieldValues = array('uf_group_id' => $params['group_id']);
271 return CRM_Utils_Weight::updateOtherWeights('CRM_Core_DAO_UFField', $oldWeight, CRM_Utils_Array::value('weight', $params, 0), $fieldValues);
272 }
273
274 /**
275 * Enable/disable profile field given a custom field id
276 *
277 * @param int $customFieldId
278 * Custom field id.
279 * @param bool $is_active
280 * Set the is_active field.
281 *
282 * @return void
283 * @static
284 */
285 public static function setUFField($customFieldId, $is_active) {
286 //find the profile id given custom field
287 $ufField = new CRM_Core_DAO_UFField();
288 $ufField->field_name = "custom_" . $customFieldId;
289
290 $ufField->find();
291 while ($ufField->fetch()) {
292 //enable/ disable profile
293 CRM_Core_BAO_UFField::setIsActive($ufField->id, $is_active);
294 }
295 }
296
297 /**
298 * Copy existing profile fields to
299 * new profile from the already built profile
300 *
301 * @param int $old_id
302 * From which we need to copy.
303 * @param bool $new_id
304 * In which to copy.
305 *
306 * @return void
307 * @static
308 */
309 public static function copy($old_id, $new_id) {
310 $ufField = new CRM_Core_DAO_UFField();
311 $ufField->uf_group_id = $old_id;
312 $ufField->find();
313 while ($ufField->fetch()) {
314 //copy the field records as it is on new ufgroup id
315 $ufField->uf_group_id = $new_id;
316 $ufField->id = NULL;
317 $ufField->save();
318 }
319 }
320
321 /**
322 * Delete profile field given a custom field
323 *
324 * @param int $customFieldId
325 * ID of the custom field to be deleted.
326 *
327 * @return void
328 *
329 * @static
330 */
331 public static function delUFField($customFieldId) {
332 //find the profile id given custom field id
333 $ufField = new CRM_Core_DAO_UFField();
334 $ufField->field_name = "custom_" . $customFieldId;
335
336 $ufField->find();
337 while ($ufField->fetch()) {
338 //enable/ disable profile
339 CRM_Core_BAO_UFField::del($ufField->id);
340 }
341 }
342
343 /**
344 * Enable/disable profile field given a custom group id
345 *
346 * @param int $customGroupId
347 * Custom group id.
348 * @param bool $is_active
349 * Value we want to set the is_active field.
350 *
351 * @return void
352 * @static
353 */
354 public static function setUFFieldStatus($customGroupId, $is_active) {
355 //find the profile id given custom group id
356 $queryString = "SELECT civicrm_custom_field.id as custom_field_id
357 FROM civicrm_custom_field, civicrm_custom_group
358 WHERE civicrm_custom_field.custom_group_id = civicrm_custom_group.id
359 AND civicrm_custom_group.id = %1";
360 $p = array(1 => array($customGroupId, 'Integer'));
361 $dao = CRM_Core_DAO::executeQuery($queryString, $p);
362
363 while ($dao->fetch()) {
364 //enable/ disable profile
365 CRM_Core_BAO_UFField::setUFField($dao->custom_field_id, $is_active);
366 }
367 }
368
369 /**
370 * Check the status of custom field used in uf fields
371 *
372 * @param int $UFFieldId
373 *
374 * @return boolean false if custom field are disabled else true
375 * @static
376 */
377 public static function checkUFStatus($UFFieldId) {
378 $fieldName = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_UFField', $UFFieldId, 'field_name');
379 // return if field is not a custom field
380 if (!$customFieldId = CRM_Core_BAO_CustomField::getKeyID($fieldName)) {
381 return TRUE;
382 }
383
384 $customField = new CRM_Core_DAO_CustomField();
385 $customField->id = $customFieldId;
386 // if uf field is custom field
387 if ($customField->find(TRUE)) {
388 if (!$customField->is_active) {
389 return FALSE;
390 }
391 else {
392 return TRUE;
393 }
394 }
395 }
396
397 /**
398 * Find out whether given profile group using Activity
399 * Profile fields with contact fields
400 */
401 public static function checkContactActivityProfileType($ufGroupId) {
402 $ufGroup = new CRM_Core_DAO_UFGroup();
403 $ufGroup->id = $ufGroupId;
404 $ufGroup->find(TRUE);
405
406 return self::checkContactActivityProfileTypeByGroupType($ufGroup->group_type);
407 }
408
409 /**
410 * FIXME say 10 ha
411 * @param $ufGroupType
412 * @return bool
413 */
414 public static function checkContactActivityProfileTypeByGroupType($ufGroupType) {
415 $profileTypes = array();
416 if ($ufGroupType) {
417 $typeParts = explode(CRM_Core_DAO::VALUE_SEPARATOR, $ufGroupType);
418 $profileTypes = explode(',', $typeParts[0]);
419 }
420
421 if (empty($profileTypes)) {
422 return FALSE;
423 }
424 $components = array('Contribution', 'Participant', 'Membership');
425 if (!in_array('Activity', $profileTypes)) {
426 return FALSE;
427 }
428 elseif (count($profileTypes) == 1) {
429 return FALSE;
430 }
431
432 if ($index = array_search('Contact', $profileTypes)) {
433 unset($profileTypes[$index]);
434 if (count($profileTypes) == 1) {
435 return TRUE;
436 }
437 }
438
439 $contactTypes = array('Individual', 'Household', 'Organization');
440 $subTypes = CRM_Contact_BAO_ContactType::subTypes();
441
442 $profileTypeComponent = array_intersect($components, $profileTypes);
443 if (!empty($profileTypeComponent) ||
444 count(array_intersect($contactTypes, $profileTypes)) > 1 ||
445 count(array_intersect($subTypes, $profileTypes)) > 1
446 ) {
447 return FALSE;
448 }
449
450 return TRUE;
451 }
452
453 /**
454 * Find out whether given profile group uses $required
455 * and/or $optional profile types
456 *
457 * @param int $ufGroupId
458 * Profile id.
459 * @param array $required
460 * Array of types those are required.
461 * @param array $optional
462 * Array of types those are optional.
463 *
464 * @return boolean $valid
465 * @static
466 */
467 public static function checkValidProfileType($ufGroupId, $required, $optional = NULL) {
468 if (!is_array($required) || empty($required)) {
469 return;
470 }
471
472 $ufGroup = new CRM_Core_DAO_UFGroup();
473 $ufGroup->id = $ufGroupId;
474 $ufGroup->find(TRUE);
475
476 $profileTypes = array();
477 if ($ufGroup->group_type) {
478 $typeParts = explode(CRM_Core_DAO::VALUE_SEPARATOR, $ufGroup->group_type);
479 $profileTypes = explode(',', $typeParts[0]);
480 }
481
482 if (empty($profileTypes)) {
483 return FALSE;
484 }
485
486 $valid = TRUE;
487 foreach ($required as $key => $val) {
488 if (!in_array($val, $profileTypes)) {
489 $valid = FALSE;
490 break;
491 }
492 }
493
494 if ($valid && is_array($optional)) {
495 foreach ($optional as $key => $val) {
496 if (in_array($val, $profileTypes)) {
497 $valid = TRUE;
498 break;
499 }
500 }
501 }
502
503 return $valid;
504 }
505
506 /**
507 * Check for mix profile fields (eg: individual + other contact types)
508 *
509 * @param int $ufGroupId
510 *
511 * @return true for mix profile else false
512 * @static
513 */
514 public static function checkProfileType($ufGroupId) {
515 $ufGroup = new CRM_Core_DAO_UFGroup();
516 $ufGroup->id = $ufGroupId;
517 $ufGroup->find(TRUE);
518
519 $profileTypes = array();
520 if ($ufGroup->group_type) {
521 $typeParts = explode(CRM_Core_DAO::VALUE_SEPARATOR, $ufGroup->group_type);
522 $profileTypes = explode(',', $typeParts[0]);
523 }
524
525 //early return if new profile.
526 if (empty($profileTypes)) {
527 return FALSE;
528 }
529
530 //we need to unset Contact
531 if (count($profileTypes) > 1) {
532 $index = array_search('Contact', $profileTypes);
533 if ($index !== FALSE) {
534 unset($profileTypes[$index]);
535 }
536 }
537
538 // suppress any subtypes if present
539 CRM_Contact_BAO_ContactType::suppressSubTypes($profileTypes);
540
541 $contactTypes = array('Contact', 'Individual', 'Household', 'Organization');
542 $components = array('Contribution', 'Participant', 'Membership', 'Activity');
543 $fields = array();
544
545 // check for mix profile condition
546 if (count($profileTypes) > 1) {
547 //check the there are any components include in profile
548 foreach ($components as $value) {
549 if (in_array($value, $profileTypes)) {
550 return TRUE;
551 }
552 }
553 //check if there are more than one contact types included in profile
554 if (count($profileTypes) > 1) {
555 return TRUE;
556 }
557 }
558 elseif (count($profileTypes) == 1) {
559 // note for subtype case count would be zero
560 $profileTypes = array_values($profileTypes);
561 if (!in_array($profileTypes[0], $contactTypes)) {
562 return TRUE;
563 }
564 }
565
566 return FALSE;
567 }
568
569 /**
570 * Get the profile type (eg: individual/organization/household)
571 *
572 * @param int $ufGroupId
573 * Uf group id.
574 * @param bool $returnMixType
575 * This is true, then field type of mix profile field is returned.
576 * @param bool $onlyPure
577 * True if only pure profiles are required.
578 *
579 * @param bool $skipComponentType
580 *
581 * @return string profile group_type
582 * @static
583 *
584 * TODO Why is this function in this class? It seems to be about the UFGroup.
585 */
586 public static function getProfileType($ufGroupId, $returnMixType = TRUE, $onlyPure = FALSE, $skipComponentType = FALSE) {
587 $ufGroup = new CRM_Core_DAO_UFGroup();
588 $ufGroup->id = $ufGroupId;
589 $ufGroup->is_active = 1;
590
591 $ufGroup->find(TRUE);
592 return self::calculateProfileType($ufGroup->group_type, $returnMixType, $onlyPure, $skipComponentType);
593 }
594
595 /**
596 * Get the profile type (eg: individual/organization/household)
597 *
598 * @param string $ufGroupType
599 * @param bool $returnMixType
600 * This is true, then field type of mix profile field is returned.
601 * @param bool $onlyPure
602 * True if only pure profiles are required.
603 * @param bool $skipComponentType
604 *
605 * @return string profile group_type
606 * @static
607 *
608 * TODO Why is this function in this class? It seems to be about the UFGroup.
609 */
610 public static function calculateProfileType($ufGroupType, $returnMixType = TRUE, $onlyPure = FALSE, $skipComponentType = FALSE) {
611 // profile types
612 $contactTypes = array('Contact', 'Individual', 'Household', 'Organization');
613 $subTypes = CRM_Contact_BAO_ContactType::subTypes();
614 $components = array('Contribution', 'Participant', 'Membership', 'Activity');
615
616 $profileTypes = array();
617 if ($ufGroupType) {
618 $typeParts = explode(CRM_Core_DAO::VALUE_SEPARATOR, $ufGroupType);
619 $profileTypes = explode(',', $typeParts[0]);
620 }
621
622 if ($onlyPure) {
623 if (count($profileTypes) == 1) {
624 return $profileTypes[0];
625 }
626 else {
627 return NULL;
628 }
629 }
630
631 //we need to unset Contact
632 if (count($profileTypes) > 1) {
633 $index = array_search('Contact', $profileTypes);
634 if ($index !== FALSE) {
635 unset($profileTypes[$index]);
636 }
637 }
638
639 $profileType = $mixProfileType = NULL;
640
641 // this case handles pure profile
642 if (count($profileTypes) == 1) {
643 $profileType = array_pop($profileTypes);
644 }
645 else {
646 //check the there are any components include in profile
647 $componentCount = array();
648 foreach ($components as $value) {
649 if (in_array($value, $profileTypes)) {
650 $componentCount[] = $value;
651 }
652 }
653
654 //check contact type included in profile
655 $contactTypeCount = array();
656 foreach ($contactTypes as $value) {
657 if (in_array($value, $profileTypes)) {
658 $contactTypeCount[] = $value;
659 }
660 }
661 // subtype counter
662 $subTypeCount = array();
663 foreach ($subTypes as $value) {
664 if (in_array($value, $profileTypes)) {
665 $subTypeCount[] = $value;
666 }
667 }
668 if (!$skipComponentType && count($componentCount) == 1) {
669 $profileType = $componentCount[0];
670 }
671 elseif (count($componentCount) > 1) {
672 $mixProfileType = $componentCount[1];
673 }
674 elseif (count($subTypeCount) == 1) {
675 $profileType = $subTypeCount[0];
676 }
677 elseif (count($contactTypeCount) == 1) {
678 $profileType = $contactTypeCount[0];
679 }
680 elseif (count($subTypeCount) > 1) {
681 // this is mix subtype profiles
682 $mixProfileType = $subTypeCount[1];
683 }
684 elseif (count($contactTypeCount) > 1) {
685 // this is mix contact profiles
686 $mixProfileType = $contactTypeCount[1];
687 }
688 }
689
690 if ($mixProfileType) {
691 if ($returnMixType) {
692 return $mixProfileType;
693 }
694 else {
695 return 'Mixed';
696 }
697 }
698 else {
699 return $profileType;
700 }
701 }
702
703 /**
704 * Check for mix profiles groups (eg: individual + other contact types)
705 *
706 * @param $ctype
707 *
708 * @return true for mix profile group else false
709 * @static
710 */
711 public static function checkProfileGroupType($ctype) {
712 $ufGroup = new CRM_Core_DAO_UFGroup();
713
714 $query = "
715 SELECT ufg.id as id
716 FROM civicrm_uf_group as ufg, civicrm_uf_join as ufj
717 WHERE ufg.id = ufj.uf_group_id
718 AND ufj.module = 'User Registration'
719 AND ufg.is_active = 1 ";
720
721 $ufGroup = CRM_Core_DAO::executeQuery($query);
722
723 $fields = array();
724 $validProfiles = array('Individual', 'Organization', 'Household', 'Contribution');
725 while ($ufGroup->fetch()) {
726 $profileType = self::getProfileType($ufGroup->id);
727 if (in_array($profileType, $validProfiles)) {
728 continue;
729 }
730 elseif ($profileType) {
731 return FALSE;
732 }
733 }
734
735 return TRUE;
736 }
737
738 /**
739 * Check for searchable or in selector field for given profile.
740 *
741 * @param int $profileID
742 *
743 * @return boolean $result true/false.
744 */
745 public static function checkSearchableORInSelector($profileID) {
746 $result = FALSE;
747 if (!$profileID) {
748 return $result;
749 }
750
751 $query = "
752 SELECT id
753 From civicrm_uf_field
754 WHERE (in_selector = 1 OR is_searchable = 1)
755 AND uf_group_id = {$profileID}";
756
757 $ufFields = CRM_Core_DAO::executeQuery($query);
758 while ($ufFields->fetch()) {
759 $result = TRUE;
760 break;
761 }
762
763 return $result;
764 }
765
766 /**
767 * Reset In selector and is searchable values for given $profileID.
768 *
769 * @param int $profileID
770 *
771 * @return void.
772 */
773 public function resetInSelectorANDSearchable($profileID) {
774 if (!$profileID) {
775 return;
776 }
777 $query = "UPDATE civicrm_uf_field SET in_selector = 0, is_searchable = 0 WHERE uf_group_id = {$profileID}";
778 CRM_Core_DAO::executeQuery($query);
779 }
780
781 /**
782 * Add fields to $profileAddressFields as appropriate.
783 * profileAddressFields is assigned to the template to tell it
784 * what fields are in the profile address
785 * that potentially should be copied to the Billing fields
786 * we want to give precedence to
787 * 1) Billing &
788 * 2) then Primary designated as 'Primary
789 * 3) location_type is primary
790 * 4) if none of these apply then it just uses the first one
791 *
792 * as this will be used to
793 * transfer profile address data to billing fields
794 * http://issues.civicrm.org/jira/browse/CRM-5869
795 *
796 * @param string $key
797 * Field key - e.g. street_address-Primary, first_name.
798 * @param array $profileAddressFields
799 * Array of profile fields that relate to address fields.
800 * @param array $profileFilter
801 * Filter to apply to profile fields - expected usage is to only fill based on.
802 * the bottom profile per CRM-13726
803 *
804 * @return bool Can the address block be hidden safe in the knowledge all fields are elsewhere collected (see CRM-15118)
805 */
806 public static function assignAddressField($key, &$profileAddressFields, $profileFilter) {
807 $billing_id = CRM_Core_BAO_LocationType::getBilling();
808 list($prefixName, $index) = CRM_Utils_System::explode('-', $key, 2);
809
810 $profileFields = civicrm_api3('uf_field', 'get', array_merge($profileFilter,
811 array(
812 'is_active' => 1,
813 'return' => 'field_name, is_required',
814 'options' => array(
815 'limit' => 0,
816 ))
817 ));
818 //check for valid fields ( fields that are present in billing block )
819 $validBillingFields = array(
820 'first_name',
821 'middle_name',
822 'last_name',
823 'street_address',
824 'supplemental_address_1',
825 'city',
826 'state_province',
827 'postal_code',
828 'country'
829 );
830 $requiredBillingFields = array_diff($validBillingFields, array('middle_name', 'supplemental_address_1'));
831 $validProfileFields = array();
832 $requiredProfileFields = array();
833
834 foreach ($profileFields['values'] as $field) {
835 if(in_array($field['field_name'], $validBillingFields)) {
836 $validProfileFields[] = $field['field_name'];
837 }
838 if ($field['is_required']) {
839 $requiredProfileFields[] = $field['field_name'];
840 }
841 }
842
843 if (!in_array($prefixName, $validProfileFields) ) {
844 return;
845 }
846
847 if (!empty($index) && (
848 // it's empty so we set it OR
849 !CRM_Utils_array::value($prefixName, $profileAddressFields)
850 //we are dealing with billing id (precedence)
851 || $index == $billing_id
852 // we are dealing with primary & billing not set
853 || ($index == 'Primary' && $profileAddressFields[$prefixName] != $billing_id)
854 || ($index == CRM_Core_BAO_LocationType::getDefault()->id
855 && $profileAddressFields[$prefixName] != $billing_id
856 && $profileAddressFields[$prefixName] != 'Primary'
857 )
858 )
859 ) {
860 $profileAddressFields[$prefixName] = $index;
861 }
862
863 $potentiallyMissingRequiredFields = array_diff($requiredBillingFields, $requiredProfileFields);
864 CRM_Core_Resources::singleton()->addSetting(array('billing' => array('billingProfileIsHideable' => empty($potentiallyMissingRequiredFields))));
865 }
866
867 /**
868 * Get a list of fields which can be added to profiles
869 *
870 * @param int $gid: UF group ID
871 * @param array $defaults: Form defaults
872 * @return array, multidimensional; e.g. $result['FieldGroup']['field_name']['label']
873 * @static
874 */
875 public static function getAvailableFields($gid = NULL, $defaults = array()) {
876 $fields = array(
877 'Contact' => array(),
878 'Individual' => CRM_Contact_BAO_Contact::importableFields('Individual', FALSE, FALSE, TRUE, TRUE, TRUE),
879 'Household' => CRM_Contact_BAO_Contact::importableFields('Household', FALSE, FALSE, TRUE, TRUE, TRUE),
880 'Organization' => CRM_Contact_BAO_Contact::importableFields('Organization', FALSE, FALSE, TRUE, TRUE, TRUE),
881 );
882
883 // include hook injected fields
884 $fields['Contact'] = array_merge($fields['Contact'], CRM_Contact_BAO_Query_Hook::singleton()->getFields());
885
886 // add current employer for individuals
887 $fields['Individual']['current_employer'] = array(
888 'name' => 'organization_name',
889 'title' => ts('Current Employer'),
890 );
891
892 $addressOptions = CRM_Core_BAO_Setting::valueOptions(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME,
893 'address_options', TRUE, NULL, TRUE
894 );
895
896 if (!$addressOptions['county']) {
897 unset($fields['Individual']['county'], $fields['Household']['county'], $fields['Organization']['county']);
898 }
899
900 // break out common contact fields array CRM-3037.
901 // from a UI perspective this makes very little sense
902 foreach ($fields['Individual'] as $key => $value) {
903 if (!empty($fields['Household'][$key]) && !empty($fields['Organization'][$key])) {
904 $fields['Contact'][$key] = $value;
905 unset($fields['Individual'][$key], $fields['Household'][$key], $fields['Organization'][$key]);
906 }
907 }
908
909 // Internal field not exposed to forms
910 unset($fields['Contact']['contact_type']);
911 unset($fields['Contact']['master_id']);
912
913 // convert phone extension in to psedo-field phone + phone extension
914 //unset extension
915 unset($fields['Contact']['phone_ext']);
916 //add psedo field
917 $fields['Contact']['phone_and_ext'] = array(
918 'name' => 'phone_and_ext',
919 'title' => ts('Phone and Extension'),
920 'hasLocationType' => 1,
921 );
922
923 // include Subtypes For Profile
924 $subTypes = CRM_Contact_BAO_ContactType::subTypeInfo();
925 foreach ($subTypes as $name => $val) {
926 //custom fields for sub type
927 $subTypeFields = CRM_Core_BAO_CustomField::getFieldsForImport($name, FALSE, FALSE, FALSE, TRUE, TRUE);
928 if (array_key_exists($val['parent'], $fields)) {
929 $fields[$name] = $fields[$val['parent']] + $subTypeFields;
930 }
931 else {
932 $fields[$name] = $subTypeFields;
933 }
934 }
935
936 if (CRM_Core_Permission::access('CiviContribute')) {
937 $contribFields = CRM_Contribute_BAO_Contribution::getContributionFields(FALSE);
938 if (!empty($contribFields)) {
939 unset($contribFields['is_test']);
940 unset($contribFields['is_pay_later']);
941 unset($contribFields['contribution_id']);
942 $contribFields['contribution_note'] = array(
943 'name' => 'contribution_note',
944 'title' => ts('Contribution Note'),
945 );
946 $fields['Contribution'] = array_merge($contribFields, self::getContribBatchEntryFields());
947 }
948 }
949
950 if (CRM_Core_Permission::access('CiviEvent')) {
951 $participantFields = CRM_Event_BAO_Query::getParticipantFields();
952 if ($participantFields) {
953 // Remove fields not supported by profiles
954 CRM_Utils_Array::remove($participantFields,
955 'external_identifier',
956 'event_id',
957 'participant_contact_id',
958 'participant_role_id',
959 'participant_status_id',
960 'participant_is_test',
961 'participant_fee_level',
962 'participant_id',
963 'participant_is_pay_later',
964 'participant_campaign'
965 );
966 if (isset($participantFields['participant_campaign_id'])) {
967 $participantFields['participant_campaign_id']['title'] = ts('Campaign');
968 }
969 $fields['Participant'] = $participantFields;
970 }
971 }
972
973 if (CRM_Core_Permission::access('CiviMember')) {
974 $membershipFields = CRM_Member_BAO_Membership::getMembershipFields();
975 // Remove fields not supported by profiles
976 CRM_Utils_Array::remove($membershipFields,
977 'membership_id',
978 'membership_type_id',
979 'member_is_test',
980 'is_override',
981 'status_id',
982 'member_is_pay_later'
983 );
984 if ($gid && CRM_Core_DAO::getFieldValue('CRM_Core_DAO_UFGroup', $gid, 'name') == 'membership_batch_entry') {
985 $fields['Membership'] = array_merge($membershipFields, self::getMemberBatchEntryFields());
986 }
987 else {
988 $fields['Membership'] = $membershipFields;
989 }
990 }
991
992 if (CRM_Core_Permission::access('CiviCase')) {
993 $caseFields = CRM_Case_BAO_Query::getFields(TRUE);
994 $caseFields = array_merge($caseFields, CRM_Core_BAO_CustomField::getFieldsForImport('Case'));
995 if ($caseFields) {
996 // Remove fields not supported by profiles
997 CRM_Utils_Array::remove($caseFields,
998 'case_id',
999 'case_type',
1000 'case_start_date',
1001 'case_end_date',
1002 'case_role',
1003 'case_status',
1004 'case_deleted'
1005 );
1006 }
1007 $fields['Case'] = $caseFields;
1008 }
1009
1010 $activityFields = CRM_Activity_BAO_Activity::getProfileFields();
1011 if ($activityFields) {
1012 // campaign related fields.
1013 if (isset($activityFields['activity_campaign_id'])) {
1014 $activityFields['activity_campaign_id']['title'] = ts('Campaign');
1015 }
1016 $fields['Activity'] = $activityFields;
1017 }
1018
1019 $fields['Formatting']['format_free_html_' . rand(1000, 9999)] = array(
1020 'name' => 'free_html',
1021 'import' => FALSE,
1022 'export' => FALSE,
1023 'title' => 'Free HTML',
1024 );
1025
1026 // Sort by title
1027 foreach ($fields as &$values) {
1028 $values = CRM_Utils_Array::crmArraySortByField($values, 'title');
1029 }
1030
1031 //group selected and unwanted fields list
1032 $ufFields = $gid ? CRM_Core_BAO_UFGroup::getFields($gid, FALSE, NULL, NULL, NULL, TRUE, NULL, TRUE) : array();
1033 $groupFieldList = array_merge($ufFields, array(
1034 'note',
1035 'email_greeting_custom',
1036 'postal_greeting_custom',
1037 'addressee_custom',
1038 'id',
1039 ));
1040 //unset selected fields
1041 foreach ($groupFieldList as $key => $value) {
1042 if (is_integer($key)) {
1043 unset($fields['Individual'][$value], $fields['Household'][$value], $fields['Organization'][$value]);
1044 continue;
1045 }
1046 if (!empty($defaults['field_name'])
1047 && $defaults['field_name']['0'] == $value['field_type']
1048 && $defaults['field_name']['1'] == $key
1049 ) {
1050 continue;
1051 }
1052 unset($fields[$value['field_type']][$key]);
1053 }
1054
1055 return $fields;
1056 }
1057
1058 /**
1059 * Get a list of fields which can be added to profiles
1060 *
1061 * @param bool $force
1062 *
1063 * @return array, multidimensional; e.g. $result['field_name']['label']
1064 * @static
1065 */
1066 public static function getAvailableFieldsFlat($force = FALSE) {
1067 // FIXME reset when data model changes
1068 static $result = NULL;
1069 if ($result === NULL || $force) {
1070 $fieldTree = self::getAvailableFields();
1071 $result = array();
1072 foreach ($fieldTree as $field_type => $fields) {
1073 foreach ($fields as $field_name => $field) {
1074 if (!isset($result[$field_name])) {
1075 $field['field_type'] = $field_type;
1076 $result[$field_name] = $field;
1077 }
1078 }
1079 }
1080 }
1081 return $result;
1082 }
1083
1084 /**
1085 * Determine whether the given field_name is valid
1086 *
1087 * @param string $fieldName
1088 * @return bool
1089 */
1090 public static function isValidFieldName($fieldName) {
1091 $availableFields = CRM_Core_BAO_UFField::getAvailableFieldsFlat();
1092 return isset($availableFields[$fieldName]);
1093 }
1094
1095 /**
1096 * @return array|null
1097 */
1098 public static function getContribBatchEntryFields() {
1099 if (self::$_contriBatchEntryFields === NULL) {
1100 self::$_contriBatchEntryFields = array(
1101 'send_receipt' => array(
1102 'name' => 'send_receipt',
1103 'title' => ts('Send Receipt'),
1104 ),
1105 'soft_credit' => array(
1106 'name' => 'soft_credit',
1107 'title' => ts('Soft Credit'),
1108 ),
1109 'soft_credit_type' => array(
1110 'name' => 'soft_credit_type',
1111 'title' => ts('Soft Credit Type'),
1112 ),
1113 'product_name' => array(
1114 'name' => 'product_name',
1115 'title' => ts('Premiums'),
1116 ),
1117 'contribution_note' => array(
1118 'name' => 'contribution_note',
1119 'title' => ts('Contribution Note'),
1120 ),
1121 );
1122 }
1123 return self::$_contriBatchEntryFields;
1124 }
1125
1126 /**
1127 * @return array|null
1128 */
1129 public static function getMemberBatchEntryFields() {
1130 if (self::$_memberBatchEntryFields === NULL) {
1131 self::$_memberBatchEntryFields = array(
1132 'send_receipt' => array(
1133 'name' => 'send_receipt',
1134 'title' => ts('Send Receipt'),
1135 ),
1136 'soft_credit' => array(
1137 'name' => 'soft_credit',
1138 'title' => ts('Soft Credit'),
1139 ),
1140 'product_name' => array(
1141 'name' => 'product_name',
1142 'title' => ts('Premiums'),
1143 ),
1144 'financial_type' => array(
1145 'name' => 'financial_type',
1146 'title' => ts('Financial Type'),
1147 ),
1148 'total_amount' => array(
1149 'name' => 'total_amount',
1150 'title' => ts('Total Amount'),
1151 ),
1152 'receive_date' => array(
1153 'name' => 'receive_date',
1154 'title' => ts('Receive Date'),
1155 ),
1156 'payment_instrument' => array(
1157 'name' => 'payment_instrument',
1158 'title' => ts('Payment Instrument'),
1159 ),
1160 'contribution_status_id' => array(
1161 'name' => 'contribution_status_id',
1162 'title' => ts('Contribution Status'),
1163 ),
1164 );
1165 }
1166 return self::$_memberBatchEntryFields;
1167 }
1168 }