Merge pull request #12558 from totten/master-prevnext-misc
[civicrm-core.git] / CRM / Case / BAO / CaseType.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 5 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2018 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
9 | |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
13 | |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
18 | |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
26 */
27
28 /**
29 *
30 * @package CRM
31 * @copyright CiviCRM LLC (c) 2004-2018
32 */
33
34 /**
35 * This class contains the functions for Case Type management.
36 */
37 class CRM_Case_BAO_CaseType extends CRM_Case_DAO_CaseType {
38
39 /**
40 * Static field for all the case information that we can potentially export.
41 *
42 * @var array
43 */
44 static $_exportableFields = NULL;
45
46 /**
47 * Takes an associative array and creates a Case Type object.
48 *
49 * the function extract all the params it needs to initialize the create a
50 * case type object. the params array could contain additional unused name/value
51 * pairs
52 *
53 * @param array $params
54 * (reference ) an assoc array of name/value pairs.
55 *
56 * @throws CRM_Core_Exception
57 *
58 * @return CRM_Case_BAO_CaseType
59 */
60 public static function add(&$params) {
61 $caseTypeDAO = new CRM_Case_DAO_CaseType();
62
63 // form the name only if missing: CRM-627
64 $nameParam = CRM_Utils_Array::value('name', $params, NULL);
65 if (!$nameParam && empty($params['id'])) {
66 $params['name'] = CRM_Utils_String::titleToVar($params['title']);
67 }
68
69 // Old case-types (pre-4.5) may keep their ucky names, but new case-types must satisfy isValidName()
70 if (empty($params['id']) && !empty($params['name']) && !CRM_Case_BAO_CaseType::isValidName($params['name'])) {
71 throw new CRM_Core_Exception("Cannot create new case-type with malformed name [{$params['name']}]");
72 }
73
74 $caseTypeName = (isset($params['name'])) ? $params['name'] : CRM_Core_DAO::getFieldValue('CRM_Case_DAO_CaseType', $params['id'], 'name', 'id', TRUE);
75
76 // function to format definition column
77 if (isset($params['definition']) && is_array($params['definition'])) {
78 $params['definition'] = self::convertDefinitionToXML($caseTypeName, $params['definition']);
79 CRM_Core_ManagedEntities::scheduleReconciliation();
80 }
81
82 $caseTypeDAO->copyValues($params);
83 $result = $caseTypeDAO->save();
84 CRM_Case_XMLRepository::singleton()->flush();
85 return $result;
86 }
87
88 /**
89 * Generate and assign an arbitrary value to a field of a test object.
90 *
91 * @param string $fieldName
92 * @param array $fieldDef
93 * @param int $counter
94 * The globally-unique ID of the test object.
95 */
96 protected function assignTestValue($fieldName, &$fieldDef, $counter) {
97 if ($fieldName == 'definition') {
98 $this->{$fieldName} = "<CaseType><name>TestCaseType{$counter}</name></CaseType>";
99 }
100 else {
101 parent::assignTestValue($fieldName, $fieldDef, $counter);
102 }
103 }
104
105
106 /**
107 * Format / convert submitted array to xml for case type definition
108 *
109 * @param string $name
110 * @param array $definition
111 * The case-type definition expressed as an array-tree.
112 * @return string
113 * XML
114 */
115 public static function convertDefinitionToXML($name, $definition) {
116 $xmlFile = '<?xml version="1.0" encoding="utf-8" ?>' . "\n\n<CaseType>\n";
117 $xmlFile .= "<name>" . self::encodeXmlString($name) . "</name>\n";
118
119 if (array_key_exists('forkable', $definition)) {
120 $xmlFile .= "<forkable>" . ((int) $definition['forkable']) . "</forkable>\n";
121 }
122
123 if (isset($definition['activityTypes'])) {
124 $xmlFile .= "<ActivityTypes>\n";
125 foreach ($definition['activityTypes'] as $values) {
126 $xmlFile .= "<ActivityType>\n";
127 foreach ($values as $key => $value) {
128 $xmlFile .= "<{$key}>" . self::encodeXmlString($value) . "</{$key}>\n";
129 }
130 $xmlFile .= "</ActivityType>\n";
131 }
132 $xmlFile .= "</ActivityTypes>\n";
133 }
134
135 if (!empty($definition['statuses'])) {
136 $xmlFile .= "<Statuses>\n";
137 foreach ($definition['statuses'] as $value) {
138 $xmlFile .= "<Status>$value</Status>\n";
139 }
140 $xmlFile .= "</Statuses>\n";
141 }
142
143 if (isset($definition['activitySets'])) {
144 $xmlFile .= "<ActivitySets>\n";
145 foreach ($definition['activitySets'] as $k => $val) {
146 $xmlFile .= "<ActivitySet>\n";
147 foreach ($val as $index => $setVal) {
148 switch ($index) {
149 case 'activityTypes':
150 if (!empty($setVal)) {
151 $xmlFile .= "<ActivityTypes>\n";
152 foreach ($setVal as $values) {
153 $xmlFile .= "<ActivityType>\n";
154 foreach ($values as $key => $value) {
155 $xmlFile .= "<{$key}>" . self::encodeXmlString($value) . "</{$key}>\n";
156 }
157 $xmlFile .= "</ActivityType>\n";
158 }
159 $xmlFile .= "</ActivityTypes>\n";
160 }
161 break;
162
163 case 'sequence': // passthrough
164 case 'timeline':
165 if ($setVal) {
166 $xmlFile .= "<{$index}>true</{$index}>\n";
167 }
168 break;
169
170 default:
171 $xmlFile .= "<{$index}>" . self::encodeXmlString($setVal) . "</{$index}>\n";
172 }
173 }
174
175 $xmlFile .= "</ActivitySet>\n";
176 }
177
178 $xmlFile .= "</ActivitySets>\n";
179 }
180
181 if (isset($definition['caseRoles'])) {
182 $xmlFile .= "<CaseRoles>\n";
183 foreach ($definition['caseRoles'] as $values) {
184 $xmlFile .= "<RelationshipType>\n";
185 foreach ($values as $key => $value) {
186 $xmlFile .= "<{$key}>" . self::encodeXmlString($value) . "</{$key}>\n";
187 }
188 $xmlFile .= "</RelationshipType>\n";
189 }
190 $xmlFile .= "</CaseRoles>\n";
191 }
192
193 $xmlFile .= '</CaseType>';
194 return $xmlFile;
195 }
196
197 /**
198 * Ugh. This shouldn't exist. Use a real XML-encoder.
199 *
200 * Escape a string for use in XML.
201 *
202 * @param string $str
203 * A string which should outputted to XML.
204 * @return string
205 * @deprecated
206 */
207 protected static function encodeXmlString($str) {
208 // PHP 5.4: return htmlspecialchars($str, ENT_XML1, 'UTF-8')
209 return htmlspecialchars($str);
210 }
211
212 /**
213 * Get the case definition either from db or read from xml file.
214 *
215 * @param SimpleXmlElement $xml
216 * A single case-type record.
217 *
218 * @return array
219 * the definition of the case-type, expressed as PHP array-tree
220 */
221 public static function convertXmlToDefinition($xml) {
222 // build PHP array based on definition
223 $definition = array();
224
225 if (isset($xml->forkable)) {
226 $definition['forkable'] = (int) $xml->forkable;
227 }
228
229 // set activity types
230 if (isset($xml->ActivityTypes)) {
231 $definition['activityTypes'] = array();
232 foreach ($xml->ActivityTypes->ActivityType as $activityTypeXML) {
233 $definition['activityTypes'][] = json_decode(json_encode($activityTypeXML), TRUE);
234 }
235 }
236
237 // set statuses
238 if (isset($xml->Statuses)) {
239 $definition['statuses'] = (array) $xml->Statuses->Status;
240 }
241
242 // set activity sets
243 if (isset($xml->ActivitySets)) {
244 $definition['activitySets'] = array();
245 $definition['timelineActivityTypes'] = array();
246
247 foreach ($xml->ActivitySets->ActivitySet as $activitySetXML) {
248 // parse basic properties
249 $activitySet = array();
250 $activitySet['name'] = (string) $activitySetXML->name;
251 $activitySet['label'] = (string) $activitySetXML->label;
252 if ('true' == (string) $activitySetXML->timeline) {
253 $activitySet['timeline'] = 1;
254 }
255 if ('true' == (string) $activitySetXML->sequence) {
256 $activitySet['sequence'] = 1;
257 }
258
259 if (isset($activitySetXML->ActivityTypes)) {
260 $activitySet['activityTypes'] = array();
261 foreach ($activitySetXML->ActivityTypes->ActivityType as $activityTypeXML) {
262 $activityType = json_decode(json_encode($activityTypeXML), TRUE);
263 $activitySet['activityTypes'][] = $activityType;
264 if ($activitySetXML->timeline) {
265 $definition['timelineActivityTypes'][] = $activityType;
266 }
267 }
268 }
269 $definition['activitySets'][] = $activitySet;
270 }
271 }
272
273 // set case roles
274 if (isset($xml->CaseRoles)) {
275 $definition['caseRoles'] = array();
276 foreach ($xml->CaseRoles->RelationshipType as $caseRoleXml) {
277 $definition['caseRoles'][] = json_decode(json_encode($caseRoleXml), TRUE);
278 }
279 }
280
281 return $definition;
282 }
283
284 /**
285 * Given the list of params in the params array, fetch the object
286 * and store the values in the values array
287 *
288 * @param array $params
289 * Input parameters to find object.
290 * @param array $values
291 * Output values of the object.
292 *
293 * @return CRM_Case_BAO_CaseType|null the found object or null
294 */
295 public static function &getValues(&$params, &$values) {
296 $caseType = new CRM_Case_BAO_CaseType();
297
298 $caseType->copyValues($params);
299
300 if ($caseType->find(TRUE)) {
301 CRM_Core_DAO::storeValues($caseType, $values);
302 return $caseType;
303 }
304 return NULL;
305 }
306
307 /**
308 * Takes an associative array and creates a case type object.
309 *
310 * @param array $params
311 * (reference ) an assoc array of name/value pairs.
312 *
313 * @return CRM_Case_BAO_CaseType
314 */
315 public static function &create(&$params) {
316 $transaction = new CRM_Core_Transaction();
317
318 if (!empty($params['id'])) {
319 CRM_Utils_Hook::pre('edit', 'CaseType', $params['id'], $params);
320 }
321 else {
322 CRM_Utils_Hook::pre('create', 'CaseType', NULL, $params);
323 }
324
325 $caseType = self::add($params);
326
327 if (is_a($caseType, 'CRM_Core_Error')) {
328 $transaction->rollback();
329 return $caseType;
330 }
331
332 if (!empty($params['id'])) {
333 CRM_Utils_Hook::post('edit', 'CaseType', $caseType->id, $case);
334 }
335 else {
336 CRM_Utils_Hook::post('create', 'CaseType', $caseType->id, $case);
337 }
338 $transaction->commit();
339 CRM_Case_XMLRepository::singleton(TRUE);
340 CRM_Core_OptionGroup::flushAll();
341
342 return $caseType;
343 }
344
345 /**
346 * Retrieve DB object based on input parameters.
347 *
348 * It also stores all the retrieved values in the default array.
349 *
350 * @param array $params
351 * (reference ) an assoc array of name/value pairs.
352 * @param array $defaults
353 * (reference ) an assoc array to hold the name / value pairs.
354 * in a hierarchical manner
355 *
356 * @return CRM_Case_BAO_CaseType
357 */
358 public static function retrieve(&$params, &$defaults) {
359 $caseType = CRM_Case_BAO_CaseType::getValues($params, $defaults);
360 return $caseType;
361 }
362
363 /**
364 * @param int $caseTypeId
365 *
366 * @throws CRM_Core_Exception
367 * @return mixed
368 */
369 public static function del($caseTypeId) {
370 $caseType = new CRM_Case_DAO_CaseType();
371 $caseType->id = $caseTypeId;
372 $refCounts = $caseType->getReferenceCounts();
373 $total = array_sum(CRM_Utils_Array::collect('count', $refCounts));
374 if ($total) {
375 throw new CRM_Core_Exception(ts("You can not delete this case type -- it is assigned to %1 existing case record(s). If you do not want this case type to be used going forward, consider disabling it instead.", array(1 => $total)));
376 }
377 $result = $caseType->delete();
378 CRM_Case_XMLRepository::singleton(TRUE);
379 return $result;
380 }
381
382 /**
383 * Determine if a case-type name is well-formed
384 *
385 * @param string $caseType
386 * @return bool
387 */
388 public static function isValidName($caseType) {
389 return preg_match('/^[a-zA-Z0-9_]+$/', $caseType);
390 }
391
392 /**
393 * Determine if the case-type has *both* DB and file-based definitions.
394 *
395 * @param int $caseTypeId
396 * @return bool|null
397 * TRUE if there are *both* DB and file-based definitions
398 */
399 public static function isForked($caseTypeId) {
400 $caseTypeName = CRM_Core_DAO::getFieldValue('CRM_Case_DAO_CaseType', $caseTypeId, 'name', 'id', TRUE);
401 if ($caseTypeName) {
402 $dbDefinition = CRM_Core_DAO::getFieldValue('CRM_Case_DAO_CaseType', $caseTypeId, 'definition', 'id', TRUE);
403 $fileDefinition = CRM_Case_XMLRepository::singleton()->retrieveFile($caseTypeName);
404 return $fileDefinition && $dbDefinition;
405 }
406 return NULL;
407 }
408
409 /**
410 * Determine if modifications are allowed on the case-type
411 *
412 * @param int $caseTypeId
413 * @return bool
414 * TRUE if the definition can be modified
415 */
416 public static function isForkable($caseTypeId) {
417 $caseTypeName = CRM_Core_DAO::getFieldValue('CRM_Case_DAO_CaseType', $caseTypeId, 'name', 'id', TRUE);
418 if ($caseTypeName) {
419 // if file-based definition explicitly disables "forkable" option, then don't allow changes to definition
420 $fileDefinition = CRM_Case_XMLRepository::singleton()->retrieveFile($caseTypeName);
421 if ($fileDefinition && isset($fileDefinition->forkable)) {
422 return CRM_Utils_String::strtobool((string) $fileDefinition->forkable);
423 }
424 }
425 return TRUE;
426 }
427
428 }