/**
 * CiviCRM to Mailchimp Sync
 *
 * @param array $params
 * @return array API result descriptor
 * @see civicrm_api3_create_success
 * @see civicrm_api3_create_error
 * @throws API_Exception
 */
function civicrm_api3_mailchimp_sync($params)
{
    $groups = CRM_Mailchimp_Utils::getGroupsToSync(array(), null, $membership_only = TRUE);
    foreach ($groups as $group_id => $details) {
        $list = new Mailchimp_Lists(CRM_Mailchimp_Utils::mailchimp());
        $webhookoutput = $list->webhooks($details['list_id']);
        if ($webhookoutput[0]['sources']['api'] == 1) {
            return civicrm_api3_create_error('civicrm_api3_mailchimp_sync -  API is set in Webhook setting for listID ' . $details['list_id'] . ' Please uncheck API');
        }
    }
    $result = $pullResult = array();
    // Do pull first from mailchimp to CiviCRM
    $pullRunner = CRM_Mailchimp_Form_Pull::getRunner($skipEndUrl = TRUE);
    if ($pullRunner) {
        $pullResult = $pullRunner->runAll();
    }
    // Do push from CiviCRM to mailchimp
    $runner = CRM_Mailchimp_Form_Sync::getRunner($skipEndUrl = TRUE);
    if ($runner) {
        $result = $runner->runAll();
    }
    if ($pullResult['is_error'] == 0 && $result['is_error'] == 0) {
        return civicrm_api3_create_success();
    } else {
        return civicrm_api3_create_error();
    }
}
/**
 * CiviCRM to Mailchimp Sync
 *
 * @param array $params
 * @return array API result descriptor
 * @see civicrm_api3_create_success
 * @see civicrm_api3_create_error
 * @throws API_Exception
 */
function civicrm_api3_mailchimp_sync($params)
{
    $result = $pullResult = array();
    // Do pull first from mailchimp to CiviCRM
    $pullRunner = CRM_Mailchimp_Form_Pull::getRunner($skipEndUrl = TRUE);
    if ($pullRunner) {
        $pullResult = $pullRunner->runAll();
    }
    // Do push from CiviCRM to mailchimp
    $runner = CRM_Mailchimp_Form_Sync::getRunner($skipEndUrl = TRUE);
    if ($runner) {
        $result = $runner->runAll();
    }
    if ($pullResult['is_error'] == 0 && $result['is_error'] == 0) {
        return civicrm_api3_create_success();
    } else {
        return civicrm_api3_create_error();
    }
}
/**
 * Pull sync from Mailchimp to CiviCRM.
 *
 * This is a schedulable job.
 *
 * @param array $params
 * @return array API result descriptor
 * @see civicrm_api3_create_success
 * @see civicrm_api3_create_error
 * @throws API_Exception
 */
function civicrm_api3_mailchimp_pullsync($params)
{
    // Do push from CiviCRM to mailchimp
    $runner = CRM_Mailchimp_Form_Pull::getRunner($skipEndUrl = TRUE);
    if ($runner) {
        $result = $runner->runAll();
    }
    if ($result['is_error'] == 0) {
        return civicrm_api3_create_success();
    } else {
        if (isset($result['exception']) && $result['exception'] instanceof Exception) {
            return civicrm_api3_create_error($result['exception']->getMessage());
        }
        return civicrm_api3_create_error('Unknown error');
    }
}