Beispiel #1
0
/**
 * 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);
}
/**
 * Make eway payment.
 *
 * @param array $params
 *
 * @throws API_Exception
 * @throws CiviCRM_API3_Exception
 *
 * @return array
 *   API Result array
 */
function civicrm_api3_ewayrecurring_payment($params)
{
    // If the site is in developer mode we return a mock success.
    if (civicrm_api3('setting', 'getvalue', array('group' => 'eway', 'name' => 'eway_developer_mode'))) {
        return civicrm_api3_create_success(array($params['managed_customer_id'] => array('trxn_id' => uniqid())), $params);
    }
    $client = CRM_Core_Payment_EwayUtils::getClient($params['payment_processor_id']);
    $endPoint = 'https://www.eway.com.au/gateway/managedpayment/ProcessPayment';
    $paymentInfo = array('man:managedCustomerID' => $params['managed_customer_id'], 'man:amount' => $params['amount_in_cents'], 'man:InvoiceReference' => $params['invoice_id'], 'man:InvoiceDescription' => $params['description']);
    $result = $client->call('man:ProcessPayment', $paymentInfo, '', $endPoint);
    if (empty($result)) {
        throw new API_Exception('No response from eWay.');
    }
    if (!empty($result['faultcode'])) {
        throw new API_Exception($result['faultstring']);
    }
    if ($result['ewayTrxnStatus'] == 'True') {
        return civicrm_api3_create_success(array($params['managed_customer_id'] => array('trxn_id' => $result['ewayTrxnNumber'])), $params);
    } else {
        if (!empty($result['ewayTrxnError'])) {
            throw new API_Exception($result['ewayTrxnError']);
        }
        throw new API_Exception('unknown EWAY processing error');
    }
}
Beispiel #3
0
/**
 * Postnummer.Create API
 *
 * @param array $params
 * @return array API result descriptor
 * @see civicrm_api3_create_success
 * @see civicrm_api3_create_error
 * @throws API_Exception
 */
function civicrm_api3_postnummer_create($params)
{
    if (!$params['post_code']) {
        throw new API_Exception('Mandatory parameter missing for Postnummer Create: post_code');
    }
    try {
        $queryParams = array();
        $queryFields = array();
        $queryParams[1] = array($params['post_code'], 'String');
        if ($params['post_city']) {
            $queryFields[] = 'post_city = %2';
            $queryParams[2] = array($params['post_city'], 'String');
        }
        if ($params['community_number']) {
            $queryFields[] = 'community_number = %3';
            $queryParams[3] = array($params['community_number'], 'String');
        }
        if ($params['community_name']) {
            $queryFields[] = 'community_name = %4';
            $queryParams[4] = array($params['community_name'], 'String');
        }
        if ($params['category']) {
            $queryFields[] = 'category = %5';
            $queryParams[5] = array($params['category'], 'String');
        }
        $query = 'INSERT INTO civicrm_post_nummer SET post_code = %1, ' . implode(", ", $queryFields);
        CRM_Core_DAO::executeQuery($query, $queryParams);
    } catch (Exception $ex) {
        throw new API_Exception('Could not create postnummer with values: ' . implode(";", $params) . '. Error message : ' . $ex->getMessage());
    }
    return civicrm_api3_create_success(array(), $params, 'PostCode', 'Get');
}
/**
 * WaitingList.InviteMembers API
 *
 * @param array $params
 * @return array API result descriptor
 * @see civicrm_api3_create_success
 * @see civicrm_api3_create_error
 * @throws API_Exception
 */
function civicrm_api3_waiting_list_InviteMembers($params)
{
    $waiting_list_group = 9;
    $maximum_membership_count = 600;
    $invited_members = 0;
    $date = date('Y-m-d H:i:s');
    $mailing_name = 'Waiting List Invitation ' . $date;
    $msg_template_id = 74;
    $sms_template_id = 79;
    $sms_provider_id = 1;
    require_once 'api/class.api.php';
    $api = new civicrm_api3();
    $params = array();
    $params['version'] = 3;
    $params['sequential'] = 1;
    $params['is_reserved'] = 1;
    $params['group_type'] = 2;
    $params['parents'] = $waiting_list_group;
    $params['title'] = $mailing_name;
    if (!$api->Group->Create($params)) {
        throw new API_Exception("Error creating invitation group " . print_r($api->errorMsg(), true));
    }
    $mailing_group_id = $api->lastResult->id;
    unset($params);
    $params['version'] = 3;
    $params['sequential'] = 1;
    $params['status_id'] = array('IN' => array(1, 2, 8));
    $params['membership_type_id'] = array('IN' => array(1, 3, 8, 9, 10, 11));
    $params['owner_membership_id'] = array('IS NULL' => 1);
    if ($api->Membership->Getcount($params)) {
        $current_membership_count = $api->lastResult;
    } else {
        throw new API_Exception("Error retrieving current membership count " . print_r($api->errorMsg(), true));
    }
    unset($params);
    $params['version'] = 3;
    $params['sequential'] = 1;
    $params['group_id'] = $waiting_list_group;
    $params['options'] = array('sort' => 'id', 'limit' => 0);
    if ($api->GroupContact->Get($params)) {
        $waiting_list = $api->lastResult->values;
        $count = $api->lastResult->count;
        if ($current_membership_count < $maximum_membership_count) {
            for ($i = 0; $i < $count; $i++) {
                if ($current_membership_count >= $maximum_membership_count) {
                    break;
                }
                waiting_list_move_contact($mailing_group_id, $waiting_list[$i]->id, $waiting_list[$i]->contact_id, $waiting_list_group);
                $current_membership_count++;
                $invited_members++;
            }
            waiting_list_create_mailing($mailing_group_id, $mailing_name, $msg_template_id, $date);
            waiting_list_create_sms($mailing_group_id, $mailing_name, $sms_template_id, $sms_provider_id, $date);
        }
    } else {
        throw new API_Exception("Error retrieving Waiting List " . print_r($api->errorMsg(), true));
    }
    $returnValues = array('invited_members' => $invited_members);
    return civicrm_api3_create_success($returnValues, $params, 'WaitingList', 'InviteMembers');
}
/**
 * Get CiviCRM Word Replacement details
 * {@getfields word_replacement_create}
 * 
 */
function civicrm_api3_word_replacement_get($params)
{
    $bao = new CRM_Core_BAO_WordReplacement();
    _civicrm_api3_dao_set_filter($bao, $params, true, 'WordReplacement');
    $wordReplacements = _civicrm_api3_dao_to_array($bao, $params, true, 'WordReplacement');
    return civicrm_api3_create_success($wordReplacements, $params, 'word_replacement', 'get', $bao);
}
Beispiel #6
0
/**
 * 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);
    return civicrm_api3_create_success($differ->getAllChangesForConnection($schema->getLogTablesForContact()));
}
/**
 * @param $apiRequest
 *
 * @return array
 * @throws API_Exception
 */
function civicrm_api3_generic_getActions($apiRequest)
{
    civicrm_api3_verify_mandatory($apiRequest, NULL, array('entity'));
    $mfp = \Civi\Core\Container::singleton()->get('magic_function_provider');
    $actions = $mfp->getActionNames($apiRequest['version'], $apiRequest['entity']);
    return civicrm_api3_create_success($actions);
}
/**
 * Creates a new household according to the specs
 */
function civicrm_api3_contact_create_household($params)
{
    if (empty($params['mode'])) {
        $params['mode'] = CRM_Householdmerge_Logic_Configuration::getHouseholdMode();
    }
    $head_id = NULL;
    switch ($params['mode']) {
        case 'hierarchy':
            $head_id = (int) $params['head_id'];
        case 'link':
            // get member IDs
            $member_ids = $params['member_ids'];
            if (is_string($member_ids)) {
                $member_ids = explode(',', $member_ids);
            }
            // sanitise member IDs
            $sanitised_member_ids = array();
            foreach ($member_ids as $member_id) {
                $sanitised_member_id = (int) $member_id;
                if ($sanitised_member_id) {
                    $sanitised_member_ids[] = $sanitised_member_id;
                }
            }
            // now pass the work on the the worker
            $worker = new CRM_Householdmerge_Logic_Worker();
            $household_id = $worker->createLinkedHousehold($params['household_name'], $sanitised_member_ids, $params['address'], $head_id);
            return civicrm_api3_create_success();
        default:
            return civicrm_api3_create_error("Contact.create_household cannot process mode '{$params['mode']}'.");
    }
}
/**
 * Metrics.collate API
 *
 * @param array $params
 * @return array API result descriptor
 * @see civicrm_api3_create_success
 * @see civicrm_api3_create_error
 * @throws API_Exception
 */
function civicrm_api3_metrics_collate($params)
{
    $data = array();
    CRM_Metricclient_Hook::collateMetrics($data);
    if (!empty($data)) {
        $header = array();
        $header['site_url'] = $_SERVER['SERVER_NAME'];
        $metricSettings = CRM_Core_BAO_Setting::getItem("metrics");
        $header['site_name'] = $metricSettings['metrics_site_name'];
        $header['data'] = $data;
        $curl = curl_init($metricSettings['metrics_reporting_url']);
        curl_setopt($curl, CURLOPT_POST, true);
        if (array_key_exists("metrics_ignore_verify_peer", $metricSettings) && $metricSettings['metrics_ignore_verify_peer'] == 1) {
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        }
        if (array_key_exists("metrics_ignore_verify_host", $metricSettings) && $metricSettings['metrics_ignore_verify_host'] == 1) {
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
        } else {
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2);
        }
        if (array_key_exists("metrics_ca_path", $metricSettings) && $metricSettings['metrics_ca_path']) {
            curl_setopt($curl, CURLOPT_CAPATH, $metricSettings['metrics_ca_path']);
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_POSTFIELDS, array("json" => json_encode($header)));
        $response = curl_exec($curl);
        $error = curl_error($curl);
        if ($error) {
            throw new API_Exception($error, 1);
        }
        return civicrm_api3_create_success(count($data), $params, 'Metrics', 'collate');
    }
    return civicrm_api3_create_success(0, $params, 'Metrics', 'collate');
}
Beispiel #10
0
/**
 * 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
 * {@getfields GroupNesting_create
 * @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);
}
/**
 * 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
 */
function civicrm_api3_participant_status_type_delete($params)
{
    if (CRM_Event_BAO_ParticipantStatusType::deleteParticipantStatusType($params['id'])) {
        return civicrm_api3_create_success(TRUE);
    }
    return civicrm_api3_create_error(TRUE);
}
Beispiel #12
0
/**
+--------------------------------------------------------------------+
| CiviCRM version 4.6                                                |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2015                                |
+--------------------------------------------------------------------+
| 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        |
+--------------------------------------------------------------------+
*/
function civicrm_api3_prevem_login($params)
{
    $prevemUrl = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::MAILING_PREFERENCES_NAME, 'prevem_url');
    $prevemURL = !empty($prevemUrl) ? CRM_Utils_URL::mask($prevemUrl, array('user', 'pass')) : NULL;
    if (!$prevemURL) {
        return civicrm_api3_create_error("prevemURL is not configured. Go to Administer>CiviMail>CiviMail Component Settings to configure prevemURL");
    }
    $prevemConsumer = parse_url($prevemUrl, PHP_URL_USER);
    $prevemSecret = parse_url($prevemUrl, PHP_URL_PASS);
    /** TODO Parse $prevemUrl. Send login request to get token. **/
    /** To send login request, see eg http://stackoverflow.com/questions/2445276/how-to-post-data-in-php-using-file-get-contents **/
    $postdata = http_build_query(array('email' => $prevemConsumer . "@foo.com", 'password' => $prevemSecret));
    $opts = array('http' => array('method' => 'POST', 'header' => 'Content-type: application/x-www-form-urlencoded', 'content' => $postdata));
    $context = stream_context_create($opts);
    $result = file_get_contents($prevemURL . '/api/Users/login', FALSE, $context);
    if ($result === FALSE) {
        return civicrm_api3_create_error("Failed to login. Check if Preview Manager is running on " . $prevemURL);
    } else {
        $accessToken = json_decode($result)->{'id'};
        if (!$accessToken) {
            return civicrm_api3_create_error("Failed to parse access token. Check if Preview Manager is running on " . $prevemURL);
        }
        $returnValues = array('url' => $prevemURL, 'consumerId' => $prevemConsumer, 'token' => $accessToken, 'password' => $prevemSecret);
        return civicrm_api3_create_success($returnValues, $params, 'Prevem', 'login');
    }
}
/**
 * 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
 */
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']);
}
/**
 * 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');
}
/**
 * Get CiviCRM domain details
 * {@getfields domain_create}
 * @example DomainGet.php
 */
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 (CRM_Utils_Array::value('current_domain', $params)) {
        $domainBAO = CRM_Core_Config::domainID();
        $params['id'] = $domainBAO;
    }
    _civicrm_api3_dao_set_filter($bao, $params, true, 'domain');
    $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', '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);
            $domains[$domain['id']] = array_merge($domains[$domain['id']], $domain);
        }
    }
    return civicrm_api3_create_success($domains, $params, 'domain', 'get', $bao);
}
function civicrm_api3_mailchimp_synchronize($params)
{
    $return = $tags = $createdContact = array();
    $apiKey = CRM_Core_BAO_Setting::getItem('MailChimp Preferences', 'api_key', NULL, FALSE);
    $tagsCount = civicrm_api3('Tag', 'getcount', array('sequential' => 1));
    $tagsGet = civicrm_api3('Tag', 'get', array('sequential' => 1, 'rowCount' => $tagsCount));
    foreach ($tagsGet['values'] as $tagIds => $tagsValues) {
        $tags[$tagsValues['id']] = $tagsValues['name'];
    }
    $mcClient = new Mailchimp($apiKey);
    $mcLists = new Mailchimp_Lists($mcClient);
    $lists = $mcLists->getList();
    foreach ($lists['data'] as $listsDetails) {
        if (!in_array($listsDetails['name'], $tags)) {
            $tagsCreate = civicrm_api3('Tag', 'create', array('sequential' => 1, 'name' => $listsDetails['name']));
        }
        $tagsCount = civicrm_api3('Tag', 'getcount', array('sequential' => 1));
        $tagsGet = civicrm_api3('Tag', 'get', array('sequential' => 1, 'rowCount' => $tagsCount));
        foreach ($tagsGet['values'] as $tagIds => $tagsValues) {
            $tags[$tagsValues['id']] = $tagsValues['name'];
        }
        if (in_array($listsDetails['name'], $tags)) {
            $keyTags = array_search($listsDetails['name'], $tags);
            $members = $mcLists->members($listsDetails['id']);
            foreach ($members['data'] as $key => $value) {
                try {
                    $createdContact = civicrm_api3('Contact', 'create', array('sequential' => 1, 'contact_type' => "Individual", 'first_name' => $value['merges']['FNAME'], 'last_name' => $value['merges']['LNAME'], 'email' => $value['merges']['EMAIL'], 'api.EntityTag.create' => array('entity_id' => "\$value.id", 'entity_table' => "civicrm_contact", 'tag_id' => $keyTags), 'dupe_check' => true));
                } catch (CiviCRM_API3_Exception $e) {
                    $result = civicrm_api3('EntityTag', 'create', array('contact_id' => $e->getExtraParams()['ids'][0], 'tag_id' => $keyTags));
                }
            }
        }
    }
    return civicrm_api3_create_success();
}
/**
 * Create a new domain - with a domain group.
 *
 * This is not fully developed & need to work on creating admin menus etc
 *
 * @param array $params
 *
 * @return array
 * @example DomainCreate.php
 * {@getfields domain_create}
 */
function civicrm_api3_multisite_domain_create($params)
{
    $transaction = new CRM_Core_Transaction();
    if (empty($params['contact_id'])) {
        $params['contact_id'] = _civicrm_api3_multisite_domain_create_if_not_exists('Contact', array('organization_name' => $params['name'], 'contact_type' => 'organization'));
    }
    $domain = civicrm_api('domain', 'getsingle', array('version' => 3, 'current_domain' => TRUE));
    $fullParams = array_merge($domain, $params);
    $fullParams['domain_version'] = $domain['version'];
    $fullParams['version'] = 3;
    unset($fullParams['id']);
    if (empty($params['group_id'])) {
        $groupParams = array('title' => !empty($params['group_name']) ? $params['group_name'] : $params['name']);
        $group = civicrm_api3('Group', 'get', array_merge($groupParams, array('options' => array('limit' => 1))));
        if (empty($group['id'])) {
            // Ideally would fix the api to be more consistent & not assume default but...
            $groupParams['group_type'] = array(1 => 1);
            $group = civicrm_api3('Group', 'create', $groupParams);
        }
        $domainGroupID = $group['id'];
    } else {
        $domainGroupID = $params['group_id'];
    }
    _civicrm_api3_multisite_domain_create_if_not_exists('GroupOrganization', array('group_id' => $domainGroupID, 'organization_id' => $params['contact_id']));
    $domainID = _civicrm_api3_multisite_domain_create_if_not_exists('domain', $fullParams);
    if (!$domainID || $domainID != civicrm_api3('Domain', 'getvalue', array('name' => $params['name'], 'return' => 'id'))) {
        throw new CiviCRM_API3_Exception('Failed to create domain', 'unknown');
    }
    $transaction->commit();
    if (!civicrm_api3('Navigation', 'getcount', array('domain_id' => $domainID))) {
        _civicrm_load_navigation($params['name'], $domainID);
    }
    civicrm_api3('Setting', 'create', array('is_enabled' => TRUE, 'domain_group_id' => $domainGroupID, 'domain_id' => $domainID));
    return civicrm_api3_create_success(array($domainID => array('id' => $domainID)));
}
Beispiel #18
0
/**
 * ContributionRecur.SetCycleDays API
 * Migratie Amnesty International Vlaanderen
 * Get cycle days from Espadon import file.
 * If cycle_day is less then 15, set to 7 in recurring
 * Else set to 21 in recurring
 *
 * @author Erik Hommel (CiviCooP) <*****@*****.**>
 * @param array $params
 * @return array API result descriptor
 * @see civicrm_api3_create_success
 * @see civicrm_api3_create_error
 * @throws API_Exception
 */
function civicrm_api3_contribution_recur_setcycledays($params)
{
    $countSeven = 0;
    $countTwentyOne = 0;
    $logger = new CRM_MigrateLogger("cycle_days_log");
    /*
     * get cycle days and then retrieve recurring contribution with all relevant data via pledge
     */
    $cycleQuery = "SELECT * FROM aivl_cycle_days WHERE processed IS NULL LIMIT 1000";
    $daoCycle = CRM_Core_DAO::executeQuery($cycleQuery);
    while ($daoCycle->fetch()) {
        _setProcessed($daoCycle->mandaat_code);
        _addCiviCampaignId($daoCycle);
        if (_validCheck($daoCycle, $logger)) {
            $cycleDay = _calcCycleDay($daoCycle->cycle_day);
            if ($cycleDay == 7) {
                $countSeven++;
            } else {
                $countTwentyOne++;
            }
            $recurParams = array(1 => array("civicrm_contribution_recur", "String"), 2 => array($cycleDay, "Integer"), 3 => array((string) $daoCycle->mandaat_code, "String"));
            $recurQuery = "UPDATE civicrm_contribution_recur recur\nJOIN civicrm_sdd_mandate sdd ON recur.id = sdd.entity_id AND sdd.entity_table = %1\nJOIN civicrm_value_sepa_direct_debit_2 custom ON sdd.reference = custom.mandate_3\nSET recur.cycle_day = %2\nWHERE sdd.reference = %3";
            try {
                CRM_Core_DAO::executeQuery($recurQuery, $recurParams);
                $logger->logMessage("INFO", "Set cycle days to " . $cycleDay . " for recurring contribution with mandate " . $daoCycle->mandaat_code);
            } catch (CiviCRM_API3_Exception $ex) {
                $logger->logMessage("WARNING", "Could not update recurring contribution for mandate " . $daoCycle->mandaat_code);
            }
        }
    }
    $returnValues = "Cycle days aangepast, " . $countSeven . " op 7 gezet en " . $countTwentyOne . " op 21";
    return civicrm_api3_create_success($returnValues, $params, 'ContributionRecur', 'SetCycleDays');
}
/**
 * params must contain at least id=xx & {one of the fields from getfields}=value
 */
function civicrm_api3_generic_setValue($apiRequest)
{
    $entity = $apiRequest['entity'];
    $params = $apiRequest['params'];
    // we can't use _spec, doesn't work with generic
    civicrm_api3_verify_mandatory($params, NULL, array('id', 'field', 'value'));
    $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, "sequential"));
    // getfields error, shouldn't happen.
    if ($fields['is_error']) {
        return $fields;
    }
    $fields = $fields['values'];
    if (!array_key_exists($field, $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[$field];
    if (array_key_exists('required', $def) && empty($value)) {
        return civicrm_api3_create_error(ts("This can't be empty, please provide a value"), array("error_code" => "required", "field" => $field));
    }
    switch ($def['type']) {
        case 1:
            //int
            if (!is_numeric($value)) {
                return civicrm_api3_create_error("Param '{$field}' must be a number", array('error_code' => 'NaN'));
            }
        case 2:
            //string
            require_once "CRM/Utils/Rule.php";
            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 16:
            //boolean
            $value = (bool) $value;
            break;
        case 4:
            //date
        //date
        default:
            return civicrm_api3_create_error("Param '{$field}' is of a type not managed yet. Join the API team and help us implement it", array('error_code' => 'NOT_IMPLEMENTED'));
    }
    if (CRM_Core_DAO::setFieldValue(_civicrm_api3_get_DAO($entity), $id, $field, $value)) {
        $entity = array('id' => $id, $field => $value);
        CRM_Utils_Hook::post('edit', $entity, $id, $entity);
        return civicrm_api3_create_success($entity);
    } else {
        return civicrm_api3_create_error("error assigning {$field}={$value} for {$entity} (id={$id})");
    }
}
/**
 * Use this API to create a new group. See the CRM Data Model for uf_group property definitions
 *
 * @param $params  array   Associative array of property name/value pairs to insert in group.
 *
 * @return   Newly create $ufGroupArray array
 * {@getfields UFGroup_create}
 * @example UFGroupCreate.php
 * @access public
 */
function civicrm_api3_uf_group_create($params)
{
    $ids = array();
    $ids['ufgroup'] = $params['id'];
    $ufGroup = CRM_Core_BAO_UFGroup::add($params, $ids);
    _civicrm_api3_object_to_array($ufGroup, $ufGroupArray[$ufGroup->id]);
    return civicrm_api3_create_success($ufGroupArray, $params);
}
 /**
  * Create an API provider for entity "Widget" with action "frobnicate".
  *
  * @return Provider\ProviderInterface
  */
 public function createWidgetFrobnicateProvider()
 {
     $provider = new \Civi\API\Provider\AdhocProvider(self::MOCK_VERSION, 'Widget');
     $provider->addAction('frobnicate', 'access CiviCRM', function ($apiRequest) {
         return civicrm_api3_create_success(array(98 => 'frob'));
     });
     return $provider;
 }
/**
 * Process incoming payment notification (we have called it 'create' so that it will be forced to be transactional
 *
 * @param $params
 *
 * @return array
 */
function civicrm_api3_payment_notification_create($params)
{
    if (!empty($params['system_log_id'])) {
        // lets replace params with this rather than allow altering
        $params = json_decode(civicrm_api3('system_log', 'getvalue', array('id' => $params['system_log_id'], 'return' => 'context')), TRUE);
    }
    return civicrm_api3_create_success(CRM_Core_Payment_OmnipayMultiProcessor::processPaymentResponse($params));
}
/**
 * Slot.Delete API
 *
 * @param array $params
 * @return array API result descriptor
 * @see civicrm_api3_create_success
 * @see civicrm_api3_create_error
 * @throws API_Exception
 */
function civicrm_api3_adhoc_charges_delete($params)
{
    if (CRM_Booking_BAO_AdhocCharges::del($params['id'])) {
        return civicrm_api3_create_success($params, $params, 'AdhocCharges', 'delete');
    } else {
        return civicrm_api3_create_error('Could not delete adhoc charges.');
    }
}
/**
 * Segment.Delete API
 *
 * @param array $params
 * @return array API result descriptor
 * @see civicrm_api3_create_success
 * @see civicrm_api3_create_error
 * @throws API_Exception
 */
function civicrm_api3_segment_delete($params)
{
    if (array_key_exists('id', $params)) {
        return civicrm_api3_create_success(CRM_Contactsegment_BAO_Segment::deleteById($params['id']), $params, 'Segment', 'Delete');
    } else {
        throw new API_Exception('Id is a mandatory param when deleting a segment', 'mandatory_id_missing', 010);
    }
}
Beispiel #25
0
/**
 * Delete a specified Dashlet.
 *
 * @param array $params
 *   Array holding 'id' of dashlet to be deleted.
 *
 * @return array
 */
function civicrm_api3_dashboard_delete($params)
{
    if (CRM_Core_BAO_Dashboard::deleteDashlet($params['id'])) {
        return civicrm_api3_create_success(1, $params, 'Dashboard', 'delete');
    } else {
        return civicrm_api3_create_error('Could not delete dashlet');
    }
}
Beispiel #26
0
/**
 * 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');
}
Beispiel #27
0
/**
 * Booking.Delete API
 *
 * @param array $params
 * @return array API result descriptor
 * @see civicrm_api3_create_success
 * @see civicrm_api3_create_error
 * @throws API_Exception
 */
function civicrm_api3_Booking_delete($params)
{
    if (CRM_Booking_BAO_Booking::del($params['id'])) {
        return civicrm_api3_create_success($params, $params, 'booking', 'delete');
    } else {
        return civicrm_api3_create_error('Could not delete booking.');
    }
}
Beispiel #28
0
/**
 * Slot.Delete API
 *
 * @param array $params
 * @return array API result descriptor
 * @see civicrm_api3_create_success
 * @see civicrm_api3_create_error
 * @throws API_Exception
 */
function civicrm_api3_sub_slot_delete($params)
{
    if (CRM_Booking_BAO_SubSlot::del($params['id'])) {
        return civicrm_api3_create_success($params, $params, 'SubSlot', 'delete');
    } else {
        return civicrm_api3_create_error('Could not delete SubSlot.');
    }
}
/**
 * MainActivity.AutomaticCaseStatus API
 *
 * @param array $params
 * @return array API result descriptor
 * @see civicrm_api3_create_success
 * @see civicrm_api3_create_error
 * @throws API_Exception
 */
function civicrm_api3_main_activity_automaticcasestatus($params)
{
    $returnValues = array();
    $auto_case_status = new CRM_Mainactivity_AutomaticCaseStatus();
    $auto_case_status->parseFromExecutionToDebriefing();
    $auto_case_status->parseFromPreperationToExecution();
    return civicrm_api3_create_success($returnValues, $params, 'MainActivity', 'AutomaticCaseStatus');
}
/**
 * Returns array of projects matching a set of one or more project properties
 *
 * @param array $params  Array of one or more valid
 *                       property_name=>value pairs. If $params is set
 *                       as null, all projects will be returned
 *
 * @return array  Array of matching projects
 * {@getfields volunteer_project_get}
 * @access public
 */
function civicrm_api3_volunteer_project_get($params)
{
    $result = CRM_Volunteer_BAO_Project::retrieve($params);
    foreach ($result as $k => $dao) {
        $result[$k] = $dao->toArray();
    }
    return civicrm_api3_create_success($result, $params, 'VolunteerProject', 'get');
}