First commit

This commit is contained in:
Theodotos Andreou 2018-01-14 13:10:16 +00:00
commit c6e2478c40
13918 changed files with 2303184 additions and 0 deletions

View file

@ -0,0 +1,68 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
* This api exposes CiviCRM Acl records.
*
* @package CiviCRM_APIv3
*/
/**
* Save an Acl.
*
* @param array $params
*
* @return array
* API result array
*/
function civicrm_api3_acl_create($params) {
return _civicrm_api3_basic_create(_civicrm_api3_get_BAO(__FUNCTION__), $params);
}
/**
* Get an Acl.
*
* @param array $params
*
* @return array
* API result array
*/
function civicrm_api3_acl_get($params) {
return _civicrm_api3_basic_get(_civicrm_api3_get_BAO(__FUNCTION__), $params);
}
/**
* Delete an Acl.
*
* @param array $params
*
* @return array
* API result array
*/
function civicrm_api3_acl_delete($params) {
return _civicrm_api3_basic_delete(_civicrm_api3_get_BAO(__FUNCTION__), $params);
}

View file

@ -0,0 +1,68 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
* This api exposes CiviCRM AclRole.
*
* @package CiviCRM_APIv3
*/
/**
* Save an AclRole.
*
* @param array $params
*
* @return array
* API result array
*/
function civicrm_api3_acl_role_create($params) {
return _civicrm_api3_basic_create(_civicrm_api3_get_BAO(__FUNCTION__), $params);
}
/**
* Get an AclRole.
*
* @param array $params
*
* @return array
* API result array
*/
function civicrm_api3_acl_role_get($params) {
return _civicrm_api3_basic_get(_civicrm_api3_get_BAO(__FUNCTION__), $params);
}
/**
* Delete an AclRole.
*
* @param array $params
*
* @return array
* API result array
*/
function civicrm_api3_acl_role_delete($params) {
return _civicrm_api3_basic_delete(_civicrm_api3_get_BAO(__FUNCTION__), $params);
}

View file

@ -0,0 +1,87 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
* This api exposes CiviCRM Scheduled Reminders.
*
* @package CiviCRM_APIv3
*/
/**
* Get CiviCRM ActionSchedule details.
*
* @param array $params
*
* @return array
* API result array
*/
function civicrm_api3_action_schedule_get($params) {
return _civicrm_api3_basic_get(_civicrm_api3_get_BAO(__FUNCTION__), $params, 'ActionSchedule');
}
/**
* Create a new ActionSchedule.
*
* @param array $params
*
* @return array
*/
function civicrm_api3_action_schedule_create($params) {
civicrm_api3_verify_one_mandatory($params, NULL, array('start_action_date', 'absolute_date'));
if (!array_key_exists('name', $params) && !array_key_exists('id', $params)) {
$params['name'] = CRM_Utils_String::munge($params['title']);
}
return _civicrm_api3_basic_create(_civicrm_api3_get_BAO(__FUNCTION__), $params, 'ActionSchedule');
}
/**
* Adjust Metadata for Create action.
*
* The metadata is used for setting defaults, documentation & validation.
*
* @param array $params
* Array of parameters determined by getfields.
*/
function _civicrm_api3_action_schedule_create_spec(&$params) {
$params['title']['api.required'] = TRUE;
$params['mapping_id']['api.required'] = TRUE;
$params['entity_value']['api.required'] = TRUE;
}
/**
* Delete an existing ActionSchedule.
*
* @param array $params
* Array containing id of the action_schedule to be deleted.
*
* @return array
* API result array
*/
function civicrm_api3_action_schedule_delete($params) {
return _civicrm_api3_basic_delete(_civicrm_api3_get_BAO(__FUNCTION__), $params);
}

View file

@ -0,0 +1,778 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
* This api exposes CiviCRM Activity records.
*
* @package CiviCRM_APIv3
*/
/**
* Creates or updates an Activity.
*
* @param array $params
* Array per getfields documentation.
*
* @throws API_Exception
* @return array
* API result array
*/
function civicrm_api3_activity_create($params) {
$isNew = empty($params['id']);
if (empty($params['id'])) {
// an update does not require any mandatory parameters
civicrm_api3_verify_one_mandatory($params,
NULL,
array(
'activity_name',
'activity_type_id',
'activity_label',
)
);
}
// check for various error and required conditions
// note that almost all the processing in there should be managed by the wrapper layer
// & should be removed - needs testing
$errors = _civicrm_api3_activity_check_params($params);
// this should not be required as should throw exception rather than return errors -
//needs testing
if (!empty($errors)) {
return $errors;
}
// processing for custom data
$values = $activityArray = array();
_civicrm_api3_custom_format_params($params, $values, 'Activity');
if (!empty($values['custom'])) {
$params['custom'] = $values['custom'];
}
// this should be set as a default rather than hard coded
// needs testing
$params['skipRecentView'] = TRUE;
// If this is a case activity, see if there is an existing activity
// and set it as an old revision. Also retrieve details we'll need.
// this handling should all be moved to the BAO layer
$case_id = '';
$createRevision = FALSE;
$oldActivityValues = array();
// Lookup case id if not supplied
if (!isset($params['case_id']) && !empty($params['id'])) {
$params['case_id'] = CRM_Core_DAO::singleValueQuery("SELECT case_id FROM civicrm_case_activity WHERE activity_id = " . (int) $params['id']);
}
if (!empty($params['case_id'])) {
$case_id = $params['case_id'];
if (!empty($params['id']) && Civi::settings()->get('civicaseActivityRevisions')) {
$oldActivityParams = array('id' => $params['id']);
if (!$oldActivityValues) {
CRM_Activity_BAO_Activity::retrieve($oldActivityParams, $oldActivityValues);
}
if (empty($oldActivityValues)) {
throw new API_Exception(ts("Unable to locate existing activity."));
}
else {
$activityDAO = new CRM_Activity_DAO_Activity();
$activityDAO->id = $params['id'];
$activityDAO->is_current_revision = 0;
if (!$activityDAO->save()) {
if (is_object($activityDAO)) {
$activityDAO->free();
}
throw new API_Exception(ts("Unable to revision existing case activity."));
}
$createRevision = TRUE;
}
}
}
$deleteActivityAssignment = FALSE;
if (isset($params['assignee_contact_id'])) {
$deleteActivityAssignment = TRUE;
}
$deleteActivityTarget = FALSE;
if (isset($params['target_contact_id'])) {
$deleteActivityTarget = TRUE;
}
// this should all be handled at the BAO layer
$params['deleteActivityAssignment'] = CRM_Utils_Array::value('deleteActivityAssignment', $params, $deleteActivityAssignment);
$params['deleteActivityTarget'] = CRM_Utils_Array::value('deleteActivityTarget', $params, $deleteActivityTarget);
if ($case_id && $createRevision) {
// This is very similar to the copy-to-case action.
if (!CRM_Utils_Array::crmIsEmptyArray($oldActivityValues['target_contact'])) {
$oldActivityValues['targetContactIds'] = implode(',', array_unique($oldActivityValues['target_contact']));
}
if (!CRM_Utils_Array::crmIsEmptyArray($oldActivityValues['assignee_contact'])) {
$oldActivityValues['assigneeContactIds'] = implode(',', array_unique($oldActivityValues['assignee_contact']));
}
$oldActivityValues['mode'] = 'copy';
$oldActivityValues['caseID'] = $case_id;
$oldActivityValues['activityID'] = $oldActivityValues['id'];
$oldActivityValues['contactID'] = $oldActivityValues['source_contact_id'];
$copyToCase = CRM_Activity_Page_AJAX::_convertToCaseActivity($oldActivityValues);
if (empty($copyToCase['error_msg'])) {
// now fix some things that are different from copy-to-case
// then fall through to the create below to update with the passed in params
$params['id'] = $copyToCase['newId'];
$params['is_auto'] = 0;
$params['original_id'] = empty($oldActivityValues['original_id']) ? $oldActivityValues['id'] : $oldActivityValues['original_id'];
}
else {
throw new API_Exception(ts("Unable to create new revision of case activity."));
}
}
// create activity
$activityBAO = CRM_Activity_BAO_Activity::create($params);
if (isset($activityBAO->id)) {
if ($case_id && $isNew && !$createRevision) {
// If this is a brand new case activity, add to case(s)
foreach ((array) $case_id as $singleCaseId) {
$caseActivityParams = array('activity_id' => $activityBAO->id, 'case_id' => $singleCaseId);
CRM_Case_BAO_Case::processCaseActivity($caseActivityParams);
}
}
_civicrm_api3_object_to_array($activityBAO, $activityArray[$activityBAO->id]);
return civicrm_api3_create_success($activityArray, $params, 'Activity', 'get', $activityBAO);
}
}
/**
* Specify Meta data for create.
*
* Note that this data is retrievable via the getfields function and is used for pre-filling defaults and
* ensuring mandatory requirements are met.
*
* @param array $params
* Array of parameters determined by getfields.
*/
function _civicrm_api3_activity_create_spec(&$params) {
$params['status_id']['api.aliases'] = array('activity_status');
$params['assignee_contact_id'] = array(
'name' => 'assignee_id',
'title' => 'Activity Assignee',
'description' => 'Contact(s) assigned to this activity.',
'type' => 1,
'FKClassName' => 'CRM_Contact_DAO_Contact',
'FKApiName' => 'Contact',
);
$params['target_contact_id'] = array(
'name' => 'target_id',
'title' => 'Activity Target',
'description' => 'Contact(s) participating in this activity.',
'type' => 1,
'FKClassName' => 'CRM_Contact_DAO_Contact',
'FKApiName' => 'Contact',
);
$params['source_contact_id'] = array(
'name' => 'source_contact_id',
'title' => 'Activity Source Contact',
'description' => 'Person who created this activity. Defaults to current user.',
'type' => 1,
'FKClassName' => 'CRM_Contact_DAO_Contact',
'api.default' => 'user_contact_id',
'FKApiName' => 'Contact',
'api.required' => TRUE,
);
$params['case_id'] = array(
'name' => 'case_id',
'title' => 'Case ID',
'description' => 'For creating an activity as part of a case.',
'type' => 1,
'FKClassName' => 'CRM_Case_DAO_Case',
'FKApiName' => 'Case',
);
}
/**
* Specify Metadata for get.
*
* @param array $params
*/
function _civicrm_api3_activity_get_spec(&$params) {
$params['tag_id'] = array(
'title' => 'Tags',
'description' => 'Find activities with specified tags.',
'type' => CRM_Utils_Type::T_INT,
'FKClassName' => 'CRM_Core_DAO_Tag',
'FKApiName' => 'Tag',
'supports_joins' => TRUE,
);
$params['file_id'] = array(
'title' => 'Attached Files',
'description' => 'Find activities with attached files.',
'type' => CRM_Utils_Type::T_INT,
'FKClassName' => 'CRM_Core_DAO_File',
'FKApiName' => 'File',
);
$params['case_id'] = array(
'title' => 'Cases',
'description' => 'Find activities within specified cases.',
'type' => CRM_Utils_Type::T_INT,
'FKClassName' => 'CRM_Case_DAO_Case',
'FKApiName' => 'Case',
'supports_joins' => TRUE,
);
$params['contact_id'] = array(
'title' => 'Activity Contact ID',
'description' => 'Find activities involving this contact (as target, source, OR assignee).',
'type' => CRM_Utils_Type::T_INT,
'FKClassName' => 'CRM_Contact_DAO_Contact',
'FKApiName' => 'Contact',
);
$params['target_contact_id'] = array(
'title' => 'Target Contact ID',
'description' => 'Find activities with specified target contact.',
'type' => CRM_Utils_Type::T_INT,
'FKClassName' => 'CRM_Contact_DAO_Contact',
'FKApiName' => 'Contact',
);
$params['source_contact_id'] = array(
'title' => 'Source Contact ID',
'description' => 'Find activities with specified source contact.',
'type' => CRM_Utils_Type::T_INT,
'FKClassName' => 'CRM_Contact_DAO_Contact',
'FKApiName' => 'Contact',
);
$params['assignee_contact_id'] = array(
'title' => 'Assignee Contact ID',
'description' => 'Find activities with specified assignee contact.',
'type' => CRM_Utils_Type::T_INT,
'FKClassName' => 'CRM_Contact_DAO_Contact',
'FKApiName' => 'Contact',
);
$params['is_overdue'] = array(
'title' => 'Is Activity Overdue',
'description' => 'Incomplete activities with a past date.',
'type' => CRM_Utils_Type::T_BOOLEAN,
);
}
/**
* Gets a CiviCRM activity according to parameters.
*
* @param array $params
* Array per getfields documentation.
*
* @return array API result array
* API result array
*
* @throws \API_Exception
* @throws \CiviCRM_API3_Exception
* @throws \Civi\API\Exception\UnauthorizedException
*/
function civicrm_api3_activity_get($params) {
$options = _civicrm_api3_get_options_from_params($params, FALSE, 'Activity', 'get');
$sql = CRM_Utils_SQL_Select::fragment();
if (empty($params['target_contact_id']) && empty($params['source_contact_id'])
&& empty($params['assignee_contact_id']) &&
!empty($params['check_permissions']) && !CRM_Core_Permission::check('view all activities')
&& !CRM_Core_Permission::check('view all contacts')
) {
// Force join on the activity contact table.
// @todo get this & other acl filters to work, remove check further down.
//$params['contact_id'] = array('IS NOT NULL' => TRUE);
}
_civicrm_api3_activity_get_extraFilters($params, $sql);
// Handle is_overdue sort
if (!empty($options['sort'])) {
$sort = explode(', ', $options['sort']);
foreach ($sort as $index => &$sortString) {
// Get sort field and direction
list($sortField, $dir) = array_pad(explode(' ', $sortString), 2, 'ASC');
if ($sortField == 'is_overdue') {
$incomplete = implode(',', array_keys(CRM_Activity_BAO_Activity::getStatusesByType(CRM_Activity_BAO_Activity::INCOMPLETE)));
$sql->orderBy("IF((a.activity_date_time >= NOW() OR a.status_id NOT IN ($incomplete)), 0, 1) $dir", NULL, $index);
// Replace the sort with a placeholder which will be ignored by sql
$sortString = '(1)';
}
}
$params['options']['sort'] = implode(', ', $sort);
}
// Ensure there's enough data for calculating is_overdue
if (!empty($options['return']['is_overdue']) && (empty($options['return']['status_id']) || empty($options['return']['activity_date_time']))) {
$options['return']['status_id'] = $options['return']['activity_date_time'] = 1;
$params['return'] = array_keys($options['return']);
}
$activities = _civicrm_api3_basic_get(_civicrm_api3_get_BAO(__FUNCTION__), $params, FALSE, 'Activity', $sql);
if (!empty($params['check_permissions']) && !CRM_Core_Permission::check('view all activities')) {
// @todo get this to work at the query level - see contact_id join above.
foreach ($activities as $activity) {
if (!CRM_Activity_BAO_Activity::checkPermission($activity['id'], CRM_Core_Action::VIEW)) {
unset($activities[$activity['id']]);
}
}
}
if ($options['is_count']) {
return civicrm_api3_create_success($activities, $params, 'Activity', 'get');
}
$activities = _civicrm_api3_activity_get_formatResult($params, $activities, $options);
//legacy custom data get - so previous formatted response is still returned too
return civicrm_api3_create_success($activities, $params, 'Activity', 'get');
}
/**
* Support filters beyond what basic_get can do.
*
* @param array $params
* @param CRM_Utils_SQL_Select $sql
* @throws \CiviCRM_API3_Exception
* @throws \Exception
*/
function _civicrm_api3_activity_get_extraFilters(&$params, &$sql) {
// Filter by activity contacts
$recordTypes = civicrm_api3('ActivityContact', 'getoptions', array('field' => 'record_type_id'));
$recordTypes = $recordTypes['values'];
$activityContactOptions = array(
'contact_id' => NULL,
'target_contact_id' => array_search('Activity Targets', $recordTypes),
'source_contact_id' => array_search('Activity Source', $recordTypes),
'assignee_contact_id' => array_search('Activity Assignees', $recordTypes),
);
foreach ($activityContactOptions as $activityContactName => $activityContactValue) {
if (!empty($params[$activityContactName])) {
if (!is_array($params[$activityContactName])) {
$params[$activityContactName] = array('=' => $params[$activityContactName]);
}
$clause = \CRM_Core_DAO::createSQLFilter('contact_id', $params[$activityContactName]);
$typeClause = $activityContactValue ? 'record_type_id = #typeId AND ' : '';
$sql->where("a.id IN (SELECT activity_id FROM civicrm_activity_contact WHERE $typeClause !clause)",
array('#typeId' => $activityContactValue, '!clause' => $clause)
);
}
}
// Handle is_overdue filter
// Boolean calculated field - does not support operators
if (isset($params['is_overdue'])) {
$incomplete = implode(',', array_keys(CRM_Activity_BAO_Activity::getStatusesByType(CRM_Activity_BAO_Activity::INCOMPLETE)));
if ($params['is_overdue']) {
$sql->where('a.activity_date_time < NOW()');
$sql->where("a.status_id IN ($incomplete)");
}
else {
$sql->where("(a.activity_date_time >= NOW() OR a.status_id NOT IN ($incomplete))");
}
}
// Define how to handle filters on some related entities.
// Subqueries are nice in (a) avoiding duplicates and (b) when the result
// list is expected to be bite-sized. Joins are nice (a) with larger
// datasets and (b) checking for non-existent relations.
$rels = array(
'tag_id' => array(
'subquery' => 'a.id IN (SELECT entity_id FROM civicrm_entity_tag WHERE entity_table = "civicrm_activity" AND !clause)',
'join' => '!joinType civicrm_entity_tag !alias ON (!alias.entity_table = "civicrm_activity" AND !alias.entity_id = a.id)',
'column' => 'tag_id',
),
'file_id' => array(
'subquery' => 'a.id IN (SELECT entity_id FROM civicrm_entity_file WHERE entity_table = "civicrm_activity" AND !clause)',
'join' => '!joinType civicrm_entity_file !alias ON (!alias.entity_table = "civicrm_activity" AND !alias.entity_id = a.id)',
'column' => 'file_id',
),
'case_id' => array(
'subquery' => 'a.id IN (SELECT activity_id FROM civicrm_case_activity WHERE !clause)',
'join' => '!joinType civicrm_case_activity !alias ON (!alias.activity_id = a.id)',
'column' => 'case_id',
),
);
foreach ($rels as $filter => $relSpec) {
if (!empty($params[$filter])) {
if (!is_array($params[$filter])) {
$params[$filter] = array('=' => $params[$filter]);
}
// $mode is one of ('LEFT JOIN', 'INNER JOIN', 'SUBQUERY')
$mode = isset($params[$filter]['IS NULL']) ? 'LEFT JOIN' : 'SUBQUERY';
if ($mode === 'SUBQUERY') {
$clause = \CRM_Core_DAO::createSQLFilter($relSpec['column'], $params[$filter]);
if ($clause) {
$sql->where($relSpec['subquery'], array('!clause' => $clause));
}
}
else {
$alias = 'actjoin_' . $filter;
$clause = \CRM_Core_DAO::createSQLFilter($alias . "." . $relSpec['column'], $params[$filter]);
if ($clause) {
$sql->join($alias, $relSpec['join'], array('!alias' => $alias, 'joinType' => $mode));
$sql->where($clause);
}
}
}
}
}
/**
* Given a list of activities, append any extra data requested about the activities.
*
* @note Called by civicrm-core and CiviHR
*
* @param array $params
* API request parameters.
* @param array $activities
*
* @return array
* new activities list
*/
function _civicrm_api3_activity_get_formatResult($params, $activities, $options) {
if (!$activities) {
return $activities;
}
$returns = $options['return'];
foreach ($params as $n => $v) {
if (substr($n, 0, 7) == 'return.') {
$returnkey = substr($n, 7);
$returns[$returnkey] = $v;
}
}
$returns['source_contact_id'] = 1;
if (!empty($returns['target_contact_name'])) {
$returns['target_contact_id'] = 1;
}
if (!empty($returns['assignee_contact_name'])) {
$returns['assignee_contact_id'] = 1;
}
$tagGet = array('tag_id', 'entity_id');
$caseGet = $caseIds = array();
foreach (array_keys($returns) as $key) {
if (strpos($key, 'tag_id.') === 0) {
$tagGet[] = $key;
$returns['tag_id'] = 1;
}
if (strpos($key, 'case_id.') === 0) {
$caseGet[] = str_replace('case_id.', '', $key);
$returns['case_id'] = 1;
}
}
foreach ($returns as $n => $v) {
switch ($n) {
case 'assignee_contact_id':
foreach ($activities as $key => $activityArray) {
$cids = $activities[$key]['assignee_contact_id'] = CRM_Activity_BAO_ActivityAssignment::retrieveAssigneeIdsByActivityId($activityArray['id']);
if ($cids && !empty($returns['assignee_contact_name'])) {
foreach ($cids as $cid) {
$activities[$key]['assignee_contact_name'][$cid] = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $cid, 'display_name');
}
}
}
break;
case 'target_contact_id':
foreach ($activities as $key => $activityArray) {
$cids = $activities[$key]['target_contact_id'] = CRM_Activity_BAO_ActivityTarget::retrieveTargetIdsByActivityId($activityArray['id']);
if ($cids && !empty($returns['target_contact_name'])) {
foreach ($cids as $cid) {
$activities[$key]['target_contact_name'][$cid] = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $cid, 'display_name');
}
}
}
break;
case 'source_contact_id':
foreach ($activities as $key => $activityArray) {
$cid = $activities[$key]['source_contact_id'] = CRM_Activity_BAO_Activity::getSourceContactID($activityArray['id']);
if ($cid && !empty($returns['source_contact_name'])) {
$activities[$key]['source_contact_name'] = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $cid, 'display_name');
}
}
break;
case 'tag_id':
$tags = civicrm_api3('EntityTag', 'get', array(
'entity_table' => 'civicrm_activity',
'entity_id' => array('IN' => array_keys($activities)),
'return' => $tagGet,
'options' => array('limit' => 0),
));
foreach ($tags['values'] as $tag) {
$key = (int) $tag['entity_id'];
unset($tag['entity_id'], $tag['id']);
$activities[$key]['tag_id'][$tag['tag_id']] = $tag;
}
break;
case 'file_id':
$dao = CRM_Core_DAO::executeQuery("SELECT entity_id, file_id FROM civicrm_entity_file WHERE entity_table = 'civicrm_activity' AND entity_id IN (%1)",
array(1 => array(implode(',', array_keys($activities)), 'String', CRM_Core_DAO::QUERY_FORMAT_NO_QUOTES)));
while ($dao->fetch()) {
$activities[$dao->entity_id]['file_id'][] = $dao->file_id;
}
break;
case 'case_id':
$dao = CRM_Core_DAO::executeQuery("SELECT activity_id, case_id FROM civicrm_case_activity WHERE activity_id IN (%1)",
array(1 => array(implode(',', array_keys($activities)), 'String', CRM_Core_DAO::QUERY_FORMAT_NO_QUOTES)));
while ($dao->fetch()) {
$activities[$dao->activity_id]['case_id'][] = $dao->case_id;
$caseIds[$dao->case_id] = $dao->case_id;
}
break;
case 'is_overdue':
foreach ($activities as $key => $activityArray) {
$activities[$key]['is_overdue'] = (int) CRM_Activity_BAO_Activity::isOverdue($activityArray);
}
break;
default:
if (substr($n, 0, 6) == 'custom') {
$returnProperties[$n] = $v;
}
}
}
// Fetch case fields via the join syntax
// Note this is limited to the first case if the activity belongs to more than one
if ($caseGet && $caseIds) {
$cases = civicrm_api3('Case', 'get', array(
'id' => array('IN' => $caseIds),
'options' => array('limit' => 0),
'check_permissions' => !empty($params['check_permissions']),
'return' => $caseGet,
));
foreach ($activities as &$activity) {
if (!empty($activity['case_id'])) {
$case = CRM_Utils_Array::value($activity['case_id'][0], $cases['values']);
if ($case) {
foreach ($case as $key => $value) {
if ($key != 'id') {
$activity['case_id.' . $key] = $value;
}
}
}
}
}
}
// Legacy extras
if (!empty($params['contact_id'])) {
$statusOptions = CRM_Activity_BAO_Activity::buildOptions('status_id', 'get');
$typeOptions = CRM_Activity_BAO_Activity::buildOptions('activity_type_id', 'validate');
foreach ($activities as $key => &$activityArray) {
if (!empty($activityArray['status_id'])) {
$activityArray['status'] = $statusOptions[$activityArray['status_id']];
}
if (!empty($activityArray['activity_type_id'])) {
$activityArray['activity_name'] = $typeOptions[$activityArray['activity_type_id']];
}
}
}
if (!empty($returnProperties) || !empty($params['contact_id'])) {
foreach ($activities as $activityId => $values) {
//@todo - should possibly load activity type id if not loaded (update with id)
_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));
}
}
return $activities;
}
/**
* Delete a specified Activity.
*
* @param array $params
* Array holding 'id' of activity to be deleted.
*
* @throws API_Exception
*
* @return array
* API result array
*/
function civicrm_api3_activity_delete($params) {
if (CRM_Activity_BAO_Activity::deleteActivity($params)) {
return civicrm_api3_create_success(1, $params, 'Activity', 'delete');
}
else {
throw new API_Exception('Could not delete Activity');
}
}
/**
* Check for required params.
*
* @param array $params
* Associated array of fields.
*
* @throws API_Exception
* @throws Exception
* @return array
* array with errors
*/
function _civicrm_api3_activity_check_params(&$params) {
$activityIds = array(
'activity' => CRM_Utils_Array::value('id', $params),
'parent' => CRM_Utils_Array::value('parent_id', $params),
'original' => CRM_Utils_Array::value('original_id', $params),
);
foreach ($activityIds as $id => $value) {
if ($value &&
!CRM_Core_DAO::getFieldValue('CRM_Activity_DAO_Activity', $value, 'id')
) {
throw new API_Exception('Invalid ' . ucfirst($id) . ' Id');
}
}
// this should be handled by wrapper layer & probably the api would already manage it
//correctly by doing pseudoconstant validation
// needs testing
$activityTypes = CRM_Activity_BAO_Activity::buildOptions('activity_type_id', 'validate');
$activityName = CRM_Utils_Array::value('activity_name', $params);
$activityName = ucfirst($activityName);
$activityLabel = CRM_Utils_Array::value('activity_label', $params);
if ($activityLabel) {
$activityTypes = CRM_Activity_BAO_Activity::buildOptions('activity_type_id', 'create');
}
$activityTypeId = CRM_Utils_Array::value('activity_type_id', $params);
if ($activityName || $activityLabel) {
$activityTypeIdInList = array_search(($activityName ? $activityName : $activityLabel), $activityTypes);
if (!$activityTypeIdInList) {
$errorString = $activityName ? "Invalid Activity Name : $activityName" : "Invalid Activity Type Label";
throw new Exception($errorString);
}
elseif ($activityTypeId && ($activityTypeId != $activityTypeIdInList)) {
throw new API_Exception('Mismatch in Activity');
}
$params['activity_type_id'] = $activityTypeIdInList;
}
elseif ($activityTypeId &&
!array_key_exists($activityTypeId, $activityTypes)
) {
throw new API_Exception('Invalid Activity Type ID');
}
// check for activity duration minutes
// this should be validated @ the wrapper layer not here
// needs testing
if (isset($params['duration_minutes']) && !is_numeric($params['duration_minutes'])) {
throw new API_Exception('Invalid Activity Duration (in minutes)');
}
//if adding a new activity & date_time not set make it now
// this should be managed by the wrapper layer & setting ['api.default'] in speces
// needs testing
if (empty($params['id']) && empty($params['activity_date_time'])) {
$params['activity_date_time'] = CRM_Utils_Date::processDate(date('Y-m-d H:i:s'));
}
return NULL;
}
/**
* Get parameters for activity list.
*
* @see _civicrm_api3_generic_getlist_params
*
* @param array $request
* API request.
*/
function _civicrm_api3_activity_getlist_params(&$request) {
$fieldsToReturn = array(
'activity_date_time',
'activity_type_id',
'subject',
'source_contact_id',
);
$request['params']['return'] = array_unique(array_merge($fieldsToReturn, $request['extra']));
$request['params']['options']['sort'] = 'activity_date_time DESC';
$request['params'] += array(
'is_current_revision' => 1,
'is_deleted' => 0,
);
}
/**
* Get output for activity list.
*
* @see _civicrm_api3_generic_getlist_output
*
* @param array $result
* @param array $request
*
* @return array
*/
function _civicrm_api3_activity_getlist_output($result, $request) {
$output = array();
if (!empty($result['values'])) {
foreach ($result['values'] as $row) {
$data = array(
'id' => $row[$request['id_field']],
'label' => $row[$request['label_field']] ? $row[$request['label_field']] : ts('(no subject)'),
'description' => array(
CRM_Core_Pseudoconstant::getLabel('CRM_Activity_BAO_Activity', 'activity_type_id', $row['activity_type_id']),
),
);
if (!empty($row['activity_date_time'])) {
$data['description'][0] .= ': ' . CRM_Utils_Date::customFormat($row['activity_date_time']);
}
if (!empty($row['source_contact_id'])) {
$data['description'][] = ts('By %1', array(
1 => CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $row['source_contact_id'], 'display_name'),
));
}
// Add repeating info
$repeat = CRM_Core_BAO_RecurringEntity::getPositionAndCount($row['id'], 'civicrm_activity');
$data['extra']['is_recur'] = FALSE;
if ($repeat) {
$data['suffix'] = ts('(%1 of %2)', array(1 => $repeat[0], 2 => $repeat[1]));
$data['extra']['is_recur'] = TRUE;
}
$output[] = $data;
}
}
return $output;
}

View file

@ -0,0 +1,82 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
* This api exposes the CiviCRM ActivityContact join table.
*
* @package CiviCRM_APIv3
*/
/**
* Add a record relating a contact with an activity.
*
* @param array $params
*
* @return array
* API result array.
*/
function civicrm_api3_activity_contact_create($params) {
return _civicrm_api3_basic_create(_civicrm_api3_get_BAO(__FUNCTION__), $params);
}
/**
* Adjust Metadata for Create action.
*
* The metadata is used for setting defaults, documentation & validation.
*
* @param array $params
* Array of parameters determined by getfields.
*/
function _civicrm_api3_activity_contact_create_spec(&$params) {
$params['contact_id']['api.required'] = 1;
$params['activity_id']['api.required'] = 1;
}
/**
* Delete an existing ActivityContact record.
*
* @param array $params
*
* @return array
* API result array
*/
function civicrm_api3_activity_contact_delete($params) {
return _civicrm_api3_basic_delete(_civicrm_api3_get_BAO(__FUNCTION__), $params);
}
/**
* Get a ActivityContact.
*
* @param array $params
* An associative array of name/value pairs.
*
* @return array
* API result array
*/
function civicrm_api3_activity_contact_get($params) {
return _civicrm_api3_basic_get(_civicrm_api3_get_BAO(__FUNCTION__), $params);
}

View file

@ -0,0 +1,123 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
* The ActivityType api is deprecated. Please use the OptionValue api instead.
*
* @deprecated
*
* @package CiviCRM_APIv3
*/
/**
* Notification of deprecated function.
*
* @deprecated api notice
* @return string
* to indicate this entire api entity is deprecated
*/
function _civicrm_api3_activity_type_deprecation() {
return 'The ActivityType api is deprecated. Please use the OptionValue api instead.';
}
/**
* Retrieve activity types.
*
* @param array $params
*
* @return array
* activity types keyed by id
* @deprecated - use the getoptions action instead
*/
function civicrm_api3_activity_type_get($params) {
$activityTypes = CRM_Core_OptionGroup::values('activity_type');
return civicrm_api3_create_success($activityTypes, $params, 'activity_type', 'get');
}
/**
* Create activity type.
*
* @param array $params
*
* @return array
* created / updated activity type
*
* @deprecated use the OptionValue api instead
*/
function civicrm_api3_activity_type_create($params) {
$action = 1;
$groupParams = array('name' => 'activity_type');
if ($optionValueID = CRM_Utils_Array::value('option_value_id', $params)) {
$action = 2;
}
$activityObject = CRM_Core_OptionValue::addOptionValue($params, $groupParams, $action, $optionValueID);
$activityType = array();
_civicrm_api3_object_to_array($activityObject, $activityType[$activityObject->id]);
return civicrm_api3_create_success($activityType, $params, 'activity_type', 'create');
}
/**
* Adjust Metadata for Create action.
*
* The metadata is used for setting defaults, documentation & validation.
*
* @param array $params
* Array of parameters determined by getfields.
*/
function _civicrm_api3_activity_type_create_spec(&$params) {
$params['label'] = array(
'api.required' => 1,
'title' => 'Label',
'type' => CRM_Utils_Type::T_STRING,
);
$params['weight'] = array(
'api.required' => 1,
'title' => 'Weight',
'type' => CRM_Utils_Type::T_STRING,
);
}
/**
* Delete ActivityType.
*
* @param array $params
* Array including id of activity_type to delete.
* @return array API result array
* @throws API_Exception
* @deprecated use OptionValue api
*/
function civicrm_api3_activity_type_delete($params) {
$result = CRM_Core_BAO_OptionValue::del($params['id']);
if ($result) {
return civicrm_api3_create_success(TRUE, $params);
}
throw new API_Exception("Failure to delete activity type id {$params['id']}");
}

View file

@ -0,0 +1,158 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
* This api exposes CiviCRM Address records.
*
* @package CiviCRM_APIv3
*/
/**
* Add an Address for a contact.
*
* FIXME: Should be using basic_create util
*
* @param array $params
* Array per getfields metadata.
*
* @return array
* API result array
*/
function civicrm_api3_address_create(&$params) {
_civicrm_api3_check_edit_permissions('CRM_Core_BAO_Address', $params);
/**
* If street_parsing, street_address has to be parsed into
* separate parts
*/
if (array_key_exists('street_parsing', $params)) {
if ($params['street_parsing'] == 1) {
if (array_key_exists('street_address', $params)) {
if (!empty($params['street_address'])) {
$parsedItems = CRM_Core_BAO_Address::parseStreetAddress(
$params['street_address']
);
if (array_key_exists('street_name', $parsedItems)) {
$params['street_name'] = $parsedItems['street_name'];
}
if (array_key_exists('street_unit', $parsedItems)) {
$params['street_unit'] = $parsedItems['street_unit'];
}
if (array_key_exists('street_number', $parsedItems)) {
$params['street_number'] = $parsedItems['street_number'];
}
if (array_key_exists('street_number_suffix', $parsedItems)) {
$params['street_number_suffix'] = $parsedItems['street_number_suffix'];
}
}
}
}
}
if (!isset($params['check_permissions'])) {
$params['check_permissions'] = 0;
}
/**
* Create array for BAO (expects address params in as an
* element in array 'address'
*/
$addressBAO = CRM_Core_BAO_Address::add($params, TRUE);
if (empty($addressBAO)) {
return civicrm_api3_create_error("Address is not created or updated ");
}
else {
$values = _civicrm_api3_dao_to_array($addressBAO, $params);
return civicrm_api3_create_success($values, $params, 'Address', $addressBAO);
}
}
/**
* Adjust Metadata for Create action.
*
* @param array $params
* Array of parameters determined by getfields.
*/
function _civicrm_api3_address_create_spec(&$params) {
$params['location_type_id']['api.required'] = 1;
$params['contact_id']['api.required'] = 1;
$params['street_parsing'] = array(
'title' => 'Street Address Parsing',
'description' => 'Optional param to indicate you want the street_address field parsed into individual params',
'type' => CRM_Utils_Type::T_BOOLEAN,
);
$params['skip_geocode'] = array(
'title' => 'Skip geocode',
'description' => 'Optional param to indicate you want to skip geocoding (useful when importing a lot of addresses
at once, the job \'Geocode and Parse Addresses\' can execute this task after the import)',
'type' => CRM_Utils_Type::T_BOOLEAN,
);
$params['world_region'] = array(
'title' => ts('World Region'),
'name' => 'world_region',
'type' => CRM_Utils_Type::T_TEXT,
);
}
/**
* Adjust Metadata for Get action.
*
* @param array $params
* Array of parameters determined by getfields.
*/
function _civicrm_api3_address_get_spec(&$params) {
$params['world_region'] = array(
'title' => ts('World Region'),
'name' => 'world_region',
'type' => CRM_Utils_Type::T_TEXT,
);
}
/**
* Delete an existing Address.
*
* @param array $params
* Array per getfields metadata.
*
* @return array
* API result array
*/
function civicrm_api3_address_delete($params) {
return _civicrm_api3_basic_delete(_civicrm_api3_get_BAO(__FUNCTION__), $params);
}
/**
* Retrieve one or more addresses.
*
* @param array $params
* Array per getfields metadata.
*
* @return array
* API result array
*/
function civicrm_api3_address_get(&$params) {
return _civicrm_api3_basic_get(_civicrm_api3_get_BAO(__FUNCTION__), $params, TRUE, 'Address');
}

View file

@ -0,0 +1,498 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
* "Attachment" is a pseudo-entity which represents a record in civicrm_file
* combined with a record in civicrm_entity_file as well as the underlying
* file content.
* For core fields use "entity_table", for custom fields use "field_name"
*
* @code
* // Create an attachment for a core field
* $result = civicrm_api3('Attachment', 'create', array(
* 'entity_table' => 'civicrm_activity',
* 'entity_id' => 123,
* 'name' => 'README.txt',
* 'mime_type' => 'text/plain',
* 'content' => 'Please to read the README',
* ));
* $attachment = $result['values'][$result['id']];
* echo sprintf("<a href='%s'>View %s</a>", $attachment['url'], $attachment['name']);
* @endcode
*
* @code
* // Create an attachment for a custom file field
* $result = civicrm_api3('Attachment', 'create', array(
* 'field_name' => 'custom_6',
* 'entity_id' => 123,
* 'name' => 'README.txt',
* 'mime_type' => 'text/plain',
* 'content' => 'Please to read the README',
* ));
* $attachment = $result['values'][$result['id']];
* echo sprintf("<a href='%s'>View %s</a>", $attachment['url'], $attachment['name']);
* @endcode
*
* @code
* // Move an existing file and save as an attachment
* $result = civicrm_api3('Attachment', 'create', array(
* 'entity_table' => 'civicrm_activity',
* 'entity_id' => 123,
* 'name' => 'README.txt',
* 'mime_type' => 'text/plain',
* 'options' => array(
* 'move-file' => '/tmp/upload1a2b3c4d',
* ),
* ));
* $attachment = $result['values'][$result['id']];
* echo sprintf("<a href='%s'>View %s</a>", $attachment['url'], $attachment['name']);
* @endcode
*
* Notes:
* - File content is not returned by default. One must specify 'return => content'.
* - Features which deal with local file system (e.g. passing "options.move-file"
* or returning a "path") are only valid when executed as a local API (ie
* "check_permissions"==false)
*
* @package CiviCRM_APIv3
*/
/**
* Adjust metadata for "create" action.
*
* @param array $spec
* List of fields.
*/
function _civicrm_api3_attachment_create_spec(&$spec) {
$spec = array_merge($spec, _civicrm_api3_attachment_getfields());
$spec['name']['api.required'] = 1;
$spec['mime_type']['api.required'] = 1;
$spec['entity_id']['api.required'] = 1;
$spec['upload_date']['api.default'] = 'now';
}
/**
* Create an Attachment.
*
* @param array $params
*
* @return array
* @throws API_Exception validation errors
* @see Civi\API\Subscriber\DynamicFKAuthorization
*/
function civicrm_api3_attachment_create($params) {
if (empty($params['id'])) {
// When creating we need either entity_table or field_name.
civicrm_api3_verify_one_mandatory($params, NULL, array('entity_table', 'field_name'));
}
$config = CRM_Core_Config::singleton();
list($id, $file, $entityFile, $name, $content, $moveFile, $isTrusted, $returnContent) = _civicrm_api3_attachment_parse_params($params);
$fileDao = new CRM_Core_BAO_File();
$entityFileDao = new CRM_Core_DAO_EntityFile();
if ($id) {
$fileDao->id = $id;
if (!$fileDao->find(TRUE)) {
throw new API_Exception("Invalid ID");
}
$entityFileDao->file_id = $id;
if (!$entityFileDao->find(TRUE)) {
throw new API_Exception("Cannot modify orphaned file");
}
}
if (!$id && !is_string($content) && !is_string($moveFile)) {
throw new API_Exception("Mandatory key(s) missing from params array: 'id' or 'content' or 'options.move-file'");
}
if (!$isTrusted && $moveFile) {
throw new API_Exception("options.move-file is only supported on secure calls");
}
if (is_string($content) && is_string($moveFile)) {
throw new API_Exception("'content' and 'options.move-file' are mutually exclusive");
}
if ($id && !$isTrusted && isset($file['upload_date']) && $file['upload_date'] != CRM_Utils_Date::isoToMysql($fileDao->upload_date)) {
throw new API_Exception("Cannot modify upload_date" . var_export(array($file['upload_date'], $fileDao->upload_date, CRM_Utils_Date::isoToMysql($fileDao->upload_date)), TRUE));
}
if ($id && $name && $name != CRM_Utils_File::cleanFileName($fileDao->uri)) {
throw new API_Exception("Cannot modify name");
}
$fileDao->copyValues($file);
if (!$id) {
$fileDao->uri = CRM_Utils_File::makeFileName($name);
}
$fileDao->save();
$entityFileDao->copyValues($entityFile);
$entityFileDao->file_id = $fileDao->id;
$entityFileDao->save();
$path = $config->customFileUploadDir . DIRECTORY_SEPARATOR . $fileDao->uri;
if (is_string($content)) {
file_put_contents($path, $content);
}
elseif (is_string($moveFile)) {
// CRM-17432 Do not use rename() since it will break file permissions.
// Also avoid move_uplaoded_file() because the API can use options.move-file.
copy($moveFile, $path);
unlink($moveFile);
}
// Save custom field to entity
if (!$id && empty($params['entity_table']) && isset($params['field_name'])) {
civicrm_api3('custom_value', 'create', array(
'entity_id' => $params['entity_id'],
$params['field_name'] => $fileDao->id,
));
}
$result = array(
$fileDao->id => _civicrm_api3_attachment_format_result($fileDao, $entityFileDao, $returnContent, $isTrusted),
);
return civicrm_api3_create_success($result, $params, 'Attachment', 'create');
}
/**
* Adjust metadata for get action.
*
* @param array $spec
* List of fields.
*/
function _civicrm_api3_attachment_get_spec(&$spec) {
$spec = array_merge($spec, _civicrm_api3_attachment_getfields());
}
/**
* Get Attachment.
*
* @param array $params
*
* @return array
* per APIv3
* @throws API_Exception validation errors
*/
function civicrm_api3_attachment_get($params) {
list($id, $file, $entityFile, $name, $content, $moveFile, $isTrusted, $returnContent) = _civicrm_api3_attachment_parse_params($params);
$dao = __civicrm_api3_attachment_find($params, $id, $file, $entityFile, $isTrusted);
$result = array();
while ($dao->fetch()) {
$result[$dao->id] = _civicrm_api3_attachment_format_result($dao, $dao, $returnContent, $isTrusted);
}
return civicrm_api3_create_success($result, $params, 'Attachment', 'create');
}
/**
* Adjust metadata for Attachment delete action.
*
* @param $spec
*/
function _civicrm_api3_attachment_delete_spec(&$spec) {
unset($spec['id']['api.required']);
$entityFileFields = CRM_Core_DAO_EntityFile::fields();
$spec['entity_table'] = $entityFileFields['entity_table'];
$spec['entity_table']['title'] = CRM_Utils_Array::value('title', $spec['entity_table'], 'Entity Table') . ' (write-once)';
$spec['entity_id'] = $entityFileFields['entity_id'];
$spec['entity_id']['title'] = CRM_Utils_Array::value('title', $spec['entity_id'], 'Entity ID') . ' (write-once)';
}
/**
* Delete Attachment.
*
* @param array $params
*
* @return array
* @throws API_Exception
*/
function civicrm_api3_attachment_delete($params) {
if (!empty($params['id'])) {
// ok
}
elseif (!empty($params['entity_table']) && !empty($params['entity_id'])) {
// ok
}
else {
throw new API_Exception("Mandatory key(s) missing from params array: id or entity_table+entity_table");
}
$config = CRM_Core_Config::singleton();
list($id, $file, $entityFile, $name, $content, $moveFile, $isTrusted, $returnContent) = _civicrm_api3_attachment_parse_params($params);
$dao = __civicrm_api3_attachment_find($params, $id, $file, $entityFile, $isTrusted);
$filePaths = array();
$fileIds = array();
while ($dao->fetch()) {
$filePaths[] = $config->customFileUploadDir . DIRECTORY_SEPARATOR . $dao->uri;
$fileIds[] = $dao->id;
}
if (!empty($fileIds)) {
$idString = implode(',', array_filter($fileIds, 'is_numeric'));
CRM_Core_DAO::executeQuery("DELETE FROM civicrm_entity_file WHERE file_id in ($idString)");
CRM_Core_DAO::executeQuery("DELETE FROM civicrm_file WHERE id in ($idString)");
}
// unlink is non-transactional, so we do this as the last step -- just in case the other steps produce errors
if (!empty($filePaths)) {
foreach ($filePaths as $filePath) {
unlink($filePath);
}
}
$result = array();
return civicrm_api3_create_success($result, $params, 'Attachment', 'create');
}
/**
* Attachment find helper.
*
* @param array $params
* @param int|null $id the user-supplied ID of the attachment record
* @param array $file
* The user-supplied vales for the file (mime_type, description, upload_date).
* @param array $entityFile
* The user-supplied values of the entity-file (entity_table, entity_id).
* @param bool $isTrusted
*
* @return CRM_Core_DAO
* @throws API_Exception
*/
function __civicrm_api3_attachment_find($params, $id, $file, $entityFile, $isTrusted) {
foreach (array('name', 'content', 'path', 'url') as $unsupportedFilter) {
if (!empty($params[$unsupportedFilter])) {
throw new API_Exception("Get by $unsupportedFilter is not currently supported");
}
}
$select = CRM_Utils_SQL_Select::from('civicrm_file cf')
->join('cef', 'INNER JOIN civicrm_entity_file cef ON cf.id = cef.file_id')
->select(array(
'cf.id',
'cf.uri',
'cf.mime_type',
'cf.description',
'cf.upload_date',
'cef.entity_table',
'cef.entity_id',
));
if ($id) {
$select->where('cf.id = #id', array('#id' => $id));
}
// Recall: $file is filtered by parse_params.
foreach ($file as $key => $value) {
$select->where('cf.!field = @value', array(
'!field' => $key,
'@value' => $value,
));
}
// Recall: $entityFile is filtered by parse_params.
foreach ($entityFile as $key => $value) {
$select->where('cef.!field = @value', array(
'!field' => $key,
'@value' => $value,
));
}
if (!$isTrusted) {
// FIXME ACLs: Add any JOIN or WHERE clauses needed to enforce access-controls for the target entity.
//
// The target entity is identified by "cef.entity_table" (aka $entityFile['entity_table']) and "cef.entity_id".
//
// As a simplification, we *require* the "get" actions to filter on a single "entity_table" which should
// avoid the complexity of matching ACL's against multiple entity types.
}
$dao = CRM_Core_DAO::executeQuery($select->toSQL());
return $dao;
}
/**
* Attachment parsing helper.
*
* @param array $params
*
* @return array
* (0 => int $id, 1 => array $file, 2 => array $entityFile, 3 => string $name, 4 => string $content,
* 5 => string $moveFile, 6 => $isTrusted, 7 => bool $returnContent)
* - array $file: whitelisted fields that can pass through directly to civicrm_file
* - array $entityFile: whitelisted fields that can pass through directly to civicrm_entity_file
* - string $name: the printable name
* - string $moveFile: the full path to a local file whose content should be loaded
* - bool $isTrusted: whether we trust the requester to do sketchy things (like moving files or reassigning entities)
* - bool $returnContent: whether we are expected to return the full content of the file
* @throws API_Exception validation errors
*/
function _civicrm_api3_attachment_parse_params($params) {
$id = CRM_Utils_Array::value('id', $params, NULL);
if ($id && !is_numeric($id)) {
throw new API_Exception("Malformed id");
}
$file = array();
foreach (array('mime_type', 'description', 'upload_date') as $field) {
if (array_key_exists($field, $params)) {
$file[$field] = $params[$field];
}
}
$entityFile = array();
foreach (array('entity_table', 'entity_id') as $field) {
if (array_key_exists($field, $params)) {
$entityFile[$field] = $params[$field];
}
}
if (empty($params['entity_table']) && isset($params['field_name'])) {
$tableInfo = CRM_Core_BAO_CustomField::getTableColumnGroup(intval(str_replace('custom_', '', $params['field_name'])));
$entityFile['entity_table'] = $tableInfo[0];
}
$name = NULL;
if (array_key_exists('name', $params)) {
if ($params['name'] != basename($params['name']) || preg_match(':[/\\\\]:', $params['name'])) {
throw new API_Exception('Malformed name');
}
$name = $params['name'];
}
$content = NULL;
if (isset($params['content'])) {
$content = $params['content'];
}
$moveFile = NULL;
if (isset($params['options']['move-file'])) {
$moveFile = $params['options']['move-file'];
}
elseif (isset($params['options.move-file'])) {
$moveFile = $params['options.move-file'];
}
$isTrusted = empty($params['check_permissions']);
$returns = isset($params['return']) ? $params['return'] : array();
$returns = is_array($returns) ? $returns : array($returns);
$returnContent = in_array('content', $returns);
return array($id, $file, $entityFile, $name, $content, $moveFile, $isTrusted, $returnContent);
}
/**
* Attachment result formatting helper.
*
* @param CRM_Core_DAO_File $fileDao
* Maybe "File" or "File JOIN EntityFile".
* @param CRM_Core_DAO_EntityFile $entityFileDao
* Maybe "EntityFile" or "File JOIN EntityFile".
* @param bool $returnContent
* Whether to return the full content of the file.
* @param bool $isTrusted
* Whether the current request is trusted to perform file-specific operations.
*
* @return array
*/
function _civicrm_api3_attachment_format_result($fileDao, $entityFileDao, $returnContent, $isTrusted) {
$config = CRM_Core_Config::singleton();
$path = $config->customFileUploadDir . DIRECTORY_SEPARATOR . $fileDao->uri;
$result = array(
'id' => $fileDao->id,
'name' => CRM_Utils_File::cleanFileName($fileDao->uri),
'mime_type' => $fileDao->mime_type,
'description' => $fileDao->description,
'upload_date' => is_numeric($fileDao->upload_date) ? CRM_Utils_Date::mysqlToIso($fileDao->upload_date) : $fileDao->upload_date,
'entity_table' => $entityFileDao->entity_table,
'entity_id' => $entityFileDao->entity_id,
'icon' => CRM_Utils_File::getIconFromMimeType($fileDao->mime_type),
);
$result['url'] = CRM_Utils_System::url(
'civicrm/file', 'reset=1&id=' . $result['id'] . '&eid=' . $result['entity_id'],
TRUE,
NULL,
FALSE,
TRUE
);
if ($isTrusted) {
$result['path'] = $path;
}
if ($returnContent) {
$result['content'] = file_get_contents($path);
}
return $result;
}
/**
* Attachment getfields helper.
*
* @return array
* list of fields (indexed by name)
*/
function _civicrm_api3_attachment_getfields() {
$fileFields = CRM_Core_DAO_File::fields();
$entityFileFields = CRM_Core_DAO_EntityFile::fields();
$spec = array();
$spec['id'] = $fileFields['id'];
$spec['name'] = array(
'title' => 'Name (write-once)',
'description' => 'The logical file name (not searchable)',
'type' => CRM_Utils_Type::T_STRING,
);
$spec['field_name'] = array(
'title' => 'Field Name (write-once)',
'description' => 'Alternative to "entity_table" param - sets custom field value.',
'type' => CRM_Utils_Type::T_STRING,
);
$spec['mime_type'] = $fileFields['mime_type'];
$spec['description'] = $fileFields['description'];
$spec['upload_date'] = $fileFields['upload_date'];
$spec['entity_table'] = $entityFileFields['entity_table'];
// Would be hard to securely handle changes.
$spec['entity_table']['title'] = CRM_Utils_Array::value('title', $spec['entity_table'], 'Entity Table') . ' (write-once)';
$spec['entity_id'] = $entityFileFields['entity_id'];
$spec['entity_id']['title'] = CRM_Utils_Array::value('title', $spec['entity_id'], 'Entity ID') . ' (write-once)'; // would be hard to securely handle changes
$spec['url'] = array(
'title' => 'URL (read-only)',
'description' => 'URL for downloading the file (not searchable, expire-able)',
'type' => CRM_Utils_Type::T_STRING,
);
$spec['path'] = array(
'title' => 'Path (read-only)',
'description' => 'Local file path (not searchable, local-only)',
'type' => CRM_Utils_Type::T_STRING,
);
$spec['content'] = array(
'title' => 'Content',
'description' => 'File content (not searchable, not returned by default)',
'type' => CRM_Utils_Type::T_STRING,
);
return $spec;
}

View file

@ -0,0 +1,88 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
* This api exposes CiviCRM Batch records.
*
* @package CiviCRM_APIv3
*/
/**
* Save a Batch.
*
* @param array $params
*
* @return array
*/
function civicrm_api3_batch_create($params) {
return _civicrm_api3_basic_create(_civicrm_api3_get_BAO(__FUNCTION__), $params);
}
/**
* Adjust Metadata for Create action.
*
* The metadata is used for setting defaults, documentation & validation.
*
* @param array $params
* Array of parameters determined by getfields.
*/
function _civicrm_api3_batch_create_spec(&$params) {
//@todo - the entity table field looks like it is not actually required & should probably be removed (or a description added if
// it is actually required)
$params['entity_table']['api.default'] = "civicrm_batch";
$params['entity_table']['type'] = CRM_Utils_Type::T_STRING;
$params['entity_table']['title'] = 'Batch Entity Table - remove?';
$params['modified_date']['api.default'] = "now";
$params['status_id']['api.required'] = 1;
$params['title']['api.required'] = 1;
$params['status_id']['api.required'] = 1;
}
/**
* Get a Batch.
*
* @param array $params
*
* @return array
* Array of retrieved batch property values.
*/
function civicrm_api3_batch_get($params) {
return _civicrm_api3_basic_get(_civicrm_api3_get_BAO(__FUNCTION__), $params);
}
/**
* Delete a Batch.
*
* @param array $params
*
* @return array
* Array of deleted values.
*/
function civicrm_api3_batch_delete($params) {
return _civicrm_api3_basic_delete(_civicrm_api3_get_BAO(__FUNCTION__), $params);
}

View file

@ -0,0 +1,89 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
* This api exposes CiviCRM Campaign records.
*
* @note Campaign component must be enabled.
*
* @package CiviCRM_APIv3
*/
/**
* Create/update Campaign.
*
* This API is used to create new campaign or update any of the existing
* In case of updating existing campaign, id of that particular campaign must
* be in $params array.
*
* @param array $params
*
* @return array
*/
function civicrm_api3_campaign_create($params) {
return _civicrm_api3_basic_create(_civicrm_api3_get_BAO(__FUNCTION__), $params, 'Campaign');
}
/**
* Adjust Metadata for Create action.
*
* The metadata is used for setting defaults, documentation & validation.
*
* @param array $params
* Array of parameters determined by getfields.
*/
function _civicrm_api3_campaign_create_spec(&$params) {
$params['title']['api.required'] = 1;
}
/**
* Returns array of campaigns matching a set of one or more properties.
*
* @param array $params
* Array per getfields
*
* @return array
* Array of matching campaigns
*/
function civicrm_api3_campaign_get($params) {
return _civicrm_api3_basic_get(_civicrm_api3_get_BAO(__FUNCTION__), $params, TRUE, 'Campaign');
}
/**
* Delete an existing campaign.
*
* This method is used to delete any existing campaign.
* Id of the campaign to be deleted is required field in $params array
*
* @param array $params
* array containing id of the group to be deleted
*
* @return array
*/
function civicrm_api3_campaign_delete($params) {
return _civicrm_api3_basic_delete(_civicrm_api3_get_BAO(__FUNCTION__), $params);
}

View file

@ -0,0 +1,765 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
* This api exposes CiviCRM Case objects.
* Developed by woolman.org
*
* @package CiviCRM_APIv3
*/
/**
* Open a new case, add client and manager roles, and standard timeline.
*
* @param array $params
*
* @code
* //REQUIRED for create:
* 'case_type_id' => int OR
* 'case_type' => str (provide one or the other)
* 'contact_id' => int // case client
* 'subject' => str
* //REQUIRED for update:
* 'id' => case Id
*
* //OPTIONAL
* 'medium_id' => int // see civicrm option values for possibilities
* 'creator_id' => int // case manager, default to the logged in user
* 'status_id' => int // defaults to 1 "ongoing"
* 'location' => str
* 'start_date' => str datestamp // defaults to: date('YmdHis')
* 'duration' => int // in minutes
* 'details' => str // html format
* @endcode
*
* @throws API_Exception
* @return array
* api result array
*/
function civicrm_api3_case_create($params) {
_civicrm_api3_case_format_params($params);
if (empty($params['id'])) {
// Creating a new case, so make sure we have the necessary parameters
civicrm_api3_verify_mandatory($params, NULL, array(
'contact_id',
'subject',
array('case_type', 'case_type_id'),
)
);
}
else {
// Update an existing case
// FIXME: Some of this logic should move to the BAO object?
// FIXME: Should we check if case with ID actually exists?
if (!isset($params['case_id']) && isset($params['id'])) {
$params['case_id'] = $params['id'];
}
if (array_key_exists('creator_id', $params)) {
throw new API_Exception('You cannot update creator id');
}
$mergedCaseId = $origContactIds = array();
// get original contact id and creator id of case
if (!empty($params['contact_id'])) {
$origContactIds = CRM_Case_BAO_Case::retrieveContactIdsByCaseId($params['id']);
$origContactId = CRM_Utils_Array::first($origContactIds);
}
// FIXME: Refactor as separate method to get contactId
if (count($origContactIds) > 1) {
// check valid orig contact id
if (empty($params['orig_contact_id'])) {
throw new API_Exception('Case is linked with more than one contact id. Provide the required params orig_contact_id to be replaced');
}
if (!empty($params['orig_contact_id']) && !in_array($params['orig_contact_id'], $origContactIds)) {
throw new API_Exception('Invalid case contact id (orig_contact_id)');
}
$origContactId = $params['orig_contact_id'];
}
// check for same contact id for edit Client
if (!empty($params['contact_id']) && !in_array($params['contact_id'], $origContactIds)) {
$mergedCaseId = CRM_Case_BAO_Case::mergeCases($params['contact_id'], $params['case_id'], $origContactId, NULL, TRUE);
}
// If we merged cases then update the merged case
if (!empty($mergedCaseId[0])) {
$params['id'] = $mergedCaseId[0];
}
}
// Create/update the case
$caseBAO = CRM_Case_BAO_Case::create($params);
if (!$caseBAO) {
throw new API_Exception('Case not created. Please check input params.');
}
if (isset($params['contact_id'])) {
foreach ((array) $params['contact_id'] as $cid) {
$contactParams = array('case_id' => $caseBAO->id, 'contact_id' => $cid);
CRM_Case_BAO_CaseContact::create($contactParams);
}
}
if (!isset($params['id'])) {
// As the API was not passed an id we have created a new case.
// Only run the xmlProcessor for new cases to get all configuration for the new case.
_civicrm_api3_case_create_xmlProcessor($params, $caseBAO);
}
// return case
$values = array();
_civicrm_api3_object_to_array($caseBAO, $values[$caseBAO->id]);
return civicrm_api3_create_success($values, $params, 'Case', 'create', $caseBAO);
}
/**
* When creating a new case, run the xmlProcessor to get all necessary params/configuration
* for the new case, as cases use an xml file to store their configuration.
* @param $params
* @param $caseBAO
*/
function _civicrm_api3_case_create_xmlProcessor($params, $caseBAO) {
// Format params for xmlProcessor
if (isset($caseBAO->id)) {
$params['id'] = $caseBAO->id;
}
// Initialize XML processor with $params
$xmlProcessor = new CRM_Case_XMLProcessor_Process();
$xmlProcessorParams = array(
'clientID' => CRM_Utils_Array::value('contact_id', $params),
'creatorID' => CRM_Utils_Array::value('creator_id', $params),
'standardTimeline' => 1,
'activityTypeName' => 'Open Case',
'caseID' => CRM_Utils_Array::value('id', $params),
'subject' => CRM_Utils_Array::value('subject', $params),
'location' => CRM_Utils_Array::value('location', $params),
'activity_date_time' => CRM_Utils_Array::value('start_date', $params),
'duration' => CRM_Utils_Array::value('duration', $params),
'medium_id' => CRM_Utils_Array::value('medium_id', $params),
'details' => CRM_Utils_Array::value('details', $params),
'custom' => array(),
);
// Do it! :-D
$xmlProcessor->run($params['case_type'], $xmlProcessorParams);
}
/**
* Adjust Metadata for Get Action.
*
* @param array $params
* Parameters determined by getfields.
*/
function _civicrm_api3_case_get_spec(&$params) {
$params['contact_id'] = array(
'api.aliases' => array('client_id'),
'title' => 'Case Client',
'description' => 'Contact id of one or more clients to retrieve cases for',
'type' => CRM_Utils_Type::T_INT,
);
$params['activity_id'] = array(
'title' => 'Case Activity',
'description' => 'Id of an activity in the case',
'type' => CRM_Utils_Type::T_INT,
);
$params['tag_id'] = array(
'title' => 'Tags',
'description' => 'Find activities with specified tags.',
'type' => 1,
'FKClassName' => 'CRM_Core_DAO_Tag',
'FKApiName' => 'Tag',
'supports_joins' => TRUE,
);
}
/**
* Adjust Metadata for Create Action.
*
* @param array $params
* Array of parameters determined by getfields.
*/
function _civicrm_api3_case_create_spec(&$params) {
$params['contact_id'] = array(
'api.aliases' => array('client_id'),
'title' => 'Case Client',
'description' => 'Contact id of case client(s)',
'api.required' => 1,
'type' => CRM_Utils_Type::T_INT,
);
$params['status_id']['api.default'] = 1;
$params['status_id']['api.aliases'] = array('case_status');
$params['creator_id']['api.default'] = 'user_contact_id';
$params['creator_id']['type'] = CRM_Utils_Type::T_INT;
$params['creator_id']['title'] = 'Case Created By';
$params['start_date']['api.default'] = 'now';
$params['medium_id'] = array(
'name' => 'medium_id',
'title' => 'Activity Medium',
'type' => CRM_Utils_Type::T_INT,
);
}
/**
* Adjust Metadata for Update action.
*
* @param array $params
* Array of parameters determined by getfields.
*/
function _civicrm_api3_case_update_spec(&$params) {
$params['id']['api.required'] = 1;
}
/**
* Adjust Metadata for Delete action.
*
* @param array $params
* Array of parameters determined by getfields.
*/
function _civicrm_api3_case_delete_spec(&$params) {
$params['id']['api.required'] = 1;
}
/**
* Get details of a particular case, or search for cases, depending on params.
*
* Please provide one (and only one) of the four get/search parameters:
*
* @param array $params
* 'id' => if set, will get all available info about a case, including contacts and activities
*
* // if no case_id provided, this function will use one of the following search parameters:
* 'client_id' => finds all cases with a specific client
* 'activity_id' => returns the case containing a specific activity
* 'contact_id' => finds all cases associated with a contact (in any role, not just client)
* $params CRM_Utils_SQL_Select $sql
* Other apis wishing to wrap & extend this one can pass in a $sql object with extra clauses
*
* @throws API_Exception
* @return array
* (get mode, case_id provided): Array with case details, case roles, case activity ids, (search mode, case_id not provided): Array of cases found
*/
function civicrm_api3_case_get($params, $sql = NULL) {
$options = _civicrm_api3_get_options_from_params($params);
if (!is_a($sql, 'CRM_Utils_SQL_Select')) {
$sql = CRM_Utils_SQL_Select::fragment();
}
// Add clause to search by client
if (!empty($params['contact_id'])) {
// Legacy support - this field historically supports a nonstandard format of array(1,2,3) as a synonym for array('IN' => array(1,2,3))
if (is_array($params['contact_id'])) {
$operator = CRM_Utils_Array::first(array_keys($params['contact_id']));
if (!in_array($operator, \CRM_Core_DAO::acceptedSQLOperators(), TRUE)) {
$params['contact_id'] = array('IN' => $params['contact_id']);
}
}
else {
$params['contact_id'] = array('=' => $params['contact_id']);
}
$clause = CRM_Core_DAO::createSQLFilter('contact_id', $params['contact_id']);
$sql->where("a.id IN (SELECT case_id FROM civicrm_case_contact WHERE $clause)");
}
// Order by case contact (primary client)
// Ex: "contact_id", "contact_id.display_name", "contact_id.sort_name DESC".
if (!empty($options['sort']) && strpos($options['sort'], 'contact_id') !== FALSE) {
$sort = explode(', ', $options['sort']);
$contactSort = NULL;
foreach ($sort as $index => &$sortString) {
if (strpos($sortString, 'contact_id') === 0) {
$contactSort = $sortString;
$sortString = '(1)';
// Get sort field and direction
list($sortField, $dir) = array_pad(explode(' ', $contactSort), 2, 'ASC');
list(, $sortField) = array_pad(explode('.', $sortField), 2, 'id');
// Validate inputs
if (!array_key_exists($sortField, CRM_Contact_DAO_Contact::fieldKeys()) || ($dir != 'ASC' && $dir != 'DESC')) {
throw new API_Exception("Unknown field specified for sort. Cannot order by '$contactSort'");
}
$sql->orderBy("case_contact.$sortField $dir", NULL, $index);
}
}
// Remove contact sort params so the basic_get function doesn't see them
$params['options']['sort'] = implode(', ', $sort);
unset($params['option_sort'], $params['option.sort'], $params['sort']);
// Add necessary joins to the first case client
if ($contactSort) {
$sql->join('ccc', 'LEFT JOIN (SELECT * FROM civicrm_case_contact WHERE id IN (SELECT MIN(id) FROM civicrm_case_contact GROUP BY case_id)) AS ccc ON ccc.case_id = a.id');
$sql->join('case_contact', 'LEFT JOIN civicrm_contact AS case_contact ON ccc.contact_id = case_contact.id AND case_contact.is_deleted <> 1');
}
}
// Add clause to search by activity
if (!empty($params['activity_id'])) {
if (!CRM_Utils_Rule::positiveInteger($params['activity_id'])) {
throw new API_Exception('Invalid parameter: activity_id. Must provide a numeric value.');
}
$activityId = $params['activity_id'];
$originalId = CRM_Core_DAO::getFieldValue('CRM_Activity_BAO_Activity', $activityId, 'original_id');
if ($originalId) {
$activityId .= ',' . $originalId;
}
$sql
->join('civicrm_case_activity', 'INNER JOIN civicrm_case_activity ON civicrm_case_activity.case_id = a.id')
->where("civicrm_case_activity.activity_id IN ($activityId)");
}
// Clause to search by tag
if (!empty($params['tag_id'])) {
$dummySpec = array();
_civicrm_api3_validate_integer($params, 'tag_id', $dummySpec, 'Case');
if (!is_array($params['tag_id'])) {
$params['tag_id'] = array('=' => $params['tag_id']);
}
$clause = \CRM_Core_DAO::createSQLFilter('tag_id', $params['tag_id']);
if ($clause) {
$sql->where('a.id IN (SELECT entity_id FROM civicrm_entity_tag WHERE entity_table = "civicrm_case" AND !clause)', array('!clause' => $clause));
}
}
$cases = _civicrm_api3_basic_get(_civicrm_api3_get_BAO(__FUNCTION__), array('sequential' => 0) + $params, TRUE, 'Case', $sql);
if (empty($options['is_count']) && !empty($cases['values'])) {
// For historic reasons we return these by default only when fetching a case by id
if (!empty($params['id']) && is_numeric($params['id']) && empty($options['return'])) {
$options['return'] = array(
'contacts' => 1,
'activities' => 1,
'contact_id' => 1,
);
}
_civicrm_api3_case_read($cases['values'], $options);
// We disabled sequential to keep the list indexed for case_read(). Now add it back.
if (!empty($params['sequential'])) {
$cases['values'] = array_values($cases['values']);
}
}
return $cases;
}
/**
* Deprecated API.
*
* Use activity API instead.
*
* @param array $params
*
* @throws API_Exception
* @return array
*/
function civicrm_api3_case_activity_create($params) {
require_once "api/v3/Activity.php";
return civicrm_api3_activity_create($params) + array(
'deprecated' => CRM_Utils_Array::value('activity_create', _civicrm_api3_case_deprecation()),
);
}
/**
* Add a timeline to a case.
*
* @param array $params
*
* @throws API_Exception
* @return array
*/
function civicrm_api3_case_addtimeline($params) {
$caseType = CRM_Case_BAO_Case::getCaseType($params['case_id'], 'name');
$xmlProcessor = new CRM_Case_XMLProcessor_Process();
$xmlProcessorParams = array(
'clientID' => CRM_Case_BAO_Case::getCaseClients($params['case_id']),
'creatorID' => $params['creator_id'],
'standardTimeline' => 0,
'activity_date_time' => $params['activity_date_time'],
'caseID' => $params['case_id'],
'caseType' => $caseType,
'activitySetName' => $params['timeline'],
);
$xmlProcessor->run($caseType, $xmlProcessorParams);
return civicrm_api3_create_success();
}
/**
* Adjust Metadata for addtimeline action.
*
* @param array $params
* Array of parameters determined by getfields.
*/
function _civicrm_api3_case_addtimeline_spec(&$params) {
$params['case_id'] = array(
'title' => 'Case ID',
'description' => 'Id of case to update',
'type' => CRM_Utils_Type::T_INT,
'api.required' => 1,
);
$params['timeline'] = array(
'title' => 'Timeline',
'description' => 'Name of activity set',
'type' => CRM_Utils_Type::T_STRING,
'api.required' => 1,
);
$params['activity_date_time'] = array(
'api.default' => 'now',
'title' => 'Activity date time',
'description' => 'Timeline start date',
'type' => CRM_Utils_Type::T_DATE,
);
$params['creator_id'] = array(
'api.default' => 'user_contact_id',
'title' => 'Activity creator',
'description' => 'Contact id of timeline creator',
'type' => CRM_Utils_Type::T_INT,
);
}
/**
* Merge 2 cases.
*
* @param array $params
*
* @throws API_Exception
* @return array
*/
function civicrm_api3_case_merge($params) {
$clients1 = CRM_Case_BAO_Case::getCaseClients($params['case_id_1']);
$clients2 = CRM_Case_BAO_Case::getCaseClients($params['case_id_2']);
CRM_Case_BAO_Case::mergeCases($clients1[0], $params['case_id_1'], $clients2[0], $params['case_id_2']);
return civicrm_api3_create_success();
}
/**
* Adjust Metadata for merge action.
*
* @param array $params
* Array of parameters determined by getfields.
*/
function _civicrm_api3_case_merge_spec(&$params) {
$params['case_id_1'] = array(
'title' => 'Case ID 1',
'description' => 'Id of main case',
'type' => CRM_Utils_Type::T_INT,
'api.required' => 1,
);
$params['case_id_2'] = array(
'title' => 'Case ID 2',
'description' => 'Id of second case',
'type' => CRM_Utils_Type::T_INT,
'api.required' => 1,
);
}
/**
* Declare deprecated api functions.
*
* @deprecated api notice
* @return array
* Array of deprecated actions
*/
function _civicrm_api3_case_deprecation() {
return array('activity_create' => 'Case api "activity_create" action is deprecated. Use the activity api instead.');
}
/**
* @deprecated Update a specified case. Use civicrm_api3_case_create() instead.
*
* @param array $params
* //REQUIRED:
* 'case_id' => int
*
* //OPTIONAL
* 'status_id' => int
* 'start_date' => str datestamp
* 'contact_id' => int // case client
*
* @throws API_Exception
* @return array
* api result array
*/
function civicrm_api3_case_update($params) {
if (!isset($params['case_id']) && isset($params['id'])) {
$params['case_id'] = $params['id'];
}
//check parameters
civicrm_api3_verify_mandatory($params, NULL, array('id'));
// return error if modifying creator id
if (array_key_exists('creator_id', $params)) {
throw new API_Exception(ts('You cannot update creator id'));
}
$mCaseId = $origContactIds = array();
// get original contact id and creator id of case
if (!empty($params['contact_id'])) {
$origContactIds = CRM_Case_BAO_Case::retrieveContactIdsByCaseId($params['id']);
$origContactId = CRM_Utils_Array::first($origContactIds);
}
if (count($origContactIds) > 1) {
// check valid orig contact id
if (!empty($params['orig_contact_id']) && !in_array($params['orig_contact_id'], $origContactIds)) {
throw new API_Exception('Invalid case contact id (orig_contact_id)');
}
elseif (empty($params['orig_contact_id'])) {
throw new API_Exception('Case is linked with more than one contact id. Provide the required params orig_contact_id to be replaced');
}
$origContactId = $params['orig_contact_id'];
}
// check for same contact id for edit Client
if (!empty($params['contact_id']) && !in_array($params['contact_id'], $origContactIds)) {
$mCaseId = CRM_Case_BAO_Case::mergeCases($params['contact_id'], $params['case_id'], $origContactId, NULL, TRUE);
}
if (!empty($mCaseId[0])) {
$params['id'] = $mCaseId[0];
}
$dao = new CRM_Case_BAO_Case();
$dao->id = $params['id'];
$dao->copyValues($params);
$dao->save();
$case = array();
_civicrm_api3_object_to_array($dao, $case);
return civicrm_api3_create_success(array($dao->id => $case), $params, 'Case', 'update', $dao);
}
/**
* Delete a specified case.
*
* @param array $params
*
* @code
* //REQUIRED:
* 'id' => int
*
* //OPTIONAL
* 'move_to_trash' => bool (defaults to false)
* @endcode
*
* @throws API_Exception
* @return mixed
*/
function civicrm_api3_case_delete($params) {
//check parameters
civicrm_api3_verify_mandatory($params, NULL, array('id'));
if (CRM_Case_BAO_Case::deleteCase($params['id'], CRM_Utils_Array::value('move_to_trash', $params, FALSE))) {
return civicrm_api3_create_success($params, $params, 'Case', 'delete');
}
else {
throw new API_Exception('Could not delete case.');
}
}
/**
* Case.restore API specification
*
* @param array $spec description of fields supported by this API call
* @return void
*/
function _civicrm_api3_case_restore_spec(&$spec) {
$result = civicrm_api3('Case', 'getfields', array('api_action' => 'delete'));
$spec = array('id' => $result['values']['id']);
}
/**
* Restore a specified case from the trash.
*
* @param array $params
* @throws API_Exception
* @return mixed
*/
function civicrm_api3_case_restore($params) {
if (CRM_Case_BAO_Case::restoreCase($params['id'])) {
return civicrm_api3_create_success($params, $params, 'Case', 'restore');
}
else {
throw new API_Exception('Could not restore case.');
}
}
/**
* Augment case results with extra data.
*
* @param array $cases
* @param array $options
*/
function _civicrm_api3_case_read(&$cases, $options) {
foreach ($cases as &$case) {
if (empty($options['return']) || !empty($options['return']['contact_id'])) {
// Legacy support for client_id - TODO: in apiv4 remove 'client_id'
$case['client_id'] = $case['contact_id'] = CRM_Case_BAO_Case::retrieveContactIdsByCaseId($case['id']);
}
if (!empty($options['return']['contacts'])) {
//get case contacts
$contacts = CRM_Case_BAO_Case::getcontactNames($case['id']);
$relations = CRM_Case_BAO_Case::getRelatedContacts($case['id']);
$case['contacts'] = array_unique(array_merge($contacts, $relations), SORT_REGULAR);
}
if (!empty($options['return']['activities'])) {
// add case activities array - we'll populate them in bulk below
$case['activities'] = array();
}
// Properly render this joined field
if (!empty($options['return']['case_type_id.definition'])) {
if (!empty($case['case_type_id.definition'])) {
list($xml) = CRM_Utils_XML::parseString($case['case_type_id.definition']);
}
else {
$caseTypeId = !empty($case['case_type_id']) ? $case['case_type_id'] : CRM_Core_DAO::getFieldValue('CRM_Case_DAO_Case', $case['id'], 'case_type_id');
$caseTypeName = !empty($case['case_type_id.name']) ? $case['case_type_id.name'] : CRM_Core_DAO::getFieldValue('CRM_Case_DAO_CaseType', $caseTypeId, 'name');
$xml = CRM_Case_XMLRepository::singleton()->retrieve($caseTypeName);
}
$case['case_type_id.definition'] = array();
if ($xml) {
$case['case_type_id.definition'] = CRM_Case_BAO_CaseType::convertXmlToDefinition($xml);
}
}
}
// Bulk-load activities
if (!empty($options['return']['activities'])) {
$query = "SELECT case_id, activity_id FROM civicrm_case_activity WHERE case_id IN (%1)";
$params = array(1 => array(implode(',', array_keys($cases)), 'String', CRM_Core_DAO::QUERY_FORMAT_NO_QUOTES));
$dao = CRM_Core_DAO::executeQuery($query, $params);
while ($dao->fetch()) {
$cases[$dao->case_id]['activities'][] = $dao->activity_id;
}
}
// Bulk-load tags. Supports joins onto the tag entity.
$tagGet = array('tag_id', 'entity_id');
foreach (array_keys($options['return']) as $key) {
if (strpos($key, 'tag_id.') === 0) {
$tagGet[] = $key;
$options['return']['tag_id'] = 1;
}
}
if (!empty($options['return']['tag_id'])) {
$tags = civicrm_api3('EntityTag', 'get', array(
'entity_table' => 'civicrm_case',
'entity_id' => array('IN' => array_keys($cases)),
'return' => $tagGet,
'options' => array('limit' => 0),
));
foreach ($tags['values'] as $tag) {
$key = (int) $tag['entity_id'];
unset($tag['entity_id'], $tag['id']);
$cases[$key]['tag_id'][$tag['tag_id']] = $tag;
}
}
}
/**
* Internal function to format create params for processing.
*
* @param array $params
*/
function _civicrm_api3_case_format_params(&$params) {
// Format/include custom params
$values = array();
_civicrm_api3_custom_format_params($params, $values, 'Case');
$params = array_merge($params, $values);
if (empty($params['case_type_id']) && empty($params['case_type'])) {
return;
}
// figure out case_type_id from case_type and vice-versa
$caseTypes = CRM_Case_PseudoConstant::caseType('name', FALSE);
if (empty($params['case_type_id'])) {
$params['case_type_id'] = array_search($params['case_type'], $caseTypes);
// DEPRECATED: lookup by label for backward compatibility
if (!$params['case_type_id']) {
$caseTypeLabels = CRM_Case_PseudoConstant::caseType('title', FALSE);
$params['case_type_id'] = array_search($params['case_type'], $caseTypeLabels);
$params['case_type'] = $caseTypes[$params['case_type_id']];
}
}
elseif (empty($params['case_type'])) {
$params['case_type'] = $caseTypes[$params['case_type_id']];
}
}
/**
* It actually works a lot better to use the CaseContact api instead of the Case api
* for entityRef fields so we can perform the necessary joins,
* so we pass off getlist requests to the CaseContact api.
*
* @param array $params
* @return mixed
*/
function civicrm_api3_case_getList($params) {
require_once 'api/v3/Generic/Getlist.php';
require_once 'api/v3/CaseContact.php';
//CRM:19956 - Assign case_id param if both id and case_id is passed to retrieve the case
if (!empty($params['id']) && !empty($params['params']) && !empty($params['params']['case_id'])) {
$params['params']['case_id'] = array('IN' => $params['id']);
unset($params['id']);
}
$params['id_field'] = 'case_id';
$params['label_field'] = $params['search_field'] = 'contact_id.sort_name';
$params['description_field'] = array(
'case_id',
'case_id.case_type_id.title',
'case_id.subject',
'case_id.status_id',
'case_id.start_date',
);
$apiRequest = array(
'version' => 3,
'entity' => 'CaseContact',
'action' => 'getlist',
'params' => $params,
);
return civicrm_api3_generic_getList($apiRequest);
}
/**
* Needed due to the above override
* @param $params
* @param $apiRequest
*/
function _civicrm_api3_case_getlist_spec(&$params, $apiRequest) {
require_once 'api/v3/Generic/Getlist.php';
_civicrm_api3_generic_getlist_spec($params, $apiRequest);
}

View file

@ -0,0 +1,107 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
* This api exposes CiviCRM CaseContact records.
*
* @package CiviCRM_APIv3
*/
/**
* Save a CaseContact.
*
* @param array $params
*
* @return array
*/
function civicrm_api3_case_contact_create($params) {
return _civicrm_api3_basic_create(_civicrm_api3_get_BAO(__FUNCTION__), $params);
}
/**
* @param array $fields
*/
function _civicrm_api3_case_contact_create_spec(&$fields) {
$fields['contact_id']['api.required'] = $fields['case_id']['api.required'] = 1;
}
/**
* Get a CaseContact.
*
* @param array $params
*
* @return array
* Array of retrieved case_contact property values.
*/
function civicrm_api3_case_contact_get($params) {
return _civicrm_api3_basic_get(_civicrm_api3_get_BAO(__FUNCTION__), $params);
}
/**
* Delete a CaseContact.
*
* @param array $params
*
* @return array
* Array of deleted values.
*/
function civicrm_api3_case_contact_delete($params) {
return _civicrm_api3_basic_delete(_civicrm_api3_get_BAO(__FUNCTION__), $params);
}
/**
* Results formatting for Case entityRef lookups.
*
* @param array $result
* @param array $request
* @param string $entity
* @param array $fields
*
* @return array
*/
function _civicrm_api3_case_contact_getlist_output($result, $request, $entity, $fields) {
$output = array();
if (!empty($result['values'])) {
foreach ($result['values'] as $row) {
$data = array(
'id' => $row[$request['id_field']],
'label' => $row[$request['label_field']] . ' - ' . $row['case_id.case_type_id.title'],
);
$status = CRM_Core_PseudoConstant::getLabel('CRM_Case_BAO_Case', 'status_id', $row['case_id.status_id']);
$date = CRM_Utils_Date::customFormat($row['case_id.start_date']);
$data['description'] = array(
"#{$row['case_id']}: $status " . ts('(opened %1)', array(1 => $date)),
$row['case_id.subject'],
);
if (!empty($request['image_field'])) {
$data['image'] = isset($row[$request['image_field']]) ? $row[$request['image_field']] : '';
}
$output[] = $data;
}
}
return $output;
}

View file

@ -0,0 +1,121 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
* This api exposes CiviCRM Case.
*
* @package CiviCRM_APIv3
*/
/**
* Create or update case type.
*
* @param array $params
* Input parameters.
*
* @throws API_Exception
* @return array
* API result array
*/
function civicrm_api3_case_type_create($params) {
civicrm_api3_verify_mandatory($params, _civicrm_api3_get_DAO(__FUNCTION__));
// Computed properties.
unset($params['is_forkable']);
unset($params['is_forked']);
if (!array_key_exists('is_active', $params) && empty($params['id'])) {
$params['is_active'] = TRUE;
}
// This is an existing case-type.
if (!empty($params['id']) && isset($params['definition'])
&& !CRM_Case_BAO_CaseType::isForked($params['id']) // which is not yet forked
&& !CRM_Case_BAO_CaseType::isForkable($params['id']) // for which new forks are prohibited
) {
unset($params['definition']);
}
$result = _civicrm_api3_basic_create(_civicrm_api3_get_BAO(__FUNCTION__), $params, 'CaseType');
return _civicrm_api3_case_type_get_formatResult($result);
}
/**
* Retrieve case types.
*
* @param array $params
*
* @return array
* case types keyed by id
*/
function civicrm_api3_case_type_get($params) {
if (!empty($params['options']) && !empty($params['options']['is_count'])) {
return _civicrm_api3_basic_get(_civicrm_api3_get_BAO(__FUNCTION__), $params);
}
$caseTypes = _civicrm_api3_basic_get(_civicrm_api3_get_BAO(__FUNCTION__), $params);
// format case type, to fetch xml definition
$options = _civicrm_api3_get_options_from_params($params);
return _civicrm_api3_case_type_get_formatResult($caseTypes, $options);
}
/**
* Format definition.
*
* @param array $result
* @param array $options
*
* @return array
* @throws \CRM_Core_Exception
*/
function _civicrm_api3_case_type_get_formatResult(&$result, $options = array()) {
foreach ($result['values'] as $key => &$caseType) {
if (!empty($caseType['definition'])) {
list($xml) = CRM_Utils_XML::parseString($caseType['definition']);
$caseType['definition'] = $xml ? CRM_Case_BAO_CaseType::convertXmlToDefinition($xml) : array();
}
else {
if (empty($options['return']) || !empty($options['return']['definition'])) {
$caseTypeName = (isset($caseType['name'])) ? $caseType['name'] : CRM_Core_DAO::getFieldValue('CRM_Case_DAO_CaseType', $caseType['id'], 'name', 'id', TRUE);
$xml = CRM_Case_XMLRepository::singleton()->retrieve($caseTypeName);
$caseType['definition'] = $xml ? CRM_Case_BAO_CaseType::convertXmlToDefinition($xml) : array();
}
}
$caseType['is_forkable'] = CRM_Case_BAO_CaseType::isForkable($caseType['id']);
$caseType['is_forked'] = CRM_Case_BAO_CaseType::isForked($caseType['id']);
}
return $result;
}
/**
* Function to delete case type.
*
* @param array $params
* Array including id of CaseType to delete.
*
* @return array
* API result array
*/
function civicrm_api3_case_type_delete($params) {
return _civicrm_api3_basic_delete(_civicrm_api3_get_BAO(__FUNCTION__), $params);
}

View file

@ -0,0 +1,195 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
* CiviCRM APIv3 pseudoconstants
*
* @deprecated
* The Constant api is deprecated as of CiviCRM 4.4. Please use the getoptions api action instead.
* @package CiviCRM_APIv3
*/
/**
* Declare deprecated api entity.
*
* @deprecated api notice
* @return string
* to indicate this entire api entity is deprecated
*/
function _civicrm_api3_constant_deprecation() {
return 'The Constant api is deprecated as of CiviCRM 4.4. Please use the getoptions api action instead.';
}
/**
* Get constant values (deprecated).
*
* @deprecated as of CiviCRM 4.4.
* It's recommended to use the api getoptions action instead
*
* @param array $params
* Name of a public static method of
* CRM_Core_PseudoConstant: one of
* activityStatus
* activityType
* addressee
* allGroup
* country
* countryIsoCode
* county
* currencyCode
* currencySymbols
* customGroup
* emailGreeting
* fromEmailAddress
* gender
* group
* groupIterator
* honor
* IMProvider
* individualPrefix
* individualSuffix
* locationType
* locationVcardName
* mailProtocol
* mappingTypes
* paymentProcessor
* paymentProcessorType
* pcm
* phoneType
* postalGreeting
* priority
* relationshipType
* stateProvince
* stateProvinceAbbreviation
* stateProvinceForCountry
* staticGroup
* tag
* tasks
* ufGroup
* visibility
* worldRegion
* wysiwygEditor
*
* @return array
*/
function civicrm_api3_constant_get($params) {
$name = $params['name'];
// all the stuff about classes should be adequately replaced by the bit in the 'else'
//ie $values = call_user_func(array('CRM_Utils_PseudoConstant', 'getConstant'), $name);
// once tests are 100% can try removing the first block & a similar block from Generic:getoptions
// Whitelist approach is safer
$allowedClasses = array(
'CRM_Core_PseudoConstant',
'CRM_Event_PseudoConstant',
'CRM_Contribute_PseudoConstant',
'CRM_Member_PseudoConstant',
);
$className = $allowedClasses[0];
if (!empty($params['class']) && in_array($params['class'], $allowedClasses)) {
$className = $params['class'];
}
$callable = "$className::$name";
if (is_callable($callable)) {
if (empty($params)) {
$values = call_user_func(array($className, $name));
}
else {
$values = call_user_func(array($className, $name));
//@TODO XAV take out the param the COOKIE, Entity, Action and so there are only the "real param" in it
//$values = call_user_func_array( array( $className, $name ), $params );
}
return civicrm_api3_create_success($values, $params, 'Constant');
}
else {
$values = call_user_func(array('CRM_Utils_PseudoConstant', 'getConstant'), $name);
if (!empty($values)) {
return civicrm_api3_create_success($values, $params, 'Constant');
}
}
return civicrm_api3_create_error('Unknown civicrm constant or method not callable');
}
/**
* Adjust metadata for constant get action.
*
* @param array $params
*/
function _civicrm_api3_constant_get_spec(&$params) {
$options = array(
'activityStatus',
'activityType',
'addressee',
'allGroup',
'country',
'countryIsoCode',
'county',
'currencyCode',
'currencySymbols',
'customGroup',
'emailGreeting',
'fromEmailAddress',
'gender',
'group',
'honor',
'IMProvider',
'individualPrefix',
'individualSuffix',
'locationType',
'locationVcardName',
'mailProtocol',
'mappingTypes',
'paymentInstrument',
'paymentProcessor',
'paymentProcessorType',
'pcm',
'phoneType',
'postalGreeting',
'priority',
'relationshipType',
'stateProvince',
'stateProvinceAbbreviation',
'stateProvinceForCountry',
'staticGroup',
'tag',
'tasks',
'ufGroup',
'visibility',
'worldRegion',
'wysiwygEditor',
);
$params = array(
'name' => array(
'title' => 'Constant Name',
'name' => 'name',
'api.required' => 1,
'options' => array_combine($options, $options),
'type' => CRM_Utils_Type::T_STRING,
),
);
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,95 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
* This api exposes CiviCRM contact types and sub-types.
*
* CiviCRM comes with 3 primary contact types - Individual, Organization & Household.
* Changing these is not advised, but sub_types can be created with this api.
* Pass 'parent_id' param to specify which base type a new sub_type extends.
*
* @package CiviCRM_APIv3
*/
/**
* Create/update ContactType.
*
* This API is used to create new ContactType or update any of the existing
* In case of updating existing ContactType, id of that particular ContactType must
* be in $params array.
*
* @param array $params
* Array per getfields metadata.
*
* @return array
* ContactType array
*/
function civicrm_api3_contact_type_create($params) {
civicrm_api3_verify_mandatory($params, _civicrm_api3_get_DAO(__FUNCTION__), array('name', 'parent_id'));
if (empty($params['id'])) {
if (!array_key_exists('label', $params)) {
$params['label'] = $params['name'];
}
if (!array_key_exists('is_active', $params)) {
$params['is_active'] = TRUE;
}
$params['name'] = CRM_Utils_String::munge($params['name']);
}
return _civicrm_api3_basic_create(_civicrm_api3_get_BAO(__FUNCTION__), $params);
}
/**
* Returns array of contact_types matching a set of one or more properties.
*
* @param array $params
* One or more valid property_name=>value pairs.
* If $params is set as null, all contact_types will be returned
*
* @return array
* Array of matching contact_types
*/
function civicrm_api3_contact_type_get($params) {
civicrm_api3_verify_mandatory($params);
return _civicrm_api3_basic_get(_civicrm_api3_get_BAO(__FUNCTION__), $params);
}
/**
* Delete an existing ContactType.
*
* This method is used to delete any existing ContactType given its id.
*
* @param array $params
* [id]
*
* @return array
* API Result Array
*/
function civicrm_api3_contact_type_delete($params) {
return _civicrm_api3_basic_delete(_civicrm_api3_get_BAO(__FUNCTION__), $params);
}

View file

@ -0,0 +1,789 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
* This api exposes CiviCRM Contribution records.
*
* @package CiviCRM_APIv3
*/
/**
* Add or update a Contribution.
*
* @param array $params
* Input parameters.
*
* @throws API_Exception
* @return array
* Api result array
*/
function civicrm_api3_contribution_create(&$params) {
$values = array();
_civicrm_api3_custom_format_params($params, $values, 'Contribution');
$params = array_merge($params, $values);
// The BAO should not clean money - it should be done in the form layer & api wrapper
// (although arguably the api should expect pre-cleaned it seems to do some cleaning.)
$params['skipCleanMoney'] = TRUE;
if (CRM_Financial_BAO_FinancialType::isACLFinancialTypeStatus()) {
if (empty($params['id'])) {
$op = CRM_Core_Action::ADD;
}
else {
if (empty($params['financial_type_id'])) {
$params['financial_type_id'] = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $params['id'], 'financial_type_id');
}
$op = CRM_Core_Action::UPDATE;
}
CRM_Financial_BAO_FinancialType::getAvailableFinancialTypes($types, $op);
if (!in_array($params['financial_type_id'], array_keys($types))) {
return civicrm_api3_create_error('You do not have permission to create this contribution');
}
}
if (!empty($params['id']) && !empty($params['contribution_status_id'])) {
$error = array();
//throw error for invalid status change such as setting completed back to pending
//@todo this sort of validation belongs in the BAO not the API - if it is not an OK
// action it needs to be blocked there. If it is Ok through a form it needs to be OK through the api
CRM_Contribute_BAO_Contribution::checkStatusValidation(NULL, $params, $error);
if (array_key_exists('contribution_status_id', $error)) {
throw new API_Exception($error['contribution_status_id']);
}
}
if (!empty($params['id']) && !empty($params['financial_type_id'])) {
$error = array();
CRM_Contribute_BAO_Contribution::checkFinancialTypeChange($params['financial_type_id'], $params['id'], $error);
if (array_key_exists('financial_type_id', $error)) {
throw new API_Exception($error['financial_type_id']);
}
}
_civicrm_api3_contribution_create_legacy_support_45($params);
return _civicrm_api3_basic_create(_civicrm_api3_get_BAO(__FUNCTION__), $params, 'Contribution');
}
/**
* Adjust Metadata for Create action.
*
* The metadata is used for setting defaults, documentation & validation.
*
* @param array $params
* Array of parameters determined by getfields.
*/
function _civicrm_api3_contribution_create_spec(&$params) {
$params['contact_id']['api.required'] = 1;
$params['total_amount']['api.required'] = 1;
$params['payment_instrument_id']['api.aliases'] = array('payment_instrument');
$params['receive_date']['api.default'] = 'now';
$params['payment_processor'] = array(
'name' => 'payment_processor',
'title' => 'Payment Processor ID',
'description' => 'ID of payment processor used for this contribution',
// field is called payment processor - not payment processor id but can only be one id so
// it seems likely someone will fix it up one day to be more consistent - lets alias it from the start
'api.aliases' => array('payment_processor_id'),
'type' => CRM_Utils_Type::T_INT,
);
$params['financial_type_id']['api.aliases'] = array('contribution_type_id', 'contribution_type');
$params['financial_type_id']['api.required'] = 1;
$params['note'] = array(
'name' => 'note',
'uniqueName' => 'contribution_note',
'title' => 'note',
'type' => 2,
'description' => 'Associated Note in the notes table',
);
$params['soft_credit_to'] = array(
'name' => 'soft_credit_to',
'title' => 'Soft Credit contact ID (legacy)',
'type' => CRM_Utils_Type::T_INT,
'description' => 'ID of Contact to be Soft credited to (deprecated - use contribution_soft api)',
'FKClassName' => 'CRM_Contact_DAO_Contact',
);
$params['honor_contact_id'] = array(
'name' => 'honor_contact_id',
'title' => 'Honoree contact ID (legacy)',
'type' => CRM_Utils_Type::T_INT,
'description' => 'ID of honoree contact (deprecated - use contribution_soft api)',
'FKClassName' => 'CRM_Contact_DAO_Contact',
);
$params['honor_type_id'] = array(
'name' => 'honor_type_id',
'title' => 'Honoree Type (legacy)',
'type' => CRM_Utils_Type::T_INT,
'description' => 'Type of honoree contact (deprecated - use contribution_soft api)',
'pseudoconstant' => TRUE,
);
// note this is a recommended option but not adding as a default to avoid
// creating unnecessary changes for the dev
$params['skipRecentView'] = array(
'name' => 'skipRecentView',
'title' => 'Skip adding to recent view',
'type' => CRM_Utils_Type::T_BOOLEAN,
'description' => 'Do not add to recent view (setting this improves performance)',
);
$params['skipLineItem'] = array(
'name' => 'skipLineItem',
'title' => 'Skip adding line items',
'type' => CRM_Utils_Type::T_BOOLEAN,
'api.default' => 0,
'description' => 'Do not add line items by default (if you wish to add your own)',
);
$params['batch_id'] = array(
'title' => 'Batch',
'type' => CRM_Utils_Type::T_INT,
'description' => 'Batch which relevant transactions should be added to',
);
$params['refund_trxn_id'] = array(
'title' => 'Refund Transaction ID',
'type' => CRM_Utils_Type::T_STRING,
'description' => 'Transaction ID specific to the refund taking place',
);
$params['card_type_id'] = array(
'title' => 'Card Type ID',
'description' => 'Providing Credit Card Type ID',
'type' => CRM_Utils_Type::T_INT,
'pseudoconstant' => array(
'optionGroupName' => 'accept_creditcard',
),
);
}
/**
* Support for schema changes made in 4.5.
*
* The main purpose of the API is to provide integrators a level of stability not provided by
* the core code or schema - this means we have to provide support for api calls (where possible)
* across schema changes.
*
* @param array $params
*/
function _civicrm_api3_contribution_create_legacy_support_45(&$params) {
//legacy soft credit handling - recommended approach is chaining
if (!empty($params['soft_credit_to'])) {
$params['soft_credit'][] = array(
'contact_id' => $params['soft_credit_to'],
'amount' => $params['total_amount'],
'soft_credit_type_id' => CRM_Core_OptionGroup::getDefaultValue("soft_credit_type"),
);
}
if (!empty($params['honor_contact_id'])) {
$params['soft_credit'][] = array(
'contact_id' => $params['honor_contact_id'],
'amount' => $params['total_amount'],
'soft_credit_type_id' => CRM_Utils_Array::value('honor_type_id', $params, CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_ContributionSoft', 'soft_credit_type_id', 'in_honor_of')),
);
}
}
/**
* Delete a Contribution.
*
* @param array $params
* Input parameters.
*
* @return array
*/
function civicrm_api3_contribution_delete($params) {
$contributionID = !empty($params['contribution_id']) ? $params['contribution_id'] : $params['id'];
// First check contribution financial type
$financialType = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionID, 'financial_type_id');
// Now check permissioned lineitems & permissioned contribution
if (CRM_Financial_BAO_FinancialType::isACLFinancialTypeStatus()
&& !CRM_Core_Permission::check('delete contributions of type ' . CRM_Contribute_PseudoConstant::financialType($financialType)) ||
!CRM_Financial_BAO_FinancialType::checkPermissionedLineItems($contributionID, 'delete', FALSE)
) {
return civicrm_api3_create_error('You do not have permission to delete this contribution');
}
if (CRM_Contribute_BAO_Contribution::deleteContribution($contributionID)) {
return civicrm_api3_create_success(array($contributionID => 1));
}
else {
return civicrm_api3_create_error('Could not delete contribution');
}
}
/**
* Modify metadata for delete action.
*
* Legacy support for contribution_id.
*
* @param array $params
*/
function _civicrm_api3_contribution_delete_spec(&$params) {
$params['id']['api.aliases'] = array('contribution_id');
}
/**
* Retrieve a set of contributions.
*
* @param array $params
* Input parameters.
*
* @return array
* Array of contributions, if error an array with an error id and error message
*/
function civicrm_api3_contribution_get($params) {
$mode = CRM_Contact_BAO_Query::MODE_CONTRIBUTE;
$additionalOptions = _civicrm_api3_contribution_get_support_nonunique_returns($params);
$returnProperties = CRM_Contribute_BAO_Query::defaultReturnProperties($mode);
$contributions = _civicrm_api3_get_using_query_object('Contribution', $params, $additionalOptions, NULL, $mode, $returnProperties);
foreach ($contributions as $id => $contribution) {
$softContribution = CRM_Contribute_BAO_ContributionSoft::getSoftContribution($id, TRUE);
$contributions[$id] = array_merge($contribution, $softContribution);
// format soft credit for backward compatibility
_civicrm_api3_format_soft_credit($contributions[$id]);
_civicrm_api3_contribution_add_supported_fields($contributions[$id]);
}
return civicrm_api3_create_success($contributions, $params, 'Contribution', 'get');
}
/**
* Fix the return values to reflect cases where the schema has been changed.
*
* At the query object level using uniquenames dismbiguates between tables.
*
* However, adding uniquename can change inputs accepted by the api, so we need
* to ensure we are asking for the unique name return fields.
*
* @param array $params
*
* @return array
* @throws \API_Exception
*/
function _civicrm_api3_contribution_get_support_nonunique_returns($params) {
$additionalOptions = array();
$options = _civicrm_api3_get_options_from_params($params, TRUE);
foreach (array('check_number', 'address_id') as $changedVariable) {
if (isset($options['return']) && !empty($options['return'][$changedVariable])) {
$additionalOptions['return']['contribution_' . $changedVariable] = 1;
}
}
return $additionalOptions;
}
/**
* Support for supported output variables.
*
* @param $contribution
*/
function _civicrm_api3_contribution_add_supported_fields(&$contribution) {
// These are output fields that are supported in our test contract.
// Arguably we should also do the same with 'campaign_id' &
// 'source' - which are also fields being rendered with unique names.
// That seems more consistent with other api where we output the actual field names.
$outputAliases = array(
'contribution_check_number' => 'check_number',
'contribution_address_id' => 'address_id',
'payment_instrument_id' => 'instrument_id',
);
foreach ($outputAliases as $returnName => $copyTo) {
if (array_key_exists($returnName, $contribution)) {
$contribution[$copyTo] = $contribution[$returnName];
}
}
}
/**
* Get number of contacts matching the supplied criteria.
*
* @param array $params
*
* @return int
*/
function civicrm_api3_contribution_getcount($params) {
$count = _civicrm_api3_get_using_query_object('Contribution', $params, array(), TRUE, CRM_Contact_BAO_Query::MODE_CONTRIBUTE);
return (int) $count;
}
/**
* This function is used to format the soft credit for backward compatibility.
*
* As of v4.4 we support multiple soft credit, so now contribution returns array with 'soft_credit' as key
* but we still return first soft credit as a part of contribution array
*
* @param $contribution
*/
function _civicrm_api3_format_soft_credit(&$contribution) {
if (!empty($contribution['soft_credit'])) {
$contribution['soft_credit_to'] = $contribution['soft_credit'][1]['contact_id'];
$contribution['soft_credit_id'] = $contribution['soft_credit'][1]['soft_credit_id'];
}
}
/**
* Adjust Metadata for Get action.
*
* The metadata is used for setting defaults, documentation & validation.
*
* @param array $params
* Array of parameters determined by getfields.
*/
function _civicrm_api3_contribution_get_spec(&$params) {
$params['contribution_test'] = array(
'api.default' => 0,
'type' => CRM_Utils_Type::T_BOOLEAN,
'title' => 'Get Test Contributions?',
'api.aliases' => array('is_test'),
);
$params['financial_type_id']['api.aliases'] = array('contribution_type_id');
$params['payment_instrument_id']['api.aliases'] = array('contribution_payment_instrument', 'payment_instrument');
$params['contact_id'] = CRM_Utils_Array::value('contribution_contact_id', $params);
$params['contact_id']['api.aliases'] = array('contribution_contact_id');
unset($params['contribution_contact_id']);
}
/**
* Legacy handling for contribution parameters.
*
* Take the input parameter list as specified in the data model and
* convert it into the same format that we use in QF and BAO object.
*
* @param array $params
* property name/value pairs to insert in new contact.
* @param array $values
* The reformatted properties that we can use internally.
*
* @return array
*/
function _civicrm_api3_contribute_format_params($params, &$values) {
//legacy way of formatting from v2 api - v3 way is to define metadata & do it in the api layer
_civicrm_api3_filter_fields_for_bao('Contribution', $params, $values);
return array();
}
/**
* Adjust Metadata for Transact action.
*
* The metadata is used for setting defaults, documentation & validation.
*
* @param array $params
* Array of parameters determined by getfields.
*/
function _civicrm_api3_contribution_transact_spec(&$params) {
$fields = civicrm_api3('Contribution', 'getfields', array('action' => 'create'));
$params = array_merge($params, $fields['values']);
$params['receive_date']['api.default'] = 'now';
}
/**
* Process a transaction and record it against the contact.
*
* @param array $params
* Input parameters.
*
* @return array
* contribution of created or updated record (or a civicrm error)
*/
function civicrm_api3_contribution_transact($params) {
// Set some params specific to payment processing
// @todo - fix this function - none of the results checked by civicrm_error would ever be an array with
// 'is_error' set
// also trxn_id is not saved.
// but since there is no test it's not desirable to jump in & make the obvious changes.
$params['payment_processor_mode'] = empty($params['is_test']) ? 'live' : 'test';
$params['amount'] = $params['total_amount'];
if (!isset($params['net_amount'])) {
$params['net_amount'] = $params['amount'];
}
if (!isset($params['invoiceID']) && isset($params['invoice_id'])) {
$params['invoiceID'] = $params['invoice_id'];
}
// Some payment processors expect a unique invoice_id - generate one if not supplied
$params['invoice_id'] = CRM_Utils_Array::value('invoice_id', $params, md5(uniqid(rand(), TRUE)));
$paymentProcessor = CRM_Financial_BAO_PaymentProcessor::getPayment($params['payment_processor'], $params['payment_processor_mode']);
$paymentProcessor['object']->doPayment($params);
$params['payment_instrument_id'] = CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_PaymentProcessorType', $paymentProcessor['payment_processor_type_id'], 'payment_type') == 1 ? 'Credit Card' : 'Debit Card';
return civicrm_api('Contribution', 'create', $params);
}
/**
* Send a contribution confirmation (receipt or invoice).
*
* The appropriate online template will be used (the existence of related objects
* (e.g. memberships ) will affect this selection
*
* @param array $params
* Input parameters.
*
* @throws Exception
*/
function civicrm_api3_contribution_sendconfirmation($params) {
$ids = $values = array();
$allowedParams = array(
'receipt_from_email',
'receipt_from_name',
'receipt_update',
'cc_receipt',
'bcc_receipt',
'receipt_text',
'payment_processor_id',
);
$input = array_intersect_key($params, array_flip($allowedParams));
$input['is_email_receipt'] = TRUE;
CRM_Contribute_BAO_Contribution::sendMail($input, $ids, $params['id'], $values);
}
/**
* Adjust Metadata for sendconfirmation action.
*
* The metadata is used for setting defaults, documentation & validation.
*
* @param array $params
* Array of parameters determined by getfields.
*/
function _civicrm_api3_contribution_sendconfirmation_spec(&$params) {
$params['id'] = array(
'api.required' => 1,
'title' => ts('Contribution ID'),
'type' => CRM_Utils_Type::T_INT,
);
$params['receipt_from_email'] = array(
'title' => ts('From Email address (string)'),
'type' => CRM_Utils_Type::T_STRING,
);
$params['receipt_from_name'] = array(
'title' => ts('From Name (string)'),
'type' => CRM_Utils_Type::T_STRING,
);
$params['cc_receipt'] = array(
'title' => ts('CC Email address (string)'),
'type' => CRM_Utils_Type::T_STRING,
);
$params['bcc_receipt'] = array(
'title' => ts('BCC Email address (string)'),
'type' => CRM_Utils_Type::T_STRING,
);
$params['receipt_text'] = array(
'title' => ts('Message (string)'),
'type' => CRM_Utils_Type::T_STRING,
);
$params['receipt_update'] = array(
'title' => ts('Update the Receipt Date'),
'type' => CRM_Utils_Type::T_BOOLEAN,
'api.default' => TRUE,
);
$params['payment_processor_id'] = array(
'title' => ts('Payment processor Id (avoids mis-guesses)'),
'type' => CRM_Utils_Type::T_INT,
);
}
/**
* Complete an existing (pending) transaction.
*
* This will update related entities (participant, membership, pledge etc)
* and take any complete actions from the contribution page (e.g. send receipt).
*
* @todo - most of this should live in the BAO layer but as we want it to be an addition
* to 4.3 which is already stable we should add it to the api layer & re-factor into the BAO layer later
*
* @param array $params
* Input parameters.
*
* @return array
* API result array
* @throws \API_Exception
* @throws \CRM_Core_Exception
* @throws \Exception
*/
function civicrm_api3_contribution_completetransaction(&$params) {
$input = $ids = array();
if (isset($params['payment_processor_id'])) {
$input['payment_processor_id'] = $params['payment_processor_id'];
}
$contribution = new CRM_Contribute_BAO_Contribution();
$contribution->id = $params['id'];
if (!$contribution->find(TRUE)) {
throw new API_Exception('A valid contribution ID is required', 'invalid_data');
}
if (!$contribution->loadRelatedObjects($input, $ids, TRUE)) {
throw new API_Exception('failed to load related objects');
}
elseif ($contribution->contribution_status_id == CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed')) {
throw new API_Exception(ts('Contribution already completed'), 'contribution_completed');
}
$input['trxn_id'] = !empty($params['trxn_id']) ? $params['trxn_id'] : $contribution->trxn_id;
if (!empty($params['fee_amount'])) {
$input['fee_amount'] = $params['fee_amount'];
}
return _ipn_process_transaction($params, $contribution, $input, $ids);
}
/**
* Provide function metadata.
*
* @param array $params
*/
function _civicrm_api3_contribution_completetransaction_spec(&$params) {
$params['id'] = array(
'title' => 'Contribution ID',
'type' => CRM_Utils_Type::T_INT,
'api.required' => TRUE,
);
$params['trxn_id'] = array(
'title' => 'Transaction ID',
'type' => CRM_Utils_Type::T_STRING,
);
$params['is_email_receipt'] = array(
'title' => 'Send email Receipt?',
'type' => CRM_Utils_Type::T_BOOLEAN,
);
$params['receipt_from_email'] = array(
'title' => 'Email to send receipt from.',
'description' => 'If not provided this will default to being based on domain mail or contribution page',
'type' => CRM_Utils_Type::T_EMAIL,
);
$params['receipt_from_name'] = array(
'title' => 'Name to send receipt from',
'description' => '. If not provided this will default to domain mail or contribution page',
'type' => CRM_Utils_Type::T_STRING,
);
$params['payment_processor_id'] = array(
'title' => 'Payment processor ID',
'description' => 'Providing this is strongly recommended, as not possible to calculate it accurately always',
'type' => CRM_Utils_Type::T_INT,
);
$params['fee_amount'] = array(
'title' => 'Fee charged on transaction',
'description' => 'If a fee has been charged then the amount',
'type' => CRM_Utils_Type::T_FLOAT,
);
$params['trxn_date'] = array(
'title' => 'Transaction Date',
'description' => 'Date this transaction occurred',
'type' => CRM_Utils_Type::T_DATE + CRM_Utils_Type::T_TIME,
);
$params['card_type_id'] = array(
'title' => 'Card Type ID',
'description' => 'Providing Credit Card Type ID',
'type' => CRM_Utils_Type::T_INT,
'pseudoconstant' => array(
'optionGroupName' => 'accept_creditcard',
),
);
}
/**
* Complete an existing (pending) transaction.
*
* This will update related entities (participant, membership, pledge etc)
* and take any complete actions from the contribution page (e.g. send receipt).
*
* @todo - most of this should live in the BAO layer but as we want it to be an addition
* to 4.3 which is already stable we should add it to the api layer & re-factor into the BAO layer later
*
* @param array $params
* Input parameters.
*
* @return array
* Api result array.
* @throws API_Exception
*/
function civicrm_api3_contribution_repeattransaction(&$params) {
$input = $ids = array();
civicrm_api3_verify_one_mandatory($params, NULL, array('contribution_recur_id', 'original_contribution_id'));
if (empty($params['original_contribution_id'])) {
// CRM-19873 call with test mode.
$params['original_contribution_id'] = civicrm_api3('contribution', 'getvalue', array(
'return' => 'id',
'contribution_status_id' => array('IN' => array('Completed')),
'contribution_recur_id' => $params['contribution_recur_id'],
'contribution_test' => CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_ContributionRecur', $params['contribution_recur_id'], 'is_test'),
'options' => array('limit' => 1, 'sort' => 'id DESC'),
));
}
$contribution = new CRM_Contribute_BAO_Contribution();
$contribution->id = $params['original_contribution_id'];
if (!$contribution->find(TRUE)) {
throw new API_Exception(
'A valid original contribution ID is required', 'invalid_data');
}
$original_contribution = clone $contribution;
$input['payment_processor_id'] = civicrm_api3('contributionRecur', 'getvalue', array(
'return' => 'payment_processor_id',
'id' => $contribution->contribution_recur_id,
));
try {
if (!$contribution->loadRelatedObjects($input, $ids, TRUE)) {
throw new API_Exception('failed to load related objects');
}
unset($contribution->id, $contribution->receive_date, $contribution->invoice_id);
$contribution->receive_date = $params['receive_date'];
$passThroughParams = array(
'trxn_id',
'total_amount',
'campaign_id',
'fee_amount',
'financial_type_id',
'contribution_status_id',
);
$input = array_intersect_key($params, array_fill_keys($passThroughParams, NULL));
return _ipn_process_transaction($params, $contribution, $input, $ids, $original_contribution);
}
catch(Exception $e) {
throw new API_Exception('failed to load related objects' . $e->getMessage() . "\n" . $e->getTraceAsString());
}
}
/**
* Calls IPN complete transaction for completing or repeating a transaction.
*
* The IPN function is overloaded with two purposes - this is simply a wrapper for that
* when separating them in the api layer.
*
* @param array $params
* @param CRM_Contribute_BAO_Contribution $contribution
* @param array $input
*
* @param array $ids
*
* @param CRM_Contribute_BAO_Contribution $firstContribution
*
* @return mixed
*/
function _ipn_process_transaction(&$params, $contribution, $input, $ids, $firstContribution = NULL) {
$objects = $contribution->_relatedObjects;
$objects['contribution'] = &$contribution;
if ($firstContribution) {
$objects['first_contribution'] = $firstContribution;
}
$input['component'] = $contribution->_component;
$input['is_test'] = $contribution->is_test;
$input['amount'] = empty($input['total_amount']) ? $contribution->total_amount : $input['total_amount'];
if (isset($params['is_email_receipt'])) {
$input['is_email_receipt'] = $params['is_email_receipt'];
}
if (!empty($params['trxn_date'])) {
$input['trxn_date'] = $params['trxn_date'];
}
if (!empty($params['receive_date'])) {
$input['receive_date'] = $params['receive_date'];
}
if (empty($contribution->contribution_page_id)) {
static $domainFromName;
static $domainFromEmail;
if (empty($domainFromEmail) && (empty($params['receipt_from_name']) || empty($params['receipt_from_email']))) {
list($domainFromName, $domainFromEmail) = CRM_Core_BAO_Domain::getNameAndEmail(TRUE);
}
$input['receipt_from_name'] = CRM_Utils_Array::value('receipt_from_name', $params, $domainFromName);
$input['receipt_from_email'] = CRM_Utils_Array::value('receipt_from_email', $params, $domainFromEmail);
}
$input['card_type_id'] = CRM_Utils_Array::value('card_type_id', $params);
$input['pan_truncation'] = CRM_Utils_Array::value('pan_truncation', $params);
$transaction = new CRM_Core_Transaction();
return CRM_Contribute_BAO_Contribution::completeOrder($input, $ids, $objects, $transaction, !empty
($contribution->contribution_recur_id), $contribution);
}
/**
* Provide function metadata.
*
* @param array $params
*/
function _civicrm_api3_contribution_repeattransaction_spec(&$params) {
$params['original_contribution_id'] = array(
'title' => 'Original Contribution ID',
'description' => 'Contribution ID to copy (will be calculated from recurring contribution if not provided)',
'type' => CRM_Utils_Type::T_INT,
);
$params['contribution_recur_id'] = array(
'title' => 'Recurring contribution ID',
'type' => CRM_Utils_Type::T_INT,
);
$params['trxn_id'] = array(
'title' => 'Transaction ID',
'type' => CRM_Utils_Type::T_STRING,
);
$params['is_email_receipt'] = array(
'title' => 'Send email Receipt?',
'type' => CRM_Utils_Type::T_BOOLEAN,
);
$params['contribution_status_id'] = array(
'title' => 'Contribution Status ID',
'name' => 'contribution_status_id',
'type' => CRM_Utils_Type::T_INT,
'pseudoconstant' => array(
'optionGroupName' => 'contribution_status',
),
'api.required' => TRUE,
);
$params['receive_date'] = array(
'title' => 'Contribution Receive Date',
'name' => 'receive_date',
'type' => CRM_Utils_Type::T_DATE + CRM_Utils_Type::T_TIME,
'api.default' => 'now',
);
$params['trxn_id'] = array(
'title' => 'Transaction ID',
'name' => 'trxn_id',
'type' => CRM_Utils_Type::T_STRING,
);
$params['campaign_id'] = array(
'title' => 'Campaign ID',
'name' => 'campaign_id',
'type' => CRM_Utils_Type::T_INT,
'pseudoconstant' => array(
'table' => 'civicrm_campaign',
'keyColumn' => 'id',
'labelColumn' => 'title',
),
);
$params['financial_type_id'] = array(
'title' => 'Financial ID (ignored if more than one line item)',
'name' => 'financial_type_id',
'type' => CRM_Utils_Type::T_INT,
'pseudoconstant' => array(
'table' => 'civicrm_financial_type',
'keyColumn' => 'id',
'labelColumn' => 'name',
),
);
$params['payment_processor_id'] = array(
'description' => ts('Payment processor ID, will be loaded from contribution_recur if not provided'),
'title' => 'Payment processor ID',
'name' => 'payment_processor_id',
'type' => CRM_Utils_Type::T_INT,
);
}

View file

@ -0,0 +1,126 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
* This api exposes CiviCRM contribution pages.
*
* @package CiviCRM_APIv3
*/
/**
* Create or update a ContributionPage.
*
* @param array $params
* Array per getfields metadata.
*
* @return array
* api result array
*/
function civicrm_api3_contribution_page_create($params) {
$result = _civicrm_api3_basic_create(_civicrm_api3_get_BAO(__FUNCTION__), $params);
CRM_Contribute_PseudoConstant::flush('contributionPageAll');
CRM_Contribute_PseudoConstant::flush('contributionPageActive');
return $result;
}
/**
* Adjust Metadata for Create action.
*
* The metadata is used for setting defaults, documentation & validation.
*
* @param array $params
* Array per getfields metadata.
*/
function _civicrm_api3_contribution_page_create_spec(&$params) {
$params['financial_type_id']['api.required'] = 1;
$params['payment_processor']['api.aliases'] = array('payment_processor_id');
$params['is_active']['api.default'] = 1;
}
/**
* Returns array of ContributionPage(s) matching a set of one or more group properties.
*
* @param array $params
* Array per getfields metadata.
*
* @return array
* API Result array Array of matching contribution_pages
*/
function civicrm_api3_contribution_page_get($params) {
return _civicrm_api3_basic_get(_civicrm_api3_get_BAO(__FUNCTION__), $params);
}
/**
* Delete an existing ContributionPage.
*
* This method is used to delete any existing ContributionPage given its id.
*
* @param array $params
* Array per getfields metadata.
*
* @return array
* API result Array
*/
function civicrm_api3_contribution_page_delete($params) {
return _civicrm_api3_basic_delete(_civicrm_api3_get_BAO(__FUNCTION__), $params);
}
/**
* Submit a ContributionPage.
*
* @param array $params
* Array per getfields metadata.
*
* @return array
* API result array
*/
function civicrm_api3_contribution_page_submit($params) {
$result = CRM_Contribute_Form_Contribution_Confirm::submit($params);
return civicrm_api3_create_success($result, $params, 'ContributionPage', 'submit');
}
/**
* Set default getlist parameters.
*
* @see _civicrm_api3_generic_getlist_defaults
*
* @param array $request
*
* @return array
*/
function _civicrm_api3_contribution_page_getlist_defaults(&$request) {
return array(
'description_field' => array(
'intro_text',
),
'params' => array(
'is_active' => 1,
),
);
}

View file

@ -0,0 +1,72 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
* This api exposes CiviCRM premium products attached to contributions.
*
* Premiums are used as incentive gifts on contribution pages.
* Use chaining to create a premium and related products in one api call.
*
* @package CiviCRM_APIv3
*/
/**
* Save a contribution product.
*
* @param array $params
*
* @throws API_Exception
* @return array
*/
function civicrm_api3_contribution_product_create($params) {
return _civicrm_api3_basic_create(_civicrm_api3_get_BAO(__FUNCTION__), $params);
}
/**
* Get a contribution product.
*
* @param array $params
*
* @return array
* Array of retrieved product property values.
*/
function civicrm_api3_contribution_product_get($params) {
return _civicrm_api3_basic_get(_civicrm_api3_get_BAO(__FUNCTION__), $params);
}
/**
* Delete a contribution product.
*
* @param array $params
*
* @throws API_Exception
* @return array
* Array of deleted values.
*/
function civicrm_api3_contribution_product_delete($params) {
return _civicrm_api3_basic_delete(_civicrm_api3_get_BAO(__FUNCTION__), $params);
}

View file

@ -0,0 +1,105 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
* This api exposes CiviCRM recurring contributions.
*
* @package CiviCRM_APIv3
*/
/**
* Create or update a ContributionRecur.
*
* @param array $params
* Array per getfields metadata.
*
* @return array
* api result array
*/
function civicrm_api3_contribution_recur_create($params) {
_civicrm_api3_custom_format_params($params, $values, 'ContributionRecur');
$params = array_merge($params, $values);
return _civicrm_api3_basic_create(_civicrm_api3_get_BAO(__FUNCTION__), $params);
}
/**
* Adjust Metadata for Create action.
*
* The metadata is used for setting defaults, documentation & validation.
*
* @param array $params
* Array of parameters determined by getfields.
*/
function _civicrm_api3_contribution_recur_create_spec(&$params) {
$params['contact_id']['api.required'] = 1;
$params['create_date']['api.default'] = 'now';
$params['frequency_interval']['api.required'] = 1;
$params['start_date']['api.default'] = 'now';
$params['modified_date']['api.default'] = 'now';
}
/**
* Returns array of contribution_recurs matching a set of one or more group properties.
*
* @param array $params
* Array of properties. If empty, all records will be returned.
*
* @return array
* API result Array of matching contribution_recurs
*/
function civicrm_api3_contribution_recur_get($params) {
return _civicrm_api3_basic_get(_civicrm_api3_get_BAO(__FUNCTION__), $params);
}
/**
* Cancel a recurring contribution of existing ContributionRecur given its id.
*
* @param array $params
* Array containing id of the recurring contribution.
*
* @return bool
* returns true is successfully cancelled
*/
function civicrm_api3_contribution_recur_cancel($params) {
civicrm_api3_verify_one_mandatory($params, NULL, array('id'));
return CRM_Contribute_BAO_ContributionRecur::cancelRecurContribution($params['id'], CRM_Core_DAO::$_nullObject) ? civicrm_api3_create_success() : civicrm_api3_create_error(ts('Error while cancelling recurring contribution'));
}
/**
* Delete an existing ContributionRecur.
*
* This method is used to delete an existing ContributionRecur given its id.
*
* @param array $params
* [id]
*
* @return array
* API result array
*/
function civicrm_api3_contribution_recur_delete($params) {
return _civicrm_api3_basic_delete(_civicrm_api3_get_BAO(__FUNCTION__), $params);
}

View file

@ -0,0 +1,86 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
* This api exposes CiviCRM soft credits.
*
* @package CiviCRM_APIv3
*/
/**
* Create or Update a Soft Credit.
*
* @param array $params
* Array per getfields metadata.
*
* @return array
* API result array
*/
function civicrm_api3_contribution_soft_create($params) {
return _civicrm_api3_basic_create(_civicrm_api3_get_BAO(__FUNCTION__), $params);
}
/**
* Adjust Metadata for Create action.
*
* The metadata is used for setting defaults, documentation & validation.
*
* @param array $params
* Array of parameters determined by getfields.
*/
function _civicrm_api3_contribution_soft_create_spec(&$params) {
$params['contribution_id']['api.required'] = 1;
$params['contact_id']['api.required'] = 1;
$params['amount']['api.required'] = 1;
}
/**
* Deletes an existing Soft Credit.
*
* @param array $params
*
* @return array
* Api formatted result.
*
* @throws API_Exception
*/
function civicrm_api3_contribution_soft_delete($params) {
return _civicrm_api3_basic_delete(_civicrm_api3_get_BAO(__FUNCTION__), $params);
}
/**
* Retrieve one or more Soft Credits.
*
* @param array $params
* Array per getfields metadata.
*
* @return array
* API result
*/
function civicrm_api3_contribution_soft_get($params) {
return _civicrm_api3_basic_get(_civicrm_api3_get_BAO(__FUNCTION__), $params);
}

View file

@ -0,0 +1,83 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
* This api exposes CiviCRM country.
*
* @package CiviCRM_APIv3
*/
/**
* Add an Country for a contact.
*
* @param array $params
* Array per getfields metadata.
*
* @return array
* API result array
* @throws \API_Exception
*/
function civicrm_api3_country_create($params) {
return _civicrm_api3_basic_create(_civicrm_api3_get_DAO(__FUNCTION__), $params);
}
/**
* Adjust Metadata for Create action.
*
* The metadata is used for setting defaults, documentation & validation.
*
* @param array $params
* Array of parameters determined by getfields.
*/
function _civicrm_api3_country_create_spec(&$params) {
$params['name']['api.required'] = 1;
}
/**
* Deletes an existing Country.
*
* @param array $params
*
* @return array
*/
function civicrm_api3_country_delete($params) {
return _civicrm_api3_basic_delete(_civicrm_api3_get_DAO(__FUNCTION__), $params);
}
/**
* Retrieve one or more countryies.
*
* @param array $params
* Array per getfields metadata.
*
* @return array
* api result array
*/
function civicrm_api3_country_get($params) {
return _civicrm_api3_basic_get(_civicrm_api3_get_DAO(__FUNCTION__), $params);
}

View file

@ -0,0 +1,278 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
* This api exposes CiviCRM custom field.
*
* @package CiviCRM_APIv3
*/
/**
* Create a 'custom field' within a custom field group.
*
* We also empty the static var in the getfields
* function after deletion so that the field is available for us (getfields manages date conversion
* among other things
*
* @param array $params
* Array per getfields metadata.
*
* @return array
* API success array
*/
function civicrm_api3_custom_field_create($params) {
// Array created for passing options in params.
if (isset($params['option_values']) && is_array($params['option_values'])) {
$weight = 0;
foreach ($params['option_values'] as $key => $value) {
// Translate simple key/value pairs into full-blown option values
if (!is_array($value)) {
$value = array(
'label' => $value,
'value' => $key,
'is_active' => 1,
'weight' => $weight,
);
$key = $weight++;
}
$params['option_label'][$key] = $value['label'];
$params['option_value'][$key] = $value['value'];
$params['option_status'][$key] = $value['is_active'];
$params['option_weight'][$key] = $value['weight'];
}
}
$values = array();
$customField = CRM_Core_BAO_CustomField::create($params);
_civicrm_api3_object_to_array_unique_fields($customField, $values[$customField->id]);
_civicrm_api3_custom_field_flush_static_caches();
return civicrm_api3_create_success($values, $params, 'CustomField', $customField);
}
/**
* Flush static caches in functions that might have stored available custom fields.
*/
function _civicrm_api3_custom_field_flush_static_caches() {
civicrm_api('CustomField', 'getfields', array('version' => 3, 'cache_clear' => 1));
CRM_Core_BAO_UFField::getAvailableFieldsFlat(TRUE);
}
/**
* Adjust Metadata for Create action.
*
* @param array $params
* Array of parameters determined by getfields.
*/
function _civicrm_api3_custom_field_create_spec(&$params) {
$params['label']['api.required'] = 1;
$params['custom_group_id']['api.required'] = 1;
$params['is_active']['api.default'] = 1;
$params['option_values'] = array(
'title' => 'Option Values',
'description' => "Pass an array of options (value => label) to create this field's option values",
);
// TODO: Why expose this to the api at all?
$params['option_type'] = array(
'title' => 'Option Type',
'description' => 'This (boolean) field tells the BAO to create an option group for the field if the field type is appropriate',
'api.default' => 1,
'type' => CRM_Utils_Type::T_BOOLEAN,
);
$params['data_type']['api.default'] = 'String';
$params['is_active']['api.default'] = 1;
}
/**
* Use this API to delete an existing custom field.
*
* @param array $params
* Array id of the field to be deleted.
*
* @return array
*/
function civicrm_api3_custom_field_delete($params) {
$field = new CRM_Core_BAO_CustomField();
$field->id = $params['id'];
$field->find(TRUE);
$customFieldDelete = CRM_Core_BAO_CustomField::deleteField($field);
civicrm_api('CustomField', 'getfields', array('version' => 3, 'cache_clear' => 1));
return $customFieldDelete ? civicrm_api3_create_error('Error while deleting custom field') : civicrm_api3_create_success();
}
/**
* Use this API to get existing custom fields.
*
* @param array $params
* Array to search on.
*
* @return array
*/
function civicrm_api3_custom_field_get($params) {
return _civicrm_api3_basic_get(_civicrm_api3_get_BAO(__FUNCTION__), $params);
}
/**
* Helper function to validate custom field value.
*
* @deprecated
*
* @param string $fieldName
* Custom field name (eg: custom_8 ).
* @param mixed $value
* Field value to be validate.
* @param array $fieldDetails
* Field Details.
* @param array $errors
* Collect validation errors.
*
* @return array|NULL
* Validation errors
* @todo remove this function - not in use but need to review functionality before
* removing as it might be useful in wrapper layer
*/
function _civicrm_api3_custom_field_validate_field($fieldName, $value, $fieldDetails, &$errors = array()) {
return NULL;
//see comment block
if (!$value) {
return $errors;
}
$dataType = $fieldDetails['data_type'];
$htmlType = $fieldDetails['html_type'];
switch ($dataType) {
case 'Int':
if (!CRM_Utils_Rule::integer($value)) {
$errors[$fieldName] = 'Invalid integer value for ' . $fieldName;
}
break;
case 'Float':
if (!CRM_Utils_Rule::numeric($value)) {
$errors[$fieldName] = 'Invalid numeric value for ' . $fieldName;
}
break;
case 'Money':
if (!CRM_Utils_Rule::money($value)) {
$errors[$fieldName] = 'Invalid numeric value for ' . $fieldName;
}
break;
case 'Link':
if (!CRM_Utils_Rule::url($value)) {
$errors[$fieldName] = 'Invalid link for ' . $fieldName;
}
break;
case 'Boolean':
if ($value != '1' && $value != '0') {
$errors[$fieldName] = 'Invalid boolean (use 1 or 0) value for ' . $fieldName;
}
break;
case 'Country':
if (empty($value)) {
break;
}
if ($htmlType != 'Multi-Select Country' && is_array($value)) {
$errors[$fieldName] = 'Invalid country for ' . $fieldName;
break;
}
if (!is_array($value)) {
$value = array($value);
}
$query = "SELECT count(*) FROM civicrm_country WHERE id IN (" . implode(',', $value) . ")";
if (CRM_Core_DAO::singleValueQuery($query) < count($value)) {
$errors[$fieldName] = 'Invalid country(s) for ' . $fieldName;
}
break;
case 'StateProvince':
if (empty($value)) {
break;
}
if ($htmlType != 'Multi-Select State/Province' && is_array($value)) {
$errors[$fieldName] = 'Invalid State/Province for ' . $fieldName;
break;
}
if (!is_array($value)) {
$value = array($value);
}
$query = "
SELECT count(*)
FROM civicrm_state_province
WHERE id IN ('" . implode("','", $value) . "')";
if (CRM_Core_DAO::singleValueQuery($query) < count($value)) {
$errors[$fieldName] = 'Invalid State/Province for ' . $fieldName;
}
break;
case 'ContactReference':
//FIX ME
break;
}
if (in_array($htmlType, array(
'Select', 'Multi-Select', 'CheckBox', 'Radio', 'AdvMulti-Select')) &&
!isset($errors[$fieldName])
) {
$options = CRM_Core_OptionGroup::valuesByID($fieldDetails['option_group_id']);
if (!is_array($value)) {
$value = array($value);
}
$invalidOptions = array_diff($value, array_keys($options));
if (!empty($invalidOptions)) {
$errors[$fieldName] = "Invalid option(s) for field '{$fieldName}': " . implode(',', $invalidOptions);
}
}
return $errors;
}
/**
* CRM-15191 - Hack to ensure the cache gets cleared after updating a custom field.
*
* @param array $params
* Array per getfields metadata.
*
* @return array
*/
function civicrm_api3_custom_field_setvalue($params) {
require_once 'api/v3/Generic/Setvalue.php';
$result = civicrm_api3_generic_setValue(array("entity" => 'CustomField', 'params' => $params));
if (empty($result['is_error'])) {
CRM_Utils_System::flushCache();
}
return $result;
}

View file

@ -0,0 +1,123 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
* This api exposes CiviCRM custom group.
*
* @package CiviCRM_APIv3
*/
/**
* Use this API to create a new group.
*
* The 'extends' value accepts an array or a comma separated string.
* e.g array(
* 'Individual','Contact') or 'Individual,Contact'
* See the CRM Data Model for custom_group property definitions
* $params['class_name'] is a required field, class being extended.
*
* @param array $params
* Array per getfields metadata.
*
* @return array
* @todo $params['extends'] is array format - is that std compatible
*/
function civicrm_api3_custom_group_create($params) {
if (isset($params['extends']) && is_string($params['extends'])) {
$extends = explode(",", $params['extends']);
unset($params['extends']);
$params['extends'] = $extends;
}
if (!isset($params['id']) && (!isset($params['extends'][0]) || !trim($params['extends'][0]))) {
return civicrm_api3_create_error("First item in params['extends'] must be a class name (e.g. 'Contact').");
}
if (isset($params['extends_entity_column_value']) && !is_array($params['extends_entity_column_value'])) {
// BAO fails if this is a string, but API getFields says this must be a string, so we'll do a double backflip
$params['extends_entity_column_value'] = CRM_Utils_Array::explodePadded($params['extends_entity_column_value']);
}
return _civicrm_api3_basic_create(_civicrm_api3_get_BAO(__FUNCTION__), $params);
}
/**
* Adjust Metadata for Create action.
*
* @param array $params
* Array of parameters determined by getfields.
*/
function _civicrm_api3_custom_group_create_spec(&$params) {
$params['extends']['api.required'] = 1;
$params['title']['api.required'] = 1;
$params['style']['api.default'] = 'Inline';
$params['is_active']['api.default'] = 1;
}
/**
* Use this API to delete an existing group.
*
* @param array $params
*
* @return array
*/
function civicrm_api3_custom_group_delete($params) {
$values = new CRM_Core_DAO_CustomGroup();
$values->id = $params['id'];
$values->find(TRUE);
$result = CRM_Core_BAO_CustomGroup::deleteGroup($values, TRUE);
return $result ? civicrm_api3_create_success() : civicrm_api3_create_error('Error while deleting custom group');
}
/**
* API to get existing custom fields.
*
* @param array $params
* Array per getfields metadata.
*
* @return array
*/
function civicrm_api3_custom_group_get($params) {
return _civicrm_api3_basic_get(_civicrm_api3_get_BAO(__FUNCTION__), $params);
}
/**
* CRM-15191 - Hack to ensure the cache gets cleared after updating a custom group.
*
* @param array $params
* Array per getfields metadata.
*
* @return array
*/
function civicrm_api3_custom_group_setvalue($params) {
require_once 'api/v3/Generic/Setvalue.php';
$result = civicrm_api3_generic_setValue(array("entity" => 'CustomGroup', 'params' => $params));
if (empty($result['is_error'])) {
CRM_Utils_System::flushCache();
}
return $result;
}

View file

@ -0,0 +1,98 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
* This api exposes CiviCRM custom search.
*
* @package CiviCRM_APIv3
*/
/**
* Retrieve custom searches.
*
* @param array $params
*
* @return array
* API result array
*/
function civicrm_api3_custom_search_get($params) {
require_once 'api/v3/OptionValue.php';
$params['option_group_id'] = CRM_Core_DAO::getFieldValue(
'CRM_Core_DAO_OptionGroup', 'custom_search', 'id', 'name'
);
return civicrm_api3_option_value_get($params);
}
/**
* Add a CustomSearch.
*
* @param array $params
*
* @return array
* API result array
*/
function civicrm_api3_custom_search_create($params) {
require_once 'api/v3/OptionValue.php';
$params['option_group_id'] = CRM_Core_DAO::getFieldValue(
'CRM_Core_DAO_OptionGroup', 'custom_search', 'id', 'name'
);
// empirically, class name goes to both 'name' and 'label'
if (array_key_exists('name', $params)) {
$params['label'] = $params['name'];
}
return civicrm_api3_option_value_create($params);
}
/**
* Adjust Metadata for Create action.
*
* The metadata is used for setting defaults, documentation & validation.
*
* @param array $params
* Array of parameters determined by getfields.
*/
function _civicrm_api3_custom_search_create_spec(&$params) {
require_once 'api/v3/OptionValue.php';
_civicrm_api3_option_value_create_spec($params);
$params['option_group_id']['api.default'] = CRM_Core_DAO::getFieldValue(
'CRM_Core_DAO_OptionGroup', 'custom_search', 'id', 'name'
);
$params['name']['api.aliases'] = array('class_name');
}
/**
* Deletes an existing CustomSearch.
*
* @param array $params
*
* @return array
* API result array
*/
function civicrm_api3_custom_search_delete($params) {
require_once 'api/v3/OptionValue.php';
return civicrm_api3_option_value_delete($params);
}

View file

@ -0,0 +1,384 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
* This api exposes CiviCRM custom value.
*
* @package CiviCRM_APIv3
*/
/**
* Sets custom values for an entity.
*
* @param array $params
* Expected keys are in format custom_fieldID:recordID or custom_groupName:fieldName:recordID.
*
* @example:
* @code
* // entity ID. You do not need to specify entity type, we figure it out based on the fields you're using
* 'entity_id' => 123,
* // (omitting :id) inserts or updates a field in a single-valued group
* 'custom_6' => 'foo',
* // custom_24 is checkbox or multiselect, so pass items as an array
* 'custom_24' => array('bar', 'baz'),
* // in this case custom_33 is part of a multi-valued group, and we're updating record id 5
* 'custom_33:5' => value,
* // inserts new record in multi-valued group
* 'custom_33:-1' => value,
* // inserts another new record in multi-valued group
* 'custom_33:-2' => value,
* // you can use group_name:field_name instead of ID
* 'custom_some_group:my_field' => 'myinfo',
* // updates record ID 8 in my_other_field in multi-valued some_big_group
* 'custom_some_big_group:my_other_field:8' => 'myinfo',
* @endcode
*
* @throws Exception
* @return array
* ['values' => TRUE] or ['is_error' => 1, 'error_message' => 'what went wrong']
*/
function civicrm_api3_custom_value_create($params) {
// @todo it's not clear where the entity_table is used as CRM_Core_BAO_CustomValueTable::setValues($create)
// didn't seem to use it
// so not clear if it's relevant
if (!empty($params['entity_table']) && substr($params['entity_table'], 0, 7) == 'civicrm') {
$params['entity_table'] = substr($params['entity_table'], 8, 7);
}
$create = array('entityID' => $params['entity_id']);
// Translate names and
//Convert arrays to multi-value strings
$sp = CRM_Core_DAO::VALUE_SEPARATOR;
foreach ($params as $id => $param) {
if (is_array($param)) {
$param = $sp . implode($sp, $param) . $sp;
}
list($c, $id) = CRM_Utils_System::explode('_', $id, 2);
if ($c != 'custom') {
continue;
}
list($i, $n, $x) = CRM_Utils_System::explode(':', $id, 3);
if (is_numeric($i)) {
$key = $i;
$x = $n;
}
else {
// Lookup names if ID was not supplied
$key = CRM_Core_BAO_CustomField::getCustomFieldID($n, $i);
if (!$key) {
continue;
}
}
if ($x && is_numeric($x)) {
$key .= '_' . $x;
}
$create['custom_' . $key] = $param;
}
$result = CRM_Core_BAO_CustomValueTable::setValues($create);
if ($result['is_error']) {
throw new Exception($result['error_message']);
}
return civicrm_api3_create_success(TRUE, $params, 'CustomValue');
}
/**
* Adjust Metadata for Create action.
*
* The metadata is used for setting defaults, documentation & validation.
*
* @param array $params
* Array of parameters determined by getfields.
*/
function _civicrm_api3_custom_value_create_spec(&$params) {
$params['entity_id']['api.required'] = 1;
$params['entity_id']['title'] = 'Entity ID';
}
/**
* Use this API to get existing custom values for an entity.
*
* @param array $params
* Array specifying the entity_id.
* Optionally include entity_type param, i.e. 'entity_type' => 'Activity'
* If no entity_type is supplied, it will be determined based on the fields you request.
* If no entity_type is supplied and no fields are specified, 'Contact' will be assumed.
* Optionally include the desired custom data to be fetched (or else all custom data for this entity will be returned)
* Example: 'entity_id' => 123, 'return.custom_6' => 1, 'return.custom_33' => 1
* If you do not know the ID, you may use group name : field name, for example 'return.foo_stuff:my_field' => 1
*
* @throws API_Exception
* @return array
*/
function civicrm_api3_custom_value_get($params) {
$getParams = array(
'entityID' => $params['entity_id'],
'entityType' => CRM_Utils_Array::value('entity_table', $params, ''),
);
if (strstr($getParams['entityType'], 'civicrm_')) {
$getParams['entityType'] = ucfirst(substr($getParams['entityType'], 8));
}
unset($params['entity_id'], $params['entity_table']);
foreach ($params as $id => $param) {
if ($param && substr($id, 0, 6) == 'return') {
$id = substr($id, 7);
list($c, $i) = CRM_Utils_System::explode('_', $id, 2);
if ($c == 'custom' && is_numeric($i)) {
$names['custom_' . $i] = 'custom_' . $i;
$id = $i;
}
else {
// Lookup names if ID was not supplied
list($group, $field) = CRM_Utils_System::explode(':', $id, 2);
$id = CRM_Core_BAO_CustomField::getCustomFieldID($field, $group);
if (!$id) {
continue;
}
$names['custom_' . $id] = 'custom_' . $i;
}
$getParams['custom_' . $id] = 1;
}
}
$result = CRM_Core_BAO_CustomValueTable::getValues($getParams);
if ($result['is_error']) {
if ($result['error_message'] == "No values found for the specified entity ID and custom field(s).") {
$values = array();
return civicrm_api3_create_success($values, $params, 'CustomValue');
}
else {
throw new API_Exception($result['error_message']);
}
}
else {
$entity_id = $result['entityID'];
unset($result['is_error'], $result['entityID']);
// Convert multi-value strings to arrays
$sp = CRM_Core_DAO::VALUE_SEPARATOR;
foreach ($result as $id => $value) {
if (strpos($value, $sp) !== FALSE) {
$value = explode($sp, trim($value, $sp));
}
$idArray = explode('_', $id);
if ($idArray[0] != 'custom') {
continue;
}
$fieldNumber = $idArray[1];
$customFieldInfo = CRM_Core_BAO_CustomField::getNameFromID($fieldNumber);
$info = array_pop($customFieldInfo);
// id is the index for returned results
if (empty($idArray[2])) {
$n = 0;
$id = $fieldNumber;
}
else {
$n = $idArray[2];
$id = $fieldNumber . "." . $idArray[2];
}
if (!empty($params['format.field_names'])) {
$id = $info['field_name'];
}
else {
$id = $fieldNumber;
}
$values[$id]['entity_id'] = $getParams['entityID'];
if (!empty($getParams['entityType'])) {
$values[$id]['entity_table'] = $getParams['entityType'];
}
//set 'latest' -useful for multi fields but set for single for consistency
$values[$id]['latest'] = $value;
$values[$id]['id'] = $id;
$values[$id][$n] = $value;
}
return civicrm_api3_create_success($values, $params, 'CustomValue');
}
}
/**
* Adjust Metadata for Get action.
*
* The metadata is used for setting defaults, documentation & validation.
*
* @param array $params
* Array of parameters determined by getfields.
*/
function _civicrm_api3_custom_value_get_spec(&$params) {
$params['entity_id']['api.required'] = 1;
$params['entity_id']['title'] = 'Entity ID';
}
/**
* CustomValue.gettree API specification
*
* @param array $spec description of fields supported by this API call
* @return void
*/
function _civicrm_api3_custom_value_gettree_spec(&$spec) {
$spec['entity_id'] = array(
'title' => 'Entity Id',
'description' => 'Id of entity',
'type' => CRM_Utils_Type::T_INT,
'api.required' => 1,
);
$entities = civicrm_api3('Entity', 'get');
$entities = array_diff($entities['values'], $entities['deprecated']);
$spec['entity_type'] = array(
'title' => 'Entity Type',
'description' => 'API name of entity type, e.g. "Contact"',
'type' => CRM_Utils_Type::T_STRING,
'api.required' => 1,
'options' => array_combine($entities, $entities),
);
// Return params for custom group, field & value
foreach (CRM_Core_DAO_CustomGroup::fields() as $field) {
$name = 'custom_group.' . $field['name'];
$spec[$name] = array('name' => $name) + $field;
}
foreach (CRM_Core_DAO_CustomField::fields() as $field) {
$name = 'custom_field.' . $field['name'];
$spec[$name] = array('name' => $name) + $field;
}
$spec['custom_value.id'] = array(
'title' => 'Custom Value Id',
'description' => 'Id of record in custom value table',
'type' => CRM_Utils_Type::T_INT,
);
$spec['custom_value.data'] = array(
'title' => 'Custom Value (Raw)',
'description' => 'Raw value as stored in the database',
'type' => CRM_Utils_Type::T_STRING,
);
$spec['custom_value.display'] = array(
'title' => 'Custom Value (Formatted)',
'description' => 'Custom value formatted for display',
'type' => CRM_Utils_Type::T_STRING,
);
}
/**
* CustomValue.gettree API
*
* @param array $params
* @return array API result
* @throws API_Exception
*/
function civicrm_api3_custom_value_gettree($params) {
$ret = array();
$options = _civicrm_api3_get_options_from_params($params);
$toReturn = array(
'custom_group' => array(),
'custom_field' => array(),
'custom_value' => array(),
);
foreach (array_keys($options['return']) as $r) {
list($type, $field) = explode('.', $r);
if (isset($toReturn[$type])) {
$toReturn[$type][] = $field;
}
}
// We must have a name if not indexing sequentially
if (empty($params['sequential']) && $toReturn['custom_field']) {
$toReturn['custom_field'][] = 'name';
}
switch ($params['entity_type']) {
case 'Contact':
$ret = array('entityType' => 'contact_type', 'subTypes' => 'contact_sub_type');
break;
case 'Activity':
case 'Campaign':
case 'Case':
case 'Contribution':
case 'Event':
case 'Grant':
case 'Membership':
case 'Relationship':
$ret = array('subTypes' => strtolower($params['entity_type']) . '_type_id');
break;
case 'Participant':
// todo
}
$treeParams = array(
'entityType' => $params['entity_type'],
'subTypes' => array(),
'subName' => NULL,
);
// Fetch entity data for custom group type/sub-type
// Also verify access permissions (api3 will throw an exception if permission denied)
if ($ret || !empty($params['check_permissions'])) {
$entityData = civicrm_api3($params['entity_type'], 'getsingle', array(
'id' => $params['entity_id'],
'return' => array_merge(array('id'), array_values($ret)),
));
foreach ($ret as $param => $key) {
if (isset($entityData[$key])) {
$treeParams[$param] = $entityData[$key];
}
}
}
$tree = CRM_Core_BAO_CustomGroup::getTree($treeParams['entityType'], $toReturn, $params['entity_id'], NULL, $treeParams['subTypes'], $treeParams['subName'], TRUE, NULL, FALSE, CRM_Utils_Array::value('check_permissions', $params, TRUE));
unset($tree['info']);
$result = array();
foreach ($tree as $group) {
$result[$group['name']] = array();
$groupToReturn = $toReturn['custom_group'] ? $toReturn['custom_group'] : array_keys($group);
foreach ($groupToReturn as $item) {
$result[$group['name']][$item] = CRM_Utils_Array::value($item, $group);
}
$result[$group['name']]['fields'] = array();
foreach ($group['fields'] as $fieldInfo) {
$field = array('value' => NULL);
$fieldToReturn = $toReturn['custom_field'] ? $toReturn['custom_field'] : array_keys($fieldInfo);
foreach ($fieldToReturn as $item) {
$field[$item] = CRM_Utils_Array::value($item, $fieldInfo);
}
unset($field['customValue']);
if (!empty($fieldInfo['customValue'])) {
$field['value'] = CRM_Utils_Array::first($fieldInfo['customValue']);
if (!$toReturn['custom_value'] || in_array('display', $toReturn['custom_value'])) {
$field['value']['display'] = CRM_Core_BAO_CustomField::displayValue($field['value']['data'], $fieldInfo);
}
foreach (array_keys($field['value']) as $key) {
if ($toReturn['custom_value'] && !in_array($key, $toReturn['custom_value'])) {
unset($field['value'][$key]);
}
}
}
if (empty($params['sequential'])) {
$result[$group['name']]['fields'][$fieldInfo['name']] = $field;
}
else {
$result[$group['name']]['fields'][] = $field;
}
}
}
return civicrm_api3_create_success($result, $params, 'CustomValue', 'gettree');
}

View file

@ -0,0 +1,323 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
* The Cxn API allows a Civi site to initiate a connection to a
* remote application. There are three primary actions:
*
* - register: Establish a new connection.
* - unregister: Destroy an existing connection.
* - get: Get a list of existing connections.
*/
/**
* Adjust metadata for "register" action.
*
* @param array $spec
* List of fields.
*/
function _civicrm_api3_cxn_register_spec(&$spec) {
$daoFields = CRM_Cxn_DAO_Cxn::fields();
$spec['app_guid'] = $daoFields['app_guid'];
$spec['app_meta_url'] = array(
'name' => 'app_meta_url',
'type' => CRM_Utils_Type::T_STRING,
'title' => ts('Application Metadata URL'),
'description' => 'Application Metadata URL',
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
);
}
/**
* Register with a remote application and create a new connection.
*
* One should generally identify an application using the app_guid.
* However, if you need to test a new/experimental application, then
* disable CIVICRM_CXN_CA and specify app_meta_url.
*
* @param array $params
* Array with keys:
* - app_guid: The unique identifer of the target application.
* - app_meta_url: The URL for the application's metadata.
* @return array
* @throws Exception
*/
function civicrm_api3_cxn_register($params) {
if (!empty($params['app_meta_url'])) {
list ($status, $json) = CRM_Utils_HttpClient::singleton()->get($params['app_meta_url']);
if (CRM_Utils_HttpClient::STATUS_OK != $status) {
throw new API_Exception("Failed to download appMeta. (Bad HTTP response)");
}
$appMeta = json_decode($json, TRUE);
if (empty($appMeta)) {
throw new API_Exception("Failed to download appMeta. (Malformed)");
}
}
elseif (!empty($params['app_guid'])) {
$appMeta = civicrm_api3('CxnApp', 'getsingle', array(
'appId' => $params['app_guid'],
));
}
if (empty($appMeta) || !is_array($appMeta)) {
throw new API_Exception("Missing expected parameter: app_guid");
}
\Civi\Cxn\Rpc\AppMeta::validate($appMeta);
try {
/** @var \Civi\Cxn\Rpc\RegistrationClient $client */
$client = \Civi::service('cxn_reg_client');
list($cxnId, $result) = $client->register($appMeta);
CRM_Cxn_BAO_Cxn::updateAppMeta($appMeta);
}
catch (Exception $e) {
CRM_Cxn_BAO_Cxn::updateAppMeta($appMeta);
throw $e;
}
return $result;
}
/**
* Adjust metadata for cxn unregister.
*
* @param array $spec
*/
function _civicrm_api3_cxn_unregister_spec(&$spec) {
$daoFields = CRM_Cxn_DAO_Cxn::fields();
$spec['cxn_guid'] = $daoFields['cxn_guid'];
$spec['app_guid'] = $daoFields['app_guid'];
$spec['force'] = array(
'name' => 'force',
'type' => CRM_Utils_Type::T_BOOLEAN,
'title' => ts('Force'),
'description' => 'Destroy connection even if the remote application is non-responsive.',
'default' => '0',
);
}
/**
* Unregister with a remote application; destroy an existing connection.
*
* Specify app_guid XOR cxn_guid.
*
* @param array $params
* Array with keys:
* - cxn_guid: string
* - app_guid: string
* - force: bool
* @return array
*/
function civicrm_api3_cxn_unregister($params) {
$cxnId = _civicrm_api3_cxn_parseCxnId($params);
$appMeta = CRM_Cxn_BAO_Cxn::getAppMeta($cxnId);
/** @var \Civi\Cxn\Rpc\RegistrationClient $client */
$client = \Civi::service('cxn_reg_client');
list($cxnId, $result) = $client->unregister($appMeta, CRM_Utils_Array::value('force', $params, FALSE));
return $result;
}
/**
* @param array $params
* An array with cxn_guid and/or app_guid.
* @return string
* The CxnId. (If not available, then an exception is thrown.)
*
* @throws API_Exception
*/
function _civicrm_api3_cxn_parseCxnId($params) {
$cxnId = NULL;
if (!empty($params['cxn_guid'])) {
$cxnId = $params['cxn_guid'];
}
elseif (!empty($params['app_guid'])) {
$cxnId = CRM_Core_DAO::singleValueQuery('SELECT cxn_guid FROM civicrm_cxn WHERE app_guid = %1', array(
1 => array($params['app_guid'], 'String'),
));
if (!$cxnId) {
throw new API_Exception("The app_guid does not correspond to an active connection.");
}
}
if (!$cxnId) {
throw new API_Exception('Missing required parameter: cxn_guid');
}
return $cxnId;
}
/**
* Adjust metadata for cxn get action.
*
* @param array $spec
*/
function _civicrm_api3_cxn_get_spec(&$spec) {
// Don't trust AJAX callers or other external code to modify, filter, or return the secret.
unset($spec['secret']);
}
/**
* Returns an array of Cxn records.
*
* @param array $params
* Array of one or more valid property_name=>value pairs.
*
* @return array
* API result array.
*/
function civicrm_api3_cxn_get($params) {
// Don't trust AJAX callers or other external code to modify, filter, or return the secret.
unset($params['secret']);
$result = _civicrm_api3_basic_get(_civicrm_api3_get_BAO(__FUNCTION__), $params);
if (is_array($result['values'])) {
foreach (array_keys($result['values']) as $i) {
if (!empty($result['values'][$i]['app_meta'])) {
$result['values'][$i]['app_meta'] = json_decode($result['values'][$i]['app_meta'], TRUE);
}
if (!empty($result['values'][$i]['perm'])) {
$result['values'][$i]['perm'] = json_decode($result['values'][$i]['perm'], TRUE);
}
// Don't trust AJAX callers or other external code to modify, filter, or return the secret.
unset($result['values'][$i]['secret']);
}
}
return $result;
}
/**
* Adjust metadata for "getlink" action.
*
* @param array $spec
* List of fields.
*/
function _civicrm_api3_cxn_getlink_spec(&$spec) {
$daoFields = CRM_Cxn_DAO_Cxn::fields();
$spec['app_guid'] = $daoFields['app_guid'];
$spec['cxn_guid'] = $daoFields['cxn_guid'];
$spec['page_name'] = array(
'name' => 'page_name',
'type' => CRM_Utils_Type::T_STRING,
'title' => ts('Page Type'),
'description' => 'The type of page (eg "settings")',
'maxlength' => 63,
'size' => CRM_Utils_Type::HUGE,
'api.aliases' => array('page'),
);
}
/**
*
* @param array $params
* Array with keys:
* - cxn_guid OR app_guid: string.
* - page: string.
* @return array
* @throws Exception
*/
function civicrm_api3_cxn_getlink($params) {
$cxnId = _civicrm_api3_cxn_parseCxnId($params);
$appMeta = CRM_Cxn_BAO_Cxn::getAppMeta($cxnId);
if (empty($params['page_name']) || !is_string($params['page_name'])) {
throw new API_Exception("Invalid page");
}
/** @var \Civi\Cxn\Rpc\RegistrationClient $client */
$client = \Civi::service('cxn_reg_client');
return $client->call($appMeta, 'Cxn', 'getlink', array(
'page' => $params['page_name'],
));
}
/**
*
* @param array $params
* @return array
* @throws Exception
*/
function civicrm_api3_cxn_getcfg($params) {
$result = array(
'CIVICRM_CXN_CA' => defined('CIVICRM_CXN_CA') ? CIVICRM_CXN_CA : NULL,
'CIVICRM_CXN_VIA' => defined('CIVICRM_CXN_VIA') ? CIVICRM_CXN_VIA : NULL,
'CIVICRM_CXN_APPS_URL' => defined('CIVICRM_CXN_APPS_URL') ? CIVICRM_CXN_APPS_URL : NULL,
'siteCallbackUrl' => CRM_Cxn_BAO_Cxn::getSiteCallbackUrl(),
);
return civicrm_api3_create_success($result);
}
/**
* Creates or modifies a Cxn row.
*
* @param array $params
* Array with keys:
* - id, cxn_guid OR app_guid: string.
* - is_active: boolean.
* - options: JSON
* @return page
* @throws Exception
*/
function civicrm_api3_cxn_create($params) {
$result = "";
try {
// get the ID
if (!empty($params['id'])) {
$cxnId = $params['id'];
}
else {
$cxnId = _civicrm_api3_cxn_parseCxnId($params);
}
// see if it's sth to update
if (isset($params['options']) || isset($params['is_active'])) {
$dao = new CRM_Cxn_DAO_Cxn();
$dao->id = $cxnId;
if ($dao->find()) {
if (isset($params['is_active'])) {
$dao->is_active = (int) $params['is_active'];
}
if (isset($params['options'])) {
$dao->options = $params['options'];
}
$result = $dao->save();
}
}
return civicrm_api3_create_success($result, $params, 'Cxn', 'create');
}
catch(Exception $ex){
throw $ex;
}
}

View file

@ -0,0 +1,121 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
use \Civi\Cxn\Rpc\Message\AppMetasMessage;
use \Civi\Cxn\Rpc\Message\GarbledMessage;
/**
* The CxnApp API provides a pseudo-entity for exploring the list
* of published applications. It is a read-only API which
* downloads and validates the application list from civicrm.org.
*
* At time of writing, this API only supports simple filtering on
* equality. If you'd like more advanced filters, consider updating
* _civicrm_api3_basic_array_get() and api_v3_UtilsTest::testBasicArrayGet.
*
* NOTE: SyntaxConformanceTest is disabled for CxnApp. As a rough
* equivalent, see api_v3_UtilsTest::testBasicArrayGet.
*/
/**
* Adjust metadata for "register" action.
*
* @param array $spec
* List of fields.
*/
function _civicrm_api3_cxn_app_get_spec(&$spec) {
$spec['appCert'] = array(
'name' => 'appCert',
'type' => CRM_Utils_Type::T_TEXT,
'title' => ts('Certificate'),
'description' => 'PEM-encoded certificate',
);
$spec['appId'] = array(
'name' => 'appId',
'type' => CRM_Utils_Type::T_STRING,
'title' => ts('Application GUID'),
'description' => 'Application GUID',
'maxlength' => 128,
'size' => CRM_Utils_Type::HUGE,
);
$spec['appUrl'] = array(
'name' => 'appUrl',
'type' => CRM_Utils_Type::T_STRING,
'title' => ts('Registration URL'),
'description' => 'An endpoint to notify when performing registration',
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
);
$spec['desc'] = array(
'name' => 'desc',
'type' => CRM_Utils_Type::T_TEXT,
'title' => ts('Description'),
'description' => 'Description',
);
//$spec['perm'] = array(
// 'name' => 'perm',
// 'type' => CRM_Utils_Type::T_TEXT,
// 'title' => ts('Permissions'),
// 'description' => 'Permissions expected for the service (struct)',
//);
}
/**
* Get a list of applications available for connections.
*
* @param array $params
* @return array
* @throws API_Exception
* @throws CRM_Core_Exception
* @throws \Civi\Cxn\Rpc\Exception\InvalidMessageException
*/
function civicrm_api3_cxn_app_get($params) {
// You should not change CIVICRM_CXN_APPS_URL in production; this is for local development.
$url = defined('CIVICRM_CXN_APPS_URL') ? CIVICRM_CXN_APPS_URL : \Civi\Cxn\Rpc\Constants::OFFICIAL_APPMETAS_URL;
list ($headers, $blob, $code) = CRM_Cxn_CiviCxnHttp::singleton()->send('GET', $url, '');
if ($code != 200) {
throw new API_Exception("Failed to download application list.");
}
$agent = new \Civi\Cxn\Rpc\Agent(NULL, NULL);
$agent->setCertValidator(CRM_Cxn_BAO_Cxn::createCertificateValidator());
$message = $agent->decode(array(AppMetasMessage::NAME, GarbledMessage::NAME), $blob);
if ($message instanceof AppMetasMessage) {
return _civicrm_api3_basic_array_get('CxnApp', $params, $message->getData(), 'appId',
array('appId', 'appUrl', 'desc', 'appCert', 'perm'));
}
elseif ($message instanceof GarbledMessage) {
return civicrm_api3_create_error('Received garbled response', array(
'garbled_message' => $message->getData(),
));
}
else {
return civicrm_api3_create_error("Unrecognized message");
}
}

View file

@ -0,0 +1,98 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
* This api exposes CiviCRM Dashboard.
*
* @package CiviCRM_APIv3
*/
/**
* Creates or updates an Dashlet.
*
* @param array $params
*
* @return array
* Array containing 'is_error' to denote success or failure and details of the created activity
*/
function civicrm_api3_dashboard_create($params) {
civicrm_api3_verify_one_mandatory($params, NULL, array(
'name',
'label',
'url',
'fullscreen_url',
)
);
return _civicrm_api3_basic_create(_civicrm_api3_get_BAO(__FUNCTION__), $params, 'Dashboard');
}
/**
* Specify Meta data for create.
*
* Note that this data is retrievable via the getfields function
* and is used for pre-filling defaults and ensuring mandatory requirements are met.
*
* @param array $params
* array of parameters determined by getfields.
*/
function _civicrm_api3_dashboard_create_spec(&$params) {
$params['is_active']['api.default'] = 1;
unset($params['version']);
}
/**
* Gets a CiviCRM Dashlets according to parameters.
*
* @param array $params
*
* @return array
*/
function civicrm_api3_dashboard_get($params) {
// NEVER COPY THIS. No idea why a newish api would not use basic_get.
$bao = new CRM_Core_BAO_Dashboard();
_civicrm_api3_dao_set_filter($bao, $params, TRUE);
$dashlets = _civicrm_api3_dao_to_array($bao, $params, TRUE, 'Dashboard');
return civicrm_api3_create_success($dashlets, $params, 'Dashboard', 'get', $bao);
}
/**
* Delete a specified Dashlet.
*
* @param array $params
* Array holding 'id' of dashlet to be deleted.
* @return array
* @throws API_Exception
*/
function civicrm_api3_dashboard_delete($params) {
if (CRM_Core_BAO_Dashboard::deleteDashlet($params['id'])) {
return civicrm_api3_create_success(1, $params, 'Dashboard', 'delete');
}
else {
throw new API_Exception('Could not delete dashlet');
}
}

View file

@ -0,0 +1,113 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
* This api exposes CiviCRM dashboard contacts.
*
* @package CiviCRM_APIv3
*/
/**
* Creates/Updates a new Dashboard Contact Entry.
*
* @param array $params
*
* @return array
*/
function civicrm_api3_dashboard_contact_create($params) {
if (empty($params['id'])) {
civicrm_api3_verify_one_mandatory($params,
NULL,
array(
'dashboard_id',
)
);
}
$errors = _civicrm_api3_dashboard_contact_check_params($params);
if ($errors !== NULL) {
return $errors;
}
return _civicrm_api3_basic_create(_civicrm_api3_get_BAO(__FUNCTION__), $params);
}
/**
* Gets a CiviCRM Dashlets of Contacts according to parameters.
*
* @param array $params
* Array per getfields metadata.
*
* @return array
*/
function civicrm_api3_dashboard_contact_get($params) {
return _civicrm_api3_basic_get(_civicrm_api3_get_BAO(__FUNCTION__), $params);
}
/**
* Adjust Metadata for Create action.
*
* The metadata is used for setting defaults, documentation & validation.
*
* @param array $params
* Array of parameters determined by getfields.
*/
function _civicrm_api3_dashboard_contact_create_spec(&$params) {
unset($params['version']);
}
/**
* Check permissions on contact dashboard retrieval.
*
* @param array $params
* Array per getfields metadata.
*
* @return array|null
*/
function _civicrm_api3_dashboard_contact_check_params(&$params) {
$dashboard_id = CRM_Utils_Array::value('dashboard_id', $params);
if ($dashboard_id) {
$allDashlets = CRM_Core_BAO_Dashboard::getDashlets(TRUE, CRM_Utils_Array::value('check_permissions', $params, 0));
if (!isset($allDashlets[$dashboard_id])) {
return civicrm_api3_create_error('Invalid or inaccessible dashboard ID');
}
}
return NULL;
}
/**
* Delete an existing dashboard-contact.
*
* This method is used to delete any existing dashboard-board. the id of the dashboard-contact
* is required field in $params array
*
* @param array $params
*
* @return array
* @throws \API_Exception
*/
function civicrm_api3_dashboard_contact_delete($params) {
return _civicrm_api3_basic_delete(_civicrm_api3_get_BAO(__FUNCTION__), $params);
}

View file

@ -0,0 +1,171 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
* This api exposes CiviCRM Domain configuration settings.
*
* @package CiviCRM_APIv3
*/
/**
* Get CiviCRM Domain details.
*
* @param array $params
*
* @return array
* @throws \API_Exception
*/
function civicrm_api3_domain_get($params) {
$params['version'] = CRM_Utils_Array::value('domain_version', $params);
unset($params['version']);
$bao = new CRM_Core_BAO_Domain();
if (!empty($params['current_domain'])) {
$domainBAO = CRM_Core_Config::domainID();
$params['id'] = $domainBAO;
}
if (!empty($params['options']) && !empty($params['options']['is_count'])) {
return _civicrm_api3_basic_get(_civicrm_api3_get_BAO(__FUNCTION__), $params);
}
_civicrm_api3_dao_set_filter($bao, $params, TRUE);
$domains = _civicrm_api3_dao_to_array($bao, $params, TRUE, 'Domain');
foreach ($domains as $domain) {
if (!empty($domain['contact_id'])) {
$values = array();
$locparams = array(
'contact_id' => $domain['contact_id'],
);
$values['location'] = CRM_Core_BAO_Location::getValues($locparams, TRUE);
$address_array = array(
'street_address', 'supplemental_address_1', 'supplemental_address_2', 'supplemental_address_3',
'city', 'state_province_id', 'postal_code', 'country_id',
'geo_code_1', 'geo_code_2',
);
if (!empty($values['location']['email'])) {
$domain['domain_email'] = CRM_Utils_Array::value('email', $values['location']['email'][1]);
}
if (!empty($values['location']['phone'])) {
$domain['domain_phone'] = array(
'phone_type' => CRM_Core_PseudoConstant::getLabel('CRM_Core_BAO_Phone', 'phone_type_id',
CRM_Utils_Array::value(
'phone_type_id',
$values['location']['phone'][1]
)
),
'phone' => CRM_Utils_Array::value(
'phone',
$values['location']['phone'][1]
),
);
}
if (!empty($values['location']['address'])) {
foreach ($address_array as $value) {
$domain['domain_address'][$value] = CRM_Utils_Array::value($value,
$values['location']['address'][1]
);
}
}
list($domain['from_name'],
$domain['from_email']
) = CRM_Core_BAO_Domain::getNameAndEmail(TRUE);
// Rename version to domain_version, see CRM-17430.
$domain['domain_version'] = $domain['version'];
unset($domain['version']);
$domains[$domain['id']] = array_merge($domains[$domain['id']], $domain);
}
}
return civicrm_api3_create_success($domains, $params, 'Domain', 'get', $bao);
}
/**
* Adjust Metadata for Get action.
*
* The metadata is used for setting defaults, documentation & validation.
*
* @param array $params
* Array of parameters determined by getfields.
*/
function _civicrm_api3_domain_get_spec(&$params) {
$params['current_domain'] = array(
'title' => "Current Domain",
'description' => "get loaded domain",
);
}
/**
* Create a new Domain.
*
* @param array $params
*
* @return array
*/
function civicrm_api3_domain_create($params) {
if (isset($params['domain_version'])) {
$params['version'] = $params['domain_version'];
}
else {
unset($params['version']);
}
$result = _civicrm_api3_basic_create(_civicrm_api3_get_BAO(__FUNCTION__), $params);
$result_value = CRM_Utils_Array::first($result['values']);
if (isset($result_value['version'])) {
// Rename version to domain_version, see CRM-17430.
$result_value['domain_version'] = $result_value['version'];
unset($result_value['version']);
$result['values'][$result['id']] = $result_value;
}
return $result;
}
/**
* Adjust Metadata for Create action.
*
* The metadata is used for setting defaults, documentation & validation.
*
* @param array $params
* Array of parameters determined by getfields.
*/
function _civicrm_api3_domain_create_spec(&$params) {
$params['domain_version'] = array(
'title' => "CiviCRM Version",
'description' => "The civicrm version this instance is running",
'type' => CRM_Utils_Type::T_STRING,
);
$params['domain_version']['api.required'] = 1;
unset($params['version']);
$params['name']['api.required'] = 1;
}

View file

@ -0,0 +1,86 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
* This api exposes CiviCRM email records.
*
* @package CiviCRM_APIv3
*/
/**
* Add an Email for a contact.
*
* @param array $params
* Array per getfields metadata.
*
* @return array
* API result array
*/
function civicrm_api3_email_create($params) {
return _civicrm_api3_basic_create(_civicrm_api3_get_BAO(__FUNCTION__), $params);
}
/**
* Adjust Metadata for Create action.
*
* The metadata is used for setting defaults, documentation & validation.
*
* @param array $params
* Array of parameters determined by getfields.
*/
function _civicrm_api3_email_create_spec(&$params) {
// TODO a 'clever' default should be introduced
$params['is_primary']['api.default'] = 0;
$params['email']['api.required'] = 1;
$params['contact_id']['api.required'] = 1;
}
/**
* Deletes an existing Email.
*
* @param array $params
* Array per getfields metadata.
*
* @return array
* API result array.
*/
function civicrm_api3_email_delete($params) {
return _civicrm_api3_basic_delete(_civicrm_api3_get_BAO(__FUNCTION__), $params);
}
/**
* Retrieve one or more emails.
*
* @param array $params
* Array per getfields metadata.
*
* @return array
* api result array
*/
function civicrm_api3_email_get($params) {
return _civicrm_api3_basic_get(_civicrm_api3_get_BAO(__FUNCTION__), $params);
}

View file

@ -0,0 +1,64 @@
<?php
/**
* Get list of deprecated entities.
*
* This is called by the api wrapper when returning the result of api.Entity.get.
*
* @param array $entities
*
* @return array
* Array of deprecated api entities
*/
function _civicrm_api3_entity_deprecation($entities) {
$deprecated = array();
if (!empty($entities['values'])) {
foreach ($entities['values'] as $entity) {
if (is_string(_civicrm_api3_deprecation_check($entity))) {
$deprecated[] = $entity;
}
}
}
return $deprecated;
}
/**
* Placeholder function.
*
* This should never be called, as it doesn't have any meaning.
*
* @param array $params
*
* @return array
*/
function civicrm_api3_entity_create($params) {
return civicrm_api3_create_error("API (Entity, Create) does not exist Creating a new entity means modifying the source code of civiCRM.");
}
/**
* Placeholder function.
*
* This should never be called, as it doesn't have any meaning.
*
* @param array $params
*
* @return array
*/
function civicrm_api3_entity_delete($params) {
return civicrm_api3_create_error("API (Entity, Delete) does not exist Deleting an entity means modifying the source code of civiCRM.");
}
/**
* Placeholder function.
*
* This should never be called, as it doesn't have any meaning.
*
* @param array $params
*
* @return array
*/
function civicrm_api3_entity_getfields($params) {
// we return an empty array so it makes it easier to write generic getdefaults / required tests
// without putting an exception in for entity
return civicrm_api3_create_success(array());
}

View file

@ -0,0 +1,81 @@
<?php
/*
--------------------------------------------------------------------
| CiviCRM version 4.7 |
--------------------------------------------------------------------
| Copyright CiviCRM LLC (c) 2004-2017 |
--------------------------------------------------------------------
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
--------------------------------------------------------------------
*/
/**
* This api exposes CiviCRM EntityBatch records.
*
* Use this api to add/remove entities from a batch.
* To create/update/delete the batches themselves, use the Batch api.
*
* @package CiviCRM_APIv3
*/
/**
* Get entity batches.
*
* @param array $params
*
* @return array
*/
function civicrm_api3_entity_batch_get($params) {
return _civicrm_api3_basic_get(_civicrm_api3_get_BAO(__FUNCTION__), $params);
}
/**
* Adjust Metadata for Create action.
*
* The metadata is used for setting defaults, documentation & validation.
*
* @param array $params
* Array of parameters determined by getfields.
*/
function _civicrm_api3_entity_batch_create_spec(&$params) {
$params['entity_id']['api.required'] = 1;
$params['batch_id']['api.required'] = 1;
}
/**
* Create an entity batch.
*
* @param array $params
*
* @return array
*/
function civicrm_api3_entity_batch_create($params) {
return _civicrm_api3_basic_create(_civicrm_api3_get_BAO(__FUNCTION__), $params);
}
/**
* Mark entity batch as removed.
*
* @param array $params
*
* @return array
*/
function civicrm_api3_entity_batch_delete($params) {
return _civicrm_api3_basic_delete(_civicrm_api3_get_BAO(__FUNCTION__), $params);
}

View file

@ -0,0 +1,76 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
* This api exposes CiviCRM EntityFinancialAccount.
*
* @package CiviCRM_APIv3
*/
/**
* Save an Entity Financial Account record.
*
* @param array $params
*
* @return array
*/
function civicrm_api3_entity_financial_account_create($params) {
return _civicrm_api3_basic_create(_civicrm_api3_get_BAO(__FUNCTION__), $params);
}
/**
* Save an Entity Financial Account record.
*
* @param array $params
*/
function _civicrm_api3_entity_financial_account_create_spec(&$params) {
$params['entity_table']['api.default'] = 'civicrm_financial_type';
}
/**
* Get an Entity Financial Account record.
*
* @param array $params
*
* @return array
* Array of retrieved EntityFinancialAccount property values.
*/
function civicrm_api3_entity_financial_account_get($params) {
return _civicrm_api3_basic_get(_civicrm_api3_get_BAO(__FUNCTION__), $params);
}
/**
* Delete an Entity Financial Account record.
*
* @param array $params
*
* @return array
* Array of deleted values.
*/
function civicrm_api3_entity_financial_account_delete($params) {
return _civicrm_api3_basic_delete(_civicrm_api3_get_BAO(__FUNCTION__), $params);
}

View file

@ -0,0 +1,82 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
* This api exposes CiviCRM FinancialType.
*
* @package CiviCRM_APIv3
*/
/**
* Save a Entity Financial Trxn.
*
* @param array $params
*
* @return array
*/
function civicrm_api3_entity_financial_trxn_create($params) {
return _civicrm_api3_basic_create(_civicrm_api3_get_BAO(__FUNCTION__), $params);
}
/**
* Get a Entity Financial Trxn.
*
* @param array $params
*
* @return array
* Array of retrieved Entity Financial Trxn property values.
*/
function civicrm_api3_entity_financial_trxn_get($params) {
return _civicrm_api3_basic_get(_civicrm_api3_get_BAO(__FUNCTION__), $params);
}
/**
* Delete a Entity Financial Trxn.
*
* @param array $params
*
* @return array
* Array of deleted values.
*/
function civicrm_api3_entity_financial_trxn_delete($params) {
return _civicrm_api3_basic_delete(_civicrm_api3_get_BAO(__FUNCTION__), $params);
}
/**
* Adjust Metadata for Create action.
*
* The metadata is used for setting defaults, documentation & validation.
*
* @param array $params
* Array of parameters determined by getfields.
*/
function _civicrm_api3_entity_financial_trxn_create_spec(&$params) {
$params['entity_table']['api.required'] = 1;
$params['entity_id']['api.required'] = 1;
$params['financial_trxn_id']['api.required'] = 1;
$params['amount']['api.required'] = 1;
}

View file

@ -0,0 +1,158 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
* This api exposes CiviCRM EntityTag records.
*
* Use this api to add/remove tags from a contact/activity/etc.
* To create/update/delete the tags themselves, use the Tag api.
*
* @package CiviCRM_APIv3
*/
/**
* Get entity tags.
*
* @param array $params
*
* @return array
*/
function civicrm_api3_entity_tag_get($params) {
return _civicrm_api3_basic_get(_civicrm_api3_get_BAO(__FUNCTION__), $params);
}
/**
* Adjust Metadata for Get action.
*
* The metadata is used for setting defaults, documentation & validation.
*
* @param array $params
* Array of parameters determined by getfields.
*/
function _civicrm_api3_entity_tag_get_spec(&$params) {
$params['entity_id']['api.aliases'] = array('contact_id');
$params['entity_table']['api.default'] = 'civicrm_contact';
}
/**
* Create an entity tag.
*
* @param array $params
*
* @return array
*/
function civicrm_api3_entity_tag_create($params) {
return _civicrm_api3_entity_tag_common($params, 'add');
}
/**
* Mark entity tag as removed.
*
* @param array $params
*
* @return array
*/
function civicrm_api3_entity_tag_delete($params) {
return _civicrm_api3_entity_tag_common($params, 'remove');
}
/**
* Modify metadata.
*
* @param array $params
*/
function _civicrm_api3_entity_tag_delete_spec(&$params) {
// set as not required as tag_id also acceptable & no either/or std yet
$params['id']['api.required'] = 0;
}
/**
* Helper function for formatting tags (part of api v2 legacy).
*
* @param array $params
* @param string $op
*
* @return array
*/
function _civicrm_api3_entity_tag_common($params, $op = 'add') {
$entityIDs = array();
$entityTable = 'civicrm_contact';
if (is_array($params)) {
foreach ($params as $n => $v) {
if ((substr($n, 0, 10) == 'contact_id') || (substr($n, 0, 9) == 'entity_id')) {
$entityIDs[] = $v;
}
elseif (substr($n, 0, 6) == 'tag_id') {
$tagIDs[] = $v;
}
elseif (substr($n, 0, 12) == 'entity_table') {
$entityTable = $v;
}
}
}
if (empty($entityIDs)) {
return civicrm_api3_create_error('contact_id is a required field');
}
if (empty($tagIDs)) {
if ($op == 'remove') {
$tagIDs = array_keys(CRM_Core_BAO_EntityTag::getContactTags($entityIDs[0]));
}
else {
return civicrm_api3_create_error('tag_id is a required field');
}
}
$values = array('is_error' => 0);
if ($op == 'add') {
$values['total_count'] = $values['added'] = $values['not_added'] = 0;
foreach ($tagIDs as $tagID) {
list($te, $a, $na) = CRM_Core_BAO_EntityTag::addEntitiesToTag($entityIDs, $tagID, $entityTable,
CRM_Utils_Array::value('check_permissions', $params));
$values['total_count'] += $te;
$values['added'] += $a;
$values['not_added'] += $na;
}
}
else {
$values['total_count'] = $values['removed'] = $values['not_removed'] = 0;
foreach ($tagIDs as $tagID) {
list($te, $r, $nr) = CRM_Core_BAO_EntityTag::removeEntitiesFromTag($entityIDs, $tagID, $entityTable, CRM_Utils_Array::value('check_permissions', $params));
$values['total_count'] += $te;
$values['removed'] += $r;
$values['not_removed'] += $nr;
}
}
if (empty($values['added']) && empty($values['removed'])) {
$values['is_error'] = 1;
$values['error_message'] = "Unable to $op tags";
}
return $values;
}

View file

@ -0,0 +1,282 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* This api exposes CiviCRM Event.
*
* @package CiviCRM_APIv3
*/
/**
* Create a Event.
*
* @param array $params
* Input parameters.
*
* @return array
* API result Array.
*/
function civicrm_api3_event_create($params) {
// Required fields for creating an event
if (empty($params['id']) && empty($params['is_template'])) {
civicrm_api3_verify_mandatory($params, NULL, array(
'start_date',
'title',
array('event_type_id', 'template_id'),
));
}
// Required fields for creating an event template
elseif (empty($params['id']) && !empty($params['is_template'])) {
civicrm_api3_verify_mandatory($params, NULL, array(
'template_title',
));
}
// Clone event from template
if (!empty($params['template_id']) && empty($params['id'])) {
$copy = CRM_Event_BAO_Event::copy($params['template_id']);
$params['id'] = $copy->id;
unset($params['template_id']);
}
_civicrm_api3_event_create_legacy_support_42($params);
return _civicrm_api3_basic_create(_civicrm_api3_get_BAO(__FUNCTION__), $params, 'Event');
}
/**
* Adjust Metadata for Create action.
*
* The metadata is used for setting defaults, documentation & validation.
*
* @param array $params
* Array of parameters determined by getfields.
*/
function _civicrm_api3_event_create_spec(&$params) {
$params['is_active']['api.default'] = 1;
$params['financial_type_id']['api.aliases'] = array('contribution_type_id');
$params['is_template']['api.default'] = 0;
}
/**
* Support for schema changes made in 4.2.
*
* The main purpose of the API is to provide integrators a level of stability not provided by
* the core code or schema - this means we have to provide support for api calls (where possible)
* across schema changes.
*
* @param array $params
*/
function _civicrm_api3_event_create_legacy_support_42(&$params) {
if (!empty($params['payment_processor_id'])) {
$params['payment_processor'] = CRM_Core_DAO::VALUE_SEPARATOR . $params['payment_processor_id'] . CRM_Core_DAO::VALUE_SEPARATOR;
}
}
/**
* Get Event record.
*
* @param array $params
*
* @return array
* Array of all found event property values.
*/
function civicrm_api3_event_get($params) {
//legacy support for $params['return.sort']
if (!empty($params['return.sort'])) {
$params['options']['sort'] = $params['return.sort'];
unset($params['return.sort']);
}
//legacy support for $params['return.offset']
if (!empty($params['return.offset'])) {
$params['options']['offset'] = $params['return.offset'];
unset($params['return.offset']);
}
//legacy support for $params['return.max_results']
if (!empty($params['return.max_results'])) {
$params['options']['limit'] = $params['return.max_results'];
unset($params['return.max_results']);
}
$sql = CRM_Utils_SQL_Select::fragment();
if (!empty($params['isCurrent'])) {
$sql->where('(start_date >= CURDATE() || end_date >= CURDATE())');
}
$events = _civicrm_api3_basic_get(_civicrm_api3_get_BAO(__FUNCTION__), $params, FALSE, 'Event', $sql, TRUE);
$options = _civicrm_api3_get_options_from_params($params, TRUE);
if ($options['is_count']) {
return civicrm_api3_create_success($events, $params, 'Event', 'get');
}
foreach ($events as $id => $event) {
if (!empty($options['return']['is_full'])) {
_civicrm_api3_event_getisfull($events, $id);
}
_civicrm_api3_event_get_legacy_support_42($events, $id);
if (!empty($options['return']['price_set_id'])) {
$events[$id]['price_set_id'] = CRM_Price_BAO_PriceSet::getFor('civicrm_event', $id);
}
}
return civicrm_api3_create_success($events, $params, 'Event', 'get');
}
/**
* Adjust Metadata for Get action.
*
* The metadata is used for setting defaults, documentation & validation.
*
* @param array $params
* Array of parameters determined by getfields.
*/
function _civicrm_api3_event_get_spec(&$params) {
$params['financial_type_id']['api.aliases'] = array('contribution_type_id');
}
/**
* Support for schema changes made in 4.2.
*
* The main purpose of the API is to provide integrators a level of stability not provided by
* the core code or schema - this means we have to provide support for api calls (where possible)
* across schema changes.
*
* @param array $event
* @param int $event_id
*/
function _civicrm_api3_event_get_legacy_support_42(&$event, $event_id) {
if (!empty($event[$event_id]['payment_processor'])) {
$processors = explode(CRM_Core_DAO::VALUE_SEPARATOR, $event[$event_id]['payment_processor']);
if (count($processors) == 3) {
$event[$event_id]['payment_processor_id'] = $processors[1];
}
}
}
/**
* Delete an existing Event.
*
* This API is used for deleting a event given its id.
*
* @param array $params
*
* @return array
*/
function civicrm_api3_event_delete($params) {
return CRM_Event_BAO_Event::del($params['id']) ? civicrm_api3_create_success() : civicrm_api3_create_error(ts('Error while deleting event'));
}
/**
* Add 'is_full' & 'available_seats' to the return array.
*
* (this might be better in the BAO)
* Default BAO function returns a string if full rather than a Bool - which is more appropriate to a form
*
* @param array $event
* Return array of the event.
* @param int $event_id
* Id of the event to be updated.
*/
function _civicrm_api3_event_getisfull(&$event, $event_id) {
$eventFullResult = CRM_Event_BAO_Participant::eventFull($event_id, 1);
if (!empty($eventFullResult) && is_int($eventFullResult)) {
$event[$event_id]['available_places'] = $eventFullResult;
}
elseif (is_null($eventFullResult)) {
return $event[$event_id]['is_full'] = 0;
}
else {
$event[$event_id]['available_places'] = 0;
}
$event[$event_id]['is_full'] = $event[$event_id]['available_places'] == 0 ? 1 : 0;
}
/**
* Get event list parameters.
*
* @see _civicrm_api3_generic_getlist_params
*
* @param array $request
*/
function _civicrm_api3_event_getlist_params(&$request) {
$fieldsToReturn = array('start_date', 'event_type_id', 'title', 'summary');
$request['params']['return'] = array_unique(array_merge($fieldsToReturn, $request['extra']));
$request['params']['options']['sort'] = 'start_date DESC';
if (empty($request['params']['id'])) {
$request['params'] += array(
'is_template' => 0,
'is_active' => 1,
);
}
}
/**
* Get event list output.
*
* @see _civicrm_api3_generic_getlist_output
*
* @param array $result
* @param array $request
*
* @return array
*/
function _civicrm_api3_event_getlist_output($result, $request) {
$output = array();
if (!empty($result['values'])) {
foreach ($result['values'] as $row) {
$data = array(
'id' => $row[$request['id_field']],
'label' => $row[$request['label_field']],
'description' => array(
CRM_Core_Pseudoconstant::getLabel(
'CRM_Event_BAO_Event',
'event_type_id',
$row['event_type_id']
),
),
);
if (!empty($row['start_date'])) {
$data['description'][0] .= ': ' . CRM_Utils_Date::customFormat($row['start_date']);
}
if (!empty($row['summary'])) {
$data['description'][] = $row['summary'];
}
// Add repeating info
$repeat = CRM_Core_BAO_RecurringEntity::getPositionAndCount($row['id'], 'civicrm_event');
$data['extra']['is_recur'] = FALSE;
if ($repeat) {
$data['suffix'] = ts('(%1 of %2)', array(1 => $repeat[0], 2 => $repeat[1]));
$data['extra']['is_recur'] = TRUE;
}
$output[] = $data;
}
}
return $output;
}

View file

@ -0,0 +1,427 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
define('API_V3_EXTENSION_DELIMITER', ',');
/**
* This provides an api interface for CiviCRM extension management.
*
* @package CiviCRM_APIv3
*/
/**
* Install an extension.
*
* @param array $params
* Input parameters.
* - key: string, eg "com.example.myextension"
* - keys: array of string, eg array("com.example.myextension1", "com.example.myextension2")
* - path: string, e.g. "/var/www/extensions/*"
*
* Using 'keys' should be more performant than making multiple API calls with 'key'
*
* @return array
*/
function civicrm_api3_extension_install($params) {
$keys = _civicrm_api3_getKeys($params);
if (!$keys) {
return civicrm_api3_create_success();
}
try {
$manager = CRM_Extension_System::singleton()->getManager();
$manager->install($manager->findInstallRequirements($keys));
}
catch (CRM_Extension_Exception $e) {
return civicrm_api3_create_error($e->getMessage());
}
return civicrm_api3_create_success();
}
/**
* Spec function for getfields
* @param $fields
*/
function _civicrm_api3_extension_install_spec(&$fields) {
$fields['keys'] = array(
'title' => 'Extension Key(s)',
'api.aliases' => array('key'),
'type' => CRM_Utils_Type::T_STRING,
'description' => 'Fully qualified name of one or more extensions',
);
$fields['path'] = array(
'title' => 'Extension Path',
'type' => CRM_Utils_Type::T_STRING,
'description' => 'The path to the extension. May use wildcard ("*").',
);
}
/**
* Upgrade an extension - runs upgrade_N hooks and system.flush.
*
* @return array
* API result
*/
function civicrm_api3_extension_upgrade() {
CRM_Core_Invoke::rebuildMenuAndCaches(TRUE);
$queue = CRM_Extension_Upgrades::createQueue();
$runner = new CRM_Queue_Runner(array(
'title' => 'Extension Upgrades',
'queue' => $queue,
'errorMode' => CRM_Queue_Runner::ERROR_ABORT,
));
try {
$result = $runner->runAll();
}
catch (CRM_Extension_Exception $e) {
return civicrm_api3_create_error($e->getMessage());
}
if ($result === TRUE) {
return civicrm_api3_create_success();
}
else {
return $result;
}
}
/**
* Enable an extension.
*
* @param array $params
* Input parameters.
* - key: string, eg "com.example.myextension"
* - keys: array of string, eg array("com.example.myextension1", "com.example.myextension2")
* - path: string, e.g. "/var/www/vendor/foo/myext" or "/var/www/vendor/*"
*
* Using 'keys' should be more performant than making multiple API calls with 'key'
*
* @return array
*/
function civicrm_api3_extension_enable($params) {
$keys = _civicrm_api3_getKeys($params);
if (count($keys) == 0) {
return civicrm_api3_create_success();
}
$manager = CRM_Extension_System::singleton()->getManager();
$manager->enable($manager->findInstallRequirements($keys));
return civicrm_api3_create_success();
}
/**
* Spec function for getfields
* @param $fields
*/
function _civicrm_api3_extension_enable_spec(&$fields) {
_civicrm_api3_extension_install_spec($fields);
}
/**
* Disable an extension.
*
* @param array $params
* Input parameters.
* - key: string, eg "com.example.myextension"
* - keys: array of string, eg array("com.example.myextension1", "com.example.myextension2")
* - path: string, e.g. "/var/www/vendor/foo/myext" or "/var/www/vendor/*"
*
* Using 'keys' should be more performant than making multiple API calls with 'key'
*
* @return array
*/
function civicrm_api3_extension_disable($params) {
$keys = _civicrm_api3_getKeys($params);
if (count($keys) == 0) {
return civicrm_api3_create_success();
}
CRM_Extension_System::singleton()->getManager()->disable($keys);
return civicrm_api3_create_success();
}
/**
* Spec function for getfields
* @param $fields
*/
function _civicrm_api3_extension_disable_spec(&$fields) {
_civicrm_api3_extension_install_spec($fields);
}
/**
* Uninstall an extension.
*
* @param array $params
* Input parameters.
* - key: string, eg "com.example.myextension"
* - keys: array of string, eg array("com.example.myextension1", "com.example.myextension2")
* - path: string, e.g. "/var/www/vendor/foo/myext" or "/var/www/vendor/*"
*
* Using 'keys' should be more performant than making multiple API calls with 'key'
*
* @todo: removeFiles as optional param
*
* @return array
*/
function civicrm_api3_extension_uninstall($params) {
$keys = _civicrm_api3_getKeys($params);
if (count($keys) == 0) {
return civicrm_api3_create_success();
}
CRM_Extension_System::singleton()->getManager()->uninstall($keys);
return civicrm_api3_create_success();
}
/**
* Spec function for getfields
* @param $fields
*/
function _civicrm_api3_extension_uninstall_spec(&$fields) {
_civicrm_api3_extension_install_spec($fields);
//$fields['removeFiles'] = array(
// 'title' => 'Remove files',
// 'description' => 'Whether to remove the source tree. Default FALSE.',
// 'type' => CRM_Utils_Type::T_BOOLEAN,
//);
}
/**
* Download and install an extension.
*
* @param array $params
* Input parameters.
* - key: string, eg "com.example.myextension"
* - url: string eg "http://repo.com/myextension-1.0.zip"
*
* @throws API_Exception
* @return array
* API result
*/
function civicrm_api3_extension_download($params) {
if (!array_key_exists('url', $params)) {
if (!CRM_Extension_System::singleton()->getBrowser()->isEnabled()) {
throw new API_Exception('Automatic downloading is disabled. Try adding parameter "url"');
}
if ($reqs = CRM_Extension_System::singleton()->getBrowser()->checkRequirements()) {
$first = array_shift($reqs);
throw new API_Exception($first['message']);
}
if ($info = CRM_Extension_System::singleton()->getBrowser()->getExtension($params['key'])) {
if ($info->downloadUrl) {
$params['url'] = $info->downloadUrl;
}
}
}
if (!array_key_exists('url', $params)) {
throw new API_Exception('Cannot resolve download url for extension. Try adding parameter "url"');
}
foreach (CRM_Extension_System::singleton()->getDownloader()->checkRequirements() as $requirement) {
return civicrm_api3_create_error($requirement['message']);
}
if (!CRM_Extension_System::singleton()->getDownloader()->download($params['key'], $params['url'])) {
return civicrm_api3_create_error('Download failed - ZIP file is unavailable or malformed');
}
CRM_Extension_System::singleton()->getCache()->flush();
CRM_Extension_System::singleton(TRUE);
if (CRM_Utils_Array::value('install', $params, TRUE)) {
CRM_Extension_System::singleton()->getManager()->install(array($params['key']));
}
return civicrm_api3_create_success();
}
/**
* Spec function for getfields
* @param $fields
*/
function _civicrm_api3_extension_download_spec(&$fields) {
$fields['key'] = array(
'title' => 'Extension Key',
'api.required' => 1,
'type' => CRM_Utils_Type::T_STRING,
'description' => 'Fully qualified name of the extension',
);
$fields['url'] = array(
'title' => 'Download URL',
'type' => CRM_Utils_Type::T_STRING,
'description' => 'Optional as the system can determine the url automatically for public extensions',
);
$fields['install'] = array(
'title' => 'Auto-install',
'type' => CRM_Utils_Type::T_STRING,
'description' => 'Automatically install the downloaded extension',
'api.default' => TRUE,
);
}
/**
* Download and install an extension.
*
* @param array $params
* Input parameters.
* - local: bool, whether to rescan local filesystem (default: TRUE)
* - remote: bool, whether to rescan remote repository (default: TRUE)
*
* @return array
* API result
*/
function civicrm_api3_extension_refresh($params) {
$system = CRM_Extension_System::singleton(TRUE);
if ($params['local']) {
$system->getManager()->refresh();
$system->getManager()->getStatuses(); // force immediate scan
}
if ($params['remote']) {
if ($system->getBrowser()->isEnabled() && empty($system->getBrowser()->checkRequirements)) {
$system->getBrowser()->refresh();
$system->getBrowser()->getExtensions(); // force immediate download
}
}
return civicrm_api3_create_success();
}
/**
* Spec function for getfields
* @param $fields
*/
function _civicrm_api3_extension_refresh_spec(&$fields) {
$fields['local'] = array(
'title' => 'Rescan Local',
'api.default' => 1,
'type' => CRM_Utils_Type::T_BOOLEAN,
'description' => 'Whether to rescan the local filesystem (default TRUE)',
);
$fields['remote'] = array(
'title' => 'Rescan Remote',
'api.default' => 1,
'type' => CRM_Utils_Type::T_BOOLEAN,
'description' => 'Whether to rescan the remote repository (default TRUE)',
);
}
/**
* Get a list of available extensions.
*
* @param array $params
*
* @return array
* API result
*/
function civicrm_api3_extension_get($params) {
$full_names = _civicrm_api3_getKeys($params, 'full_name');
$keys = _civicrm_api3_getKeys($params, 'key');
$keys = array_merge($full_names, $keys);
$statuses = CRM_Extension_System::singleton()->getManager()->getStatuses();
$mapper = CRM_Extension_System::singleton()->getMapper();
$result = array();
$id = 0;
foreach ($statuses as $key => $status) {
try {
$obj = $mapper->keyToInfo($key);
}
catch (CRM_Extension_Exception $ex) {
CRM_Core_Session::setStatus(ts('Failed to read extension (%1). Please refresh the extension list.', array(1 => $key)));
continue;
}
$info = CRM_Extension_System::createExtendedInfo($obj);
$info['id'] = $id++; // backward compatibility with indexing scheme
if (!empty($keys)) {
if (in_array($key, $keys)) {
$result[] = $info;
}
}
else {
$result[] = $info;
}
}
$options = _civicrm_api3_get_options_from_params($params);
$returnFields = !empty($options['return']) ? $options['return'] : array();
if (!in_array('id', $returnFields)) {
$returnFields = array_merge($returnFields, array('id'));
}
return _civicrm_api3_basic_array_get('Extension', $params, $result, 'id', $returnFields);
}
/**
* Get a list of remotely available extensions.
*
* @param array $params
*
* @return array
* API result
*/
function civicrm_api3_extension_getremote($params) {
$extensions = CRM_Extension_System::singleton()->getBrowser()->getExtensions();
$result = array();
$id = 0;
foreach ($extensions as $key => $obj) {
$info = array();
$info['id'] = $id++; // backward compatibility with indexing scheme
$info = array_merge($info, (array) $obj);
$result[] = $info;
}
return _civicrm_api3_basic_array_get('Extension', $params, $result, 'id', CRM_Utils_Array::value('return', $params, array()));
}
/**
* Determine the list of extension keys.
*
* @param array $params
* @param string $key
* API request params with 'keys' or 'path'.
* - keys: A comma-delimited list of extension names
* - path: An absolute directory path. May append '*' to match all sub-directories.
*
* @return array
*/
function _civicrm_api3_getKeys($params, $key = 'keys') {
if ($key == 'path') {
return CRM_Extension_System::singleton()->getMapper()->getKeysByPath($params['path']);
}
if (isset($params[$key])) {
if (is_array($params[$key])) {
return $params[$key];
}
if ($params[$key] == '') {
return array();
}
return explode(API_V3_EXTENSION_DELIMITER, $params[$key]);
}
else {
return array();
}
}

View file

@ -0,0 +1,141 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
* This api is a simple wrapper of the CiviCRM file DAO.
*
* Creating and updating files is a complex process and this api is usually insufficient.
* Use the "Attachment" api instead for more robust file handling.
*
* @fixme no unit tests
* @package CiviCRM_APIv3
*/
/**
* Create a file record.
* @note This is only one of several steps needed to create a file in CiviCRM.
* Use the "Attachment" api to better handle all steps.
*
* @param array $params
* Array per getfields metadata.
*
* @return array
*/
function civicrm_api3_file_create($params) {
civicrm_api3_verify_mandatory($params, 'CRM_Core_DAO_File', array('uri'));
if (!isset($params['upload_date'])) {
$params['upload_date'] = date("Ymd");
}
$fileDAO = new CRM_Core_DAO_File();
$properties = array(
'id',
'file_type_id',
'mime_type',
'uri',
'document',
'description',
'upload_date',
);
foreach ($properties as $name) {
if (array_key_exists($name, $params)) {
$fileDAO->$name = $params[$name];
}
}
$fileDAO->save();
$file = array();
_civicrm_api3_object_to_array($fileDAO, $file);
return civicrm_api3_create_success($file, $params, 'File', 'create', $fileDAO);
}
/**
* Get a File.
*
* @param array $params
* Array per getfields metadata.
*
* @return array
* Array of all found file object property values.
*/
function civicrm_api3_file_get($params) {
civicrm_api3_verify_one_mandatory($params);
return _civicrm_api3_basic_get(_civicrm_api3_get_BAO(__FUNCTION__), $params);
}
/**
* Update an existing File.
*
* @param array $params
* Array per getfields metadata.
*
* @return array
*/
function civicrm_api3_file_update($params) {
if (!isset($params['id'])) {
return civicrm_api3_create_error('Required parameter missing');
}
$fileDAO = new CRM_Core_DAO_File();
$fileDAO->id = $params['id'];
if ($fileDAO->find(TRUE)) {
$fileDAO->copyValues($params);
if (!$params['upload_date'] && !$fileDAO->upload_date) {
$fileDAO->upload_date = date("Ymd");
}
$fileDAO->save();
}
$file = array();
$cloneDAO = clone($fileDAO);
_civicrm_api3_object_to_array($cloneDAO, $file);
return $file;
}
/**
* Delete an existing File.
*
* @param array $params
* Array per getfields metadata.
* @return array API Result Array
* @throws API_Exception
*/
function civicrm_api3_file_delete($params) {
civicrm_api3_verify_mandatory($params, NULL, array('id'));
if (CRM_Core_BAO_File::deleteEntityFile('*', $params['id'])) {
return civicrm_api3_create_success();
}
else {
throw new API_Exception('Error while deleting a file.');
}
}

View file

@ -0,0 +1,67 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
* This api exposes CiviCRM FinancialAccount.
*
* @package CiviCRM_APIv3
*/
/**
* Save a FinancialAccount.
*
* @param array $params
*
* @return array
*/
function civicrm_api3_financial_account_create($params) {
return _civicrm_api3_basic_create(_civicrm_api3_get_BAO(__FUNCTION__), $params);
}
/**
* Get a FinancialAccount.
*
* @param array $params
*
* @return array
* Array of retrieved FinancialAccount property values.
*/
function civicrm_api3_financial_account_get($params) {
return _civicrm_api3_basic_get(_civicrm_api3_get_BAO(__FUNCTION__), $params);
}
/**
* Delete a FinancialAccount.
*
* @param array $params
*
* @return array
* Array of deleted values.
*/
function civicrm_api3_financial_account_delete($params) {
return _civicrm_api3_basic_delete(_civicrm_api3_get_BAO(__FUNCTION__), $params);
}

View file

@ -0,0 +1,67 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
* This api exposes CiviCRM FinancialItem.
*
* @package CiviCRM_APIv3
*/
/**
* Save a Financial Item.
*
* @param array $params
*
* @return array
*/
function civicrm_api3_financial_item_create($params) {
return _civicrm_api3_basic_create(_civicrm_api3_get_BAO(__FUNCTION__), $params);
}
/**
* Get a FinancialItem.
*
* @param array $params
*
* @return array
* Array of retrieved Financial Item property values.
*/
function civicrm_api3_financial_item_get($params) {
return _civicrm_api3_basic_get(_civicrm_api3_get_BAO(__FUNCTION__), $params);
}
/**
* Delete a Financial Item.
*
* @param array $params
*
* @return array
* Array of deleted values.
*/
function civicrm_api3_financial_item_delete($params) {
return _civicrm_api3_basic_delete(_civicrm_api3_get_BAO(__FUNCTION__), $params);
}

View file

@ -0,0 +1,86 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
* This api exposes CiviCRM FinancialItem.
*
* @package CiviCRM_APIv3
*/
/**
* Save a Financial Item.
*
* @param array $params
*
* @return array
*/
function civicrm_api3_financial_trxn_create($params) {
if (empty($params['id']) && empty($params['contribution_id']) && empty($params['entity_id'])) {
throw new API_Exception("Mandatory key(s) missing from params array: both contribution_id and entity_id are missing");
}
return _civicrm_api3_basic_create('CRM_Core_BAO_FinancialTrxn', $params);
}
/**
* Get a Financialtrxn.
*
* @param array $params
*
* @return array
* Array of retrieved Financial trxn property values.
*/
function civicrm_api3_financial_trxn_get($params) {
return _civicrm_api3_basic_get(_civicrm_api3_get_BAO(__FUNCTION__), $params);
}
/**
* Delete a Financial trxn.
*
* @param array $params
*
* @return array
* Array of deleted values.
*/
function civicrm_api3_financial_trxn_delete($params) {
return _civicrm_api3_basic_delete(_civicrm_api3_get_BAO(__FUNCTION__), $params);
}
/**
* Adjust Metadata for Create action.
*
* The metadata is used for setting defaults, documentation & validation.
*
* @param array $params
* Array of parameters determined by getfields.
*/
function _civicrm_api3_financial_trxn_create_spec(&$params) {
$params['to_financial_account_id']['api.required'] = 1;
$params['status_id']['api.required'] = 1;
$params['payment_instrument_id']['api.required'] = 1;
$params['total_amount']['api.required'] = 1;
}

View file

@ -0,0 +1,67 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
* This api exposes CiviCRM FinancialType.
*
* @package CiviCRM_APIv3
*/
/**
* Save a FinancialType.
*
* @param array $params
*
* @return array
*/
function civicrm_api3_financial_type_create($params) {
return _civicrm_api3_basic_create(_civicrm_api3_get_BAO(__FUNCTION__), $params);
}
/**
* Get a FinancialType.
*
* @param array $params
*
* @return array
* Array of retrieved FinancialType property values.
*/
function civicrm_api3_financial_type_get($params) {
return _civicrm_api3_basic_get(_civicrm_api3_get_BAO(__FUNCTION__), $params);
}
/**
* Delete a FinancialType.
*
* @param array $params
*
* @return array
* Array of deleted values.
*/
function civicrm_api3_financial_type_delete($params) {
return _civicrm_api3_basic_delete(_civicrm_api3_get_BAO(__FUNCTION__), $params);
}

View file

@ -0,0 +1,527 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
* @package CiviCRM_APIv3
*/
/**
* Get information about fields for a given api request.
*
* Getfields information is used for documentation, validation, default setting
* We first query the scheme using the $dao->fields function & then augment
* that information by calling the _spec functions that apply to the relevant function
* Note that we use 'unique' field names as described in the xml/schema files
* for get requests & just field name for create. This is because some get functions
* access multiple objects e.g. contact api accesses is_deleted from the activity
* table & from the contact table
*
* @param array $apiRequest
* Api request as an array. Keys are.
* - entity: string
* - action: string
* - version: string
* - function: callback (mixed)
* - params: array, varies
*
* @param bool $unique
* Determines whether to key by unique field names (only affects get-type) actions
*
* @return array
* API success object
*/
function civicrm_api3_generic_getfields($apiRequest, $unique = TRUE) {
static $results = array();
if ((CRM_Utils_Array::value('cache_clear', $apiRequest['params']))) {
$results = array();
// we will also clear pseudoconstants here - should potentially be moved to relevant BAO classes
CRM_Core_PseudoConstant::flush();
if (!empty($apiRequest['params']['fieldname'])) {
CRM_Utils_PseudoConstant::flushConstant($apiRequest['params']['fieldname']);
}
if (!empty($apiRequest['params']['option_group_id'])) {
$optionGroupName = civicrm_api('option_group', 'getvalue', array(
'version' => 3,
'id' => $apiRequest['params']['option_group_id'],
'return' => 'name',
));
if (is_string($optionGroupName)) {
CRM_Utils_PseudoConstant::flushConstant(_civicrm_api_get_camel_name($optionGroupName));
}
}
}
$entity = $apiRequest['entity'];
$lowercase_entity = _civicrm_api_get_entity_name_from_camel($entity);
$subentity = CRM_Utils_Array::value('contact_type', $apiRequest['params']);
$action = CRM_Utils_Array::value('action', $apiRequest['params']);
$sequential = empty($apiRequest['params']['sequential']) ? 0 : 1;
$apiRequest['params']['options'] = CRM_Utils_Array::value('options', $apiRequest['params'], array());
$optionsToResolve = (array) CRM_Utils_Array::value('get_options', $apiRequest['params']['options'], array());
if (!$action || $action == 'getvalue' || $action == 'getcount') {
$action = 'get';
}
// If no options, return results from cache
if (!$apiRequest['params']['options'] && isset($results[$entity . $subentity]) && isset($action, $results[$entity . $subentity])
&& isset($action, $results[$entity . $subentity][$sequential])) {
return $results[$entity . $subentity][$action][$sequential];
}
// defaults based on data model and API policy
switch ($action) {
case 'getfields':
$values = _civicrm_api_get_fields($entity, FALSE, $apiRequest['params']);
return civicrm_api3_create_success($values, $apiRequest['params'], $entity, 'getfields');
case 'create':
case 'update':
case 'replace':
$unique = FALSE;
case 'get':
case 'getsingle':
case 'getcount':
case 'getstat':
$metadata = _civicrm_api_get_fields($apiRequest['entity'], $unique, $apiRequest['params']);
if (empty($metadata['id'])) {
// if id is not set we will set it eg. 'id' from 'case_id', case_id will be an alias
if (!empty($metadata[strtolower($apiRequest['entity']) . '_id'])) {
$metadata['id'] = $metadata[$lowercase_entity . '_id'];
unset($metadata[$lowercase_entity . '_id']);
$metadata['id']['api.aliases'] = array($lowercase_entity . '_id');
}
}
else {
// really the preference would be to set the unique name in the xml
// question is which is a less risky fix this close to a release - setting in xml for the known failure
// (note) or setting for all api where fields is returning 'id' & we want to accept 'note_id' @ the api layer
// nb we don't officially accept note_id anyway - rationale here is more about centralising a now-tested
// inconsistency
$metadata['id']['api.aliases'] = array($lowercase_entity . '_id');
}
break;
case 'delete':
$metadata = array(
'id' => array(
'title' => $entity . ' ID',
'api.required' => 1,
'api.aliases' => array($lowercase_entity . '_id'),
'type' => CRM_Utils_Type::T_INT,
));
break;
// Note: adding setvalue case here instead of in a generic spec function because
// some APIs override the generic setvalue fn which causes the generic spec to be overlooked.
case 'setvalue':
$metadata = array(
'field' => array(
'title' => 'Field name',
'api.required' => 1,
'type' => CRM_Utils_Type::T_STRING,
),
'id' => array(
'title' => $entity . ' ID',
'api.required' => 1,
'type' => CRM_Utils_Type::T_INT,
),
'value' => array(
'title' => 'Value',
'description' => "Field value to set",
'api.required' => 1,
),
);
if (array_intersect(array('all', 'field'), $optionsToResolve)) {
$options = civicrm_api3_generic_getfields(array('entity' => $entity, array('params' => array('action' => 'create'))));
$metadata['field']['options'] = CRM_Utils_Array::collect('title', $options['values']);
}
break;
default:
// oddballs are on their own
$metadata = array();
}
// Hack for product api to pass tests.
if (!is_string($apiRequest['params']['options'])) {
// Normalize this for the sake of spec funcions
$apiRequest['params']['options']['get_options'] = $optionsToResolve;
}
// find any supplemental information
$hypApiRequest = array('entity' => $apiRequest['entity'], 'action' => $action, 'version' => $apiRequest['version']);
if ($action == 'getsingle') {
$hypApiRequest['action'] = 'get';
}
try {
list ($apiProvider, $hypApiRequest) = \Civi::service('civi_api_kernel')->resolve($hypApiRequest);
if (isset($hypApiRequest['function'])) {
$helper = '_' . $hypApiRequest['function'] . '_spec';
}
else {
// not implemented MagicFunctionProvider
$helper = NULL;
}
}
catch (\Civi\API\Exception\NotImplementedException $e) {
$helper = NULL;
}
if (function_exists($helper)) {
// alter
$helper($metadata, $apiRequest);
}
foreach ($metadata as $fieldname => $fieldSpec) {
// Ensure 'name' is set
if (!isset($fieldSpec['name'])) {
$metadata[$fieldname]['name'] = $fieldname;
}
_civicrm_api3_generic_get_metadata_options($metadata, $apiRequest, $fieldname, $fieldSpec);
// Convert options to "sequential" format
if ($sequential && !empty($metadata[$fieldname]['options'])) {
$metadata[$fieldname]['options'] = CRM_Utils_Array::makeNonAssociative($metadata[$fieldname]['options']);
}
}
$results[$entity][$action][$sequential] = civicrm_api3_create_success($metadata, $apiRequest['params'], $entity, 'getfields');
return $results[$entity][$action][$sequential];
}
/**
* Get metadata for a field
*
* @param array $apiRequest
*
* @return array
* API success object
*/
function civicrm_api3_generic_getfield($apiRequest) {
$params = $apiRequest['params'];
$sequential = !empty($params['sequential']);
$fieldName = _civicrm_api3_api_resolve_alias($apiRequest['entity'], $params['name'], $params['action']);
if (!$fieldName) {
return civicrm_api3_create_error("The field '{$params['name']}' doesn't exist.");
}
// Turn off sequential to make the field easier to find
$apiRequest['params']['sequential'] = 0;
if (isset($params['get_options'])) {
$apiRequest['params']['options']['get_options_context'] = $params['get_options'];
$apiRequest['params']['options']['get_options'] = $fieldName;
}
$result = civicrm_api3_generic_getfields($apiRequest, FALSE);
$result = $result['values'][$fieldName];
// Fix sequential options since we forced it off
if ($sequential && !empty($result['options'])) {
$result['options'] = CRM_Utils_Array::makeNonAssociative($result['options']);
}
return civicrm_api3_create_success($result, $apiRequest['params'], $apiRequest['entity'], 'getfield');
}
/**
* Get metadata for getfield action.
*
* @param array $params
* @param array $apiRequest
*
* @throws \CiviCRM_API3_Exception
* @throws \Exception
*/
function _civicrm_api3_generic_getfield_spec(&$params, $apiRequest) {
$params = array(
'name' => array(
'title' => 'Field name',
'description' => 'Name or alias of field to lookup',
'api.required' => 1,
'type' => CRM_Utils_Type::T_STRING,
),
'action' => array(
'title' => 'API Action',
'api.required' => 1,
'type' => CRM_Utils_Type::T_STRING,
'api.aliases' => array('api_action'),
),
'get_options' => array(
'title' => 'Get Options',
'description' => 'Context for which to get field options, or null to skip fetching options.',
'type' => CRM_Utils_Type::T_STRING,
'options' => CRM_Core_DAO::buildOptionsContext(),
'api.aliases' => array('context'),
),
);
// Add available options to these params if requested
if (array_intersect(array('all', 'action'), $apiRequest['params']['options']['get_options'])) {
$actions = civicrm_api3($apiRequest['entity'], 'getactions');
$actions = array_combine($actions['values'], $actions['values']);
// Let's not go meta-crazy
CRM_Utils_Array::remove($actions, 'getactions', 'getoptions', 'getfields', 'getfield', 'getcount', 'getrefcount', 'getsingle', 'getlist', 'getvalue', 'setvalue', 'update');
$params['action']['options'] = $actions;
}
}
/**
* API return function to reformat results as count.
*
* @param array $apiRequest
* Api request as an array. Keys are.
*
* @throws API_Exception
* @return int
* count of results
*/
function civicrm_api3_generic_getcount($apiRequest) {
$apiRequest['params']['options']['is_count'] = TRUE;
$result = civicrm_api($apiRequest['entity'], 'get', $apiRequest['params']);
if (is_numeric(CRM_Utils_Array::value('values', $result))) {
return (int) $result['values'];
}
if (!isset($result['count'])) {
throw new API_Exception(ts('Unexpected result from getcount') . print_r($result, TRUE));
}
return $result['count'];
}
/**
* API return function to reformat results as single result.
*
* @param array $apiRequest
* Api request as an array. Keys are.
*
* @return int
* count of results
*/
function civicrm_api3_generic_getsingle($apiRequest) {
// So the first entity is always result['values'][0].
$apiRequest['params']['sequential'] = 1;
$result = civicrm_api($apiRequest['entity'], 'get', $apiRequest['params']);
if ($result['is_error'] !== 0) {
return $result;
}
if ($result['count'] === 1) {
return $result['values'][0];
}
if ($result['count'] !== 1) {
return civicrm_api3_create_error("Expected one " . $apiRequest['entity'] . " but found " . $result['count'], array('count' => $result['count']));
}
return civicrm_api3_create_error("Undefined behavior");
}
/**
* API return function to reformat results as single value.
*
* @param array $apiRequest
* Api request as an array. Keys are.
*
* @return int
* count of results
*/
function civicrm_api3_generic_getvalue($apiRequest) {
$apiRequest['params']['sequential'] = 1;
$result = civicrm_api($apiRequest['entity'], 'get', $apiRequest['params']);
if ($result['is_error'] !== 0) {
return $result;
}
if ($result['count'] !== 1) {
$result = civicrm_api3_create_error("Expected one " . $apiRequest['entity'] . " but found " . $result['count'], array('count' => $result['count']));
return $result;
}
// we only take "return=" as valid options
if (!empty($apiRequest['params']['return'])) {
if (!isset($result['values'][0][$apiRequest['params']['return']])) {
return civicrm_api3_create_error("field " . $apiRequest['params']['return'] . " unset or not existing", array('invalid_field' => $apiRequest['params']['return']));
}
return $result['values'][0][$apiRequest['params']['return']];
}
return civicrm_api3_create_error("missing param return=field you want to read the value of", array('error_type' => 'mandatory_missing', 'missing_param' => 'return'));
}
/**
* Get count of contact references.
*
* @param array $params
* @param array $apiRequest
*/
function _civicrm_api3_generic_getrefcount_spec(&$params, $apiRequest) {
$params['id']['api.required'] = 1;
$params['id']['title'] = $apiRequest['entity'] . ' ID';
$params['id']['type'] = CRM_Utils_Type::T_INT;
}
/**
* API to determine if a record is in-use.
*
* @param array $apiRequest
* Api request as an array.
*
* @throws API_Exception
* @return array
* API result (int 0 or 1)
*/
function civicrm_api3_generic_getrefcount($apiRequest) {
$entityToClassMap = CRM_Core_DAO_AllCoreTables::daoToClass();
if (!isset($entityToClassMap[$apiRequest['entity']])) {
throw new API_Exception("The entity '{$apiRequest['entity']}' is unknown or unsupported by 'getrefcount'. Consider implementing this API.", 'getrefcount_unsupported');
}
$daoClass = $entityToClassMap[$apiRequest['entity']];
/* @var $dao CRM_Core_DAO */
$dao = new $daoClass();
$dao->id = $apiRequest['params']['id'];
if ($dao->find(TRUE)) {
return civicrm_api3_create_success($dao->getReferenceCounts());
}
else {
return civicrm_api3_create_success(array());
}
}
/**
* API wrapper for replace function.
*
* @param array $apiRequest
* Api request as an array. Keys are.
*
* @return int
* count of results
*/
function civicrm_api3_generic_replace($apiRequest) {
return _civicrm_api3_generic_replace($apiRequest['entity'], $apiRequest['params']);
}
/**
* API wrapper for getoptions function.
*
* @param array $apiRequest
* Api request as an array.
*
* @return array
* Array of results
*/
function civicrm_api3_generic_getoptions($apiRequest) {
// Resolve aliases.
$fieldName = _civicrm_api3_api_resolve_alias($apiRequest['entity'], $apiRequest['params']['field']);
if (!$fieldName) {
return civicrm_api3_create_error("The field '{$apiRequest['params']['field']}' doesn't exist.");
}
// Validate 'context' from params
$context = CRM_Utils_Array::value('context', $apiRequest['params']);
CRM_Core_DAO::buildOptionsContext($context);
unset($apiRequest['params']['context'], $apiRequest['params']['field']);
$baoName = _civicrm_api3_get_BAO($apiRequest['entity']);
$options = $baoName::buildOptions($fieldName, $context, $apiRequest['params']);
if ($options === FALSE) {
return civicrm_api3_create_error("The field '{$fieldName}' has no associated option list.");
}
// Support 'sequential' output as a non-associative array
if (!empty($apiRequest['params']['sequential'])) {
$options = CRM_Utils_Array::makeNonAssociative($options);
}
return civicrm_api3_create_success($options, $apiRequest['params'], $apiRequest['entity'], 'getoptions');
}
/**
* Provide metadata for this generic action
*
* @param $params
* @param $apiRequest
*/
function _civicrm_api3_generic_getoptions_spec(&$params, $apiRequest) {
$params += array(
'field' => array(
'title' => 'Field name',
'api.required' => 1,
'type' => CRM_Utils_Type::T_STRING,
),
'context' => array(
'title' => 'Context',
'type' => CRM_Utils_Type::T_STRING,
'options' => CRM_Core_DAO::buildOptionsContext(),
),
);
// Add available fields if requested
if (array_intersect(array('all', 'field'), $apiRequest['params']['options']['get_options'])) {
$fields = civicrm_api3_generic_getfields(array('entity' => $apiRequest['entity'], array('params' => array('action' => 'create'))));
$params['field']['options'] = array();
foreach ($fields['values'] as $name => $field) {
if (isset($field['pseudoconstant']) || CRM_Utils_Array::value('type', $field) == CRM_Utils_Type::T_BOOLEAN) {
$params['field']['options'][$name] = CRM_Utils_Array::value('title', $field, $name);
}
}
}
}
/**
* Get metadata.
*
* Function fills the 'options' array on the metadata returned by getfields if
* 1) the param option 'get_options' is defined - e.g. $params['options']['get_options'] => array('custom_1)
* (this is passed in as the $fieldsToResolve array)
* 2) the field is a pseudoconstant and is NOT an FK
* - the reason for this is that checking / transformation is done on pseudoconstants but
* - if the field is an FK then mysql will enforce the data quality (& we have handling on failure)
* @todo - if may be we should define a 'resolve' key on the pseudoconstant for when these rules are not fine enough
*
* This function is only split out for the purpose of code clarity / comment block documentation
*
* @param array $metadata
* The array of metadata that will form the result of the getfields function.
* @param array $apiRequest
* @param string $fieldname
* Field currently being processed.
* @param array $fieldSpec
* Metadata for that field.
*/
function _civicrm_api3_generic_get_metadata_options(&$metadata, $apiRequest, $fieldname, $fieldSpec) {
if (empty($fieldSpec['pseudoconstant']) && empty($fieldSpec['option_group_id'])) {
return;
}
$fieldsToResolve = $apiRequest['params']['options']['get_options'];
if (!empty($metadata[$fieldname]['options']) || (!in_array($fieldname, $fieldsToResolve) && !in_array('all', $fieldsToResolve))) {
return;
}
// Allow caller to specify context
$context = CRM_Utils_Array::value('get_options_context', $apiRequest['params']['options']);
// Default to api action if it is a supported context.
if (!$context) {
$action = CRM_Utils_Array::value('action', $apiRequest['params']);
$contexts = CRM_Core_DAO::buildOptionsContext();
if (isset($contexts[$action])) {
$context = $action;
}
}
$options = civicrm_api($apiRequest['entity'], 'getoptions', array('version' => 3, 'field' => $fieldname, 'context' => $context));
if (is_array(CRM_Utils_Array::value('values', $options))) {
$metadata[$fieldname]['options'] = $options['values'];
}
}

View file

@ -0,0 +1,45 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
* @package CiviCRM_APIv3
*/
/**
* Get available api actions.
*
* @param array $apiRequest
*
* @return array
* @throws API_Exception
*/
function civicrm_api3_generic_getActions($apiRequest) {
civicrm_api3_verify_mandatory($apiRequest, NULL, array('entity'));
$mfp = \Civi::service('magic_function_provider');
$actions = $mfp->getActionNames($apiRequest['version'], $apiRequest['entity']);
return civicrm_api3_create_success($actions, $apiRequest['params'], $apiRequest['entity'], 'getactions');
}

View file

@ -0,0 +1,290 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
* @package CiviCRM_APIv3
*/
/**
* Generic api wrapper used for quicksearch and autocomplete.
*
* @param array $apiRequest
*
* @return mixed
*/
function civicrm_api3_generic_getList($apiRequest) {
$entity = _civicrm_api_get_entity_name_from_camel($apiRequest['entity']);
$request = $apiRequest['params'];
$meta = civicrm_api3_generic_getfields(array('action' => 'get') + $apiRequest, FALSE);
// Hey api, would you like to provide default values?
$fnName = "_civicrm_api3_{$entity}_getlist_defaults";
$defaults = function_exists($fnName) ? $fnName($request) : array();
_civicrm_api3_generic_getList_defaults($entity, $request, $defaults, $meta['values']);
// Hey api, would you like to format the search params?
$fnName = "_civicrm_api3_{$entity}_getlist_params";
$fnName = function_exists($fnName) ? $fnName : '_civicrm_api3_generic_getlist_params';
$fnName($request);
$request['params']['check_permissions'] = !empty($apiRequest['params']['check_permissions']);
$result = civicrm_api3($entity, 'get', $request['params']);
// Hey api, would you like to format the output?
$fnName = "_civicrm_api3_{$entity}_getlist_output";
$fnName = function_exists($fnName) ? $fnName : '_civicrm_api3_generic_getlist_output';
$values = $fnName($result, $request, $entity, $meta['values']);
_civicrm_api3_generic_getlist_postprocess($result, $request, $values);
$output = array('page_num' => $request['page_num']);
// Limit is set for searching but not fetching by id
if (!empty($request['params']['options']['limit'])) {
// If we have an extra result then this is not the last page
$last = $request['params']['options']['limit'] - 1;
$output['more_results'] = isset($values[$last]);
unset($values[$last]);
}
return civicrm_api3_create_success($values, $request['params'], $entity, 'getlist', CRM_Core_DAO::$_nullObject, $output);
}
/**
* Set defaults for api.getlist.
*
* @param string $entity
* @param array $request
* @param array $apiDefaults
* @param array $fields
*/
function _civicrm_api3_generic_getList_defaults($entity, &$request, $apiDefaults, $fields) {
$defaults = array(
'page_num' => 1,
'input' => '',
'image_field' => NULL,
'color_field' => isset($fields['color']) ? 'color' : NULL,
'id_field' => $entity == 'option_value' ? 'value' : 'id',
'description_field' => array(),
'add_wildcard' => Civi::settings()->get('includeWildCardInName'),
'params' => array(),
'extra' => array(),
);
// Find main field from meta
foreach (array('sort_name', 'title', 'label', 'name', 'subject') as $field) {
if (isset($fields[$field])) {
$defaults['label_field'] = $defaults['search_field'] = $field;
break;
}
}
// Find fields to be used for the description
foreach (array('description') as $field) {
if (isset($fields[$field])) {
$defaults['description_field'][] = $field;
}
}
$resultsPerPage = Civi::settings()->get('search_autocomplete_count');
if (isset($request['params']) && isset($apiDefaults['params'])) {
$request['params'] += $apiDefaults['params'];
}
$request += $apiDefaults + $defaults;
// Default api params
$params = array(
'sequential' => 1,
'options' => array(),
);
// When searching e.g. autocomplete
if ($request['input']) {
$params[$request['search_field']] = array('LIKE' => ($request['add_wildcard'] ? '%' : '') . $request['input'] . '%');
}
// When looking up a field e.g. displaying existing record
if (!empty($request['id'])) {
if (is_string($request['id']) && strpos($request['id'], ',')) {
$request['id'] = explode(',', trim($request['id'], ', '));
}
// Don't run into search limits when prefilling selection
$params['options']['limit'] = NULL;
unset($params['options']['offset'], $request['params']['options']['limit'], $request['params']['options']['offset']);
$params[$request['id_field']] = is_array($request['id']) ? array('IN' => $request['id']) : $request['id'];
}
$request['params'] += $params;
$request['params']['options'] += array(
// Add pagination parameters
'sort' => $request['label_field'],
// Adding one extra result allows us to see if there are any more
'limit' => $resultsPerPage + 1,
// Because sql is zero-based
'offset' => ($request['page_num'] - 1) * $resultsPerPage,
);
}
/**
* Fallback implementation of getlist_params. May be overridden by individual apis.
*
* @param array $request
*/
function _civicrm_api3_generic_getlist_params(&$request) {
$fieldsToReturn = array($request['id_field'], $request['label_field']);
if (!empty($request['image_field'])) {
$fieldsToReturn[] = $request['image_field'];
}
if (!empty($request['color_field'])) {
$fieldsToReturn[] = $request['color_field'];
}
if (!empty($request['description_field'])) {
$fieldsToReturn = array_merge($fieldsToReturn, (array) $request['description_field']);
}
$request['params']['return'] = array_unique(array_merge($fieldsToReturn, $request['extra']));
}
/**
* Fallback implementation of getlist_output. May be overridden by individual api functions.
*
* @param array $result
* @param array $request
* @param string $entity
* @param array $fields
*
* @return array
*/
function _civicrm_api3_generic_getlist_output($result, $request, $entity, $fields) {
$output = array();
if (!empty($result['values'])) {
foreach ($result['values'] as $row) {
$data = array(
'id' => $row[$request['id_field']],
'label' => $row[$request['label_field']],
);
if (!empty($request['description_field'])) {
$data['description'] = array();
foreach ((array) $request['description_field'] as $field) {
if (!empty($row[$field])) {
if (!isset($fields[$field]['pseudoconstant'])) {
$data['description'][] = $row[$field];
}
else {
$data['description'][] = CRM_Core_PseudoConstant::getLabel(
_civicrm_api3_get_BAO($entity),
$field,
$row[$field]
);
}
}
}
};
if (!empty($request['image_field'])) {
$data['image'] = isset($row[$request['image_field']]) ? $row[$request['image_field']] : '';
}
if (isset($row[$request['color_field']])) {
$data['color'] = $row[$request['color_field']];
}
$output[] = $data;
}
}
return $output;
}
/**
* Common postprocess for getlist output
*
* @param $result
* @param $request
* @param $values
*/
function _civicrm_api3_generic_getlist_postprocess($result, $request, &$values) {
$chains = array();
foreach ($request['params'] as $field => $param) {
if (substr($field, 0, 4) === 'api.') {
$chains[] = $field;
}
}
if (!empty($result['values'])) {
foreach (array_values($result['values']) as $num => $row) {
foreach ($request['extra'] as $field) {
$values[$num]['extra'][$field] = isset($row[$field]) ? $row[$field] : NULL;
}
foreach ($chains as $chain) {
$values[$num][$chain] = isset($row[$chain]) ? $row[$chain] : NULL;
}
}
}
}
/**
* Provide metadata for this api
*
* @param array $params
* @param array $apiRequest
*/
function _civicrm_api3_generic_getlist_spec(&$params, $apiRequest) {
$params += array(
'page_num' => array(
'title' => 'Page Number',
'description' => "Current page of a multi-page lookup",
'type' => CRM_Utils_Type::T_INT,
),
'input' => array(
'title' => 'Search Input',
'description' => "String to search on",
'type' => CRM_Utils_Type::T_TEXT,
),
'params' => array(
'title' => 'API Params',
'description' => "Additional filters to send to the {$apiRequest['entity']} API.",
),
'extra' => array(
'title' => 'Extra',
'description' => 'Array of additional fields to return.',
),
'image_field' => array(
'title' => 'Image Field',
'description' => "Field that this entity uses to store icons (usually automatic)",
'type' => CRM_Utils_Type::T_TEXT,
),
'id_field' => array(
'title' => 'ID Field',
'description' => "Field that uniquely identifies this entity (usually automatic)",
'type' => CRM_Utils_Type::T_TEXT,
),
'description_field' => array(
'title' => 'Description Field',
'description' => "Field that this entity uses to store summary text (usually automatic)",
'type' => CRM_Utils_Type::T_TEXT,
),
'label_field' => array(
'title' => 'Label Field',
'description' => "Field to display as title of results (usually automatic)",
'type' => CRM_Utils_Type::T_TEXT,
),
'search_field' => array(
'title' => 'Search Field',
'description' => "Field to search on (assumed to be the same as label field unless otherwise specified)",
'type' => CRM_Utils_Type::T_TEXT,
),
);
}

View file

@ -0,0 +1,164 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
* @package CiviCRM_APIv3
*/
/**
* Set a single value using the api.
*
* This function is called when no specific setvalue api exists.
* Params must contain at least id=xx & {one of the fields from getfields}=value
*
* @param array $apiRequest
*
* @throws API_Exception
* @return array
*/
function civicrm_api3_generic_setValue($apiRequest) {
$entity = $apiRequest['entity'];
$params = $apiRequest['params'];
$id = $params['id'];
if (!is_numeric($id)) {
return civicrm_api3_create_error(ts('Please enter a number'), array(
'error_code' => 'NaN',
'field' => "id",
));
}
$field = CRM_Utils_String::munge($params['field']);
$value = $params['value'];
$fields = civicrm_api($entity, 'getFields', array(
'version' => 3,
'action' => 'create',
"sequential")
);
// getfields error, shouldn't happen.
if ($fields['is_error']) {
return $fields;
}
$fields = $fields['values'];
$isCustom = strpos($field, 'custom_') === 0;
// Trim off the id portion of a multivalued custom field name
$fieldKey = $isCustom && substr_count($field, '_') > 1 ? rtrim(rtrim($field, '1234567890'), '_') : $field;
if (!array_key_exists($fieldKey, $fields)) {
return civicrm_api3_create_error("Param 'field' ($field) is invalid. must be an existing field", array("error_code" => "invalid_field", "fields" => array_keys($fields)));
}
$def = $fields[$fieldKey];
$title = CRM_Utils_Array::value('title', $def, ts('Field'));
// Disallow empty values except for the number zero.
// TODO: create a utility for this since it's needed in many places
if (!empty($def['required']) || !empty($def['is_required'])) {
if ((empty($value) || $value === 'null') && $value !== '0' && $value !== 0) {
return civicrm_api3_create_error(ts('%1 is a required field.', array(1 => $title)), array("error_code" => "required", "field" => $field));
}
}
switch ($def['type']) {
case CRM_Utils_Type::T_FLOAT:
if (!is_numeric($value) && !empty($value) && $value !== 'null') {
return civicrm_api3_create_error(ts('%1 must be a number.', array(1 => $title)), array('error_code' => 'NaN'));
}
break;
case CRM_Utils_Type::T_INT:
if (!CRM_Utils_Rule::integer($value) && !empty($value) && $value !== 'null') {
return civicrm_api3_create_error(ts('%1 must be a number.', array(1 => $title)), array('error_code' => 'NaN'));
}
break;
case CRM_Utils_Type::T_STRING:
case CRM_Utils_Type::T_TEXT:
if (!CRM_Utils_Rule::xssString($value)) {
return civicrm_api3_create_error(ts('Illegal characters in input (potential scripting attack)'), array('error_code' => 'XSS'));
}
if (array_key_exists('maxlength', $def)) {
$value = substr($value, 0, $def['maxlength']);
}
break;
case CRM_Utils_Type::T_DATE:
$value = CRM_Utils_Type::escape($value, "Date", FALSE);
if (!$value) {
return civicrm_api3_create_error("Param '$field' is not a date. format YYYYMMDD or YYYYMMDDHHMMSS");
}
break;
case CRM_Utils_Type::T_BOOLEAN:
// Allow empty value for non-required fields
if ($value === '' || $value === 'null') {
$value = '';
}
else {
$value = (boolean) $value;
}
break;
default:
return civicrm_api3_create_error("Param '$field' is of a type not managed yet (" . $def['type'] . "). Join the API team and help us implement it", array('error_code' => 'NOT_IMPLEMENTED'));
}
$dao_name = _civicrm_api3_get_DAO($entity);
$params = array('id' => $id, $field => $value);
if ((!empty($def['pseudoconstant']) || !empty($def['option_group_id'])) && $value !== '' && $value !== 'null') {
_civicrm_api3_api_match_pseudoconstant($params[$field], $entity, $field, $def);
}
CRM_Utils_Hook::pre('edit', $entity, $id, $params);
// Custom fields
if ($isCustom) {
CRM_Utils_Array::crmReplaceKey($params, 'id', 'entityID');
// Treat 'null' as empty value. This is awful but the rest of the code supports it.
if ($params[$field] === 'null') {
$params[$field] = '';
}
CRM_Core_BAO_CustomValueTable::setValues($params);
CRM_Utils_Hook::post('edit', $entity, $id);
}
// Core fields
elseif (CRM_Core_DAO::setFieldValue($dao_name, $id, $field, $params[$field])) {
$entityDAO = new $dao_name();
$entityDAO->copyValues($params);
CRM_Utils_Hook::post('edit', $entity, $entityDAO->id, $entityDAO);
}
else {
return civicrm_api3_create_error("error assigning $field=$value for $entity (id=$id)");
}
// Add changelog entry - TODO: Should we do this for other entities as well?
if (strtolower($entity) === 'contact') {
CRM_Core_BAO_Log::register($id, 'civicrm_contact', $id);
}
return civicrm_api3_create_success($params);
}

View file

@ -0,0 +1,82 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
* @package CiviCRM_APIv3
*/
/**
* Update function is basically a hack.
*
* We want to remove it but must resolve issues in
* http://issues.civicrm.org/jira/browse/CRM-12144
*
* It is not recommended & if update doesn't work & fix does then update will not be fixed
*
* To do this, perform a 'get' action to load the existing values, then merge in the updates
* and call 'create' to save the revised entity.
*
* @deprecated
*
* @param array $apiRequest
* Array with keys:
* - entity: string
* - action: string
* - version: string
* - function: callback (mixed)
* - params: array, varies
*
* @return array|int|mixed
*/
function civicrm_api3_generic_update($apiRequest) {
//$key_id = strtolower ($apiRequest['entity'])."_id";
$key_id = "id";
if (!array_key_exists($key_id, $apiRequest['params'])) {
return civicrm_api3_create_error("Mandatory parameter missing $key_id");
}
// @fixme
// tests show that contribution works better with create
// this is horrible but to make it work we'll just handle it separately
if (strtolower($apiRequest['entity']) == 'contribution') {
return civicrm_api($apiRequest['entity'], 'create', $apiRequest['params']);
}
$seek = array($key_id => $apiRequest['params'][$key_id], 'version' => $apiRequest['version']);
$existing = civicrm_api($apiRequest['entity'], 'get', $seek);
if ($existing['is_error']) {
return $existing;
}
if ($existing['count'] > 1) {
return civicrm_api3_create_error("More than one " . $apiRequest['entity'] . " with id " . $apiRequest['params'][$key_id]);
}
if ($existing['count'] == 0) {
return civicrm_api3_create_error("No " . $apiRequest['entity'] . " with id " . $apiRequest['params'][$key_id]);
}
$existing = array_pop($existing['values']);
$p = array_merge($existing, $apiRequest['params']);
return civicrm_api($apiRequest['entity'], 'create', $p);
}

View file

@ -0,0 +1,53 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
* @package CiviCRM_APIv3
*/
/**
* Provide meta-data for this api.
*
* @param array $params
*/
function _civicrm_api3_generic_validate_spec(&$params) {
$params['action']['api.required'] = TRUE;
$params['action']['title'] = ts('API Action');
}
/**
* Generic api wrapper used for validation of entity-action pair.
*
* @param array $apiRequest
*
* @return mixed
*/
function civicrm_api3_generic_validate($apiRequest) {
$errors = _civicrm_api3_validate($apiRequest['entity'], $apiRequest['params']['action'], $apiRequest['params']);
return civicrm_api3_create_success($errors, $apiRequest['params'], $apiRequest['entity'], 'validate');
}

View file

@ -0,0 +1,88 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
* This api exposes CiviCRM Grant records.
*
* @note Grant component must be enabled.
*
* @package CiviCRM_APIv3
*/
/**
* Create/update Grant.
*
* @param array $params
* Array per getfields metadata.
*
* @return array
*/
function civicrm_api3_grant_create($params) {
return _civicrm_api3_basic_create(_civicrm_api3_get_BAO(__FUNCTION__), $params, 'Grant');
}
/**
* Adjust Metadata for Create action.
*
* The metadata is used for setting defaults, documentation & validation.
*
* @param array $params
* Array of parameters determined by getfields.
*/
function _civicrm_api3_grant_create_spec(&$params) {
$params['contact_id']['api.required'] = 1;
$params['grant_type_id']['api.required'] = 1;
$params['status_id']['api.required'] = 1;
$params['amount_total']['api.required'] = 1;
$params['status_id']['api.aliases'] = array('grant_status');
}
/**
* Returns array of grants matching a set of one or more properties.
*
* @param array $params
* Array per getfields metadata.
*
* @return array
* Array of matching grants
*/
function civicrm_api3_grant_get($params) {
return _civicrm_api3_basic_get(_civicrm_api3_get_BAO(__FUNCTION__), $params, TRUE, 'Grant');
}
/**
* This method is used to delete an existing Grant.
*
* @param array $params
* Id of the Grant to be deleted is required.
*
* @return array
* API Result Array
*/
function civicrm_api3_grant_delete($params) {
return _civicrm_api3_basic_delete(_civicrm_api3_get_BAO(__FUNCTION__), $params);
}

View file

@ -0,0 +1,107 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
* This api exposes CiviCRM Groups.
*
* This api is for creating/deleting groups or fetching a list of existing groups.
* To add/remove contacts to a group, use the GroupContact api instead.
*
* @package CiviCRM_APIv3
*/
/**
* Create/update group.
*
* @param array $params
* name/value pairs to insert in new 'Group'
*
* @return array
* API result array
*/
function civicrm_api3_group_create($params) {
return _civicrm_api3_basic_create(_civicrm_api3_get_BAO(__FUNCTION__), $params, 'Group');
}
/**
* Adjust Metadata for Create action.
*
* The metadata is used for setting defaults, documentation & validation.
*
* @param array $params
* Array of parameters determined by getfields.
*/
function _civicrm_api3_group_create_spec(&$params) {
$params['is_active']['api.default'] = 1;
$params['title']['api.required'] = 1;
}
/**
* Returns array of groups matching a set of one or more Group properties.
*
* @param array $params
* Array of properties. If empty, all records will be returned.
*
* @return array
* Array of matching groups
*/
function civicrm_api3_group_get($params) {
$options = _civicrm_api3_get_options_from_params($params, TRUE, 'Group', 'get');
if ($options['is_count']) {
$params['options']['is_count'] = 0;
$params['return'] = 'id';
}
$groups = _civicrm_api3_basic_get(_civicrm_api3_get_BAO(__FUNCTION__), $params, FALSE, 'Group');
foreach ($groups as $id => $group) {
if (!empty($params['check_permissions']) && !CRM_Contact_BAO_Group::checkPermission($group['id'])) {
unset($groups[$id]);
}
if (!empty($options['return']) && in_array('member_count', $options['return'])) {
$groups[$id]['member_count'] = CRM_Contact_BAO_Group::memberCount($id);
}
}
return civicrm_api3_create_success($groups, $params, 'Group', 'get');
}
/**
* Delete an existing Group.
*
* @param array $params
* [id]
* @return array API result array
* @throws API_Exception
*/
function civicrm_api3_group_delete($params) {
$group = civicrm_api3_group_get(array('id' => $params['id']));
if ($group['count'] == 0) {
throw new API_Exception('Could not delete group ' . $params['id']);
}
CRM_Contact_BAO_Group::discard($params['id']);
return civicrm_api3_create_success(TRUE);
}

View file

@ -0,0 +1,314 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
* This api exposes CiviCRM GroupContact records.
*
* This api is for adding/removing contacts from a group,
* or fetching a list of groups for a contact.
*
* Important note: This api does not fetch smart groups for a contact.
* To fetch all contacts in a smart group, use the Contact api
* passing a contact_id and group_id.
*
* To create/delete groups, use the group api instead.
*
* @package CiviCRM_APIv3
*/
/**
* Fetch a list of groups for a contact, or contacts for a group.
*
* @Note: this only applies to static groups, not smart groups.
* To fetch all contacts in a smart group, use the Contact api
* passing a contact_id and group_id.
*
* If no status mentioned in params, by default 'added' will be used
* to fetch the records
*
* @param array $params
* Name value pair of contact information.
*
* @return array
* list of groups, given contact subsribed to
*/
function civicrm_api3_group_contact_get($params) {
if (empty($params['contact_id'])) {
if (empty($params['status'])) {
//default to 'Added'
$params['status'] = 'Added';
}
//ie. id passed in so we have to return something
return _civicrm_api3_basic_get(_civicrm_api3_get_BAO(__FUNCTION__), $params);
}
$status = CRM_Utils_Array::value('status', $params, 'Added');
$groupId = CRM_Utils_Array::value('group_id', $params);
$values = CRM_Contact_BAO_GroupContact::getContactGroup($params['contact_id'], $status, NULL, FALSE, TRUE, FALSE, TRUE, $groupId);
return civicrm_api3_create_success($values, $params, 'GroupContact');
}
/**
* Adjust metadata for Create action.
*
* @param array $params
*/
function _civicrm_api3_group_contact_create_spec(&$params) {
$params['contact_id']['api.required'] = 1;
$params['group_id']['api.required'] = 1;
}
/**
* Add contact(s) to group(s).
*
* This api has a legacy/nonstandard signature.
* On success, the return array will be structured as follows:
* @code
* array(
* "is_error" => 0,
* "version" => 3,
* "count" => 3,
* "values" => array(
* "not_added" => integer,
* "added" => integer,
* "total_count" => integer
* )
* )
* @endcode
*
* On failure, the return array will be structured as follows:
* @code
* array(
* 'is_error' => 1,
* 'error_message' = string,
* 'error_data' = mixed or undefined
* )
* @endcode
*
* @param array $params
* Input parameters:
* - "contact_id" (required): First contact to add, or array of Contact IDs
* - "group_id" (required): First group to add contact(s) to, or array of Group IDs
* - "status" (optional): "Added" (default), "Pending" or "Removed"
* Legacy input parameters (will be deprecated):
* - "contact_id.1" etc. (optional): Additional contact_id to add to group(s)
* - "group_id.1" etc. (optional): Additional groups to add contact(s) to
*
* @return array
* Information about operation results
*/
function civicrm_api3_group_contact_create($params) {
// Nonstandard bao - doesn't accept ID as a param, so convert id to group_id + contact_id
if (!empty($params['id'])) {
$getParams = array('id' => $params['id']);
$info = _civicrm_api3_basic_get(_civicrm_api3_get_BAO(__FUNCTION__), $getParams);
if (!empty($info['values'][$params['id']])) {
$params['group_id'] = $info['values'][$params['id']]['group_id'];
$params['contact_id'] = $info['values'][$params['id']]['contact_id'];
}
}
$action = CRM_Utils_Array::value('status', $params, 'Added');
return _civicrm_api3_group_contact_common($params, $action);
}
/**
* Delete group contact record.
*
* @param array $params
* @return array
* @throws API_Exception
* @throws CiviCRM_API3_Exception
* @deprecated
*/
function civicrm_api3_group_contact_delete($params) {
$checkParams = $params;
if (!empty($checkParams['status']) && in_array($checkParams['status'], array('Removed', 'Deleted'))) {
$checkParams['status'] = array('IN' => array('Added', 'Pending'));
}
elseif (!empty($checkParams['status']) && $checkParams['status'] == 'Added') {
$checkParams['status'] = array('IN' => array('Pending', 'Removed'));
}
elseif (!empty($checkParams['status'])) {
unset($checkParams['status']);
}
$groupContact = civicrm_api3('GroupContact', 'get', $checkParams);
if ($groupContact['count'] == 0 && !empty($params['skip_undelete'])) {
$checkParams['status'] = array('IN' => array('Removed', 'Pending'));
}
$groupContact2 = civicrm_api3('GroupContact', 'get', $checkParams);
if ($groupContact['count'] == 0 && $groupContact2['count'] == 0) {
throw new API_Exception('Cannot Delete GroupContact');
}
$params['status'] = CRM_Utils_Array::value('status', $params, empty($params['skip_undelete']) ? 'Removed' : 'Deleted');
// "Deleted" isn't a real option so skip the api wrapper to avoid pseudoconstant validation
return civicrm_api3_group_contact_create($params);
}
/**
* Adjust metadata.
*
* @param array $params
*/
function _civicrm_api3_group_contact_delete_spec(&$params) {
// set as not required no either/or std yet
$params['id']['api.required'] = 0;
}
/**
* Get pending group contacts.
*
* @param array $params
*
* @return array|int
* @deprecated
*/
function civicrm_api3_group_contact_pending($params) {
$params['status'] = 'Pending';
return civicrm_api('GroupContact', 'Create', $params);
}
/**
* Group contact helper function.
*
* @todo behaviour is highly non-standard - need to figure out how to make this 'behave'
* & at the very least return IDs & details of the groups created / changed
*
* @param array $params
* @param string $op
*
* @return array
*/
function _civicrm_api3_group_contact_common($params, $op = 'Added') {
$contactIDs = array();
$groupIDs = array();
// CRM-16959: Handle multiple Contact IDs and Group IDs in legacy format
// (contact_id.1, contact_id.2) or as an array
foreach ($params as $n => $v) {
if (substr($n, 0, 10) == 'contact_id') {
if (is_array($v)) {
foreach ($v as $arr_v) {
$contactIDs[] = $arr_v;
}
}
else {
$contactIDs[] = $v;
}
}
elseif (substr($n, 0, 8) == 'group_id') {
if (is_array($v)) {
foreach ($v as $arr_v) {
$groupIDs[] = $arr_v;
}
}
else {
$groupIDs[] = $v;
}
}
}
$method = CRM_Utils_Array::value('method', $params, 'API');
$status = CRM_Utils_Array::value('status', $params, $op);
$tracking = CRM_Utils_Array::value('tracking', $params);
if ($op == 'Added' || $op == 'Pending') {
$extraReturnValues = array(
'total_count' => 0,
'added' => 0,
'not_added' => 0,
);
foreach ($groupIDs as $groupID) {
list($tc, $a, $na) = CRM_Contact_BAO_GroupContact::addContactsToGroup($contactIDs,
$groupID,
$method,
$status,
$tracking
);
$extraReturnValues['total_count'] += $tc;
$extraReturnValues['added'] += $a;
$extraReturnValues['not_added'] += $na;
}
}
else {
$extraReturnValues = array(
'total_count' => 0,
'removed' => 0,
'not_removed' => 0,
);
foreach ($groupIDs as $groupID) {
list($tc, $r, $nr) = CRM_Contact_BAO_GroupContact::removeContactsFromGroup($contactIDs, $groupID, $method, $status, $tracking);
$extraReturnValues['total_count'] += $tc;
$extraReturnValues['removed'] += $r;
$extraReturnValues['not_removed'] += $nr;
}
}
// can't pass this by reference
$dao = NULL;
return civicrm_api3_create_success(1, $params, 'GroupContact', 'create', $dao, $extraReturnValues);
}
/**
* Update group contact status.
*
* @deprecated - this should be part of create but need to know we aren't missing something
*
* @param array $params
*
* @return bool
* @throws \API_Exception
*/
function civicrm_api3_group_contact_update_status($params) {
civicrm_api3_verify_mandatory($params, NULL, array('contact_id', 'group_id'));
CRM_Contact_BAO_GroupContact::addContactsToGroup(
array($params['contact_id']),
$params['group_id'],
CRM_Utils_Array::value('method', $params, 'API'),
'Added',
CRM_Utils_Array::value('tracking', $params)
);
return TRUE;
}
/**
* Deprecated function notices.
*
* @deprecated api notice
* @return array
* Array of deprecated actions
*/
function _civicrm_api3_group_contact_deprecation() {
return array(
'delete' => 'GroupContact "delete" action is deprecated in favor of "create".',
'pending' => 'GroupContact "pending" action is deprecated in favor of "create".',
'update_status' => 'GroupContact "update_status" action is deprecated in favor of "create".',
);
}

View file

@ -0,0 +1,94 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
* This api exposes CiviCRM GroupNesting.
*
* This defines parent/child relationships between nested groups.
*
* @package CiviCRM_APIv3
*/
/**
* Provides group nesting record(s) given parent and/or child id.
*
* @param array $params
* An array containing at least child_group_id or parent_group_id.
*
* @return array
* list of group nesting records
*/
function civicrm_api3_group_nesting_get($params) {
return _civicrm_api3_basic_get('CRM_Contact_DAO_GroupNesting', $params);
}
/**
* Creates group nesting record for given parent and child id.
*
* Parent and child groups need to exist.
*
* @param array $params
* Parameters array - allowed array keys include:.
*
* @return array
* TBD
* @todo Work out the return value.
*/
function civicrm_api3_group_nesting_create($params) {
CRM_Contact_BAO_GroupNesting::add($params['parent_group_id'], $params['child_group_id']);
// FIXME: CRM_Contact_BAO_GroupNesting requires some work
$result = array('is_error' => 0);
return civicrm_api3_create_success($result, $params, 'GroupNesting');
}
/**
* Adjust Metadata for Create action.
*
* The metadata is used for setting defaults, documentation & validation.
*
* @param array $params
* Array of parameters determined by getfields.
*/
function _civicrm_api3_group_nesting_create_spec(&$params) {
$params['child_group_id']['api.required'] = 1;
$params['parent_group_id']['api.required'] = 1;
}
/**
* Removes specific nesting records.
*
* @param array $params
*
* @return array
* API Success or fail array
*
* @todo Work out the return value.
*/
function civicrm_api3_group_nesting_delete($params) {
return _civicrm_api3_basic_delete(_civicrm_api3_get_BAO(__FUNCTION__), $params);
}

View file

@ -0,0 +1,96 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
* This api exposes the relationships between organizations and CiviCRM groups.
*
* @package CiviCRM_APIv3
*/
/**
* Get group organization record/s.
*
* @param array $params
* Name value pair of contact information.
*
* @return array
* list of groups, given contact subscribed to
*/
function civicrm_api3_group_organization_get($params) {
return _civicrm_api3_basic_get('CRM_Contact_DAO_GroupOrganization', $params);
}
/**
* Create group organization record.
*
* @param array $params
* Array.
*
* @return array
*/
function civicrm_api3_group_organization_create($params) {
$groupOrgBAO = CRM_Contact_BAO_GroupOrganization::add($params);
if (is_null($groupOrgBAO)) {
return civicrm_api3_create_error("group organization not created");
}
_civicrm_api3_object_to_array($groupOrgBAO, $values);
return civicrm_api3_create_success($values, $params, 'GroupOrganization', 'get', $groupOrgBAO);
}
/**
* Adjust Metadata for Create action.
*
* The metadata is used for setting defaults, documentation & validation.
*
* @param array $params
* Array of parameters determined by getfields.
*/
function _civicrm_api3_group_organization_create_spec(&$params) {
$params['organization_id']['api.required'] = 1;
$params['group_id']['api.required'] = 1;
}
/**
* Deletes an existing Group Organization.
*
* This API is used for deleting a Group Organization
*
* @param array $params
* With 'id' = ID of the Group Organization to be deleted.
*
* @return array
* API Result
*/
function civicrm_api3_group_organization_delete($params) {
$result = CRM_Contact_BAO_GroupOrganization::deleteGroupOrganization($params['id']);
return $result ? civicrm_api3_create_success('Deleted Group Organization successfully') : civicrm_api3_create_error('Could not delete Group Organization');
}

View file

@ -0,0 +1,80 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
* This api exposes CiviCRM IM records.
*
* @package CiviCRM_APIv3
*/
/**
* Add an IM for a contact.
*
* @param array $params
*
* @return array
*/
function civicrm_api3_im_create($params) {
return _civicrm_api3_basic_create(_civicrm_api3_get_BAO(__FUNCTION__), $params);
}
/**
* Adjust Metadata for Create action.
*
* The metadata is used for setting defaults, documentation & validation.
*
* @param array $params
* Array of parameters determined by getfields.
*/
function _civicrm_api3_im_create_spec(&$params) {
$params['contact_id']['api.required'] = 1;
}
/**
* Deletes an existing IM.
*
* @param array $params
*
* @return array
* API result Array
*/
function civicrm_api3_im_delete($params) {
return _civicrm_api3_basic_delete(_civicrm_api3_get_BAO(__FUNCTION__), $params);
}
/**
* Retrieve one or more IM.
*
* @param array $params
* An associative array of name/value pairs.
*
* @return array
* details of found IM
*/
function civicrm_api3_im_get($params) {
return _civicrm_api3_basic_get(_civicrm_api3_get_BAO(__FUNCTION__), $params);
}

View file

@ -0,0 +1,689 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
* This api is used for working with scheduled "cron" jobs.
*
* @package CiviCRM_APIv3
*/
/**
* Adjust metadata for "Create" action.
*
* The metadata is used for setting defaults, documentation & validation.
*
* @param array $params
* Array of parameters determined by getfields.
*/
function _civicrm_api3_job_create_spec(&$params) {
$params['run_frequency']['api.required'] = 1;
$params['name']['api.required'] = 1;
$params['api_entity']['api.required'] = 1;
$params['api_action']['api.required'] = 1;
$params['domain_id']['api.default'] = CRM_Core_Config::domainID();
$params['is_active']['api.default'] = 1;
}
/**
* Create scheduled job.
*
* @param array $params
* Associative array of property name/value pairs to insert in new job.
*
* @return array
*/
function civicrm_api3_job_create($params) {
return _civicrm_api3_basic_create(_civicrm_api3_get_BAO(__FUNCTION__), $params);
}
/**
* Retrieve one or more job.
*
* @param array $params
* input parameters
*
* @return array
*/
function civicrm_api3_job_get($params) {
return _civicrm_api3_basic_get(_civicrm_api3_get_BAO(__FUNCTION__), $params);
}
/**
* Delete a job.
*
* @param array $params
*/
function civicrm_api3_job_delete($params) {
_civicrm_api3_basic_delete(_civicrm_api3_get_BAO(__FUNCTION__), $params);
}
/**
* Dumb wrapper to execute scheduled jobs.
*
* Always creates success - errors and results are handled in the job log.
*
* @param array $params
* input parameters (unused).
*
* @return array
* API Result Array
*/
function civicrm_api3_job_execute($params) {
$facility = new CRM_Core_JobManager();
$facility->execute(FALSE);
// Always creates success - results are handled elsewhere.
return civicrm_api3_create_success(1, $params, 'Job');
}
/**
* Adjust Metadata for Execute action.
*
* @param array $params
* Array of parameters determined by getfields.
*/
function _civicrm_api3_job_execute_spec(&$params) {
}
/**
* Geocode group of contacts based on given params.
*
* @param array $params
* input parameters.
*
* @return array
* API Result Array
*/
function civicrm_api3_job_geocode($params) {
$gc = new CRM_Utils_Address_BatchUpdate($params);
$result = $gc->run();
if ($result['is_error'] == 0) {
return civicrm_api3_create_success($result['messages']);
}
else {
return civicrm_api3_create_error($result['messages']);
}
}
/**
* First check on Code documentation.
*
* @param array $params
*/
function _civicrm_api3_job_geocode_spec(&$params) {
$params['start'] = array(
'title' => 'Starting Contact ID',
'type' => CRM_Utils_Type::T_INT,
);
$params['end'] = array(
'title' => 'Ending Contact ID',
'type' => CRM_Utils_Type::T_INT,
);
$params['geocoding'] = array(
'title' => 'Geocode address?',
'type' => CRM_Utils_Type::T_BOOLEAN,
);
$params['parse'] = array(
'title' => 'Parse street address?',
'type' => CRM_Utils_Type::T_BOOLEAN,
);
$params['throttle'] = array(
'title' => 'Throttle?',
'description' => 'If enabled, geo-codes at a slow rate',
'type' => CRM_Utils_Type::T_BOOLEAN,
);
}
/**
* Send the scheduled reminders for all contacts (either for activities or events).
*
* @param array $params
* (reference ) input parameters.
* now - the time to use, in YmdHis format
* - makes testing a bit simpler since we can simulate past/future time
*
* @return array
*/
function civicrm_api3_job_send_reminder($params) {
//note that $params['rowCount' can be overridden by one of the preferred syntaxes ($options['limit'] = x
//It's not clear whether than syntax can be passed in via the UI config - but this keeps the pre 4.4.4 behaviour
// in that case (ie. makes it non-configurable via the UI). Another approach would be to set a default of 0
// in the _spec function - but since that is a deprecated value it seems more contentious than this approach
$params['rowCount'] = 0;
$lock = Civi::lockManager()->acquire('worker.core.ActionSchedule');
if (!$lock->isAcquired()) {
return civicrm_api3_create_error('Could not acquire lock, another ActionSchedule process is running');
}
$result = CRM_Core_BAO_ActionSchedule::processQueue(CRM_Utils_Array::value('now', $params), $params);
$lock->release();
if ($result['is_error'] == 0) {
return civicrm_api3_create_success();
}
else {
return civicrm_api3_create_error($result['messages']);
}
}
/**
* Adjust metadata for "send_reminder" action.
*
* The metadata is used for setting defaults, documentation & validation.
*
* @param array $params
* Array of parameters determined by getfields.
*/
function _civicrm_api3_job_send_reminder(&$params) {
//@todo this function will now take all fields in action_schedule as params
// as it is calling the api fn to set the filters - update getfields to reflect
$params['id'] = array(
'type' => CRM_Utils_Type::T_INT,
'title' => 'Action Schedule ID',
);
}
/**
* Execute a specific report instance and send the output via email.
*
* @param array $params
* (reference ) input parameters.
* sendmail - Boolean - should email be sent?, required
* instanceId - Integer - the report instance ID
* resetVal - Integer - should we reset form state (always true)?
*
* @return array
*/
function civicrm_api3_job_mail_report($params) {
$result = CRM_Report_Utils_Report::processReport($params);
if ($result['is_error'] == 0) {
// this should be handling by throwing exceptions but can't remove until we can test that.
return civicrm_api3_create_success();
}
else {
return civicrm_api3_create_error($result['messages']);
}
}
/**
* This method allows to update Email Greetings, Postal Greetings and Addressee for a specific contact type.
*
* IMPORTANT: You must first create valid option value before using via admin interface.
* Check option lists for Email Greetings, Postal Greetings and Addressee
*
* @todo - is this here by mistake or should it be added to _spec function :id - Integer - greetings option group.
*
* @param array $params
*
* @return array
*/
function civicrm_api3_job_update_greeting($params) {
if (isset($params['ct']) && isset($params['gt'])) {
$ct = explode(',', $params['ct']);
$gt = explode(',', $params['gt']);
foreach ($ct as $ctKey => $ctValue) {
foreach ($gt as $gtKey => $gtValue) {
$params['ct'] = trim($ctValue);
$params['gt'] = trim($gtValue);
CRM_Contact_BAO_Contact_Utils::updateGreeting($params);
}
}
}
else {
CRM_Contact_BAO_Contact_Utils::updateGreeting($params);
}
return civicrm_api3_create_success();
}
/**
* Adjust Metadata for Get action.
*
* The metadata is used for setting defaults, documentation & validation.
*
* @param array $params
* Array of parameters determined by getfields.
*/
function _civicrm_api3_job_update_greeting_spec(&$params) {
$params['ct'] = array(
'api.required' => 1,
'title' => 'Contact Type',
'type' => CRM_Utils_Type::T_STRING,
);
$params['gt'] = array(
'api.required' => 1,
'title' => 'Greeting Type',
'type' => CRM_Utils_Type::T_STRING,
);
}
/**
* Mass update pledge statuses.
*
* @param array $params
*
* @return array
*/
function civicrm_api3_job_process_pledge($params) {
// *** Uncomment the next line if you want automated reminders to be sent
// $params['send_reminders'] = true;
$result = CRM_Pledge_BAO_Pledge::updatePledgeStatus($params);
if ($result['is_error'] == 0) {
// experiment: detailed execution log is a result here
return civicrm_api3_create_success($result['messages']);
}
else {
return civicrm_api3_create_error($result['error_message']);
}
}
/**
* Process mail queue.
*
* @param array $params
*
* @return array
*/
function civicrm_api3_job_process_mailing($params) {
$mailsProcessedOrig = CRM_Mailing_BAO_MailingJob::$mailsProcessed;
try {
CRM_Core_BAO_Setting::isAPIJobAllowedToRun($params);
}
catch (Exception $e) {
return civicrm_api3_create_error($e->getMessage());
}
if (!CRM_Mailing_BAO_Mailing::processQueue()) {
return civicrm_api3_create_error('Process Queue failed');
}
else {
$values = array(
'processed' => CRM_Mailing_BAO_MailingJob::$mailsProcessed - $mailsProcessedOrig,
);
return civicrm_api3_create_success($values, $params, 'Job', 'process_mailing');
}
}
/**
* Process sms queue.
*
* @param array $params
*
* @return array
*/
function civicrm_api3_job_process_sms($params) {
$mailsProcessedOrig = CRM_Mailing_BAO_MailingJob::$mailsProcessed;
if (!CRM_Mailing_BAO_Mailing::processQueue('sms')) {
return civicrm_api3_create_error('Process Queue failed');
}
else {
$values = array(
'processed' => CRM_Mailing_BAO_MailingJob::$mailsProcessed - $mailsProcessedOrig,
);
return civicrm_api3_create_success($values, $params, 'Job', 'process_sms');
}
}
/**
* Job to get mail responses from civiMailing.
*
* @param array $params
*
* @return array
*/
function civicrm_api3_job_fetch_bounces($params) {
$lock = Civi::lockManager()->acquire('worker.mailing.EmailProcessor');
if (!$lock->isAcquired()) {
return civicrm_api3_create_error('Could not acquire lock, another EmailProcessor process is running');
}
CRM_Utils_Mail_EmailProcessor::processBounces($params['is_create_activities']);
$lock->release();
return civicrm_api3_create_success(1, $params, 'Job', 'fetch_bounces');
}
/**
* Metadata for bounce function.
*
* @param array $params
*/
function _civicrm_api3_job_fetch_bounces_spec(&$params) {
$params['is_create_activities'] = array(
'api.default' => 0,
'type' => CRM_Utils_Type::T_BOOLEAN,
'title' => ts('Create activities for replies?'),
);
}
/**
* Job to get mail and create activities.
*
* @param array $params
*
* @return array
*/
function civicrm_api3_job_fetch_activities($params) {
$lock = Civi::lockManager()->acquire('worker.mailing.EmailProcessor');
if (!$lock->isAcquired()) {
return civicrm_api3_create_error('Could not acquire lock, another EmailProcessor process is running');
}
try {
CRM_Utils_Mail_EmailProcessor::processActivities();
$values = array();
$lock->release();
return civicrm_api3_create_success($values, $params, 'Job', 'fetch_activities');
}
catch (Exception $e) {
$lock->release();
return civicrm_api3_create_error($e->getMessage());
}
}
/**
* Process participant statuses.
*
* @param array $params
* Input parameters.
*
* @return array
* array of properties, if error an array with an error id and error message
*/
function civicrm_api3_job_process_participant($params) {
$result = CRM_Event_BAO_ParticipantStatusType::process($params);
if (!$result['is_error']) {
return civicrm_api3_create_success(implode("\r\r", $result['messages']));
}
else {
return civicrm_api3_create_error('Error while processing participant statuses');
}
}
/**
* This api checks and updates the status of all membership records for a given domain.
*
* The function uses the calc_membership_status and update_contact_membership APIs.
*
* IMPORTANT:
* Sending renewal reminders has been migrated from this job to the Scheduled Reminders function as of 4.3.
*
* @param array $params
* Input parameters NOT USED.
*
* @return bool
* true if success, else false
*/
function civicrm_api3_job_process_membership($params) {
$lock = Civi::lockManager()->acquire('worker.member.UpdateMembership');
if (!$lock->isAcquired()) {
return civicrm_api3_create_error('Could not acquire lock, another Membership Processing process is running');
}
$result = CRM_Member_BAO_Membership::updateAllMembershipStatus();
$lock->release();
if ($result['is_error'] == 0) {
return civicrm_api3_create_success($result['messages'], $params, 'Job', 'process_membership');
}
else {
return civicrm_api3_create_error($result['messages']);
}
}
/**
* This api checks and updates the status of all survey respondents.
*
* @param array $params
* (reference ) input parameters.
*
* @return bool
* true if success, else false
*/
function civicrm_api3_job_process_respondent($params) {
$result = CRM_Campaign_BAO_Survey::releaseRespondent($params);
if ($result['is_error'] == 0) {
return civicrm_api3_create_success();
}
else {
return civicrm_api3_create_error($result['messages']);
}
}
/**
* Merges given pair of duplicate contacts.
*
* @param array $params
* Input parameters.
*
* @return array
* API Result Array
* @throws \CiviCRM_API3_Exception
*/
function civicrm_api3_job_process_batch_merge($params) {
$rule_group_id = CRM_Utils_Array::value('rule_group_id', $params);
if (!$rule_group_id) {
$rule_group_id = civicrm_api3('RuleGroup', 'getvalue', array(
'contact_type' => 'Individual',
'used' => 'Unsupervised',
'return' => 'id',
'options' => array('limit' => 1),
));
}
$rgid = CRM_Utils_Array::value('rgid', $params);
$gid = CRM_Utils_Array::value('gid', $params);
$mode = CRM_Utils_Array::value('mode', $params, 'safe');
$result = CRM_Dedupe_Merger::batchMerge($rule_group_id, $gid, $mode, 1, 2, CRM_Utils_Array::value('criteria', $params, array()), CRM_Utils_Array::value('check_permissions', $params));
return civicrm_api3_create_success($result, $params);
}
/**
* Metadata for batch merge function.
*
* @param $params
*/
function _civicrm_api3_job_process_batch_merge_spec(&$params) {
$params['rule_group_id'] = array(
'title' => 'Dedupe rule group id, defaults to Contact Unsupervised rule',
'type' => CRM_Utils_Type::T_INT,
'api.aliases' => array('rgid'),
);
$params['gid'] = array(
'title' => 'group id',
'type' => CRM_Utils_Type::T_INT,
);
$params['mode'] = array(
'title' => 'Mode',
'description' => 'helps decide how to behave when there are conflicts. A \'safe\' value skips the merge if there are no conflicts. Does a force merge otherwise.',
'type' => CRM_Utils_Type::T_STRING,
);
$params['auto_flip'] = array(
'title' => 'Auto Flip',
'description' => 'let the api decide which contact to retain and which to delete?',
'type' => CRM_Utils_Type::T_BOOLEAN,
);
}
/**
* Runs handlePaymentCron method in the specified payment processor.
*
* @param array $params
* Input parameters.
*
* Expected @params array keys are: INCORRECTLY DOCUMENTED AND SHOULD BE IN THE _spec function
* for retrieval via getfields.
* {string 'processor_name' - the name of the payment processor, eg: Sagepay}
*/
function civicrm_api3_job_run_payment_cron($params) {
// live mode
CRM_Core_Payment::handlePaymentMethod(
'PaymentCron',
array_merge(
$params,
array(
'caller' => 'api',
)
)
);
// test mode
CRM_Core_Payment::handlePaymentMethod(
'PaymentCron',
array_merge(
$params,
array(
'mode' => 'test',
)
)
);
}
/**
* This api cleans up all the old session entries and temp tables.
*
* We recommend that sites run this on an hourly basis.
*
* @param array $params
* Sends in various config parameters to decide what needs to be cleaned.
*/
function civicrm_api3_job_cleanup($params) {
$session = CRM_Utils_Array::value('session', $params, TRUE);
$tempTable = CRM_Utils_Array::value('tempTables', $params, TRUE);
$jobLog = CRM_Utils_Array::value('jobLog', $params, TRUE);
$prevNext = CRM_Utils_Array::value('prevNext', $params, TRUE);
$dbCache = CRM_Utils_Array::value('dbCache', $params, FALSE);
$memCache = CRM_Utils_Array::value('memCache', $params, FALSE);
$tplCache = CRM_Utils_Array::value('tplCache', $params, FALSE);
$wordRplc = CRM_Utils_Array::value('wordRplc', $params, FALSE);
if ($session || $tempTable || $prevNext) {
CRM_Core_BAO_Cache::cleanup($session, $tempTable, $prevNext);
}
if ($jobLog) {
CRM_Core_BAO_Job::cleanup();
}
if ($tplCache) {
$config = CRM_Core_Config::singleton();
$config->cleanup(1, FALSE);
}
if ($dbCache) {
CRM_Core_Config::clearDBCache();
}
if ($memCache) {
CRM_Utils_System::flushCache();
}
if ($wordRplc) {
CRM_Core_BAO_WordReplacement::rebuild();
}
}
/**
* Set expired relationships to disabled.
*
* @param array $params
*
* @return array
* @throws \API_Exception
*/
function civicrm_api3_job_disable_expired_relationships($params) {
$result = CRM_Contact_BAO_Relationship::disableExpiredRelationships();
if (!$result) {
throw new API_Exception('Failed to disable all expired relationships.');
}
return civicrm_api3_create_success(1, $params, 'Job', 'disable_expired_relationships');
}
/**
* This api reloads all the smart groups.
*
* If the org has a large number of smart groups it is recommended that they use the limit clause
* to limit the number of smart groups evaluated on a per job basis.
*
* Might also help to increase the smartGroupCacheTimeout and use the cache.
*
* @param array $params
*
* @return array
* @throws \API_Exception
*/
function civicrm_api3_job_group_rebuild($params) {
$lock = Civi::lockManager()->acquire('worker.core.GroupRebuild');
if (!$lock->isAcquired()) {
throw new API_Exception('Could not acquire lock, another GroupRebuild process is running');
}
$limit = CRM_Utils_Array::value('limit', $params, 0);
CRM_Contact_BAO_GroupContactCache::loadAll(NULL, $limit);
$lock->release();
return civicrm_api3_create_success();
}
/**
* Flush smart groups caches.
*
* This job purges aged smart group cache data (based on the timeout value). Sites can decide whether they want this
* job and / or the group cache rebuild job to run. In some cases performance is better when old caches are cleared out
* prior to any attempt to rebuild them. Also, many sites are very happy to have caches built on demand, provided the
* user is not having to wait for deadlocks to clear when invalidating them.
*
* @param array $params
*
* @return array
* @throws \API_Exception
*/
function civicrm_api3_job_group_cache_flush($params) {
CRM_Contact_BAO_GroupContactCache::deterministicCacheFlush();
return civicrm_api3_create_success();
}
/**
* Check for CiviCRM software updates.
*
* Anonymous site statistics are sent back to civicrm.org during this check.
*/
function civicrm_api3_job_version_check() {
$vc = new CRM_Utils_VersionCheck();
$vc->fetch();
return civicrm_api3_create_success();
}

View file

@ -0,0 +1,38 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
* Retrieve one or more job log record.
*
* @param array $params
* input parameters
*
* @return array
*/
function civicrm_api3_job_log_get($params) {
return _civicrm_api3_basic_get(_civicrm_api3_get_BAO(__FUNCTION__), $params);
}

View file

@ -0,0 +1,105 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
* This api exposes CiviCRM LineItem records.
*
* Line items are sub-components of a complete financial transaction record.
*
* @package CiviCRM_APIv3
*/
/**
* Create or update a line_item.
*
* @param array $params
* Array of property name/value pairs to insert in new 'line_item'
*
* @return array
* api result array
*/
function civicrm_api3_line_item_create($params) {
$params = CRM_Contribute_BAO_Contribution::checkTaxAmount($params, TRUE);
return _civicrm_api3_basic_create(_civicrm_api3_get_BAO(__FUNCTION__), $params);
}
/**
* Adjust Metadata for Create action.
*
* The metadata is used for setting defaults, documentation & validation.
*
* @param array $params
* Array of parameters determined by getfields.
*/
function _civicrm_api3_line_item_create_spec(&$params) {
$params['entity_id']['api.required'] = 1;
$params['qty']['api.required'] = 1;
$params['unit_price']['api.required'] = 1;
$params['line_total']['api.required'] = 1;
$params['label']['api.default'] = 'line item';
}
/**
* Returns array of line_items matching a set of one or more group properties.
*
* @param array $params
* Array of one or more valid property_name=>value pairs. If $params is set.
* as null, all line_items will be returned (default limit is 25)
*
* @return array
* Array of matching line_items
*/
function civicrm_api3_line_item_get($params) {
if (CRM_Financial_BAO_FinancialType::isACLFinancialTypeStatus() && CRM_Utils_Array::value('check_permissions', $params)) {
CRM_Price_BAO_LineItem::getAPILineItemParams($params);
}
return _civicrm_api3_basic_get(_civicrm_api3_get_BAO(__FUNCTION__), $params);
}
/**
* Delete an existing LineItem.
*
* This method is used to delete any existing LineItem given its id.
*
* @param array $params
* Array containing id of the group to be deleted.
* @return array API result array
* @throws API_Exception
*/
function civicrm_api3_line_item_delete($params) {
if (CRM_Financial_BAO_FinancialType::isACLFinancialTypeStatus() && CRM_Utils_Array::value('check_permissions', $params)) {
CRM_Financial_BAO_FinancialType::getAvailableFinancialTypes($types, CRM_Core_Action::DELETE);
if (empty($params['financial_type_id'])) {
$params['financial_type_id'] = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_LineItem', $params['id'], 'financial_type_id');
}
if (!in_array($params['financial_type_id'], array_keys($types))) {
throw new API_Exception('You do not have permission to delete this line item');
}
}
return _civicrm_api3_basic_delete(_civicrm_api3_get_BAO(__FUNCTION__), $params);
}

View file

@ -0,0 +1,138 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
* This api exposes CiviCRM LocBlock records.
*
* @package CiviCRM_APIv3
*/
/**
* Create or update a LocBlock.
*
* @param array $params
* Name/value pairs to insert in new 'LocBlock'.
*
* @return array
* API result array.
*
* @throws \API_Exception
*/
function civicrm_api3_loc_block_create($params) {
$entities = array();
$any_mandatory = array(
'address',
'address_id',
'phone',
'phone_id',
'im',
'im_id',
'email',
'email_id',
);
civicrm_api3_verify_one_mandatory($params, NULL, $any_mandatory);
// Call the appropriate api to create entities if any are passed in the params.
// This is basically chaining but in reverse - we create the sub-entities first
// because chaining does not work in reverse, or with keys like 'email_2'.
$items = array('address', 'email', 'phone', 'im');
foreach ($items as $item) {
foreach (array('', '_2') as $suf) {
$key = $item . $suf;
if (!empty($params[$key]) && is_array($params[$key])) {
$info = $params[$key];
// If all we get is an id don't bother calling the api.
if (count($info) == 1 && !empty($info['id'])) {
$params[$key . '_id'] = $info['id'];
}
// Bother calling the api.
else {
$info['contact_id'] = CRM_Utils_Array::value('contact_id', $info, 'null');
$result = civicrm_api3($item, 'create', $info);
$entities[$key] = $result['values'][$result['id']];
$params[$key . '_id'] = $result['id'];
}
}
}
}
$dao = new CRM_Core_DAO_LocBlock();
$dao->copyValues($params);
$dao->save();
if (!empty($dao->id)) {
$values = array($dao->id => $entities);
_civicrm_api3_object_to_array($dao, $values[$dao->id]);
return civicrm_api3_create_success($values, $params, 'LocBlock', 'create', $dao);
}
throw New API_Exception('Unable to create LocBlock. Please check your params.');
}
/**
* Returns array of loc_blocks matching a set of one or more properties.
*
* @param array $params
* Array of one or more valid property_name=>value pairs. If $params is set.
* as null, all loc_blocks will be returned (default limit is 25).
*
* @return array
* API result array.
*/
function civicrm_api3_loc_block_get($params) {
$options = _civicrm_api3_get_options_from_params($params);
// If a return param has been set then fetch the appropriate fk objects
// This is a helper because api chaining does not work with a key like 'email_2'.
if (!empty($options['return'])) {
unset($params['return']);
$values = array();
$items = array('address', 'email', 'phone', 'im');
$returnAll = !empty($options['return']['all']);
foreach (_civicrm_api3_basic_get('CRM_Core_DAO_LocBlock', $params, FALSE) as $val) {
foreach ($items as $item) {
foreach (array('', '_2') as $suf) {
$key = $item . $suf;
if (!empty($val[$key . '_id']) && ($returnAll || !empty($options['return'][$key]))) {
$val[$key] = civicrm_api($item, 'getsingle', array('version' => 3, 'id' => $val[$key . '_id']));
}
}
}
$values[$val['id']] = $val;
}
return civicrm_api3_create_success($values, $params, 'LocBlock', 'get');
}
return _civicrm_api3_basic_get('CRM_Core_DAO_LocBlock', $params);
}
/**
* Delete an existing LocBlock.
*
* @param array $params
* Array containing id of the record to be deleted.
*
* @return array
* API result array.
*/
function civicrm_api3_loc_block_delete($params) {
return _civicrm_api3_basic_delete('CRM_Core_DAO_LocBlock', $params);
}

View file

@ -0,0 +1,87 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
* This api exposes CiviCRM LocationType records.
*
* @package CiviCRM_APIv3
*/
/**
* Add a LocationType.
*
* @param array $params
*
* @return array
* API result array.
*/
function civicrm_api3_location_type_create($params) {
//set display_name equal to name if it's not defined
if (!array_key_exists('display_name', $params) && array_key_exists('name', $params)) {
$params['display_name'] = $params['name'];
}
return _civicrm_api3_basic_create(_civicrm_api3_get_BAO(__FUNCTION__), $params);
}
/**
* Adjust Metadata for Create action.
*
* The metadata is used for setting defaults, documentation & validation.
*
* @param array $params
* Array of parameters determined by getfields.
*/
function _civicrm_api3_location_type_create_spec(&$params) {
$params['is_active']['api.default'] = 1;
$params['name']['api.required'] = 1;
}
/**
* Deletes an existing LocationType.
*
* @param array $params
*
* @return array
* API result array.
*/
function civicrm_api3_location_type_delete($params) {
return _civicrm_api3_basic_delete(_civicrm_api3_get_BAO(__FUNCTION__), $params);
}
/**
* Retrieve one or more LocationTypes.
*
* @param array $params
* An associative array of name/value pairs.
*
* @return array
* API result array.
*/
function civicrm_api3_location_type_get($params) {
return _civicrm_api3_basic_get(_civicrm_api3_get_BAO(__FUNCTION__), $params);
}

View file

@ -0,0 +1,132 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
* This api exposes functionality for interacting with the logging functionality.
*
* @package CiviCRM_APIv3
*/
/**
* Revert a log change.
*
* @param array $params
*
* @return array
* API Success Array
* @throws \API_Exception
* @throws \Civi\API\Exception\UnauthorizedException
*/
function civicrm_api3_logging_revert($params) {
$schema = new CRM_Logging_Schema();
$reverter = new CRM_Logging_Reverter($params['log_conn_id'], CRM_Utils_Array::value('log_date', $params));
$tables = !empty($params['tables']) ? (array) $params['tables'] : $schema->getLogTablesForContact();
$reverter->calculateDiffsFromLogConnAndDate($tables);
$reverter->revert();
return civicrm_api3_create_success(1);
}
/**
* Get a log change.
*
* @param array $params
*
* @throws \API_Exception
* @throws \Civi\API\Exception\UnauthorizedException
*/
function _civicrm_api3_logging_revert_spec(&$params) {
$params['log_conn_id'] = array(
'title' => 'Logging Connection ID',
'type' => CRM_Utils_Type::T_STRING,
'api.required' => TRUE,
);
$params['log_date'] = array(
'title' => 'Logging Timestamp',
'type' => CRM_Utils_Type::T_DATE + CRM_Utils_Type::T_TIME,
);
$params['interval'] = array(
'title' => ts('Interval (required if date is included)'),
'type' => CRM_Utils_Type::T_STRING,
'api.default' => '10 SECOND',
'description' => ts('Used when log_date is passed in'),
);
$params['tables'] = array(
'title' => ts('Tables to revert'),
'type' => CRM_Utils_Type::T_STRING,
'description' => ts('Tables to revert, if not set all contact-referring entities will be reverted'),
);
}
/**
* Get a log change.
*
* @param array $params
*
* @return array
* API Success Array
* @throws \API_Exception
* @throws \Civi\API\Exception\UnauthorizedException
*/
function civicrm_api3_logging_get($params) {
$schema = new CRM_Logging_Schema();
$interval = (empty($params['log_date'])) ? NULL : $params['interval'];
$differ = new CRM_Logging_Differ($params['log_conn_id'], CRM_Utils_Array::value('log_date', $params), $interval);
$tables = !empty($params['tables']) ? (array) $params['tables'] : $schema->getLogTablesForContact();
return civicrm_api3_create_success($differ->getAllChangesForConnection($tables));
}
/**
* Get a log change.
*
* @param array $params
*
* @throws \API_Exception
* @throws \Civi\API\Exception\UnauthorizedException
*/
function _civicrm_api3_logging_get_spec(&$params) {
$params['log_conn_id'] = array(
'title' => 'Logging Connection ID',
'type' => CRM_Utils_Type::T_STRING,
'api.required' => TRUE,
);
$params['log_date'] = array(
'title' => 'Logging Timestamp',
'type' => CRM_Utils_Type::T_DATE + CRM_Utils_Type::T_TIME,
);
$params['interval'] = array(
'title' => ts('Interval (required if date is included)'),
'type' => CRM_Utils_Type::T_STRING,
'api.default' => '10 SECOND',
'description' => ts('Used when log_date is passed in'),
);
$params['tables'] = array(
'title' => ts('Tables to query'),
'type' => CRM_Utils_Type::T_STRING,
'description' => ts('Tables to query, if not set all contact-referring entities will be queried'),
);
}

View file

@ -0,0 +1,83 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
* This api exposes CiviCRM mail settings.
*
* @package CiviCRM_APIv3
*/
/**
* Create or update a MailSettings.
*
* @param array $params
* name/value pairs to insert in new 'MailSettings'
*
* @return array
* API result array.
*/
function civicrm_api3_mail_settings_create($params) {
return _civicrm_api3_basic_create(_civicrm_api3_get_BAO(__FUNCTION__), $params);
}
/**
* Adjust Metadata for Create action.
*
* The metadata is used for setting defaults, documentation & validation.
*
* @param array $params
* Array of parameters determined by getfields.
*/
function _civicrm_api3_mail_settings_create_spec(&$params) {
}
/**
* Returns array of MailSettings matching a set of one or more properties.
*
* @param array $params
* Array of one or more property_name=>value pairs.
* If $params is set as null, all MailSettings will be returned.
*
* @return array
* API result array.
*/
function civicrm_api3_mail_settings_get($params) {
return _civicrm_api3_basic_get(_civicrm_api3_get_BAO(__FUNCTION__), $params);
}
/**
* Delete an existing MailSettings.
*
* @param array $params
* [id]
*
* @return array
* API result array.
*/
function civicrm_api3_mail_settings_delete($params) {
return _civicrm_api3_basic_delete(_civicrm_api3_get_BAO(__FUNCTION__), $params);
}

View file

@ -0,0 +1,789 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* APIv3 functions for registering/processing mailing events.
*
* @package CiviCRM_APIv3
*/
/**
* Handle a create event.
*
* @param array $params
*
* @return array
* API Success Array
* @throws \API_Exception
* @throws \Civi\API\Exception\UnauthorizedException
*/
function civicrm_api3_mailing_create($params) {
if (isset($params['template_options']) && is_array($params['template_options'])) {
$params['template_options'] = ($params['template_options'] === array()) ? '{}' : json_encode($params['template_options']);
}
if (CRM_Mailing_Info::workflowEnabled()) {
// Note: 'schedule mailings' and 'approve mailings' can update certain fields, but can't create.
if (empty($params['id'])) {
if (!CRM_Core_Permission::check('access CiviMail') && !CRM_Core_Permission::check('create mailings')) {
throw new \Civi\API\Exception\UnauthorizedException("Cannot create new mailing. Required permission: 'access CiviMail' or 'create mailings'");
}
}
$safeParams = array();
$fieldPerms = CRM_Mailing_BAO_Mailing::getWorkflowFieldPerms();
foreach (array_keys($params) as $field) {
if (CRM_Core_Permission::check($fieldPerms[$field])) {
$safeParams[$field] = $params[$field];
}
}
}
else {
$safeParams = $params;
}
$timestampCheck = TRUE;
if (!empty($params['id']) && !empty($params['modified_date'])) {
$timestampCheck = _civicrm_api3_compare_timestamps($safeParams['modified_date'], $safeParams['id'], 'Mailing');
unset($safeParams['modified_date']);
}
if (!$timestampCheck) {
throw new API_Exception("Mailing has not been saved, Content maybe out of date, please refresh the page and try again");
}
$safeParams['_evil_bao_validator_'] = 'CRM_Mailing_BAO_Mailing::checkSendable';
$result = _civicrm_api3_basic_create(_civicrm_api3_get_BAO(__FUNCTION__), $safeParams);
return _civicrm_api3_mailing_get_formatResult($result);
}
/**
* Get tokens for one or more entity type
*
* Output will be formatted either as a flat list,
* or pass sequential=1 to retrieve as a hierarchy formatted for select2.
*
* @param array $params
* Should contain an array of entities to retrieve tokens for.
*
* @return array
* @throws \API_Exception
*/
function civicrm_api3_mailing_gettokens($params) {
$tokens = array();
foreach ((array) $params['entity'] as $ent) {
$func = lcfirst($ent) . 'Tokens';
if (!method_exists('CRM_Core_SelectValues', $func)) {
throw new API_Exception('Unknown token entity: ' . $ent);
}
$tokens = array_merge(CRM_Core_SelectValues::$func(), $tokens);
}
if (!empty($params['sequential'])) {
$tokens = CRM_Utils_Token::formatTokensForDisplay($tokens);
}
return civicrm_api3_create_success($tokens, $params, 'Mailing', 'gettokens');
}
/**
* Adjust Metadata for Create action.
*
* The metadata is used for setting defaults, documentation & validation.
*
* @param array $params
* Array of parameters determined by getfields.
*/
function _civicrm_api3_mailing_gettokens_spec(&$params) {
$params['entity'] = array(
'api.default' => array('contact'),
'api.required' => 1,
'api.multiple' => 1,
'title' => 'Entity',
'options' => array(),
);
// Fetch a list of token functions and format to look like entity names
foreach (get_class_methods('CRM_Core_SelectValues') as $func) {
if (strpos($func, 'Tokens')) {
$ent = ucfirst(str_replace('Tokens', '', $func));
$params['entity']['options'][$ent] = $ent;
}
}
}
/**
* Adjust Metadata for Create action.
*
* The metadata is used for setting defaults, documentation & validation.
*
* @param array $params
* Array of parameters determined by getfields.
*/
function _civicrm_api3_mailing_create_spec(&$params) {
$params['created_id']['api.default'] = 'user_contact_id';
$params['override_verp']['api.default'] = !CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::MAILING_PREFERENCES_NAME, 'track_civimail_replies');
$params['visibility']['api.default'] = 'Public Pages';
$params['dedupe_email']['api.default'] = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::MAILING_PREFERENCES_NAME, 'dedupe_email_default');
$params['forward_replies']['api.default'] = FALSE;
$params['auto_responder']['api.default'] = FALSE;
$params['open_tracking']['api.default'] = TRUE;
$params['url_tracking']['api.default'] = TRUE;
$params['header_id']['api.default'] = CRM_Mailing_PseudoConstant::defaultComponent('Header', '');
$params['footer_id']['api.default'] = CRM_Mailing_PseudoConstant::defaultComponent('Footer', '');
$params['optout_id']['api.default'] = CRM_Mailing_PseudoConstant::defaultComponent('OptOut', '');
$params['reply_id']['api.default'] = CRM_Mailing_PseudoConstant::defaultComponent('Reply', '');
$params['resubscribe_id']['api.default'] = CRM_Mailing_PseudoConstant::defaultComponent('Resubscribe', '');
$params['unsubscribe_id']['api.default'] = CRM_Mailing_PseudoConstant::defaultComponent('Unsubscribe', '');
$params['mailing_type']['api.default'] = 'standalone';
$defaultAddress = CRM_Core_OptionGroup::values('from_email_address', NULL, NULL, NULL, ' AND is_default = 1');
foreach ($defaultAddress as $value) {
if (preg_match('/"(.*)" <(.*)>/', $value, $match)) {
$params['from_email']['api.default'] = $match[2];
$params['from_name']['api.default'] = $match[1];
}
}
}
/**
* Adjust metadata for clone spec action.
*
* @param array $spec
*/
function _civicrm_api3_mailing_clone_spec(&$spec) {
$mailingFields = CRM_Mailing_DAO_Mailing::fields();
$spec['id'] = $mailingFields['id'];
$spec['id']['api.required'] = 1;
}
/**
* Clone mailing.
*
* @param array $params
*
* @return array
* @throws \CiviCRM_API3_Exception
*/
function civicrm_api3_mailing_clone($params) {
$BLACKLIST = array(
'id',
'is_completed',
'created_id',
'created_date',
'scheduled_id',
'scheduled_date',
'approver_id',
'approval_date',
'approval_status_id',
'approval_note',
'is_archived',
'hash',
'mailing_type',
);
$get = civicrm_api3('Mailing', 'getsingle', array('id' => $params['id']));
$newParams = array();
$newParams['debug'] = CRM_Utils_Array::value('debug', $params);
$newParams['groups']['include'] = array();
$newParams['groups']['exclude'] = array();
$newParams['mailings']['include'] = array();
$newParams['mailings']['exclude'] = array();
foreach ($get as $field => $value) {
if (!in_array($field, $BLACKLIST)) {
$newParams[$field] = $value;
}
}
$dao = new CRM_Mailing_DAO_MailingGroup();
$dao->mailing_id = $params['id'];
$dao->find();
while ($dao->fetch()) {
// CRM-11431; account for multi-lingual
$entity = (substr($dao->entity_table, 0, 15) == 'civicrm_mailing') ? 'mailings' : 'groups';
$newParams[$entity][strtolower($dao->group_type)][] = $dao->entity_id;
}
return civicrm_api3('Mailing', 'create', $newParams);
}
/**
* Handle a delete event.
*
* @param array $params
*
* @return array
* API Success Array
*/
function civicrm_api3_mailing_delete($params) {
return _civicrm_api3_basic_delete(_civicrm_api3_get_BAO(__FUNCTION__), $params);
}
/**
* Handle a get event.
*
* @param array $params
*
* @return array
*/
function civicrm_api3_mailing_get($params) {
$result = _civicrm_api3_basic_get(_civicrm_api3_get_BAO(__FUNCTION__), $params);
return _civicrm_api3_mailing_get_formatResult($result);
}
/**
* Format definition.
*
* @param array $result
*
* @return array
* @throws \CRM_Core_Exception
*/
function _civicrm_api3_mailing_get_formatResult($result) {
if (isset($result['values']) && is_array($result['values'])) {
foreach ($result['values'] as $key => $caseType) {
if (isset($result['values'][$key]['template_options']) && is_string($result['values'][$key]['template_options'])) {
$result['values'][$key]['template_options'] = json_decode($result['values'][$key]['template_options'], TRUE);
}
}
}
return $result;
}
/**
* Adjust metadata for mailing submit api function.
*
* @param array $spec
*/
function _civicrm_api3_mailing_submit_spec(&$spec) {
$mailingFields = CRM_Mailing_DAO_Mailing::fields();
$spec['id'] = $mailingFields['id'];
$spec['scheduled_date'] = $mailingFields['scheduled_date'];
$spec['approval_date'] = $mailingFields['approval_date'];
$spec['approval_status_id'] = $mailingFields['approval_status_id'];
$spec['approval_note'] = $mailingFields['approval_note'];
// _skip_evil_bao_auto_recipients_: bool
}
/**
* Mailing submit.
*
* @param array $params
*
* @return array
* @throws API_Exception
*/
function civicrm_api3_mailing_submit($params) {
civicrm_api3_verify_mandatory($params, 'CRM_Mailing_DAO_Mailing', array('id'));
if (!isset($params['scheduled_date']) && !isset($updateParams['approval_date'])) {
throw new API_Exception("Missing parameter scheduled_date and/or approval_date");
}
if (!is_numeric(CRM_Core_Session::getLoggedInContactID())) {
throw new API_Exception("Failed to determine current user");
}
$updateParams = array();
$updateParams['id'] = $params['id'];
// Note: we'll pass along scheduling/approval fields, but they may get ignored
// if we don't have permission.
if (isset($params['scheduled_date'])) {
$updateParams['scheduled_date'] = $params['scheduled_date'];
$updateParams['scheduled_id'] = CRM_Core_Session::getLoggedInContactID();
}
if (isset($params['approval_date'])) {
$updateParams['approval_date'] = $params['approval_date'];
$updateParams['approver_id'] = CRM_Core_Session::getLoggedInContactID();
$updateParams['approval_status_id'] = CRM_Utils_Array::value('approval_status_id', $updateParams, CRM_Core_OptionGroup::getDefaultValue('mail_approval_status'));
}
if (isset($params['approval_note'])) {
$updateParams['approval_note'] = $params['approval_note'];
}
if (isset($params['_skip_evil_bao_auto_recipients_'])) {
$updateParams['_skip_evil_bao_auto_recipients_'] = $params['_skip_evil_bao_auto_recipients_'];
}
$updateParams['options']['reload'] = 1;
return civicrm_api3('Mailing', 'create', $updateParams);
}
/**
* Process a bounce event by passing through to the BAOs.
*
* @param array $params
*
* @throws API_Exception
* @return array
*/
function civicrm_api3_mailing_event_bounce($params) {
$body = $params['body'];
unset($params['body']);
$params += CRM_Mailing_BAO_BouncePattern::match($body);
if (CRM_Mailing_Event_BAO_Bounce::create($params)) {
return civicrm_api3_create_success($params);
}
else {
throw new API_Exception(ts('Queue event could not be found'), 'no_queue_event');
}
}
/**
* Adjust Metadata for bounce_spec action.
*
* The metadata is used for setting defaults, documentation & validation.
*
* @param array $params
* Array of parameters determined by getfields.
*/
function _civicrm_api3_mailing_event_bounce_spec(&$params) {
$params['job_id']['api.required'] = 1;
$params['job_id']['title'] = 'Job ID';
$params['event_queue_id']['api.required'] = 1;
$params['event_queue_id']['title'] = 'Event Queue ID';
$params['hash']['api.required'] = 1;
$params['hash']['title'] = 'Hash';
$params['body']['api.required'] = 1;
$params['body']['title'] = 'Body';
}
/**
* Handle a confirm event.
*
* @deprecated
*
* @param array $params
*
* @return array
*/
function civicrm_api3_mailing_event_confirm($params) {
return civicrm_api('MailingEventConfirm', 'create', $params);
}
/**
* Declare deprecated functions.
*
* @deprecated api notice
* @return array
* Array of deprecated actions
*/
function _civicrm_api3_mailing_deprecation() {
return array('event_confirm' => 'Mailing api "event_confirm" action is deprecated. Use the mailing_event_confirm api instead.');
}
/**
* Handle a reply event.
*
* @param array $params
*
* @return array
*/
function civicrm_api3_mailing_event_reply($params) {
$job = $params['job_id'];
$queue = $params['event_queue_id'];
$hash = $params['hash'];
$replyto = $params['replyTo'];
$bodyTxt = CRM_Utils_Array::value('bodyTxt', $params);
$bodyHTML = CRM_Utils_Array::value('bodyHTML', $params);
$fullEmail = CRM_Utils_Array::value('fullEmail', $params);
$mailing = CRM_Mailing_Event_BAO_Reply::reply($job, $queue, $hash, $replyto);
if (empty($mailing)) {
return civicrm_api3_create_error('Queue event could not be found');
}
CRM_Mailing_Event_BAO_Reply::send($queue, $mailing, $bodyTxt, $replyto, $bodyHTML, $fullEmail);
return civicrm_api3_create_success($params);
}
/**
* Adjust Metadata for event_reply action.
*
* The metadata is used for setting defaults, documentation & validation.
*
* @param array $params
* Array of parameters determined by getfields.
*/
function _civicrm_api3_mailing_event_reply_spec(&$params) {
$params['job_id']['api.required'] = 1;
$params['job_id']['title'] = 'Job ID';
$params['event_queue_id']['api.required'] = 1;
$params['event_queue_id']['title'] = 'Event Queue ID';
$params['hash']['api.required'] = 1;
$params['hash']['title'] = 'Hash';
$params['replyTo']['api.required'] = 0;
$params['replyTo']['title'] = 'Reply To';//doesn't really explain adequately
}
/**
* Handle a forward event.
*
* @param array $params
*
* @return array
*/
function civicrm_api3_mailing_event_forward($params) {
$job = $params['job_id'];
$queue = $params['event_queue_id'];
$hash = $params['hash'];
$email = $params['email'];
$fromEmail = CRM_Utils_Array::value('fromEmail', $params);
$params = CRM_Utils_Array::value('params', $params);
$forward = CRM_Mailing_Event_BAO_Forward::forward($job, $queue, $hash, $email, $fromEmail, $params);
if ($forward) {
return civicrm_api3_create_success($params);
}
return civicrm_api3_create_error('Queue event could not be found');
}
/**
* Adjust Metadata for event_forward action.
*
* The metadata is used for setting defaults, documentation & validation.
*
* @param array $params
* Array of parameters determined by getfields.
*/
function _civicrm_api3_mailing_event_forward_spec(&$params) {
$params['job_id']['api.required'] = 1;
$params['job_id']['title'] = 'Job ID';
$params['event_queue_id']['api.required'] = 1;
$params['event_queue_id']['title'] = 'Event Queue ID';
$params['hash']['api.required'] = 1;
$params['hash']['title'] = 'Hash';
$params['email']['api.required'] = 1;
$params['email']['title'] = 'Forwarded to Email';
}
/**
* Handle a click event.
*
* @param array $params
*
* @return array
*/
function civicrm_api3_mailing_event_click($params) {
civicrm_api3_verify_mandatory($params,
'CRM_Mailing_Event_DAO_TrackableURLOpen',
array('event_queue_id', 'url_id'),
FALSE
);
$url_id = $params['url_id'];
$queue = $params['event_queue_id'];
$url = CRM_Mailing_Event_BAO_TrackableURLOpen::track($queue, $url_id);
$values = array();
$values['url'] = $url;
$values['is_error'] = 0;
return civicrm_api3_create_success($values);
}
/**
* Handle an open event.
*
* @param array $params
*
* @return array
*/
function civicrm_api3_mailing_event_open($params) {
civicrm_api3_verify_mandatory($params,
'CRM_Mailing_Event_DAO_Opened',
array('event_queue_id'),
FALSE
);
$queue = $params['event_queue_id'];
$success = CRM_Mailing_Event_BAO_Opened::open($queue);
if (!$success) {
return civicrm_api3_create_error('mailing open event failed');
}
return civicrm_api3_create_success($params);
}
/**
* Preview mailing.
*
* @param array $params
* Array per getfields metadata.
*
* @return array
* @throws \API_Exception
*/
function civicrm_api3_mailing_preview($params) {
civicrm_api3_verify_mandatory($params,
'CRM_Mailing_DAO_Mailing',
array('id'),
FALSE
);
$fromEmail = NULL;
if (!empty($params['from_email'])) {
$fromEmail = $params['from_email'];
}
$session = CRM_Core_Session::singleton();
$mailing = new CRM_Mailing_BAO_Mailing();
$mailing->id = $params['id'];
$mailing->find(TRUE);
CRM_Mailing_BAO_Mailing::tokenReplace($mailing);
// get and format attachments
$attachments = CRM_Core_BAO_File::getEntityFile('civicrm_mailing', $mailing->id);
$returnProperties = $mailing->getReturnProperties();
$contactID = CRM_Utils_Array::value('contact_id', $params);
if (!$contactID) {
$contactID = $session->get('userID');
}
$mailingParams = array('contact_id' => $contactID);
$details = CRM_Utils_Token::getTokenDetails($mailingParams, $returnProperties, TRUE, TRUE, NULL, $mailing->getFlattenedTokens());
$mime = $mailing->compose(NULL, NULL, NULL, $session->get('userID'), $fromEmail, $fromEmail,
TRUE, $details[0][$contactID], $attachments
);
return civicrm_api3_create_success(array(
'id' => $params['id'],
'contact_id' => $contactID,
'subject' => $mime->_headers['Subject'],
'body_html' => $mime->getHTMLBody(),
'body_text' => $mime->getTXTBody(),
));
}
/**
* Adjust metadata for send test function.
*
* @param array $spec
*/
function _civicrm_api3_mailing_send_test_spec(&$spec) {
$spec['test_group']['title'] = 'Test Group ID';
$spec['test_email']['title'] = 'Test Email Address';
}
/**
* Send test mailing.
*
* @param array $params
*
* @return array
* @throws \API_Exception
* @throws \CiviCRM_API3_Exception
*/
function civicrm_api3_mailing_send_test($params) {
if (!array_key_exists('test_group', $params) && !array_key_exists('test_email', $params)) {
throw new API_Exception("Mandatory key(s) missing from params array: test_group and/or test_email field are required");
}
civicrm_api3_verify_mandatory($params,
'CRM_Mailing_DAO_MailingJob',
array('mailing_id'),
FALSE
);
$testEmailParams = _civicrm_api3_generic_replace_base_params($params);
$testEmailParams['is_test'] = 1;
$testEmailParams['status'] = 'Scheduled';
$testEmailParams['scheduled_date'] = CRM_Utils_Date::processDate(date('Y-m-d'), date('H:i:s'));
$job = civicrm_api3('MailingJob', 'create', $testEmailParams);
$testEmailParams['job_id'] = $job['id'];
$testEmailParams['emails'] = array_key_exists('test_email', $testEmailParams) ? explode(',', $testEmailParams['test_email']) : NULL;
if (!empty($params['test_email'])) {
$query = CRM_Utils_SQL_Select::from('civicrm_email e')
->select(array('e.id', 'e.contact_id', 'e.email'))
->join('c', 'INNER JOIN civicrm_contact c ON e.contact_id = c.id')
->where('e.email IN (@emails)', array('@emails' => $testEmailParams['emails']))
->where('e.on_hold = 0')
->where('c.is_opt_out = 0')
->where('c.do_not_email = 0')
->where('c.is_deceased = 0')
->where('c.is_deleted = 0')
->groupBy('e.id')
->orderBy(array('e.is_bulkmail DESC', 'e.is_primary DESC'))
->toSQL();
$dao = CRM_Core_DAO::executeQuery($query);
$emailDetail = array();
// fetch contact_id and email id for all existing emails
while ($dao->fetch()) {
$emailDetail[$dao->email] = array(
'contact_id' => $dao->contact_id,
'email_id' => $dao->id,
);
}
$dao->free();
foreach ($testEmailParams['emails'] as $key => $email) {
$email = trim($email);
$contactId = $emailId = NULL;
if (array_key_exists($email, $emailDetail)) {
$emailId = $emailDetail[$email]['email_id'];
$contactId = $emailDetail[$email]['contact_id'];
}
if (!$contactId) {
//create new contact.
$contact = civicrm_api3('Contact', 'create',
array(
'contact_type' => 'Individual',
'email' => $email,
'api.Email.get' => array('return' => 'id'),
)
);
$contactId = $contact['id'];
$emailId = $contact['values'][$contactId]['api.Email.get']['id'];
}
civicrm_api3('MailingEventQueue', 'create',
array(
'job_id' => $job['id'],
'email_id' => $emailId,
'contact_id' => $contactId,
)
);
}
}
$isComplete = FALSE;
$config = CRM_Core_Config::singleton();
$mailerJobSize = Civi::settings()->get('mailerJobSize');
while (!$isComplete) {
// Q: In CRM_Mailing_BAO_Mailing::processQueue(), the three runJobs*()
// functions are all called. Why does Mailing.send_test only call one?
// CRM_Mailing_BAO_MailingJob::runJobs_pre($mailerJobSize, NULL);
$isComplete = CRM_Mailing_BAO_MailingJob::runJobs($testEmailParams);
// CRM_Mailing_BAO_MailingJob::runJobs_post(NULL);
}
//return delivered mail info
$mailDelivered = CRM_Mailing_Event_BAO_Delivered::getRows($params['mailing_id'], $job['id'], TRUE, NULL, NULL, NULL, TRUE);
return civicrm_api3_create_success($mailDelivered);
}
/**
* Adjust Metadata for send_mail action.
*
* The metadata is used for setting defaults, documentation & validation.
*
* @param array $params
* Array of parameters determined by getfields.
*/
function _civicrm_api3_mailing_stats_spec(&$params) {
$params['date']['api.default'] = 'now';
$params['date']['title'] = 'Date';
$params['is_distinct']['api.default'] = FALSE;
$params['is_distinct']['title'] = 'Is Distinct';
}
/**
* Function which needs to be explained.
*
* @param array $params
*
* @return array
* @throws \API_Exception
*/
function civicrm_api3_mailing_stats($params) {
civicrm_api3_verify_mandatory($params,
'CRM_Mailing_DAO_MailingJob',
array('mailing_id'),
FALSE
);
if ($params['date'] == 'now') {
$params['date'] = date('YmdHis');
}
else {
$params['date'] = CRM_Utils_Date::processDate($params['date'] . ' ' . $params['date_time']);
}
$stats[$params['mailing_id']] = array();
if (empty($params['job_id'])) {
$params['job_id'] = NULL;
}
foreach (array('Delivered', 'Bounces', 'Unsubscribers', 'Unique Clicks', 'Opened') as $detail) {
switch ($detail) {
case 'Delivered':
$stats[$params['mailing_id']] += array(
$detail => CRM_Mailing_Event_BAO_Delivered::getTotalCount($params['mailing_id'], $params['job_id'], (bool) $params['is_distinct'], $params['date']),
);
break;
case 'Bounces':
$stats[$params['mailing_id']] += array(
$detail => CRM_Mailing_Event_BAO_Bounce::getTotalCount($params['mailing_id'], $params['job_id'], (bool) $params['is_distinct'], $params['date']),
);
break;
case 'Unsubscribers':
$stats[$params['mailing_id']] += array(
$detail => CRM_Mailing_Event_BAO_Unsubscribe::getTotalCount($params['mailing_id'], $params['job_id'], (bool) $params['is_distinct'], NULL, $params['date']),
);
break;
case 'Unique Clicks':
$stats[$params['mailing_id']] += array(
$detail => CRM_Mailing_Event_BAO_TrackableURLOpen::getTotalCount($params['mailing_id'], $params['job_id'], (bool) $params['is_distinct'], NULL, $params['date']),
);
break;
case 'Opened':
$stats[$params['mailing_id']] += array(
$detail => CRM_Mailing_Event_BAO_Opened::getTotalCount($params['mailing_id'], $params['job_id'], (bool) $params['is_distinct'], $params['date']),
);
break;
}
}
return civicrm_api3_create_success($stats);
}
/**
* Fix the reset dates on the email record based on when a mail was last delivered.
*
* We only consider mailings that were completed and finished in the last 3 to 7 days
* Both the min and max days can be set via the params
*
* @param array $params
*
* @return array
*/
function civicrm_api3_mailing_update_email_resetdate($params) {
CRM_Mailing_Event_BAO_Delivered::updateEmailResetDate(
CRM_Utils_Array::value('minDays', $params, 3),
CRM_Utils_Array::value('maxDays', $params, 3)
);
return civicrm_api3_create_success();
}

View file

@ -0,0 +1,281 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* APIv3 functions for registering/processing mailing ab testing events.
*
* @package CiviCRM_APIv3
*/
/**
* @param array $spec
*/
function _civicrm_api3_mailing_a_b_create_spec(&$spec) {
$spec['created_date']['api.default'] = 'now';
$spec['created_id']['api.required'] = 1;
$spec['created_id']['api.default'] = 'user_contact_id';
}
/**
* Handle a create mailing ab testing.
*
* @param array $params
*
* @return array
* API Success Array
*/
function civicrm_api3_mailing_a_b_create($params) {
return _civicrm_api3_basic_create(_civicrm_api3_get_BAO(__FUNCTION__), $params);
}
/**
* Handle a delete event.
*
* @param array $params
*
* @return array
* API Success Array
*/
function civicrm_api3_mailing_a_b_delete($params) {
return _civicrm_api3_basic_delete(_civicrm_api3_get_BAO(__FUNCTION__), $params);
}
/**
* Handle a get event.
*
* @param array $params
*
* @return array
*/
function civicrm_api3_mailing_a_b_get($params) {
return _civicrm_api3_basic_get(_civicrm_api3_get_BAO(__FUNCTION__), $params);
}
/**
* Adjust Metadata for submit action.
*
* The metadata is used for setting defaults, documentation & validation.
*
* @param array $spec
* Array of parameters determined by getfields.
*/
function _civicrm_api3_mailing_a_b_submit_spec(&$spec) {
$mailingFields = CRM_Mailing_DAO_Mailing::fields();
$mailingAbFields = CRM_Mailing_DAO_MailingAB::fields();
$spec['id'] = $mailingAbFields['id'];
$spec['status'] = $mailingAbFields['status'];
$spec['scheduled_date'] = $mailingFields['scheduled_date'];
$spec['approval_date'] = $mailingFields['approval_date'];
$spec['approval_status_id'] = $mailingFields['approval_status_id'];
$spec['approval_note'] = $mailingFields['approval_note'];
// Note: we'll pass through approval_* fields to the underlying mailing, but they may be ignored
// if the user doesn't have suitable permission. If separate approvals are required, they must be provided
// outside the A/B Test UI.
}
/**
* Send A/B mail to A/B recipients respectively.
*
* @param array $params
*
* @return array
* @throws API_Exception
*/
function civicrm_api3_mailing_a_b_submit($params) {
civicrm_api3_verify_mandatory($params, 'CRM_Mailing_DAO_MailingAB', array('id', 'status'));
if (!isset($params['scheduled_date']) && !isset($updateParams['approval_date'])) {
throw new API_Exception("Missing parameter scheduled_date and/or approval_date");
}
$dao = new CRM_Mailing_DAO_MailingAB();
$dao->id = $params['id'];
if (!$dao->find(TRUE)) {
throw new API_Exception("Failed to locate A/B test by ID");
}
if (empty($dao->mailing_id_a) || empty($dao->mailing_id_b) || empty($dao->mailing_id_c)) {
throw new API_Exception("Missing mailing IDs for A/B test");
}
$submitParams = CRM_Utils_Array::subset($params, array(
'scheduled_date',
'approval_date',
'approval_note',
'approval_status_id',
));
switch ($params['status']) {
case 'Testing':
if (!empty($dao->status) && $dao->status != 'Draft') {
throw new API_Exception("Cannot transition to state 'Testing'");
}
civicrm_api3('Mailing', 'submit', $submitParams + array(
'id' => $dao->mailing_id_a,
'_skip_evil_bao_auto_recipients_' => 0,
));
civicrm_api3('Mailing', 'submit', $submitParams + array(
'id' => $dao->mailing_id_b,
'_skip_evil_bao_auto_recipients_' => 1,
));
CRM_Mailing_BAO_MailingAB::distributeRecipients($dao);
break;
case 'Final':
if ($dao->status != 'Testing') {
throw new API_Exception("Cannot transition to state 'Final'");
}
civicrm_api3('Mailing', 'submit', $submitParams + array(
'id' => $dao->mailing_id_c,
'_skip_evil_bao_auto_recipients_' => 1,
));
break;
default:
throw new API_Exception("Unrecognized submission status");
}
return civicrm_api3('MailingAB', 'create', array(
'id' => $dao->id,
'status' => $params['status'],
'options' => array(
'reload' => 1,
),
));
}
/**
* Adjust Metadata for graph_stats action.
*
* The metadata is used for setting defaults, documentation & validation.
*
* @param array $params
* Array of parameters determined by getfields.
*/
function _civicrm_api3_mailing_a_b_graph_stats_spec(&$params) {
$params['criteria'] = array(
'title' => 'Criteria',
'default' => 'Open',
'type' => CRM_Utils_Type::T_STRING,
);
// mailing_ab_winner_criteria
$params['target_date']['title'] = 'Target Date';
$params['target_date']['type'] = CRM_Utils_Type::T_DATE + CRM_Utils_Type::T_TIME;
$params['split_count'] = array(
'title' => 'Split Count',
'api.default' => 6,
'type' => CRM_Utils_Type::T_INT,
);
$params['split_count_select']['title'] = 'Split Count Select';
$params['split_count_select']['api.required'] = 1;
$params['target_url']['title'] = 'Target URL';
}
/**
* Send graph detail for A/B tests mail.
*
* @param array $params
*
* @return array
* @throws API_Exception
*/
function civicrm_api3_mailing_a_b_graph_stats($params) {
civicrm_api3_verify_mandatory($params,
'CRM_Mailing_DAO_MailingAB',
array('id'),
FALSE
);
$defaults = array(
'criteria' => 'Open',
'target_date' => CRM_Utils_Time::getTime('YmdHis'),
'split_count' => 6,
'split_count_select' => 1,
);
$params = array_merge($defaults, $params);
$mailingAB = civicrm_api3('MailingAB', 'getsingle', array('id' => $params['id']));
$graphStats = array();
$ABFormat = array('A' => 'mailing_id_a', 'B' => 'mailing_id_b');
foreach ($ABFormat as $name => $column) {
switch (strtolower($params['criteria'])) {
case 'open':
$result = CRM_Mailing_Event_BAO_Opened::getRows($mailingAB['mailing_id_a'], NULL, TRUE, 0, 1, "civicrm_mailing_event_opened.time_stamp ASC");
$startDate = CRM_Utils_Date::processDate($result[0]['date']);
$targetDate = CRM_Utils_Date::processDate($params['target_date']);
$dateDuration = round(round(strtotime($targetDate) - strtotime($startDate)) / $params['split_count']);
$toDate = strtotime($startDate) + ($dateDuration * $params['split_count_select']);
$toDate = date('YmdHis', $toDate);
$graphStats[$name] = array(
$params['split_count_select'] => array(
'count' => CRM_Mailing_Event_BAO_Opened::getTotalCount($mailingAB[$column], NULL, TRUE, $toDate),
'time' => CRM_Utils_Date::customFormat($toDate),
),
);
break;
case 'total unique clicks':
$result = CRM_Mailing_Event_BAO_TrackableURLOpen::getRows($mailingAB['mailing_id_a'], NULL, TRUE, 0, 1, "civicrm_mailing_event_trackable_url_open.time_stamp ASC");
$startDate = CRM_Utils_Date::processDate($result[0]['date']);
$targetDate = CRM_Utils_Date::processDate($params['target_date']);
$dateDuration = round(abs(strtotime($targetDate) - strtotime($startDate)) / $params['split_count']);
$toDate = strtotime($startDate) + ($dateDuration * $params['split_count_select']);
$toDate = date('YmdHis', $toDate);
$graphStats[$name] = array(
$params['split_count_select'] => array(
'count' => CRM_Mailing_Event_BAO_TrackableURLOpen::getTotalCount($params['mailing_id'], NULL, FALSE, NULL, $toDate),
'time' => CRM_Utils_Date::customFormat($toDate),
),
);
break;
case 'total clicks on a particular link':
if (empty($params['target_url'])) {
throw new API_Exception("Provide url to get stats result for total clicks on a particular link");
}
// FIXME: doesn't make sense to get url_id mailing_id_(a|b) while getting start date in mailing_id_a
$url_id = CRM_Mailing_BAO_TrackableURL::getTrackerURLId($mailingAB[$column], $params['target_url']);
$result = CRM_Mailing_Event_BAO_TrackableURLOpen::getRows($mailingAB['mailing_id_a'], NULL, FALSE, $url_id, 0, 1, "civicrm_mailing_event_trackable_url_open.time_stamp ASC");
$startDate = CRM_Utils_Date::processDate($result[0]['date']);
$targetDate = CRM_Utils_Date::processDate($params['target_date']);
$dateDuration = round(abs(strtotime($targetDate) - strtotime($startDate)) / $params['split_count']);
$toDate = strtotime($startDate) + ($dateDuration * $params['split_count_select']);
$toDate = CRM_Utils_Date::processDate($toDate);
$graphStats[$name] = array(
$params['split_count_select'] => array(
'count' => CRM_Mailing_Event_BAO_TrackableURLOpen::getTotalCount($params['mailing_id'], NULL, FALSE, $url_id, $toDate),
'time' => CRM_Utils_Date::customFormat($toDate),
),
);
break;
}
}
return civicrm_api3_create_success($graphStats);
}

View file

@ -0,0 +1,95 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
* This api exposes CiviCRM MailingComponent (header and footer).
*
* @package CiviCRM_APIv3
*/
/**
* Save a MailingComponent.
*
* @param array $params
*
* @throws API_Exception
* @return array
* API result array.
*/
function civicrm_api3_mailing_component_create($params) {
return _civicrm_api3_basic_create(_civicrm_api3_get_BAO(__FUNCTION__), $params);
}
/**
* Adjust Metadata for Create action.
*
* The metadata is used for setting defaults, documentation & validation.
*
* @param array $spec
* Array of parameters determined by getfields.
*/
function _civicrm_api3_mailing_component_create_spec(&$spec) {
$spec['is_active']['api.default'] = 1;
$spec['name']['api.required'] = 1;
$spec['component_type']['api.required'] = 1;
}
/**
* Get a MailingComponent.
*
* @param array $params
*
* @return array
* API result array.
*/
function civicrm_api3_mailing_component_get($params) {
return _civicrm_api3_basic_get(_civicrm_api3_get_BAO(__FUNCTION__), $params);
}
/**
* Adjust metadata for get.
*
* @param array $params
*/
function _civicrm_api3_mailing_component_get_spec(&$params) {
// fetch active records by default
$params['is_active']['api.default'] = 1;
}
/**
* Delete a MailingComponent.
*
* @param array $params
*
* @throws API_Exception
* @return array
* API result array.
*/
function civicrm_api3_mailing_component_delete($params) {
return _civicrm_api3_basic_delete(_civicrm_api3_get_BAO(__FUNCTION__), $params);
}

View file

@ -0,0 +1,293 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
* This api exposes CiviCRM contact and mailing.
*
* @package CiviCRM_APIv3
*/
/**
* Get all the mailings and details that a contact was involved with.
*
* @param array $params
* Input parameters - see _spec for details (returned by getfields)
*
* @return array
* API result
*/
function civicrm_api3_mailing_contact_get($params) {
return civicrm_api3_create_success(_civicrm_api3_mailing_contact_getresults($params, FALSE));
}
/**
* This is a wrapper for the functions that return the results from the 'quasi-entity' mailing contact.
*
* @param array $params
* @param bool $count
*
* @throws Exception
*/
function _civicrm_api3_mailing_contact_getresults($params, $count) {
if (empty($params['type'])) {
//ie. because the api is an anomaly & passing in id is not valid
throw new Exception('This api call does not accept api as a parameter');
}
$options = _civicrm_api3_get_options_from_params($params, TRUE, 'contribution', 'get');
$fnName = '_civicrm_api3_mailing_contact_get_' . strtolower($params['type']);
return $fnName(
$params['contact_id'],
$options['offset'],
$options['limit'],
$options['sort'],
$count
);
}
/**
* Adjust Metadata for Get action.
*
* @param array $params
* Array of parameters determined by getfields.
*/
function _civicrm_api3_mailing_contact_get_spec(&$params) {
$params['contact_id'] = array(
'api.required' => 1,
'title' => 'Contact ID',
'type' => CRM_Utils_Type::T_INT,
);
$params['type'] = array(
'api.default' => 'Delivered',
'title' => 'Type', // doesn't really explain the field - but not sure I understand it to explain it better
'type' => CRM_Utils_Type::T_STRING,
'options' => array(
'Delivered' => 'Delivered',
'Bounced' => 'Bounced',
),
);
}
/**
* Helper function for mailing contact queries.
*
* @param int $contactID
* @param $offset
* @param $limit
* @param $selectFields
* @param $fromClause
* @param $whereClause
* @param $sort
* @param $getCount
*
* @return array
*/
function _civicrm_api3_mailing_contact_query(
$contactID,
$offset,
$limit,
$selectFields,
$fromClause,
$whereClause,
$sort,
$getCount
) {
if ($getCount) {
$sql = "
SELECT count(*)
FROM civicrm_mailing m
INNER JOIN civicrm_contact c ON m.created_id = c.id
INNER JOIN civicrm_mailing_job j ON j.mailing_id = m.id
INNER JOIN civicrm_mailing_event_queue meq ON meq.job_id = j.id
$fromClause
WHERE j.is_test = 0
AND meq.contact_id = %1
$whereClause
GROUP BY m.id
";
$qParams = array(
1 => array($contactID, 'Integer'),
);
$dao = CRM_Core_DAO::executeQuery($sql, $qParams);
$results = $dao->N;
}
else {
$defaultFields = array(
'm.id' => 'mailing_id',
'm.subject' => 'subject',
'c.id' => 'creator_id',
'c.sort_name' => 'creator_name',
);
if ($selectFields) {
$fields = array_merge($selectFields, $defaultFields);
}
else {
$fields = $defaultFields;
}
$select = array();
foreach ($fields as $n => $l) {
$select[] = "$n as $l";
}
$select = implode(', ', $select);
$orderBy = 'ORDER BY MIN(j.start_date) DESC';
if ($sort) {
$orderBy = "ORDER BY $sort";
}
$groupBy = CRM_Contact_BAO_Query::getGroupByFromSelectColumns(array_keys($fields), "m.id");
$sql = "
SELECT $select
FROM civicrm_mailing m
INNER JOIN civicrm_contact c ON m.created_id = c.id
INNER JOIN civicrm_mailing_job j ON j.mailing_id = m.id
INNER JOIN civicrm_mailing_event_queue meq ON meq.job_id = j.id
$fromClause
WHERE j.is_test = 0
AND meq.contact_id = %1
$whereClause
{$groupBy}
{$orderBy}
";
if ($limit > 0) {
$sql .= "
LIMIT %2, %3
";
}
$qParams = array(
1 => array($contactID, 'Integer'),
2 => array($offset, 'Integer'),
3 => array($limit, 'Integer'),
);
$dao = CRM_Core_DAO::executeQuery($sql, $qParams);
$results = array();
while ($dao->fetch()) {
foreach ($fields as $n => $l) {
$results[$dao->mailing_id][$l] = $dao->$l;
}
}
}
return $results;
}
/**
* Get delivered mailing contacts.
*
* @param int $contactID
* @param $offset
* @param $limit
* @param $sort
* @param $getCount
*
* @return array
*/
function _civicrm_api3_mailing_contact_get_delivered(
$contactID,
$offset,
$limit,
$sort,
$getCount
) {
$selectFields = array('med.time_stamp' => 'start_date');
$fromClause = "
INNER JOIN civicrm_mailing_event_delivered med ON med.event_queue_id = meq.id
LEFT JOIN civicrm_mailing_event_bounce meb ON meb.event_queue_id = meq.id
";
$whereClause = "
AND meb.id IS NULL
";
return _civicrm_api3_mailing_contact_query(
$contactID,
$offset,
$limit,
$selectFields,
$fromClause,
$whereClause,
$sort,
$getCount
);
}
/**
* Get bounced mailing contact records.
*
* @param int $contactID
* @param $offset
* @param $limit
* @param $sort
* @param $getCount
*
* @return array
*/
function _civicrm_api3_mailing_contact_get_bounced(
$contactID,
$offset,
$limit,
$sort,
$getCount
) {
$fromClause = "
INNER JOIN civicrm_mailing_event_bounce meb ON meb.event_queue_id = meq.id
";
return _civicrm_api3_mailing_contact_query(
$contactID,
$offset,
$limit,
NULL,
$fromClause,
NULL,
$sort,
$getCount
);
}
/**
* Get count of all the mailings that a contact was involved with.
*
* @param array $params
* Input parameters per getfields
*
* @return array
* API result
*/
function civicrm_api3_mailing_contact_getcount($params) {
return _civicrm_api3_mailing_contact_getresults($params, TRUE);
}

View file

@ -0,0 +1,83 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* APIv3 functions for registering/processing mailing group events.
*
* @package CiviCRM_APIv3
*/
/**
* Handle a confirm event.
*
* @param array $params
* name/value pairs to insert in new 'survey'
*
* @throws Exception
* @return array
* api result array
*/
function civicrm_api3_mailing_event_confirm_create($params) {
$contact_id = $params['contact_id'];
$subscribe_id = $params['subscribe_id'];
$hash = $params['hash'];
$confirm = CRM_Mailing_Event_BAO_Confirm::confirm($contact_id, $subscribe_id, $hash) !== FALSE;
if (!$confirm) {
throw new Exception('Confirmation failed');
}
return civicrm_api3_create_success($params);
}
/**
* Adjust Metadata for Create action.
*
* The metadata is used for setting defaults, documentation & validation.
*
* @param array $params
* Array of parameters determined by getfields.
*/
function _civicrm_api3_mailing_event_confirm_create_spec(&$params) {
$params['contact_id'] = array(
'api.required' => 1,
'title' => 'Contact ID',
'type' => CRM_Utils_Type::T_INT,
);
$params['subscribe_id'] = array(
'api.required' => 1,
'title' => 'Subscribe Event ID',
'type' => CRM_Utils_Type::T_INT,
);
$params['hash'] = array(
'api.required' => 1,
'title' => 'Hash',
'type' => CRM_Utils_Type::T_STRING,
);
}

View file

@ -0,0 +1,90 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* APIv3 functions for registering/processing mailing group events.
*
* @package CiviCRM_APIv3
*/
/**
* Handle a queue event.
*
* @param array $params
* Array of property.
*
* @throws Exception
* @return array
* api result array
*/
function civicrm_api3_mailing_event_queue_create($params) {
if (!array_key_exists('id', $params) && !array_key_exists('email_id', $params) && !array_key_exists('phone_id', $params)) {
throw new API_Exception("Mandatory key missing from params array: id, email_id, or phone_id field is required");
}
civicrm_api3_verify_mandatory($params,
'CRM_Mailing_DAO_MailingJob',
array('job_id', 'contact_id'),
FALSE
);
return _civicrm_api3_basic_create('CRM_Mailing_Event_BAO_Queue', $params);
}
/**
* Get mailing event queue record.
*
* @param array $params
*
* @return array
*/
function civicrm_api3_mailing_event_queue_get($params) {
return _civicrm_api3_basic_get('CRM_Mailing_Event_BAO_Queue', $params);
}
/**
* Delete mailing event queue record.
*
* @param array $params
*
* @return array
* @throws \API_Exception
*/
function civicrm_api3_mailing_event_queue_delete($params) {
return _civicrm_api3_basic_delete('CRM_Mailing_Event_BAO_Queue', $params);
}
/**
* Adjust Metadata for Create action.
*
* The metadata is used for setting defaults, documentation & validation.
*
* @param array $params
* Array of parameters determined by getfields.
*/
function _civicrm_api3_mailing_event_queue_create_spec(&$params) {
$params['job_id']['api.required'] = 1;
$params['contact_id']['api.required'] = 1;
}

View file

@ -0,0 +1,86 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* APIv3 functions for registering/processing mailing group events.
*
* @package CiviCRM_APIv3
*/
/**
* Subscribe from mailing group.
*
* @param array $params
*
* @return array
* api result array
*/
function civicrm_api3_mailing_event_resubscribe_create($params) {
$groups = CRM_Mailing_Event_BAO_Resubscribe::resub_to_mailing(
$params['job_id'],
$params['event_queue_id'],
$params['hash']
);
if (count($groups)) {
CRM_Mailing_Event_BAO_Resubscribe::send_resub_response(
$params['event_queue_id'],
$groups, FALSE,
$params['job_id']
);
return civicrm_api3_create_success($params);
}
return civicrm_api3_create_error('Queue event could not be found');
}
/**
* Adjust Metadata for Create action.
*
* The metadata is used for setting defaults, documentation & validation.
*
* @param array $params
* Array of parameters determined by getfields.
*/
function _civicrm_api3_mailing_event_resubscribe_create_spec(&$params) {
$params['event_queue_id'] = array(
'api.required' => 1,
'title' => 'Event Queue ID',
'type' => CRM_Utils_Type::T_INT,
);
$params['job_id'] = array(
'api.required' => 1,
'title' => 'Job ID',
'type' => CRM_Utils_Type::T_INT,
);
$params['hash'] = array(
'api.required' => 1,
'title' => 'Hash',
'type' => CRM_Utils_Type::T_STRING,
);
}

View file

@ -0,0 +1,93 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* APIv3 functions for registering/processing mailing group events.
*
* @package CiviCRM_APIv3
*/
/**
* Subscribe from mailing group.
*
* @param array $params
* Array per getfields metadata.
*
* @throws API_Exception
* @return array
* api result array
*/
function civicrm_api3_mailing_event_subscribe_create($params) {
$email = $params['email'];
$group_id = $params['group_id'];
$contact_id = CRM_Utils_Array::value('contact_id', $params);
$group = new CRM_Contact_DAO_Group();
$group->is_active = 1;
$group->id = (int) $group_id;
if (!$group->find(TRUE)) {
throw new API_Exception('Invalid Group id');
}
$subscribe = CRM_Mailing_Event_BAO_Subscribe::subscribe($group_id, $email, $contact_id);
if ($subscribe !== NULL) {
/* Ask the contact for confirmation */
$subscribe->send_confirm_request($email);
$values = array();
$values[$subscribe->id]['contact_id'] = $subscribe->contact_id;
$values[$subscribe->id]['subscribe_id'] = $subscribe->id;
$values[$subscribe->id]['hash'] = $subscribe->hash;
return civicrm_api3_create_success($values);
}
return civicrm_api3_create_error('Subscription failed');
}
/**
* Adjust Metadata for Create action.
*
* The metadata is used for setting defaults, documentation & validation.
*
* @param array $params
* Array of parameters determined by getfields.
*/
function _civicrm_api3_mailing_event_subscribe_create_spec(&$params) {
$params['email'] = array(
'api.required' => 1,
'title' => 'Unsubscribe Email',
'type' => CRM_Utils_Type::T_STRING,
);
$params['group_id'] = array(
'api.required' => 1,
'title' => 'Unsubscribe From Group',
'type' => CRM_Utils_Type::T_INT,
);
}

View file

@ -0,0 +1,93 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* APIv3 functions for registering/processing mailing group events.
*
* @package CiviCRM_APIv3
*/
/**
* Unsubscribe from mailing group.
*
* @param array $params
* Array per getfields metadata.
*
* @return array
* Api result array
*/
function civicrm_api3_mailing_event_unsubscribe_create($params) {
$job = $params['job_id'];
$queue = $params['event_queue_id'];
$hash = $params['hash'];
if (empty($params['org_unsubscribe'])) {
$groups = CRM_Mailing_Event_BAO_Unsubscribe::unsub_from_mailing($job, $queue, $hash);
if (count($groups)) {
CRM_Mailing_Event_BAO_Unsubscribe::send_unsub_response($queue, $groups, FALSE, $job);
return civicrm_api3_create_success($params);
}
}
else {
$unsubs = CRM_Mailing_Event_BAO_Unsubscribe::unsub_from_domain($job, $queue, $hash);
if (!$unsubs) {
return civicrm_api3_create_error('Domain Queue event could not be found');
}
CRM_Mailing_Event_BAO_Unsubscribe::send_unsub_response($queue, NULL, TRUE, $job);
return civicrm_api3_create_success($params);
}
return civicrm_api3_create_error('Queue event could not be found');
}
/**
* Adjust Metadata for Create action.
*
* The metadata is used for setting defaults, documentation & validation.
*
* @param array $params
* Array of parameters determined by getfields.
*/
function _civicrm_api3_mailing_event_unsubscribe_create_spec(&$params) {
$params['job_id'] = array(
'api.required' => 1,
'title' => 'Mailing Job ID',
'type' => CRM_Utils_Type::T_INT,
);
$params['hash'] = array(
'api.required' => 1,
'title' => 'Mailing Hash',
'type' => CRM_Utils_Type::T_STRING,
);
$params['event_queue_id'] = array(
'api.required' => 1,
'title' => 'Mailing Queue ID',
'type' => CRM_Utils_Type::T_INT,
);
}

View file

@ -0,0 +1,138 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
* APIv3 functions for registering/processing mailing group events.
*
* @deprecated
* @package CiviCRM_APIv3
*/
/**
* Declare deprecated functions.
*
* @deprecated api notice
* @return string
* to indicate this entire api entity is deprecated
*/
function _civicrm_api3_mailing_group_deprecation() {
$message = 'This action is deprecated. Use the mailing_event API instead.';
return array(
'event_unsubscribe' => $message,
'event_domain_unsubscribe' => $message,
'event_resubscribe' => $message,
'event_subscribe' => $message,
);
}
/**
* Handle an unsubscribe event.
*
* @deprecated
*
* @param array $params
*
* @return array
*/
function civicrm_api3_mailing_group_event_unsubscribe($params) {
return civicrm_api('mailing_event_unsubscribe', 'create', $params);
}
/**
* Handle a site-level unsubscribe event.
*
* @deprecated
*
* @param array $params
*
* @return array
*/
function civicrm_api3_mailing_group_event_domain_unsubscribe($params) {
$params['org_unsubscribe'] = 1;
return civicrm_api('mailing_event_unsubscribe', 'create', $params);
}
/**
* Handle a re-subscription event.
*
* @deprecated
*
* @param array $params
*
* @return array
*/
function civicrm_api3_mailing_group_event_resubscribe($params) {
return civicrm_api('mailing_event_resubscribe', 'create', $params);
}
/**
* Handle a subscription event.
*
* @deprecated
*
* @param array $params
*
* @return array
*/
function civicrm_api3_mailing_group_event_subscribe($params) {
return civicrm_api('mailing_event_subscribe', 'create', $params);
}
/**
* Create mailing group.
*
* @param array $params
*
* @return array
* @throws \API_Exception
*/
function civicrm_api3_mailing_group_create($params) {
return _civicrm_api3_basic_create(_civicrm_api3_get_BAO(__FUNCTION__), $params);
}
/**
* Get mailing group.
*
* @param array $params
*
* @return array
*/
function civicrm_api3_mailing_group_get($params) {
return _civicrm_api3_basic_get(_civicrm_api3_get_BAO(__FUNCTION__), $params);
}
/**
* Delete mailing group.
*
* @param array $params
*
* @return array
* @throws \API_Exception
*/
function civicrm_api3_mailing_group_delete($params) {
return _civicrm_api3_basic_delete(_civicrm_api3_get_BAO(__FUNCTION__), $params);
}

View file

@ -0,0 +1,83 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* APIv3 functions for registering/processing mailing jobs.
*
* @package CiviCRM_APIv3
*/
/**
* Handle creation of a MailingJob for a Mailing.
*
* @param array $params
*
* @return array
* @throws \API_Exception
*/
function civicrm_api3_mailing_job_create($params) {
return _civicrm_api3_basic_create(_civicrm_api3_get_BAO(__FUNCTION__), $params);
}
/**
* Adjust Metadata for Create action.
*
* The metadata is used for setting defaults, documentation & validation.
*
* @param array $params
* Array of parameters determined by getfields.
*/
function _civicrm_api3_mailing_job_create_spec(&$params) {
$params['status']['api.default'] = 'Scheduled';
$params['scheduled_date']['api.default'] = 'now';
$params['is_test']['api.default'] = 0;
}
/**
* Returns array of Mailing Jobs matching a set of one or more group properties.
*
* @param array $params
*
* @return array
* API return Array of matching mailing jobs.
*/
function civicrm_api3_mailing_job_get($params) {
return _civicrm_api3_basic_get(_civicrm_api3_get_BAO(__FUNCTION__), $params);
}
/**
* Handle deletion of a Mailing Job for a Mailing.
*
* @param array $params
*
* @return array
* @throws \API_Exception
*/
function civicrm_api3_mailing_job_delete($params) {
return _civicrm_api3_basic_delete(_civicrm_api3_get_BAO(__FUNCTION__), $params);
}

View file

@ -0,0 +1,46 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
* API for retrieving mailing recipients.
*
* @package CiviCRM_APIv3
*/
/**
* Returns array of MailingRecipients.
*
* @param array $params
* Array per getfields metadata.
*
* @return array
* API return Array of matching mailing jobs
*/
function civicrm_api3_mailing_recipients_get($params) {
return _civicrm_api3_basic_get(_civicrm_api3_get_BAO(__FUNCTION__), $params);
}

View file

@ -0,0 +1,81 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
* This api exposes CiviCRM Mapping records.
*
* @package CiviCRM_APIv3
*/
/**
* Add a Mapping.
*
* @param array $params
*
* @return array
*/
function civicrm_api3_mapping_create($params) {
return _civicrm_api3_basic_create(_civicrm_api3_get_BAO(__FUNCTION__), $params);
}
/**
* Adjust Metadata for Create action.
*
* The metadata is used for setting defaults, documentation & validation.
*
* @param array $spec
* Array of parameters determined by getfields.
*/
function _civicrm_api3_mapping_create_spec(&$spec) {
$spec['name']['api.required'] = 1;
}
/**
* Deletes an existing Mapping.
*
* @param array $params
*
* @return array
* API result Array
*/
function civicrm_api3_mapping_delete($params) {
return _civicrm_api3_basic_delete(_civicrm_api3_get_BAO(__FUNCTION__), $params);
}
/**
* Retrieve one or more Mappings.
*
* @param array $params
* An associative array of name/value pairs.
*
* @return array
* details of found Mappings
*/
function civicrm_api3_mapping_get($params) {
return _civicrm_api3_basic_get(_civicrm_api3_get_BAO(__FUNCTION__), $params);
}

View file

@ -0,0 +1,81 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
* This api exposes CiviCRM MappingField records.
*
* @package CiviCRM_APIv3
*/
/**
* Add a Mapping Field.
*
* @param array $params
*
* @return array
*/
function civicrm_api3_mapping_field_create($params) {
return _civicrm_api3_basic_create(_civicrm_api3_get_BAO(__FUNCTION__), $params);
}
/**
* Adjust Metadata for Create action.
*
* The metadata is used for setting defaults, documentation & validation.
*
* @param array $params
* Array of parameters determined by getfields.
*/
function _civicrm_api3_mapping_field_create_spec(&$params) {
$params['mapping_id']['api.required'] = 1;
}
/**
* Deletes an existing Mapping Field.
*
* @param array $params
*
* @return array
* API result Array
*/
function civicrm_api3_mapping_field_delete($params) {
return _civicrm_api3_basic_delete(_civicrm_api3_get_BAO(__FUNCTION__), $params);
}
/**
* Retrieve one or more Mapping Fields.
*
* @param array $params
* An associative array of name/value pairs.
*
* @return array
* details of found Mapping Fields
*/
function civicrm_api3_mapping_field_get($params) {
return _civicrm_api3_basic_get(_civicrm_api3_get_BAO(__FUNCTION__), $params);
}

View file

@ -0,0 +1,335 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* This api exposes CiviCRM membership contact records.
*
* @package CiviCRM_APIv3
*/
/**
* Adjust Metadata for Delete action.
*
* The metadata is used for setting defaults, documentation & validation.
*
* @param array $params
* Array of parameters determined by getfields.
*/
function _civicrm_api3_membership_delete_spec(&$params) {
$params['preserve_contribution'] = array(
'api.required' => 0,
'title' => 'Preserve Contribution',
'description' => 'By default this is 0, or 0 if not set. Set to 1 to preserve the associated contribution record when membership is deleted.',
'type' => CRM_Utils_Type::T_BOOLEAN,
);
}
/**
* Deletes an existing contact Membership.
*
* @param array $params
* Array array holding id - Id of the contact membership to be deleted.
* @return array API result array.
* @throws API_Exception
*/
function civicrm_api3_membership_delete($params) {
if (isset($params['preserve_contribution'])) {
if (CRM_Member_BAO_Membership::del($params['id'], $params['preserve_contribution'])) {
return civicrm_api3_create_success(TRUE, $params);
}
else {
throw new API_Exception(ts('Could not delete membership'));
}
}
else {
return _civicrm_api3_basic_delete(_civicrm_api3_get_BAO(__FUNCTION__), $params);
}
}
/**
* Create a Contact Membership.
*
* This API is used for creating a Membership for a contact.
* Required parameters : membership_type_id and status_id.
*
* @param array $params
* Array of name/value property values of civicrm_membership.
*
* @return array
* API result array.
*/
function civicrm_api3_membership_create($params) {
// check params for membership id during update
if (!empty($params['id']) && !isset($params['skipStatusCal'])) {
// Don't calculate status on existing membership - expect API use to pass them in
// or leave unchanged.
$params['skipStatusCal'] = 1;
}
else {
// also check for status id if override is set (during add/update)
if (!empty($params['is_override']) && empty($params['status_id'])) {
return civicrm_api3_create_error('Status ID required');
}
}
$values = array();
_civicrm_api3_custom_format_params($params, $values, 'Membership');
$params = array_merge($params, $values);
// Fixme: This code belongs in the BAO
if (empty($params['id']) || !empty($params['num_terms'])) {
if (empty($params['id'])) {
$calcDates = CRM_Member_BAO_MembershipType::getDatesForMembershipType(
$params['membership_type_id'],
CRM_Utils_Array::value('join_date', $params),
CRM_Utils_Array::value('start_date', $params),
CRM_Utils_Array::value('end_date', $params),
CRM_Utils_Array::value('num_terms', $params, 1)
);
}
else {
$calcDates = CRM_Member_BAO_MembershipType::getRenewalDatesForMembershipType(
$params['id'],
NULL,
CRM_Utils_Array::value('membership_type_id', $params),
$params['num_terms']
);
}
foreach (array('join_date', 'start_date', 'end_date') as $date) {
if (empty($params[$date]) && isset($calcDates[$date])) {
$params[$date] = $calcDates[$date];
}
}
}
// Fixme: This code belongs in the BAO
$action = CRM_Core_Action::ADD;
// we need user id during add mode
$ids = array();
if (!empty($params['contact_id'])) {
$ids['userId'] = $params['contact_id'];
}
//for edit membership id should be present
// probably not required now.
if (!empty($params['id'])) {
$ids['membership'] = $params['id'];
$action = CRM_Core_Action::UPDATE;
}
//need to pass action to handle related memberships.
$params['action'] = $action;
$membershipBAO = CRM_Member_BAO_Membership::create($params, $ids, TRUE);
if (array_key_exists('is_error', $membershipBAO)) {
// In case of no valid status for given dates, $membershipBAO
// is going to contain 'is_error' => "Error Message"
return civicrm_api3_create_error(ts('The membership can not be saved, no valid membership status for given dates'));
}
$membership = array();
_civicrm_api3_object_to_array($membershipBAO, $membership[$membershipBAO->id]);
return civicrm_api3_create_success($membership, $params, 'Membership', 'create', $membershipBAO);
}
/**
* Adjust Metadata for Create action.
*
* The metadata is used for setting defaults, documentation & validation.
*
* @param array $params
* Array of parameters determined by getfields.
*/
function _civicrm_api3_membership_create_spec(&$params) {
$params['contact_id']['api.required'] = 1;
$params['membership_type_id']['api.required'] = 1;
$params['is_test']['api.default'] = 0;
$params['membership_type_id']['api.aliases'] = array('membership_type');
$params['status_id']['api.aliases'] = array('membership_status');
$params['skipStatusCal'] = array(
'title' => 'Skip status calculation',
'description' => 'By default this is 0 if id is not set and 1 if it is set.',
'type' => CRM_Utils_Type::T_BOOLEAN,
);
$params['num_terms'] = array(
'title' => 'Number of terms',
'description' => 'Terms to add/renew. If this parameter is passed, dates will be calculated automatically. If no id is passed (new membership) and no dates are given, num_terms will be assumed to be 1.',
'type' => CRM_Utils_Type::T_INT,
);
}
/**
* Adjust Metadata for Get action.
*
* The metadata is used for setting defaults, documentation & validation.
*
* @param array $params
* Array of parameters determined by getfields.
*/
function _civicrm_api3_membership_get_spec(&$params) {
$params['membership_type_id']['api.aliases'] = array('membership_type');
$params['active_only'] = array(
'title' => 'Active Only',
'description' => 'Only retrieve active memberships',
'type' => CRM_Utils_Type::T_BOOLEAN,
);
}
/**
* Get contact Membership record.
*
* This api will return the membership records for the contacts
* having membership based on the relationship with the direct members.
*
* @param array $params
* Key/value pairs for contact_id and some.
* options affecting the desired results; has legacy support
* for just passing the contact_id itself as the argument
*
* @return array
* Array of all found membership property values.
*/
function civicrm_api3_membership_get($params) {
$activeOnly = $membershipTypeId = $membershipType = NULL;
$contactID = CRM_Utils_Array::value('contact_id', $params);
if (!empty($params['filters']) && is_array($params['filters']) && isset($params['filters']['is_current'])) {
$activeOnly = $params['filters']['is_current'];
unset($params['filters']['is_current']);
}
$activeOnly = CRM_Utils_Array::value('active_only', $params, $activeOnly);
if ($activeOnly && empty($params['status_id'])) {
$params['status_id'] = array('IN' => CRM_Member_BAO_MembershipStatus::getMembershipStatusCurrent());
}
$options = _civicrm_api3_get_options_from_params($params, TRUE, 'Membership', 'get');
if ($options['is_count']) {
return _civicrm_api3_basic_get(_civicrm_api3_get_BAO(__FUNCTION__), $params);
}
$membershipValues = _civicrm_api3_basic_get(_civicrm_api3_get_BAO(__FUNCTION__), $params, FALSE, 'Membership');
$return = $options['return'];
if (empty($membershipValues) ||
(!empty($return)
&& !array_key_exists('related_contact_id', $return)
&& !array_key_exists('relationship_name', $return)
)
) {
return civicrm_api3_create_success($membershipValues, $params, 'Membership', 'get');
}
$members = _civicrm_api3_membership_relationsship_get_customv2behaviour($params, $membershipValues, $contactID);
return civicrm_api3_create_success($members, $params, 'Membership', 'get');
}
/**
* Perform api v2 custom behaviour.
*
* When we copied apiv3 from api v2 we brought across some custom behaviours - in the case of
* membership a complicated return array is constructed. The original
* behaviour made contact_id a required field. We still need to keep this for v3 when contact_id
* is passed in as part of the reasonable expectation developers have that we will keep the api
* as stable as possible
*
* @param array $params
* Parameters passed into get function.
* @param int $membershipTypeId
* @param $activeOnly
*
* @return array
* result for calling function
*/
function _civicrm_api3_membership_get_customv2behaviour(&$params, $membershipTypeId, $activeOnly) {
// get the membership for the given contact ID
$membershipParams = array('contact_id' => $params['contact_id']);
if ($membershipTypeId) {
$membershipParams['membership_type_id'] = $membershipTypeId;
}
$membershipValues = array();
CRM_Member_BAO_Membership::getValues($membershipParams, $membershipValues, $activeOnly);
return $membershipValues;
}
/**
* Non-standard behaviour inherited from v2.
*
* @param array $params
* Parameters passed into get function.
* @param $membershipValues
* @param int $contactID
*
* @return array
* result for calling function
*/
function _civicrm_api3_membership_relationsship_get_customv2behaviour(&$params, $membershipValues, $contactID) {
$relationships = array();
foreach ($membershipValues as $membershipId => $values) {
// populate the membership type name for the membership type id
$membershipType = CRM_Member_BAO_MembershipType::getMembershipTypeDetails($values['membership_type_id']);
$membershipValues[$membershipId]['membership_name'] = $membershipType['name'];
if (!empty($membershipType['relationship_type_id'])) {
$relationships[$membershipType['relationship_type_id']] = $membershipId;
}
// populating relationship type name.
$relationshipType = new CRM_Contact_BAO_RelationshipType();
$relationshipType->id = CRM_Utils_Array::value('relationship_type_id', $membershipType);
if ($relationshipType->find(TRUE)) {
$membershipValues[$membershipId]['relationship_name'] = $relationshipType->name_a_b;
}
_civicrm_api3_custom_data_get($membershipValues[$membershipId], CRM_Utils_Array::value('check_permissions', $params), 'Membership', $membershipId, NULL, $values['membership_type_id']);
}
$members = $membershipValues;
// Populating contacts in members array based on their relationship with direct members.
if (!empty($relationships)) {
foreach ($relationships as $relTypeId => $membershipId) {
// As members are not direct members, there should not be
// membership id in the result array.
unset($membershipValues[$membershipId]['id']);
$relationship = new CRM_Contact_BAO_Relationship();
$relationship->contact_id_b = $contactID;
$relationship->relationship_type_id = $relTypeId;
if ($relationship->find()) {
while ($relationship->fetch()) {
clone($relationship);
$membershipValues[$membershipId]['contact_id'] = $relationship->contact_id_a;
$members[$membershipId]['related_contact_id'] = $relationship->contact_id_a;
}
}
}
}
return $members;
}

View file

@ -0,0 +1,90 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
* This api exposes CiviCRM MembershipBlock records.
*
* @package CiviCRM_APIv3
*/
/**
* API to Create or update a MembershipBlock.
*
* @param array $params
* An associative array of name/value property values of MembershipBlock.
*
* @return array
* API result array
*/
function civicrm_api3_membership_block_create($params) {
return _civicrm_api3_basic_create(_civicrm_api3_get_BAO(__FUNCTION__), $params);
}
/**
* Adjust Metadata for Create action.
*
* The metadata is used for setting defaults, documentation & validation.
*
* @param array $params
* Array of parameters determined by getfields.
*/
function _civicrm_api3_membership_block_create_spec(&$params) {
$params['is_active']['api.default'] = TRUE;
$params['entity_id']['api.required'] = TRUE;
$params['entity_table']['api.default'] = 'civicrm_contribution_page';
}
/**
* Get a Membership Block.
*
* This api is used for finding an existing membership block.
*
* @param array $params
* An associative array of name/value property values of civicrm_membership_block.
* {getfields MembershipBlock_get}
*
* @return array
* API result array
*/
function civicrm_api3_membership_block_get($params) {
return _civicrm_api3_basic_get(_civicrm_api3_get_BAO(__FUNCTION__), $params);
}
/**
* Deletes an existing membership block.
*
* This API is used for deleting a membership block
* Required parameters : id of a membership block
*
* @param array $params
*
* @return array
* API result array
*/
function civicrm_api3_membership_block_delete($params) {
return _civicrm_api3_basic_delete(_civicrm_api3_get_BAO(__FUNCTION__), $params);
}

View file

@ -0,0 +1,88 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
* This api exposes CiviCRM MembershipLog records.
*
* @package CiviCRM_APIv3
*/
/**
* API to Create or update a MembershipLog.
*
* @param array $params
* Values of MembershipLog.
*
* @return array
* API result array.
*/
function civicrm_api3_membership_log_create($params) {
return _civicrm_api3_basic_create(_civicrm_api3_get_BAO(__FUNCTION__), $params);
}
/**
* Adjust Metadata for Create action.
*
* The metadata is used for setting defaults, documentation & validation.
*
* @param array $params
* Array of parameters determined by getfields.
*/
function _civicrm_api3_membership_log_create_spec(&$params) {
$params['membership_id']['api.required'] = TRUE;
}
/**
* Get a Membership Log.
*
* This api is used for finding an existing membership log.
*
* @param array $params
* An associative array of name/value property values of civicrm_membership_log.
* {getfields MembershipLog_get}
*
* @return array
* API result array
*/
function civicrm_api3_membership_log_get($params) {
return _civicrm_api3_basic_get(_civicrm_api3_get_BAO(__FUNCTION__), $params);
}
/**
* Deletes an existing membership log.
*
* This API is used for deleting a membership log
* Required parameters : id of a membership log
*
* @param array $params
*
* @return array
* API result array
*/
function civicrm_api3_membership_log_delete($params) {
return _civicrm_api3_basic_delete(_civicrm_api3_get_BAO(__FUNCTION__), $params);
}

View file

@ -0,0 +1,77 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
* This api exposes CiviCRM membership contribution link.
*
* @package CiviCRM_APIv3
* @todo delete function doesn't exist
*/
/**
* Add or update a link between contribution and membership.
*
* @param array $params
* Input parameters.
*
* @return array
* API result array.
*/
function civicrm_api3_membership_payment_create($params) {
return _civicrm_api3_basic_create(_civicrm_api3_get_BAO(__FUNCTION__), $params);
}
/**
* Adjust Metadata for Create action.
*
* The metadata is used for setting defaults, documentation & validation.
*
* @param array $params
* Array of parameters determined by getfields.
*/
function _civicrm_api3_membership_payment_create_spec(&$params) {
$params['membership_id']['api.required'] = 1;
$params['contribution_id']['api.required'] = 1;
$params['membership_type_id'] = array(
'title' => 'Membership type id',
'description' => 'The id of the membership type',
'type' => CRM_Utils_Type::T_INT,
);
}
/**
* Retrieve one or more membership payment records.
*
* @param array $params
* Input parameters.
*
* @return array
* API result array.
*/
function civicrm_api3_membership_payment_get($params) {
return _civicrm_api3_basic_get('CRM_Member_DAO_MembershipPayment', $params);
}

View file

@ -0,0 +1,194 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
* This api exposes CiviCRM membership status.
*
* @package CiviCRM_APIv3
*/
/**
* Create a Membership Status.
*
* @param array $params
* Array of name/value property values of civicrm_membership_status.
*
* @return array
*/
function civicrm_api3_membership_status_create($params) {
return _civicrm_api3_basic_create(_civicrm_api3_get_BAO(__FUNCTION__), $params);
}
/**
* Adjust Metadata for Create action.
*
* The metadata is used for setting defaults, documentation & validation.
*
* @param array $params
* Array of parameters determined by getfields.
*/
function _civicrm_api3_membership_status_create_spec(&$params) {
$params['name']['api.required'] = 1;
}
/**
* Get a membership status.
*
* This api is used for finding an existing membership status.
*
* @param array $params
* An associative array of name/value property values of civicrm_membership_status.
*
* @return array
* Array of all found membership status property values.
*/
function civicrm_api3_membership_status_get($params) {
return _civicrm_api3_basic_get('CRM_Member_BAO_MembershipStatus', $params);
}
/**
* Update an existing membership status.
*
* This api is used for updating an existing membership status.
* Required parameters: id of a membership status
*
* @param array $params
* Array of name/value property values of civicrm_membership_status.
*
* @deprecated - should just use create
*
* @return array
* Array of updated membership status property values
*/
function civicrm_api3_membership_status_update($params) {
civicrm_api3_verify_mandatory($params, NULL, array('id'));
//don't allow duplicate names.
$name = CRM_Utils_Array::value('name', $params);
if ($name) {
$status = new CRM_Member_DAO_MembershipStatus();
$status->name = $params['name'];
if ($status->find(TRUE) && $status->id != $params['id']) {
return civicrm_api3_create_error(ts('A membership status with this name already exists.'));
}
}
$membershipStatusBAO = new CRM_Member_BAO_MembershipStatus();
$membershipStatusBAO->id = $params['id'];
if ($membershipStatusBAO->find(TRUE)) {
$fields = $membershipStatusBAO->fields();
foreach ($fields as $name => $field) {
if (array_key_exists($name, $params)) {
$membershipStatusBAO->$name = $params[$name];
}
}
$membershipStatusBAO->save();
}
$membershipStatus = array();
$cloneBAO = clone($membershipStatusBAO);
_civicrm_api3_object_to_array($cloneBAO, $membershipStatus);
$membershipStatus['is_error'] = 0;
return $membershipStatus;
}
/**
* Deletes an existing membership status.
*
* This API is used for deleting a membership status
*
* @param array $params
* @return array
* @throws API_Exception
* @throws CRM_Core_Exception
*/
function civicrm_api3_membership_status_delete($params) {
$memberStatusDelete = CRM_Member_BAO_MembershipStatus::del($params['id'], TRUE);
if ($memberStatusDelete) {
throw new API_Exception($memberStatusDelete['error_message']);
}
return civicrm_api3_create_success();
}
/**
* Derives the Membership Status of a given Membership Record.
*
* This API is used for deriving Membership Status of a given Membership
* record using the rules encoded in the membership_status table.
*
* @param array $membershipParams
*
* @throws API_Exception
*
* @return array
* Array of status id and status name
*/
function civicrm_api3_membership_status_calc($membershipParams) {
if (!($membershipID = CRM_Utils_Array::value('membership_id', $membershipParams))) {
throw new API_Exception('membershipParams do not contain membership_id');
}
if (empty($membershipParams['id'])) {
//for consistency lets make sure id is set as this will get passed to hooks downstream
$membershipParams['id'] = $membershipID;
}
$query = "
SELECT start_date, end_date, join_date, membership_type_id
FROM civicrm_membership
WHERE id = %1
";
$params = array(1 => array($membershipID, 'Integer'));
$dao = CRM_Core_DAO::executeQuery($query, $params);
if ($dao->fetch()) {
$membershipTypeID = empty($membershipParams['membership_type_id']) ? $dao->membership_type_id : $membershipParams['membership_type_id'];
$result = CRM_Member_BAO_MembershipStatus::getMembershipStatusByDate($dao->start_date, $dao->end_date, $dao->join_date, 'today', CRM_Utils_Array::value('ignore_admin_only', $membershipParams), $membershipTypeID, $membershipParams);
//make is error zero only when valid status found.
if (!empty($result['id'])) {
$result['is_error'] = 0;
}
}
else {
$dao->free();
throw new API_Exception('did not find a membership record');
}
$dao->free();
return $result;
}
/**
* Adjust Metadata for Calc action.
*
* The metadata is used for setting defaults, documentation & validation.
*
* @param array $params
* Array of parameters determined by getfields.
*/
function _civicrm_api3_membership_status_calc_spec(&$params) {
$params['membership_id']['api.required'] = 1;
$params['membership_id']['title'] = 'Membership ID';
}

View file

@ -0,0 +1,128 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
* This api exposes CiviCRM membership type.
*
* @package CiviCRM_APIv3
*/
/**
* API to Create or update a Membership Type.
*
* @param array $params
* Array of name/value property values of civicrm_membership_type.
*
* @return array
* API result array.
*/
function civicrm_api3_membership_type_create($params) {
// Workaround for fields using nonstandard serialization
foreach (array('relationship_type_id', 'relationship_direction') as $field) {
if (isset($params[$field]) && is_array($params[$field])) {
$params[$field] = implode(CRM_Core_DAO::VALUE_SEPARATOR, $params[$field]);
}
}
return _civicrm_api3_basic_create(_civicrm_api3_get_BAO(__FUNCTION__), $params, 'Membership_type');
}
/**
* Adjust Metadata for Create action.
*
* The metadata is used for setting defaults, documentation & validation.
*
* @param array $params
* Array of parameters determined by getfields.
*/
function _civicrm_api3_membership_type_create_spec(&$params) {
// todo could set default here probably
$params['domain_id']['api.required'] = 1;
$params['member_of_contact_id']['api.required'] = 1;
$params['financial_type_id']['api.required'] = 1;
$params['name']['api.required'] = 1;
$params['duration_unit']['api.required'] = 1;
$params['duration_interval']['api.required'] = 1;
$params['period_type']['api.required'] = 1;
$params['is_active']['api.default'] = 1;
}
/**
* Get a Membership Type.
*
* This api is used for finding an existing membership type.
*
* @param array $params
* Array of name/value property values of civicrm_membership_type.
*
* @return array
* API result array.
*/
function civicrm_api3_membership_type_get($params) {
$results = _civicrm_api3_basic_get(_civicrm_api3_get_BAO(__FUNCTION__), $params);
if (!empty($results['values']) && is_array($results['values'])) {
foreach ($results['values'] as &$item) {
// Workaround for fields using nonstandard serialization
foreach (array('relationship_type_id', 'relationship_direction') as $field) {
if (isset($item[$field]) && !is_array($item[$field])) {
$item[$field] = (array) $item[$field];
}
}
}
}
return $results;
}
/**
* Adjust input for getlist action.
*
* We want to only return active membership types for getlist. It's a bit
* arguable whether this should be applied at the 'get' level but, since it's hard
* to unset we'll just do it here.
*
* The usage of getlist is entity-reference fields & the like
* so using only active ones makes sense.
*
* @param array $request
* Array of parameters determined by getfields.
*/
function _civicrm_api3_membership_type_getlist_params(&$request) {
if (!isset($request['params']['is_active']) && empty($request['params']['id'])) {
$request['params']['is_active'] = 1;
}
}
/**
* Deletes an existing membership type.
*
* @param array $params
*
* @return array
* API result array.
*/
function civicrm_api3_membership_type_delete($params) {
return _civicrm_api3_basic_delete(_civicrm_api3_get_BAO(__FUNCTION__), $params);
}

View file

@ -0,0 +1,203 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
* This api exposes CiviCRM message_template.
*
* @package CiviCRM_APIv3
*/
/**
* Create message template.
*
* @param array $params
*
* @return array
* @throws \API_Exception
*/
function civicrm_api3_message_template_create($params) {
return _civicrm_api3_basic_create(_civicrm_api3_get_BAO(__FUNCTION__), $params);
}
/**
* Adjust Metadata for Create action.
*
* The metadata is used for setting defaults, documentation & validation.
*
* @param array $params
* Array of parameters determined by getfields.
*/
function _civicrm_api3_message_template_create_spec(&$params) {
$params['msg_title']['api.required'] = 1;
$params['is_active']['api.default'] = TRUE;
/* $params['entity_id']['api.required'] = 1;
$params['entity_table']['api.default'] = "civicrm_contribution_recur";
$params['type']['api.default'] = "R";
*/
}
/**
* Delete message template.
*
* @param array $params
*
* @return bool
* API result array
*/
function civicrm_api3_message_template_delete($params) {
return _civicrm_api3_basic_delete(_civicrm_api3_get_BAO(__FUNCTION__), $params);
}
/**
* Adjust metadata for message_template get action.
*
* @param array $params
*/
function _civicrm_api3_message_template_get_spec(&$params) {
// fetch active records by default
$params['is_active']['api.default'] = 1;
}
/**
* Retrieve one or more message_template.
*
* @param array $params
* Array of name/value pairs.
*
* @return array
* API result array.
*/
function civicrm_api3_message_template_get($params) {
return _civicrm_api3_basic_get(_civicrm_api3_get_BAO(__FUNCTION__), $params);
}
/**
* Sends a template.
*
* @param array $params
* @throws API_Exception
*/
function civicrm_api3_message_template_send($params) {
// Change external param names to internal ones
$fieldSpec = array();
_civicrm_api3_message_template_send_spec($fieldSpec);
foreach ($fieldSpec as $field => $spec) {
if (isset($spec['api.aliases']) && array_key_exists($field, $params)) {
$params[CRM_Utils_Array::first($spec['api.aliases'])] = $params[$field];
unset($params[$field]);
}
}
if (empty($params['messageTemplateID'])) {
if (empty($params['groupName']) || empty($params['valueName'])) {
// Can't use civicrm_api3_verify_mandatory for this because it would give the wrong field names
throw new API_Exception(
"Mandatory key(s) missing from params array: requires id or option_group_name + option_value_name",
"mandatory_missing",
array("fields" => array('id', 'option_group_name', 'option_value_name'))
);
}
}
CRM_Core_BAO_MessageTemplate::sendTemplate($params);
}
/**
* Adjust Metadata for Create action.
*
* The metadata is used for setting defaults, documentation &
* validation.
*
* @param array $params
* Array of parameters determined by getfields.
*/
function _civicrm_api3_message_template_send_spec(&$params) {
$params['id']['description'] = 'ID of the template';
$params['id']['title'] = 'Message Template ID';
$params['id']['api.aliases'] = array('messageTemplateID', 'message_template_id');
$params['id']['type'] = CRM_Utils_Type::T_INT;
$params['option_group_name']['description'] = 'option group name of the template (required if no id supplied)';
$params['option_group_name']['title'] = 'Option Group Name';
$params['option_group_name']['api.aliases'] = array('groupName');
$params['option_group_name']['type'] = CRM_Utils_Type::T_STRING;
$params['option_value_name']['description'] = 'option value name of the template (required if no id supplied)';
$params['option_value_name']['title'] = 'Option Value Name';
$params['option_value_name']['api.aliases'] = array('valueName');
$params['option_value_name']['type'] = CRM_Utils_Type::T_STRING;
$params['contact_id']['description'] = 'contact id if contact tokens are to be replaced';
$params['contact_id']['title'] = 'Contact ID';
$params['contact_id']['api.aliases'] = array('contactId');
$params['contact_id']['type'] = CRM_Utils_Type::T_INT;
$params['template_params']['description'] = 'additional template params (other than the ones already set in the template singleton)';
$params['template_params']['title'] = 'Template Params';
$params['template_params']['api.aliases'] = array('tplParams');
// FIXME: Type??
$params['from']['description'] = 'the From: header';
$params['from']['title'] = 'From';
$params['from']['type'] = CRM_Utils_Type::T_STRING;
$params['to_name']['description'] = 'the recipients name';
$params['to_name']['title'] = 'Recipient Name';
$params['to_name']['api.aliases'] = array('toName');
$params['to_name']['type'] = CRM_Utils_Type::T_STRING;
$params['to_email']['description'] = 'the recipients email - mail is sent only if set';
$params['to_email']['title'] = 'Recipient Email';
$params['to_email']['api.aliases'] = array('toEmail');
$params['to_email']['type'] = CRM_Utils_Type::T_STRING;
$params['cc']['description'] = 'the Cc: header';
$params['cc']['title'] = 'CC';
$params['cc']['type'] = CRM_Utils_Type::T_STRING;
$params['bcc']['description'] = 'the Bcc: header';
$params['bcc']['title'] = 'BCC';
$params['bcc']['type'] = CRM_Utils_Type::T_STRING;
$params['reply_to']['description'] = 'the Reply-To: header';
$params['reply_to']['title'] = 'Reply To';
$params['reply_to']['api.aliases'] = array('replyTo');
$params['reply_to']['type'] = CRM_Utils_Type::T_STRING;
$params['attachments']['description'] = 'email attachments';
$params['attachments']['title'] = 'Attachments';
// FIXME: Type??
$params['is_test']['description'] = 'whether this is a test email (and hence should include the test banner)';
$params['is_test']['title'] = 'Is Test';
$params['is_test']['api.aliases'] = array('isTest');
$params['is_test']['type'] = CRM_Utils_Type::T_BOOLEAN;
$params['pdf_filename']['description'] = 'filename of optional PDF version to add as attachment (do not include path)';
$params['pdf_filename']['title'] = 'PDF Filename';
$params['pdf_filename']['api.aliases'] = array('PDFFilename');
$params['pdf_filename']['type'] = CRM_Utils_Type::T_STRING;
}

View file

@ -0,0 +1,134 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
* This api exposes CiviCRM Navigation BAO.
*
* @package CiviCRM_APIv3
*/
/**
* Adjust metadata for navigation reset action.
*
* @param array $params
*/
function _civicrm_api3_navigation_reset_spec(&$params) {
$params['for']['api.required'] = TRUE;
$params['for']['title'] = "Is this reset for all navigation or reports";
$params['for']['type'] = CRM_Utils_Type::T_STRING;
$params['for']['options'] = array(
'all' => 'General Navigation rebuild from xml',
'report' => 'Reset report menu to default structure',
);
$params['domain_id']['api.default'] = CRM_Core_Config::domainID();
$params['domain_id']['type'] = CRM_Utils_Type::T_INT;
$params['domain_id']['title'] = 'Domain ID';
}
/**
* Reset navigation.
*
* @param array $params
* Array of name/value pairs.
*
* @return array
* API result array.
*/
function civicrm_api3_navigation_reset($params) {
if ($params['for'] == 'report') {
CRM_Core_BAO_Navigation::rebuildReportsNavigation($params['domain_id']);
}
CRM_Core_BAO_Navigation::resetNavigation();
return civicrm_api3_create_success(1, $params, 'navigation', 'reset');
}
/**
* Adjust metadata for navigation get action.
*
* @param array $params
*/
function _civicrm_api3_navigation_get_spec(&$params) {
}
/**
* Reset navigation.
*
* @param array $params
* Array of name/value pairs.
*
* @return array
* API result array.
*/
function civicrm_api3_navigation_get($params) {
return _civicrm_api3_basic_get(_civicrm_api3_get_BAO(__FUNCTION__), $params);
}
/**
* Adjust metadata for navigation create action.
*
* @param array $params
*/
function _civicrm_api3_navigation_create_spec(&$params) {
$params['domain_id']['api.default'] = CRM_Core_Config::domainID();
$params['domain_id']['type'] = CRM_Utils_Type::T_INT;
$params['domain_id']['title'] = 'Domain ID';
}
/**
* Create navigation item.
*
* @param array $params
* Array of name/value pairs.
*
* @return array
* API result array.
*/
function civicrm_api3_navigation_create($params) {
civicrm_api3_verify_one_mandatory($params, NULL, array('name', 'label'));
return _civicrm_api3_basic_create(_civicrm_api3_get_BAO(__FUNCTION__), $params);
}
/**
* Adjust metadata for navigation create action.
*
* @param array $params
*/
function _civicrm_api3_navigation_delete_spec(&$params) {
}
/**
* Delete navigation item.
*
* @param array $params
* Array of name/value pairs.
*
* @return array
* API result array.
*/
function civicrm_api3_navigation_delete($params) {
return _civicrm_api3_basic_delete(_civicrm_api3_get_BAO(__FUNCTION__), $params);
}

View file

@ -0,0 +1,129 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
* This api exposes CiviCRM note.
*
* @package CiviCRM_APIv3
*/
/**
* Create Note.
*
* This API is used for creating a note.
* Required parameters : entity_id AND note
*
* @param array $params
* An associative array of name/value property values of civicrm_note.
*
* @return array
* API result array
*/
function civicrm_api3_note_create($params) {
return _civicrm_api3_basic_create(_civicrm_api3_get_BAO(__FUNCTION__), $params);
}
/**
* Adjust Metadata for Create action.
*
* The metadata is used for setting defaults, documentation & validation.
*
* @param array $params
* Array of parameters determined by getfields.
*/
function _civicrm_api3_note_create_spec(&$params) {
$params['entity_table']['api.default'] = "civicrm_contact";
$params['modified_date']['api.default'] = "now";
$params['note']['api.required'] = 1;
$params['entity_id']['api.required'] = 1;
}
/**
* Deletes an existing note.
*
* This API is used for deleting a note
*
* @param array $params
* Including id of the note to be deleted.
*
* @return array
*/
function civicrm_api3_note_delete($params) {
$result = new CRM_Core_BAO_Note();
return $result->del($params['id']) ? civicrm_api3_create_success() : civicrm_api3_create_error('Error while deleting Note');
}
/**
* Retrieve a specific note or notes, given a set of input params.
*
* @param array $params
* Input parameters.
*
* @return array
* array of properties,
* if error an array with an error id and error message
*/
function civicrm_api3_note_get($params) {
return _civicrm_api3_basic_get('CRM_Core_BAO_Note', $params);
}
/**
* Adjust Metadata for Get action.
*
* The metadata is used for setting defaults, documentation & validation.
*
* @param array $params
* Array of parameters determined by getfields.
*/
function _civicrm_api3_note_get_spec(&$params) {
$params['entity_table']['api.default'] = "civicrm_contact";
}
/**
* Get all descendants of given note.
*
* @param array $params
* array; only required 'id' parameter is used.
*
* @return array
* Nested associative array beginning with direct children of given note.
*/
function civicrm_api3_note_tree_get($params) {
civicrm_api3_verify_mandatory($params, NULL, array('id'));
if (!is_numeric($params['id'])) {
return civicrm_api3_create_error(ts("Invalid note ID"));
}
if (!isset($params['max_depth'])) {
$params['max_depth'] = 0;
}
if (!isset($params['snippet'])) {
$params['snippet'] = FALSE;
}
$noteTree = CRM_Core_BAO_Note::getNoteTree($params['id'], $params['max_depth'], $params['snippet']);
return civicrm_api3_create_success($noteTree, $params);
}

View file

@ -0,0 +1,81 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
* This api exposes CiviCRM OpenID records.
*
* @package CiviCRM_APIv3
*/
/**
* Add an OpenID for a contact.
*
* @param array $params
*
* @return array
* API result array
*/
function civicrm_api3_open_i_d_create($params) {
return _civicrm_api3_basic_create(_civicrm_api3_get_BAO(__FUNCTION__), $params);
}
/**
* Adjust Metadata for Create action.
*
* The metadata is used for setting defaults, documentation & validation.
*
* @param array $params
* Array of parameters determined by getfields.
*/
function _civicrm_api3_open_i_d_create_spec(&$params) {
$params['contact_id']['api.required'] = 1;
}
/**
* Deletes an existing OpenID.
*
* @param array $params
*
* @return array
* API result array
*/
function civicrm_api3_open_i_d_delete($params) {
return _civicrm_api3_basic_delete(_civicrm_api3_get_BAO(__FUNCTION__), $params);
}
/**
* Retrieve one or more OpenID.
*
* @param array $params
* An associative array of name/value pairs.
*
* @return array
* API result array
*/
function civicrm_api3_open_i_d_get($params) {
return _civicrm_api3_basic_get(_civicrm_api3_get_BAO(__FUNCTION__), $params);
}

View file

@ -0,0 +1,85 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
* This api exposes CiviCRM option groups.
*
* OptionGroups are containers for option values.
*
* @package CiviCRM_APIv3
*/
/**
* Get option groups.
*
* @param array $params
*
* @return array
*/
function civicrm_api3_option_group_get($params) {
return _civicrm_api3_basic_get(_civicrm_api3_get_BAO(__FUNCTION__), $params);
}
/**
* Create/update option group.
*
* @param array $params
* Array per getfields metadata.
*
* @return array
*/
function civicrm_api3_option_group_create($params) {
return _civicrm_api3_basic_create(_civicrm_api3_get_BAO(__FUNCTION__), $params);
}
/**
* Adjust Metadata for Create action.
*
* The metadata is used for setting defaults, documentation & validation.
*
* @param array $params
* Array of parameters determined by getfields.
*/
function _civicrm_api3_option_group_create_spec(&$params) {
$params['name']['api.unique'] = 1;
$params['is_active']['api.default'] = TRUE;
}
/**
* Delete an existing Option Group.
*
* This method is used to delete any existing OptionGroup given its id.
*
* @param array $params
* [id]
*
* @return array
* API Result Array
*/
function civicrm_api3_option_group_delete($params) {
return _civicrm_api3_basic_delete(_civicrm_api3_get_BAO(__FUNCTION__), $params);
}

View file

@ -0,0 +1,118 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
* This api exposes CiviCRM option values.
*
* Values are grouped by "OptionGroup"
*
* @package CiviCRM_APIv3
*/
/**
* Retrieve one or more option values.
*
* @param array $params
*
* @return array
* API result array
*/
function civicrm_api3_option_value_get($params) {
return _civicrm_api3_basic_get(_civicrm_api3_get_BAO(__FUNCTION__), $params);
}
/**
* Adjust Metadata for get action.
*
* The metadata is used for setting defaults, documentation & validation.
*
* @param array $params
* Array of parameters determined by getfields.
*/
function _civicrm_api3_option_value_get_spec(&$params) {
$params['option_group_id']['api.aliases'] = array('option_group_name');
}
/**
* Add an OptionValue.
*
* @param array $params
*
* @throws API_Exception
* @return array
* API result array
*/
function civicrm_api3_option_value_create($params) {
$result = _civicrm_api3_basic_create(_civicrm_api3_get_BAO(__FUNCTION__), $params);
if (!empty($params['id']) && !array_key_exists('option_group_id', $params)) {
$groupId = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_OptionValue',
$params['id'], 'option_group_id', 'id'
);
}
else {
$groupId = $params['option_group_id'];
}
civicrm_api('option_value', 'getfields', array('version' => 3, 'cache_clear' => 1, 'option_group_id' => $groupId));
return $result;
}
/**
* Adjust Metadata for Create action.
*
* The metadata is used for setting defaults, documentation & validation.
*
* @param array $params
* Array of parameters determined by getfields.
*/
function _civicrm_api3_option_value_create_spec(&$params) {
$params['is_active']['api.default'] = 1;
//continue to support component
$params['component_id']['api.aliases'] = array('component');
// $params['name']['api.aliases'] = array('label');
$params['option_group_id']['api.required'] = TRUE;
}
/**
* Deletes an existing option value.
*
* @param array $params
* @return array API result array
* @throws API_Exception
*/
function civicrm_api3_option_value_delete($params) {
// We will get the option group id before deleting so we can flush pseudoconstants.
$optionGroupID = civicrm_api('option_value', 'getvalue', array('version' => 3, 'id' => $params['id'], 'return' => 'option_group_id'));
$result = CRM_Core_BAO_OptionValue::del($params['id']);
if ($result) {
civicrm_api('option_value', 'getfields', array('version' => 3, 'cache_clear' => 1, 'option_group_id' => $optionGroupID));
return civicrm_api3_create_success();
}
else {
throw new API_Exception('Could not delete OptionValue ' . $params['id']);
}
}

View file

@ -0,0 +1,228 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
* This api exposes CiviCRM Order objects, an abstract entity
* comprised of contributions and related line items.
*
* @package CiviCRM_APIv3
*/
/**
* Retrieve a set of Order.
*
* @param array $params
* Input parameters.
*
* @return array
* Array of Order, if error an array with an error id and error message
*/
function civicrm_api3_order_get($params) {
$contributions = array();
$params['api.line_item.get'] = array('qty' => array('<>' => 0));
$isSequential = FALSE;
if (CRM_Utils_Array::value('sequential', $params)) {
$params['sequential'] = 0;
$isSequential = TRUE;
}
$result = civicrm_api3('Contribution', 'get', $params);
if (!empty($result['values'])) {
foreach ($result['values'] as $key => $contribution) {
$contributions[$key] = $contribution;
$contributions[$key]['line_items'] = $contribution['api.line_item.get']['values'];
unset($contributions[$key]['api.line_item.get']);
}
}
$params['sequential'] = $isSequential;
return civicrm_api3_create_success($contributions, $params, 'Order', 'get');
}
/**
* Add or update a Order.
*
* @param array $params
* Input parameters.
*
* @throws API_Exception
* @return array
* Api result array
*/
function civicrm_api3_order_create(&$params) {
$contribution = array();
$entity = NULL;
$entityIds = array();
if (CRM_Utils_Array::value('line_items', $params) && is_array($params['line_items'])) {
$priceSetID = NULL;
CRM_Contribute_BAO_Contribution::checkLineItems($params);
foreach ($params['line_items'] as $lineItems) {
$entityParams = CRM_Utils_Array::value('params', $lineItems, array());
if (!empty($entityParams) && !empty($lineItems['line_item'])) {
$item = reset($lineItems['line_item']);
$entity = str_replace('civicrm_', '', $item['entity_table']);
}
if ($entityParams) {
if (in_array($entity, array('participant', 'membership'))) {
$entityParams['skipLineItem'] = TRUE;
$entityResult = civicrm_api3($entity, 'create', $entityParams);
$params['contribution_mode'] = $entity;
$entityIds[] = $params[$entity . '_id'] = $entityResult['id'];
foreach ($lineItems['line_item'] as &$items) {
$items['entity_id'] = $entityResult['id'];
}
}
else {
// pledge payment
}
}
if (empty($priceSetID)) {
$item = reset($lineItems['line_item']);
$priceSetID = civicrm_api3('PriceField', 'getvalue', array(
'return' => 'price_set_id',
'id' => $item['price_field_id'],
));
$params['line_item'][$priceSetID] = array();
}
$params['line_item'][$priceSetID] = array_merge($params['line_item'][$priceSetID], $lineItems['line_item']);
}
}
$contribution = civicrm_api3('Contribution', 'create', $params);
// add payments
if ($entity && CRM_Utils_Array::value('id', $contribution)) {
foreach ($entityIds as $entityId) {
$paymentParams = array(
'contribution_id' => $contribution['id'],
$entity . '_id' => $entityId,
);
// if entity is pledge then build pledge param
if ($entity == 'pledge') {
$paymentParams += $entityParams;
}
$payments = civicrm_api3($entity . '_payment', 'create', $paymentParams);
}
}
return civicrm_api3_create_success(CRM_Utils_Array::value('values', $contribution), $params, 'Order', 'create');
}
/**
* Delete a Order.
*
* @param array $params
* Input parameters.
* @return array
* @throws API_Exception
* @throws CiviCRM_API3_Exception
*/
function civicrm_api3_order_delete($params) {
$contribution = civicrm_api3('Contribution', 'get', array(
'return' => array('is_test'),
'id' => $params['id'],
));
if ($contribution['id'] && $contribution['values'][$contribution['id']]['is_test'] == TRUE) {
$result = civicrm_api3('Contribution', 'delete', $params);
}
else {
throw new API_Exception('Only test orders can be deleted.');
}
return civicrm_api3_create_success($result['values'], $params, 'Order', 'delete');
}
/**
* Cancel an Order.
*
* @param array $params
* Input parameters.
*
* @return array
*/
function civicrm_api3_order_cancel($params) {
$contributionStatuses = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
$params['contribution_status_id'] = array_search('Cancelled', $contributionStatuses);
$result = civicrm_api3('Contribution', 'create', $params);
CRM_Contribute_BAO_Contribution::transitionComponents($params);
return civicrm_api3_create_success($result['values'], $params, 'Order', 'cancel');
}
/**
* Adjust Metadata for Cancel action.
*
* The metadata is used for setting defaults, documentation & validation.
*
* @param array $params
* Array of parameters determined by getfields.
*/
function _civicrm_api3_order_cancel_spec(&$params) {
$params['contribution_id'] = array(
'api.required' => 1 ,
'title' => 'Contribution ID',
'type' => CRM_Utils_Type::T_INT,
);
}
/**
* Adjust Metadata for Create action.
*
* The metadata is used for setting defaults, documentation & validation.
*
* @param array $params
* Array of parameters determined by getfields.
*/
function _civicrm_api3_order_create_spec(&$params) {
$params['contact_id'] = array(
'name' => 'contact_id',
'title' => 'Contact ID',
'type' => CRM_Utils_Type::T_INT,
'api.required' => TRUE,
);
$params['total_amount'] = array(
'name' => 'total_amount',
'title' => 'Total Amount',
'api.required' => TRUE,
);
$params['financial_type_id'] = array(
'name' => 'financial_type_id',
'title' => 'Financial Type',
'type' => CRM_Utils_Type::T_INT,
'api.required' => TRUE,
);
}
/**
* Adjust Metadata for Delete action.
*
* The metadata is used for setting defaults, documentation & validation.
*
* @param array $params
* Array of parameters determined by getfields.
*/
function _civicrm_api3_order_delete_spec(&$params) {
$params['contribution_id'] = array(
'api.required' => TRUE,
'title' => 'Contribution ID',
'type' => CRM_Utils_Type::T_INT,
);
$params['id']['api.aliases'] = array('contribution_id');
}

View file

@ -0,0 +1,212 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
* This api exposes CiviCRM participant.
*
* @package CiviCRM_APIv3
*/
/**
* Create an Event Participant.
*
* @param array $params
* An associative array of name/value property values of civicrm_participant.
*
* @return array
* API result array
*/
function civicrm_api3_participant_create($params) {
// Check that event id is not an template - should be done @ BAO layer.
if (!empty($params['event_id'])) {
$isTemplate = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $params['event_id'], 'is_template');
if (!empty($isTemplate)) {
return civicrm_api3_create_error(ts('Event templates are not meant to be registered.'));
}
}
$values = $participant = array();
_civicrm_api3_custom_format_params($params, $values, 'Participant');
$params = array_merge($values, $params);
$participantBAO = CRM_Event_BAO_Participant::create($params);
if (empty($params['price_set_id']) && empty($params['id']) && !empty($params['fee_level'])) {
_civicrm_api3_participant_createlineitem($params, $participantBAO);
}
_civicrm_api3_object_to_array($participantBAO, $participant[$participantBAO->id]);
return civicrm_api3_create_success($participant, $params, 'Participant', 'create', $participantBAO);
}
/**
* Create a default participant line item.
*
* @todo this should be done in the BAO not the api
*
* @param array $params
* @param $participant
*
* @throws \CiviCRM_API3_Exception
*/
function _civicrm_api3_participant_createlineitem(&$params, $participant) {
// it is possible that a fee level contains information about multiple
// price field values.
$priceFieldValueDetails = CRM_Utils_Array::explodePadded(
$params["fee_level"]);
foreach ($priceFieldValueDetails as $detail) {
if (preg_match('/- ([0-9]+)$/', $detail, $matches)) {
// it is possible that a price field value is payd for multiple times.
// (FIXME: if the price field value ends in minus followed by whitespace
// and a number, things will go wrong.)
$qty = $matches[1];
preg_match('/^(.*) - [0-9]+$/', $detail, $matches);
$label = $matches[1];
}
else {
$label = $detail;
$qty = 1;
}
$sql = "
SELECT ps.id AS setID, pf.id AS priceFieldID, pfv.id AS priceFieldValueID, pfv.amount AS amount
FROM civicrm_price_set_entity cpse
LEFT JOIN civicrm_price_set ps ON cpse.price_set_id = ps.id AND cpse.entity_id = %1 AND cpse.entity_table = 'civicrm_event'
LEFT JOIN civicrm_price_field pf ON pf.`price_set_id` = ps.id
LEFT JOIN civicrm_price_field_value pfv ON pfv.price_field_id = pf.id
where ps.id is not null and pfv.label = %2
";
$qParams = array(
1 => array($params['event_id'], 'Integer'),
2 => array($label, 'String'),
);
$dao = CRM_Core_DAO::executeQuery($sql, $qParams);
if ($dao->fetch()) {
$lineItemParams = array(
'price_field_id' => $dao->priceFieldID,
'price_field_value_id' => $dao->priceFieldValueID,
'entity_table' => 'civicrm_participant',
'entity_id' => $participant->id,
'label' => $label,
'qty' => $qty,
'participant_count' => 0,
'unit_price' => $dao->amount,
'line_total' => $qty * $dao->amount,
);
civicrm_api3('line_item', 'create', $lineItemParams);
}
}
}
/**
* Adjust Metadata for Create action.
*
* The metadata is used for setting defaults, documentation & validation.
*
* @param array $params
* Array of parameters determined by getfields.
*/
function _civicrm_api3_participant_create_spec(&$params) {
$params['status_id']['api.default'] = "1";
$params['register_date']['api.default'] = "now";
$params['event_id']['api.required'] = 1;
$params['contact_id']['api.required'] = 1;
// These are for the sake of search builder options - can be removed if that is fixed
$params['role_id']['api.aliases'] = array('participant_role');
$params['status_id']['api.aliases'] = array('participant_status');
}
/**
* Retrieve a specific participant, given a set of input params.
*
* @param array $params
* input parameters.
*
* @return array
* array of properties, if error an array with an error id and error message
*/
function civicrm_api3_participant_get($params) {
$mode = CRM_Contact_BAO_Query::MODE_EVENT;
list($dao, $query) = _civicrm_api3_get_query_object($params, $mode, 'Participant');
$participant = array();
while ($dao->fetch()) {
$query->convertToPseudoNames($dao, FALSE, TRUE);
$participant[$dao->participant_id] = $query->store($dao);
//@todo - is this required - contribution & pledge use the same query but don't self-retrieve custom data
_civicrm_api3_custom_data_get($participant[$dao->participant_id], CRM_Utils_Array::value('check_permissions', $params), 'Participant', $dao->participant_id, NULL);
}
return civicrm_api3_create_success($participant, $params, 'Participant', 'get', $dao);
}
/**
* Adjust Metadata for Get action.
*
* The metadata is used for setting defaults, documentation & validation.
*
* @param array $params
* Array of parameters determined by getfields.
*/
function _civicrm_api3_participant_get_spec(&$params) {
$params['participant_test'] = array(
'api.default' => 0,
'title' => 'Get Test Participants',
'type' => CRM_Utils_Type::T_BOOLEAN,
);
}
/**
* Deletes an existing contact participant.
*
* This API is used for deleting a contact participant
*
* @param array $params
* Array containing Id of the contact participant to be deleted.
*
* @throws Exception
* @return array
*/
function civicrm_api3_participant_delete($params) {
$result = CRM_Event_BAO_Participant::deleteParticipant($params['id']);
if ($result) {
return civicrm_api3_create_success();
}
else {
throw new Exception('Error while deleting participant');
}
}

View file

@ -0,0 +1,96 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
* This api exposes CiviCRM participant payments.
*
* @package CiviCRM_APIv3
*/
/**
* Create a Event Participant Payment.
*
* This API is used for creating a Participant Payment of Event.
* Required parameters: participant_id, contribution_id.
*
* @param array $params
* An associative array of name/value property values of civicrm_participant_payment.
*
* @return array
*/
function civicrm_api3_participant_payment_create($params) {
$ids = array();
if (!empty($params['id'])) {
$ids['id'] = $params['id'];
}
$participantPayment = CRM_Event_BAO_ParticipantPayment::create($params, $ids);
$payment = array();
_civicrm_api3_object_to_array($participantPayment, $payment[$participantPayment->id]);
return civicrm_api3_create_success($payment, $params);
}
/**
* Adjust Metadata for Create action.
*
* The metadata is used for setting defaults, documentation & validation.
*
* @param array $params
* Array of parameters determined by getfields.
*/
function _civicrm_api3_participant_payment_create_spec(&$params) {
$params['participant_id']['api.required'] = 1;
$params['contribution_id']['api.required'] = 1;
}
/**
* Deletes an existing Participant Payment.
*
* @param array $params
*
* @return array
* API result
*/
function civicrm_api3_participant_payment_delete($params) {
$participant = new CRM_Event_BAO_ParticipantPayment();
return $participant->deleteParticipantPayment($params) ? civicrm_api3_create_success() : civicrm_api3_create_error('Error while deleting participantPayment');
}
/**
* Retrieve one or more participant payment records.
*
* @param array $params
* Input parameters.
*
* @return array
* array of properties, if error an array with an error id and error message
*/
function civicrm_api3_participant_payment_get($params) {
return _civicrm_api3_basic_get('CRM_Event_DAO_ParticipantPayment', $params);
}

View file

@ -0,0 +1,80 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
* This api exposes CiviCRM participant status options.
*
* @package CiviCRM_APIv3
*/
/**
* Create/update participant_status.
*
* This API is used to create new participant_status or update any of the existing
* In case of updating existing participant_status, id of that particular participant_status must
* be in $params array.
*
* @param array $params
* name/value pairs to insert in new 'participant_status'
*
* @return array
* participant_status array
*/
function civicrm_api3_participant_status_type_create($params) {
return _civicrm_api3_basic_create(_civicrm_api3_get_BAO(__FUNCTION__), $params);
}
/**
* Returns array of participant_statuses matching a set of one or more group properties.
*
* @param array $params
* Array of properties. If empty, all records will be returned.
*
* @return array
* Array of matching participant_statuses
*/
function civicrm_api3_participant_status_type_get($params) {
return _civicrm_api3_basic_get(_civicrm_api3_get_BAO(__FUNCTION__), $params);
}
/**
* Delete an existing participant_status.
*
* This method is used to delete any existing participant_status given its id.
*
* @param array $params
* [id]
* @return array api result array
* @throws API_Exception
*/
function civicrm_api3_participant_status_type_delete($params) {
if (CRM_Event_BAO_ParticipantStatusType::deleteParticipantStatusType($params['id'])) {
return civicrm_api3_create_success(TRUE);
}
throw new API_Exception('Could not delete participant status type id ' . $params['id']);
}

View file

@ -0,0 +1,303 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
* This api exposes CiviCRM Contribution Payment records.
*
* @package CiviCRM_APIv3
*/
/**
* Retrieve a set of financial transactions which are payments.
*
* @param array $params
* Input parameters.
*
* @return array
* Array of financial transactions which are payments, if error an array with an error id and error message
*/
function civicrm_api3_payment_get($params) {
$financialTrxn = array();
$limit = '';
if (isset($params['options']) && CRM_Utils_Array::value('limit', $params['options'])) {
$limit = CRM_Utils_Array::value('limit', $params['options']);
}
$params['options']['limit'] = 0;
$eft = civicrm_api3('EntityFinancialTrxn', 'get', $params);
if (!empty($eft['values'])) {
$eftIds = array();
foreach ($eft['values'] as $efts) {
if (empty($efts['financial_trxn_id'])) {
continue;
}
$eftIds[] = $efts['financial_trxn_id'];
$map[$efts['financial_trxn_id']] = $efts['entity_id'];
}
if (!empty($eftIds)) {
$ftParams = array(
'id' => array('IN' => $eftIds),
'is_payment' => 1,
);
if ($limit) {
$ftParams['options']['limit'] = $limit;
}
$financialTrxn = civicrm_api3('FinancialTrxn', 'get', $ftParams);
foreach ($financialTrxn['values'] as &$values) {
$values['contribution_id'] = $map[$values['id']];
}
}
}
return civicrm_api3_create_success(CRM_Utils_Array::value('values', $financialTrxn, array()), $params, 'Payment', 'get');
}
/**
* Delete a payment.
*
* @param array $params
* Input parameters.
*
* @throws API_Exception
* @return array
* Api result array
*/
function civicrm_api3_payment_delete(&$params) {
return civicrm_api3('FinancialTrxn', 'delete', $params);
}
/**
* Cancel/Refund a payment for a Contribution.
*
* @param array $params
* Input parameters.
*
* @throws API_Exception
* @return array
* Api result array
*/
function civicrm_api3_payment_cancel(&$params) {
$eftParams = array(
'entity_table' => 'civicrm_contribution',
'financial_trxn_id' => $params['id'],
);
$entity = civicrm_api3('EntityFinancialTrxn', 'getsingle', $eftParams);
$contributionId = $entity['entity_id'];
$params['total_amount'] = $entity['amount'];
unset($params['id']);
$trxn = CRM_Contribute_BAO_Contribution::recordAdditionalPayment($contributionId, $params, 'refund', NULL, FALSE);
$values = array();
_civicrm_api3_object_to_array_unique_fields($trxn, $values[$trxn->id]);
return civicrm_api3_create_success($values, $params, 'Payment', 'cancel', $trxn);
}
/**
* Add a payment for a Contribution.
*
* @param array $params
* Input parameters.
*
* @throws API_Exception
* @return array
* Api result array
*/
function civicrm_api3_payment_create(&$params) {
// Check if it is an update
if (CRM_Utils_Array::value('id', $params)) {
$amount = $params['total_amount'];
civicrm_api3('Payment', 'cancel', $params);
$params['total_amount'] = $amount;
}
// Get contribution
$contribution = civicrm_api3('Contribution', 'getsingle', array('id' => $params['contribution_id']));
$contributionStatus = CRM_Contribute_PseudoConstant::contributionStatus($contribution['contribution_status_id'], 'name');
if ($contributionStatus != 'Partially paid'
&& !($contributionStatus == 'Pending' && $contribution['is_pay_later'] == TRUE)
) {
throw new API_Exception('Please select a contribution which has a partial or pending payment');
}
else {
// Check if pending contribution
$fullyPaidPayLater = FALSE;
if ($contributionStatus == 'Pending') {
$cmp = bccomp($contribution['total_amount'], $params['total_amount'], 5);
// Total payment amount is the whole amount paid against pending contribution
if ($cmp == 0 || $cmp == -1) {
civicrm_api3('Contribution', 'completetransaction', array('id' => $contribution['id']));
// Get the trxn
$trxnId = CRM_Core_BAO_FinancialTrxn::getFinancialTrxnId($contribution['id'], 'DESC');
$ftParams = array('id' => $trxnId['financialTrxnId']);
$trxn = CRM_Core_BAO_FinancialTrxn::retrieve($ftParams, CRM_Core_DAO::$_nullArray);
$fullyPaidPayLater = TRUE;
}
else {
civicrm_api3('Contribution', 'create',
array(
'id' => $contribution['id'],
'contribution_status_id' => 'Partially paid',
)
);
}
}
if (!$fullyPaidPayLater) {
$trxn = CRM_Core_BAO_FinancialTrxn::getPartialPaymentTrxn($contribution, $params);
if (CRM_Utils_Array::value('line_item', $params) && !empty($trxn)) {
foreach ($params['line_item'] as $values) {
foreach ($values as $id => $amount) {
$p = array('id' => $id);
$check = CRM_Price_BAO_LineItem::retrieve($p, $defaults);
if (empty($check)) {
throw new API_Exception('Please specify a valid Line Item.');
}
// get financial item
$sql = "SELECT fi.id
FROM civicrm_financial_item fi
INNER JOIN civicrm_line_item li ON li.id = fi.entity_id and fi.entity_table = 'civicrm_line_item'
WHERE li.contribution_id = %1 AND li.id = %2";
$sqlParams = array(
1 => array($params['contribution_id'], 'Integer'),
2 => array($id, 'Integer'),
);
$fid = CRM_Core_DAO::singleValueQuery($sql, $sqlParams);
// Record Entity Financial Trxn
$eftParams = array(
'entity_table' => 'civicrm_financial_item',
'financial_trxn_id' => $trxn->id,
'amount' => $amount,
'entity_id' => $fid,
);
civicrm_api3('EntityFinancialTrxn', 'create', $eftParams);
}
}
}
elseif (!empty($trxn)) {
// Assign the lineitems proportionally
CRM_Contribute_BAO_Contribution::assignProportionalLineItems($params, $trxn->id, $contribution['total_amount']);
}
}
}
$values = array();
_civicrm_api3_object_to_array_unique_fields($trxn, $values[$trxn->id]);
return civicrm_api3_create_success($values, $params, 'Payment', 'create', $trxn);
}
/**
* Adjust Metadata for Create action.
*
* The metadata is used for setting defaults, documentation & validation.
*
* @param array $params
* Array of parameters.
*/
function _civicrm_api3_payment_create_spec(&$params) {
$params = array(
'contribution_id' => array(
'api.required' => 1 ,
'title' => 'Contribution ID',
'type' => CRM_Utils_Type::T_INT,
),
'total_amount' => array(
'api.required' => 1 ,
'title' => 'Total Payment Amount',
'type' => CRM_Utils_Type::T_FLOAT,
),
'payment_processor_id' => array(
'title' => 'Payment Processor ID',
'type' => CRM_Utils_Type::T_INT,
'description' => ts('Payment processor ID - required for payment processor payments'),
),
'id' => array(
'title' => 'Payment ID',
'type' => CRM_Utils_Type::T_INT,
'api.aliases' => array('payment_id'),
),
);
}
/**
* Adjust Metadata for Get action.
*
* The metadata is used for setting defaults, documentation & validation.
*
* @param array $params
* Array of parameters determined by getfields.
*/
function _civicrm_api3_payment_get_spec(&$params) {
$params = array(
'contribution_id' => array(
'title' => 'Contribution ID',
'type' => CRM_Utils_Type::T_INT,
),
'entity_table' => array(
'title' => 'Entity Table',
'api.default' => 'civicrm_contribution',
),
'entity_id' => array(
'title' => 'Entity ID',
'type' => CRM_Utils_Type::T_INT,
'api.aliases' => array('contribution_id'),
),
);
}
/**
* Adjust Metadata for Delete action.
*
* The metadata is used for setting defaults, documentation & validation.
*
* @param array $params
* Array of parameters.
*/
function _civicrm_api3_payment_delete_spec(&$params) {
$params = array(
'id' => array(
'api.required' => 1 ,
'title' => 'Payment ID',
'type' => CRM_Utils_Type::T_INT,
'api.aliases' => array('payment_id'),
),
);
}
/**
* Adjust Metadata for Cancel action.
*
* The metadata is used for setting defaults, documentation & validation.
*
* @param array $params
* Array of parameters.
*/
function _civicrm_api3_payment_cancel_spec(&$params) {
$params = array(
'id' => array(
'api.required' => 1 ,
'title' => 'Payment ID',
'type' => CRM_Utils_Type::T_INT,
'api.aliases' => array('payment_id'),
),
);
}

View file

@ -0,0 +1,112 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
* This api exposes CiviCRM PaymentProcessor.
*
* @package CiviCRM_APIv3
*/
/**
* Add/Update a PaymentProcessor.
*
* @param array $params
*
* @return array
* API result array
*/
function civicrm_api3_payment_processor_create($params) {
if (empty($params['id']) && empty($params['payment_instrument_id'])) {
$params['payment_instrument_id'] = civicrm_api3('PaymentProcessorType', 'getvalue', array(
'id' => $params['payment_processor_type_id'],
'return' => 'payment_instrument_id',
));
}
return _civicrm_api3_basic_create(_civicrm_api3_get_BAO(__FUNCTION__), $params);
}
/**
* Adjust Metadata for Create action.
*
* The metadata is used for setting defaults, documentation & validation.
*
* @param array $params
* Array of parameters determined by getfields.
*/
function _civicrm_api3_payment_processor_create_spec(&$params) {
$params['payment_processor_type_id']['api.required'] = 1;
$params['is_default']['api.default'] = 0;
$params['is_test']['api.default'] = 0;
}
/**
* Deletes an existing PaymentProcessor.
*
* @param array $params
*
* @return array
* API result array
*/
function civicrm_api3_payment_processor_delete($params) {
return _civicrm_api3_basic_delete(_civicrm_api3_get_BAO(__FUNCTION__), $params);
}
/**
* Retrieve one or more PaymentProcessor.
*
* @param array $params
* Array of name/value pairs.
*
* @return array
* API result array
*/
function civicrm_api3_payment_processor_get($params) {
return _civicrm_api3_basic_get(_civicrm_api3_get_BAO(__FUNCTION__), $params);
}
/**
* Set default getlist parameters.
*
* @see _civicrm_api3_generic_getlist_defaults
*
* @param array $request
*
* @return array
*/
function _civicrm_api3_payment_processor_getlist_defaults(&$request) {
return array(
'description_field' => array(
'payment_processor_type_id',
'description',
),
'params' => array(
'is_test' => 0,
'is_active' => 1,
),
);
}

View file

@ -0,0 +1,105 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
* This api exposes CiviCRM payment processor types.
*
* @package CiviCRM_APIv3
*/
/**
* Create payment_processor type.
*
* @param array $params
* Associative array of property name/value pairs to insert in new payment_processor type.
*
* @return array
*/
function civicrm_api3_payment_processor_type_create($params) {
if (isset($params['id']) && !CRM_Utils_Rule::integer($params['id'])) {
return civicrm_api3_create_error('Invalid value for payment_processor type ID');
}
$paymentProcessorType = CRM_Financial_BAO_PaymentProcessorType::create($params);
$relType = array();
_civicrm_api3_object_to_array($paymentProcessorType, $relType[$paymentProcessorType->id]);
return civicrm_api3_create_success($relType, $params, 'PaymentProcessorType', 'create', $paymentProcessorType);
}
/**
* Adjust Metadata for Create action.
*
* The metadata is used for setting defaults, documentation & validation.
*
* @param array $params
* Array of parameters determined by getfields.
*/
function _civicrm_api3_payment_processor_type_create_spec(&$params) {
$params['billing_mode']['api.required'] = 1;
$params['class_name']['api.required'] = 1;
$params['is_active']['api.default'] = 1;
$params['is_recur']['api.default'] = FALSE;
// FIXME bool support // $params['is_recur']['api.required'] = 1;
$params['name']['api.required'] = 1;
$params['title']['api.required'] = 1;
$params['payment_instrument_id']['api.default'] = 'Credit Card';
}
/**
* Get all payment_processor types.
*
* @param array $params
*
* @return array
*/
function civicrm_api3_payment_processor_type_get($params) {
return _civicrm_api3_basic_get(_civicrm_api3_get_BAO(__FUNCTION__), $params);
}
/**
* Delete a payment_processor type delete.
*
* @param array $params
*
* @return array
* API Result Array
*/
function civicrm_api3_payment_processor_type_delete($params) {
if ($params['id'] != NULL && !CRM_Utils_Rule::integer($params['id'])) {
return civicrm_api3_create_error('Invalid value for payment processor type ID');
}
$payProcTypeBAO = new CRM_Financial_BAO_PaymentProcessorType();
$result = $payProcTypeBAO->del($params['id']);
if (!$result) {
return civicrm_api3_create_error('Could not delete payment processor type');
}
return civicrm_api3_create_success($result, $params, 'PaymentProcessorType', 'delete', $payProcTypeBAO);
}

View file

@ -0,0 +1,93 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
* This api exposes CiviCRM Payment Token records.
*
* @note Contribute component must be enabled.
*
* @package CiviCRM_APIv3
*/
/**
* Create/update Payment Token.
*
* This API is used to create new campaign or update any of the existing
* In case of updating existing campaign, id of that particular campaign must
* be in $params array.
*
* @param array $params
*
* @return array
*/
function civicrm_api3_payment_token_create($params) {
return _civicrm_api3_basic_create(_civicrm_api3_get_BAO(__FUNCTION__), $params, 'PaymentToken');
}
/**
* Adjust Metadata for Create action.
*
* The metadata is used for setting defaults, documentation & validation.
*
* @param array $params
* Array of parameters determined by getfields.
*/
function _civicrm_api3_payment_token_create_spec(&$params) {
$params['token']['api.required'] = 1;
$params['contact_id']['api.required'] = 1;
$params['payment_processor_id']['api.required'] = 1;
$params['created_id']['api.default'] = 'user_contact_id';
$params['created_date']['api.default'] = 'now';
}
/**
* Returns array of campaigns matching a set of one or more properties.
*
* @param array $params
* Array per getfields
*
* @return array
* Array of matching campaigns
*/
function civicrm_api3_payment_token_get($params) {
return _civicrm_api3_basic_get(_civicrm_api3_get_BAO(__FUNCTION__), $params, TRUE, 'PaymentToken');
}
/**
* Delete an existing payment token.
*
* This method is used to delete any existing payment token.
* Id of the payment token to be deleted is required field in $params array
*
* @param array $params
* array containing id of the group to be deleted
*
* @return array
*/
function civicrm_api3_payment_token_delete($params) {
return _civicrm_api3_basic_delete(_civicrm_api3_get_BAO(__FUNCTION__), $params);
}

View file

@ -0,0 +1,86 @@
<?php
/*
* +--------------------------------------------------------------------+
* | CiviCRM version 4.7 |
* +--------------------------------------------------------------------+
* | Copyright CiviCRM LLC (c) 2004-2017 |
* +--------------------------------------------------------------------+
* | This file is a part of CiviCRM. |
* | |
* | CiviCRM is free software; you can copy, modify, and distribute it |
* | under the terms of the GNU Affero General Public License |
* | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
* | |
* | CiviCRM is distributed in the hope that it will be useful, but |
* | WITHOUT ANY WARRANTY; without even the implied warranty of |
* | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
* | See the GNU Affero General Public License for more details. |
* | |
* | You should have received a copy of the GNU Affero General Public |
* | License and the CiviCRM Licensing Exception along |
* | with this program; if not, contact CiviCRM LLC |
* | at info[AT]civicrm[DOT]org. If you have questions about the |
* | GNU Affero General Public License or the licensing of CiviCRM, |
* | see the CiviCRM license FAQ at http://civicrm.org/licensing |
* +--------------------------------------------------------------------+
*/
/**
* This api exposes CiviCRM PCP records.
*
*
* @package CiviCRM_APIv3
*/
/**
* Create or update a survey.
*
* @param array $params
* Array per getfields metadata.
*
* @return array api result array
*/
function civicrm_api3_pcp_create($params) {
return _civicrm_api3_basic_create(_civicrm_api3_get_BAO(__FUNCTION__), $params, 'Pcp');
}
/**
* Adjust Metadata for Create action.
*
* The metadata is used for setting defaults, documentation & validation.
*
* @param array $params
* Array of parameters determined by getfields.
*/
function _civicrm_api3_pcp_create_spec(&$params) {
$params['title']['api.required'] = 1;
$params['contact_id']['api.required'] = 1;
$params['page_id']['api.required'] = 1;
$params['pcp_block_id']['api.required'] = 1;
}
/**
* Returns array of pcps matching a set of one or more properties.
*
* @param array $params
* Array per getfields
*
* @return array Array of matching pcps
*/
function civicrm_api3_pcp_get($params) {
return _civicrm_api3_basic_get(_civicrm_api3_get_BAO(__FUNCTION__), $params, TRUE, 'Pcp');
}
/**
* Delete an existing PCP.
*
* This method is used to delete any existing PCP given its id.
*
* @param array $params
* [id]
*
* @return array api result array
*/
function civicrm_api3_pcp_delete($params) {
return _civicrm_api3_basic_delete(_civicrm_api3_get_BAO(__FUNCTION__), $params);
}

View file

@ -0,0 +1,78 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
* This api exposes CiviCRM phone records.
*
* @package CiviCRM_APIv3
*/
/**
* Add an Phone for a contact.
*
* @param array $params
* Array per getfields metadata.
*
* @return array
*/
function civicrm_api3_phone_create($params) {
return _civicrm_api3_basic_create(_civicrm_api3_get_BAO(__FUNCTION__), $params, 'Phone');
}
/**
* Adjust Metadata for Create action.
*
* The metadata is used for setting defaults, documentation & validation.
*
* @param array $params
* Array of parameters determined by getfields.
*/
function _civicrm_api3_phone_create_spec(&$params) {
$params['contact_id']['api.required'] = 1;
$params['phone']['api.required'] = 1;
// hopefully change to use handleprimary
$params['is_primary']['api.default'] = 0;
}
/**
* Delete an existing Phone.
*
* @param array $params
* Array per getfields metadata.
*
* @return array
* Api Result
*/
function civicrm_api3_phone_delete($params) {
return _civicrm_api3_basic_delete(_civicrm_api3_get_BAO(__FUNCTION__), $params);
}
/**
* civicrm_api('Phone','Get') to retrieve one or more phones is implemented by
* function civicrm_api3_phone_get ($params) into the file Phone/Get.php
* Could have been implemented here in this file too, but we moved it to illustrate the feature with a real usage.
*/

View file

@ -0,0 +1,49 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
* @package CiviCRM_APIv3
*/
/**
* Retrieve one or more phones.
*
* This function has been declared there instead than in api/v3/Phone.php
* for no specific reasons, beside to demonstrate this feature
* (that might be useful in your module, eg if you want to implement a
* civicrm_api ('Phone','Dial') that you would then simply put in
* your module under api/v3/Phone/Dial.php.
*
* @param array $params
* Array per getfields metadata.
*
* @return array
* API result array
*/
function civicrm_api3_phone_get($params) {
return _civicrm_api3_basic_get(_civicrm_api3_get_BAO(__FUNCTION__), $params);
}

Some files were not shown because too many files have changed in this diff Show more