Commit | Line | Data |
---|---|---|
6a488035 TO |
1 | <?php |
2 | /* | |
3 | +--------------------------------------------------------------------+ | |
bc77d7c0 | 4 | | Copyright CiviCRM LLC. All rights reserved. | |
6a488035 | 5 | | | |
bc77d7c0 TO |
6 | | This work is published under the GNU AGPLv3 license with some | |
7 | | permitted exceptions and without any warranty. For full license | | |
8 | | and copyright information, see https://civicrm.org/licensing | | |
6a488035 | 9 | +--------------------------------------------------------------------+ |
d25dd0ee | 10 | */ |
6a488035 TO |
11 | |
12 | /** | |
13 | * | |
14 | * @package CRM | |
ca5cec67 | 15 | * @copyright CiviCRM LLC https://civicrm.org/licensing |
6a488035 TO |
16 | */ |
17 | ||
18 | /** | |
3a8f58ec | 19 | * Business object for managing custom data groups. |
6a488035 TO |
20 | */ |
21 | class CRM_Core_BAO_CustomGroup extends CRM_Core_DAO_CustomGroup { | |
22 | ||
6a488035 | 23 | /** |
fe482240 | 24 | * Takes an associative array and creates a custom group object. |
6a488035 TO |
25 | * |
26 | * This function is invoked from within the web form layer and also from the api layer | |
27 | * | |
6a0b768e TO |
28 | * @param array $params |
29 | * (reference) an assoc array of name/value pairs. | |
6a488035 | 30 | * |
16b10e64 | 31 | * @return CRM_Core_DAO_CustomGroup |
aa965915 | 32 | * @throws \Exception |
6a488035 | 33 | */ |
00be9182 | 34 | public static function create(&$params) { |
6a488035 TO |
35 | // create custom group dao, populate fields and then save. |
36 | $group = new CRM_Core_DAO_CustomGroup(); | |
117cc973 EM |
37 | if (isset($params['title'])) { |
38 | $group->title = $params['title']; | |
39 | } | |
6a488035 | 40 | |
9857487f | 41 | $extendsChildType = NULL; |
aa965915 | 42 | // lets allow user to pass direct child type value, CRM-6893 |
a7488080 | 43 | if (!empty($params['extends_entity_column_value'])) { |
6a488035 TO |
44 | $extendsChildType = $params['extends_entity_column_value']; |
45 | } | |
46 | if (!CRM_Utils_System::isNull($extendsChildType)) { | |
92ef7828 SL |
47 | $b = self::getMungedEntity($params['extends'], $params['extends_entity_column_id'] ?? NULL); |
48 | $registeredSubTypes = self::getSubTypes()[$b]; | |
13d328b3 SL |
49 | if (is_array($extendsChildType)) { |
50 | foreach ($extendsChildType as $childType) { | |
51 | if (!array_key_exists($childType, $registeredSubTypes) && !in_array($childType, $registeredSubTypes, TRUE)) { | |
52 | throw new CRM_Core_Exception('Supplied Sub type is not valid for the specified entitiy'); | |
53 | } | |
54 | } | |
55 | } | |
56 | else { | |
57 | if (!array_key_exists($extendsChildType, $registeredSubTypes) && !in_array($extendsChildType, $registeredSubTypes, TRUE)) { | |
58 | throw new CRM_Core_Exception('Supplied Sub type is not valid for the specified entitiy'); | |
59 | } | |
60 | $extendsChildType = [$extendsChildType]; | |
61 | } | |
9857487f SL |
62 | $extendsChildType = implode(CRM_Core_DAO::VALUE_SEPARATOR, $extendsChildType); |
63 | if ($params['extends'] == 'Relationship') { | |
be2fb01f | 64 | $extendsChildType = str_replace(['_a_b', '_b_a'], [ |
353ffa53 TO |
65 | '', |
66 | '', | |
be2fb01f | 67 | ], $extendsChildType); |
6a488035 TO |
68 | } |
69 | if (substr($extendsChildType, 0, 1) != CRM_Core_DAO::VALUE_SEPARATOR) { | |
9d72cede EM |
70 | $extendsChildType = CRM_Core_DAO::VALUE_SEPARATOR . $extendsChildType . |
71 | CRM_Core_DAO::VALUE_SEPARATOR; | |
6a488035 TO |
72 | } |
73 | } | |
74 | else { | |
75 | $extendsChildType = 'null'; | |
76 | } | |
77 | $group->extends_entity_column_value = $extendsChildType; | |
78 | ||
79 | if (isset($params['id'])) { | |
80 | $oldWeight = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomGroup', $params['id'], 'weight', 'id'); | |
81 | } | |
82 | else { | |
83 | $oldWeight = 0; | |
84 | } | |
85 | $group->weight = CRM_Utils_Weight::updateOtherWeights('CRM_Core_DAO_CustomGroup', $oldWeight, CRM_Utils_Array::value('weight', $params, FALSE)); | |
be2fb01f | 86 | $fields = [ |
9d72cede EM |
87 | 'style', |
88 | 'collapse_display', | |
89 | 'collapse_adv_display', | |
90 | 'help_pre', | |
91 | 'help_post', | |
92 | 'is_active', | |
21dfd5f5 | 93 | 'is_multiple', |
2af06525 | 94 | 'icon', |
9857487f SL |
95 | 'extends_entity_column_id', |
96 | 'extends', | |
be2fb01f | 97 | ]; |
da0577d8 CW |
98 | $current_db_version = CRM_Core_BAO_Domain::version(); |
99 | $is_public_version = version_compare($current_db_version, '4.7.19', '>='); | |
f7ed3a24 SL |
100 | if ($is_public_version) { |
101 | $fields[] = 'is_public'; | |
102 | } | |
6a488035 | 103 | foreach ($fields as $field) { |
e2cb881c MD |
104 | if (isset($params[$field])) { |
105 | $group->$field = $params[$field]; | |
117cc973 | 106 | } |
6a488035 TO |
107 | } |
108 | $group->max_multiple = isset($params['is_multiple']) ? (isset($params['max_multiple']) && | |
109 | $params['max_multiple'] >= '0' | |
110 | ) ? $params['max_multiple'] : 'null' : 'null'; | |
111 | ||
c746070e | 112 | $tableName = $tableNameNeedingIndexUpdate = NULL; |
6a488035 TO |
113 | if (isset($params['id'])) { |
114 | $group->id = $params['id']; | |
6a488035 | 115 | |
c746070e | 116 | if (isset($params['is_multiple'])) { |
aa965915 | 117 | // check whether custom group was changed from single-valued to multiple-valued |
c746070e | 118 | $isMultiple = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomGroup', |
6a488035 | 119 | $params['id'], |
c746070e | 120 | 'is_multiple' |
6a488035 | 121 | ); |
c746070e | 122 | |
1f85becb SL |
123 | // dev/core#227 Fix issue where is_multiple in params maybe an empty string if checkbox is not rendered on the form. |
124 | $paramsIsMultiple = empty($params['is_multiple']) ? 0 : 1; | |
125 | if ($paramsIsMultiple != $isMultiple) { | |
c746070e | 126 | $tableNameNeedingIndexUpdate = CRM_Core_DAO::getFieldValue( |
127 | 'CRM_Core_DAO_CustomGroup', | |
128 | $params['id'], | |
129 | 'table_name' | |
130 | ); | |
131 | } | |
6a488035 TO |
132 | } |
133 | } | |
134 | else { | |
9c1bc317 CW |
135 | $group->created_id = $params['created_id'] ?? NULL; |
136 | $group->created_date = $params['created_date'] ?? NULL; | |
6a488035 | 137 | |
e6766df9 CW |
138 | // Process name only during create, so it never changes |
139 | if (!empty($params['name'])) { | |
140 | $group->name = CRM_Utils_String::munge($params['name']); | |
6a488035 TO |
141 | } |
142 | else { | |
e6766df9 | 143 | $group->name = CRM_Utils_String::munge($group->title); |
6a488035 TO |
144 | } |
145 | ||
e6766df9 CW |
146 | self::validateCustomGroupName($group); |
147 | ||
8b3b9a2e ARW |
148 | if (isset($params['table_name'])) { |
149 | $tableName = $params['table_name']; | |
150 | ||
151 | if (CRM_Core_DAO_AllCoreTables::isCoreTable($tableName)) { | |
152 | // Bad idea. Prevent group creation because it might lead to a broken configuration. | |
36769590 | 153 | throw new CRM_Core_Exception(ts('Cannot create custom table because %1 is already a core table.', ['1' => $tableName])); |
8b3b9a2e ARW |
154 | } |
155 | } | |
6a488035 TO |
156 | } |
157 | ||
4e8506a4 | 158 | if (array_key_exists('is_reserved', $params)) { |
1155dd58 | 159 | $group->is_reserved = $params['is_reserved'] ? 1 : 0; |
f329e1de | 160 | } |
202f05c9 FG |
161 | $op = isset($params['id']) ? 'edit' : 'create'; |
162 | CRM_Utils_Hook::pre($op, 'CustomGroup', CRM_Utils_Array::value('id', $params), $params); | |
163 | ||
6a488035 TO |
164 | // enclose the below in a transaction |
165 | $transaction = new CRM_Core_Transaction(); | |
166 | ||
167 | $group->save(); | |
8b3b9a2e ARW |
168 | if (!isset($params['id'])) { |
169 | if (!isset($params['table_name'])) { | |
2caf0feb | 170 | $munged_title = strtolower(CRM_Utils_String::munge($group->title, '_', 13)); |
8b3b9a2e ARW |
171 | $tableName = "civicrm_value_{$munged_title}_{$group->id}"; |
172 | } | |
6a488035 TO |
173 | $group->table_name = $tableName; |
174 | CRM_Core_DAO::setFieldValue('CRM_Core_DAO_CustomGroup', | |
175 | $group->id, | |
176 | 'table_name', | |
177 | $tableName | |
178 | ); | |
179 | ||
180 | // now create the table associated with this group | |
181 | self::createTable($group); | |
182 | } | |
c746070e | 183 | elseif ($tableNameNeedingIndexUpdate) { |
184 | CRM_Core_BAO_SchemaHandler::changeUniqueToIndex($tableNameNeedingIndexUpdate, CRM_Utils_Array::value('is_multiple', $params)); | |
6a488035 TO |
185 | } |
186 | ||
187 | if (CRM_Utils_Array::value('overrideFKConstraint', $params) == 1) { | |
188 | $table = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomGroup', | |
189 | $params['id'], | |
190 | 'table_name' | |
191 | ); | |
9857487f | 192 | CRM_Core_BAO_SchemaHandler::changeFKConstraint($table, self::mapTableName($params['extends'])); |
6a488035 TO |
193 | } |
194 | $transaction->commit(); | |
195 | ||
196 | // reset the cache | |
197 | CRM_Utils_System::flushCache(); | |
198 | ||
199 | if ($tableName) { | |
200 | CRM_Utils_Hook::post('create', 'CustomGroup', $group->id, $group); | |
201 | } | |
202 | else { | |
203 | CRM_Utils_Hook::post('edit', 'CustomGroup', $group->id, $group); | |
204 | } | |
205 | ||
206 | return $group; | |
207 | } | |
208 | ||
209 | /** | |
4f940304 | 210 | * Retrieve DB object and copy to defaults array. |
6a488035 | 211 | * |
6a0b768e | 212 | * @param array $params |
4f940304 | 213 | * Array of criteria values. |
6a0b768e | 214 | * @param array $defaults |
4f940304 | 215 | * Array to be populated with found values. |
6a488035 | 216 | * |
4f940304 CW |
217 | * @return self|null |
218 | * The DAO object, if found. | |
219 | * | |
220 | * @deprecated | |
6a488035 | 221 | */ |
4f940304 CW |
222 | public static function retrieve($params, &$defaults) { |
223 | return self::commonRetrieve(self::class, $params, $defaults); | |
6a488035 TO |
224 | } |
225 | ||
e6766df9 CW |
226 | /** |
227 | * Ensure group name does not conflict with an existing field | |
228 | * | |
229 | * @param CRM_Core_DAO_CustomGroup $group | |
230 | */ | |
231 | public static function validateCustomGroupName(CRM_Core_DAO_CustomGroup $group) { | |
232 | $extends = in_array($group->extends, CRM_Contact_BAO_ContactType::basicTypes(TRUE)) ? 'Contact' : $group->extends; | |
233 | $extendsDAO = CRM_Core_DAO_AllCoreTables::getFullName($extends); | |
234 | if ($extendsDAO) { | |
235 | $fields = array_column($extendsDAO::fields(), 'name'); | |
236 | if (in_array($group->name, $fields)) { | |
237 | $group->name .= '0'; | |
238 | } | |
239 | } | |
240 | } | |
241 | ||
6a488035 | 242 | /** |
fe482240 | 243 | * Update the is_active flag in the db. |
6a488035 | 244 | * |
6a0b768e TO |
245 | * @param int $id |
246 | * Id of the database record. | |
a1a2a83d | 247 | * @param bool $is_active |
6a0b768e | 248 | * Value we want to set the is_active field. |
6a488035 | 249 | * |
8a4fede3 | 250 | * @return bool |
251 | * true if we found and updated the object, else false | |
6a488035 | 252 | */ |
00be9182 | 253 | public static function setIsActive($id, $is_active) { |
6a488035 | 254 | // reset the cache |
9cdf85c1 | 255 | Civi::cache('fields')->flush(); |
5e601882 SL |
256 | // reset ACL and system caches. |
257 | CRM_Core_BAO_Cache::resetCaches(); | |
6a488035 TO |
258 | |
259 | if (!$is_active) { | |
260 | CRM_Core_BAO_UFField::setUFFieldStatus($id, $is_active); | |
261 | } | |
262 | ||
263 | return CRM_Core_DAO::setFieldValue('CRM_Core_DAO_CustomGroup', $id, 'is_active', $is_active); | |
264 | } | |
265 | ||
266 | /** | |
267 | * Determine if given entity (sub)type has any custom groups | |
268 | * | |
6a0b768e TO |
269 | * @param string $extends |
270 | * E.g. "Individual", "Activity". | |
271 | * @param int $columnId | |
272 | * E.g. custom-group matching mechanism (usu NULL for matching on sub type-id); see extends_entity_column_id. | |
273 | * @param string $columnValue | |
274 | * E.g. "Student" or "3" or "3\05"; see extends_entity_column_value. | |
77b97be7 EM |
275 | * |
276 | * @return bool | |
6a488035 TO |
277 | */ |
278 | public static function hasCustomGroup($extends, $columnId, $columnValue) { | |
279 | $dao = new CRM_Core_DAO_CustomGroup(); | |
9d72cede | 280 | $dao->extends = $extends; |
6a488035 | 281 | $dao->extends_entity_column_id = $columnId; |
6c552737 | 282 | $escapedValue = CRM_Core_DAO::VALUE_SEPARATOR . CRM_Core_DAO::escapeString($columnValue) . CRM_Core_DAO::VALUE_SEPARATOR; |
6a488035 TO |
283 | $dao->whereAdd("extends_entity_column_value LIKE \"%$escapedValue%\""); |
284 | //$dao->extends_entity_column_value = $columnValue; | |
63d76404 | 285 | return (bool) $dao->find(); |
6a488035 TO |
286 | } |
287 | ||
288 | /** | |
289 | * Determine if there are any CustomGroups for the given $activityTypeId. | |
290 | * If none found, create one. | |
291 | * | |
292 | * @param int $activityTypeId | |
9d72cede | 293 | * |
a6c01b45 CW |
294 | * @return bool |
295 | * TRUE if a group is found or created; FALSE on error | |
6a488035 TO |
296 | */ |
297 | public static function autoCreateByActivityType($activityTypeId) { | |
298 | if (self::hasCustomGroup('Activity', NULL, $activityTypeId)) { | |
299 | return TRUE; | |
300 | } | |
cf9ccf98 TO |
301 | // everything |
302 | $activityTypes = CRM_Core_PseudoConstant::activityType(TRUE, TRUE, FALSE, 'label', TRUE, FALSE); | |
be2fb01f | 303 | $params = [ |
6a488035 TO |
304 | 'version' => 3, |
305 | 'extends' => 'Activity', | |
306 | 'extends_entity_column_id' => NULL, | |
be2fb01f CW |
307 | 'extends_entity_column_value' => CRM_Utils_Array::implodePadded([$activityTypeId]), |
308 | 'title' => ts('%1 Questions', [1 => $activityTypes[$activityTypeId]]), | |
6a488035 TO |
309 | 'style' => 'Inline', |
310 | 'is_active' => 1, | |
be2fb01f | 311 | ]; |
6a488035 | 312 | $result = civicrm_api('CustomGroup', 'create', $params); |
9d72cede | 313 | return !$result['is_error']; |
6a488035 TO |
314 | } |
315 | ||
316 | /** | |
c43cedc8 | 317 | * Get custom groups/fields data for type of entity in a tree structure representing group->field hierarchy |
318 | * This may also include entity specific data values. | |
6a488035 TO |
319 | * |
320 | * An array containing all custom groups and their custom fields is returned. | |
321 | * | |
6a0b768e TO |
322 | * @param string $entityType |
323 | * Of the contact whose contact type is needed. | |
0b330e6d CW |
324 | * @param array $toReturn |
325 | * What data should be returned. ['custom_group' => ['id', 'name', etc.], 'custom_field' => ['id', 'label', etc.]] | |
c490a46a CW |
326 | * @param int $entityID |
327 | * @param int $groupID | |
79363422 | 328 | * @param array $subTypes |
c43cedc8 | 329 | * @param string $subName |
c490a46a CW |
330 | * @param bool $fromCache |
331 | * @param bool $onlySubType | |
b62bc939 EM |
332 | * Only return specified subtype or return specified subtype + unrestricted fields. |
333 | * @param bool $returnAll | |
334 | * Do not restrict by subtype at all. (The parameter feels a bit cludgey but is only used from the | |
335 | * api - through which it is properly tested - so can be refactored with some comfort.) | |
317103ab CW |
336 | * @param bool|int $checkPermission |
337 | * Either a CRM_Core_Permission constant or FALSE to disable checks | |
0b330e6d | 338 | * @param string|int $singleRecord |
e1d48b72 | 339 | * holds 'new' or id if view/edit/copy form for a single record is being loaded. |
460931ca | 340 | * @param bool $showPublicOnly |
e9ff5391 | 341 | * |
a6c01b45 | 342 | * @return array |
e9ff5391 | 343 | * Custom field 'tree'. |
344 | * | |
16b10e64 CW |
345 | * The returned array is keyed by group id and has the custom group table fields |
346 | * and a subkey 'fields' holding the specific custom fields. | |
347 | * If entityId is passed in the fields keys have a subkey 'customValue' which holds custom data | |
348 | * if set for the given entity. This is structured as an array of values with each one having the keys 'id', 'data' | |
c43cedc8 | 349 | * |
350 | * @todo - review this - It also returns an array called 'info' with tables, select, from, where keys | |
16b10e64 CW |
351 | * The reason for the info array in unclear and it could be determined from parsing the group tree after creation |
352 | * With caching the performance impact would be small & the function would be cleaner | |
aa965915 MWMC |
353 | * |
354 | * @throws \CRM_Core_Exception | |
6a488035 | 355 | */ |
27dd6252 | 356 | public static function getTree( |
0e6e8724 | 357 | $entityType, |
be2fb01f | 358 | $toReturn = [], |
6a488035 | 359 | $entityID = NULL, |
9d72cede | 360 | $groupID = NULL, |
be2fb01f | 361 | $subTypes = [], |
9d72cede | 362 | $subName = NULL, |
63dbed83 | 363 | $fromCache = TRUE, |
b62bc939 | 364 | $onlySubType = NULL, |
e9ff5391 | 365 | $returnAll = FALSE, |
317103ab | 366 | $checkPermission = CRM_Core_Permission::EDIT, |
460931ca JP |
367 | $singleRecord = NULL, |
368 | $showPublicOnly = FALSE | |
6a488035 | 369 | ) { |
317103ab CW |
370 | if ($checkPermission === TRUE) { |
371 | CRM_Core_Error::deprecatedWarning('Unexpected TRUE passed to CustomGroup::getTree $checkPermission param.'); | |
372 | $checkPermission = CRM_Core_Permission::EDIT; | |
373 | } | |
6a488035 TO |
374 | if ($entityID) { |
375 | $entityID = CRM_Utils_Type::escape($entityID, 'Integer'); | |
376 | } | |
79363422 E |
377 | if (!is_array($subTypes)) { |
378 | if (empty($subTypes)) { | |
be2fb01f | 379 | $subTypes = []; |
79363422 E |
380 | } |
381 | else { | |
45e5c872 | 382 | if (stristr($subTypes, ',')) { |
35e83f39 | 383 | $subTypes = explode(',', $subTypes); |
384 | } | |
385 | else { | |
386 | $subTypes = explode(CRM_Core_DAO::VALUE_SEPARATOR, trim($subTypes, CRM_Core_DAO::VALUE_SEPARATOR)); | |
387 | } | |
79363422 E |
388 | } |
389 | } | |
6a488035 TO |
390 | |
391 | // create a new tree | |
6a488035 | 392 | |
0b330e6d | 393 | // legacy hardcoded list of data to return |
be2fb01f CW |
394 | $tableData = [ |
395 | 'custom_field' => [ | |
6a488035 | 396 | 'id', |
24871985 | 397 | 'name', |
6a488035 TO |
398 | 'label', |
399 | 'column_name', | |
400 | 'data_type', | |
401 | 'html_type', | |
402 | 'default_value', | |
403 | 'attributes', | |
404 | 'is_required', | |
405 | 'is_view', | |
406 | 'help_pre', | |
407 | 'help_post', | |
408 | 'options_per_line', | |
409 | 'start_date_years', | |
410 | 'end_date_years', | |
411 | 'date_format', | |
412 | 'time_format', | |
413 | 'option_group_id', | |
21dfd5f5 | 414 | 'in_selector', |
be2fb01f CW |
415 | ], |
416 | 'custom_group' => [ | |
6a488035 TO |
417 | 'id', |
418 | 'name', | |
419 | 'table_name', | |
420 | 'title', | |
421 | 'help_pre', | |
422 | 'help_post', | |
423 | 'collapse_display', | |
f6ad11c1 | 424 | 'style', |
6a488035 TO |
425 | 'is_multiple', |
426 | 'extends', | |
427 | 'extends_entity_column_id', | |
428 | 'extends_entity_column_value', | |
429 | 'max_multiple', | |
be2fb01f CW |
430 | ], |
431 | ]; | |
da0577d8 CW |
432 | $current_db_version = CRM_Core_BAO_Domain::version(); |
433 | $is_public_version = version_compare($current_db_version, '4.7.19', '>='); | |
434 | $serialize_version = version_compare($current_db_version, '5.27.alpha1', '>='); | |
f7ed3a24 SL |
435 | if ($is_public_version) { |
436 | $tableData['custom_group'][] = 'is_public'; | |
437 | } | |
da0577d8 CW |
438 | if ($serialize_version) { |
439 | $tableData['custom_field'][] = 'serialize'; | |
440 | } | |
0b330e6d CW |
441 | if (!$toReturn || !is_array($toReturn)) { |
442 | $toReturn = $tableData; | |
443 | } | |
444 | else { | |
ee21211c CW |
445 | // Supply defaults and remove unknown array keys |
446 | $toReturn = array_intersect_key(array_filter($toReturn) + $tableData, $tableData); | |
0b330e6d | 447 | // Merge in required fields that we must have |
be2fb01f CW |
448 | $toReturn['custom_field'] = array_unique(array_merge($toReturn['custom_field'], ['id', 'column_name', 'data_type'])); |
449 | $toReturn['custom_group'] = array_unique(array_merge($toReturn['custom_group'], ['id', 'is_multiple', 'table_name', 'name'])); | |
0b330e6d CW |
450 | // Validate return fields |
451 | $toReturn['custom_field'] = array_intersect($toReturn['custom_field'], array_keys(CRM_Core_DAO_CustomField::fieldKeys())); | |
452 | $toReturn['custom_group'] = array_intersect($toReturn['custom_group'], array_keys(CRM_Core_DAO_CustomGroup::fieldKeys())); | |
453 | } | |
6a488035 TO |
454 | |
455 | // create select | |
be2fb01f | 456 | $select = []; |
0b330e6d | 457 | foreach ($toReturn as $tableName => $tableColumn) { |
6a488035 | 458 | foreach ($tableColumn as $columnName) { |
0b330e6d | 459 | $select[] = "civicrm_{$tableName}.{$columnName} as civicrm_{$tableName}_{$columnName}"; |
6a488035 TO |
460 | } |
461 | } | |
462 | $strSelect = "SELECT " . implode(', ', $select); | |
463 | ||
464 | // from, where, order by | |
465 | $strFrom = " | |
466 | FROM civicrm_custom_group | |
467 | LEFT JOIN civicrm_custom_field ON (civicrm_custom_field.custom_group_id = civicrm_custom_group.id) | |
468 | "; | |
469 | ||
470 | // if entity is either individual, organization or household pls get custom groups for 'contact' too. | |
9d72cede EM |
471 | if ($entityType == "Individual" || $entityType == 'Organization' || |
472 | $entityType == 'Household' | |
473 | ) { | |
6a488035 TO |
474 | $in = "'$entityType', 'Contact'"; |
475 | } | |
476 | elseif (strpos($entityType, "'") !== FALSE) { | |
477 | // this allows the calling function to send in multiple entity types | |
478 | $in = $entityType; | |
479 | } | |
480 | else { | |
481 | // quote it | |
482 | $in = "'$entityType'"; | |
483 | } | |
484 | ||
be2fb01f | 485 | $params = []; |
babf3eef | 486 | $sqlParamKey = 1; |
b2ccd9fe | 487 | $subType = ''; |
79363422 E |
488 | if (!empty($subTypes)) { |
489 | foreach ($subTypes as $key => $subType) { | |
8cefa956 | 490 | $subTypeClauses[] = self::whereListHas("civicrm_custom_group.extends_entity_column_value", self::validateSubTypeByEntity($entityType, $subType)); |
6a488035 | 491 | } |
cf9ccf98 | 492 | $subTypeClause = '(' . implode(' OR ', $subTypeClauses) . ')'; |
79363422 E |
493 | if (!$onlySubType) { |
494 | $subTypeClause = '(' . $subTypeClause . ' OR civicrm_custom_group.extends_entity_column_value IS NULL )'; | |
993c3848 CB |
495 | } |
496 | ||
6a488035 TO |
497 | $strWhere = " |
498 | WHERE civicrm_custom_group.is_active = 1 | |
499 | AND civicrm_custom_field.is_active = 1 | |
500 | AND civicrm_custom_group.extends IN ($in) | |
501 | AND $subTypeClause | |
502 | "; | |
503 | if ($subName) { | |
babf3eef | 504 | $strWhere .= " AND civicrm_custom_group.extends_entity_column_id = %{$sqlParamKey}"; |
be2fb01f | 505 | $params[$sqlParamKey] = [$subName, 'String']; |
babf3eef | 506 | $sqlParamKey = $sqlParamKey + 1; |
6a488035 TO |
507 | } |
508 | } | |
509 | else { | |
510 | $strWhere = " | |
511 | WHERE civicrm_custom_group.is_active = 1 | |
512 | AND civicrm_custom_field.is_active = 1 | |
513 | AND civicrm_custom_group.extends IN ($in) | |
6a488035 | 514 | "; |
b62bc939 EM |
515 | if (!$returnAll) { |
516 | $strWhere .= "AND civicrm_custom_group.extends_entity_column_value IS NULL"; | |
517 | } | |
6a488035 TO |
518 | } |
519 | ||
6a488035 TO |
520 | if ($groupID > 0) { |
521 | // since we want a specific group id we add it to the where clause | |
babf3eef | 522 | $strWhere .= " AND civicrm_custom_group.id = %{$sqlParamKey}"; |
be2fb01f | 523 | $params[$sqlParamKey] = [$groupID, 'Integer']; |
6a488035 TO |
524 | } |
525 | elseif (!$groupID) { | |
526 | // since groupID is false we need to show all Inline groups | |
527 | $strWhere .= " AND civicrm_custom_group.style = 'Inline'"; | |
528 | } | |
e9ff5391 | 529 | if ($checkPermission) { |
530 | // ensure that the user has access to these custom groups | |
531 | $strWhere .= " AND " . | |
317103ab | 532 | CRM_Core_Permission::customGroupClause($checkPermission, |
e9ff5391 | 533 | 'civicrm_custom_group.' |
534 | ); | |
535 | } | |
6a488035 | 536 | |
f7ed3a24 | 537 | if ($showPublicOnly && $is_public_version) { |
460931ca JP |
538 | $strWhere .= "AND civicrm_custom_group.is_public = 1"; |
539 | } | |
540 | ||
6a488035 TO |
541 | $orderBy = " |
542 | ORDER BY civicrm_custom_group.weight, | |
543 | civicrm_custom_group.title, | |
544 | civicrm_custom_field.weight, | |
545 | civicrm_custom_field.label | |
546 | "; | |
547 | ||
548 | // final query string | |
549 | $queryString = "$strSelect $strFrom $strWhere $orderBy"; | |
550 | ||
551 | // lets see if we can retrieve the groupTree from cache | |
552 | $cacheString = $queryString; | |
9d72cede | 553 | if ($groupID > 0) { |
6a488035 | 554 | $cacheString .= "_{$groupID}"; |
9d72cede EM |
555 | } |
556 | else { | |
6a488035 TO |
557 | $cacheString .= "_Inline"; |
558 | } | |
559 | ||
560 | $cacheKey = "CRM_Core_DAO_CustomGroup_Query " . md5($cacheString); | |
6c552737 | 561 | $multipleFieldGroupCacheKey = "CRM_Core_DAO_CustomGroup_QueryMultipleFields " . md5($cacheString); |
6a488035 | 562 | $cache = CRM_Utils_Cache::singleton(); |
6a488035 TO |
563 | if ($fromCache) { |
564 | $groupTree = $cache->get($cacheKey); | |
c43cedc8 | 565 | $multipleFieldGroups = $cache->get($multipleFieldGroupCacheKey); |
6a488035 TO |
566 | } |
567 | ||
568 | if (empty($groupTree)) { | |
b2ccd9fe | 569 | list($multipleFieldGroups, $groupTree) = self::buildGroupTree($entityType, $toReturn, $subTypes, $queryString, $params, $subType); |
6a488035 TO |
570 | |
571 | $cache->set($cacheKey, $groupTree); | |
c43cedc8 | 572 | $cache->set($multipleFieldGroupCacheKey, $multipleFieldGroups); |
6a488035 | 573 | } |
aa965915 | 574 | // entitySelectClauses is an array of select clauses for custom value tables which are not multiple |
c43cedc8 | 575 | // and have data for the given entities. $entityMultipleSelectClauses is the same for ones with multiple |
be2fb01f CW |
576 | $entitySingleSelectClauses = $entityMultipleSelectClauses = $groupTree['info']['select'] = []; |
577 | $singleFieldTables = []; | |
6a488035 TO |
578 | // now that we have all the groups and fields, lets get the values |
579 | // since we need to know the table and field names | |
6a488035 | 580 | // add info to groupTree |
c43cedc8 | 581 | |
9d72cede | 582 | if (isset($groupTree['info']) && !empty($groupTree['info']) && |
e1d48b72 | 583 | !empty($groupTree['info']['tables']) && $singleRecord != 'new' |
9d72cede | 584 | ) { |
be2fb01f | 585 | $select = $from = $where = []; |
c43cedc8 | 586 | $groupTree['info']['where'] = NULL; |
6a488035 | 587 | |
c43cedc8 | 588 | foreach ($groupTree['info']['tables'] as $table => $fields) { |
9d72cede | 589 | $groupTree['info']['from'][] = $table; |
be2fb01f | 590 | $select = [ |
9d72cede | 591 | "{$table}.id as {$table}_id", |
21dfd5f5 | 592 | "{$table}.entity_id as {$table}_entity_id", |
be2fb01f | 593 | ]; |
6a488035 TO |
594 | foreach ($fields as $column => $dontCare) { |
595 | $select[] = "{$table}.{$column} as {$table}_{$column}"; | |
596 | } | |
c43cedc8 | 597 | $groupTree['info']['select'] = array_merge($groupTree['info']['select'], $select); |
6a488035 | 598 | if ($entityID) { |
c43cedc8 | 599 | $groupTree['info']['where'][] = "{$table}.entity_id = $entityID"; |
9d72cede EM |
600 | if (in_array($table, $multipleFieldGroups) && |
601 | self::customGroupDataExistsForEntity($entityID, $table) | |
602 | ) { | |
c43cedc8 | 603 | $entityMultipleSelectClauses[$table] = $select; |
604 | } | |
9d72cede | 605 | else { |
c43cedc8 | 606 | $singleFieldTables[] = $table; |
607 | $entitySingleSelectClauses = array_merge($entitySingleSelectClauses, $select); | |
608 | } | |
609 | ||
6a488035 TO |
610 | } |
611 | } | |
c43cedc8 | 612 | if ($entityID && !empty($singleFieldTables)) { |
e8cb3963 | 613 | self::buildEntityTreeSingleFields($groupTree, $entityID, $entitySingleSelectClauses, $singleFieldTables); |
c43cedc8 | 614 | } |
615 | $multipleFieldTablesWithEntityData = array_keys($entityMultipleSelectClauses); | |
9d72cede | 616 | if (!empty($multipleFieldTablesWithEntityData)) { |
e1d48b72 | 617 | self::buildEntityTreeMultipleFields($groupTree, $entityID, $entityMultipleSelectClauses, $multipleFieldTablesWithEntityData, $singleRecord); |
c43cedc8 | 618 | } |
6a488035 | 619 | |
9d72cede | 620 | } |
c43cedc8 | 621 | return $groupTree; |
622 | } | |
6a488035 | 623 | |
79363422 E |
624 | /** |
625 | * Clean and validate the filter before it is used in a db query. | |
626 | * | |
627 | * @param string $entityType | |
628 | * @param string $subType | |
629 | * | |
630 | * @return string | |
631 | * @throws \CRM_Core_Exception | |
79363422 E |
632 | */ |
633 | protected static function validateSubTypeByEntity($entityType, $subType) { | |
634 | $subType = trim($subType, CRM_Core_DAO::VALUE_SEPARATOR); | |
635 | if (is_numeric($subType)) { | |
636 | return $subType; | |
637 | } | |
93ecb8e8 | 638 | |
639 | $contactTypes = CRM_Contact_BAO_ContactType::basicTypeInfo(TRUE); | |
be2fb01f | 640 | $contactTypes = array_merge($contactTypes, ['Event' => 1]); |
2072f97d | 641 | |
93ecb8e8 | 642 | if ($entityType != 'Contact' && !array_key_exists($entityType, $contactTypes)) { |
79363422 E |
643 | throw new CRM_Core_Exception('Invalid Entity Filter'); |
644 | } | |
93ecb8e8 | 645 | $subTypes = CRM_Contact_BAO_ContactType::subTypeInfo($entityType, TRUE); |
2072f97d | 646 | $subTypes = array_merge($subTypes, CRM_Event_PseudoConstant::eventType()); |
93ecb8e8 | 647 | if (!array_key_exists($subType, $subTypes)) { |
79363422 E |
648 | throw new CRM_Core_Exception('Invalid Filter'); |
649 | } | |
650 | return $subType; | |
651 | } | |
652 | ||
8cefa956 TO |
653 | /** |
654 | * Suppose you have a SQL column, $column, which includes a delimited list, and you want | |
655 | * a WHERE condition for rows that include $value. Use whereListHas(). | |
656 | * | |
657 | * @param string $column | |
658 | * @param string $value | |
659 | * @param string $delimiter | |
660 | * @return string | |
661 | * SQL condition. | |
662 | */ | |
518fa0ee | 663 | private static function whereListHas($column, $value, $delimiter = CRM_Core_DAO::VALUE_SEPARATOR) { |
cf9ccf98 TO |
664 | // ? |
665 | $bareValue = trim($value, $delimiter); | |
8cefa956 TO |
666 | $escapedValue = CRM_Utils_Type::escape("%{$delimiter}{$bareValue}{$delimiter}%", 'String', FALSE); |
667 | return "($column LIKE \"$escapedValue\")"; | |
668 | } | |
669 | ||
c43cedc8 | 670 | /** |
671 | * Check whether the custom group has any data for the given entity. | |
672 | * | |
6a0b768e TO |
673 | * @param int $entityID |
674 | * Id of entity for whom we are checking data for. | |
675 | * @param string $table | |
676 | * Table that we are checking. | |
c43cedc8 | 677 | * |
2a6da8d7 EM |
678 | * @param bool $getCount |
679 | * | |
5c766a0b | 680 | * @return bool |
a6c01b45 | 681 | * does this entity have data in this custom table |
c43cedc8 | 682 | */ |
518fa0ee | 683 | public static function customGroupDataExistsForEntity($entityID, $table, $getCount = FALSE) { |
c43cedc8 | 684 | $query = " |
685 | SELECT count(id) | |
686 | FROM $table | |
687 | WHERE entity_id = $entityID | |
688 | "; | |
689 | $recordExists = CRM_Core_DAO::singleValueQuery($query); | |
bf076628 PJ |
690 | if ($getCount) { |
691 | return $recordExists; | |
692 | } | |
63d76404 | 693 | return (bool) $recordExists; |
c43cedc8 | 694 | } |
6a488035 | 695 | |
9d72cede EM |
696 | /** |
697 | * Build the group tree for Custom fields which are not 'is_multiple' | |
698 | * | |
699 | * The combination of all these fields in one query with a 'using' join was not working for | |
700 | * multiple fields. These now have a new behaviour (one at a time) but the single fields still use this | |
701 | * mechanism as it seemed to be acceptable in this context | |
702 | * | |
6a0b768e TO |
703 | * @param array $groupTree |
704 | * (reference) group tree array which is being built. | |
705 | * @param int $entityID | |
706 | * Id of entity for whom the tree is being build up. | |
707 | * @param array $entitySingleSelectClauses | |
708 | * Array of select clauses relevant to the entity. | |
709 | * @param array $singleFieldTablesWithEntityData | |
710 | * Array of tables in which this entity has data. | |
9d72cede | 711 | */ |
518fa0ee | 712 | public static function buildEntityTreeSingleFields(&$groupTree, $entityID, $entitySingleSelectClauses, $singleFieldTablesWithEntityData) { |
c43cedc8 | 713 | $select = implode(', ', $entitySingleSelectClauses); |
714 | $fromSQL = " (SELECT $entityID as entity_id ) as first "; | |
715 | foreach ($singleFieldTablesWithEntityData as $table) { | |
716 | $fromSQL .= "\nLEFT JOIN $table USING (entity_id)"; | |
717 | } | |
6a488035 | 718 | |
c43cedc8 | 719 | $query = " |
720 | SELECT $select | |
721 | FROM $fromSQL | |
722 | WHERE first.entity_id = $entityID | |
723 | "; | |
e8cb3963 | 724 | self::buildTreeEntityDataFromQuery($groupTree, $query, $singleFieldTablesWithEntityData); |
c43cedc8 | 725 | } |
6a488035 | 726 | |
c43cedc8 | 727 | /** |
9d72cede EM |
728 | * Build the group tree for Custom fields which are 'is_multiple' |
729 | * | |
730 | * This is done one table at a time to avoid Cross-Joins resulting in too many rows being returned | |
731 | * | |
6a0b768e TO |
732 | * @param array $groupTree |
733 | * (reference) group tree array which is being built. | |
734 | * @param int $entityID | |
735 | * Id of entity for whom the tree is being build up. | |
736 | * @param array $entityMultipleSelectClauses | |
737 | * Array of select clauses relevant to the entity. | |
738 | * @param array $multipleFieldTablesWithEntityData | |
739 | * Array of tables in which this entity has data. | |
aa965915 | 740 | * @param string|int $singleRecord |
e1d48b72 | 741 | * holds 'new' or id if view/edit/copy form for a single record is being loaded. |
9d72cede | 742 | */ |
518fa0ee | 743 | public static function buildEntityTreeMultipleFields(&$groupTree, $entityID, $entityMultipleSelectClauses, $multipleFieldTablesWithEntityData, $singleRecord = NULL) { |
c43cedc8 | 744 | foreach ($entityMultipleSelectClauses as $table => $selectClauses) { |
745 | $select = implode(',', $selectClauses); | |
746 | $query = " | |
747 | SELECT $select | |
748 | FROM $table | |
749 | WHERE entity_id = $entityID | |
750 | "; | |
e1d48b72 | 751 | if ($singleRecord) { |
752 | $offset = $singleRecord - 1; | |
753 | $query .= " LIMIT {$offset}, 1"; | |
754 | } | |
be2fb01f | 755 | self::buildTreeEntityDataFromQuery($groupTree, $query, [$table], $singleRecord); |
c43cedc8 | 756 | } |
757 | } | |
758 | ||
759 | /** | |
760 | * Build the tree entity data - starting from a query retrieving the custom fields build the group | |
761 | * tree data for the relevant entity (entity is included in the query). | |
762 | * | |
763 | * This function represents shared code between the buildEntityTreeMultipleFields & the buildEntityTreeSingleFields function | |
764 | * | |
6a0b768e TO |
765 | * @param array $groupTree |
766 | * (reference) group tree array which is being built. | |
c43cedc8 | 767 | * @param string $query |
6a0b768e TO |
768 | * @param array $includedTables |
769 | * Tables to include - required because the function (for historical reasons). | |
16b10e64 | 770 | * iterates through the group tree |
aa965915 | 771 | * @param string|int $singleRecord |
e1d48b72 | 772 | * holds 'new' OR id if view/edit/copy form for a single record is being loaded. |
c43cedc8 | 773 | */ |
518fa0ee | 774 | public static function buildTreeEntityDataFromQuery(&$groupTree, $query, $includedTables, $singleRecord = NULL) { |
c43cedc8 | 775 | $dao = CRM_Core_DAO::executeQuery($query); |
776 | while ($dao->fetch()) { | |
777 | foreach ($groupTree as $groupID => $group) { | |
778 | if ($groupID === 'info') { | |
779 | continue; | |
780 | } | |
781 | $table = $groupTree[$groupID]['table_name']; | |
782 | //working from the groupTree instead of the table list means we have to iterate & exclude. | |
783 | // this could possibly be re-written as other parts of the function have been refactored | |
784 | // for now we just check if the given table is to be included in this function | |
9d72cede | 785 | if (!in_array($table, $includedTables)) { |
c43cedc8 | 786 | continue; |
787 | } | |
788 | foreach ($group['fields'] as $fieldID => $dontCare) { | |
e1d48b72 | 789 | self::buildCustomFieldData($dao, $groupTree, $table, $groupID, $fieldID, $singleRecord); |
c43cedc8 | 790 | } |
791 | } | |
792 | } | |
793 | } | |
794 | ||
795 | /** | |
796 | * Build the entity-specific custom data into the group tree on a per-field basis | |
797 | * | |
6a0b768e TO |
798 | * @param object $dao |
799 | * Object representing the custom field to be populated into the groupTree. | |
800 | * @param array $groupTree | |
801 | * (reference) the group tree being build. | |
802 | * @param string $table | |
803 | * Table name. | |
3a8f58ec | 804 | * @param int $groupID |
6a0b768e | 805 | * Custom group ID. |
3a8f58ec | 806 | * @param int $fieldID |
6a0b768e | 807 | * Custom field ID. |
aa965915 | 808 | * @param string|int $singleRecord |
e1d48b72 | 809 | * holds 'new' or id if loading view/edit/copy for a single record. |
c43cedc8 | 810 | */ |
518fa0ee | 811 | public static function buildCustomFieldData($dao, &$groupTree, $table, $groupID, $fieldID, $singleRecord = NULL) { |
9d72cede EM |
812 | $column = $groupTree[$groupID]['fields'][$fieldID]['column_name']; |
813 | $idName = "{$table}_id"; | |
c43cedc8 | 814 | $fieldName = "{$table}_{$column}"; |
815 | $dataType = $groupTree[$groupID]['fields'][$fieldID]['data_type']; | |
816 | if ($dataType == 'File') { | |
817 | if (isset($dao->$fieldName)) { | |
9d72cede EM |
818 | $config = CRM_Core_Config::singleton(); |
819 | $fileDAO = new CRM_Core_DAO_File(); | |
c43cedc8 | 820 | $fileDAO->id = $dao->$fieldName; |
821 | ||
822 | if ($fileDAO->find(TRUE)) { | |
823 | $entityIDName = "{$table}_entity_id"; | |
efddd94f | 824 | $fileHash = CRM_Core_BAO_File::generateFileHash($dao->$entityIDName, $fileDAO->id); |
c43cedc8 | 825 | $customValue['id'] = $dao->$idName; |
826 | $customValue['data'] = $fileDAO->uri; | |
827 | $customValue['fid'] = $fileDAO->id; | |
ff9aeadb | 828 | $customValue['fileURL'] = CRM_Utils_System::url('civicrm/file', "reset=1&id={$fileDAO->id}&eid={$dao->$entityIDName}&fcs=$fileHash"); |
c43cedc8 | 829 | $customValue['displayURL'] = NULL; |
830 | $deleteExtra = ts('Are you sure you want to delete attached file.'); | |
be2fb01f CW |
831 | $deleteURL = [ |
832 | CRM_Core_Action::DELETE => [ | |
c43cedc8 | 833 | 'name' => ts('Delete Attached File'), |
834 | 'url' => 'civicrm/file', | |
ff9aeadb | 835 | 'qs' => 'reset=1&id=%%id%%&eid=%%eid%%&fid=%%fid%%&action=delete&fcs=%%fcs%%', |
a1a2a83d TO |
836 | 'extra' => 'onclick = "if (confirm( \'' . $deleteExtra |
837 | . '\' ) ) this.href+=\'&confirmed=1\'; else return false;"', | |
be2fb01f CW |
838 | ], |
839 | ]; | |
c43cedc8 | 840 | $customValue['deleteURL'] = CRM_Core_Action::formLink($deleteURL, |
841 | CRM_Core_Action::DELETE, | |
be2fb01f | 842 | [ |
c43cedc8 | 843 | 'id' => $fileDAO->id, |
844 | 'eid' => $dao->$entityIDName, | |
845 | 'fid' => $fieldID, | |
ff9aeadb | 846 | 'fcs' => $fileHash, |
be2fb01f | 847 | ], |
87dab4a4 AH |
848 | ts('more'), |
849 | FALSE, | |
850 | 'file.manage.delete', | |
851 | 'File', | |
852 | $fileDAO->id | |
c43cedc8 | 853 | ); |
854 | $customValue['deleteURLArgs'] = CRM_Core_BAO_File::deleteURLArgs($table, $dao->$entityIDName, $fileDAO->id); | |
855 | $customValue['fileName'] = CRM_Utils_File::cleanFileName(basename($fileDAO->uri)); | |
856 | if ($fileDAO->mime_type == "image/jpeg" || | |
857 | $fileDAO->mime_type == "image/pjpeg" || | |
858 | $fileDAO->mime_type == "image/gif" || | |
859 | $fileDAO->mime_type == "image/x-png" || | |
860 | $fileDAO->mime_type == "image/png" | |
861 | ) { | |
862 | $customValue['displayURL'] = $customValue['fileURL']; | |
863 | $entityId = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_EntityFile', | |
864 | $fileDAO->id, | |
865 | 'entity_id', | |
866 | 'file_id' | |
867 | ); | |
6c552737 | 868 | $customValue['imageURL'] = str_replace('persist/contribute', 'custom', $config->imageUploadURL) . |
9d72cede | 869 | $fileDAO->uri; |
9bbc34f1 | 870 | list($path) = CRM_Core_BAO_File::path($fileDAO->id, $entityId); |
a52de115 CB |
871 | if ($path && file_exists($path)) { |
872 | list($imageWidth, $imageHeight) = getimagesize($path); | |
873 | list($imageThumbWidth, $imageThumbHeight) = CRM_Contact_BAO_Contact::getThumbSize($imageWidth, $imageHeight); | |
874 | $customValue['imageThumbWidth'] = $imageThumbWidth; | |
875 | $customValue['imageThumbHeight'] = $imageThumbHeight; | |
876 | } | |
6a488035 TO |
877 | } |
878 | } | |
879 | } | |
c43cedc8 | 880 | else { |
be2fb01f | 881 | $customValue = [ |
c43cedc8 | 882 | 'id' => $dao->$idName, |
883 | 'data' => '', | |
be2fb01f | 884 | ]; |
c43cedc8 | 885 | } |
886 | } | |
887 | else { | |
be2fb01f | 888 | $customValue = [ |
c43cedc8 | 889 | 'id' => $dao->$idName, |
890 | 'data' => $dao->$fieldName, | |
be2fb01f | 891 | ]; |
6a488035 TO |
892 | } |
893 | ||
c43cedc8 | 894 | if (!array_key_exists('customValue', $groupTree[$groupID]['fields'][$fieldID])) { |
be2fb01f | 895 | $groupTree[$groupID]['fields'][$fieldID]['customValue'] = []; |
c43cedc8 | 896 | } |
e1d48b72 | 897 | if (empty($groupTree[$groupID]['fields'][$fieldID]['customValue']) && !empty($singleRecord)) { |
be2fb01f | 898 | $groupTree[$groupID]['fields'][$fieldID]['customValue'] = [$singleRecord => $customValue]; |
e1d48b72 | 899 | } |
900 | elseif (empty($groupTree[$groupID]['fields'][$fieldID]['customValue'])) { | |
be2fb01f | 901 | $groupTree[$groupID]['fields'][$fieldID]['customValue'] = [1 => $customValue]; |
c43cedc8 | 902 | } |
903 | else { | |
904 | $groupTree[$groupID]['fields'][$fieldID]['customValue'][] = $customValue; | |
905 | } | |
6a488035 TO |
906 | } |
907 | ||
908 | /** | |
909 | * Get the group title. | |
910 | * | |
6a0b768e TO |
911 | * @param int $id |
912 | * Id of group. | |
6a488035 | 913 | * |
a6c01b45 CW |
914 | * @return string |
915 | * title | |
6a488035 TO |
916 | */ |
917 | public static function getTitle($id) { | |
918 | return CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomGroup', $id, 'title'); | |
919 | } | |
920 | ||
921 | /** | |
922 | * Get custom group details for a group. | |
923 | * | |
924 | * An array containing custom group details (including their custom field) is returned. | |
925 | * | |
6a0b768e TO |
926 | * @param int $groupId |
927 | * Group id whose details are needed. | |
928 | * @param bool $searchable | |
929 | * Is this field searchable. | |
930 | * @param array $extends | |
931 | * Which table does it extend if any. | |
dd244018 | 932 | * |
aa965915 | 933 | * @param bool $inSelector |
6a488035 | 934 | * |
a6c01b45 CW |
935 | * @return array |
936 | * array consisting of all group and field details | |
6a488035 | 937 | */ |
e41f4660 | 938 | public static function &getGroupDetail($groupId = NULL, $searchable = NULL, &$extends = NULL, $inSelector = NULL) { |
6a488035 | 939 | // create a new tree |
be2fb01f | 940 | $groupTree = []; |
6a488035 TO |
941 | |
942 | // using tableData to build the queryString | |
be2fb01f CW |
943 | $tableData = [ |
944 | 'civicrm_custom_field' => [ | |
6a488035 TO |
945 | 'id', |
946 | 'label', | |
947 | 'data_type', | |
948 | 'html_type', | |
949 | 'default_value', | |
950 | 'attributes', | |
951 | 'is_required', | |
952 | 'help_pre', | |
953 | 'help_post', | |
954 | 'options_per_line', | |
955 | 'is_searchable', | |
956 | 'start_date_years', | |
957 | 'end_date_years', | |
958 | 'is_search_range', | |
959 | 'date_format', | |
960 | 'time_format', | |
961 | 'note_columns', | |
962 | 'note_rows', | |
963 | 'column_name', | |
964 | 'is_view', | |
965 | 'option_group_id', | |
e41f4660 | 966 | 'in_selector', |
be2fb01f CW |
967 | ], |
968 | 'civicrm_custom_group' => [ | |
6a488035 TO |
969 | 'id', |
970 | 'name', | |
971 | 'title', | |
972 | 'help_pre', | |
973 | 'help_post', | |
974 | 'collapse_display', | |
975 | 'collapse_adv_display', | |
976 | 'extends', | |
977 | 'extends_entity_column_value', | |
978 | 'table_name', | |
e41f4660 | 979 | 'is_multiple', |
be2fb01f CW |
980 | ], |
981 | ]; | |
6a488035 TO |
982 | |
983 | // create select | |
be2fb01f | 984 | $s = []; |
6a488035 TO |
985 | foreach ($tableData as $tableName => $tableColumn) { |
986 | foreach ($tableColumn as $columnName) { | |
987 | $s[] = "{$tableName}.{$columnName} as {$tableName}_{$columnName}"; | |
988 | } | |
989 | } | |
990 | $select = 'SELECT ' . implode(', ', $s); | |
be2fb01f | 991 | $params = []; |
6a488035 TO |
992 | // from, where, order by |
993 | $from = " FROM civicrm_custom_field, civicrm_custom_group"; | |
994 | $where = " WHERE civicrm_custom_field.custom_group_id = civicrm_custom_group.id | |
995 | AND civicrm_custom_group.is_active = 1 | |
996 | AND civicrm_custom_field.is_active = 1 "; | |
997 | if ($groupId) { | |
be2fb01f | 998 | $params[1] = [$groupId, 'Integer']; |
6a488035 TO |
999 | $where .= " AND civicrm_custom_group.id = %1"; |
1000 | } | |
1001 | ||
1002 | if ($searchable) { | |
1003 | $where .= " AND civicrm_custom_field.is_searchable = 1"; | |
1004 | } | |
1005 | ||
e41f4660 PJ |
1006 | if ($inSelector) { |
1007 | $where .= " AND civicrm_custom_field.in_selector = 1 AND civicrm_custom_group.is_multiple = 1 "; | |
1008 | } | |
1009 | ||
6a488035 | 1010 | if ($extends) { |
be2fb01f | 1011 | $clause = []; |
6a488035 TO |
1012 | foreach ($extends as $e) { |
1013 | $clause[] = "civicrm_custom_group.extends = '$e'"; | |
1014 | } | |
1015 | $where .= " AND ( " . implode(' OR ', $clause) . " ) "; | |
1016 | ||
1017 | //include case activities customdata if case is enabled | |
1018 | if (in_array('Activity', $extends)) { | |
1019 | $extendValues = implode(',', array_keys(CRM_Core_PseudoConstant::activityType(TRUE, TRUE, FALSE, 'label', TRUE))); | |
1020 | $where .= " AND ( civicrm_custom_group.extends_entity_column_value IS NULL OR REPLACE( civicrm_custom_group.extends_entity_column_value, %2, ' ') IN ($extendValues) ) "; | |
be2fb01f | 1021 | $params[2] = [CRM_Core_DAO::VALUE_SEPARATOR, 'String']; |
6a488035 TO |
1022 | } |
1023 | } | |
1024 | ||
1025 | // ensure that the user has access to these custom groups | |
9d72cede EM |
1026 | $where .= " AND " . |
1027 | CRM_Core_Permission::customGroupClause(CRM_Core_Permission::VIEW, | |
1028 | 'civicrm_custom_group.' | |
1029 | ); | |
6a488035 TO |
1030 | |
1031 | $orderBy = " ORDER BY civicrm_custom_group.weight, civicrm_custom_field.weight"; | |
1032 | ||
1033 | // final query string | |
1034 | $queryString = $select . $from . $where . $orderBy; | |
1035 | ||
1036 | // dummy dao needed | |
1037 | $crmDAO = CRM_Core_DAO::executeQuery($queryString, $params); | |
1038 | ||
1039 | // process records | |
1040 | while ($crmDAO->fetch()) { | |
1041 | $groupId = $crmDAO->civicrm_custom_group_id; | |
1042 | $fieldId = $crmDAO->civicrm_custom_field_id; | |
1043 | ||
1044 | // create an array for groups if it does not exist | |
1045 | if (!array_key_exists($groupId, $groupTree)) { | |
be2fb01f | 1046 | $groupTree[$groupId] = []; |
6a488035 TO |
1047 | $groupTree[$groupId]['id'] = $groupId; |
1048 | ||
1049 | foreach ($tableData['civicrm_custom_group'] as $v) { | |
1050 | $fullField = "civicrm_custom_group_" . $v; | |
1051 | ||
1052 | if ($v == 'id' || is_null($crmDAO->$fullField)) { | |
1053 | continue; | |
1054 | } | |
1055 | ||
1056 | $groupTree[$groupId][$v] = $crmDAO->$fullField; | |
1057 | } | |
1058 | ||
be2fb01f | 1059 | $groupTree[$groupId]['fields'] = []; |
6a488035 TO |
1060 | } |
1061 | ||
1062 | // add the fields now (note - the query row will always contain a field) | |
be2fb01f | 1063 | $groupTree[$groupId]['fields'][$fieldId] = []; |
6a488035 TO |
1064 | $groupTree[$groupId]['fields'][$fieldId]['id'] = $fieldId; |
1065 | ||
1066 | foreach ($tableData['civicrm_custom_field'] as $v) { | |
1067 | $fullField = "civicrm_custom_field_" . $v; | |
1068 | if ($v == 'id' || is_null($crmDAO->$fullField)) { | |
1069 | continue; | |
1070 | } | |
1071 | $groupTree[$groupId]['fields'][$fieldId][$v] = $crmDAO->$fullField; | |
1072 | } | |
1073 | } | |
1074 | ||
1075 | return $groupTree; | |
1076 | } | |
1077 | ||
b5c2afd0 EM |
1078 | /** |
1079 | * @param $entityType | |
1080 | * @param $path | |
1081 | * @param string $cidToken | |
1082 | * | |
1083 | * @return array | |
1084 | */ | |
6a488035 TO |
1085 | public static function &getActiveGroups($entityType, $path, $cidToken = '%%cid%%') { |
1086 | // for Group's | |
1087 | $customGroupDAO = new CRM_Core_DAO_CustomGroup(); | |
1088 | ||
e41f4660 PJ |
1089 | // get 'Tab' and 'Tab with table' groups |
1090 | $customGroupDAO->whereAdd("style IN ('Tab', 'Tab with table')"); | |
6a488035 TO |
1091 | $customGroupDAO->whereAdd("is_active = 1"); |
1092 | ||
1093 | // add whereAdd for entity type | |
1094 | self::_addWhereAdd($customGroupDAO, $entityType, $cidToken); | |
1095 | ||
be2fb01f | 1096 | $groups = []; |
6a488035 TO |
1097 | |
1098 | $permissionClause = CRM_Core_Permission::customGroupClause(CRM_Core_Permission::VIEW, NULL, TRUE); | |
1099 | $customGroupDAO->whereAdd($permissionClause); | |
1100 | ||
1101 | // order by weight | |
1102 | $customGroupDAO->orderBy('weight'); | |
1103 | $customGroupDAO->find(); | |
1104 | ||
1105 | // process each group with menu tab | |
1106 | while ($customGroupDAO->fetch()) { | |
be2fb01f | 1107 | $group = []; |
9d72cede EM |
1108 | $group['id'] = $customGroupDAO->id; |
1109 | $group['path'] = $path; | |
1110 | $group['title'] = "$customGroupDAO->title"; | |
1111 | $group['query'] = "reset=1&gid={$customGroupDAO->id}&cid={$cidToken}"; | |
be2fb01f | 1112 | $group['extra'] = ['gid' => $customGroupDAO->id]; |
6a488035 | 1113 | $group['table_name'] = $customGroupDAO->table_name; |
a97040f5 | 1114 | $group['is_multiple'] = $customGroupDAO->is_multiple; |
2af06525 | 1115 | $group['icon'] = $customGroupDAO->icon; |
9d72cede | 1116 | $groups[] = $group; |
6a488035 TO |
1117 | } |
1118 | ||
1119 | return $groups; | |
1120 | } | |
1121 | ||
1122 | /** | |
1123 | * Get the table name for the entity type | |
1124 | * currently if entity type is 'Contact', 'Individual', 'Household', 'Organization' | |
1125 | * tableName is 'civicrm_contact' | |
1126 | * | |
6a0b768e TO |
1127 | * @param string $entityType |
1128 | * What entity are we extending here ?. | |
6a488035 | 1129 | * |
a6c01b45 | 1130 | * @return string |
6a488035 | 1131 | * |
6a488035 | 1132 | * |
6de76520 | 1133 | * @see _apachesolr_civiAttachments_dereference_file_parent |
6a488035 | 1134 | */ |
6de76520 | 1135 | public static function getTableNameByEntityName($entityType) { |
6a488035 TO |
1136 | switch ($entityType) { |
1137 | case 'Contact': | |
1138 | case 'Individual': | |
1139 | case 'Household': | |
1140 | case 'Organization': | |
c9eaf5de | 1141 | return 'civicrm_contact'; |
6a488035 | 1142 | |
c9eaf5de CW |
1143 | default: |
1144 | return CRM_Core_DAO_AllCoreTables::getTableForEntityName($entityType); | |
6a488035 | 1145 | } |
6a488035 TO |
1146 | } |
1147 | ||
1148 | /** | |
1149 | * Get a list of custom groups which extend a given entity type. | |
1150 | * If there are custom-groups which only apply to certain subtypes, | |
1151 | * those WILL be included. | |
1152 | * | |
5a4f6742 | 1153 | * @param string $entityType |
9d72cede | 1154 | * |
6a488035 TO |
1155 | * @return CRM_Core_DAO_CustomGroup |
1156 | */ | |
00be9182 | 1157 | public static function getAllCustomGroupsByBaseEntity($entityType) { |
6a488035 TO |
1158 | $customGroupDAO = new CRM_Core_DAO_CustomGroup(); |
1159 | self::_addWhereAdd($customGroupDAO, $entityType, NULL, TRUE); | |
1160 | return $customGroupDAO; | |
1161 | } | |
1162 | ||
1163 | /** | |
1164 | * Add the whereAdd clause for the DAO depending on the type of entity | |
1165 | * the custom group is extending. | |
1166 | * | |
6c552737 | 1167 | * @param object $customGroupDAO |
6a0b768e TO |
1168 | * @param string $entityType |
1169 | * What entity are we extending here ?. | |
fd31fa4c | 1170 | * |
6c552737 | 1171 | * @param int $entityID |
fd31fa4c | 1172 | * @param bool $allSubtypes |
6a488035 TO |
1173 | */ |
1174 | private static function _addWhereAdd(&$customGroupDAO, $entityType, $entityID = NULL, $allSubtypes = FALSE) { | |
1175 | $addSubtypeClause = FALSE; | |
6bbc383d | 1176 | // This function isn't really accessible with user data but since the string |
1177 | // is not passed as a param to the query CRM_Core_DAO::escapeString seems like a harmless | |
1178 | // precaution. | |
1179 | $entityType = CRM_Core_DAO::escapeString($entityType); | |
6a488035 TO |
1180 | |
1181 | switch ($entityType) { | |
1182 | case 'Contact': | |
1183 | // if contact, get all related to contact | |
1184 | $extendList = "'Contact','Individual','Household','Organization'"; | |
1185 | $customGroupDAO->whereAdd("extends IN ( $extendList )"); | |
1186 | if (!$allSubtypes) { | |
1187 | $addSubtypeClause = TRUE; | |
1188 | } | |
1189 | break; | |
1190 | ||
1191 | case 'Individual': | |
1192 | case 'Household': | |
1193 | case 'Organization': | |
1194 | // is I/H/O then get I/H/O and contact | |
1195 | $extendList = "'Contact','$entityType'"; | |
1196 | $customGroupDAO->whereAdd("extends IN ( $extendList )"); | |
1197 | if (!$allSubtypes) { | |
1198 | $addSubtypeClause = TRUE; | |
1199 | } | |
1200 | break; | |
1201 | ||
6bbc383d | 1202 | default: |
6a488035 TO |
1203 | $customGroupDAO->whereAdd("extends IN ('$entityType')"); |
1204 | break; | |
1205 | } | |
1206 | ||
1207 | if ($addSubtypeClause) { | |
1208 | $csType = is_numeric($entityID) ? CRM_Contact_BAO_Contact::getContactSubType($entityID) : FALSE; | |
1209 | ||
1210 | if (!empty($csType)) { | |
be2fb01f | 1211 | $subtypeClause = []; |
6a488035 | 1212 | foreach ($csType as $subtype) { |
9d72cede EM |
1213 | $subtype = CRM_Core_DAO::VALUE_SEPARATOR . $subtype . |
1214 | CRM_Core_DAO::VALUE_SEPARATOR; | |
6a488035 TO |
1215 | $subtypeClause[] = "extends_entity_column_value LIKE '%{$subtype}%'"; |
1216 | } | |
1217 | $subtypeClause[] = "extends_entity_column_value IS NULL"; | |
9d72cede EM |
1218 | $customGroupDAO->whereAdd("( " . implode(' OR ', $subtypeClause) . |
1219 | " )"); | |
6a488035 TO |
1220 | } |
1221 | else { | |
1222 | $customGroupDAO->whereAdd("extends_entity_column_value IS NULL"); | |
1223 | } | |
1224 | } | |
1225 | } | |
1226 | ||
1227 | /** | |
1228 | * Delete the Custom Group. | |
1229 | * | |
3a8f58ec EM |
1230 | * @param CRM_Core_BAO_CustomGroup $group |
1231 | * Custom group object. | |
5a4f6742 CW |
1232 | * @param bool $force |
1233 | * whether to force the deletion, even if there are custom fields. | |
6a488035 | 1234 | * |
5c766a0b | 1235 | * @return bool |
3a8f58ec | 1236 | * False if field exists for this group, true if group gets deleted. |
6a488035 TO |
1237 | */ |
1238 | public static function deleteGroup($group, $force = FALSE) { | |
1239 | ||
3a8f58ec | 1240 | //check whether this contain any custom fields |
6a488035 TO |
1241 | $customField = new CRM_Core_DAO_CustomField(); |
1242 | $customField->custom_group_id = $group->id; | |
1243 | $customField->find(); | |
1244 | ||
1245 | // return early if there are custom fields and we're not | |
1246 | // forcing the delete, otherwise delete the fields one by one | |
1247 | while ($customField->fetch()) { | |
1248 | if (!$force) { | |
1249 | return FALSE; | |
1250 | } | |
1251 | CRM_Core_BAO_CustomField::deleteField($customField); | |
1252 | } | |
1253 | ||
1254 | // drop the table associated with this custom group | |
1255 | CRM_Core_BAO_SchemaHandler::dropTable($group->table_name); | |
1256 | ||
1257 | //delete custom group | |
1258 | $group->delete(); | |
1259 | ||
1260 | CRM_Utils_Hook::post('delete', 'CustomGroup', $group->id, $group); | |
1261 | ||
1262 | return TRUE; | |
1263 | } | |
1264 | ||
a4fc91e0 MW |
1265 | /** |
1266 | * Delete a record from supplied params. | |
1267 | * API3 calls deleteGroup() which removes the related civicrm_value_X table. | |
1268 | * This function does the same for API4. | |
1269 | * | |
1270 | * @param array $record | |
1271 | * 'id' is required. | |
1272 | * @return CRM_Core_DAO | |
1273 | * @throws CRM_Core_Exception | |
1274 | */ | |
1275 | public static function deleteRecord(array $record) { | |
1276 | $table = CRM_Core_DAO::getFieldValue(__CLASS__, $record['id'], 'table_name'); | |
1277 | $result = parent::deleteRecord($record); | |
1278 | CRM_Core_BAO_SchemaHandler::dropTable($table); | |
1279 | return $result; | |
1280 | } | |
1281 | ||
b5c2afd0 | 1282 | /** |
3a8f58ec EM |
1283 | * Set defaults. |
1284 | * | |
1285 | * @param array $groupTree | |
1286 | * @param array $defaults | |
b5c2afd0 EM |
1287 | * @param bool $viewMode |
1288 | * @param bool $inactiveNeeded | |
1289 | * @param int $action | |
1290 | */ | |
00be9182 | 1291 | public static function setDefaults(&$groupTree, &$defaults, $viewMode = FALSE, $inactiveNeeded = FALSE, $action = CRM_Core_Action::NONE) { |
6a488035 TO |
1292 | foreach ($groupTree as $id => $group) { |
1293 | if (!isset($group['fields'])) { | |
1294 | continue; | |
1295 | } | |
6a488035 | 1296 | foreach ($group['fields'] as $field) { |
015ba54e | 1297 | if (isset($field['element_value'])) { |
6a488035 TO |
1298 | $value = $field['element_value']; |
1299 | } | |
015ba54e | 1300 | elseif (isset($field['default_value']) && |
6a488035 TO |
1301 | ($action != CRM_Core_Action::UPDATE || |
1302 | // CRM-7548 | |
1303 | !array_key_exists('element_value', $field) | |
1304 | ) | |
1305 | ) { | |
1306 | $value = $viewMode ? NULL : $field['default_value']; | |
1307 | } | |
1308 | else { | |
1309 | continue; | |
1310 | } | |
1311 | ||
3dd2f681 BZ |
1312 | if (empty($field['element_name'])) { |
1313 | continue; | |
6df71703 | 1314 | } |
58593e74 | 1315 | |
3dd2f681 | 1316 | $elementName = $field['element_name']; |
e30142ba | 1317 | $serialize = CRM_Core_BAO_CustomField::isSerialized($field); |
58593e74 | 1318 | |
e30142ba | 1319 | if ($serialize) { |
a61d2ab7 | 1320 | if ($field['data_type'] != 'Country' && $field['data_type'] != 'StateProvince' && $field['data_type'] != 'ContactReference') { |
be2fb01f | 1321 | $defaults[$elementName] = []; |
6a488035 TO |
1322 | $customOption = CRM_Core_BAO_CustomOption::getCustomOption($field['id'], $inactiveNeeded); |
1323 | if ($viewMode) { | |
1324 | $checkedData = explode(CRM_Core_DAO::VALUE_SEPARATOR, substr($value, 1, -1)); | |
1325 | if (isset($value)) { | |
1326 | foreach ($customOption as $customValue => $customLabel) { | |
1327 | if (in_array($customValue, $checkedData)) { | |
1328 | if ($field['html_type'] == 'CheckBox') { | |
1329 | $defaults[$elementName][$customValue] = 1; | |
1330 | } | |
1331 | else { | |
1332 | $defaults[$elementName][$customValue] = $customValue; | |
1333 | } | |
1334 | } | |
1335 | else { | |
1336 | $defaults[$elementName][$customValue] = 0; | |
1337 | } | |
1338 | } | |
1339 | } | |
1340 | } | |
1341 | else { | |
1342 | if (isset($field['customValue']['data'])) { | |
1343 | $checkedData = explode(CRM_Core_DAO::VALUE_SEPARATOR, substr($field['customValue']['data'], 1, -1)); | |
1344 | foreach ($customOption as $val) { | |
1345 | if (in_array($val['value'], $checkedData)) { | |
1346 | if ($field['html_type'] == 'CheckBox') { | |
1347 | $defaults[$elementName][$val['value']] = 1; | |
1348 | } | |
1349 | else { | |
1350 | $defaults[$elementName][$val['value']] = $val['value']; | |
1351 | } | |
1352 | } | |
1353 | else { | |
1354 | $defaults[$elementName][$val['value']] = 0; | |
1355 | } | |
1356 | } | |
1357 | } | |
1358 | else { | |
b4afac65 | 1359 | // Values may be "array strings" or actual arrays. Handle both. |
fb56e964 | 1360 | if (is_array($value) && count($value)) { |
1361 | CRM_Utils_Array::formatArrayKeys($value); | |
1362 | $checkedValue = $value; | |
1363 | } | |
1364 | else { | |
1365 | $checkedValue = explode(CRM_Core_DAO::VALUE_SEPARATOR, substr($value, 1, -1)); | |
1366 | } | |
6a488035 TO |
1367 | foreach ($customOption as $val) { |
1368 | if (in_array($val['value'], $checkedValue)) { | |
1369 | if ($field['html_type'] == 'CheckBox') { | |
1370 | $defaults[$elementName][$val['value']] = 1; | |
1371 | } | |
1372 | else { | |
1373 | $defaults[$elementName][$val['value']] = $val['value']; | |
1374 | } | |
1375 | } | |
1376 | } | |
1377 | } | |
1378 | } | |
e30142ba CW |
1379 | } |
1380 | else { | |
6a488035 | 1381 | if (isset($value)) { |
b4afac65 CW |
1382 | // Values may be "array strings" or actual arrays. Handle both. |
1383 | if (is_array($value) && count($value)) { | |
1384 | CRM_Utils_Array::formatArrayKeys($value); | |
1385 | $checkedValue = $value; | |
1386 | } | |
01f1409c CW |
1387 | // Serialized values from db |
1388 | elseif ($value === '' || strpos($value, CRM_Core_DAO::VALUE_SEPARATOR) !== FALSE) { | |
1389 | $checkedValue = CRM_Utils_Array::explodePadded($value); | |
1390 | } | |
1391 | // Comma-separated values e.g. from a select2 widget during reload on form error | |
b4afac65 | 1392 | else { |
01f1409c | 1393 | $checkedValue = explode(',', $value); |
b4afac65 | 1394 | } |
6a488035 TO |
1395 | foreach ($checkedValue as $val) { |
1396 | if ($val) { | |
1397 | $defaults[$elementName][$val] = $val; | |
1398 | } | |
1399 | } | |
1400 | } | |
e30142ba CW |
1401 | } |
1402 | } | |
1403 | else { | |
1404 | if ($field['data_type'] == 'Country') { | |
6a488035 TO |
1405 | if ($value) { |
1406 | $defaults[$elementName] = $value; | |
1407 | } | |
1408 | else { | |
1409 | $config = CRM_Core_Config::singleton(); | |
1410 | $defaults[$elementName] = $config->defaultContactCountry; | |
1411 | } | |
e30142ba CW |
1412 | } |
1413 | else { | |
6a488035 | 1414 | if ($field['data_type'] == "Float") { |
9d72cede | 1415 | $defaults[$elementName] = (float) $value; |
6a488035 TO |
1416 | } |
1417 | elseif ($field['data_type'] == 'Money' && | |
1418 | $field['html_type'] == 'Text' | |
1419 | ) { | |
476a47e9 | 1420 | $defaults[$elementName] = CRM_Utils_Money::formatLocaleNumericRoundedForDefaultCurrency($value); |
6a488035 TO |
1421 | } |
1422 | else { | |
1423 | $defaults[$elementName] = $value; | |
1424 | } | |
e30142ba | 1425 | } |
6a488035 TO |
1426 | } |
1427 | } | |
1428 | } | |
1429 | } | |
1430 | ||
b5c2afd0 | 1431 | /** |
54844703 CW |
1432 | * Old function only called from one place... |
1433 | * @see CRM_Dedupe_Finder::formatParams | |
3a8f58ec EM |
1434 | * |
1435 | * @param array $groupTree | |
c490a46a | 1436 | * @param array $params |
b5c2afd0 EM |
1437 | * @param bool $skipFile |
1438 | */ | |
00be9182 | 1439 | public static function postProcess(&$groupTree, &$params, $skipFile = FALSE) { |
6a488035 | 1440 | // Get the Custom form values and groupTree |
6a488035 TO |
1441 | foreach ($groupTree as $groupID => $group) { |
1442 | if ($groupID === 'info') { | |
1443 | continue; | |
1444 | } | |
1445 | foreach ($group['fields'] as $field) { | |
1446 | $fieldId = $field['id']; | |
54844703 | 1447 | $serialize = CRM_Core_BAO_CustomField::isSerialized($field); |
6a488035 | 1448 | |
54844703 CW |
1449 | // Reset all checkbox, radio and multiselect data |
1450 | if ($field['html_type'] == 'Radio' || $serialize) { | |
6a488035 TO |
1451 | $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = 'NULL'; |
1452 | } | |
1453 | ||
1454 | $v = NULL; | |
1455 | foreach ($params as $key => $val) { | |
1456 | if (preg_match('/^custom_(\d+)_?(-?\d+)?$/', $key, $match) && | |
1457 | $match[1] == $field['id'] | |
1458 | ) { | |
1459 | $v = $val; | |
1460 | } | |
1461 | } | |
1462 | ||
6a488035 TO |
1463 | if (!isset($groupTree[$groupID]['fields'][$fieldId]['customValue'])) { |
1464 | // field exists in db so populate value from "form". | |
be2fb01f | 1465 | $groupTree[$groupID]['fields'][$fieldId]['customValue'] = []; |
6a488035 TO |
1466 | } |
1467 | ||
54844703 CW |
1468 | // Serialize checkbox and multi-select data (using array keys for checkbox) |
1469 | if ($serialize) { | |
1470 | $v = ($v && $field['html_type'] === 'Checkbox') ? array_keys($v) : $v; | |
1471 | $v = $v ? CRM_Utils_Array::implodePadded($v) : NULL; | |
1472 | } | |
6a488035 | 1473 | |
54844703 | 1474 | switch ($field['html_type']) { |
6a488035 TO |
1475 | |
1476 | case 'Select Date': | |
1477 | $date = CRM_Utils_Date::processDate($v); | |
1478 | $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = $date; | |
1479 | break; | |
1480 | ||
1481 | case 'File': | |
1482 | if ($skipFile) { | |
94b444d0 | 1483 | break; |
6a488035 TO |
1484 | } |
1485 | ||
aa965915 | 1486 | // store the file in d/b |
6a488035 | 1487 | $entityId = explode('=', $groupTree['info']['where'][0]); |
be2fb01f | 1488 | $fileParams = ['upload_date' => date('YmdHis')]; |
6a488035 TO |
1489 | |
1490 | if ($groupTree[$groupID]['fields'][$fieldId]['customValue']['fid']) { | |
1491 | $fileParams['id'] = $groupTree[$groupID]['fields'][$fieldId]['customValue']['fid']; | |
1492 | } | |
1493 | if (!empty($v)) { | |
1494 | $fileParams['uri'] = $v['name']; | |
1495 | $fileParams['mime_type'] = $v['type']; | |
1496 | CRM_Core_BAO_File::filePostProcess($v['name'], | |
1497 | $groupTree[$groupID]['fields'][$fieldId]['customValue']['fid'], | |
1498 | $groupTree[$groupID]['table_name'], | |
1499 | trim($entityId[1]), | |
1500 | FALSE, | |
1501 | TRUE, | |
1502 | $fileParams, | |
1503 | 'custom_' . $fieldId, | |
1504 | $v['type'] | |
1505 | ); | |
1506 | } | |
be2fb01f CW |
1507 | $defaults = []; |
1508 | $paramsFile = [ | |
6a488035 TO |
1509 | 'entity_table' => $groupTree[$groupID]['table_name'], |
1510 | 'entity_id' => $entityId[1], | |
be2fb01f | 1511 | ]; |
6a488035 TO |
1512 | |
1513 | CRM_Core_DAO::commonRetrieve('CRM_Core_DAO_EntityFile', | |
1514 | $paramsFile, | |
1515 | $defaults | |
1516 | ); | |
1517 | ||
1518 | $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = $defaults['file_id']; | |
1519 | break; | |
1520 | ||
1521 | default: | |
1522 | $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = $v; | |
1523 | break; | |
1524 | } | |
1525 | } | |
1526 | } | |
1527 | } | |
1528 | ||
1529 | /** | |
fe482240 | 1530 | * Generic function to build all the form elements for a specific group tree. |
6a488035 | 1531 | * |
6a0b768e TO |
1532 | * @param CRM_Core_Form $form |
1533 | * The form object. | |
1534 | * @param array $groupTree | |
1535 | * The group tree object. | |
1536 | * @param bool $inactiveNeeded | |
1537 | * Return inactive custom groups. | |
1538 | * @param string $prefix | |
1539 | * Prefix for custom grouptree assigned to template. | |
aa965915 MWMC |
1540 | * |
1541 | * @throws \CiviCRM_API3_Exception | |
6a488035 | 1542 | */ |
00be9182 | 1543 | public static function buildQuickForm(&$form, &$groupTree, $inactiveNeeded = FALSE, $prefix = '') { |
6a488035 | 1544 | $form->assign_by_ref("{$prefix}groupTree", $groupTree); |
6a488035 | 1545 | |
6a488035 | 1546 | foreach ($groupTree as $id => $group) { |
6a488035 | 1547 | foreach ($group['fields'] as $field) { |
9c1bc317 | 1548 | $required = $field['is_required'] ?? NULL; |
6a488035 TO |
1549 | //fix for CRM-1620 |
1550 | if ($field['data_type'] == 'File') { | |
bdadc7ac | 1551 | if (!empty($field['element_value']['data'])) { |
6a488035 TO |
1552 | $required = 0; |
1553 | } | |
1554 | } | |
1555 | ||
1556 | $fieldId = $field['id']; | |
1557 | $elementName = $field['element_name']; | |
3a7773be | 1558 | CRM_Core_BAO_CustomField::addQuickFormElement($form, $elementName, $fieldId, $required); |
25cdc89e MWMC |
1559 | if ($form->getAction() == CRM_Core_Action::VIEW) { |
1560 | $form->getElement($elementName)->freeze(); | |
1561 | } | |
6a488035 TO |
1562 | } |
1563 | } | |
1564 | } | |
1565 | ||
1566 | /** | |
3a8f58ec | 1567 | * Extract the get params from the url, validate and store it in session. |
6a488035 | 1568 | * |
6a0b768e TO |
1569 | * @param CRM_Core_Form $form |
1570 | * The form object. | |
1571 | * @param string $type | |
1572 | * The type of custom group we are using. | |
6a488035 | 1573 | * |
03110609 | 1574 | * @return array |
aa965915 MWMC |
1575 | * @throws \CRM_Core_Exception |
1576 | * @throws \CiviCRM_API3_Exception | |
6a488035 | 1577 | */ |
00be9182 | 1578 | public static function extractGetParams(&$form, $type) { |
6a488035 | 1579 | if (empty($_GET)) { |
be2fb01f | 1580 | return []; |
6a488035 TO |
1581 | } |
1582 | ||
79363422 | 1583 | $groupTree = CRM_Core_BAO_CustomGroup::getTree($type); |
be2fb01f CW |
1584 | $customValue = []; |
1585 | $htmlType = [ | |
9d72cede EM |
1586 | 'CheckBox', |
1587 | 'Multi-Select', | |
9d72cede | 1588 | 'Select', |
21dfd5f5 | 1589 | 'Radio', |
be2fb01f | 1590 | ]; |
6a488035 TO |
1591 | |
1592 | foreach ($groupTree as $group) { | |
1593 | if (!isset($group['fields'])) { | |
1594 | continue; | |
1595 | } | |
1596 | foreach ($group['fields'] as $key => $field) { | |
1597 | $fieldName = 'custom_' . $key; | |
6fc7508a | 1598 | $value = CRM_Utils_Request::retrieve($fieldName, 'String', $form, FALSE, NULL, 'GET'); |
6a488035 TO |
1599 | |
1600 | if ($value) { | |
1601 | $valid = FALSE; | |
1602 | if (!in_array($field['html_type'], $htmlType) || | |
1603 | $field['data_type'] == 'Boolean' | |
1604 | ) { | |
1605 | $valid = CRM_Core_BAO_CustomValue::typecheck($field['data_type'], $value); | |
1606 | } | |
3d86eb05 | 1607 | if (CRM_Core_BAO_CustomField::isSerialized($field)) { |
9d72cede EM |
1608 | $value = str_replace("|", ",", $value); |
1609 | $mulValues = explode(',', $value); | |
6a488035 | 1610 | $customOption = CRM_Core_BAO_CustomOption::getCustomOption($key, TRUE); |
be2fb01f | 1611 | $val = []; |
6a488035 TO |
1612 | foreach ($mulValues as $v1) { |
1613 | foreach ($customOption as $coID => $coValue) { | |
9d72cede EM |
1614 | if (strtolower(trim($coValue['label'])) == |
1615 | strtolower(trim($v1)) | |
1616 | ) { | |
6a488035 TO |
1617 | $val[$coValue['value']] = 1; |
1618 | } | |
1619 | } | |
1620 | } | |
1621 | if (!empty($val)) { | |
1622 | $value = $val; | |
1623 | $valid = TRUE; | |
1624 | } | |
1625 | else { | |
1626 | $value = NULL; | |
1627 | } | |
1628 | } | |
36769590 | 1629 | elseif ($field['html_type'] === 'Select' || |
1630 | ($field['html_type'] === 'Radio' && | |
1631 | $field['data_type'] !== 'Boolean' | |
6a488035 TO |
1632 | ) |
1633 | ) { | |
1634 | $customOption = CRM_Core_BAO_CustomOption::getCustomOption($key, TRUE); | |
1635 | foreach ($customOption as $customID => $coValue) { | |
9d72cede EM |
1636 | if (strtolower(trim($coValue['label'])) == |
1637 | strtolower(trim($value)) | |
1638 | ) { | |
6a488035 TO |
1639 | $value = $coValue['value']; |
1640 | $valid = TRUE; | |
1641 | } | |
1642 | } | |
1643 | } | |
36769590 | 1644 | elseif ($field['data_type'] === 'Date') { |
31349d27 | 1645 | $valid = CRM_Utils_Rule::date($value); |
6a488035 TO |
1646 | } |
1647 | ||
1648 | if ($valid) { | |
1649 | $customValue[$fieldName] = $value; | |
1650 | } | |
1651 | } | |
1652 | } | |
1653 | } | |
1654 | ||
1655 | return $customValue; | |
1656 | } | |
1657 | ||
1658 | /** | |
100fef9d | 1659 | * Check the type of custom field type (eg: Used for Individual, Contribution, etc) |
6a488035 TO |
1660 | * this function is used to get the custom fields of a type (eg: Used for Individual, Contribution, etc ) |
1661 | * | |
6a0b768e TO |
1662 | * @param int $customFieldId |
1663 | * Custom field id. | |
1664 | * @param array $removeCustomFieldTypes | |
1665 | * Remove custom fields of a type eg: array("Individual") ;. | |
6a488035 | 1666 | * |
5c766a0b | 1667 | * @return bool |
a6c01b45 | 1668 | * false if it matches else true |
36769590 | 1669 | * |
1670 | * @throws \CRM_Core_Exception | |
6a488035 | 1671 | */ |
00be9182 | 1672 | public static function checkCustomField($customFieldId, &$removeCustomFieldTypes) { |
36769590 | 1673 | $query = 'SELECT cg.extends as extends |
6a488035 TO |
1674 | FROM civicrm_custom_group as cg, civicrm_custom_field as cf |
1675 | WHERE cg.id = cf.custom_group_id | |
36769590 | 1676 | AND cf.id =' . |
9d72cede | 1677 | CRM_Utils_Type::escape($customFieldId, 'Integer'); |
6a488035 TO |
1678 | |
1679 | $extends = CRM_Core_DAO::singleValueQuery($query); | |
1680 | ||
1681 | if (in_array($extends, $removeCustomFieldTypes)) { | |
1682 | return FALSE; | |
1683 | } | |
1684 | return TRUE; | |
1685 | } | |
1686 | ||
b5c2afd0 EM |
1687 | /** |
1688 | * @param $table | |
1689 | * | |
1690 | * @return string | |
1691 | * @throws Exception | |
1692 | */ | |
00be9182 | 1693 | public static function mapTableName($table) { |
6a488035 TO |
1694 | switch ($table) { |
1695 | case 'Contact': | |
1696 | case 'Individual': | |
1697 | case 'Household': | |
1698 | case 'Organization': | |
1699 | return 'civicrm_contact'; | |
1700 | ||
1701 | case 'Activity': | |
1702 | return 'civicrm_activity'; | |
1703 | ||
1704 | case 'Group': | |
1705 | return 'civicrm_group'; | |
1706 | ||
1707 | case 'Contribution': | |
1708 | return 'civicrm_contribution'; | |
1709 | ||
95974e8e DG |
1710 | case 'ContributionRecur': |
1711 | return 'civicrm_contribution_recur'; | |
1712 | ||
6a488035 TO |
1713 | case 'Relationship': |
1714 | return 'civicrm_relationship'; | |
1715 | ||
1716 | case 'Event': | |
1717 | return 'civicrm_event'; | |
1718 | ||
1719 | case 'Membership': | |
1720 | return 'civicrm_membership'; | |
1721 | ||
1722 | case 'Participant': | |
1723 | case 'ParticipantRole': | |
1724 | case 'ParticipantEventName': | |
1725 | case 'ParticipantEventType': | |
1726 | return 'civicrm_participant'; | |
1727 | ||
1728 | case 'Grant': | |
1729 | return 'civicrm_grant'; | |
1730 | ||
1731 | case 'Pledge': | |
1732 | return 'civicrm_pledge'; | |
1733 | ||
1734 | case 'Address': | |
1735 | return 'civicrm_address'; | |
1736 | ||
1737 | case 'Campaign': | |
1738 | return 'civicrm_campaign'; | |
1739 | ||
1740 | default: | |
1741 | $query = " | |
1742 | SELECT IF( EXISTS(SELECT name FROM civicrm_contact_type WHERE name like %1), 1, 0 )"; | |
be2fb01f | 1743 | $qParams = [1 => [$table, 'String']]; |
6a488035 TO |
1744 | $result = CRM_Core_DAO::singleValueQuery($query, $qParams); |
1745 | ||
1746 | if ($result) { | |
1747 | return 'civicrm_contact'; | |
1748 | } | |
1749 | else { | |
1750 | $extendObjs = CRM_Core_OptionGroup::values('cg_extend_objects', FALSE, FALSE, FALSE, NULL, 'name'); | |
1751 | if (array_key_exists($table, $extendObjs)) { | |
1752 | return $extendObjs[$table]; | |
1753 | } | |
36769590 | 1754 | throw new CRM_Core_Exception('Unknown error'); |
6a488035 TO |
1755 | } |
1756 | } | |
1757 | } | |
1758 | ||
b5c2afd0 EM |
1759 | /** |
1760 | * @param $group | |
aa965915 MWMC |
1761 | * |
1762 | * @throws \Exception | |
b5c2afd0 | 1763 | */ |
00be9182 | 1764 | public static function createTable($group) { |
be2fb01f | 1765 | $params = [ |
6a488035 TO |
1766 | 'name' => $group->table_name, |
1767 | 'is_multiple' => $group->is_multiple ? 1 : 0, | |
1768 | 'extends_name' => self::mapTableName($group->extends), | |
be2fb01f | 1769 | ]; |
6a488035 TO |
1770 | |
1771 | $tableParams = CRM_Core_BAO_CustomField::defaultCustomTableSchema($params); | |
1772 | ||
1773 | CRM_Core_BAO_SchemaHandler::createTable($tableParams); | |
1774 | } | |
1775 | ||
1776 | /** | |
aa965915 | 1777 | * Function returns formatted groupTree, so that form can be easily built in template |
6a488035 | 1778 | * |
6a0b768e | 1779 | * @param array $groupTree |
6a0b768e | 1780 | * @param int $groupCount |
aa965915 MWMC |
1781 | * Group count by default 1, but can vary for multiple value custom data. |
1782 | * @param \CRM_Core_Form $form | |
6a488035 | 1783 | * |
a6c01b45 | 1784 | * @return array |
aa965915 | 1785 | * @throws \CRM_Core_Exception |
6a488035 | 1786 | */ |
1ac1a7d0 | 1787 | public static function formatGroupTree($groupTree, $groupCount = 1, &$form = NULL) { |
be2fb01f CW |
1788 | $formattedGroupTree = []; |
1789 | $uploadNames = $formValues = []; | |
fb56e964 | 1790 | |
29a1df58 | 1791 | // retrieve qf key from url |
1792 | $qfKey = CRM_Utils_Request::retrieve('qf', 'String'); | |
1793 | ||
1794 | // fetch submitted custom field values later use to set as a default values | |
1795 | if ($qfKey) { | |
792fce0b | 1796 | $submittedValues = Civi::cache('customData')->get($qfKey); |
fb56e964 | 1797 | } |
6a488035 TO |
1798 | |
1799 | foreach ($groupTree as $key => $value) { | |
1800 | if ($key === 'info') { | |
1801 | continue; | |
1802 | } | |
1803 | ||
1804 | // add group information | |
9c1bc317 CW |
1805 | $formattedGroupTree[$key]['name'] = $value['name'] ?? NULL; |
1806 | $formattedGroupTree[$key]['title'] = $value['title'] ?? NULL; | |
1807 | $formattedGroupTree[$key]['help_pre'] = $value['help_pre'] ?? NULL; | |
1808 | $formattedGroupTree[$key]['help_post'] = $value['help_post'] ?? NULL; | |
1809 | $formattedGroupTree[$key]['collapse_display'] = $value['collapse_display'] ?? NULL; | |
1810 | $formattedGroupTree[$key]['collapse_adv_display'] = $value['collapse_adv_display'] ?? NULL; | |
1811 | $formattedGroupTree[$key]['style'] = $value['style'] ?? NULL; | |
6a488035 | 1812 | |
64f4eebe | 1813 | // this params needed of building multiple values |
9c1bc317 CW |
1814 | $formattedGroupTree[$key]['is_multiple'] = $value['is_multiple'] ?? NULL; |
1815 | $formattedGroupTree[$key]['extends'] = $value['extends'] ?? NULL; | |
1816 | $formattedGroupTree[$key]['extends_entity_column_id'] = $value['extends_entity_column_id'] ?? NULL; | |
1817 | $formattedGroupTree[$key]['extends_entity_column_value'] = $value['extends_entity_column_value'] ?? NULL; | |
1818 | $formattedGroupTree[$key]['subtype'] = $value['subtype'] ?? NULL; | |
1819 | $formattedGroupTree[$key]['max_multiple'] = $value['max_multiple'] ?? NULL; | |
6a488035 | 1820 | |
1ac1a7d0 EM |
1821 | // Properties that might have been filtered out but which |
1822 | // should be present to avoid smarty e-notices. | |
1823 | $expectedProperties = ['options_per_line', 'help_pre', 'help_post']; | |
6a488035 TO |
1824 | // add field information |
1825 | foreach ($value['fields'] as $k => $properties) { | |
88d6cd73 | 1826 | $properties = array_merge(array_fill_keys($expectedProperties, NULL), $properties); |
6a488035 | 1827 | $properties['element_name'] = "custom_{$k}_-{$groupCount}"; |
9d72cede | 1828 | if (isset($properties['customValue']) && |
fb56e964 | 1829 | !CRM_Utils_System::isNull($properties['customValue']) && |
1830 | !isset($properties['element_value']) | |
9d72cede | 1831 | ) { |
6a488035 TO |
1832 | if (isset($properties['customValue'][$groupCount])) { |
1833 | $properties['element_name'] = "custom_{$k}_{$properties['customValue'][$groupCount]['id']}"; | |
1834 | $formattedGroupTree[$key]['table_id'] = $properties['customValue'][$groupCount]['id']; | |
36769590 | 1835 | if ($properties['data_type'] === 'File') { |
6a488035 TO |
1836 | $properties['element_value'] = $properties['customValue'][$groupCount]; |
1837 | $uploadNames[] = $properties['element_name']; | |
1838 | } | |
1839 | else { | |
1840 | $properties['element_value'] = $properties['customValue'][$groupCount]['data']; | |
1841 | } | |
1842 | } | |
1843 | } | |
16806c95 | 1844 | if ($value = CRM_Utils_Request::retrieve($properties['element_name'], 'String', $form, FALSE, NULL, 'POST')) { |
1845 | $formValues[$properties['element_name']] = $value; | |
1846 | } | |
1847 | elseif (isset($submittedValues[$properties['element_name']])) { | |
1848 | $properties['element_value'] = $submittedValues[$properties['element_name']]; | |
1849 | } | |
6a488035 TO |
1850 | unset($properties['customValue']); |
1851 | $formattedGroupTree[$key]['fields'][$k] = $properties; | |
1852 | } | |
1853 | } | |
1854 | ||
1855 | if ($form) { | |
fb56e964 | 1856 | if (count($formValues)) { |
29a1df58 | 1857 | $qf = $form->get('qfKey'); |
1858 | $form->assign('qfKey', $qf); | |
792fce0b | 1859 | Civi::cache('customData')->set($qf, $formValues); |
fb56e964 | 1860 | } |
1861 | ||
6a488035 TO |
1862 | // hack for field type File |
1863 | $formUploadNames = $form->get('uploadNames'); | |
1864 | if (is_array($formUploadNames)) { | |
1865 | $uploadNames = array_unique(array_merge($formUploadNames, $uploadNames)); | |
1866 | } | |
1867 | ||
1868 | $form->set('uploadNames', $uploadNames); | |
1869 | } | |
1870 | ||
1871 | return $formattedGroupTree; | |
1872 | } | |
1873 | ||
1874 | /** | |
fe482240 | 1875 | * Build custom data view. |
77b97be7 | 1876 | * |
24eba103 | 1877 | * @param CRM_Core_Form|CRM_Core_Page $form |
6a0b768e TO |
1878 | * Page object. |
1879 | * @param array $groupTree | |
6a0b768e TO |
1880 | * @param bool $returnCount |
1881 | * True if customValue count needs to be returned. | |
100fef9d | 1882 | * @param int $gID |
77b97be7 | 1883 | * @param null $prefix |
100fef9d | 1884 | * @param int $customValueId |
080d719e | 1885 | * @param int $entityId |
317103ab | 1886 | * @param bool $checkEditPermission |
77b97be7 EM |
1887 | * |
1888 | * @return array|int | |
5d7c2bd2 | 1889 | * @throws \CRM_Core_Exception |
6a488035 | 1890 | */ |
317103ab CW |
1891 | public static function buildCustomDataView(&$form, $groupTree, $returnCount = FALSE, $gID = NULL, $prefix = NULL, $customValueId = NULL, $entityId = NULL, $checkEditPermission = FALSE) { |
1892 | // Filter out pesky extra info | |
1893 | unset($groupTree['info']); | |
1894 | ||
be2fb01f | 1895 | $details = []; |
317103ab CW |
1896 | |
1897 | $editableGroups = []; | |
1898 | if ($checkEditPermission) { | |
1899 | $editableGroups = \CRM_Core_Permission::customGroup(CRM_Core_Permission::EDIT); | |
1900 | } | |
1901 | ||
6a488035 | 1902 | foreach ($groupTree as $key => $group) { |
6a488035 TO |
1903 | |
1904 | foreach ($group['fields'] as $k => $properties) { | |
1905 | $groupID = $group['id']; | |
1906 | if (!empty($properties['customValue'])) { | |
1907 | foreach ($properties['customValue'] as $values) { | |
e41f4660 PJ |
1908 | if (!empty($customValueId) && $customValueId != $values['id']) { |
1909 | continue; | |
1910 | } | |
9c1bc317 CW |
1911 | $details[$groupID][$values['id']]['title'] = $group['title'] ?? NULL; |
1912 | $details[$groupID][$values['id']]['name'] = $group['name'] ?? NULL; | |
1913 | $details[$groupID][$values['id']]['help_pre'] = $group['help_pre'] ?? NULL; | |
1914 | $details[$groupID][$values['id']]['help_post'] = $group['help_post'] ?? NULL; | |
1915 | $details[$groupID][$values['id']]['collapse_display'] = $group['collapse_display'] ?? NULL; | |
1916 | $details[$groupID][$values['id']]['collapse_adv_display'] = $group['collapse_adv_display'] ?? NULL; | |
1917 | $details[$groupID][$values['id']]['style'] = $group['style'] ?? NULL; | |
be2fb01f | 1918 | $details[$groupID][$values['id']]['fields'][$k] = [ |
6b409353 CW |
1919 | 'field_title' => $properties['label'] ?? NULL, |
1920 | 'field_type' => $properties['html_type'] ?? NULL, | |
1921 | 'field_data_type' => $properties['data_type'] ?? NULL, | |
080d719e | 1922 | 'field_value' => CRM_Core_BAO_CustomField::displayValue($values['data'], $properties['id'], $entityId), |
6b409353 | 1923 | 'options_per_line' => $properties['options_per_line'] ?? NULL, |
be2fb01f | 1924 | ]; |
7dcdb6fa CW |
1925 | // editable = whether this set contains any non-read-only fields |
1926 | if (!isset($details[$groupID][$values['id']]['editable'])) { | |
1927 | $details[$groupID][$values['id']]['editable'] = FALSE; | |
1928 | } | |
317103ab | 1929 | if (empty($properties['is_view']) && in_array($key, $editableGroups)) { |
7dcdb6fa CW |
1930 | $details[$groupID][$values['id']]['editable'] = TRUE; |
1931 | } | |
6a488035 | 1932 | // also return contact reference contact id if user has view all or edit all contacts perm |
a61d2ab7 CW |
1933 | if ($details[$groupID][$values['id']]['fields'][$k]['field_data_type'] === 'ContactReference' |
1934 | && CRM_Core_Permission::check([['view all contacts', 'edit all contacts']]) | |
6a488035 | 1935 | ) { |
a61d2ab7 CW |
1936 | $details[$groupID][$values['id']]['fields'][$k]['contact_ref_links'] = []; |
1937 | $path = CRM_Contact_DAO_Contact::getEntityPaths()['view']; | |
1938 | foreach (CRM_Utils_Array::explodePadded($values['data'] ?? []) as $contactId) { | |
1939 | $displayName = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $contactId, 'display_name'); | |
1940 | if ($displayName) { | |
1941 | $url = CRM_Utils_System::url(str_replace('[id]', $contactId, $path)); | |
1942 | $details[$groupID][$values['id']]['fields'][$k]['contact_ref_links'][] = '<a href="' . $url . '" title="' . htmlspecialchars(ts('View Contact')) . '">' . | |
1943 | $displayName . '</a>'; | |
1944 | } | |
1945 | } | |
6a488035 TO |
1946 | } |
1947 | } | |
1948 | } | |
1949 | else { | |
9c1bc317 CW |
1950 | $details[$groupID][0]['title'] = $group['title'] ?? NULL; |
1951 | $details[$groupID][0]['name'] = $group['name'] ?? NULL; | |
1952 | $details[$groupID][0]['help_pre'] = $group['help_pre'] ?? NULL; | |
1953 | $details[$groupID][0]['help_post'] = $group['help_post'] ?? NULL; | |
1954 | $details[$groupID][0]['collapse_display'] = $group['collapse_display'] ?? NULL; | |
1955 | $details[$groupID][0]['collapse_adv_display'] = $group['collapse_adv_display'] ?? NULL; | |
1956 | $details[$groupID][0]['style'] = $group['style'] ?? NULL; | |
a61d2ab7 | 1957 | $details[$groupID][0]['fields'][$k] = ['field_title' => $properties['label'] ?? NULL]; |
6a488035 TO |
1958 | } |
1959 | } | |
1960 | } | |
1961 | ||
1962 | if ($returnCount) { | |
aa965915 MWMC |
1963 | // return a single value count if group id is passed to function |
1964 | // else return a groupId and count mapped array | |
9d72cede | 1965 | if (!empty($gID)) { |
6a488035 TO |
1966 | return count($details[$gID]); |
1967 | } | |
1968 | else { | |
be2fb01f | 1969 | $countValue = []; |
9d72cede | 1970 | foreach ($details as $key => $value) { |
6a488035 TO |
1971 | $countValue[$key] = count($details[$key]); |
1972 | } | |
1973 | return $countValue; | |
1974 | } | |
1975 | } | |
1976 | else { | |
1977 | $form->assign_by_ref("{$prefix}viewCustomData", $details); | |
1978 | return $details; | |
1979 | } | |
1980 | } | |
1981 | ||
6a488035 TO |
1982 | /** |
1983 | * Get the custom group titles by custom field ids. | |
1984 | * | |
6a0b768e TO |
1985 | * @param array $fieldIds |
1986 | * Array of custom field ids. | |
6a488035 | 1987 | * |
a1a2a83d | 1988 | * @return array|NULL |
a6c01b45 | 1989 | * array consisting of groups and fields labels with ids. |
6a488035 TO |
1990 | */ |
1991 | public static function getGroupTitles($fieldIds) { | |
1992 | if (!is_array($fieldIds) && empty($fieldIds)) { | |
a1a2a83d | 1993 | return NULL; |
6a488035 TO |
1994 | } |
1995 | ||
be2fb01f | 1996 | $groupLabels = []; |
6a488035 TO |
1997 | $fIds = "(" . implode(',', $fieldIds) . ")"; |
1998 | ||
1999 | $query = " | |
2000 | SELECT civicrm_custom_group.id as groupID, civicrm_custom_group.title as groupTitle, | |
2001 | civicrm_custom_field.label as fieldLabel, civicrm_custom_field.id as fieldID | |
2002 | FROM civicrm_custom_group, civicrm_custom_field | |
2003 | WHERE civicrm_custom_group.id = civicrm_custom_field.custom_group_id | |
2004 | AND civicrm_custom_field.id IN {$fIds}"; | |
2005 | ||
2006 | $dao = CRM_Core_DAO::executeQuery($query); | |
2007 | while ($dao->fetch()) { | |
be2fb01f | 2008 | $groupLabels[$dao->fieldID] = [ |
6a488035 TO |
2009 | 'fieldID' => $dao->fieldID, |
2010 | 'fieldLabel' => $dao->fieldLabel, | |
2011 | 'groupID' => $dao->groupID, | |
2012 | 'groupTitle' => $dao->groupTitle, | |
be2fb01f | 2013 | ]; |
6a488035 TO |
2014 | } |
2015 | ||
2016 | return $groupLabels; | |
2017 | } | |
2018 | ||
00be9182 | 2019 | public static function dropAllTables() { |
6a488035 TO |
2020 | $query = "SELECT table_name FROM civicrm_custom_group"; |
2021 | $dao = CRM_Core_DAO::executeQuery($query); | |
2022 | ||
2023 | while ($dao->fetch()) { | |
2024 | $query = "DROP TABLE IF EXISTS {$dao->table_name}"; | |
2025 | CRM_Core_DAO::executeQuery($query); | |
2026 | } | |
2027 | } | |
2028 | ||
2029 | /** | |
2030 | * Check whether custom group is empty or not. | |
2031 | * | |
6a0b768e TO |
2032 | * @param int $gID |
2033 | * Custom group id. | |
6a488035 | 2034 | * |
a1a2a83d | 2035 | * @return bool|NULL |
a6c01b45 | 2036 | * true if empty otherwise false. |
6a488035 | 2037 | */ |
00be9182 | 2038 | public static function isGroupEmpty($gID) { |
6a488035 | 2039 | if (!$gID) { |
a1a2a83d | 2040 | return NULL; |
6a488035 TO |
2041 | } |
2042 | ||
2043 | $tableName = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomGroup', | |
9d72cede EM |
2044 | $gID, |
2045 | 'table_name' | |
2046 | ); | |
6a488035 TO |
2047 | |
2048 | $query = "SELECT count(id) FROM {$tableName} WHERE id IS NOT NULL LIMIT 1"; | |
2049 | $value = CRM_Core_DAO::singleValueQuery($query); | |
2050 | ||
2051 | if (empty($value)) { | |
2052 | return TRUE; | |
2053 | } | |
2054 | ||
2055 | return FALSE; | |
2056 | } | |
2057 | ||
2058 | /** | |
2059 | * Get the list of types for objects that a custom group extends to. | |
2060 | * | |
6a0b768e TO |
2061 | * @param array $types |
2062 | * Var which should have the list appended. | |
6a488035 | 2063 | * |
a6c01b45 | 2064 | * @return array |
16b10e64 | 2065 | * Array of types. |
aa965915 | 2066 | * @throws \Exception |
6a488035 | 2067 | */ |
be2fb01f CW |
2068 | public static function getExtendedObjectTypes(&$types = []) { |
2069 | static $flag = FALSE, $objTypes = []; | |
6a488035 TO |
2070 | |
2071 | if (!$flag) { | |
be2fb01f | 2072 | $extendObjs = []; |
fffc190b | 2073 | CRM_Core_OptionValue::getValues(['name' => 'cg_extend_objects'], $extendObjs, 'weight', TRUE); |
6a488035 TO |
2074 | |
2075 | foreach ($extendObjs as $ovId => $ovValues) { | |
2076 | if ($ovValues['description']) { | |
2077 | // description is expected to be a callback func to subtypes | |
2078 | list($callback, $args) = explode(';', trim($ovValues['description'])); | |
2079 | ||
0e6e8724 | 2080 | if (empty($args)) { |
be2fb01f | 2081 | $args = []; |
6a488035 TO |
2082 | } |
2083 | ||
2084 | if (!is_array($args)) { | |
36769590 | 2085 | throw new CRM_Core_Exception('Arg is not of type array'); |
6a488035 TO |
2086 | } |
2087 | ||
2088 | list($className) = explode('::', $callback); | |
aa965915 | 2089 | require_once str_replace('_', DIRECTORY_SEPARATOR, $className) . '.php'; |
6a488035 TO |
2090 | |
2091 | $objTypes[$ovValues['value']] = call_user_func_array($callback, $args); | |
2092 | } | |
2093 | } | |
2094 | $flag = TRUE; | |
2095 | } | |
2096 | ||
2097 | $types = array_merge($types, $objTypes); | |
2098 | return $objTypes; | |
2099 | } | |
2100 | ||
b5c2afd0 | 2101 | /** |
100fef9d CW |
2102 | * @param int $customGroupId |
2103 | * @param int $entityId | |
b5c2afd0 EM |
2104 | * |
2105 | * @return bool | |
2106 | */ | |
00be9182 | 2107 | public static function hasReachedMaxLimit($customGroupId, $entityId) { |
aa965915 | 2108 | // check whether the group is multiple |
6a488035 | 2109 | $isMultiple = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomGroup', $customGroupId, 'is_multiple'); |
63d76404 | 2110 | $isMultiple = (bool) $isMultiple; |
6a488035 TO |
2111 | $hasReachedMax = FALSE; |
2112 | if ($isMultiple && | |
9d72cede EM |
2113 | ($maxMultiple = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomGroup', $customGroupId, 'max_multiple')) |
2114 | ) { | |
6a488035 TO |
2115 | if (!$maxMultiple) { |
2116 | $hasReachedMax = FALSE; | |
9d72cede EM |
2117 | } |
2118 | else { | |
6a488035 | 2119 | $tableName = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomGroup', $customGroupId, 'table_name'); |
aa965915 | 2120 | // count the number of entries for a entity |
6a488035 | 2121 | $sql = "SELECT COUNT(id) FROM {$tableName} WHERE entity_id = %1"; |
be2fb01f | 2122 | $params = [1 => [$entityId, 'Integer']]; |
6a488035 TO |
2123 | $count = CRM_Core_DAO::singleValueQuery($sql, $params); |
2124 | ||
2125 | if ($count >= $maxMultiple) { | |
2126 | $hasReachedMax = TRUE; | |
2127 | } | |
2128 | } | |
2129 | } | |
2130 | return $hasReachedMax; | |
2131 | } | |
2132 | ||
b5c2afd0 EM |
2133 | /** |
2134 | * @return array | |
2135 | */ | |
00be9182 | 2136 | public static function getMultipleFieldGroup() { |
be2fb01f | 2137 | $multipleGroup = []; |
9ff5f6c0 | 2138 | $dao = new CRM_Core_DAO_CustomGroup(); |
9d72cede | 2139 | $dao->is_multiple = 1; |
209a3cc3 | 2140 | $dao->is_active = 1; |
9ff5f6c0 | 2141 | $dao->find(); |
9d72cede | 2142 | while ($dao->fetch()) { |
9ff5f6c0 N |
2143 | $multipleGroup[$dao->id] = $dao->title; |
2144 | } | |
2145 | return $multipleGroup; | |
2146 | } | |
96025800 | 2147 | |
b2ccd9fe | 2148 | /** |
2149 | * Build the metadata tree for the custom group. | |
2150 | * | |
2151 | * @param string $entityType | |
2152 | * @param array $toReturn | |
2153 | * @param array $subTypes | |
2154 | * @param string $queryString | |
2155 | * @param array $params | |
2156 | * @param string $subType | |
2157 | * | |
2158 | * @return array | |
2159 | * @throws \CRM_Core_Exception | |
2160 | */ | |
2161 | private static function buildGroupTree($entityType, $toReturn, $subTypes, $queryString, $params, $subType) { | |
2162 | $groupTree = $multipleFieldGroups = []; | |
2163 | $crmDAO = CRM_Core_DAO::executeQuery($queryString, $params); | |
2164 | $customValueTables = []; | |
2165 | ||
2166 | // process records | |
2167 | while ($crmDAO->fetch()) { | |
2168 | // get the id's | |
2169 | $groupID = $crmDAO->civicrm_custom_group_id; | |
2170 | $fieldId = $crmDAO->civicrm_custom_field_id; | |
2171 | if ($crmDAO->civicrm_custom_group_is_multiple) { | |
2172 | $multipleFieldGroups[$groupID] = $crmDAO->civicrm_custom_group_table_name; | |
2173 | } | |
2174 | // create an array for groups if it does not exist | |
2175 | if (!array_key_exists($groupID, $groupTree)) { | |
2176 | $groupTree[$groupID] = []; | |
2177 | $groupTree[$groupID]['id'] = $groupID; | |
2178 | ||
2179 | // populate the group information | |
2180 | foreach ($toReturn['custom_group'] as $fieldName) { | |
2181 | $fullFieldName = "civicrm_custom_group_$fieldName"; | |
2182 | if ($fieldName == 'id' || | |
2183 | is_null($crmDAO->$fullFieldName) | |
2184 | ) { | |
2185 | continue; | |
2186 | } | |
2187 | // CRM-5507 | |
2188 | // This is an old bit of code - per the CRM number & probably does not work reliably if | |
2189 | // that one contact sub-type exists. | |
2190 | if ($fieldName == 'extends_entity_column_value' && !empty($subTypes[0])) { | |
2191 | $groupTree[$groupID]['subtype'] = self::validateSubTypeByEntity($entityType, $subType); | |
2192 | } | |
2193 | $groupTree[$groupID][$fieldName] = $crmDAO->$fullFieldName; | |
2194 | } | |
2195 | $groupTree[$groupID]['fields'] = []; | |
2196 | ||
2197 | $customValueTables[$crmDAO->civicrm_custom_group_table_name] = []; | |
2198 | } | |
2199 | ||
2200 | // add the fields now (note - the query row will always contain a field) | |
2201 | // we only reset this once, since multiple values come is as multiple rows | |
2202 | if (!array_key_exists($fieldId, $groupTree[$groupID]['fields'])) { | |
2203 | $groupTree[$groupID]['fields'][$fieldId] = []; | |
2204 | } | |
2205 | ||
2206 | $customValueTables[$crmDAO->civicrm_custom_group_table_name][$crmDAO->civicrm_custom_field_column_name] = 1; | |
2207 | $groupTree[$groupID]['fields'][$fieldId]['id'] = $fieldId; | |
2208 | // populate information for a custom field | |
2209 | foreach ($toReturn['custom_field'] as $fieldName) { | |
2210 | $fullFieldName = "civicrm_custom_field_$fieldName"; | |
2211 | if ($fieldName == 'id' || | |
2212 | is_null($crmDAO->$fullFieldName) | |
2213 | ) { | |
2214 | continue; | |
2215 | } | |
2216 | $groupTree[$groupID]['fields'][$fieldId][$fieldName] = $crmDAO->$fullFieldName; | |
2217 | } | |
2218 | } | |
2219 | ||
2220 | if (!empty($customValueTables)) { | |
2221 | $groupTree['info'] = ['tables' => $customValueTables]; | |
2222 | } | |
2223 | return [$multipleFieldGroups, $groupTree]; | |
2224 | } | |
2225 | ||
13d328b3 SL |
2226 | public static function getSubTypes(): array { |
2227 | $sel2 = []; | |
2228 | $activityType = CRM_Core_PseudoConstant::activityType(FALSE, TRUE, FALSE, 'label', TRUE); | |
2229 | ||
2230 | $eventType = CRM_Core_OptionGroup::values('event_type'); | |
2231 | $grantType = CRM_Core_OptionGroup::values('grant_type'); | |
2232 | $campaignTypes = CRM_Campaign_PseudoConstant::campaignType(); | |
2233 | $membershipType = CRM_Member_BAO_MembershipType::getMembershipTypes(FALSE); | |
2234 | $participantRole = CRM_Core_OptionGroup::values('participant_role'); | |
2235 | ||
2236 | asort($activityType); | |
2237 | asort($eventType); | |
2238 | asort($grantType); | |
2239 | asort($membershipType); | |
2240 | asort($participantRole); | |
2241 | ||
2242 | $sel2['Event'] = $eventType; | |
2243 | $sel2['Grant'] = $grantType; | |
2244 | $sel2['Activity'] = $activityType; | |
2245 | $sel2['Campaign'] = $campaignTypes; | |
2246 | $sel2['Membership'] = $membershipType; | |
2247 | $sel2['ParticipantRole'] = $participantRole; | |
2248 | $sel2['ParticipantEventName'] = CRM_Event_PseudoConstant::event(NULL, FALSE, "( is_template IS NULL OR is_template != 1 )"); | |
2249 | $sel2['ParticipantEventType'] = $eventType; | |
2250 | $sel2['Contribution'] = CRM_Contribute_PseudoConstant::financialType(); | |
2251 | $sel2['Relationship'] = CRM_Custom_Form_Group::getRelationshipTypes(); | |
2252 | ||
2253 | $sel2['Individual'] = CRM_Contact_BAO_ContactType::subTypePairs('Individual', FALSE, NULL); | |
2254 | $sel2['Household'] = CRM_Contact_BAO_ContactType::subTypePairs('Household', FALSE, NULL); | |
2255 | $sel2['Organization'] = CRM_Contact_BAO_ContactType::subTypePairs('Organization', FALSE, NULL); | |
2256 | ||
2257 | CRM_Core_BAO_CustomGroup::getExtendedObjectTypes($sel2); | |
2258 | return $sel2; | |
2259 | } | |
2260 | ||
92ef7828 SL |
2261 | /** |
2262 | * Get the munged entity. | |
2263 | * | |
2264 | * This is the entity eg. Relationship or the name of the sub entity | |
2265 | * e.g ParticipantRole. | |
2266 | * | |
2267 | * @param string $extends | |
2268 | * @param int|null $extendsEntityColumn | |
2269 | * | |
2270 | * @return string | |
2271 | */ | |
2272 | protected static function getMungedEntity($extends, $extendsEntityColumn = NULL) { | |
2273 | if (!$extendsEntityColumn || $extendsEntityColumn === 'null') { | |
2274 | return $extends; | |
2275 | } | |
2276 | return CRM_Core_OptionGroup::values('custom_data_type', FALSE, FALSE, FALSE, NULL, 'name')[$extendsEntityColumn]; | |
2277 | } | |
2278 | ||
317103ab CW |
2279 | /** |
2280 | * @param int $groupId | |
2281 | * @param int $operation | |
2282 | * @param int|null $userId | |
2283 | */ | |
2284 | public static function checkGroupAccess($groupId, $operation = CRM_Core_Permission::EDIT, $userId = NULL): bool { | |
2285 | $allowedGroups = CRM_Core_Permission::customGroup($operation, FALSE, $userId); | |
2286 | return in_array($groupId, $allowedGroups); | |
2287 | } | |
2288 | ||
9d72cede | 2289 | } |