INFRA-132 - Put space after flow-control (if/switch/for/foreach/while)
[civicrm-core.git] / api / v3 / Activity.php
1 <?php
2 // $Id$
3
4 /*
5 +--------------------------------------------------------------------+
6 | CiviCRM version 4.6 |
7 +--------------------------------------------------------------------+
8 | Copyright CiviCRM LLC (c) 2004-2014 |
9 +--------------------------------------------------------------------+
10 | This file is a part of CiviCRM. |
11 | |
12 | CiviCRM is free software; you can copy, modify, and distribute it |
13 | under the terms of the GNU Affero General Public License |
14 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
15 | |
16 | CiviCRM is distributed in the hope that it will be useful, but |
17 | WITHOUT ANY WARRANTY; without even the implied warranty of |
18 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
19 | See the GNU Affero General Public License for more details. |
20 | |
21 | You should have received a copy of the GNU Affero General Public |
22 | License and the CiviCRM Licensing Exception along |
23 | with this program; if not, contact CiviCRM LLC |
24 | at info[AT]civicrm[DOT]org. If you have questions about the |
25 | GNU Affero General Public License or the licensing of CiviCRM, |
26 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
27 +--------------------------------------------------------------------+
28 */
29
30 /**
31 * File for the CiviCRM APIv3 activity functions
32 *
33 * @package CiviCRM_APIv3
34 * @subpackage API_Activity
35 * @copyright CiviCRM LLC (c) 2004-2014
36 * @version $Id: Activity.php 30486 2010-11-02 16:12:09Z shot $
37 *
38 */
39
40
41 /**
42 * Creates or updates an Activity. See the example for usage
43 *
44 * @param array $params
45 * Associative array of property name/value.
46 * pairs for the activity.
47 * {@getfields activity_create}
48 *
49 * @throws API_Exception
50 * @return array Array containing 'is_error' to denote success or failure and details of the created activity
51 *
52 * @example ActivityCreate.php Standard create example
53 * @example Activity/ContactRefCustomField.php Create example including setting a contact reference custom field
54 * {@example ActivityCreate.php 0}
55 */
56 function civicrm_api3_activity_create($params) {
57
58 if (empty($params['id'])) {
59 // an update does not require any mandatory parameters
60 civicrm_api3_verify_one_mandatory($params,
61 NULL,
62 array(
63 'activity_name', 'activity_type_id', 'activity_label',
64 )
65 );
66 }
67
68 // check for various error and required conditions
69 // note that almost all the processing in there should be managed by the wrapper layer
70 // & should be removed - needs testing
71 $errors = _civicrm_api3_activity_check_params($params);
72
73 // this should not be required as should throw exception rather than return errors -
74 //needs testing
75 if (!empty($errors)) {
76 return $errors;
77 }
78
79 // processing for custom data
80 $values = $activityArray = array();
81 _civicrm_api3_custom_format_params($params, $values, 'Activity');
82
83 if (!empty($values['custom'])) {
84 $params['custom'] = $values['custom'];
85 }
86
87 // this should be set as a default rather than hard coded
88 // needs testing
89 $params['skipRecentView'] = TRUE;
90
91 // If this is a case activity, see if there is an existing activity
92 // and set it as an old revision. Also retrieve details we'll need.
93 // this handling should all be moved to the BAO layer
94 $case_id = '';
95 $createRevision = FALSE;
96 $oldActivityValues = array();
97 if (!empty($params['case_id'])) {
98 $case_id = $params['case_id'];
99 if (!empty($params['id'])) {
100 $oldActivityParams = array('id' => $params['id']);
101 if (!$oldActivityValues) {
102 CRM_Activity_BAO_Activity::retrieve($oldActivityParams, $oldActivityValues);
103 }
104 if (empty($oldActivityValues)) {
105 throw new API_Exception(ts("Unable to locate existing activity."));
106 }
107 else {
108 $activityDAO = new CRM_Activity_DAO_Activity();
109 $activityDAO->id = $params['id'];
110 $activityDAO->is_current_revision = 0;
111 if (!$activityDAO->save()) {
112 if (is_object($activityDAO)) {
113 $activityDAO->free();
114 }
115 throw new API_Exception(ts("Unable to revision existing case activity."));
116 }
117 $createRevision = TRUE;
118 }
119 }
120 }
121
122 $deleteActivityAssignment = FALSE;
123 if (isset($params['assignee_contact_id'])) {
124 $deleteActivityAssignment = TRUE;
125 }
126
127 $deleteActivityTarget = FALSE;
128 if (isset($params['target_contact_id'])) {
129 $deleteActivityTarget = TRUE;
130 }
131
132 // this should all be handled at the BAO layer
133 $params['deleteActivityAssignment'] = CRM_Utils_Array::value('deleteActivityAssignment', $params, $deleteActivityAssignment);
134 $params['deleteActivityTarget'] = CRM_Utils_Array::value('deleteActivityTarget', $params, $deleteActivityTarget);
135
136 if ($case_id && $createRevision) {
137 // This is very similar to the copy-to-case action.
138 if (!CRM_Utils_Array::crmIsEmptyArray($oldActivityValues['target_contact'])) {
139 $oldActivityValues['targetContactIds'] = implode(',', array_unique($oldActivityValues['target_contact']));
140 }
141 if (!CRM_Utils_Array::crmIsEmptyArray($oldActivityValues['assignee_contact'])) {
142 $oldActivityValues['assigneeContactIds'] = implode(',', array_unique($oldActivityValues['assignee_contact']));
143 }
144 $oldActivityValues['mode'] = 'copy';
145 $oldActivityValues['caseID'] = $case_id;
146 $oldActivityValues['activityID'] = $oldActivityValues['id'];
147 $oldActivityValues['contactID'] = $oldActivityValues['source_contact_id'];
148
149 $copyToCase = CRM_Activity_Page_AJAX::_convertToCaseActivity($oldActivityValues);
150 if (empty($copyToCase['error_msg'])) {
151 // now fix some things that are different from copy-to-case
152 // then fall through to the create below to update with the passed in params
153 $params['id'] = $copyToCase['newId'];
154 $params['is_auto'] = 0;
155 $params['original_id'] = empty($oldActivityValues['original_id']) ? $oldActivityValues['id'] : $oldActivityValues['original_id'];
156 }
157 else {
158 throw new API_Exception(ts("Unable to create new revision of case activity."));
159 }
160 }
161
162 // create activity
163 $activityBAO = CRM_Activity_BAO_Activity::create($params);
164
165 if (isset($activityBAO->id)) {
166 if ($case_id && !$createRevision) {
167 // If this is a brand new case activity we need to add this
168 $caseActivityParams = array('activity_id' => $activityBAO->id, 'case_id' => $case_id);
169 CRM_Case_BAO_Case::processCaseActivity($caseActivityParams);
170 }
171
172 _civicrm_api3_object_to_array($activityBAO, $activityArray[$activityBAO->id]);
173 return civicrm_api3_create_success($activityArray, $params, 'activity', 'get', $activityBAO);
174 }
175 }
176
177 /**
178 * Specify Meta data for create. Note that this data is retrievable via the getfields function
179 * and is used for pre-filling defaults and ensuring mandatory requirements are met.
180 * @param array $params
181 * (reference) array of parameters determined by getfields.
182 */
183 function _civicrm_api3_activity_create_spec(&$params) {
184
185 //default for source_contact_id = currently logged in user
186 $params['source_contact_id']['api.default'] = 'user_contact_id';
187
188 $params['status_id']['api.aliases'] = array('activity_status');
189
190 $params['assignee_contact_id'] = array(
191 'name' => 'assignee_id',
192 'title' => 'assigned to',
193 'type' => 1,
194 'FKClassName' => 'CRM_Activity_DAO_ActivityContact',
195 );
196 $params['target_contact_id'] = array(
197 'name' => 'target_id',
198 'title' => 'Activity Target',
199 'type' => 1,
200 'FKClassName' => 'CRM_Activity_DAO_ActivityContact',
201 );
202
203 $params['source_contact_id'] = array(
204 'name' => 'source_contact_id',
205 'title' => 'Activity Source Contact',
206 'type' => 1,
207 'FKClassName' => 'CRM_Activity_DAO_ActivityContact',
208 'api.default' => 'user_contact_id',
209 );
210
211 }
212
213 /**
214 * Gets a CiviCRM activity according to parameters
215 *
216 * @param array $params
217 * Associative array of property name/value.
218 * pairs for the activity.
219 *
220 * @return array
221 *
222 * {@getfields activity_get}
223 * @example ActivityGet.php Basic example
224 * @example Activity/DateTimeHigh.php Example get with date filtering
225 * {@example ActivityGet.php 0}
226 */
227 function civicrm_api3_activity_get($params) {
228 if (!empty($params['contact_id'])) {
229 $activities = CRM_Activity_BAO_Activity::getContactActivity($params['contact_id']);
230 //BAO function doesn't actually return a contact ID - hack api for now & add to test so when api re-write happens it won't get missed
231 foreach ($activities as $key => $activityArray) {
232 $activities[$key]['id'] = $key;
233 }
234 }
235 else {
236 $activities = _civicrm_api3_basic_get(_civicrm_api3_get_BAO(__FUNCTION__), $params, FALSE);
237 }
238 $options = _civicrm_api3_get_options_from_params($params, FALSE, 'activity', 'get');
239 if ($options['is_count']) {
240 return civicrm_api3_create_success($activities, $params, 'activity', 'get');
241 }
242
243 $activities = _civicrm_api3_activity_get_formatResult($params, $activities);
244 //legacy custom data get - so previous formatted response is still returned too
245 return civicrm_api3_create_success($activities, $params, 'activity', 'get');
246 }
247
248 /**
249 * Given a list of activities, append any extra data requested about the activities
250 *
251 * NOTE: Called by civicrm-core and CiviHR
252 *
253 * @param array $params
254 * API request parameters.
255 * @param array $activities
256 * @return array new activities list
257 */
258 function _civicrm_api3_activity_get_formatResult($params, $activities) {
259 $returns = CRM_Utils_Array::value('return', $params, array());
260 if (!is_array($returns)) {
261 $returns = str_replace(' ', '', $returns);
262 $returns = explode(',', $returns);
263 }
264 $returns = array_fill_keys($returns, 1);
265
266 foreach ($params as $n => $v) {
267 if (substr($n, 0, 7) == 'return.') {
268 $returnkey = substr($n, 7);
269 $returns[$returnkey] = $v;
270 }
271 }
272 $returns['source_contact_id'] = 1;
273 foreach ($returns as $n => $v) {
274 switch ($n) {
275 case 'assignee_contact_id':
276 foreach ($activities as $key => $activityArray) {
277 $activities[$key]['assignee_contact_id'] = CRM_Activity_BAO_ActivityAssignment::retrieveAssigneeIdsByActivityId($activityArray['id']);
278 }
279 break;
280
281 case 'target_contact_id':
282 foreach ($activities as $key => $activityArray) {
283 $activities[$key]['target_contact_id'] = CRM_Activity_BAO_ActivityTarget::retrieveTargetIdsByActivityId($activityArray['id']);
284 }
285 break;
286
287 case 'source_contact_id':
288 foreach ($activities as $key => $activityArray) {
289 $activities[$key]['source_contact_id'] = CRM_Activity_BAO_Activity::getSourceContactID($activityArray['id']);
290 }
291 break;
292
293 default:
294 if (substr($n, 0, 6) == 'custom') {
295 $returnProperties[$n] = $v;
296 }
297 }
298 }
299 if (!empty($activities) && (!empty($returnProperties) || !empty($params['contact_id']))) {
300 foreach ($activities as $activityId => $values) {
301 //@todo - should possibly load activity type id if not loaded (update with id)
302 _civicrm_api3_custom_data_get($activities[$activityId], 'Activity', $activityId, NULL, CRM_Utils_Array::value('activity_type_id', $values));
303 }
304 }
305 return $activities;
306 }
307
308
309 /**
310 * Delete a specified Activity.
311 *
312 * @param array $params
313 * Array holding 'id' of activity to be deleted.
314 * {@getfields activity_delete}
315 *
316 * @throws API_Exception
317 * @return void|CRM_Core_Error An error if 'activityName or ID' is invalid,
318 * permissions are insufficient, etc. or CiviCRM success array
319 *
320 *
321 *
322 * @example ActivityDelete.php Standard Delete Example
323 *
324 */
325 function civicrm_api3_activity_delete($params) {
326
327 if (CRM_Activity_BAO_Activity::deleteActivity($params)) {
328 return civicrm_api3_create_success(1, $params, 'activity', 'delete');
329 }
330 else {
331 throw new API_Exception('Could not delete activity');
332 }
333 }
334
335 /**
336 * Check for required params
337 *
338 * @param array $params
339 * Associated array of fields.
340 *
341 * @throws API_Exception
342 * @throws Exception
343 * @return array $error array with errors
344 */
345 function _civicrm_api3_activity_check_params(&$params) {
346
347 $contactIDFields = array_intersect_key($params,
348 array(
349 'source_contact_id' => 1,
350 'assignee_contact_id' => 1,
351 'target_contact_id' => 1,
352 )
353 );
354
355 // this should be handled by wrapper layer & probably the api would already manage it
356 //correctly by doing post validation - ie. a failure should result in a roll-back = an error
357 // needs testing
358 if (!empty($contactIDFields)) {
359 $contactIds = array();
360 foreach ($contactIDFields as $fieldname => $contactfield) {
361 if (empty($contactfield)) {
362 continue;
363 }
364 if (is_array($contactfield)) {
365 foreach ($contactfield as $contactkey => $contactvalue) {
366 $contactIds[$contactvalue] = $contactvalue;
367 }
368 }
369 else {
370 $contactIds[$contactfield] = $contactfield;
371 }
372 }
373
374 $sql = '
375 SELECT count(*)
376 FROM civicrm_contact
377 WHERE id IN (' . implode(', ', $contactIds) . ' )';
378 if (count($contactIds) != CRM_Core_DAO::singleValueQuery($sql)) {
379 throw new API_Exception('Invalid ' . ' Contact Id');
380 }
381 }
382
383 $activityIds = array(
384 'activity' => CRM_Utils_Array::value('id', $params),
385 'parent' => CRM_Utils_Array::value('parent_id', $params),
386 'original' => CRM_Utils_Array::value('original_id', $params),
387 );
388
389 foreach ($activityIds as $id => $value) {
390 if ($value &&
391 !CRM_Core_DAO::getFieldValue('CRM_Activity_DAO_Activity', $value, 'id')
392 ) {
393 throw new API_Exception('Invalid ' . ucfirst($id) . ' Id');
394 }
395 }
396 // this should be handled by wrapper layer & probably the api would already manage it
397 //correctly by doing pseudoconstant validation
398 // needs testing
399 $activityTypes = CRM_Activity_BAO_Activity::buildOptions('activity_type_id', 'validate');
400 $activityName = CRM_Utils_Array::value('activity_name', $params);
401 $activityName = ucfirst($activityName);
402 $activityLabel = CRM_Utils_Array::value('activity_label', $params);
403 if ($activityLabel) {
404 $activityTypes = CRM_Activity_BAO_Activity::buildOptions('activity_type_id', 'create');
405 }
406
407 $activityTypeId = CRM_Utils_Array::value('activity_type_id', $params);
408
409 if ($activityName || $activityLabel) {
410 $activityTypeIdInList = array_search(($activityName ? $activityName : $activityLabel), $activityTypes);
411
412 if (!$activityTypeIdInList) {
413 $errorString = $activityName ? "Invalid Activity Name : $activityName" : "Invalid Activity Type Label";
414 throw new Exception($errorString);
415 }
416 elseif ($activityTypeId && ($activityTypeId != $activityTypeIdInList)) {
417 throw new API_Exception('Mismatch in Activity');
418 }
419 $params['activity_type_id'] = $activityTypeIdInList;
420 }
421 elseif ($activityTypeId &&
422 !array_key_exists($activityTypeId, $activityTypes)
423 ) {
424 throw new API_Exception('Invalid Activity Type ID');
425 }
426
427 // check for activity duration minutes
428 // this should be validated @ the wrapper layer not here
429 // needs testing
430 if (isset($params['duration_minutes']) && !is_numeric($params['duration_minutes'])) {
431 throw new API_Exception('Invalid Activity Duration (in minutes)');
432 }
433
434 //if adding a new activity & date_time not set make it now
435 // this should be managed by the wrapper layer & setting ['api.default'] in speces
436 // needs testing
437 if (empty($params['id']) && empty($params['activity_date_time'])) {
438 $params['activity_date_time'] = CRM_Utils_Date::processDate(date('Y-m-d H:i:s'));
439 }
440
441 return NULL;
442 }
443
444 /**
445 * @see _civicrm_api3_generic_getlist_params.
446 *
447 * @param $request
448 * Array.
449 */
450 function _civicrm_api3_activity_getlist_params(&$request) {
451 $fieldsToReturn = array('activity_date_time', 'activity_type_id', 'subject', 'source_contact_id');
452 $request['params']['return'] = array_unique(array_merge($fieldsToReturn, $request['extra']));
453 $request['params']['options']['sort'] = 'activity_date_time DESC';
454 $request['params'] += array(
455 'is_current_revision' => 1,
456 'is_deleted' => 0,
457 );
458 }
459
460 /**
461 * @see _civicrm_api3_generic_getlist_output
462 *
463 * @param $result
464 * Array.
465 * @param $request
466 * Array.
467 *
468 * @return array
469 */
470 function _civicrm_api3_activity_getlist_output($result, $request) {
471 $output = array();
472 if (!empty($result['values'])) {
473 foreach ($result['values'] as $row) {
474 $data = array(
475 'id' => $row[$request['id_field']],
476 'label' => $row[$request['label_field']] ? $row[$request['label_field']] : ts('(no subject)'),
477 'description' => array(CRM_Core_Pseudoconstant::getLabel('CRM_Activity_BAO_Activity', 'activity_type_id', $row['activity_type_id'])),
478 );
479 if (!empty($row['activity_date_time'])) {
480 $data['description'][0] .= ': ' . CRM_Utils_Date::customFormat($row['activity_date_time']);
481 }
482 if (!empty($row['source_contact_id'])) {
483 $data['description'][] = ts('By %1', array(1 => CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $row['source_contact_id'], 'display_name')));
484 }
485 foreach ($request['extra'] as $field) {
486 $data['extra'][$field] = isset($row[$field]) ? $row[$field] : NULL;
487 }
488 $output[] = $data;
489 }
490 }
491 return $output;
492 }