3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2017 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
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. |
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. |
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 +--------------------------------------------------------------------+
29 * This api exposes CiviCRM Activity records.
31 * @package CiviCRM_APIv3
36 * Creates or updates an Activity.
38 * @param array $params
39 * Array per getfields documentation.
41 * @throws API_Exception
45 function civicrm_api3_activity_create($params) {
47 if (empty($params['id'])) {
48 // an update does not require any mandatory parameters
49 civicrm_api3_verify_one_mandatory($params,
59 // check for various error and required conditions
60 // note that almost all the processing in there should be managed by the wrapper layer
61 // & should be removed - needs testing
62 $errors = _civicrm_api3_activity_check_params($params);
64 // this should not be required as should throw exception rather than return errors -
66 if (!empty($errors)) {
70 // processing for custom data
71 $values = $activityArray = array();
72 _civicrm_api3_custom_format_params($params, $values, 'Activity');
74 if (!empty($values['custom'])) {
75 $params['custom'] = $values['custom'];
78 // this should be set as a default rather than hard coded
80 $params['skipRecentView'] = TRUE;
82 // If this is a case activity, see if there is an existing activity
83 // and set it as an old revision. Also retrieve details we'll need.
84 // this handling should all be moved to the BAO layer
86 $createRevision = FALSE;
87 $oldActivityValues = array();
88 // Lookup case id if not supplied
89 if (!isset($params['case_id']) && !empty($params['id'])) {
90 $params['case_id'] = CRM_Core_DAO
::singleValueQuery("SELECT case_id FROM civicrm_case_activity WHERE activity_id = " . (int) $params['id']);
92 if (!empty($params['case_id'])) {
93 $case_id = $params['case_id'];
94 if (!empty($params['id'])) {
95 $oldActivityParams = array('id' => $params['id']);
96 if (!$oldActivityValues) {
97 CRM_Activity_BAO_Activity
::retrieve($oldActivityParams, $oldActivityValues);
99 if (empty($oldActivityValues)) {
100 throw new API_Exception(ts("Unable to locate existing activity."));
103 $activityDAO = new CRM_Activity_DAO_Activity();
104 $activityDAO->id
= $params['id'];
105 $activityDAO->is_current_revision
= 0;
106 if (!$activityDAO->save()) {
107 if (is_object($activityDAO)) {
108 $activityDAO->free();
110 throw new API_Exception(ts("Unable to revision existing case activity."));
112 $createRevision = TRUE;
117 $deleteActivityAssignment = FALSE;
118 if (isset($params['assignee_contact_id'])) {
119 $deleteActivityAssignment = TRUE;
122 $deleteActivityTarget = FALSE;
123 if (isset($params['target_contact_id'])) {
124 $deleteActivityTarget = TRUE;
127 // this should all be handled at the BAO layer
128 $params['deleteActivityAssignment'] = CRM_Utils_Array
::value('deleteActivityAssignment', $params, $deleteActivityAssignment);
129 $params['deleteActivityTarget'] = CRM_Utils_Array
::value('deleteActivityTarget', $params, $deleteActivityTarget);
131 if ($case_id && $createRevision) {
132 // This is very similar to the copy-to-case action.
133 if (!CRM_Utils_Array
::crmIsEmptyArray($oldActivityValues['target_contact'])) {
134 $oldActivityValues['targetContactIds'] = implode(',', array_unique($oldActivityValues['target_contact']));
136 if (!CRM_Utils_Array
::crmIsEmptyArray($oldActivityValues['assignee_contact'])) {
137 $oldActivityValues['assigneeContactIds'] = implode(',', array_unique($oldActivityValues['assignee_contact']));
139 $oldActivityValues['mode'] = 'copy';
140 $oldActivityValues['caseID'] = $case_id;
141 $oldActivityValues['activityID'] = $oldActivityValues['id'];
142 $oldActivityValues['contactID'] = $oldActivityValues['source_contact_id'];
144 $copyToCase = CRM_Activity_Page_AJAX
::_convertToCaseActivity($oldActivityValues);
145 if (empty($copyToCase['error_msg'])) {
146 // now fix some things that are different from copy-to-case
147 // then fall through to the create below to update with the passed in params
148 $params['id'] = $copyToCase['newId'];
149 $params['is_auto'] = 0;
150 $params['original_id'] = empty($oldActivityValues['original_id']) ?
$oldActivityValues['id'] : $oldActivityValues['original_id'];
153 throw new API_Exception(ts("Unable to create new revision of case activity."));
158 $activityBAO = CRM_Activity_BAO_Activity
::create($params);
160 if (isset($activityBAO->id
)) {
161 if ($case_id && !$createRevision) {
162 // If this is a brand new case activity, add to case(s)
163 foreach ((array) $case_id as $singleCaseId) {
164 $caseActivityParams = array('activity_id' => $activityBAO->id
, 'case_id' => $singleCaseId);
165 CRM_Case_BAO_Case
::processCaseActivity($caseActivityParams);
169 _civicrm_api3_object_to_array($activityBAO, $activityArray[$activityBAO->id
]);
170 return civicrm_api3_create_success($activityArray, $params, 'Activity', 'get', $activityBAO);
175 * Specify Meta data for create.
177 * Note that this data is retrievable via the getfields function and is used for pre-filling defaults and
178 * ensuring mandatory requirements are met.
180 * @param array $params
181 * Array of parameters determined by getfields.
183 function _civicrm_api3_activity_create_spec(&$params) {
185 $params['status_id']['api.aliases'] = array('activity_status');
187 $params['assignee_contact_id'] = array(
188 'name' => 'assignee_id',
189 'title' => 'Activity Assignee',
190 'description' => 'Contact(s) assigned to this activity.',
192 'FKClassName' => 'CRM_Contact_DAO_Contact',
193 'FKApiName' => 'Contact',
195 $params['target_contact_id'] = array(
196 'name' => 'target_id',
197 'title' => 'Activity Target',
198 'description' => 'Contact(s) participating in this activity.',
200 'FKClassName' => 'CRM_Contact_DAO_Contact',
201 'FKApiName' => 'Contact',
204 $params['source_contact_id'] = array(
205 'name' => 'source_contact_id',
206 'title' => 'Activity Source Contact',
207 'description' => 'Person who created this activity. Defaults to current user.',
209 'FKClassName' => 'CRM_Contact_DAO_Contact',
210 'api.default' => 'user_contact_id',
211 'FKApiName' => 'Contact',
212 'api.required' => TRUE,
215 $params['case_id'] = array(
217 'title' => 'Case ID',
218 'description' => 'For creating an activity as part of a case.',
220 'FKClassName' => 'CRM_Case_DAO_Case',
221 'FKApiName' => 'Case',
227 * Specify Metadata for get.
229 * @param array $params
231 function _civicrm_api3_activity_get_spec(&$params) {
232 $params['tag_id'] = array(
234 'description' => 'Find activities with specified tags.',
236 'FKClassName' => 'CRM_Core_DAO_Tag',
237 'FKApiName' => 'Tag',
238 'supports_joins' => TRUE,
240 $params['file_id'] = array(
241 'title' => 'Attached Files',
242 'description' => 'Find activities with attached files.',
244 'FKClassName' => 'CRM_Core_DAO_File',
245 'FKApiName' => 'File',
247 $params['case_id'] = array(
249 'description' => 'Find activities within specified cases.',
251 'FKClassName' => 'CRM_Case_DAO_Case',
252 'FKApiName' => 'Case',
254 $params['contact_id'] = array(
255 'title' => 'Activity Contact ID',
256 'description' => 'Find activities involving this contact (as target, source, OR assignee).',
258 'FKClassName' => 'CRM_Contact_DAO_Contact',
259 'FKApiName' => 'Contact',
261 $params['target_contact_id'] = array(
262 'title' => 'Target Contact ID',
263 'description' => 'Find activities with specified target contact.',
265 'FKClassName' => 'CRM_Contact_DAO_Contact',
266 'FKApiName' => 'Contact',
268 $params['source_contact_id'] = array(
269 'title' => 'Source Contact ID',
270 'description' => 'Find activities with specified source contact.',
272 'FKClassName' => 'CRM_Contact_DAO_Contact',
273 'FKApiName' => 'Contact',
275 $params['assignee_contact_id'] = array(
276 'title' => 'Assignee Contact ID',
277 'description' => 'Find activities with specified assignee contact.',
279 'FKClassName' => 'CRM_Contact_DAO_Contact',
280 'FKApiName' => 'Contact',
285 * Gets a CiviCRM activity according to parameters.
287 * @param array $params
288 * Array per getfields documentation.
290 * @return array API result array
293 * @throws \API_Exception
294 * @throws \CiviCRM_API3_Exception
295 * @throws \Civi\API\Exception\UnauthorizedException
297 function civicrm_api3_activity_get($params) {
299 $sql = CRM_Utils_SQL_Select
::fragment();
300 $recordTypes = civicrm_api3('ActivityContact', 'getoptions', array('field' => 'record_type_id'));
301 $recordTypes = $recordTypes['values'];
302 $activityContactOptions = array(
303 'contact_id' => NULL,
304 'target_contact_id' => array_search('Activity Targets', $recordTypes),
305 'source_contact_id' => array_search('Activity Source', $recordTypes),
306 'assignee_contact_id' => array_search('Activity Assignees', $recordTypes),
308 if (empty($params['target_contact_id']) && empty($params['source_contact_id'])
309 && empty($params['assignee_contact_id']) &&
310 !empty($params['check_permissions']) && !CRM_Core_Permission
::check('view all activities')
311 && !CRM_Core_Permission
::check('view all contacts')
313 // Force join on the activity contact table.
314 // @todo get this & other acl filters to work, remove check further down.
315 //$params['contact_id'] = array('IS NOT NULL' => TRUE);
318 foreach ($activityContactOptions as $activityContactName => $activityContactValue) {
319 if (!empty($params[$activityContactName])) {
320 if (!is_array($params[$activityContactName])) {
321 $params[$activityContactName] = array('=' => $params[$activityContactName]);
323 $clause = \CRM_Core_DAO
::createSQLFilter('contact_id', $params[$activityContactName]);
324 $typeClause = $activityContactValue ?
'record_type_id = #typeId AND ' : '';
325 $sql->where("a.id IN (SELECT activity_id FROM civicrm_activity_contact WHERE $typeClause !clause)",
326 array('#typeId' => $activityContactValue, '!clause' => $clause)
330 if (!empty($params['tag_id'])) {
331 if (!is_array($params['tag_id'])) {
332 $params['tag_id'] = array('=' => $params['tag_id']);
334 $clause = \CRM_Core_DAO
::createSQLFilter('tag_id', $params['tag_id']);
336 $sql->where('a.id IN (SELECT entity_id FROM civicrm_entity_tag WHERE entity_table = "civicrm_activity" AND !clause)', array('!clause' => $clause));
339 if (!empty($params['file_id'])) {
340 if (!is_array($params['file_id'])) {
341 $params['file_id'] = array('=' => $params['file_id']);
343 $clause = \CRM_Core_DAO
::createSQLFilter('file_id', $params['file_id']);
345 $sql->where('a.id IN (SELECT entity_id FROM civicrm_entity_file WHERE entity_table = "civicrm_activity" AND !clause)', array('!clause' => $clause));
348 if (!empty($params['case_id'])) {
349 if (!is_array($params['case_id'])) {
350 $params['case_id'] = array('=' => $params['case_id']);
352 $clause = \CRM_Core_DAO
::createSQLFilter('case_id', $params['case_id']);
354 $sql->where('a.id IN (SELECT activity_id FROM civicrm_case_activity WHERE !clause)', array('!clause' => $clause));
357 $activities = _civicrm_api3_basic_get(_civicrm_api3_get_BAO(__FUNCTION__
), $params, FALSE, 'Activity', $sql);
358 if (!empty($params['check_permissions']) && !CRM_Core_Permission
::check('view all activities')) {
359 // @todo get this to work at the query level - see contact_id join above.
360 foreach ($activities as $activity) {
361 if (!CRM_Activity_BAO_Activity
::checkPermission($activity['id'], CRM_Core_Action
::VIEW
)) {
362 unset($activities[$activity['id']]);
366 $options = _civicrm_api3_get_options_from_params($params, FALSE, 'Activity', 'get');
367 if ($options['is_count']) {
368 return civicrm_api3_create_success($activities, $params, 'Activity', 'get');
371 $activities = _civicrm_api3_activity_get_formatResult($params, $activities, $options);
372 //legacy custom data get - so previous formatted response is still returned too
373 return civicrm_api3_create_success($activities, $params, 'Activity', 'get');
377 * Given a list of activities, append any extra data requested about the activities.
379 * @note Called by civicrm-core and CiviHR
381 * @param array $params
382 * API request parameters.
383 * @param array $activities
386 * new activities list
388 function _civicrm_api3_activity_get_formatResult($params, $activities, $options) {
393 $returns = $options['return'];
394 foreach ($params as $n => $v) {
395 if (substr($n, 0, 7) == 'return.') {
396 $returnkey = substr($n, 7);
397 $returns[$returnkey] = $v;
401 $returns['source_contact_id'] = 1;
402 if (!empty($returns['target_contact_name'])) {
403 $returns['target_contact_id'] = 1;
405 if (!empty($returns['assignee_contact_name'])) {
406 $returns['assignee_contact_id'] = 1;
409 $tagGet = array('tag_id', 'entity_id');
410 foreach (array_keys($returns) as $key) {
411 if (strpos($key, 'tag_id.') === 0) {
413 $returns['tag_id'] = 1;
417 foreach ($returns as $n => $v) {
419 case 'assignee_contact_id':
420 foreach ($activities as $key => $activityArray) {
421 $cids = $activities[$key]['assignee_contact_id'] = CRM_Activity_BAO_ActivityAssignment
::retrieveAssigneeIdsByActivityId($activityArray['id']);
422 if ($cids && !empty($returns['assignee_contact_name'])) {
423 foreach ($cids as $cid) {
424 $activities[$key]['assignee_contact_name'][$cid] = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $cid, 'display_name');
430 case 'target_contact_id':
431 foreach ($activities as $key => $activityArray) {
432 $cids = $activities[$key]['target_contact_id'] = CRM_Activity_BAO_ActivityTarget
::retrieveTargetIdsByActivityId($activityArray['id']);
433 if ($cids && !empty($returns['target_contact_name'])) {
434 foreach ($cids as $cid) {
435 $activities[$key]['target_contact_name'][$cid] = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $cid, 'display_name');
441 case 'source_contact_id':
442 foreach ($activities as $key => $activityArray) {
443 $cid = $activities[$key]['source_contact_id'] = CRM_Activity_BAO_Activity
::getSourceContactID($activityArray['id']);
444 if ($cid && !empty($returns['source_contact_name'])) {
445 $activities[$key]['source_contact_name'] = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $cid, 'display_name');
451 $tags = civicrm_api3('EntityTag', 'get', array(
452 'entity_table' => 'civicrm_activity',
453 'entity_id' => array('IN' => array_keys($activities)),
455 'options' => array('limit' => 0),
457 foreach ($tags['values'] as $tag) {
458 $key = (int) $tag['entity_id'];
459 unset($tag['entity_id'], $tag['id']);
460 $activities[$key]['tag_id'][$tag['tag_id']] = $tag;
465 $dao = CRM_Core_DAO
::executeQuery("SELECT entity_id, file_id FROM civicrm_entity_file WHERE entity_table = 'civicrm_activity' AND entity_id IN (%1)",
466 array(1 => array(implode(',', array_keys($activities)), 'String', CRM_Core_DAO
::QUERY_FORMAT_NO_QUOTES
)));
467 while ($dao->fetch()) {
468 $activities[$dao->entity_id
]['file_id'][] = $dao->file_id
;
473 $dao = CRM_Core_DAO
::executeQuery("SELECT activity_id, case_id FROM civicrm_case_activity WHERE activity_id IN (%1)",
474 array(1 => array(implode(',', array_keys($activities)), 'String', CRM_Core_DAO
::QUERY_FORMAT_NO_QUOTES
)));
475 while ($dao->fetch()) {
476 $activities[$dao->activity_id
]['case_id'][] = $dao->case_id
;
481 if (substr($n, 0, 6) == 'custom') {
482 $returnProperties[$n] = $v;
488 if (!empty($params['contact_id'])) {
489 $statusOptions = CRM_Activity_BAO_Activity
::buildOptions('status_id', 'get');
490 $typeOptions = CRM_Activity_BAO_Activity
::buildOptions('activity_type_id', 'validate');
491 foreach ($activities as $key => &$activityArray) {
492 if (!empty($activityArray['status_id'])) {
493 $activityArray['status'] = $statusOptions[$activityArray['status_id']];
495 if (!empty($activityArray['activity_type_id'])) {
496 $activityArray['activity_name'] = $typeOptions[$activityArray['activity_type_id']];
501 if (!empty($returnProperties) ||
!empty($params['contact_id'])) {
502 foreach ($activities as $activityId => $values) {
503 //@todo - should possibly load activity type id if not loaded (update with id)
504 _civicrm_api3_custom_data_get($activities[$activityId], CRM_Utils_Array
::value('check_permissions', $params), 'Activity', $activityId, NULL, CRM_Utils_Array
::value('activity_type_id', $values));
512 * Delete a specified Activity.
514 * @param array $params
515 * Array holding 'id' of activity to be deleted.
517 * @throws API_Exception
522 function civicrm_api3_activity_delete($params) {
524 if (CRM_Activity_BAO_Activity
::deleteActivity($params)) {
525 return civicrm_api3_create_success(1, $params, 'Activity', 'delete');
528 throw new API_Exception('Could not delete Activity');
533 * Check for required params.
535 * @param array $params
536 * Associated array of fields.
538 * @throws API_Exception
543 function _civicrm_api3_activity_check_params(&$params) {
544 $activityIds = array(
545 'activity' => CRM_Utils_Array
::value('id', $params),
546 'parent' => CRM_Utils_Array
::value('parent_id', $params),
547 'original' => CRM_Utils_Array
::value('original_id', $params),
550 foreach ($activityIds as $id => $value) {
552 !CRM_Core_DAO
::getFieldValue('CRM_Activity_DAO_Activity', $value, 'id')
554 throw new API_Exception('Invalid ' . ucfirst($id) . ' Id');
557 // this should be handled by wrapper layer & probably the api would already manage it
558 //correctly by doing pseudoconstant validation
560 $activityTypes = CRM_Activity_BAO_Activity
::buildOptions('activity_type_id', 'validate');
561 $activityName = CRM_Utils_Array
::value('activity_name', $params);
562 $activityName = ucfirst($activityName);
563 $activityLabel = CRM_Utils_Array
::value('activity_label', $params);
564 if ($activityLabel) {
565 $activityTypes = CRM_Activity_BAO_Activity
::buildOptions('activity_type_id', 'create');
568 $activityTypeId = CRM_Utils_Array
::value('activity_type_id', $params);
570 if ($activityName ||
$activityLabel) {
571 $activityTypeIdInList = array_search(($activityName ?
$activityName : $activityLabel), $activityTypes);
573 if (!$activityTypeIdInList) {
574 $errorString = $activityName ?
"Invalid Activity Name : $activityName" : "Invalid Activity Type Label";
575 throw new Exception($errorString);
577 elseif ($activityTypeId && ($activityTypeId != $activityTypeIdInList)) {
578 throw new API_Exception('Mismatch in Activity');
580 $params['activity_type_id'] = $activityTypeIdInList;
582 elseif ($activityTypeId &&
583 !array_key_exists($activityTypeId, $activityTypes)
585 throw new API_Exception('Invalid Activity Type ID');
588 // check for activity duration minutes
589 // this should be validated @ the wrapper layer not here
591 if (isset($params['duration_minutes']) && !is_numeric($params['duration_minutes'])) {
592 throw new API_Exception('Invalid Activity Duration (in minutes)');
595 //if adding a new activity & date_time not set make it now
596 // this should be managed by the wrapper layer & setting ['api.default'] in speces
598 if (empty($params['id']) && empty($params['activity_date_time'])) {
599 $params['activity_date_time'] = CRM_Utils_Date
::processDate(date('Y-m-d H:i:s'));
606 * Get parameters for activity list.
608 * @see _civicrm_api3_generic_getlist_params
610 * @param array $request
613 function _civicrm_api3_activity_getlist_params(&$request) {
614 $fieldsToReturn = array(
615 'activity_date_time',
620 $request['params']['return'] = array_unique(array_merge($fieldsToReturn, $request['extra']));
621 $request['params']['options']['sort'] = 'activity_date_time DESC';
622 $request['params'] +
= array(
623 'is_current_revision' => 1,
629 * Get output for activity list.
631 * @see _civicrm_api3_generic_getlist_output
633 * @param array $result
634 * @param array $request
638 function _civicrm_api3_activity_getlist_output($result, $request) {
640 if (!empty($result['values'])) {
641 foreach ($result['values'] as $row) {
643 'id' => $row[$request['id_field']],
644 'label' => $row[$request['label_field']] ?
$row[$request['label_field']] : ts('(no subject)'),
645 'description' => array(
646 CRM_Core_Pseudoconstant
::getLabel('CRM_Activity_BAO_Activity', 'activity_type_id', $row['activity_type_id']),
649 if (!empty($row['activity_date_time'])) {
650 $data['description'][0] .= ': ' . CRM_Utils_Date
::customFormat($row['activity_date_time']);
652 if (!empty($row['source_contact_id'])) {
653 $data['description'][] = ts('By %1', array(
654 1 => CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $row['source_contact_id'], 'display_name'),
657 // Add repeating info
658 $repeat = CRM_Core_BAO_RecurringEntity
::getPositionAndCount($row['id'], 'civicrm_activity');
659 $data['extra']['is_recur'] = FALSE;
661 $data['suffix'] = ts('(%1 of %2)', array(1 => $repeat[0], 2 => $repeat[1]));
662 $data['extra']['is_recur'] = TRUE;