Merge pull request #115 from dlobo/CRM-12088
[civicrm-core.git] / CRM / Core / BAO / CustomGroup.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.3 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2013 |
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-2013
32 * $Id$
33 *
34 */
35
36 /**
37 * Business object for managing custom data groups
38 *
39 */
40 class CRM_Core_BAO_CustomGroup extends CRM_Core_DAO_CustomGroup {
41
42 /**
43 * class constructor
44 */
45 function __construct() {
46 parent::__construct();
47 }
48
49 /**
50 * takes an associative array and creates a custom group object
51 *
52 * This function is invoked from within the web form layer and also from the api layer
53 *
54 * @param array $params (reference) an assoc array of name/value pairs
55 *
56 * @return object CRM_Core_DAO_CustomGroup object
57 * @access public
58 * @static
59 */
60 static function create(&$params) {
61 // create custom group dao, populate fields and then save.
62 $group = new CRM_Core_DAO_CustomGroup();
63 $group->title = $params['title'];
64
65 if (in_array($params['extends'][0],
66 array(
67 'ParticipantRole',
68 'ParticipantEventName',
69 'ParticipantEventType',
70 )
71 )) {
72 $group->extends = 'Participant';
73 }
74 else {
75 $group->extends = $params['extends'][0];
76 }
77
78 $group->extends_entity_column_id = 'null';
79 if (
80 $params['extends'][0] == 'ParticipantRole' ||
81 $params['extends'][0] == 'ParticipantEventName' ||
82 $params['extends'][0] == 'ParticipantEventType'
83 ) {
84 $group->extends_entity_column_id =
85 CRM_Core_DAO::getFieldValue('CRM_Core_DAO_OptionValue', $params['extends'][0], 'value', 'name');
86 }
87
88 //this is format when form get submit.
89 $extendsChildType = CRM_Utils_Array::value(1, $params['extends']);
90 //lets allow user to pass direct child type value, CRM-6893
91 if (CRM_Utils_Array::value('extends_entity_column_value', $params)) {
92 $extendsChildType = $params['extends_entity_column_value'];
93 }
94 if (!CRM_Utils_System::isNull($extendsChildType)) {
95 $extendsChildType = implode(CRM_Core_DAO::VALUE_SEPARATOR, $extendsChildType);
96 if (CRM_Utils_Array::value(0, $params['extends']) == 'Relationship') {
97 $extendsChildType = str_replace(array('_a_b', '_b_a'), array('', ''), $extendsChildType);
98 }
99 if (substr($extendsChildType, 0, 1) != CRM_Core_DAO::VALUE_SEPARATOR) {
100 $extendsChildType = CRM_Core_DAO::VALUE_SEPARATOR . $extendsChildType . CRM_Core_DAO::VALUE_SEPARATOR;
101 }
102 }
103 else {
104 $extendsChildType = 'null';
105 }
106 $group->extends_entity_column_value = $extendsChildType;
107
108 if (isset($params['id'])) {
109 $oldWeight = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomGroup', $params['id'], 'weight', 'id');
110 }
111 else {
112 $oldWeight = 0;
113 }
114 $group->weight = CRM_Utils_Weight::updateOtherWeights('CRM_Core_DAO_CustomGroup', $oldWeight, CRM_Utils_Array::value('weight', $params, FALSE));
115 $fields = array('style', 'collapse_display', 'collapse_adv_display', 'help_pre', 'help_post', 'is_active', 'is_multiple');
116 foreach ($fields as $field) {
117 $group->$field = CRM_Utils_Array::value($field, $params, FALSE);
118 }
119 $group->max_multiple = isset($params['is_multiple']) ? (isset($params['max_multiple']) &&
120 $params['max_multiple'] >= '0'
121 ) ? $params['max_multiple'] : 'null' : 'null';
122
123 $tableName = $oldTableName = NULL;
124 if (isset($params['id'])) {
125 $group->id = $params['id'];
126 //check whether custom group was changed from single-valued to multiple-valued
127 $isMultiple = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomGroup',
128 $params['id'],
129 'is_multiple'
130 );
131
132 if ((CRM_Utils_Array::value('is_multiple', $params) || $isMultiple) &&
133 ($params['is_multiple'] != $isMultiple)
134 ) {
135 $oldTableName = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomGroup',
136 $params['id'],
137 'table_name'
138 );
139 }
140 }
141 else {
142 $group->created_id = CRM_Utils_Array::value('created_id', $params);
143 $group->created_date = CRM_Utils_Array::value('created_date', $params);
144
145 // we do this only once, so name never changes
146 if (isset($params['name'])) {
147 $group->name = CRM_Utils_String::munge($params['name'], '_', 64);
148 }
149 else {
150 $group->name = CRM_Utils_String::munge($group->title, '_', 64);
151 }
152
153 // lets create the table associated with the group and save it
154 $tableName = $group->table_name = "civicrm_value_" . strtolower($group->name);
155 }
156
157 // enclose the below in a transaction
158 $transaction = new CRM_Core_Transaction();
159
160 $group->save();
161 if ($tableName) {
162 // now append group id to table name, this prevent any name conflicts
163 // like CRM-2742
164 $tableName .= "_{$group->id}";
165 $group->table_name = $tableName;
166 CRM_Core_DAO::setFieldValue('CRM_Core_DAO_CustomGroup',
167 $group->id,
168 'table_name',
169 $tableName
170 );
171
172 // now create the table associated with this group
173 self::createTable($group);
174 }
175 elseif ($oldTableName) {
176 CRM_Core_BAO_SchemaHandler::changeUniqueToIndex($oldTableName, CRM_Utils_Array::value('is_multiple', $params));
177 }
178
179 if (CRM_Utils_Array::value('overrideFKConstraint', $params) == 1) {
180 $table = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomGroup',
181 $params['id'],
182 'table_name'
183 );
184 CRM_Core_BAO_SchemaHandler::changeFKConstraint($table, self::mapTableName($params['extends'][0]));
185 }
186 $transaction->commit();
187
188 // reset the cache
189 CRM_Utils_System::flushCache();
190
191 if ($tableName) {
192 CRM_Utils_Hook::post('create', 'CustomGroup', $group->id, $group);
193 }
194 else {
195 CRM_Utils_Hook::post('edit', 'CustomGroup', $group->id, $group);
196 }
197
198 return $group;
199 }
200
201 /**
202 * Takes a bunch of params that are needed to match certain criteria and
203 * retrieves the relevant objects. Typically the valid params are only
204 * contact_id. We'll tweak this function to be more full featured over a period
205 * of time. This is the inverse function of create. It also stores all the retrieved
206 * values in the default array
207 *
208 * @param array $params (reference ) an assoc array of name/value pairs
209 * @param array $defaults (reference ) an assoc array to hold the flattened values
210 *
211 * @return object CRM_Core_DAO_CustomGroup object
212 * @access public
213 * @static
214 */
215 static function retrieve(&$params, &$defaults) {
216 return CRM_Core_DAO::commonRetrieve('CRM_Core_DAO_CustomGroup', $params, $defaults);
217 }
218
219 /**
220 * update the is_active flag in the db
221 *
222 * @param int $id id of the database record
223 * @param boolean $is_active value we want to set the is_active field
224 *
225 * @return Object DAO object on sucess, null otherwise
226 * @static
227 * @access public
228 */
229 static function setIsActive($id, $is_active) {
230 // reset the cache
231 CRM_Core_BAO_Cache::deleteGroup('contact fields');
232
233 if (!$is_active) {
234 CRM_Core_BAO_UFField::setUFFieldStatus($id, $is_active);
235 }
236
237 return CRM_Core_DAO::setFieldValue('CRM_Core_DAO_CustomGroup', $id, 'is_active', $is_active);
238 }
239
240 /**
241 * Determine if given entity (sub)type has any custom groups
242 *
243 * @param string $extends e.g. "Individual", "Activity"
244 * @param int $columnId e.g. custom-group matching mechanism (usu NULL for matching on sub type-id); see extends_entity_column_id
245 * @param string $columnValue e.g. "Student" or "3" or "3\05"; see extends_entity_column_value
246 */
247 public static function hasCustomGroup($extends, $columnId, $columnValue) {
248 $dao = new CRM_Core_DAO_CustomGroup();
249 $dao->extends = $extends;
250 $dao->extends_entity_column_id = $columnId;
251 $escapedValue = CRM_Core_DAO::VALUE_SEPARATOR . CRM_Core_DAO::escapeString($columnValue) . CRM_Core_DAO::VALUE_SEPARATOR;
252 $dao->whereAdd("extends_entity_column_value LIKE \"%$escapedValue%\"");
253 //$dao->extends_entity_column_value = $columnValue;
254 return $dao->find() ? TRUE : FALSE;
255 }
256
257 /**
258 * Determine if there are any CustomGroups for the given $activityTypeId.
259 * If none found, create one.
260 *
261 * @param int $activityTypeId
262 * @return bool TRUE if a group is found or created; FALSE on error
263 */
264 public static function autoCreateByActivityType($activityTypeId) {
265 if (self::hasCustomGroup('Activity', NULL, $activityTypeId)) {
266 return TRUE;
267 }
268 $activityTypes = CRM_Core_PseudoConstant::activityType(TRUE, TRUE, FALSE, 'label', TRUE, FALSE); // everything
269 $params = array(
270 'version' => 3,
271 'extends' => 'Activity',
272 'extends_entity_column_id' => NULL,
273 'extends_entity_column_value' => CRM_Utils_Array::implodePadded(array($activityTypeId)),
274 'title' => ts('%1 Questions', array(1 => $activityTypes[$activityTypeId])),
275 'style' => 'Inline',
276 'is_active' => 1,
277 );
278 $result = civicrm_api('CustomGroup', 'create', $params);
279 return ! $result['is_error'];
280 }
281
282 /**
283 * Get custom groups/fields for type of entity.
284 *
285 * An array containing all custom groups and their custom fields is returned.
286 *
287 * @param string $entityType - of the contact whose contact type is needed
288 * @param int $entityId - optional - id of entity if we need to populate the tree with custom values.
289 * @param int $groupId - optional group id (if we need it for a single group only)
290 * - if groupId is 0 it gets for inline groups only
291 * - if groupId is -1 we get for all groups
292 *
293 * @return array $groupTree - array consisting of all groups and fields and optionally populated with custom data values.
294 *
295 * @access public
296 *
297 * @static
298 *
299 */
300 public static function &getTree($entityType,
301 &$form,
302 $entityID = NULL,
303 $groupID = NULL,
304 $subType = NULL,
305 $subName = NULL,
306 $fromCache = TRUE
307 ) {
308 if ($entityID) {
309 $entityID = CRM_Utils_Type::escape($entityID, 'Integer');
310 }
311
312 // create a new tree
313 $strSelect = $strFrom = $strWhere = $orderBy = '';
314 $tableData = array();
315
316 // using tableData to build the queryString
317 $tableData = array(
318 'civicrm_custom_field' =>
319 array(
320 'id',
321 'label',
322 'column_name',
323 'data_type',
324 'html_type',
325 'default_value',
326 'attributes',
327 'is_required',
328 'is_view',
329 'help_pre',
330 'help_post',
331 'options_per_line',
332 'start_date_years',
333 'end_date_years',
334 'date_format',
335 'time_format',
336 'option_group_id',
337 ),
338 'civicrm_custom_group' =>
339 array(
340 'id',
341 'name',
342 'table_name',
343 'title',
344 'help_pre',
345 'help_post',
346 'collapse_display',
347 'is_multiple',
348 'extends',
349 'extends_entity_column_id',
350 'extends_entity_column_value',
351 'max_multiple',
352 ),
353 );
354
355 // create select
356 $select = array();
357 foreach ($tableData as $tableName => $tableColumn) {
358 foreach ($tableColumn as $columnName) {
359 $alias = $tableName . "_" . $columnName;
360 $select[] = "{$tableName}.{$columnName} as {$tableName}_{$columnName}";
361 }
362 }
363 $strSelect = "SELECT " . implode(', ', $select);
364
365 // from, where, order by
366 $strFrom = "
367 FROM civicrm_custom_group
368 LEFT JOIN civicrm_custom_field ON (civicrm_custom_field.custom_group_id = civicrm_custom_group.id)
369 ";
370
371 // if entity is either individual, organization or household pls get custom groups for 'contact' too.
372 if ($entityType == "Individual" || $entityType == 'Organization' || $entityType == 'Household') {
373 $in = "'$entityType', 'Contact'";
374 }
375 elseif (strpos($entityType, "'") !== FALSE) {
376 // this allows the calling function to send in multiple entity types
377 $in = $entityType;
378 }
379 else {
380 // quote it
381 $in = "'$entityType'";
382 }
383
384 if ($subType) {
385 $subTypeClause = '';
386 if (is_array($subType)) {
387 $subType = implode(',', $subType);
388 }
389 if (strpos($subType, ',')) {
390 $subTypeParts = explode(',', $subType);
391 $subTypeClauses = array();
392 foreach ($subTypeParts as $subTypePart) {
393 $subTypePart = CRM_Core_DAO::VALUE_SEPARATOR . trim($subTypePart, CRM_Core_DAO::VALUE_SEPARATOR) . CRM_Core_DAO::VALUE_SEPARATOR;
394 $subTypeClauses[] = "civicrm_custom_group.extends_entity_column_value LIKE '%$subTypePart%'";
395 }
396 $subTypeClause = '(' . implode(' OR ', $subTypeClauses) . " OR civicrm_custom_group.extends_entity_column_value IS NULL )";
397 }
398 else {
399 $subType = CRM_Core_DAO::VALUE_SEPARATOR . trim($subType, CRM_Core_DAO::VALUE_SEPARATOR) . CRM_Core_DAO::VALUE_SEPARATOR;
400
401 $subTypeClause = "( civicrm_custom_group.extends_entity_column_value LIKE '%$subType%'
402 OR civicrm_custom_group.extends_entity_column_value IS NULL )";
403 }
404
405 $strWhere = "
406 WHERE civicrm_custom_group.is_active = 1
407 AND civicrm_custom_field.is_active = 1
408 AND civicrm_custom_group.extends IN ($in)
409 AND $subTypeClause
410 ";
411 if ($subName) {
412 $strWhere .= " AND civicrm_custom_group.extends_entity_column_id = {$subName} ";
413 }
414 }
415 else {
416 $strWhere = "
417 WHERE civicrm_custom_group.is_active = 1
418 AND civicrm_custom_field.is_active = 1
419 AND civicrm_custom_group.extends IN ($in)
420 AND civicrm_custom_group.extends_entity_column_value IS NULL
421 ";
422 }
423
424 $params = array();
425 if ($groupID > 0) {
426 // since we want a specific group id we add it to the where clause
427 $strWhere .= " AND civicrm_custom_group.id = %1";
428 $params[1] = array($groupID, 'Integer');
429 }
430 elseif (!$groupID) {
431 // since groupID is false we need to show all Inline groups
432 $strWhere .= " AND civicrm_custom_group.style = 'Inline'";
433 }
434
435 // ensure that the user has access to these custom groups
436 $strWhere .= " AND " . CRM_Core_Permission::customGroupClause(CRM_Core_Permission::VIEW,
437 'civicrm_custom_group.'
438 );
439
440 $orderBy = "
441 ORDER BY civicrm_custom_group.weight,
442 civicrm_custom_group.title,
443 civicrm_custom_field.weight,
444 civicrm_custom_field.label
445 ";
446
447 // final query string
448 $queryString = "$strSelect $strFrom $strWhere $orderBy";
449
450 // lets see if we can retrieve the groupTree from cache
451 $cacheString = $queryString;
452 if ( $groupID > 0 ) {
453 $cacheString .= "_{$groupID}";
454 } else {
455 $cacheString .= "_Inline";
456 }
457
458 $cacheKey = "CRM_Core_DAO_CustomGroup_Query " . md5($cacheString);
459
460 $cache = CRM_Utils_Cache::singleton();
461
462 if ($fromCache) {
463 $groupTree = $cache->get($cacheKey);
464 }
465
466 if (empty($groupTree)) {
467 $groupTree = array();
468 $crmDAO = CRM_Core_DAO::executeQuery($queryString, $params);
469
470 $customValueTables = array();
471
472 // process records
473 while ($crmDAO->fetch()) {
474 // get the id's
475 $groupID = $crmDAO->civicrm_custom_group_id;
476 $fieldId = $crmDAO->civicrm_custom_field_id;
477
478 // create an array for groups if it does not exist
479 if (!array_key_exists($groupID, $groupTree)) {
480 $groupTree[$groupID] = array();
481 $groupTree[$groupID]['id'] = $groupID;
482
483 // populate the group information
484 foreach ($tableData['civicrm_custom_group'] as $fieldName) {
485 $fullFieldName = "civicrm_custom_group_$fieldName";
486 if ($fieldName == 'id' ||
487 is_null($crmDAO->$fullFieldName)
488 ) {
489 continue;
490 }
491 // CRM-5507
492 if ($fieldName == 'extends_entity_column_value' && $subType) {
493 $groupTree[$groupID]['subtype'] = trim($subType, CRM_Core_DAO::VALUE_SEPARATOR);
494 }
495 $groupTree[$groupID][$fieldName] = $crmDAO->$fullFieldName;
496 }
497 $groupTree[$groupID]['fields'] = array();
498
499 $customValueTables[$crmDAO->civicrm_custom_group_table_name] = array();
500 }
501
502 // add the fields now (note - the query row will always contain a field)
503 // we only reset this once, since multiple values come is as multiple rows
504 if (!array_key_exists($fieldId, $groupTree[$groupID]['fields'])) {
505 $groupTree[$groupID]['fields'][$fieldId] = array();
506 }
507
508 $customValueTables[$crmDAO->civicrm_custom_group_table_name][$crmDAO->civicrm_custom_field_column_name] = 1;
509 $groupTree[$groupID]['fields'][$fieldId]['id'] = $fieldId;
510 // populate information for a custom field
511 foreach ($tableData['civicrm_custom_field'] as $fieldName) {
512 $fullFieldName = "civicrm_custom_field_$fieldName";
513 if ($fieldName == 'id' ||
514 is_null($crmDAO->$fullFieldName)
515 ) {
516 continue;
517 }
518 $groupTree[$groupID]['fields'][$fieldId][$fieldName] = $crmDAO->$fullFieldName;
519 }
520 }
521
522 if (!empty($customValueTables)) {
523 $groupTree['info'] = array('tables' => $customValueTables);
524 }
525
526 $cache->set($cacheKey, $groupTree);
527 }
528
529 // now that we have all the groups and fields, lets get the values
530 // since we need to know the table and field names
531
532 // add info to groupTree
533 if (isset($groupTree['info']) && !empty($groupTree['info'])) {
534 $select = $from = $where = array();
535 foreach ($groupTree['info']['tables'] as $table => $fields) {
536 $from[] = $table;
537 $select[] = "{$table}.id as {$table}_id";
538 $select[] = "{$table}.entity_id as {$table}_entity_id";
539
540 foreach ($fields as $column => $dontCare) {
541 $select[] = "{$table}.{$column} as {$table}_{$column}";
542 }
543
544 if ($entityID) {
545 $where[] = "{$table}.entity_id = $entityID";
546 }
547 }
548
549 $groupTree['info']['select'] = $select;
550 $groupTree['info']['from'] = $from;
551 $groupTree['info']['where'] = NULL;
552
553 if ($entityID) {
554 $groupTree['info']['where'] = $where;
555 $select = implode(', ', $select);
556
557 // this is a hack to find a table that has some values for this
558 // entityID to make the below LEFT JOIN work (CRM-2518)
559 $firstTable = NULL;
560 foreach ($from as $table) {
561 $query = "
562 SELECT id
563 FROM $table
564 WHERE entity_id = $entityID
565 ";
566 $recordExists = CRM_Core_DAO::singleValueQuery($query);
567 if ($recordExists) {
568 $firstTable = $table;
569 break;
570 }
571 }
572
573 if ($firstTable) {
574 $fromSQL = $firstTable;
575 foreach ($from as $table) {
576 if ($table != $firstTable) {
577 $fromSQL .= "\nLEFT JOIN $table USING (entity_id)";
578 }
579 }
580
581 $query = "
582 SELECT $select
583 FROM $fromSQL
584 WHERE {$firstTable}.entity_id = $entityID
585 ";
586
587 $dao = CRM_Core_DAO::executeQuery($query);
588
589 while ($dao->fetch()) {
590 foreach ($groupTree as $groupID => $group) {
591 if ($groupID === 'info') {
592 continue;
593 }
594 $table = $groupTree[$groupID]['table_name'];
595 foreach ($group['fields'] as $fieldID => $dontCare) {
596 $column = $groupTree[$groupID]['fields'][$fieldID]['column_name'];
597 $idName = "{$table}_id";
598 $fieldName = "{$table}_{$column}";
599
600 $dataType = $groupTree[$groupID]['fields'][$fieldID]['data_type'];
601 if ($dataType == 'File') {
602 if (isset($dao->$fieldName)) {
603 $config = CRM_Core_Config::singleton();
604 $fileDAO = new CRM_Core_DAO_File();
605 $fileDAO->id = $dao->$fieldName;
606
607 if ($fileDAO->find(TRUE)) {
608 $entityIDName = "{$table}_entity_id";
609 $customValue['id'] = $dao->$idName;
610 $customValue['data'] = $fileDAO->uri;
611 $customValue['fid'] = $fileDAO->id;
612 $customValue['fileURL'] = CRM_Utils_System::url('civicrm/file', "reset=1&id={$fileDAO->id}&eid={$dao->$entityIDName}");
613 $customValue['displayURL'] = NULL;
614 $deleteExtra = ts('Are you sure you want to delete attached file.');
615 $deleteURL = array(
616 CRM_Core_Action::DELETE =>
617 array(
618 'name' => ts('Delete Attached File'),
619 'url' => 'civicrm/file',
620 'qs' => 'reset=1&id=%%id%%&eid=%%eid%%&fid=%%fid%%&action=delete',
621 'extra' =>
622 'onclick = "if (confirm( \'' . $deleteExtra . '\' ) ) this.href+=\'&amp;confirmed=1\'; else return false;"',
623 ),
624 );
625 $customValue['deleteURL'] = CRM_Core_Action::formLink($deleteURL,
626 CRM_Core_Action::DELETE,
627 array(
628 'id' => $fileDAO->id,
629 'eid' => $dao->$entityIDName,
630 'fid' => $fieldID,
631 )
632 );
633 $customValue['fileName'] = CRM_Utils_File::cleanFileName(basename($fileDAO->uri));
634 if ($fileDAO->mime_type == "image/jpeg" ||
635 $fileDAO->mime_type == "image/pjpeg" ||
636 $fileDAO->mime_type == "image/gif" ||
637 $fileDAO->mime_type == "image/x-png" ||
638 $fileDAO->mime_type == "image/png"
639 ) {
640 $customValue['displayURL'] = $customValue['fileURL'];
641 $entityId = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_EntityFile',
642 $fileDAO->id,
643 'entity_id',
644 'file_id'
645 );
646 $customValue['imageURL'] = str_replace('persist/contribute', 'custom', $config->imageUploadURL) . $fileDAO->uri;
647 list($path) = CRM_Core_BAO_File::path($fileDAO->id, $entityId,
648 NULL, NULL
649 );
650 list($imageWidth, $imageHeight) = getimagesize($path);
651 list($imageThumbWidth, $imageThumbHeight) = CRM_Contact_BAO_Contact::getThumbSize($imageWidth, $imageHeight);
652 $customValue['imageThumbWidth'] = $imageThumbWidth;
653 $customValue['imageThumbHeight'] = $imageThumbHeight;
654 }
655 }
656 }
657 else {
658 $customValue = array(
659 'id' => $dao->$idName,
660 'data' => '',
661 );
662 }
663 }
664 else {
665 $customValue = array(
666 'id' => $dao->$idName,
667 'data' => $dao->$fieldName,
668 );
669 }
670 if (!array_key_exists('customValue', $groupTree[$groupID]['fields'][$fieldID])) {
671 $groupTree[$groupID]['fields'][$fieldID]['customValue'] = array();
672 }
673 if (empty($groupTree[$groupID]['fields'][$fieldID]['customValue'])) {
674 $groupTree[$groupID]['fields'][$fieldID]['customValue'] = array(1 => $customValue);
675 }
676 else {
677 $groupTree[$groupID]['fields'][$fieldID]['customValue'][] = $customValue;
678 }
679 }
680 }
681 }
682 }
683 }
684 }
685
686 return $groupTree;
687 }
688
689 /**
690 * Get the group title.
691 *
692 * @param int $id id of group.
693 *
694 * @return string title
695 *
696 * @access public
697 * @static
698 *
699 */
700 public static function getTitle($id) {
701 return CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomGroup', $id, 'title');
702 }
703
704 /**
705 * Get custom group details for a group.
706 *
707 * An array containing custom group details (including their custom field) is returned.
708 *
709 * @param int $groupId - group id whose details are needed
710 * @param boolean $searchable - is this field searchable
711 * @param array $extends - which table does it extend if any
712 *
713 * @return array $groupTree - array consisting of all group and field details
714 *
715 * @access public
716 *
717 * @static
718 *
719 */
720 public static function &getGroupDetail($groupId = NULL, $searchable = NULL, &$extends = NULL) {
721 // create a new tree
722 $groupTree = array();
723 $select = $from = $where = $orderBy = '';
724
725 $tableData = array();
726
727 // using tableData to build the queryString
728 $tableData = array(
729 'civicrm_custom_field' =>
730 array(
731 'id',
732 'label',
733 'data_type',
734 'html_type',
735 'default_value',
736 'attributes',
737 'is_required',
738 'help_pre',
739 'help_post',
740 'options_per_line',
741 'is_searchable',
742 'start_date_years',
743 'end_date_years',
744 'is_search_range',
745 'date_format',
746 'time_format',
747 'note_columns',
748 'note_rows',
749 'column_name',
750 'is_view',
751 'option_group_id',
752 ),
753 'civicrm_custom_group' =>
754 array(
755 'id',
756 'name',
757 'title',
758 'help_pre',
759 'help_post',
760 'collapse_display',
761 'collapse_adv_display',
762 'extends',
763 'extends_entity_column_value',
764 'table_name',
765 ),
766 );
767
768 // create select
769 $select = "SELECT";
770 $s = array();
771 foreach ($tableData as $tableName => $tableColumn) {
772 foreach ($tableColumn as $columnName) {
773 $s[] = "{$tableName}.{$columnName} as {$tableName}_{$columnName}";
774 }
775 }
776 $select = 'SELECT ' . implode(', ', $s);
777 $params = array();
778 // from, where, order by
779 $from = " FROM civicrm_custom_field, civicrm_custom_group";
780 $where = " WHERE civicrm_custom_field.custom_group_id = civicrm_custom_group.id
781 AND civicrm_custom_group.is_active = 1
782 AND civicrm_custom_field.is_active = 1 ";
783 if ($groupId) {
784 $params[1] = array($groupId, 'Integer');
785 $where .= " AND civicrm_custom_group.id = %1";
786 }
787
788 if ($searchable) {
789 $where .= " AND civicrm_custom_field.is_searchable = 1";
790 }
791
792 if ($extends) {
793 $clause = array();
794 foreach ($extends as $e) {
795 $clause[] = "civicrm_custom_group.extends = '$e'";
796 }
797 $where .= " AND ( " . implode(' OR ', $clause) . " ) ";
798
799 //include case activities customdata if case is enabled
800 if (in_array('Activity', $extends)) {
801 $extendValues = implode(',', array_keys(CRM_Core_PseudoConstant::activityType(TRUE, TRUE, FALSE, 'label', TRUE)));
802 $where .= " AND ( civicrm_custom_group.extends_entity_column_value IS NULL OR REPLACE( civicrm_custom_group.extends_entity_column_value, %2, ' ') IN ($extendValues) ) ";
803 $params[2] = array(CRM_Core_DAO::VALUE_SEPARATOR, 'String');
804 }
805 }
806
807 // ensure that the user has access to these custom groups
808 $where .= " AND " . CRM_Core_Permission::customGroupClause(CRM_Core_Permission::VIEW,
809 'civicrm_custom_group.'
810 );
811
812 $orderBy = " ORDER BY civicrm_custom_group.weight, civicrm_custom_field.weight";
813
814 // final query string
815 $queryString = $select . $from . $where . $orderBy;
816
817 // dummy dao needed
818 $crmDAO = CRM_Core_DAO::executeQuery($queryString, $params);
819
820 // process records
821 while ($crmDAO->fetch()) {
822 $groupId = $crmDAO->civicrm_custom_group_id;
823 $fieldId = $crmDAO->civicrm_custom_field_id;
824
825 // create an array for groups if it does not exist
826 if (!array_key_exists($groupId, $groupTree)) {
827 $groupTree[$groupId] = array();
828 $groupTree[$groupId]['id'] = $groupId;
829
830 foreach ($tableData['civicrm_custom_group'] as $v) {
831 $fullField = "civicrm_custom_group_" . $v;
832
833 if ($v == 'id' || is_null($crmDAO->$fullField)) {
834 continue;
835 }
836
837 $groupTree[$groupId][$v] = $crmDAO->$fullField;
838 }
839
840 $groupTree[$groupId]['fields'] = array();
841 }
842
843 // add the fields now (note - the query row will always contain a field)
844 $groupTree[$groupId]['fields'][$fieldId] = array();
845 $groupTree[$groupId]['fields'][$fieldId]['id'] = $fieldId;
846
847 foreach ($tableData['civicrm_custom_field'] as $v) {
848 $fullField = "civicrm_custom_field_" . $v;
849 if ($v == 'id' || is_null($crmDAO->$fullField)) {
850 continue;
851 }
852 $groupTree[$groupId]['fields'][$fieldId][$v] = $crmDAO->$fullField;
853 }
854 }
855
856 return $groupTree;
857 }
858
859 public static function &getActiveGroups($entityType, $path, $cidToken = '%%cid%%') {
860 // for Group's
861 $customGroupDAO = new CRM_Core_DAO_CustomGroup();
862
863 // get only 'Tab' groups
864 $customGroupDAO->whereAdd("style = 'Tab'");
865 $customGroupDAO->whereAdd("is_active = 1");
866
867 // add whereAdd for entity type
868 self::_addWhereAdd($customGroupDAO, $entityType, $cidToken);
869
870 $groups = array();
871
872 $permissionClause = CRM_Core_Permission::customGroupClause(CRM_Core_Permission::VIEW, NULL, TRUE);
873 $customGroupDAO->whereAdd($permissionClause);
874
875 // order by weight
876 $customGroupDAO->orderBy('weight');
877 $customGroupDAO->find();
878
879 // process each group with menu tab
880 while ($customGroupDAO->fetch()) {
881 $group = array();
882 $group['id'] = $customGroupDAO->id;
883 $group['path'] = $path;
884 $group['title'] = "$customGroupDAO->title";
885 $group['query'] = "reset=1&gid={$customGroupDAO->id}&cid={$cidToken}";
886 $group['extra'] = array('gid' => $customGroupDAO->id);
887 $group['table_name'] = $customGroupDAO->table_name;
888 $groups[] = $group;
889 }
890
891 return $groups;
892 }
893
894 /**
895 * Get the table name for the entity type
896 * currently if entity type is 'Contact', 'Individual', 'Household', 'Organization'
897 * tableName is 'civicrm_contact'
898 *
899 * @param string $entityType what entity are we extending here ?
900 *
901 * @return string $tableName
902 *
903 * @access private
904 * @static
905 *
906 */
907 private static function _getTableName($entityType) {
908 $tableName = '';
909 switch ($entityType) {
910 case 'Contact':
911 case 'Individual':
912 case 'Household':
913 case 'Organization':
914 $tableName = 'civicrm_contact';
915 break;
916
917 case 'Contribution':
918 $tableName = 'civicrm_contribution';
919 break;
920
921 case 'Group':
922 $tableName = 'civicrm_group';
923 break;
924 // DRAFTING: Verify if we cannot make it pluggable
925
926 case 'Activity':
927 $tableName = 'civicrm_activity';
928 break;
929
930 case 'Relationship':
931 $tableName = 'civicrm_relationship';
932 break;
933
934 case 'Membership':
935 $tableName = 'civicrm_membership';
936 break;
937
938 case 'Participant':
939 $tableName = 'civicrm_participant';
940 break;
941
942 case 'Event':
943 $tableName = 'civicrm_event';
944 break;
945
946 case 'Grant':
947 $tableName = 'civicrm_grant';
948 break;
949 // need to add cases for Location, Address
950 }
951
952 return $tableName;
953 }
954
955 /**
956 * Get a list of custom groups which extend a given entity type.
957 * If there are custom-groups which only apply to certain subtypes,
958 * those WILL be included.
959 *
960 * @param $entityType string
961 * @return CRM_Core_DAO_CustomGroup
962 */
963 static function getAllCustomGroupsByBaseEntity($entityType) {
964 $customGroupDAO = new CRM_Core_DAO_CustomGroup();
965 self::_addWhereAdd($customGroupDAO, $entityType, NULL, TRUE);
966 return $customGroupDAO;
967 }
968
969 /**
970 * Add the whereAdd clause for the DAO depending on the type of entity
971 * the custom group is extending.
972 *
973 * @param object CRM_Core_DAO_CustomGroup (reference) - Custom Group DAO.
974 * @param string $entityType - what entity are we extending here ?
975 *
976 * @return void
977 *
978 * @access private
979 * @static
980 *
981 */
982 private static function _addWhereAdd(&$customGroupDAO, $entityType, $entityID = NULL, $allSubtypes = FALSE) {
983 $addSubtypeClause = FALSE;
984
985 switch ($entityType) {
986 case 'Contact':
987 // if contact, get all related to contact
988 $extendList = "'Contact','Individual','Household','Organization'";
989 $customGroupDAO->whereAdd("extends IN ( $extendList )");
990 if (!$allSubtypes) {
991 $addSubtypeClause = TRUE;
992 }
993 break;
994
995 case 'Individual':
996 case 'Household':
997 case 'Organization':
998 // is I/H/O then get I/H/O and contact
999 $extendList = "'Contact','$entityType'";
1000 $customGroupDAO->whereAdd("extends IN ( $extendList )");
1001 if (!$allSubtypes) {
1002 $addSubtypeClause = TRUE;
1003 }
1004 break;
1005
1006 case 'Location':
1007 case 'Address':
1008 case 'Activity':
1009 case 'Contribution':
1010 case 'Membership':
1011 case 'Participant':
1012 $customGroupDAO->whereAdd("extends IN ('$entityType')");
1013 break;
1014 }
1015
1016 if ($addSubtypeClause) {
1017 $csType = is_numeric($entityID) ? CRM_Contact_BAO_Contact::getContactSubType($entityID) : FALSE;
1018
1019 if (!empty($csType)) {
1020 $subtypeClause = array();
1021 foreach ($csType as $subtype) {
1022 $subtype = CRM_Core_DAO::VALUE_SEPARATOR . $subtype . CRM_Core_DAO::VALUE_SEPARATOR;
1023 $subtypeClause[] = "extends_entity_column_value LIKE '%{$subtype}%'";
1024 }
1025 $subtypeClause[] = "extends_entity_column_value IS NULL";
1026 $customGroupDAO->whereAdd("( " . implode(' OR ', $subtypeClause) . " )");
1027 }
1028 else {
1029 $customGroupDAO->whereAdd("extends_entity_column_value IS NULL");
1030 }
1031 }
1032 }
1033
1034 /**
1035 * Delete the Custom Group.
1036 *
1037 * @param $group object the DAO custom group object
1038 * @param $force boolean whether to force the deletion, even if there are custom fields
1039 *
1040 * @return boolean false if field exists for this group, true if group gets deleted.
1041 *
1042 * @access public
1043 * @static
1044 *
1045 */
1046 public static function deleteGroup($group, $force = FALSE) {
1047
1048 //check wheter this contain any custom fields
1049 $customField = new CRM_Core_DAO_CustomField();
1050 $customField->custom_group_id = $group->id;
1051 $customField->find();
1052
1053 // return early if there are custom fields and we're not
1054 // forcing the delete, otherwise delete the fields one by one
1055 while ($customField->fetch()) {
1056 if (!$force) {
1057 return FALSE;
1058 }
1059 CRM_Core_BAO_CustomField::deleteField($customField);
1060 }
1061
1062 // drop the table associated with this custom group
1063 CRM_Core_BAO_SchemaHandler::dropTable($group->table_name);
1064
1065 //delete custom group
1066 $group->delete();
1067
1068 CRM_Utils_Hook::post('delete', 'CustomGroup', $group->id, $group);
1069
1070 return TRUE;
1071 }
1072
1073 static function setDefaults(&$groupTree, &$defaults, $viewMode = FALSE, $inactiveNeeded = FALSE, $action = CRM_Core_Action::NONE) {
1074 foreach ($groupTree as $id => $group) {
1075 if (!isset($group['fields'])) {
1076 continue;
1077 }
1078 $groupId = CRM_Utils_Array::value('id', $group);
1079 foreach ($group['fields'] as $field) {
1080 if (CRM_Utils_Array::value('element_value', $field) !== NULL) {
1081 $value = $field['element_value'];
1082 }
1083 elseif (CRM_Utils_Array::value('default_value', $field) !== NULL &&
1084 ($action != CRM_Core_Action::UPDATE ||
1085 // CRM-7548
1086 !array_key_exists('element_value', $field)
1087 )
1088 ) {
1089 $value = $viewMode ? NULL : $field['default_value'];
1090 }
1091 else {
1092 continue;
1093 }
1094
1095 $fieldId = $field['id'];
1096 $elementName = $field['element_name'];
1097 switch ($field['html_type']) {
1098 case 'Multi-Select':
1099 case 'AdvMulti-Select':
1100 case 'CheckBox':
1101 $defaults[$elementName] = array();
1102 $customOption = CRM_Core_BAO_CustomOption::getCustomOption($field['id'], $inactiveNeeded);
1103 if ($viewMode) {
1104 $checkedData = explode(CRM_Core_DAO::VALUE_SEPARATOR, substr($value, 1, -1));
1105 if (isset($value)) {
1106 foreach ($customOption as $customValue => $customLabel) {
1107 if (in_array($customValue, $checkedData)) {
1108 if ($field['html_type'] == 'CheckBox') {
1109 $defaults[$elementName][$customValue] = 1;
1110 }
1111 else {
1112 $defaults[$elementName][$customValue] = $customValue;
1113 }
1114 }
1115 else {
1116 $defaults[$elementName][$customValue] = 0;
1117 }
1118 }
1119 }
1120 }
1121 else {
1122 if (isset($field['customValue']['data'])) {
1123 $checkedData = explode(CRM_Core_DAO::VALUE_SEPARATOR, substr($field['customValue']['data'], 1, -1));
1124 foreach ($customOption as $val) {
1125 if (in_array($val['value'], $checkedData)) {
1126 if ($field['html_type'] == 'CheckBox') {
1127 $defaults[$elementName][$val['value']] = 1;
1128 }
1129 else {
1130 $defaults[$elementName][$val['value']] = $val['value'];
1131 }
1132 }
1133 else {
1134 $defaults[$elementName][$val['value']] = 0;
1135 }
1136 }
1137 }
1138 else {
1139 $checkedValue = explode(CRM_Core_DAO::VALUE_SEPARATOR, substr($value, 1, -1));
1140 foreach ($customOption as $val) {
1141 if (in_array($val['value'], $checkedValue)) {
1142 if ($field['html_type'] == 'CheckBox') {
1143 $defaults[$elementName][$val['value']] = 1;
1144 }
1145 else {
1146 $defaults[$elementName][$val['value']] = $val['value'];
1147 }
1148 }
1149 }
1150 }
1151 }
1152 break;
1153
1154 case 'Select Date':
1155 if (isset($value)) {
1156 if (empty($field['time_format'])) {
1157 list($defaults[$elementName]) = CRM_Utils_Date::setDateDefaults($value, NULL,
1158 $field['date_format']
1159 );
1160 }
1161 else {
1162 $timeElement = $elementName . '_time';
1163 if (substr($elementName, -1) == ']') {
1164 $timeElement = substr($elementName, 0, -1) . '_time]';
1165 }
1166 list($defaults[$elementName], $defaults[$timeElement]) = CRM_Utils_Date::setDateDefaults($value, NULL, $field['date_format'], $field['time_format']);
1167 }
1168 }
1169 break;
1170
1171 case 'Multi-Select Country':
1172 case 'Multi-Select State/Province':
1173 if (isset($value)) {
1174 $checkedValue = explode(CRM_Core_DAO::VALUE_SEPARATOR, $value);
1175 foreach ($checkedValue as $val) {
1176 if ($val) {
1177 $defaults[$elementName][$val] = $val;
1178 }
1179 }
1180 }
1181 break;
1182
1183 case 'Select Country':
1184 if ($value) {
1185 $defaults[$elementName] = $value;
1186 }
1187 else {
1188 $config = CRM_Core_Config::singleton();
1189 $defaults[$elementName] = $config->defaultContactCountry;
1190 }
1191 break;
1192
1193 case 'Autocomplete-Select':
1194 $hiddenEleName = $elementName . '_id';
1195 if (substr($elementName, -1) == ']') {
1196 $hiddenEleName = substr($elementName, 0, -1) . '_id]';
1197 }
1198 if ($field['data_type'] == "ContactReference") {
1199 if (is_numeric($value)) {
1200 $defaults[$hiddenEleName] = $value;
1201 $defaults[$elementName] = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $value, 'sort_name');
1202 }
1203 }
1204 else {
1205 $label = CRM_Core_BAO_CustomOption::getOptionLabel($field['id'], $value);
1206 $defaults[$hiddenEleName] = $value;
1207 $defaults[$elementName] = $label;
1208 }
1209 break;
1210
1211 default:
1212 if ($field['data_type'] == "Float") {
1213 $defaults[$elementName] = (float)$value;
1214 }
1215 elseif ($field['data_type'] == 'Money' &&
1216 $field['html_type'] == 'Text'
1217 ) {
1218 $defaults[$elementName] = CRM_Utils_Money::format($value, NULL, '%a');
1219 }
1220 else {
1221 $defaults[$elementName] = $value;
1222 }
1223 }
1224 }
1225 }
1226 }
1227
1228 static function postProcess(&$groupTree, &$params, $skipFile = FALSE) {
1229 // Get the Custom form values and groupTree
1230 // first reset all checkbox and radio data
1231 foreach ($groupTree as $groupID => $group) {
1232 if ($groupID === 'info') {
1233 continue;
1234 }
1235 foreach ($group['fields'] as $field) {
1236 $fieldId = $field['id'];
1237
1238 //added Multi-Select option in the below if-statement
1239 if ($field['html_type'] == 'CheckBox' || $field['html_type'] == 'Radio' ||
1240 $field['html_type'] == 'AdvMulti-Select' || $field['html_type'] == 'Multi-Select'
1241 ) {
1242 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = 'NULL';
1243 }
1244
1245 $v = NULL;
1246 foreach ($params as $key => $val) {
1247 if (preg_match('/^custom_(\d+)_?(-?\d+)?$/', $key, $match) &&
1248 $match[1] == $field['id']
1249 ) {
1250 $v = $val;
1251 }
1252 }
1253
1254
1255 if (!isset($groupTree[$groupID]['fields'][$fieldId]['customValue'])) {
1256 // field exists in db so populate value from "form".
1257 $groupTree[$groupID]['fields'][$fieldId]['customValue'] = array();
1258 }
1259
1260 switch ($groupTree[$groupID]['fields'][$fieldId]['html_type']) {
1261
1262 //added for CheckBox
1263
1264 case 'CheckBox':
1265 if (!empty($v)) {
1266 $customValue = array_keys($v);
1267 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = CRM_Core_DAO::VALUE_SEPARATOR . implode(CRM_Core_DAO::VALUE_SEPARATOR, $customValue) . CRM_Core_DAO::VALUE_SEPARATOR;
1268 }
1269 else {
1270 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = NULL;
1271 }
1272 break;
1273
1274 //added for Advanced Multi-Select
1275
1276 case 'AdvMulti-Select':
1277 //added for Multi-Select
1278 case 'Multi-Select':
1279 if (!empty($v)) {
1280 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = CRM_Core_DAO::VALUE_SEPARATOR . implode(CRM_Core_DAO::VALUE_SEPARATOR, $v) . CRM_Core_DAO::VALUE_SEPARATOR;
1281 }
1282 else {
1283 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = NULL;
1284 }
1285 break;
1286
1287 case 'Select Date':
1288 $date = CRM_Utils_Date::processDate($v);
1289 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = $date;
1290 break;
1291
1292 case 'File':
1293 if ($skipFile) {
1294 continue;
1295 }
1296
1297 //store the file in d/b
1298 $entityId = explode('=', $groupTree['info']['where'][0]);
1299 $fileParams = array('upload_date' => date('Ymdhis'));
1300
1301 if ($groupTree[$groupID]['fields'][$fieldId]['customValue']['fid']) {
1302 $fileParams['id'] = $groupTree[$groupID]['fields'][$fieldId]['customValue']['fid'];
1303 }
1304 if (!empty($v)) {
1305 $fileParams['uri'] = $v['name'];
1306 $fileParams['mime_type'] = $v['type'];
1307 CRM_Core_BAO_File::filePostProcess($v['name'],
1308 $groupTree[$groupID]['fields'][$fieldId]['customValue']['fid'],
1309 $groupTree[$groupID]['table_name'],
1310 trim($entityId[1]),
1311 FALSE,
1312 TRUE,
1313 $fileParams,
1314 'custom_' . $fieldId,
1315 $v['type']
1316 );
1317 }
1318 $defaults = array();
1319 $paramsFile = array(
1320 'entity_table' => $groupTree[$groupID]['table_name'],
1321 'entity_id' => $entityId[1],
1322 );
1323
1324 CRM_Core_DAO::commonRetrieve('CRM_Core_DAO_EntityFile',
1325 $paramsFile,
1326 $defaults
1327 );
1328
1329 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = $defaults['file_id'];
1330 break;
1331
1332 default:
1333 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = $v;
1334 break;
1335 }
1336 }
1337 }
1338 }
1339
1340 /**
1341 * generic function to build all the form elements for a specific group tree
1342 *
1343 * @param CRM_Core_Form $form the form object
1344 * @param array $groupTree the group tree object
1345 * @param string $showName
1346 * @param string $hideName
1347 *
1348 * @return void
1349 * @access public
1350 * @static
1351 */
1352 static function buildQuickForm(&$form,
1353 &$groupTree,
1354 $inactiveNeeded = FALSE,
1355 $groupCount = 1,
1356 $prefix = ''
1357 ) {
1358
1359 $form->assign_by_ref("{$prefix}groupTree", $groupTree);
1360 $sBlocks = array();
1361 $hBlocks = array();
1362
1363 // this is fix for date field
1364 $form->assign('currentYear', date('Y'));
1365
1366 foreach ($groupTree as $id => $group) {
1367
1368 CRM_Core_ShowHideBlocks::links($form, $group['title'], '', '');
1369
1370 $groupId = CRM_Utils_Array::value('id', $group);
1371 foreach ($group['fields'] as $field) {
1372 $required = CRM_Utils_Array::value('is_required', $field);
1373 //fix for CRM-1620
1374 if ($field['data_type'] == 'File') {
1375 if (isset($field['customValue']['data'])) {
1376 $required = 0;
1377 }
1378 }
1379
1380 $fieldId = $field['id'];
1381 $elementName = $field['element_name'];
1382 CRM_Core_BAO_CustomField::addQuickFormElement($form, $elementName, $fieldId, $inactiveNeeded, $required);
1383 }
1384 }
1385 }
1386
1387 /**
1388 * Function to extract the get params from the url, validate
1389 * and store it in session
1390 *
1391 * @param CRM_Core_Form $form the form object
1392 * @param string $type the type of custom group we are using
1393 *
1394 * @return void
1395 * @access public
1396 * @static
1397 */
1398 static function extractGetParams(&$form, $type) {
1399 // if not GET params return
1400 if (empty($_GET)) {
1401 return;
1402 }
1403
1404 $groupTree = CRM_Core_BAO_CustomGroup::getTree($type, $form);
1405 $customValue = array();
1406 $htmlType = array('CheckBox', 'Multi-Select', 'AdvMulti-Select', 'Select', 'Radio');
1407
1408 foreach ($groupTree as $group) {
1409 if (!isset($group['fields'])) {
1410 continue;
1411 }
1412 foreach ($group['fields'] as $key => $field) {
1413 $fieldName = 'custom_' . $key;
1414 $value = CRM_Utils_Request::retrieve($fieldName, 'String', $form);
1415
1416 if ($value) {
1417 $valid = FALSE;
1418 if (!in_array($field['html_type'], $htmlType) ||
1419 $field['data_type'] == 'Boolean'
1420 ) {
1421 $valid = CRM_Core_BAO_CustomValue::typecheck($field['data_type'], $value);
1422 }
1423 if ($field['html_type'] == 'CheckBox' ||
1424 $field['html_type'] == 'AdvMulti-Select' ||
1425 $field['html_type'] == 'Multi-Select'
1426 ) {
1427 $value = str_replace("|", ",", $value);
1428 $mulValues = explode(',', $value);
1429 $customOption = CRM_Core_BAO_CustomOption::getCustomOption($key, TRUE);
1430 $val = array();
1431 foreach ($mulValues as $v1) {
1432 foreach ($customOption as $coID => $coValue) {
1433 if (strtolower(trim($coValue['label'])) == strtolower(trim($v1))) {
1434 $val[$coValue['value']] = 1;
1435 }
1436 }
1437 }
1438 if (!empty($val)) {
1439 $value = $val;
1440 $valid = TRUE;
1441 }
1442 else {
1443 $value = NULL;
1444 }
1445 }
1446 elseif ($field['html_type'] == 'Select' ||
1447 ($field['html_type'] == 'Radio' &&
1448 $field['data_type'] != 'Boolean'
1449 )
1450 ) {
1451 $customOption = CRM_Core_BAO_CustomOption::getCustomOption($key, TRUE);
1452 foreach ($customOption as $customID => $coValue) {
1453 if (strtolower(trim($coValue['label'])) == strtolower(trim($value))) {
1454 $value = $coValue['value'];
1455 $valid = TRUE;
1456 }
1457 }
1458 }
1459 elseif ($field['data_type'] == 'Date') {
1460 if (!empty($value)) {
1461 $time = NULL;
1462 if (CRM_Utils_Array::value('time_format', $field)) {
1463 $time = CRM_Utils_Request::retrieve($fieldName . '_time', 'String', $form);
1464 }
1465 list($value, $time) = CRM_Utils_Date::setDateDefaults($value . ' ' . $time);
1466 if (CRM_Utils_Array::value('time_format', $field)) {
1467 $customValue[$fieldName . '_time'] = $time;
1468 }
1469 }
1470 $valid = TRUE;
1471 }
1472
1473 if ($valid) {
1474 $customValue[$fieldName] = $value;
1475 }
1476 }
1477 }
1478 }
1479
1480 return $customValue;
1481 }
1482
1483 /**
1484 * Function to check the type of custom field type (eg: Used for Individual, Contribution, etc)
1485 * this function is used to get the custom fields of a type (eg: Used for Individual, Contribution, etc )
1486 *
1487 * @param int $customFieldId custom field id
1488 * @param array $removeCustomFieldTypes remove custom fields of a type eg: array("Individual") ;
1489 *
1490 *
1491 * @return boolean false if it matches else true
1492 * @static
1493 * @access public
1494 */
1495 static function checkCustomField($customFieldId, &$removeCustomFieldTypes) {
1496 $query = "SELECT cg.extends as extends
1497 FROM civicrm_custom_group as cg, civicrm_custom_field as cf
1498 WHERE cg.id = cf.custom_group_id
1499 AND cf.id =" . CRM_Utils_Type::escape($customFieldId, 'Integer');
1500
1501 $extends = CRM_Core_DAO::singleValueQuery($query);
1502
1503 if (in_array($extends, $removeCustomFieldTypes)) {
1504 return FALSE;
1505 }
1506 return TRUE;
1507 }
1508
1509 static function mapTableName($table) {
1510 switch ($table) {
1511 case 'Contact':
1512 case 'Individual':
1513 case 'Household':
1514 case 'Organization':
1515 return 'civicrm_contact';
1516
1517 case 'Activity':
1518 return 'civicrm_activity';
1519
1520 case 'Group':
1521 return 'civicrm_group';
1522
1523 case 'Contribution':
1524 return 'civicrm_contribution';
1525
1526 case 'Relationship':
1527 return 'civicrm_relationship';
1528
1529 case 'Event':
1530 return 'civicrm_event';
1531
1532 case 'Membership':
1533 return 'civicrm_membership';
1534
1535 case 'Participant':
1536 case 'ParticipantRole':
1537 case 'ParticipantEventName':
1538 case 'ParticipantEventType':
1539 return 'civicrm_participant';
1540
1541 case 'Grant':
1542 return 'civicrm_grant';
1543
1544 case 'Pledge':
1545 return 'civicrm_pledge';
1546
1547 case 'Address':
1548 return 'civicrm_address';
1549
1550 case 'Campaign':
1551 return 'civicrm_campaign';
1552
1553 default:
1554 $query = "
1555 SELECT IF( EXISTS(SELECT name FROM civicrm_contact_type WHERE name like %1), 1, 0 )";
1556 $qParams = array(1 => array($table, 'String'));
1557 $result = CRM_Core_DAO::singleValueQuery($query, $qParams);
1558
1559 if ($result) {
1560 return 'civicrm_contact';
1561 }
1562 else {
1563 $extendObjs = CRM_Core_OptionGroup::values('cg_extend_objects', FALSE, FALSE, FALSE, NULL, 'name');
1564 if (array_key_exists($table, $extendObjs)) {
1565 return $extendObjs[$table];
1566 }
1567 CRM_Core_Error::fatal();
1568 }
1569 }
1570 }
1571
1572 static function createTable($group) {
1573 $params = array(
1574 'name' => $group->table_name,
1575 'is_multiple' => $group->is_multiple ? 1 : 0,
1576 'extends_name' => self::mapTableName($group->extends),
1577 );
1578
1579 $tableParams = CRM_Core_BAO_CustomField::defaultCustomTableSchema($params);
1580
1581 CRM_Core_BAO_SchemaHandler::createTable($tableParams);
1582 }
1583
1584 /**
1585 * Function returns formatted groupTree, sothat form can be easily build in template
1586 *
1587 * @param array $groupTree associated array
1588 * @param int $groupCount group count by default 1, but can varry for multiple value custom data
1589 * @param object form object
1590 *
1591 * @return array $formattedGroupTree
1592 */
1593 static function formatGroupTree(&$groupTree, $groupCount = 1, &$form) {
1594 $formattedGroupTree = array();
1595 $uploadNames = array();
1596
1597 foreach ($groupTree as $key => $value) {
1598 if ($key === 'info') {
1599 continue;
1600 }
1601
1602 // add group information
1603 $formattedGroupTree[$key]['name'] = CRM_Utils_Array::value('name', $value);
1604 $formattedGroupTree[$key]['title'] = CRM_Utils_Array::value('title', $value);
1605 $formattedGroupTree[$key]['help_pre'] = CRM_Utils_Array::value('help_pre', $value);
1606 $formattedGroupTree[$key]['help_post'] = CRM_Utils_Array::value('help_post', $value);
1607 $formattedGroupTree[$key]['collapse_display'] = CRM_Utils_Array::value('collapse_display', $value);
1608 $formattedGroupTree[$key]['collapse_adv_display'] = CRM_Utils_Array::value('collapse_adv_display', $value);
1609
1610 // this params needed of bulding multiple values
1611 $formattedGroupTree[$key]['is_multiple'] = CRM_Utils_Array::value('is_multiple', $value);
1612 $formattedGroupTree[$key]['extends'] = CRM_Utils_Array::value('extends', $value);
1613 $formattedGroupTree[$key]['extends_entity_column_id'] = CRM_Utils_Array::value('extends_entity_column_id', $value);
1614 $formattedGroupTree[$key]['extends_entity_column_value'] = CRM_Utils_Array::value('extends_entity_column_value', $value);
1615 $formattedGroupTree[$key]['subtype'] = CRM_Utils_Array::value('subtype', $value);
1616 $formattedGroupTree[$key]['max_multiple'] = CRM_Utils_Array::value('max_multiple', $value);
1617
1618 // add field information
1619 foreach ($value['fields'] as $k => $properties) {
1620 $properties['element_name'] = "custom_{$k}_-{$groupCount}";
1621 if (isset($properties['customValue']) && !CRM_Utils_system::isNull($properties['customValue'])) {
1622 if (isset($properties['customValue'][$groupCount])) {
1623 $properties['element_name'] = "custom_{$k}_{$properties['customValue'][$groupCount]['id']}";
1624 $formattedGroupTree[$key]['table_id'] = $properties['customValue'][$groupCount]['id'];
1625 if ($properties['data_type'] == 'File') {
1626 $properties['element_value'] = $properties['customValue'][$groupCount];
1627 $uploadNames[] = $properties['element_name'];
1628 }
1629 else {
1630 $properties['element_value'] = $properties['customValue'][$groupCount]['data'];
1631 }
1632 }
1633 }
1634 unset($properties['customValue']);
1635 $formattedGroupTree[$key]['fields'][$k] = $properties;
1636 }
1637 }
1638
1639 if ($form) {
1640 // hack for field type File
1641 $formUploadNames = $form->get('uploadNames');
1642 if (is_array($formUploadNames)) {
1643 $uploadNames = array_unique(array_merge($formUploadNames, $uploadNames));
1644 }
1645
1646 $form->set('uploadNames', $uploadNames);
1647 }
1648
1649 return $formattedGroupTree;
1650 }
1651
1652 /**
1653 * Build custom data view
1654 * @param object $form page object
1655 * @param array $groupTree associated array
1656 * @param boolean $returnCount true if customValue count needs to be returned
1657 */
1658 static function buildCustomDataView(&$form, &$groupTree, $returnCount = FALSE, $gID = NULL, $prefix = NULL) {
1659 foreach ($groupTree as $key => $group) {
1660 if ($key === 'info') {
1661 continue;
1662 }
1663
1664 foreach ($group['fields'] as $k => $properties) {
1665 $groupID = $group['id'];
1666 if (!empty($properties['customValue'])) {
1667 foreach ($properties['customValue'] as $values) {
1668 $details[$groupID][$values['id']]['title'] = CRM_Utils_Array::value('title', $group);
1669 $details[$groupID][$values['id']]['name'] = CRM_Utils_Array::value('name', $group);
1670 $details[$groupID][$values['id']]['help_pre'] = CRM_Utils_Array::value('help_pre', $group);
1671 $details[$groupID][$values['id']]['help_post'] = CRM_Utils_Array::value('help_post', $group);
1672 $details[$groupID][$values['id']]['collapse_display'] = CRM_Utils_Array::value('collapse_display', $group);
1673 $details[$groupID][$values['id']]['collapse_adv_display'] = CRM_Utils_Array::value('collapse_adv_display', $group);
1674 $details[$groupID][$values['id']]['fields'][$k] = array('field_title' => CRM_Utils_Array::value('label', $properties),
1675 'field_type' => CRM_Utils_Array::value('html_type',
1676 $properties
1677 ),
1678 'field_data_type' => CRM_Utils_Array::value('data_type',
1679 $properties
1680 ),
1681 'field_value' => self::formatCustomValues($values,
1682 $properties
1683 ),
1684 'options_per_line' => CRM_Utils_Array::value('options_per_line',
1685 $properties
1686 ),
1687 );
1688 // also return contact reference contact id if user has view all or edit all contacts perm
1689 if ((CRM_Core_Permission::check('view all contacts') || CRM_Core_Permission::check('edit all contacts'))
1690 && $details[$groupID][$values['id']]['fields'][$k]['field_data_type'] == 'ContactReference'
1691 ) {
1692 $details[$groupID][$values['id']]['fields'][$k]['contact_ref_id'] = CRM_Utils_Array::value('data', $values);
1693 }
1694 }
1695 }
1696 else {
1697 $details[$groupID][0]['title'] = CRM_Utils_Array::value('title', $group);
1698 $details[$groupID][0]['name'] = CRM_Utils_Array::value('name', $group);
1699 $details[$groupID][0]['help_pre'] = CRM_Utils_Array::value('help_pre', $group);
1700 $details[$groupID][0]['help_post'] = CRM_Utils_Array::value('help_post', $group);
1701 $details[$groupID][0]['collapse_display'] = CRM_Utils_Array::value('collapse_display', $group);
1702 $details[$groupID][0]['collapse_adv_display'] = CRM_Utils_Array::value('collapse_adv_display', $group);
1703 $details[$groupID][0]['fields'][$k] = array('field_title' => CRM_Utils_Array::value('label', $properties));
1704 }
1705 }
1706 }
1707
1708 if ($returnCount) {
1709 //return a single value count if group id is passed to function
1710 //else return a groupId and count mapped array
1711 if (!empty($gID)){
1712 return count($details[$gID]);
1713 }
1714 else {
1715 foreach( $details as $key => $value ) {
1716 $countValue[$key] = count($details[$key]);
1717 }
1718 return $countValue;
1719 }
1720 }
1721 else {
1722 $form->assign_by_ref("{$prefix}viewCustomData", $details);
1723 return $details;
1724 }
1725 }
1726
1727 /**
1728 * Format custom value according to data, view mode
1729 *
1730 * @param array $values associated array of custom values
1731 * @param array $field associated array
1732 * @param boolean $dncOptionPerLine true if optionPerLine should not be consider
1733 *
1734 */
1735 static function formatCustomValues(&$values, &$field, $dncOptionPerLine = FALSE) {
1736 $value = $values['data'];
1737
1738 //changed isset CRM-4601
1739 if (CRM_Utils_System::isNull($value)) {
1740 return;
1741 }
1742
1743 $htmlType = CRM_Utils_Array::value('html_type', $field);
1744 $dataType = CRM_Utils_Array::value('data_type', $field);
1745 $option_group_id = CRM_Utils_Array::value('option_group_id', $field);
1746 $timeFormat = CRM_Utils_Array::value('time_format', $field);
1747 $optionPerLine = CRM_Utils_Array::value('options_per_line', $field);
1748
1749 $freezeString = "";
1750 $freezeStringChecked = "";
1751
1752 switch ($dataType) {
1753 case 'Date':
1754 $customTimeFormat = '';
1755 $customFormat = NULL;
1756
1757 switch ($timeFormat) {
1758 case 1:
1759 $customTimeFormat = '%l:%M %P';
1760 break;
1761
1762 case 2:
1763 $customTimeFormat = '%H:%M';
1764 break;
1765
1766 default:
1767 // if time is not selected remove time from value
1768 $value = substr($value, 0, 10);
1769 }
1770
1771 $supportableFormats = array(
1772 'mm/dd' => "%B %E%f $customTimeFormat",
1773 'dd-mm' => "%E%f %B $customTimeFormat",
1774 'yy' => "%Y $customTimeFormat",
1775 'M yy' => "%b %Y $customTimeFormat",
1776 'yy-mm' => "%Y-%m $customTimeFormat"
1777 );
1778
1779 if ($format = CRM_Utils_Array::value('date_format', $field)) {
1780 if (array_key_exists($format, $supportableFormats)) {
1781 $customFormat = $supportableFormats["$format"];
1782 }
1783 }
1784
1785 $retValue = CRM_Utils_Date::customFormat($value, $customFormat);
1786 break;
1787
1788 case 'Boolean':
1789 if ($value == '1') {
1790 $retValue = $freezeStringChecked . ts('Yes') . "\n";
1791 }
1792 else {
1793 $retValue = $freezeStringChecked . ts('No') . "\n";
1794 }
1795 break;
1796
1797 case 'Link':
1798 if ($value) {
1799 $retValue = CRM_Utils_System::formatWikiURL($value);
1800 }
1801 break;
1802
1803 case 'File':
1804 $retValue = $values;
1805 break;
1806
1807 case 'ContactReference':
1808 if (CRM_Utils_Array::value('data', $values)) {
1809 $retValue = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $values['data'], 'display_name');
1810 }
1811 break;
1812
1813 case 'Memo':
1814 $retValue = $value;
1815 break;
1816
1817 case 'Float':
1818 if ($htmlType == 'Text') {
1819 $retValue = (float)$value;
1820 break;
1821 }
1822 case 'Money':
1823 if ($htmlType == 'Text') {
1824 $retValue = CRM_Utils_Money::format($value, NULL, '%a');
1825 break;
1826 }
1827 case 'String':
1828 case 'Int':
1829 if (in_array($htmlType, array('Text', 'TextArea'))) {
1830 $retValue = $value;
1831 break;
1832 }
1833 // note that if its not text / textarea, the code falls thru and executes
1834 // the below case also
1835 case 'StateProvince':
1836 case 'Country':
1837 $options = array();
1838 $coDAO = NULL;
1839
1840 //added check for Multi-Select in the below if-statement
1841 $customData[] = $value;
1842
1843 //form custom data for multiple-valued custom data
1844 switch ($htmlType) {
1845 case 'Multi-Select Country':
1846 case 'Select Country':
1847 $customData = $value;
1848 if (!is_array($value)) {
1849 $customData = explode(CRM_Core_DAO::VALUE_SEPARATOR, $value);
1850 }
1851 $query = "
1852 SELECT id as value, name as label
1853 FROM civicrm_country";
1854 $coDAO = CRM_Core_DAO::executeQuery($query);
1855 break;
1856
1857 case 'Select State/Province':
1858 case 'Multi-Select State/Province':
1859 $customData = $value;
1860 if (!is_array($value)) {
1861 $customData = explode(CRM_Core_DAO::VALUE_SEPARATOR, $value);
1862 }
1863
1864 $query = "
1865 SELECT id as value, name as label
1866 FROM civicrm_state_province";
1867 $coDAO = CRM_Core_DAO::executeQuery($query);
1868 break;
1869
1870 case 'Select':
1871 $customData = explode(CRM_Core_DAO::VALUE_SEPARATOR, $value);
1872 if ($option_group_id) {
1873 $options = CRM_Core_BAO_OptionValue::getOptionValuesAssocArray($option_group_id);
1874 }
1875 break;
1876
1877 case 'CheckBox':
1878 case 'AdvMulti-Select':
1879 case 'Multi-Select':
1880 $customData = explode(CRM_Core_DAO::VALUE_SEPARATOR, $value);
1881 default:
1882 if ($option_group_id) {
1883 $options = CRM_Core_BAO_OptionValue::getOptionValuesAssocArray($option_group_id);
1884 }
1885 }
1886
1887 if (is_object($coDAO)) {
1888 while ($coDAO->fetch()) {
1889 $options[$coDAO->value] = $coDAO->label;
1890 }
1891 }
1892
1893 CRM_Utils_Hook::customFieldOptions($field['id'], $options, FALSE);
1894
1895 $retValue = NULL;
1896 foreach ($options as $optionValue => $optionLabel) {
1897 if ($dataType == 'Money') {
1898 foreach ($customData as $k => $v) {
1899 $customData[] = CRM_Utils_Money::format($v, NULL, '%a');
1900 }
1901 }
1902
1903 //to show only values that are checked
1904 if (in_array((string) $optionValue, $customData)) {
1905 $checked = in_array($optionValue, $customData) ? $freezeStringChecked : $freezeString;
1906 if (!$optionPerLine || $dncOptionPerLine) {
1907 if ($retValue) {
1908 $retValue .= ", ";
1909 }
1910 $retValue .= $checked . $optionLabel;
1911 }
1912 else {
1913 $retValue[] = $checked . $optionLabel;
1914 }
1915 }
1916 }
1917 break;
1918 }
1919
1920 //special case for option per line formatting
1921 if ($optionPerLine > 1 && is_array($retValue)) {
1922 $rowCounter = 0;
1923 $fieldCounter = 0;
1924 $displayValues = array();
1925 $displayString = '';
1926 foreach ($retValue as $val) {
1927 if ($displayString) {
1928 $displayString .= ", ";
1929 }
1930
1931 $displayString .= $val;
1932 $rowCounter++;
1933 $fieldCounter++;
1934
1935 if (($rowCounter == $optionPerLine) || ($fieldCounter == count($retValue))) {
1936 $displayValues[] = $displayString;
1937 $displayString = '';
1938 $rowCounter = 0;
1939 }
1940 }
1941 $retValue = $displayValues;
1942 }
1943
1944 $retValue = isset($retValue) ? $retValue : NULL;
1945 return $retValue;
1946 }
1947
1948 /**
1949 * Get the custom group titles by custom field ids.
1950 *
1951 * @param array $fieldIds - array of custom field ids.
1952 *
1953 * @return array $groupLabels - array consisting of groups and fields labels with ids.
1954 * @access public
1955 */
1956 public static function getGroupTitles($fieldIds) {
1957 if (!is_array($fieldIds) && empty($fieldIds)) {
1958 return;
1959 }
1960
1961 $groupLabels = array();
1962 $fIds = "(" . implode(',', $fieldIds) . ")";
1963
1964 $query = "
1965 SELECT civicrm_custom_group.id as groupID, civicrm_custom_group.title as groupTitle,
1966 civicrm_custom_field.label as fieldLabel, civicrm_custom_field.id as fieldID
1967 FROM civicrm_custom_group, civicrm_custom_field
1968 WHERE civicrm_custom_group.id = civicrm_custom_field.custom_group_id
1969 AND civicrm_custom_field.id IN {$fIds}";
1970
1971 $dao = CRM_Core_DAO::executeQuery($query);
1972 while ($dao->fetch()) {
1973 $groupLabels[$dao->fieldID] = array(
1974 'fieldID' => $dao->fieldID,
1975 'fieldLabel' => $dao->fieldLabel,
1976 'groupID' => $dao->groupID,
1977 'groupTitle' => $dao->groupTitle,
1978 );
1979 }
1980
1981 return $groupLabels;
1982 }
1983
1984 static function dropAllTables() {
1985 $query = "SELECT table_name FROM civicrm_custom_group";
1986 $dao = CRM_Core_DAO::executeQuery($query);
1987
1988 while ($dao->fetch()) {
1989 $query = "DROP TABLE IF EXISTS {$dao->table_name}";
1990 CRM_Core_DAO::executeQuery($query);
1991 }
1992 }
1993
1994 /**
1995 * Check whether custom group is empty or not.
1996 *
1997 * @param int $gID - custom group id.
1998 *
1999 * @return boolean true if empty otherwise false.
2000 * @access public
2001 */
2002 static function isGroupEmpty($gID) {
2003 if (!$gID) {
2004 return;
2005 }
2006
2007 $tableName = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomGroup',
2008 $gID,
2009 'table_name'
2010 );
2011
2012 $query = "SELECT count(id) FROM {$tableName} WHERE id IS NOT NULL LIMIT 1";
2013 $value = CRM_Core_DAO::singleValueQuery($query);
2014
2015 if (empty($value)) {
2016 return TRUE;
2017 }
2018
2019 return FALSE;
2020 }
2021
2022 /**
2023 * Get the list of types for objects that a custom group extends to.
2024 *
2025 * @param array $types - var which should have the list appended.
2026 *
2027 * @return array of types.
2028 * @access public
2029 */
2030 static function getExtendedObjectTypes(&$types = array( )) {
2031 static $flag = FALSE, $objTypes = array();
2032
2033 if (!$flag) {
2034 $extendObjs = array();
2035 CRM_Core_OptionValue::getValues(array('name' => 'cg_extend_objects'), $extendObjs);
2036
2037 foreach ($extendObjs as $ovId => $ovValues) {
2038 if ($ovValues['description']) {
2039 // description is expected to be a callback func to subtypes
2040 list($callback, $args) = explode(';', trim($ovValues['description']));
2041
2042 if (!empty($args)) {
2043 eval('$args = ' . $args . ';');
2044 }
2045 else {
2046 $args = array();
2047 }
2048
2049 if (!is_array($args)) {
2050 CRM_Core_Error::fatal('Arg is not of type array');
2051 }
2052
2053 list($className) = explode('::', $callback);
2054 require_once (str_replace('_',DIRECTORY_SEPARATOR, $className) . '.php');
2055
2056 $objTypes[$ovValues['value']] = call_user_func_array($callback, $args);
2057 }
2058 }
2059 $flag = TRUE;
2060 }
2061
2062 $types = array_merge($types, $objTypes);
2063 return $objTypes;
2064 }
2065
2066 function hasReachedMaxLimit($customGroupId, $entityId) {
2067 //check whether the group is multiple
2068 $isMultiple = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomGroup', $customGroupId, 'is_multiple');
2069 $isMultiple = ($isMultiple) ? TRUE : FALSE;
2070 $hasReachedMax = FALSE;
2071 if ($isMultiple &&
2072 ($maxMultiple = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomGroup', $customGroupId, 'max_multiple'))) {
2073 if (!$maxMultiple) {
2074 $hasReachedMax = FALSE;
2075 } else {
2076 $tableName = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomGroup', $customGroupId, 'table_name');
2077 //count the number of entries for a entity
2078 $sql = "SELECT COUNT(id) FROM {$tableName} WHERE entity_id = %1";
2079 $params = array(1 => array($entityId, 'Integer'));
2080 $count = CRM_Core_DAO::singleValueQuery($sql, $params);
2081
2082 if ($count >= $maxMultiple) {
2083 $hasReachedMax = TRUE;
2084 }
2085 }
2086 }
2087 return $hasReachedMax;
2088 }
2089
2090 }
2091