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