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