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