Merge pull request #10462 from civicrm/4.7.20-rc
[civicrm-core.git] / CRM / Case / BAO / CaseType.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2017 |
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-2017
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 return $caseTypeDAO->save();
84 }
85
86 /**
87 * Generate and assign an arbitrary value to a field of a test object.
88 *
89 * @param string $fieldName
90 * @param array $fieldDef
91 * @param int $counter
92 * The globally-unique ID of the test object.
93 */
94 protected function assignTestValue($fieldName, &$fieldDef, $counter) {
95 if ($fieldName == 'definition') {
96 $this->{$fieldName} = "<CaseType><name>TestCaseType{$counter}</name></CaseType>";
97 }
98 else {
99 parent::assignTestValue($fieldName, $fieldDef, $counter);
100 }
101 }
102
103
104 /**
105 * Format / convert submitted array to xml for case type definition
106 *
107 * @param string $name
108 * @param array $definition
109 * The case-type definition expressed as an array-tree.
110 * @return string
111 * XML
112 */
113 public static function convertDefinitionToXML($name, $definition) {
114 $xmlFile = '<?xml version="1.0" encoding="utf-8" ?>' . "\n\n<CaseType>\n";
115 $xmlFile .= "<name>" . self::encodeXmlString($name) . "</name>\n";
116
117 if (array_key_exists('forkable', $definition)) {
118 $xmlFile .= "<forkable>" . ((int) $definition['forkable']) . "</forkable>\n";
119 }
120
121 if (isset($definition['activityTypes'])) {
122 $xmlFile .= "<ActivityTypes>\n";
123 foreach ($definition['activityTypes'] as $values) {
124 $xmlFile .= "<ActivityType>\n";
125 foreach ($values as $key => $value) {
126 $xmlFile .= "<{$key}>" . self::encodeXmlString($value) . "</{$key}>\n";
127 }
128 $xmlFile .= "</ActivityType>\n";
129 }
130 $xmlFile .= "</ActivityTypes>\n";
131 }
132
133 if (!empty($definition['statuses'])) {
134 $xmlFile .= "<Statuses>\n";
135 foreach ($definition['statuses'] as $value) {
136 $xmlFile .= "<Status>$value</Status>\n";
137 }
138 $xmlFile .= "</Statuses>\n";
139 }
140
141 if (isset($definition['activitySets'])) {
142 $xmlFile .= "<ActivitySets>\n";
143 foreach ($definition['activitySets'] as $k => $val) {
144 $xmlFile .= "<ActivitySet>\n";
145 foreach ($val as $index => $setVal) {
146 switch ($index) {
147 case 'activityTypes':
148 if (!empty($setVal)) {
149 $xmlFile .= "<ActivityTypes>\n";
150 foreach ($setVal as $values) {
151 $xmlFile .= "<ActivityType>\n";
152 foreach ($values as $key => $value) {
153 $xmlFile .= "<{$key}>" . self::encodeXmlString($value) . "</{$key}>\n";
154 }
155 $xmlFile .= "</ActivityType>\n";
156 }
157 $xmlFile .= "</ActivityTypes>\n";
158 }
159 break;
160
161 case 'sequence': // passthrough
162 case 'timeline':
163 if ($setVal) {
164 $xmlFile .= "<{$index}>true</{$index}>\n";
165 }
166 break;
167
168 default:
169 $xmlFile .= "<{$index}>" . self::encodeXmlString($setVal) . "</{$index}>\n";
170 }
171 }
172
173 $xmlFile .= "</ActivitySet>\n";
174 }
175
176 $xmlFile .= "</ActivitySets>\n";
177 }
178
179 if (isset($definition['caseRoles'])) {
180 $xmlFile .= "<CaseRoles>\n";
181 foreach ($definition['caseRoles'] as $values) {
182 $xmlFile .= "<RelationshipType>\n";
183 foreach ($values as $key => $value) {
184 $xmlFile .= "<{$key}>" . self::encodeXmlString($value) . "</{$key}>\n";
185 }
186 $xmlFile .= "</RelationshipType>\n";
187 }
188 $xmlFile .= "</CaseRoles>\n";
189 }
190
191 $xmlFile .= '</CaseType>';
192 return $xmlFile;
193 }
194
195 /**
196 * Ugh. This shouldn't exist. Use a real XML-encoder.
197 *
198 * Escape a string for use in XML.
199 *
200 * @param string $str
201 * A string which should outputted to XML.
202 * @return string
203 * @deprecated
204 */
205 protected static function encodeXmlString($str) {
206 // PHP 5.4: return htmlspecialchars($str, ENT_XML1, 'UTF-8')
207 return htmlspecialchars($str);
208 }
209
210 /**
211 * Get the case definition either from db or read from xml file.
212 *
213 * @param SimpleXmlElement $xml
214 * A single case-type record.
215 *
216 * @return array
217 * the definition of the case-type, expressed as PHP array-tree
218 */
219 public static function convertXmlToDefinition($xml) {
220 // build PHP array based on definition
221 $definition = array();
222
223 if (isset($xml->forkable)) {
224 $definition['forkable'] = (int) $xml->forkable;
225 }
226
227 // set activity types
228 if (isset($xml->ActivityTypes)) {
229 $definition['activityTypes'] = array();
230 foreach ($xml->ActivityTypes->ActivityType as $activityTypeXML) {
231 $definition['activityTypes'][] = json_decode(json_encode($activityTypeXML), TRUE);
232 }
233 }
234
235 // set statuses
236 if (isset($xml->Statuses)) {
237 $definition['statuses'] = (array) $xml->Statuses->Status;
238 }
239
240 // set activity sets
241 if (isset($xml->ActivitySets)) {
242 $definition['activitySets'] = array();
243 foreach ($xml->ActivitySets->ActivitySet as $activitySetXML) {
244 // parse basic properties
245 $activitySet = array();
246 $activitySet['name'] = (string) $activitySetXML->name;
247 $activitySet['label'] = (string) $activitySetXML->label;
248 if ('true' == (string) $activitySetXML->timeline) {
249 $activitySet['timeline'] = 1;
250 }
251 if ('true' == (string) $activitySetXML->sequence) {
252 $activitySet['sequence'] = 1;
253 }
254
255 if (isset($activitySetXML->ActivityTypes)) {
256 $activitySet['activityTypes'] = array();
257 foreach ($activitySetXML->ActivityTypes->ActivityType as $activityTypeXML) {
258 $activitySet['activityTypes'][] = json_decode(json_encode($activityTypeXML), TRUE);
259 }
260 }
261 $definition['activitySets'][] = $activitySet;
262 }
263 }
264
265 // set case roles
266 if (isset($xml->CaseRoles)) {
267 $definition['caseRoles'] = array();
268 foreach ($xml->CaseRoles->RelationshipType as $caseRoleXml) {
269 $definition['caseRoles'][] = json_decode(json_encode($caseRoleXml), TRUE);
270 }
271 }
272
273 return $definition;
274 }
275
276 /**
277 * Given the list of params in the params array, fetch the object
278 * and store the values in the values array
279 *
280 * @param array $params
281 * Input parameters to find object.
282 * @param array $values
283 * Output values of the object.
284 *
285 * @return CRM_Case_BAO_CaseType|null the found object or null
286 */
287 public static function &getValues(&$params, &$values) {
288 $caseType = new CRM_Case_BAO_CaseType();
289
290 $caseType->copyValues($params);
291
292 if ($caseType->find(TRUE)) {
293 CRM_Core_DAO::storeValues($caseType, $values);
294 return $caseType;
295 }
296 return NULL;
297 }
298
299 /**
300 * Takes an associative array and creates a case type object.
301 *
302 * @param array $params
303 * (reference ) an assoc array of name/value pairs.
304 *
305 * @return CRM_Case_BAO_CaseType
306 */
307 public static function &create(&$params) {
308 $transaction = new CRM_Core_Transaction();
309
310 if (!empty($params['id'])) {
311 CRM_Utils_Hook::pre('edit', 'CaseType', $params['id'], $params);
312 }
313 else {
314 CRM_Utils_Hook::pre('create', 'CaseType', NULL, $params);
315 }
316
317 $caseType = self::add($params);
318
319 if (is_a($caseType, 'CRM_Core_Error')) {
320 $transaction->rollback();
321 return $caseType;
322 }
323
324 if (!empty($params['id'])) {
325 CRM_Utils_Hook::post('edit', 'CaseType', $caseType->id, $case);
326 }
327 else {
328 CRM_Utils_Hook::post('create', 'CaseType', $caseType->id, $case);
329 }
330 $transaction->commit();
331 CRM_Case_XMLRepository::singleton(TRUE);
332
333 return $caseType;
334 }
335
336 /**
337 * Retrieve DB object based on input parameters.
338 *
339 * It also stores all the retrieved values in the default array.
340 *
341 * @param array $params
342 * (reference ) an assoc array of name/value pairs.
343 * @param array $defaults
344 * (reference ) an assoc array to hold the name / value pairs.
345 * in a hierarchical manner
346 *
347 * @return CRM_Case_BAO_CaseType
348 */
349 public static function retrieve(&$params, &$defaults) {
350 $caseType = CRM_Case_BAO_CaseType::getValues($params, $defaults);
351 return $caseType;
352 }
353
354 /**
355 * @param int $caseTypeId
356 *
357 * @throws CRM_Core_Exception
358 * @return mixed
359 */
360 public static function del($caseTypeId) {
361 $caseType = new CRM_Case_DAO_CaseType();
362 $caseType->id = $caseTypeId;
363 $refCounts = $caseType->getReferenceCounts();
364 $total = array_sum(CRM_Utils_Array::collect('count', $refCounts));
365 if ($total) {
366 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)));
367 }
368 $result = $caseType->delete();
369 CRM_Case_XMLRepository::singleton(TRUE);
370 return $result;
371 }
372
373 /**
374 * Determine if a case-type name is well-formed
375 *
376 * @param string $caseType
377 * @return bool
378 */
379 public static function isValidName($caseType) {
380 return preg_match('/^[a-zA-Z0-9_]+$/', $caseType);
381 }
382
383 /**
384 * Determine if the case-type has *both* DB and file-based definitions.
385 *
386 * @param int $caseTypeId
387 * @return bool|null
388 * TRUE if there are *both* DB and file-based definitions
389 */
390 public static function isForked($caseTypeId) {
391 $caseTypeName = CRM_Core_DAO::getFieldValue('CRM_Case_DAO_CaseType', $caseTypeId, 'name', 'id', TRUE);
392 if ($caseTypeName) {
393 $dbDefinition = CRM_Core_DAO::getFieldValue('CRM_Case_DAO_CaseType', $caseTypeId, 'definition', 'id', TRUE);
394 $fileDefinition = CRM_Case_XMLRepository::singleton()->retrieveFile($caseTypeName);
395 return $fileDefinition && $dbDefinition;
396 }
397 return NULL;
398 }
399
400 /**
401 * Determine if modifications are allowed on the case-type
402 *
403 * @param int $caseTypeId
404 * @return bool
405 * TRUE if the definition can be modified
406 */
407 public static function isForkable($caseTypeId) {
408 $caseTypeName = CRM_Core_DAO::getFieldValue('CRM_Case_DAO_CaseType', $caseTypeId, 'name', 'id', TRUE);
409 if ($caseTypeName) {
410 // if file-based definition explicitly disables "forkable" option, then don't allow changes to definition
411 $fileDefinition = CRM_Case_XMLRepository::singleton()->retrieveFile($caseTypeName);
412 if ($fileDefinition && isset($fileDefinition->forkable)) {
413 return CRM_Utils_String::strtobool((string) $fileDefinition->forkable);
414 }
415 }
416 return TRUE;
417 }
418
419 }